matroska

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 27 Imported by: 2 modules, 1 package

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 matroska provides a high-level Matroska muxer and demuxer.

The package accepts normalized codec frames/access units. It does not parse RTP, repair packet loss, depacketize codecs, or depend on protocol packages.

Index

Constants

View Source
const (
	ContentEncodingScopeBlock   uint64 = 1
	ContentEncodingScopePrivate uint64 = 2
	ContentEncodingScopeNext    uint64 = 4

	ContentEncodingTypeCompression uint64 = 0
	ContentEncodingTypeEncryption  uint64 = 1

	ContentCompAlgoZlib            uint64 = 0
	ContentCompAlgoBzlib           uint64 = 1
	ContentCompAlgoLZO1X           uint64 = 2
	ContentCompAlgoHeaderStripping uint64 = 3

	ContentEncAlgoNotEncrypted uint64 = 0
	ContentEncAlgoDES          uint64 = 1
	ContentEncAlgoTripleDES    uint64 = 2
	ContentEncAlgoTwofish      uint64 = 3
	ContentEncAlgoBlowfish     uint64 = 4
	ContentEncAlgoAES          uint64 = 5

	ContentEncAESCipherModeCTR uint64 = 1
	ContentEncAESCipherModeCBC uint64 = 2

	ContentSigAlgoNotSigned uint64 = 0
	ContentSigAlgoRSA       uint64 = 1

	ContentSigHashAlgoNotSigned uint64 = 0
	ContentSigHashAlgoSHA1      uint64 = 1
	ContentSigHashAlgoMD5       uint64 = 2
)

Variables

View Source
var (
	ErrNilReader                  = errors.New("matroska: nil reader")
	ErrNilWriter                  = errors.New("matroska: nil writer")
	ErrNilPacket                  = errors.New("matroska: nil packet")
	ErrClosed                     = errors.New("matroska: closed")
	ErrInvalidTrack               = errors.New("matroska: invalid track")
	ErrUnknownTrack               = errors.New("matroska: unknown track")
	ErrNonSeekableReader          = errors.New("matroska: reader is not seekable")
	ErrTrackAfterWrite            = errors.New("matroska: cannot add track after writing packets")
	ErrUnsupportedCodec           = errors.New("matroska: unsupported codec")
	ErrUnsupportedElement         = errors.New("matroska: unsupported element")
	ErrUnsupportedContentEncoding = errors.New("matroska: content encoding is not supported")
	ErrLZOContentEncoding         = errors.New("matroska: LZO content encoding is not supported")
	ErrBzip2ContentEncodingWrite  = errors.New("matroska: writing bzip2 content encoding is not supported (read-only)")
	ErrUnsupportedLacing          = errors.New("matroska: lacing is not supported")
	ErrLaceTooLarge               = errors.New("matroska: laced block exceeds configured bounds")
	ErrInvalidData                = errors.New("matroska: invalid data")
	ErrSeekHeadTooSmall           = errors.New("matroska: reserved seek head is too small")
	ErrPayloadTooSmall            = errors.New("matroska: packet data capacity too small")
	ErrTimecodeOverflow           = errors.New("matroska: block timecode out of range")
)

Functions

func Descriptor

func Descriptor() format.Descriptor

func Register

func Register(registry *format.SimpleRegistry)

Types

type Attachment

type Attachment struct {
	UID             uint64
	Filename        string
	MIMEType        string
	Description     string
	Data            []byte
	UnknownElements []UnknownElement
}

type AudioConfig

type AudioConfig struct {
	SampleRate       int
	OutputSampleRate int
	Channels         int
	BitDepth         int
}

type BlockAddition

type BlockAddition struct {
	ID   uint64
	Data []byte
}

type BlockAdditionMapping

type BlockAdditionMapping struct {
	IDValue   uint64
	Name      string
	Type      uint64
	ExtraData []byte
}

type Chapter

type Chapter struct {
	UID             uint64
	StringUID       string
	StartNS         int64
	EndNS           int64
	EndSet          bool
	Hidden          bool
	Enabled         bool
	EnabledSet      bool
	TrackUIDs       []uint64
	Displays        []ChapterDisplay
	Children        []Chapter
	UnknownElements []UnknownElement
}

type ChapterDisplay

type ChapterDisplay struct {
	String          string
	Language        string
	LanguageBCP47   string
	Country         string
	UnknownElements []UnknownElement
}

type ChapterEdition

type ChapterEdition struct {
	UID             uint64
	Hidden          bool
	Default         bool
	Ordered         bool
	Chapters        []Chapter
	UnknownElements []UnknownElement
}

type Codec

type Codec int
const (
	CodecUnknown Codec = iota
	CodecOpus
	CodecVorbis
	CodecFLAC
	CodecAAC
	CodecPCMU
	CodecPCMA
	CodecVP8
	CodecVP9
	CodecAV1
	CodecH264
	CodecH265
	CodecTextUTF8
)

type ContentCompression

type ContentCompression struct {
	Algorithm uint64
	Settings  []byte
}

type ContentEncAESSettings

type ContentEncAESSettings struct {
	CipherMode uint64
}

type ContentEncoding

type ContentEncoding struct {
	Order          uint64
	Scope          uint64
	Type           uint64
	Compression    ContentCompression
	CompressionSet bool
	Encryption     ContentEncryption
	EncryptionSet  bool
}

type ContentEncryption

type ContentEncryption struct {
	Algorithm              uint64
	KeyID                  []byte
	AESSettings            ContentEncAESSettings
	AESSettingsSet         bool
	Signature              []byte
	SignatureKeyID         []byte
	SignatureAlgorithm     uint64
	SignatureHashAlgorithm uint64
}

type ContentEncryptionKey

type ContentEncryptionKey struct {
	KeyID []byte
	Key   []byte
}

type CuePoint

type CuePoint struct {
	TrackID             uint32
	TimeNS              int64
	ClusterPosition     uint64
	RelativePosition    uint64
	RelativePositionSet bool
	DurationNS          int64
	DurationSet         bool
	BlockNumber         uint64
	BlockNumberSet      bool
	CodecStatePosition  uint64
	CodecStateSet       bool
	References          []CueReference
	Positions           []CueTrackPosition
}

type CuePolicy

type CuePolicy int

CuePolicy controls which packets are indexed in seekable output.

const (
	// CuePolicyDefault indexes audio packets and keyframe video packets.
	CuePolicyDefault CuePolicy = iota
	// CuePolicyKeyframes indexes only packets marked as keyframes.
	CuePolicyKeyframes
	// CuePolicyAllPackets indexes every written packet or laced block.
	CuePolicyAllPackets
	// CuePolicyNone disables cue collection and Cues writing.
	CuePolicyNone
)

type CueReference

type CueReference struct {
	TimeNS             int64
	ClusterPosition    uint64
	BlockNumber        uint64
	BlockNumberSet     bool
	CodecStatePosition uint64
	CodecStateSet      bool
}

type CueTrackPosition

type CueTrackPosition struct {
	TrackID             uint32
	ClusterPosition     uint64
	RelativePosition    uint64
	RelativePositionSet bool
	DurationNS          int64
	DurationSet         bool
	BlockNumber         uint64
	BlockNumberSet      bool
	CodecStatePosition  uint64
	CodecStateSet       bool
	References          []CueReference
}

type Demuxer

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

func NewDemuxer

func NewDemuxer(r io.Reader, opts DemuxerOptions) (*Demuxer, error)

func (*Demuxer) Attachments

func (d *Demuxer) Attachments() []Attachment

func (*Demuxer) CanSeek

func (d *Demuxer) CanSeek() bool

CanSeek reports whether the reader can reposition: it is an io.Seeker that knows its position, which a pipe does not.

func (*Demuxer) Chapters

func (d *Demuxer) Chapters() []ChapterEdition

func (*Demuxer) Cues

func (d *Demuxer) Cues() []CuePoint

func (*Demuxer) DocType

func (d *Demuxer) DocType() string

func (*Demuxer) Info

func (d *Demuxer) Info() SegmentInfo

func (*Demuxer) ReadCuedPacketAtTime

func (d *Demuxer) ReadCuedPacketAtTime(timeNS int64, dst *Packet) error

ReadCuedPacketAtTime seeks to the first cue at or after timeNS and reads the cued packet. Exact block cues jump to the block; cluster-only cues scan within the referenced Cluster until the cue's track/time is reached. It does not scan uncued packets between cues; use ReadPacketAtTime when uncued packets should be considered too.

func (*Demuxer) ReadCuedTrackPacketAtTime

func (d *Demuxer) ReadCuedTrackPacketAtTime(trackID uint32, timeNS int64, dst *Packet) error

ReadCuedTrackPacketAtTime seeks to the first cue for trackID at or after timeNS and reads that cued packet. Exact block cues jump to the block; cluster-only cues scan within the referenced Cluster until the cue's track/time is reached. It does not scan uncued packets between cues; use ReadTrackPacketAtTime when uncued packets should be considered too.

func (*Demuxer) ReadPacket

func (d *Demuxer) ReadPacket(dst *Packet) error

ReadPacket reads the next packet into dst. The read is zero-allocation by contract: the payload is written into dst.Data's existing capacity (Reset keeps the backing array), so the caller sizes dst.Data once — for example make([]byte, 0, maxPacketSize) — and a payload that does not fit is refused with ErrPayloadTooSmall instead of growing the buffer. io.EOF reports the end of the media.

func (*Demuxer) ReadPacketAtTime

func (d *Demuxer) ReadPacketAtTime(timeNS int64, dst *Packet) error

ReadPacketAtTime reads the first packet at or after timeNS. Seekable readers use a direct packet index when Cues are absent or too sparse to identify uncued packets without scanning.

func (*Demuxer) ReadTrackPacketAtTime

func (d *Demuxer) ReadTrackPacketAtTime(trackID uint32, timeNS int64, dst *Packet) error

ReadTrackPacketAtTime reads the first packet for trackID at or after timeNS. Seekable readers use a direct packet index when Cues are absent or too sparse for that track.

func (*Demuxer) SeekEntries

func (d *Demuxer) SeekEntries() []SeekEntry

func (*Demuxer) SeekToTime

func (d *Demuxer) SeekToTime(timeNS int64) error

func (*Demuxer) SeekToTrackTime

func (d *Demuxer) SeekToTrackTime(trackID uint32, timeNS int64) error

SeekToTrackTime seeks to the nearest preceding cue for trackID and timeNS. If the requested time is before that track's first cue, it seeks to the first cue for the track.

func (*Demuxer) Tags

func (d *Demuxer) Tags() []Tag

func (*Demuxer) Tracks

func (d *Demuxer) Tracks() []Track

func (*Demuxer) UnknownAttachmentsElements

func (d *Demuxer) UnknownAttachmentsElements() []UnknownElement

func (*Demuxer) UnknownChaptersElements

func (d *Demuxer) UnknownChaptersElements() []UnknownElement

func (*Demuxer) UnknownSegmentElements

func (d *Demuxer) UnknownSegmentElements() []UnknownElement

func (*Demuxer) UnknownTagsElements

func (d *Demuxer) UnknownTagsElements() []UnknownElement

func (*Demuxer) UnknownTracksElements

func (d *Demuxer) UnknownTracksElements() []UnknownElement

type DemuxerFactory

type DemuxerFactory struct{}

func (DemuxerFactory) NewDemuxer

func (DemuxerFactory) NewDemuxer(ctx context.Context, result format.ProbeResult) (format.Demuxer, error)

type DemuxerOptions

type DemuxerOptions struct {
	MaxElementSize        uint64
	MaxLaceFrames         int
	MaxLacePayload        int
	ContentEncryptionKeys []ContentEncryptionKey
}

type FormatDemuxer

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

FormatDemuxer adapts a Matroska-family demuxer to format.Demuxer. The zero value reads Matroska; NewFormatDemuxer reads a profile through its own demuxer.

func NewFormatDemuxer

func NewFormatDemuxer(format av.FormatID, open func(io.Reader) (TrackDemuxer, error)) *FormatDemuxer

NewFormatDemuxer returns the adapter reading format through the demuxer open returns for each input.

func (*FormatDemuxer) CanSeek

func (d *FormatDemuxer) CanSeek() bool

CanSeek reports whether the opened input can reposition (format.Seeker): the track demuxer's CanSeek when it has one.

func (*FormatDemuxer) Close

func (d *FormatDemuxer) Close() error

func (*FormatDemuxer) Format

func (d *FormatDemuxer) Format() av.FormatID

func (*FormatDemuxer) Open

func (*FormatDemuxer) ReadInto

func (d *FormatDemuxer) ReadInto(ctx context.Context, out *format.ReadResult) error

func (*FormatDemuxer) Seek

func (d *FormatDemuxer) Seek(ctx context.Context, position time.Duration) error

Seek implements format.Seeker: it repositions the demuxer to the nearest cue at or before position (falling back to the demuxer's cluster index when the file carries no Cues), so the next ReadInto resumes at a keyframe-aligned point at or before position. Input opened from a reader that cannot seek reports an error wrapping format.ErrNotSeekable.

func (*FormatDemuxer) Streams

func (d *FormatDemuxer) Streams() []av.Stream

type FormatMuxer

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

FormatMuxer adapts a Matroska-family muxer to format.Muxer. The zero value writes Matroska; NewFormatMuxer writes a profile through its own muxer.

func NewFormatMuxer

func NewFormatMuxer(format av.FormatID, open func(io.Writer) (TrackMuxer, error)) *FormatMuxer

NewFormatMuxer returns the adapter writing format through the muxer open returns for each output.

func (*FormatMuxer) Close

func (m *FormatMuxer) Close() error

func (*FormatMuxer) Format

func (m *FormatMuxer) Format() av.FormatID

func (*FormatMuxer) Open

func (m *FormatMuxer) Open(ctx context.Context, output format.Output, streams []av.Stream, _ format.OpenOptions) error

func (*FormatMuxer) Write

func (m *FormatMuxer) Write(ctx context.Context, packet *av.Packet, _ *format.WriteResult) error

type LacedPacket

type LacedPacket struct {
	TrackID                uint32
	TimeNS                 int64
	FrameDurationNS        int64
	ReferenceBlockTimeNS   []int64
	ReferencePriority      uint64
	DiscardPaddingNS       int64
	CodecState             []byte
	BlockAdditions         []BlockAddition
	UnknownClusterElements []UnknownElement
	Keyframe               bool
	Invisible              bool
	Discardable            bool
	Lacing                 LacingMode
	Frames                 [][]byte
}

LacedPacket writes multiple frames for one track into a single laced block. Frame timestamps are derived by demuxers from FrameDurationNS when set, or from the track default duration otherwise.

type LacingMode

type LacingMode int

LacingMode selects how multiple frames are packed into one laced block.

const (
	// LacingAuto uses fixed-size lacing for equal-sized frames and EBML lacing
	// otherwise.
	LacingAuto LacingMode = iota
	// LacingXiph writes Xiph lacing.
	LacingXiph
	// LacingEBML writes EBML lacing.
	LacingEBML
	// LacingFixed writes fixed-size lacing and requires equal-sized frames.
	LacingFixed
)

type Muxer

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

func NewMuxer

func NewMuxer(w io.Writer, opts MuxerOptions) (*Muxer, error)

func (*Muxer) AddTrack

func (m *Muxer) AddTrack(track Track) (uint32, error)

func (*Muxer) Close

func (m *Muxer) Close() error

func (*Muxer) WriteLacedPacket

func (m *Muxer) WriteLacedPacket(packet LacedPacket) error

WriteLacedPacket writes multiple frames for one track into one laced block. It uses SimpleBlock unless BlockGroup-only metadata is present. For timestamp-accurate SimpleBlock demuxing, the track should declare DefaultDurationNS. When FrameDurationNS is set, a BlockGroup is written and the demuxer returns that per-frame duration for each laced frame.

func (*Muxer) WritePacket

func (m *Muxer) WritePacket(packet Packet) error

type MuxerFactory

type MuxerFactory struct{}

func (MuxerFactory) NewMuxer

func (MuxerFactory) NewMuxer(ctx context.Context, id av.FormatID) (format.Muxer, error)

type MuxerOptions

type MuxerOptions struct {
	DocType                    string
	DocTypeVersion             uint64
	DocTypeReadVersion         uint64
	MuxingApp                  string
	WritingApp                 string
	Info                       SegmentInfo
	Attachments                []Attachment
	Chapters                   []ChapterEdition
	Tags                       []Tag
	UnknownSegmentElements     []UnknownElement
	UnknownTracksElements      []UnknownElement
	UnknownAttachmentsElements []UnknownElement
	UnknownChaptersElements    []UnknownElement
	UnknownTagsElements        []UnknownElement
	TimecodeScaleNS            int64
	ClusterMaxDurationNS       int64
	Streaming                  bool
	CueCapacity                int
	CuePolicy                  CuePolicy
	WriteCRC32                 bool
	ContentEncryptionKeys      []ContentEncryptionKey
	ContentEncryptionInitialIV []byte
}

type Packet

type Packet struct {
	TrackID                     uint32
	TimeNS                      int64
	DurationNS                  int64
	ReferenceBlockTimeNS        []int64
	ReferencePriority           uint64
	DiscardPaddingNS            int64
	CodecState                  []byte
	BlockAdditions              []BlockAddition
	Keyframe                    bool
	Invisible                   bool
	Discardable                 bool
	Data                        []byte
	ContentEncryptionPartitions []uint32
	UnknownClusterElements      []UnknownElement
}

func (*Packet) Reset

func (p *Packet) Reset()

type Prober

type Prober struct{}

func (Prober) Probe

type SeekEntry

type SeekEntry struct {
	ID       uint64
	Position uint64
}

type SegmentInfo

type SegmentInfo struct {
	SegmentUUID     []byte
	SegmentFilename string
	PrevUUID        []byte
	PrevFilename    string
	NextUUID        []byte
	NextFilename    string
	DurationNS      int64
	DurationSet     bool
	Title           string
	DateUTC         time.Time
	DateUTCSet      bool
	MuxingApp       string
	WritingApp      string
	UnknownElements []UnknownElement
}

type SimpleTag

type SimpleTag struct {
	Name            string
	Language        string
	LanguageBCP47   string
	Default         bool
	DefaultSet      bool
	String          string
	StringSet       bool
	Binary          []byte
	Children        []SimpleTag
	UnknownElements []UnknownElement
}

type Tag

type Tag struct {
	Target          TagTarget
	Simple          []SimpleTag
	UnknownElements []UnknownElement
}

type TagTarget

type TagTarget struct {
	TypeValue       uint64
	Type            string
	TrackUIDs       []uint64
	EditionUIDs     []uint64
	ChapterUIDs     []uint64
	AttachmentUIDs  []uint64
	UnknownElements []UnknownElement
}

type Track

type Track struct {
	ID                            uint32
	UID                           uint64
	Type                          TrackType
	Codec                         Codec
	Name                          string
	Language                      string
	LanguageBCP47                 string
	CodecName                     string
	TimebaseNum                   int64
	TimebaseDen                   int64
	DefaultDurationNS             int64
	DefaultDecodedFieldDurationNS int64
	TrackTimestampScale           float64
	TrackTimestampScaleSet        bool
	TrackOffsetNS                 int64
	TrackOffsetSet                bool
	MinCache                      uint64
	MinCacheSet                   bool
	MaxCache                      uint64
	MaxCacheSet                   bool
	CodecDecodeAll                bool
	CodecDecodeAllSet             bool
	CodecDelayNS                  int64
	SeekPreRollNS                 int64
	FlagEnabled                   bool
	FlagEnabledSet                bool
	FlagDefault                   bool
	FlagDefaultSet                bool
	FlagForced                    bool
	FlagForcedSet                 bool
	FlagHearingImpaired           bool
	FlagHearingImpairedSet        bool
	FlagVisualImpaired            bool
	FlagVisualImpairedSet         bool
	FlagTextDescriptions          bool
	FlagTextDescriptionsSet       bool
	FlagOriginal                  bool
	FlagOriginalSet               bool
	FlagCommentary                bool
	FlagCommentarySet             bool
	FlagLacing                    bool
	FlagLacingSet                 bool
	MaxBlockAdditionID            uint64
	BlockAdditionMappings         []BlockAdditionMapping
	TrackOverlays                 []uint64
	TrackTranslates               []TrackTranslate
	ContentEncodings              []ContentEncoding
	Audio                         AudioConfig
	Video                         VideoConfig
	UnknownElements               []UnknownElement

	CodecPrivate []byte
}

type TrackDemuxer

type TrackDemuxer interface {
	Tracks() []Track
	ReadPacket(*Packet) error
	SeekToTime(int64) error
}

TrackDemuxer is the packet demuxer the av adapter reads through: *Demuxer, or a profile's demuxer.

type TrackMuxer

type TrackMuxer interface {
	AddTrack(Track) (uint32, error)
	WritePacket(Packet) error
	Close() error
}

TrackMuxer is the packet muxer the av adapter writes through: *Muxer, or a profile's muxer, such as WebM's, that checks tracks against the profile.

type TrackTranslate

type TrackTranslate struct {
	TrackID     []byte
	Codec       uint64
	EditionUIDs []uint64
}

type TrackType

type TrackType int
const (
	TrackUnknown TrackType = iota
	TrackAudio
	TrackVideo
	TrackSubtitle
)

type UnknownElement

type UnknownElement struct {
	ID  uint64
	Raw []byte
}

type VideoColourConfig

type VideoColourConfig struct {
	MatrixCoefficients         int
	MatrixCoefficientsSet      bool
	BitsPerChannel             int
	BitsPerChannelSet          bool
	ChromaSubsamplingHorz      int
	ChromaSubsamplingHorzSet   bool
	ChromaSubsamplingVert      int
	ChromaSubsamplingVertSet   bool
	CbSubsamplingHorz          int
	CbSubsamplingHorzSet       bool
	CbSubsamplingVert          int
	CbSubsamplingVertSet       bool
	ChromaSitingHorz           int
	ChromaSitingHorzSet        bool
	ChromaSitingVert           int
	ChromaSitingVertSet        bool
	Range                      int
	RangeSet                   bool
	TransferCharacteristics    int
	TransferCharacteristicsSet bool
	Primaries                  int
	PrimariesSet               bool
	MaxCLL                     int
	MaxCLLSet                  bool
	MaxFALL                    int
	MaxFALLSet                 bool
	MasteringMetadata          VideoMasteringMetadataConfig
}

type VideoConfig

type VideoConfig struct {
	Width              int
	Height             int
	FlagInterlaced     int
	FlagInterlacedSet  bool
	FieldOrder         int
	FieldOrderSet      bool
	StereoMode         int
	StereoModeSet      bool
	AlphaMode          int
	AlphaModeSet       bool
	PixelCropBottom    int
	PixelCropTop       int
	PixelCropLeft      int
	PixelCropRight     int
	DisplayWidth       int
	DisplayHeight      int
	DisplayUnit        int
	AspectRatioType    int
	AspectRatioTypeSet bool
	Colour             VideoColourConfig
	Projection         VideoProjectionConfig
}

type VideoMasteringMetadataConfig

type VideoMasteringMetadataConfig struct {
	PrimaryRChromaticityX      float64
	PrimaryRChromaticityXSet   bool
	PrimaryRChromaticityY      float64
	PrimaryRChromaticityYSet   bool
	PrimaryGChromaticityX      float64
	PrimaryGChromaticityXSet   bool
	PrimaryGChromaticityY      float64
	PrimaryGChromaticityYSet   bool
	PrimaryBChromaticityX      float64
	PrimaryBChromaticityXSet   bool
	PrimaryBChromaticityY      float64
	PrimaryBChromaticityYSet   bool
	WhitePointChromaticityX    float64
	WhitePointChromaticityXSet bool
	WhitePointChromaticityY    float64
	WhitePointChromaticityYSet bool
	LuminanceMax               float64
	LuminanceMaxSet            bool
	LuminanceMin               float64
	LuminanceMinSet            bool
}

type VideoProjectionConfig

type VideoProjectionConfig struct {
	Set       bool
	Type      int
	Private   []byte
	PoseYaw   float64
	PosePitch float64
	PoseRoll  float64
}

Jump to

Keyboard shortcuts

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