Documentation
¶
Overview ¶
Package media holds Sweef's pure-Go media stack: container parsers, audio decoders, frame providers and (in subpackage webaudio) the Web Audio DSP graph. It has no dependency on the engine so it can be tested against ffprobe/ffmpeg directly.
Index ¶
- Constants
- Variables
- func AnimatedImageFrames(data []byte) (frames []image.Image, seconds []float64, loops bool, ok bool)
- func B64URL(s string) ([]byte, error)
- func CanPlayType(mime string) string
- func DecryptSample(p *Protection, e *SampleEnc, key, data []byte) ([]byte, error)
- func FFmpegPath() string
- func HasNativeVideo(codec string) bool
- func IntersectRanges(a, b [][2]float64) [][2]float64
- func IsTypeSupportedMSE(mime string) bool
- func NativeAudio(info *Info) bool
- func OpusHeadBytes(ch, inputRate, preSkip int) []byte
- func ParseMIME(s string) (typ string, codecs []string, hasCodecs bool, ok bool)
- func Playable(info *Info) (bool, string)
- func SetFFmpegEnabled(on bool)
- func SetUSACTargetLoudness(lkfs float64)
- func VP8Keyframe(b []byte) bool
- func WCAudioName(codec string) string
- func WCVideoName(codec string) string
- type AudioDecoder
- type BytesSource
- type FLACStreamInfo
- type Fragment
- type FrameSource
- type Info
- type KeyHolder
- type KeyStore
- type MP4Init
- type MP4Moov
- type MSEBuffer
- func (b *MSEBuffer) Abort()
- func (b *MSEBuffer) Append(data []byte, cur float64) (*MSEResult, error)
- func (b *MSEBuffer) Buffered() [][2]float64
- func (b *MSEBuffer) Bytes() int
- func (b *MSEBuffer) ChangeType(mime string)
- func (b *MSEBuffer) FirstStore(kind string) *TrackStore
- func (b *MSEBuffer) Gen() uint64
- func (b *MSEBuffer) Remove(start, end float64)
- func (b *MSEBuffer) SetAppendWindow(start, end float64)
- func (b *MSEBuffer) SetKeyStore(k *KeyStore)
- func (b *MSEBuffer) SetMode(sequence bool)
- func (b *MSEBuffer) SetQuota(n int)
- func (b *MSEBuffer) SetTimestampOffset(v float64)
- func (b *MSEBuffer) Store(id int) *TrackStore
- func (b *MSEBuffer) TimestampOffset() float64
- func (b *MSEBuffer) Tracks() []TrackConfig
- func (b *MSEBuffer) Truncate(d float64)
- type MSEInit
- type MSEInitData
- type MSEResult
- type PCM
- type Picture
- type Protection
- type Sample
- type SampleEnc
- type SampleRef
- type SeekPoint
- type Source
- type Subsample
- type Track
- type TrackConfig
- type TrackSet
- type TrackStore
- func (t *TrackStore) Append(ss []Sample)
- func (t *TrackStore) At(dts float64) (Sample, bool)
- func (t *TrackStore) Bytes() int
- func (t *TrackStore) Config() TrackConfig
- func (t *TrackStore) CountPTS(after, upTo float64) int
- func (t *TrackStore) Duration() float64
- func (t *TrackStore) End() float64
- func (t *TrackStore) EvictBefore(limit float64, need int) int
- func (t *TrackStore) FirstAfter(tm float64) (Sample, bool)
- func (t *TrackStore) Gen() uint64
- func (t *TrackStore) Index(dts float64) int
- func (t *TrackStore) Insert(run []Sample) int
- func (t *TrackStore) KeyAtOrBefore(dts float64) (Sample, bool)
- func (t *TrackStore) Len() int
- func (t *TrackStore) Next(dts float64) (s Sample, ok, gap bool)
- func (t *TrackStore) Prev(dts float64) (Sample, bool)
- func (t *TrackStore) Ranges() [][2]float64
- func (t *TrackStore) Remove(start, end float64) int
- func (t *TrackStore) RemoveAll()
- func (t *TrackStore) SetConfig(c TrackConfig)
- func (t *TrackStore) ShownAt(tm float64) (Sample, bool)
- func (t *TrackStore) Snapshot() []Sample
- type VideoChunk
- type VideoDecoder
- type VideoSamples
- type WAVFormat
- type WCAudioDecoder
- type WCOpusEncoder
- type WCPicture
- type WCVP8Encoder
- type WCVideoDecoder
- type WebMBlock
- type WebMInit
Constants ¶
const ( QuotaVideo = 150 << 20 QuotaAudio = 12 << 20 )
Default buffer limits, the same as Chromium's SourceBuffer limits.
Variables ¶
var ( // ErrQuotaExceeded: the buffer is full and nothing before the current // playback position can be evicted (QuotaExceededError in the API). ErrQuotaExceeded = errors.New("mse: buffer full") // ErrBadStream: the appended bytes are not a valid stream (decode error). ErrBadStream = errors.New("mse: malformed byte stream") )
Errors returned by MSEBuffer.Append.
var ErrNoKey = errors.New("media: the decryption key is not available")
ErrNoKey is returned by Sample.Bytes for an encrypted sample whose key has not been supplied yet.
var ErrTruncated = errors.New("media: truncated data")
ErrTruncated means the resource ended inside a structure.
var ErrUnknownFormat = errors.New("media: unrecognised container")
ErrUnknownFormat is returned when no parser recognises the data.
var ErrUnsupported = errors.New("media: unsupported codec")
ErrUnsupported means no decoder is available for the stream.
Functions ¶
func AnimatedImageFrames ¶
func AnimatedImageFrames(data []byte) (frames []image.Image, seconds []float64, loops bool, ok bool)
AnimatedImageFrames decodes an animated GIF or APNG into composited frames and their display durations in seconds; ok is false for still images and other formats.
func B64URL ¶
B64URL decodes the base64url strings of Clear Key licenses and key ID lists (padding is optional).
func CanPlayType ¶
CanPlayType implements HTMLMediaElement.canPlayType truthfully for what Sweef can decode or render. The answers match Chromium (checked in media_test.go against a recorded matrix) for the royalty-free formats; H.264/AAC answer only when ffmpeg is available.
func DecryptSample ¶
func DecryptSample(p *Protection, e *SampleEnc, key, data []byte) ([]byte, error)
DecryptSample returns the plaintext of an encrypted sample payload (data is not modified).
func FFmpegPath ¶
func FFmpegPath() string
FFmpegPath returns the ffmpeg binary or "" when unavailable (or disabled through SWEEF_NO_FFMPEG=1 / SetFFmpegEnabled(false)).
func HasNativeVideo ¶
HasNativeVideo reports whether codec (ffprobe style name) can be decoded without ffmpeg.
func IntersectRanges ¶
IntersectRanges returns the intersection of two sorted range lists.
func IsTypeSupportedMSE ¶
IsTypeSupportedMSE is MediaSource.isTypeSupported: only fragmented containers the segment parsers handle.
func NativeAudio ¶
NativeAudio reports whether the codec of a container is decoded by pure Go.
func OpusHeadBytes ¶
OpusHeadBytes builds the identification header (RFC 7845) WebCodecs uses as the Opus decoder description.
func ParseMIME ¶
ParseMIME splits "type/subtype; codecs=\"a, b\"" into its parts. ok is false for malformed types; quoted reports whether codecs was quoted.
func Playable ¶
Playable reports whether a probed resource can be played by an element. reason is empty when playable.
func SetFFmpegEnabled ¶
func SetFFmpegEnabled(on bool)
SetFFmpegEnabled toggles the use of ffmpeg process-wide (tests).
func SetUSACTargetLoudness ¶
func SetUSACTargetLoudness(lkfs float64)
SetUSACTargetLoudness sets the loudness (in LKFS, e.g. -16 or -24) that USAC / xHE-AAC streams carrying loudness metadata are normalised to. A value of 0 disables the normalisation (the default).
func VP8Keyframe ¶
VP8Keyframe is a convenience for tests: whether a raw VP8 frame is a key frame.
func WCAudioName ¶
WCAudioName maps a codec string to the decoder family ("" if unknown).
func WCVideoName ¶
WCVideoName maps a WebCodecs video codec string to the decoder name used here ("" when it is not a video codec this tree knows).
Types ¶
type AudioDecoder ¶
type AudioDecoder interface {
// Decode decodes one access unit to planar float32 PCM. The slices are
// valid until the next call. Zero frames are fine (start-up packets).
Decode(pkt []byte) ([][]float32, error)
// Reset drops decoder history (after a seek or a gap).
Reset()
// Rate is the output sample rate; Channels the output channel count.
Rate() int
Channels() int
// Preroll is the number of access units to decode and discard before
// the first one that is wanted after Reset, so that overlap-add and
// prediction state has converged.
Preroll() int
}
AudioDecoder decodes compressed audio access units one at a time, as the player feeds them from a TrackStore.
func NewAudioDecoder ¶
func NewAudioDecoder(c TrackConfig) (AudioDecoder, error)
NewAudioDecoder returns a streaming decoder for an audio track.
type BytesSource ¶
type BytesSource []byte
BytesSource wraps an in-memory buffer.
func (BytesSource) Size ¶
func (b BytesSource) Size() int64
type FLACStreamInfo ¶
type Fragment ¶
type Fragment struct {
TrackID int
Start, End float64
Samples int
Keyframe bool
// contains filtered or unexported fields
}
Fragment is one moof's span of a track (seconds) used by probing and MSE.
type FrameSource ¶
type FrameSource interface {
// Mode names the tier: "native" (pure-Go decoder), "ffmpeg", "mjpeg", "anim".
Mode() string
// Frame returns the frame displayed at t seconds. It may block (ffmpeg).
Frame(t float64) (image.Image, error)
Close()
}
FrameSource produces the video frame to show at a presentation time.
func OpenAnimatedImage ¶
func OpenAnimatedImage(data []byte) (FrameSource, bool)
OpenAnimatedImage opens a GIF or APNG as a time-driven frame source. It is used for animated images (not <video>); ok is false for still images.
func OpenFrames ¶
func OpenFrames(src Source, info *Info, path string) (FrameSource, error)
OpenFrames chooses the best available frame provider for the resource. path, when non-empty, is a local file holding the full resource.
type Info ¶
type Info struct {
Container string `json:"container"` // mp4 webm matroska ogg wav mp3 flac aac avi gif apng
Brand string `json:"brand,omitempty"`
Duration float64 `json:"duration"` // seconds; <0 when unknown
Size int64 `json:"size"`
Tracks []Track `json:"tracks"`
Seek []SeekPoint `json:"-"`
Fragmented bool `json:"fragmented,omitempty"`
DataStart int64 `json:"dataStart"` // first byte of media payload
DataEnd int64 `json:"dataEnd"`
BitRate int `json:"bitRate,omitempty"` // average bytes*8/duration of the payload
Title string `json:"title,omitempty"`
XingFrame bool `json:"-"` // mp3: first frame is a Xing/Info header (decodes as silence)
SkipStart int `json:"-"` // mp3: LAME encoder delay (samples)
SkipEnd int `json:"-"` // mp3: LAME padding (samples)
}
Info is the result of probing a media resource.
func ProbeBytes ¶
ProbeBytes is Probe over an in-memory buffer.
func (*Info) ByteForTime ¶
ByteForTime returns the byte offset to start reading from to play at time t (nearest preceding seek point, or a linear estimate).
func (*Info) TimeForByte ¶
TimeForByte is the inverse of ByteForTime.
type KeyHolder ¶
type KeyHolder struct {
// contains filtered or unexported fields
}
KeyHolder points at the KeyStore of the MediaKeys currently attached to the media element that plays a buffer (nil while none is).
type KeyStore ¶
type KeyStore struct {
// contains filtered or unexported fields
}
KeyStore holds content keys by key ID. It is filled by the Clear Key license handling of the page.
type MP4Init ¶
MP4Init summarises an fMP4 initialisation segment for MSE.
func ParseMP4Init ¶
ParseMP4Init parses an initialisation segment (ftyp+moov).
type MP4Moov ¶
type MP4Moov struct {
Timescale uint32
Duration float64
Tracks []*mp4Track
Fragmented bool
FragDur float64
}
MP4Moov is the parsed movie header; used by MSE for init segments.
type MSEBuffer ¶
type MSEBuffer struct {
Mime string
// contains filtered or unexported fields
}
MSEBuffer is the Go side of one SourceBuffer: a byte-stream parser plus the coded frame store of each track, with the MediaSource coded frame processing rules (timestampOffset, append window, segments/sequence mode, overlap removal, random access point handling) and the buffer limits.
func NewMSEBuffer ¶
NewMSEBuffer creates a buffer for a SourceBuffer of the given MIME type.
func (*MSEBuffer) Abort ¶
func (b *MSEBuffer) Abort()
Abort resets the parser and the append window (SourceBuffer.abort()).
func (*MSEBuffer) Append ¶
Append feeds data to the parser and stores the coded frames it yields. cur is the playback position: when the buffer is full, frames before it are evicted, oldest group of pictures first.
func (*MSEBuffer) ChangeType ¶
ChangeType switches the buffer to another MIME type: the parser is replaced and the next appended initialization segment redefines the tracks. Already buffered frames stay (they keep their own configuration).
func (*MSEBuffer) FirstStore ¶
func (b *MSEBuffer) FirstStore(kind string) *TrackStore
FirstStore returns the first store of the given kind ("video" or "audio").
func (*MSEBuffer) SetAppendWindow ¶
SetAppendWindow sets the append window; frames outside it are dropped.
func (*MSEBuffer) SetKeyStore ¶
SetKeyStore attaches the content keys (or nil) used to decrypt the samples of this buffer as they are read.
func (*MSEBuffer) SetTimestampOffset ¶
SetTimestampOffset sets the offset added to every coded frame timestamp.
func (*MSEBuffer) Store ¶
func (b *MSEBuffer) Store(id int) *TrackStore
Store returns the sample store of a track id (nil when unknown).
func (*MSEBuffer) TimestampOffset ¶
TimestampOffset returns the current offset (sequence mode changes it).
func (*MSEBuffer) Tracks ¶
func (b *MSEBuffer) Tracks() []TrackConfig
Tracks lists the track configurations in init order.
type MSEInit ¶
type MSEInit struct {
Duration float64
Tracks []Track
First bool // the first initialization segment of this buffer
// InitData is what an "encrypted" event carries: the pssh boxes ("cenc"), or the key IDs ("keyids") when the
// stream names them without a pssh box.
InitData []MSEInitData
}
MSEInit is reported with every initialization segment.
type MSEInitData ¶
MSEInitData is one initialization data blob for EME.
type MSEResult ¶
type MSEResult struct {
InitData []MSEInitData // pssh boxes of movie fragments (init segments report theirs in Init)
Init *MSEInit
Frames int // coded frames added to the buffer
Dropped int // frames discarded (append window, missing random access point)
Evicted int // bytes freed by coded frame eviction before the append
Buffered [][2]float64
}
MSEResult is what one append produced.
type PCM ¶
PCM is decoded audio: planar float32 in [-1, 1].
func DecodeAudio ¶
DecodeAudio decodes a complete resource to PCM at its native rate.
func DecodeAudioFFmpeg ¶
DecodeAudioFFmpeg decodes anything ffmpeg understands. rate/channels may be 0 to keep the source layout (then mono/44100 is assumed for the raw read).
func DecodeFLAC ¶
DecodeFLAC decodes a whole FLAC stream.
type Picture ¶
type Picture struct {
// contains filtered or unexported fields
}
Picture is a decoded frame that has not been converted to RGB yet. The conversion happens only for frames that are shown.
type Protection ¶
type Protection struct {
Scheme string // "cenc", "cens", "cbc1", "cbcs"
IVSize int // per-sample IV size in bytes; 0 means the constant IV is used
KID [16]byte
ConstIV []byte
CryptBlocks int // pattern: encrypted blocks ...
SkipBlocks int // ... then clear blocks (both 0: every block is encrypted)
Protected bool
}
Protection is the track-level protection scheme information (the sinf box and its tenc defaults).
type Sample ¶
type Sample struct {
DTS, PTS, Dur float64
Key bool
Size int
// Cfg is the configuration of the initialization segment the sample came
// with (MSE: a quality switch changes it mid-stream); nil means the store's.
Cfg *TrackConfig
// contains filtered or unexported fields
}
Sample is one coded access unit of a track. Times are in seconds on the presentation timeline (for MSE, after timestampOffset was applied).
func NewLazySample ¶
NewLazySample builds a sample whose payload is fetched on demand.
func (Sample) Bytes ¶
Bytes returns the coded payload, decrypted when the sample is encrypted and its key is known.
type SampleEnc ¶
SampleEnc is the per-sample encryption information (senc, or saiz/saio auxiliary data).
type SampleRef ¶
MP4Samples returns the sample table (offset, size, time, sync) of a track of a progressive file; used to pull MJPEG frames.
type Track ¶
type Track struct {
ID int `json:"id"`
Kind string `json:"kind"` // "audio", "video", "text"
Codec string `json:"codec"` // RFC 6381 style: avc1.64001e, mp4a.40.2, vp8, vorbis, opus, flac, mp3, 1 (pcm)
CodecName string `json:"codecName"` // ffprobe style: h264, aac, vp8, vorbis, opus, flac, mp3, pcm_s16le
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
FrameRate float64 `json:"frameRate,omitempty"`
SampleRate int `json:"sampleRate,omitempty"`
Channels int `json:"channels,omitempty"`
BitsPerSample int `json:"bitsPerSample,omitempty"`
BitRate int `json:"bitRate,omitempty"`
Duration float64 `json:"duration,omitempty"`
Language string `json:"language,omitempty"`
Name string `json:"name,omitempty"`
Default bool `json:"default,omitempty"`
Frames int `json:"frames,omitempty"`
// contains filtered or unexported fields
}
Track describes one elementary stream of a container.
type TrackConfig ¶
type TrackConfig struct {
ID int
Kind string // "video" | "audio"
Codec string // RFC 6381 string (avc1.64001f, mp4a.40.2, opus, vp09...)
CodecName string // h264 hevc vp8 vp9 av1 aac opus vorbis mp3
Cfg []byte // avcC/hvcC/vpcC/av1C, AudioSpecificConfig, OpusHead or dOps
CfgKind string // "asc" "opushead" "dops" "avcc" ... (audio) / "" (video)
Width int
Height int
FrameRate float64
SampleRate int
Channels int
Skip int // audio: samples (at the output rate) to discard at the start of the track (priming)
Prot *Protection // Common Encryption protection of the track (nil: clear)
}
TrackConfig is what a decoder needs to know about a track.
type TrackSet ¶
type TrackSet struct {
Video, Audio *TrackStore
// Done is nil for a resource that is indexed completely when it is
// returned; otherwise it is closed when a background indexer or decoder has
// added the last sample (until then the stores grow, like a SourceBuffer).
Done <-chan struct{}
// contains filtered or unexported fields
}
TrackSet is what a player needs from a progressive resource: the video and audio sample stores and a way to know when they are complete.
func OpenTrackSet ¶
OpenTrackSet opens any resource the player can handle: MP4/WebM through OpenTracks, MP3 with a background frame indexer, and WAV, FLAC, Ogg and ADTS AAC through a background decode into 16-bit PCM chunks.
type TrackStore ¶
type TrackStore struct {
// contains filtered or unexported fields
}
TrackStore holds the samples of one track sorted by decode time. It backs both progressive files (filled once) and SourceBuffers (appended to, overwritten and trimmed while a decoder reads from it), so every method is safe for concurrent use.
func NewTrackStore ¶
func NewTrackStore(cfg TrackConfig) *TrackStore
NewTrackStore creates an empty store.
func OpenTracks ¶
func OpenTracks(src Source, info *Info) (video, audio *TrackStore, err error)
OpenTracks indexes the first video and the first audio track of a progressive resource (MP4 or fragmented MP4, WebM, Matroska) as sample stores. Payloads of MP4 samples are read from src on demand; WebM is read into memory. A missing track is a nil store.
func (*TrackStore) Append ¶
func (t *TrackStore) Append(ss []Sample)
Append adds samples that are already ordered after everything in the store (progressive loading).
func (*TrackStore) At ¶
func (t *TrackStore) At(dts float64) (Sample, bool)
At returns the sample with the given decode time exactly (within 1 us).
func (*TrackStore) Config ¶
func (t *TrackStore) Config() TrackConfig
Config returns the track configuration.
func (*TrackStore) CountPTS ¶
func (t *TrackStore) CountPTS(after, upTo float64) int
CountPTS counts the samples presented in (after, upTo].
func (*TrackStore) Duration ¶
func (t *TrackStore) Duration() float64
Duration is the end of the last sample by decode order (progressive files).
func (*TrackStore) End ¶
func (t *TrackStore) End() float64
End is the largest end time of any sample (0 when empty).
func (*TrackStore) EvictBefore ¶
func (t *TrackStore) EvictBefore(limit float64, need int) int
EvictBefore frees at least need bytes by dropping whole groups of pictures (sync sample to the next sync sample) that end at or before limit, oldest first. It reports the bytes freed.
func (*TrackStore) FirstAfter ¶
func (t *TrackStore) FirstAfter(tm float64) (Sample, bool)
FirstAfter returns the first sample whose PTS is >= tm (audio seeking and buffering checks).
func (*TrackStore) Gen ¶
func (t *TrackStore) Gen() uint64
Gen changes whenever the contents or the configuration change.
func (*TrackStore) Index ¶
func (t *TrackStore) Index(dts float64) int
Index is the decode-order position of the sample at dts, or -1.
func (*TrackStore) Insert ¶
func (t *TrackStore) Insert(run []Sample) int
Insert adds a run of samples in decode order (one coded frame group), removing what it overwrites: existing samples whose decode time falls in the run's span, plus the non-key samples that followed them (they lost their references). It reports the bytes removed.
func (*TrackStore) KeyAtOrBefore ¶
func (t *TrackStore) KeyAtOrBefore(dts float64) (Sample, bool)
KeyAtOrBefore returns the nearest sync sample with decode time <= dts that is connected to dts without a gap.
func (*TrackStore) Next ¶
func (t *TrackStore) Next(dts float64) (s Sample, ok, gap bool)
Next returns the first sample after dts in decode order. ok is false at the end of the store; gap is true when a hole in the timeline separates it from dts (the caller must restart from a sync sample).
func (*TrackStore) Prev ¶
func (t *TrackStore) Prev(dts float64) (Sample, bool)
Prev returns the last sample before dts in decode order.
func (*TrackStore) Ranges ¶
func (t *TrackStore) Ranges() [][2]float64
Ranges returns the buffered time ranges (presentation intervals merged across gaps smaller than twice the longest sample).
func (*TrackStore) Remove ¶
func (t *TrackStore) Remove(start, end float64) int
Remove deletes the samples whose presentation time is in [start, end) and the non-key samples that depended on them. It reports the bytes freed.
func (*TrackStore) SetConfig ¶
func (t *TrackStore) SetConfig(c TrackConfig)
SetConfig replaces the configuration (a new init segment).
func (*TrackStore) ShownAt ¶
func (t *TrackStore) ShownAt(tm float64) (Sample, bool)
ShownAt returns the sample presented at time tm: the one with the largest PTS not after tm. ok is false when tm is before the first sample, or past the end of the range it falls in (a gap).
func (*TrackStore) Snapshot ¶
func (t *TrackStore) Snapshot() []Sample
Snapshot returns a copy of all samples (tests, diagnostics).
type VideoChunk ¶
VideoChunk is one access unit.
type VideoDecoder ¶
type VideoDecoder struct {
// contains filtered or unexported fields
}
VideoDecoder decodes video access units one at a time, in decode order, with a pure-Go decoder. It is what the player drives from a TrackStore.
func NewVideoDecoder ¶
func NewVideoDecoder(c TrackConfig) (*VideoDecoder, error)
NewVideoDecoder creates a decoder for the track configuration.
func (*VideoDecoder) Codec ¶
func (d *VideoDecoder) Codec() string
Codec is the codec name the decoder was made for.
func (*VideoDecoder) Decode ¶
func (d *VideoDecoder) Decode(data []byte) (Picture, error)
Decode decodes one access unit. The returned picture is invalid when the unit does not produce a displayable picture (a hidden alt-ref frame, a parameter-set-only unit).
func (*VideoDecoder) Disposable ¶
func (d *VideoDecoder) Disposable(data []byte) bool
Disposable reports whether no later picture is predicted from this access unit, so a player that is running late can skip decoding it (only H.264 is recognised: a slice NAL with nal_ref_idc 0, as non-reference B-frames are coded; everything else reports false).
func (*VideoDecoder) Reset ¶
func (d *VideoDecoder) Reset()
Reset drops reference pictures: the next unit must be a sync sample.
type VideoSamples ¶
type VideoSamples struct {
Codec string
Description []byte
Width int
Height int
Chunks []VideoChunk
}
VideoSamples is the first video track of a file as WebCodecs sees it: the codec string, the decoder description and the access units in decode order with their presentation times in microseconds.
func ExtractVideoSamples ¶
func ExtractVideoSamples(data []byte) (*VideoSamples, error)
ExtractVideoSamples demuxes the first video track of an MP4 or WebM file (used by the tests of the WebCodecs layer, and by tools that need the access units of a clip).
type WCAudioDecoder ¶
type WCAudioDecoder struct {
// contains filtered or unexported fields
}
WCAudioDecoder decodes one audio stream to planar float32.
func NewWCAudioDecoder ¶
NewWCAudioDecoder creates a decoder. desc is the codec description (the AudioSpecificConfig, OpusHead, or the Vorbis headers in Xiph lacing); adts says that AAC chunks carry ADTS headers (and no description is needed).
func (*WCAudioDecoder) Channels ¶
func (d *WCAudioDecoder) Channels() int
Channels is the decoder's output channel count.
type WCOpusEncoder ¶
type WCOpusEncoder struct {
// contains filtered or unexported fields
}
WCOpusEncoder encodes interleaved float32 PCM to Opus packets of a fixed duration.
func NewWCOpusEncoder ¶
func NewWCOpusEncoder(rate, ch, bitrate, frameUs int, application string) (*WCOpusEncoder, error)
NewWCOpusEncoder creates an encoder. frameUs is the packet duration in microseconds (2500, 5000, 10000, 20000, 40000 or 60000; 0 means 20000); application is "audio" (default), "voip" or "lowdelay".
func (*WCOpusEncoder) Encode ¶
func (e *WCOpusEncoder) Encode(pcm []float32) ([]byte, error)
Encode encodes exactly FrameSamples samples per channel (interleaved).
func (*WCOpusEncoder) FrameSamples ¶
func (e *WCOpusEncoder) FrameSamples() int
FrameSamples is the number of samples per channel in one packet.
func (*WCOpusEncoder) PreSkip ¶
func (e *WCOpusEncoder) PreSkip() int
PreSkip is the encoder delay in samples at 48 kHz (what OpusHead's pre-skip field carries).
func (*WCOpusEncoder) SetBitrate ¶
func (e *WCOpusEncoder) SetBitrate(bps int)
SetBitrate changes the target bitrate.
func (*WCOpusEncoder) SetCBR ¶
func (e *WCOpusEncoder) SetCBR(on bool)
SetCBR switches between constant and variable bitrate.
type WCPicture ¶
type WCPicture struct {
Width, Height int
Format string // "I420", "I422", "I444" or "RGBA"
Planes [][]byte // one per plane; for RGBA a single interleaved plane
Strides []int
FullRange bool
Matrix string // "bt709" or "smpte170m" for YUV, "rgb" for RGBA
}
WCPicture is a decoded picture in the layout WebCodecs hands out: tightly packed planes.
type WCVP8Encoder ¶
type WCVP8Encoder struct {
// contains filtered or unexported fields
}
WCVP8Encoder is a VP8 encoder with the knobs WebCodecs has.
func NewWCVP8Encoder ¶
func NewWCVP8Encoder(w, h, bitrate int, fps float64, keyInterval int) (*WCVP8Encoder, error)
NewWCVP8Encoder creates an encoder for w x h frames (at least 16 x 16).
func (*WCVP8Encoder) Encode ¶
func (e *WCVP8Encoder) Encode(w, h int, y, u, v []byte, ys, cs int, key bool) (data []byte, isKey bool, err error)
Encode encodes one I420 picture. A different size than before resizes the encoder (the output is a key frame). data is nil when rate control dropped the frame.
func (*WCVP8Encoder) SetBitrate ¶
func (e *WCVP8Encoder) SetBitrate(bps int)
SetBitrate and SetFrameRate reconfigure rate control without a new key frame.
func (*WCVP8Encoder) SetFrameRate ¶
func (e *WCVP8Encoder) SetFrameRate(fps float64)
type WCVideoDecoder ¶
type WCVideoDecoder struct {
// contains filtered or unexported fields
}
WCVideoDecoder decodes one video elementary stream.
func NewWCVideoDecoder ¶
func NewWCVideoDecoder(codec string, desc []byte) (*WCVideoDecoder, error)
NewWCVideoDecoder creates a decoder. desc is the codec description (avcC, hvcC, av1C) or nil: H.264 without a description is read as Annex B, as WebCodecs defines.
func (*WCVideoDecoder) Decode ¶
func (d *WCVideoDecoder) Decode(data []byte) ([]*WCPicture, error)
Decode decodes one access unit (one chunk) and returns the pictures it completes: none for a hidden frame or a parameter-set-only unit, usually one. A picture that came with a recoverable error is returned without the error.
func (*WCVideoDecoder) DecodeOrder ¶
func (d *WCVideoDecoder) DecodeOrder() bool
DecodeOrder reports how pictures relate to chunks: true when the picture Decode returns is the one the chunk carries (the caller reorders by timestamp, ReorderDepth pictures deep); false for HEVC, whose decoder outputs in display order with its own delay (the caller gives the pictures the smallest outstanding timestamps).
func (*WCVideoDecoder) Flush ¶
func (d *WCVideoDecoder) Flush() []*WCPicture
Flush returns the pictures still held back by the decoder's own output delay (HEVC).
func (*WCVideoDecoder) ReorderDepth ¶
func (d *WCVideoDecoder) ReorderDepth() int
ReorderDepth is how many pictures a consumer ordering by timestamp has to hold back (H.264 only).
func (*WCVideoDecoder) Reset ¶
func (d *WCVideoDecoder) Reset()
Reset drops the reference pictures: the next chunk must be a key frame.
type WebMBlock ¶
type WebMBlock struct {
Track int
Time float64 // absolute seconds
Duration float64
Key bool
Data []byte
}
WebMBlock is one (Simple)Block: time is seconds relative to the cluster start only when called from ParseWebMBlocks; WebMSegment resolves absolute.
func ParseWebMBlocks ¶
ParseWebMBlocks decodes the Clusters in b (a buffer starting at a Cluster element or at a Segment's children) with the default 1 ms timecode scale.
func ParseWebMBlocksScale ¶
ParseWebMBlocksScale is ParseWebMBlocks with an explicit timecode scale.
Source Files
¶
- aac.go
- aac_mdct.go
- aac_tables.go
- aac_tables_gen.go
- adec.go
- apng.go
- audio_containers.go
- audio_packets.go
- av1adapter.go
- canplay.go
- cenc.go
- decode.go
- doc.go
- ebml.go
- esbr_adj.go
- esbr_core.go
- esbr_env.go
- esbr_hbe.go
- esbr_hdr.go
- esbr_hf.go
- esbr_parse.go
- esbr_pvc.go
- esbr_qmf.go
- esbr_tables_gen.go
- flac.go
- frames.go
- info.go
- lpd_acelp.go
- lpd_avq.go
- lpd_dec.go
- lpd_main.go
- lpd_parse.go
- lpd_tcx.go
- lpd_trans.go
- mp4.go
- mps_dec.go
- mps_parse.go
- mps_tables_gen.go
- mse.go
- mse_mp4.go
- mse_webm.go
- opus.go
- ps.go
- sbr.go
- sbr_qmf.go
- sbr_tables_gen.go
- track.go
- tracks.go
- trackset.go
- usac_ac.go
- usac_config.go
- usac_dec.go
- usac_fd.go
- usac_loud.go
- usac_mdct.go
- usac_stereo.go
- usac_stream.go
- usac_tables_gen.go
- usac_tables_xaac_gen.go
- vdec.go
- vframes.go
- vsamples.go
- wcodecs.go
- yuvrgba.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package av1 is a pure-Go AV1 video decoder (AV1 Bitstream & Decoding Process Specification v1.0.0 errata 1).
|
Package av1 is a pure-Go AV1 video decoder (AV1 Bitstream & Decoding Process Specification v1.0.0 errata 1). |
|
Package cdm is the key-system layer behind Encrypted Media Extensions: one Go interface that Clear Key, Widevine, PlayReady and FairPlay backends all implement, so the EME JavaScript layer (MediaKeySystemAccess, MediaKeys, MediaKeySession) can drive every key system the same way.
|
Package cdm is the key-system layer behind Encrypted Media Extensions: one Go interface that Clear Key, Widevine, PlayReady and FairPlay backends all implement, so the EME JavaScript layer (MediaKeySystemAccess, MediaKeys, MediaKeySession) can drive every key system the same way. |
|
fairplay
Package fairplay is the FairPlay Streaming key system (com.apple.fps) on macOS, backed by AVFoundation's AVContentKeySession, driven from Go through the Objective-C runtime with purego (no cgo).
|
Package fairplay is the FairPlay Streaming key system (com.apple.fps) on macOS, backed by AVFoundation's AVContentKeySession, driven from Go through the Objective-C runtime with purego (no cgo). |
|
platform
Package platform assembles the key system registry for the running operating system: Clear Key everywhere, Widevine through the separate CDM host helper wherever a Widevine CDM is installed, PlayReady on Windows and FairPlay on macOS (both unverified and opt-in, see their packages).
|
Package platform assembles the key system registry for the running operating system: Clear Key everywhere, Widevine through the separate CDM host helper wherever a Widevine CDM is installed, PlayReady on Windows and FairPlay on macOS (both unverified and opt-in, see their packages). |
|
playready
Package playready is the PlayReady (com.microsoft.playready) key system on Windows, backed by the PlayReady CDM that ships with Windows through Media Foundation's content decryption module interfaces (IMFContentDecryptionModuleFactory / Access / IMFContentDecryptionModule / Session, mfmediaengine.h and mfcontentdecryptionmodule.h of the Windows SDK), called from Go through COM vtables with golang.org/x/sys/windows.
|
Package playready is the PlayReady (com.microsoft.playready) key system on Windows, backed by the PlayReady CDM that ships with Windows through Media Foundation's content decryption module interfaces (IMFContentDecryptionModuleFactory / Access / IMFContentDecryptionModule / Session, mfmediaengine.h and mfcontentdecryptionmodule.h of the Windows SDK), called from Go through COM vtables with golang.org/x/sys/windows. |
|
widevinehost
Package widevinehost hosts a Chromium-ABI Content Decryption Module (the Widevine CDM shared library) from pure Go, without cgo.
|
Package widevinehost hosts a Chromium-ABI Content Decryption Module (the Widevine CDM shared library) from pure Go, without cgo. |
|
Package h264 is a pure-Go H.264/AVC decoder for 8-bit 4:2:0 progressive video: Baseline, Main and High profiles with CAVLC or CABAC, I/P/B slices, multiple reference frames, weighted prediction, 8x8 transform and the in-loop deblocking filter.
|
Package h264 is a pure-Go H.264/AVC decoder for 8-bit 4:2:0 progressive video: Baseline, Main and High profiles with CAVLC or CABAC, I/P/B slices, multiple reference frames, weighted prediction, 8x8 transform and the in-loop deblocking filter. |
|
Package hevc is a pure-Go HEVC / H.265 video decoder (ITU-T H.265): Main, Main 10, Main Still Picture, the range extensions (4:0:0 to 4:4:4, 8 to 16 bit samples, extended precision processing, CABAC bypass alignment), the screen content coding extensions (palette mode, current picture referencing, adaptive colour transform, adaptive motion vector resolution) and multilayer streams with inter-layer prediction (MV-HEVC: any layer can be selected with SetOutputLayer, the base layer by default).
|
Package hevc is a pure-Go HEVC / H.265 video decoder (ITU-T H.265): Main, Main 10, Main Still Picture, the range extensions (4:0:0 to 4:4:4, 8 to 16 bit samples, extended precision processing, CABAC bypass alignment), the screen content coding extensions (palette mode, current picture referencing, adaptive colour transform, adaptive motion vector resolution) and multilayer streams with inter-layer prediction (MV-HEVC: any layer can be selected with SetOutputLayer, the base layer by default). |
|
Package vp8 is a complete VP8 video decoder (RFC 6386): key frames and inter frames with motion compensation, golden and altref references, segmentation, probability updates and both loop filters.
|
Package vp8 is a complete VP8 video decoder (RFC 6386): key frames and inter frames with motion compensation, golden and altref references, segmentation, probability updates and both loop filters. |
|
Package vp8enc is a pure Go VP8 video encoder (RFC 6386) for real-time use.
|
Package vp8enc is a pure Go VP8 video encoder (RFC 6386) for real-time use. |
|
Package vp9 is a pure-Go VP9 video decoder following the VP9 Bitstream & Decoding Process Specification v0.6: profile 0 (8-bit 4:2:0) with all intra and inter tools (compound prediction, scaled references, segmentation, tiles, loop filter, backward probability adaptation).
|
Package vp9 is a pure-Go VP9 video decoder following the VP9 Bitstream & Decoding Process Specification v0.6: profile 0 (8-bit 4:2:0) with all intra and inter tools (compound prediction, scaled references, segmentation, tiles, loop filter, backward probability adaptation). |
|
Package wavefront is the progress counter that the row-parallel loop filters of the video decoders wait on: row r of a picture may process unit c once row r-1 has finished unit c+1 or so.
|
Package wavefront is the progress counter that the row-parallel loop filters of the video decoders wait on: row r of a picture may process unit c once row r-1 has finished unit c+1 or so. |
|
Package webaudio implements the Web Audio rendering graph in pure Go: nodes, AudioParam automation, channel mixing and the DSP kernels.
|
Package webaudio implements the Web Audio rendering graph in pure Go: nodes, AudioParam automation, channel mixing and the DSP kernels. |
|
Package yuv defines the planar picture type shared by the pure-Go video decoders for formats that image.YCbCr cannot hold: sample depths above 8 bits, 4:0:0 and the less common chroma layouts.
|
Package yuv defines the planar picture type shared by the pure-Go video decoders for formats that image.YCbCr cannot hold: sample depths above 8 bits, 4:0:0 and the less common chroma layouts. |