media

package
v0.1.0-alpha.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 39 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	QuotaVideo = 150 << 20
	QuotaAudio = 12 << 20
)

Default buffer limits, the same as Chromium's SourceBuffer limits.

Variables

View Source
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.

View Source
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.

View Source
var ErrTruncated = errors.New("media: truncated data")

ErrTruncated means the resource ended inside a structure.

View Source
var ErrUnknownFormat = errors.New("media: unrecognised container")

ErrUnknownFormat is returned when no parser recognises the data.

View Source
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

func B64URL(s string) ([]byte, error)

B64URL decodes the base64url strings of Clear Key licenses and key ID lists (padding is optional).

func CanPlayType

func CanPlayType(mime string) string

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

func HasNativeVideo(codec string) bool

HasNativeVideo reports whether codec (ffprobe style name) can be decoded without ffmpeg.

func IntersectRanges

func IntersectRanges(a, b [][2]float64) [][2]float64

IntersectRanges returns the intersection of two sorted range lists.

func IsTypeSupportedMSE

func IsTypeSupportedMSE(mime string) bool

IsTypeSupportedMSE is MediaSource.isTypeSupported: only fragmented containers the segment parsers handle.

func NativeAudio

func NativeAudio(info *Info) bool

NativeAudio reports whether the codec of a container is decoded by pure Go.

func OpusHeadBytes

func OpusHeadBytes(ch, inputRate, preSkip int) []byte

OpusHeadBytes builds the identification header (RFC 7845) WebCodecs uses as the Opus decoder description.

func ParseMIME

func ParseMIME(s string) (typ string, codecs []string, hasCodecs bool, ok bool)

ParseMIME splits "type/subtype; codecs=\"a, b\"" into its parts. ok is false for malformed types; quoted reports whether codecs was quoted.

func Playable

func Playable(info *Info) (bool, string)

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

func VP8Keyframe(b []byte) bool

VP8Keyframe is a convenience for tests: whether a raw VP8 frame is a key frame.

func WCAudioName

func WCAudioName(codec string) string

WCAudioName maps a codec string to the decoder family ("" if unknown).

func WCVideoName

func WCVideoName(codec string) string

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) ReadAt

func (b BytesSource) ReadAt(p []byte, off int64) (int, error)

func (BytesSource) Size

func (b BytesSource) Size() int64

type FLACStreamInfo

type FLACStreamInfo struct {
	MinBlock, MaxBlock int
	SampleRate         int
	Channels, Bits     int
	TotalSamples       int64
	FirstFrame         int64
	Seek               []SeekPoint
}

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.

func ParseMP4Segment

func ParseMP4Segment(b []byte, init *MP4Init) ([]Fragment, error)

ParseMP4Segment returns per-track time spans of a media segment (moof+mdat...). The init segment is needed for timescales.

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 Probe

func Probe(r io.ReaderAt, size int64) (*Info, error)

Probe sniffs and parses the container of r.

func ProbeBytes

func ProbeBytes(b []byte) (*Info, error)

ProbeBytes is Probe over an in-memory buffer.

func (*Info) Audio

func (i *Info) Audio() *Track

Audio returns the first audio track or nil.

func (*Info) ByteForTime

func (i *Info) ByteForTime(t float64) int64

ByteForTime returns the byte offset to start reading from to play at time t (nearest preceding seek point, or a linear estimate).

func (*Info) HasVideo

func (i *Info) HasVideo() bool

HasVideo reports whether any video track exists.

func (*Info) MIME

func (i *Info) MIME() string

MIME is the canonical MIME type including a codecs parameter.

func (*Info) TimeForByte

func (i *Info) TimeForByte(b int64) float64

TimeForByte is the inverse of ByteForTime.

func (*Info) Video

func (i *Info) Video() *Track

Video returns the first video track or nil.

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).

func (*KeyHolder) Get

func (h *KeyHolder) Get() *KeyStore

Get returns the attached key store.

func (*KeyHolder) Set

func (h *KeyHolder) Set(k *KeyStore)

Set attaches or detaches (nil) a key store.

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.

func NewKeyStore

func NewKeyStore() *KeyStore

NewKeyStore creates an empty store.

func (*KeyStore) Add

func (k *KeyStore) Add(kid [16]byte, key []byte)

Add stores a key (16 bytes) for a key ID.

func (*KeyStore) Get

func (k *KeyStore) Get(kid [16]byte) []byte

Get returns the key for a key ID, or nil.

type MP4Init

type MP4Init struct {
	Tracks []Track
	Dur    float64
	// contains filtered or unexported fields
}

MP4Init summarises an fMP4 initialisation segment for MSE.

func ParseMP4Init

func ParseMP4Init(b []byte) (*MP4Init, error)

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

func NewMSEBuffer(mime string) *MSEBuffer

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

func (b *MSEBuffer) Append(data []byte, cur float64) (*MSEResult, error)

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) Buffered

func (b *MSEBuffer) Buffered() [][2]float64

Buffered is the intersection of the tracks' buffered ranges.

func (*MSEBuffer) Bytes

func (b *MSEBuffer) Bytes() int

Bytes is the amount of coded data held.

func (*MSEBuffer) ChangeType

func (b *MSEBuffer) ChangeType(mime string)

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) Gen

func (b *MSEBuffer) Gen() uint64

Gen changes whenever the buffered data changes.

func (*MSEBuffer) Remove

func (b *MSEBuffer) Remove(start, end float64)

Remove deletes buffered frames in [start, end) (SourceBuffer.remove()).

func (*MSEBuffer) SetAppendWindow

func (b *MSEBuffer) SetAppendWindow(start, end float64)

SetAppendWindow sets the append window; frames outside it are dropped.

func (*MSEBuffer) SetKeyStore

func (b *MSEBuffer) SetKeyStore(k *KeyStore)

SetKeyStore attaches the content keys (or nil) used to decrypt the samples of this buffer as they are read.

func (*MSEBuffer) SetMode

func (b *MSEBuffer) SetMode(sequence bool)

SetMode selects "segments" (false) or "sequence" (true) timestamp mode.

func (*MSEBuffer) SetQuota

func (b *MSEBuffer) SetQuota(n int)

SetQuota overrides the buffer limit in bytes (0 restores the default).

func (*MSEBuffer) SetTimestampOffset

func (b *MSEBuffer) SetTimestampOffset(v float64)

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

func (b *MSEBuffer) TimestampOffset() float64

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.

func (*MSEBuffer) Truncate

func (b *MSEBuffer) Truncate(d float64)

Truncate removes everything at or after d (a duration shorter than the buffered data, MediaSource.duration setter).

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

type MSEInitData struct {
	Type string // "cenc" or "keyids"
	Data []byte
}

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

type PCM struct {
	SampleRate int
	Data       [][]float32
}

PCM is decoded audio: planar float32 in [-1, 1].

func DecodeAudio

func DecodeAudio(data []byte) (*PCM, error)

DecodeAudio decodes a complete resource to PCM at its native rate.

func DecodeAudioFFmpeg

func DecodeAudioFFmpeg(data []byte, rate, channels int) (*PCM, error)

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

func DecodeFLAC(data []byte) (*PCM, error)

DecodeFLAC decodes a whole FLAC stream.

func Resample

func Resample(p *PCM, to int) *PCM

Resample converts PCM to another rate with a windowed-sinc kernel.

func (*PCM) Duration

func (p *PCM) Duration() float64

Duration in seconds.

func (*PCM) Frames

func (p *PCM) Frames() int

Frames is the sample-frame count.

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.

func (Picture) RGBA

func (p Picture) RGBA() *image.RGBA

RGBA converts the picture for display (BT.709 for HD, BT.601 below).

func (Picture) Size

func (p Picture) Size() (int, int)

Size is the picture size in pixels.

func (Picture) Valid

func (p Picture) Valid() bool

Valid reports whether the picture holds pixels.

func (Picture) Wait

func (p Picture) Wait()

Wait blocks until the picture is completely decoded (pictures of a decoder that works on several frames at once are returned while their last rows are still being reconstructed).

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

func NewLazySample(dts, pts, dur float64, key bool, size int, load func() ([]byte, error)) Sample

NewLazySample builds a sample whose payload is fetched on demand.

func NewSample

func NewSample(dts, pts, dur float64, key bool, data []byte) Sample

NewSample builds a sample from an in-memory payload.

func (Sample) Bytes

func (s Sample) Bytes() ([]byte, error)

Bytes returns the coded payload, decrypted when the sample is encrypted and its key is known.

func (Sample) Encrypted

func (s Sample) Encrypted() bool

Encrypted reports whether the sample's payload is encrypted.

func (Sample) End

func (s Sample) End() float64

End is the end of the sample's presentation interval.

func (Sample) KID

func (s Sample) KID() [16]byte

KID is the key ID the sample is encrypted with.

type SampleEnc

type SampleEnc struct {
	IV   []byte
	Subs []Subsample
}

SampleEnc is the per-sample encryption information (senc, or saiz/saio auxiliary data).

type SampleRef

type SampleRef struct {
	Offset int64
	Size   int
	Time   float64
	Sync   bool
}

MP4Samples returns the sample table (offset, size, time, sync) of a track of a progressive file; used to pull MJPEG frames.

func MP4Samples

func MP4Samples(r io.ReaderAt, size int64, trackID int) (fourcc string, refs []SampleRef, err error)

type SeekPoint

type SeekPoint struct {
	Time   float64 `json:"t"`
	Offset int64   `json:"o"`
}

SeekPoint maps a presentation time to a byte offset (a keyframe/cue/page).

type Source

type Source interface {
	io.ReaderAt
	Size() int64
}

Source is a random-access media resource.

type Subsample

type Subsample struct {
	Clear uint16
	Enc   uint32
}

Subsample is one clear run followed by one encrypted run of a sample.

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

func OpenTrackSet(src Source, info *Info) (*TrackSet, error)

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.

func (*TrackSet) Failed

func (t *TrackSet) Failed() error

Failed returns the error of a background job, if any.

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) Bytes

func (t *TrackStore) Bytes() int

Bytes is the total coded size.

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) Len

func (t *TrackStore) Len() int

Len is the number of samples.

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) RemoveAll

func (t *TrackStore) RemoveAll()

RemoveAll empties the store.

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

type VideoChunk struct {
	Data     []byte
	PTS, Dur int64 // microseconds
	Key      bool
}

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 WAVFormat

type WAVFormat struct {
	Tag, Channels, SampleRate, BlockAlign, Bits int
	DataOff, DataLen                            int64
}

type WCAudioDecoder

type WCAudioDecoder struct {
	// contains filtered or unexported fields
}

WCAudioDecoder decodes one audio stream to planar float32.

func NewWCAudioDecoder

func NewWCAudioDecoder(codec string, desc []byte, rate, ch int, adts bool) (*WCAudioDecoder, error)

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.

func (*WCAudioDecoder) Decode

func (d *WCAudioDecoder) Decode(pkt []byte) (planar [][]float32, rate int, err error)

Decode decodes one chunk. The result is valid until the next call; it may be empty (priming).

func (*WCAudioDecoder) Reset

func (d *WCAudioDecoder) Reset()

Reset drops decoder history.

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

func ParseWebMBlocks(b []byte) []WebMBlock

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

func ParseWebMBlocksScale(b []byte, scale uint64) []WebMBlock

ParseWebMBlocksScale is ParseWebMBlocks with an explicit timecode scale.

type WebMInit

type WebMInit struct {
	Scale  uint64
	Dur    float64
	Tracks []Track
}

WebMInit describes an init segment (EBML header + Segment{Info,Tracks}).

func ParseWebMInit

func ParseWebMInit(b []byte) (*WebMInit, error)

ParseWebMInit parses the head of a WebM stream up to the first Cluster.

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).
cdm
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL