Documentation
¶
Overview ¶
Package av is the transport-neutral media vocabulary every other package speaks: packets, frames, events, and streams, plus the identifiers (media, codec, format, protocol), rational timestamps, and the reference-counted payload buffers (Buffer, NewBuffer) every branch shares instead of copying. It depends on nothing in goav and changes least.
Index ¶
- Constants
- func EventQoSReport(event *Event) (lateness time.Duration, dropped bool, ok bool)
- func EventRateValue(event *Event) (float64, bool)
- func EventSegmentEnd(event *Event) (time.Duration, bool)
- func RescaleValue(value int64, from TimeBase, to TimeBase) (int64, bool)
- type AudioFrame
- type AudioGeometry
- type Buffer
- type BufferOwner
- type Clock
- type CodecID
- type CodecParameters
- type Duration
- type Epoch
- type Event
- type EventType
- type FormatID
- type Frame
- type MediaType
- type Metadata
- type Packet
- type Plane
- type ProtocolID
- type Stream
- type StreamID
- type StreamSelector
- type TimeBase
- type Timestamp
- type VideoFrame
- type VideoGeometry
Constants ¶
const ( MIMEOpus = "audio/opus" MIMEVP8 = "video/vp8" MIMEVP9 = "video/vp9" MIMEH264 = "video/h264" MIMEAV1 = "video/av1" )
The negotiated MIME type names RTP payload maps, SDP, and codec descriptors carry for the well-known codecs.
const ( SampleFormatS16 = "s16" SampleFormatF32 = "f32" PixelFormatGray8 = "gray8" // Planar 8-bit YUV formats. PixelFormatYUV420P, PixelFormatYUV422P, and // PixelFormatYUV444P alias the canonical I420/I422/I444 names (identical // 3-plane Y, U, V memory layout). PixelFormatI420 = "i420" PixelFormatYUV420P = PixelFormatI420 PixelFormatI422 = "i422" PixelFormatYUV422P = PixelFormatI422 PixelFormatI444 = "i444" PixelFormatYUV444P = PixelFormatI444 )
Sample and pixel format names used in CodecParameters, AudioFrame, and VideoFrame. Open strings: adapters may introduce more.
const MetadataAttachmentID = "attachment_id"
MetadataAttachmentID is the Event.Metadata key carrying a runtime branch attachment id on EventBranchAttached and EventBranchDetached.
const MetadataAttachmentName = "attachment_name"
MetadataAttachmentName is the Event.Metadata key carrying a runtime branch attachment name on EventBranchAttached and EventBranchDetached.
const MetadataBitrate = "bitrate_bps"
MetadataBitrate is the Event.Metadata key carrying a requested encoder bitrate as a decimal string in bits per second. It is the payload of EventBitrateChanged events.
const MetadataDestinationName = "destination_name"
MetadataDestinationName is the Event.Metadata key carrying the destination finalized by a destination lifecycle event.
const MetadataDetachDisposition = "detach_disposition"
MetadataDetachDisposition is the Event.Metadata key carrying how a detached branch finalized its destinations: "detach", "drain", or "abort".
const MetadataMediaType = "media_type"
MetadataMediaType is the Metadata key carrying a media kind as a string, the cold-path fallback when a typed MediaType field is unavailable.
const MetadataRate = "rate"
MetadataRate is the Event.Metadata key carrying a requested playback rate as a decimal string (1 = realtime). Build with RateMetadata, read with EventRateValue.
const MetadataSegmentEnd = "segment_end_ns"
MetadataSegmentEnd is the Event.Metadata key carrying a segment's exclusive end as decimal nanoseconds from the start of the media. It is the second payload of EventSegment events — the start rides Event.Timestamp — built with SegmentEndMetadata and read with EventSegmentEnd.
Variables ¶
This section is empty.
Functions ¶
func EventQoSReport ¶
EventQoSReport extracts the lateness and shed disposition from an EventQoS event. It reports ok=false when the event carries no positive decimal lateness payload — policy-refusal EventQoS events (Cause set, no payload) and malformed reports fail here, so a QoS policy never reacts to them.
func EventRateValue ¶
EventRateValue extracts the requested playback rate from an EventRate event. It prefers the typed Event.Rate field and falls back to MetadataRate for callers that populated Metadata directly. It reports false when neither carries a positive, finite rate.
func EventSegmentEnd ¶
EventSegmentEnd extracts the exclusive end bound from an EventSegment event. It prefers the typed Event.End field and falls back to MetadataSegmentEnd for callers that populated Metadata directly.
Types ¶
type AudioFrame ¶
type AudioFrame struct {
SampleRate int
Channels int
ChannelLayout string
SampleFormat string
Samples int
}
AudioFrame is the audio-specific header of a Frame: layout, sample format, and the per-channel sample count of the planes.
type AudioGeometry ¶
AudioGeometry is an audio layout (rate, channels, channel layout), the audio conversion target shape.
type Buffer ¶
type Buffer struct {
Bytes []byte
Owner BufferOwner
}
Buffer is one byte payload: Bytes, plus the reference count behind them when they came from a pool.
Payloads follow the rule GStreamer and libav use: bytes published on a graph are immutable. A Buffer without an Owner is ordinary memory its producer never writes again once published, so anyone may keep it. A Buffer with an Owner is pooled (NewBuffer) and shared by reference: a message lends it to each handler for the call, Retain keeps it past that call, Release returns the reference, and MakeWritable copies it before a write when anyone else holds it. Every branch of a fanout reads the same bytes; none is copied per edge.
func NewBuffer ¶
NewBuffer returns an n-byte pooled Buffer holding one reference, which the caller owns: write it, publish it, and Release it when done. Its bytes are not zeroed. The pool is process-wide and backed by the garbage collector, so a reference that is never released costs a reuse, never a leak.
func (*Buffer) MakeWritable ¶
func (b *Buffer) MakeWritable()
MakeWritable readies b for writing: unless b holds the only reference to pooled bytes, it copies them into a new pooled Buffer and releases b's old reference, so the write reaches no one else. b must be a reference the caller holds (its own Retain, NewBuffer, or Frame.Ref), never bytes a message lent it.
func (Buffer) MarshalJSON ¶
MarshalJSON writes the bytes, base64-encoded like a []byte; the owner is a runtime fact and stays out of the JSON.
func (*Buffer) Release ¶
func (b *Buffer) Release()
Release drops the caller's reference and clears b. Releasing bytes without an Owner just clears b.
func (*Buffer) Reset ¶
func (b *Buffer) Reset()
Reset clears b for reuse without releasing it. Bytes without an Owner keep their backing array as scratch capacity; pooled bytes are dropped, because once released the pool may hand them to someone else.
func (Buffer) Retain ¶
func (b Buffer) Retain()
Retain adds a reference for a copy of b the caller keeps past the call that lent it. Bytes without an Owner need none: Retain is a no-op for them.
func (*Buffer) UnmarshalJSON ¶
UnmarshalJSON reads bytes MarshalJSON wrote into ordinary memory.
type BufferOwner ¶
type BufferOwner interface {
Retain()
Release()
Refs() int
}
BufferOwner is the reference count behind a pooled Buffer: Retain adds a reference, Release drops one and recycles the bytes once the last is gone, and Refs reports how many are live. Methods are safe for concurrent use. NewBuffer's pool is one implementation; an adapter with memory of its own (a decoder's reference pictures, a mapped file) can supply another.
type Clock ¶
type Clock interface {
// Now reports the elapsed monotonic time since the clock's arbitrary,
// fixed origin. Only differences between readings are meaningful.
Now() time.Duration
// Sleep blocks until d has elapsed on this clock or ctx is done, returning
// ctx.Err() when interrupted and nil when the wait completed. A
// non-positive d returns immediately (still honouring an already-done ctx).
Sleep(ctx context.Context, d time.Duration) error
}
Clock is the monotonic time source used by paced sources, playout gates, and task timelines. Tests inject a fake so nothing sleeps for real.
Implementations must be safe for concurrent use.
func MonotonicClock ¶
func MonotonicClock() Clock
MonotonicClock returns the standard Clock: Now reads the process monotonic clock and Sleep waits on a timer, interrupted by ctx. This is the default a realtime pacer uses when no clock is injected.
type CodecID ¶
type CodecID string
CodecID names a codec. The type is an open string: external adapters introduce their own ids through the same registries and recipes as the well-known ones below.
const ( CodecUnknown CodecID = "" CodecOpus CodecID = "opus" CodecVorbis CodecID = "vorbis" CodecFLAC CodecID = "flac" CodecAAC CodecID = "aac" CodecVP8 CodecID = "vp8" CodecVP9 CodecID = "vp9" CodecH264 CodecID = "h264" CodecHEVC CodecID = "hevc" CodecAV1 CodecID = "av1" CodecPCM CodecID = "pcm" CodecTextUTF8 CodecID = "text_utf8" )
Well-known codec ids.
type CodecParameters ¶
type CodecParameters struct {
ID CodecID `json:"id,omitempty"`
Type MediaType `json:"type,omitempty"`
Profile string `json:"profile,omitempty"`
Level string `json:"level,omitempty"`
ClockRate uint32 `json:"clockRate,omitempty"`
SampleRate int `json:"sampleRate,omitempty"`
Channels int `json:"channels,omitempty"`
ChannelLayout string `json:"channelLayout,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
PixelFormat string `json:"pixelFormat,omitempty"`
SampleFormat string `json:"sampleFormat,omitempty"`
ExtraData Buffer `json:"extraData,omitzero"`
Attributes Metadata `json:"attributes,omitempty"`
}
CodecParameters are the codec-level facts a stream declares: identity, timing, audio/video geometry, formats, and codec-specific extradata. Decoders are configured from these; the planner reads them as shape facts.
type Duration ¶
Duration is a media time span: Value counted in Base units.
func DurationFromStdDuration ¶
DurationFromStdDuration converts a standard Go duration into a media duration.
func SamplesDuration ¶
SamplesDuration returns the media duration of a sample count at a sample rate (samples/sampleRate seconds), or the zero Duration when the rate is unknown.
type Epoch ¶
type Epoch uint64
Epoch is a monotonic configuration generation: it increments when a stream's codec parameters change mid-run, so consumers can tell which configuration a packet or frame belongs to.
type Event ¶
type Event struct {
Type EventType
StreamID StreamID
Epoch Epoch
At time.Time
Timestamp Timestamp
// Bitrate carries the target encoder bitrate in bits per second for
// EventBitrateChanged (avoiding stringly-typed Metadata allocations).
Bitrate int
// Rate carries the playback rate multiplier for EventRate.
Rate float64
// End carries the exclusive media end position for EventSegment.
End time.Duration
Stream *Stream
Codec *CodecParameters
Cause error
Reason string
Metadata Metadata
}
Event is one out-of-band signal: its type, the stream it concerns, and the typed payload fields the type documents (Stream, Codec, Timestamp, Bitrate, Rate, End, Cause, Metadata). Events ride the data path in order with the media.
type EventType ¶
type EventType string
EventType names an out-of-band signal riding the data path alongside packets and frames.
const ( // EventStreamAdded announces a stream the source discovered after it // opened: Event.Stream carries the full av.Stream and Event.StreamID its // id. Sources emit it mid-run, before the new stream's media, so the // runtime can attach branches to the stream without a rebuild. EventStreamAdded EventType = "stream_added" // EventStreamRemoved announces that the stream named by Event.StreamID // ended; branches attached to it can be detached. EventStreamRemoved EventType = "stream_removed" // EventAttachError reports a failed runtime reaction to a discovered // stream: a dynamic-stream rule branch that could not be attached or // detached. Cause carries the failure, Reason names the rule branch, and // StreamID is the discovered stream. EventAttachError EventType = "attach_error" // EventBranchAttached reports that task.Attach added a runtime branch // group. Metadata carries MetadataAttachmentID and MetadataAttachmentName. EventBranchAttached EventType = "branch_attached" // EventBranchFailed reports the first returned handler error in an // isolated branch. The durable branch snapshot retains Cause. EventBranchFailed EventType = "branch_failed" // EventBranchDetached reports that task.Detach removed a runtime branch // group. Metadata carries MetadataAttachmentID, MetadataAttachmentName, and // MetadataDetachDisposition. EventBranchDetached EventType = "branch_detached" // EventDestinationCommitted reports that a task or runtime branch // destination was committed. EventDestinationCommitted EventType = "destination_committed" // EventDestinationAborted reports that a task or runtime branch destination // was aborted. EventDestinationAborted EventType = "destination_aborted" // EventDestinationClosed reports a closed nontransactional destination // whose processing was abandoned. Partial external output may remain. EventDestinationClosed EventType = "destination_closed" // EventDestinationCommitError reports a failed destination finalization. EventDestinationCommitError EventType = "destination_commit_error" // EventCleanupError reports a node's failed finalization after its caller // timed out waiting for handling to stop. Reason and Metadata["node"] name // the node; Cause wraps the failure. This observer notification is best // effort. Graph and task Close also retain the error after reclamation, // even if their observer stream has already closed. EventCleanupError EventType = "cleanup_error" // EventCodecChanged announces that a stream's codec parameters changed // mid-run; Event.Codec carries the new parameters, and decoders reset to // them. EventCodecChanged EventType = "codec_changed" // EventDiscontinuity marks a timeline break (a seek landed, a receiver // reset): downstream decoders reset and consumers re-sync on it. EventDiscontinuity EventType = "discontinuity" // EventPacketLoss reports transport loss detected before the marked // position, typically from an RTP receiver's sequence tracking. EventPacketLoss EventType = "packet_loss" // EventKeyframeRequired asks the encoders on its path to produce a // keyframe (sync point) as soon as possible. EventKeyframeRequired EventType = "keyframe_required" // EventBackpressure reports sustained downstream pressure, surfaced so // adaptive sources can slow down. EventBackpressure EventType = "backpressure" // EventStats carries periodic diagnostic counters on Event.Metadata. EventStats EventType = "stats" // EventEndOfStream marks the natural end of the stream named by // Event.StreamID: downstream nodes flush and destinations finalize. EventEndOfStream EventType = "end_of_stream" // EventSeek asks a source to reposition to the media position carried in // Event.Timestamp (measured from the start of the media). It is delivered // out-of-band to a source's control seam, not routed downstream; the source // acknowledges by emitting EventDiscontinuity before the first message at // the new position. EventSeek EventType = "seek" // EventRate carries a task-wide playback-rate change (1 = realtime, 2 = 2x, // 0.5 = half; positive only) in Event.Metadata[MetadataRate]. Build with // RateMetadata and read with EventRateValue. EventRate EventType = "rate" // EventSegment asks a source to play [start, end) and end naturally. Start // rides Event.Timestamp; exclusive end rides Event.Metadata[MetadataSegmentEnd] // (SegmentEndMetadata / EventSegmentEnd). EventSegment EventType = "segment" // EventBitrateChanged asks encoders on its path to retarget bitrate without // restarting (Event.Metadata[MetadataBitrate] in bits/sec). EventBitrateChanged EventType = "bitrate_changed" // EventSelectActive asks a running Select stage to switch its active arm // to Event.StreamID. Select stages consume it; joins forward it unchanged. EventSelectActive EventType = "select_active" // EventQoS reports late or shed delivery at a playout, sync, or MaxLatency // gate on the task observer stream (Watch). Build metadata with QoSMetadata // and read with EventQoSReport; rate-limited per producer (~1/sec). EventQoS EventType = "qos" // EventTaskReady fires at most once on Watch when every initial sink has // received its first media message (packet or frame). Sinks attached at // runtime do not gate readiness. EventTaskReady EventType = "task_ready" // EventReconnect reports a live input reconnecting under goav.Reconnect. // Metadata carries "attempt"/"delay", or "state":"reconnected" once back. EventReconnect EventType = "reconnect" )
The event vocabulary. Each constant documents who emits it and what consumers do with it.
type FormatID ¶
type FormatID string
FormatID names a container or transport framing format. The type is an open string: external format adapters introduce their own ids.
const ( FormatUnknown FormatID = "" FormatWebRTC FormatID = "webrtc" FormatRTP FormatID = "rtp" FormatFLV FormatID = "flv" FormatOgg FormatID = "ogg" FormatIVF FormatID = "ivf" FormatAnnexB FormatID = "annexb" FormatMatroska FormatID = "matroska" FormatWebM FormatID = "webm" FormatMP4 FormatID = "mp4" )
Well-known format ids.
type Frame ¶
type Frame struct {
StreamID StreamID
CodecEpoch Epoch
Type MediaType
PTS Timestamp
Duration Duration
Video *VideoFrame
Audio *AudioFrame
Planes []Plane
Metadata Metadata
}
Frame is one decoded media unit: plane data plus exactly one of the Video or Audio headers describing it. Plane bytes are immutable once published and shared by reference, one reference per plane (see Buffer); keep a frame past the call that lent it with Ref.
func (*Frame) MakeWritable ¶
func (f *Frame) MakeWritable()
MakeWritable readies every plane for writing (see Buffer.MakeWritable). f must hold its references: a header from Ref, or one its producer filled.
func (*Frame) Ref ¶
Ref returns a new frame header holding its own references to f's payload, for keeping f past the call that lent it: the planes, the Video or Audio header, and the Metadata map are copied, and each plane buffer is retained; the bytes themselves are shared, not copied. Release it when done.
type MediaType ¶
type MediaType string
MediaType is the kind of media a stream, packet, or frame carries.
type Metadata ¶
Metadata is the open string-to-string side channel on streams, packets, frames, events, inputs, and destinations — cold-path facts only; typed fields carry everything the hot path reads.
func QoSMetadata ¶
QoSMetadata builds the event metadata that carries one QoS report: how far past due the message was at admit time and whether it was shed (dropped) or delivered late. It is the encoding half of EventQoS.
func RateMetadata ¶
RateMetadata builds the event metadata that carries a playback-rate change: MetadataRate holding the rate as a decimal string. It is the encoding half of EventRate, so control producers and sources agree on the wire form.
func SegmentEndMetadata ¶
SegmentEndMetadata builds the event metadata that carries a segment's exclusive end bound: MetadataSegmentEnd holding the position as decimal nanoseconds from the start of the media. It is the encoding half of EventSegment's end (the start rides Event.Timestamp like EventSeek).
type Packet ¶
type Packet struct {
StreamID StreamID
// Type is the typed media kind so drop/route decisions stay on the hot path
// without a Metadata map lookup. Producers should set it; Metadata is the
// cold-path fallback.
Type MediaType
CodecEpoch Epoch
Payload Buffer
PTS Timestamp
DTS Timestamp
Duration Duration
Keyframe bool
Corrupt bool
Discontinuous bool
LossBefore bool
Metadata Metadata
}
Packet is one encoded media unit: the payload bytes plus the stream, timing, keyframe, and integrity facts routing and muxing read. The payload is immutable once published and shared by reference (see Buffer); keep a packet past the call that lent it with Ref.
func (*Packet) Ref ¶
Ref returns a new packet header holding its own reference to p's payload, for keeping p past the call that lent it; the Metadata map is copied. Release it when done.
type Plane ¶
Plane is one raw-media plane: its bytes, the row stride, and the offset of the first sample within the buffer.
type ProtocolID ¶
type ProtocolID string
ProtocolID names how an input or output is reached: a file-like reader, a live transport, or an application-pushed custom source.
const ( ProtocolUnknown ProtocolID = "" ProtocolFile ProtocolID = "file" ProtocolRTP ProtocolID = "rtp" ProtocolWebRTC ProtocolID = "webrtc" ProtocolCustom ProtocolID = "custom" )
Well-known protocol ids.
type Stream ¶
type Stream struct {
ID StreamID `json:"id,omitempty"`
Index int `json:"index"`
Type MediaType `json:"type,omitempty"`
Codec CodecParameters `json:"codec,omitzero"`
TimeBase TimeBase `json:"timeBase,omitzero"`
Language string `json:"language,omitempty"`
Name string `json:"name,omitempty"`
Epoch Epoch `json:"epoch,omitempty"`
Metadata Metadata `json:"metadata,omitempty"`
}
Stream describes one media stream an input carries: identity, kind, codec parameters, timing, and labels. Probers and source providers produce streams; selectors match against them.
type StreamID ¶
type StreamID string
StreamID identifies one media stream within a task; packets, frames, and events carry it so routing never inspects payloads.
type StreamSelector ¶
type StreamSelector struct {
ID StreamID
Index int
UseIndex bool
Type MediaType
Codec CodecID
Name string
}
StreamSelector matches streams by any combination of id, probe index (UseIndex gates Index), media kind, codec, and name. Zero fields match anything.
type TimeBase ¶
TimeBase is the rational unit (Num/Den seconds) timestamp and duration values are measured in — 1/48000 for 48kHz audio, 1/90000 for RTP video.
func RTPTimeBase ¶
RTPTimeBase returns the timebase of an RTP clock rate (1/clockRate seconds), or the zero TimeBase when the rate is unknown.
func (TimeBase) FromDuration ¶
FromDuration converts a standard Go duration to a value in this timebase.
func (TimeBase) ToDuration ¶
ToDuration converts a value in this timebase to a standard Go duration.
type Timestamp ¶
Timestamp is a media position: Value counted in Base units. Convert with Rescale/ToDuration instead of mixing bases arithmetically.
func RTPToTimestamp ¶
RTPToTimestamp wraps a raw RTP timestamp value in its clock-rate timebase.
func TimestampFromStdDuration ¶
TimestampFromStdDuration converts elapsed time from zero into a timestamp.
type VideoFrame ¶
VideoFrame is the video-specific header of a Frame: geometry and pixel format of the planes.
type VideoGeometry ¶
VideoGeometry is a width/height pair, the video conversion target shape.