kolo-media se sitúa entre tus códecs y kolo-moq. Quien envía describe sus tracks en un catálogo, marca los frames con un solo reloj y los publica como objetos LOC (Low Overhead Media Container, draft-ietf-moq-loc-04). Quien recibe lee el catálogo, se suscribe a los tracks que puede decodificar y reproduce los frames a través de un jitter buffer, con el audio y el video sincronizados, siguiendo las actualizaciones del catálogo. Trabaja solo con frames ya codificados: la captura, los códecs y la salida se quedan en tu aplicación. Un broadcast también puede sellarse de extremo a extremo con secobj de kolo-moq, para que un relay lo reenvíe sin poder leerlo. El paquete de Go se llama kolomedia.
Un broadcast, del catálogo a la reproducción
El catálogo enumera los tracks. El receptor reproduce los que puede decodificar, y el audio y el video quedan sincronizados.
- Un broadcast es un namespace de kolo-moq. Su catálogo es un track con un grupo por cada versión, y enumera los demás tracks del broadcast.
- Cada track de audio o video es otro track del mismo namespace. Un solo Clock marca cada frame, y WriteFrame lo publica sin esperar a los suscriptores. Un número de prioridad menor se envía antes.
- Watch se suscribe al catálogo y Select elige un track de audio y uno de video que el receptor pueda decodificar. Una versión nueva del catálogo puede cambiar la elección.
- Cada track elegido entra en su propio jitter buffer de Playout, que reordena los frames, descarta los duplicados y los tardíos y fija un retardo a partir del jitter que mide, entre 100 ms y 400 ms por defecto.
- El audio marca el reloj y el video sigue el audio que de verdad se reprodujo, así que los dos quedan sincronizados. Next devuelve cada frame cuando le toca.
Instalación
go get github.com/ciranda-dev/kolo-mediaPara fijar esta versión, ejecuta go get github.com/ciranda-dev/kolo-media@v0.1.0. Es Go puro, sin cgo y sin nada que instalar, así que compila con CGO_ENABLED=0. Necesita Go 1.26 o más reciente. Depende de kolo-moq v0.1.0, que go get instala con ella.
Inicio rápido
Este programa publica un track de audio y lo ve en 127.0.0.1, con medios generados. Alice publica un broadcast con un track de audio y lo sirve, y un reloj marca sus frames, cada uno de 20 ms de silencio. Bob se conecta a ella y reproduce lo que su catálogo le ofrece: solo pide el códec PCMS16LE, así que Select elige el track de Alice.
package main
import (
"context"
"fmt"
"log"
"time"
koloid "github.com/ciranda-dev/kolo-id"
kolomedia "github.com/ciranda-dev/kolo-media"
kolomoq "github.com/ciranda-dev/kolo-moq"
kolosecure "github.com/ciranda-dev/kolo-secure"
)
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
alice, bob := must(koloid.Generate()), must(koloid.Generate())
// Alice publishes a broadcast with one audio track and serves it.
origin := must(kolomoq.NewOrigin(nil))
ns := kolomoq.Namespace{"room", "alice"}
broadcast := must(kolomedia.NewBroadcast(origin, ns))
defer broadcast.Close()
mic := must(broadcast.AddTrack(kolomedia.Track{
Name: "mic", Kind: kolomedia.Audio, Codec: kolomedia.PCMS16LE, Timescale: 48000,
SampleRate: 48000, Channels: 1, FrameDuration: 20 * time.Millisecond,
}, kolomedia.PackagerOptions{}))
ln := must(kolosecure.Listen(ctx, "127.0.0.1:0", alice, nil))
defer ln.Close()
go func() {
if conn, err := ln.Accept(ctx); err == nil {
if s, err := kolomoq.NewServer(ctx, conn, &kolomoq.Config{Origin: origin}); err == nil {
<-s.Done()
}
}
}()
// Her encoder would produce these frames: 20 ms of silence each.
clock := kolomedia.NewClock()
go func() {
for range time.Tick(20 * time.Millisecond) {
ts, err := clock.At(time.Now(), 48000)
if err != nil || mic.WriteFrame(kolomedia.Frame{Timestamp: ts, Data: make([]byte, 1920)}) != nil {
return
}
}
}()
// Bob dials alice and plays what her catalog offers him.
conn := must(kolosecure.Dial(ctx, ln.Addr().String(), bob, alice.PublicKey(), nil))
session := must(kolomoq.NewClient(ctx, conn, nil))
defer session.Close()
caps := kolomedia.Capabilities{Codecs: []kolomedia.Codec{kolomedia.PCMS16LE}}
watcher := must(kolomedia.Watch(ctx, session, ns, kolomedia.WatchOptions{Capabilities: caps}))
defer watcher.Close()
for range 5 {
frame, track, err := watcher.Next(ctx, kolomedia.Audio)
if err != nil {
log.Fatal(err)
}
fmt.Println("play", track.Name, len(frame.Data), "bytes")
}
fmt.Println("playout delay", watcher.Stats().Playout.Delay)
}Imprime:
play mic 1920 bytes
play mic 1920 bytes
play mic 1920 bytes
play mic 1920 bytes
play mic 1920 bytes
playout delay 100msEl repositorio también trae examples/publish, que ejecuta un relay y publica por él un tono generado y un track de video, y examples/watch, que ve ese broadcast e imprime cada segundo los frames, el nivel del tono y el desfase entre audio y video.
Referencia de la API
La referencia de la API se genera a partir del código Go y está en inglés.
Package kolomedia describes, packages, publishes and plays out the encoded audio and video of a Kolo broadcast on kolo-moq: a binary catalog, LOC objects (draft-ietf-moq-loc-04), a shared media clock, a receive-side playout with jitter buffers and A/V sync, rendition selection, and Broadcast and Watch to tie them to MoQ sessions. It never captures, encodes, decodes or renders, and it does not use cgo.
Experimental: the API may change before v1.0.0.
Constantes
const (
PropertyTimescale = 0x08
PropertyAudioLevel = 0x0C
PropertyVideoConfig = 0x0D
PropertyAudioConfig = 0x0F
PropertyTimestamp = 0x10
)LOC property types (draft-ietf-moq-loc-04). An even type carries a varint Value, an odd type Bytes.
const (
CatalogPriority = 28
AudioPriority = 48
VideoPriority = 68
)MoQ publisher priorities (lower is sent first): the catalog, then audio, then video, all ahead of a track at kolomoq.DefaultPriority.
const CatalogTrack = "catalog"CatalogTrack is the name of the track that carries a broadcast's catalog: one group per catalog version, with the encoded catalog as its only object.
const DefaultTimescale = 1_000_000DefaultTimescale is the LOC default: timestamps in microseconds since the Unix epoch.
const MediaGroupTimeout = 30 * time.SecondMediaGroupTimeout is the subgroup delivery timeout of media tracks: a group not sent 30 s after it ended is no use to a live subscriber and is dropped.
Variables
var (
// ErrInvalidFrame means a frame is empty, out of range or does not fit its track.
ErrInvalidFrame = errors.New("kolomedia: invalid frame")
// ErrInvalidTrack means a track description is not valid.
ErrInvalidTrack = errors.New("kolomedia: invalid track")
// ErrInvalidCatalog means a catalog is malformed, over a limit or not valid.
ErrInvalidCatalog = errors.New("kolomedia: invalid catalog")
// ErrCatalogFormat means an encoded catalog has an unknown format version.
ErrCatalogFormat = errors.New("kolomedia: unsupported catalog format")
// ErrInvalidTimescale means a timescale of zero.
ErrInvalidTimescale = errors.New("kolomedia: invalid timescale")
// ErrTimestampRange means a timestamp or duration does not fit the target unit.
ErrTimestampRange = errors.New("kolomedia: timestamp out of range")
// ErrTimestampOrder means a frame's timestamp is not after the previous frame's.
ErrTimestampOrder = errors.New("kolomedia: timestamp not after the previous frame")
// ErrNeedKeyframe means a video track was given a delta frame where a group must start: before
// its first keyframe, or after a failed TrackPublisher.WriteFrame.
ErrNeedKeyframe = errors.New("kolomedia: video track needs a keyframe")
// ErrMissingProperty means an object lacks a property its track requires.
ErrMissingProperty = errors.New("kolomedia: missing property")
// ErrDuplicateProperty means an object carries a property more than once.
ErrDuplicateProperty = errors.New("kolomedia: duplicate property")
// ErrMalformedProperty means a property has the wrong form or value, or does not belong to the track's kind.
ErrMalformedProperty = errors.New("kolomedia: malformed property")
// ErrPropertyMismatch means a property disagrees with the track's catalog entry.
ErrPropertyMismatch = errors.New("kolomedia: property does not match the catalog")
// ErrInvalidConfig means a playout configuration is not valid.
ErrInvalidConfig = errors.New("kolomedia: invalid configuration")
// ErrUnknownTrack means a track name the playout or broadcast does not have.
ErrUnknownTrack = errors.New("kolomedia: unknown track")
// ErrFrameTooLarge means a frame is larger than a whole track buffer, or its object is larger than
// the origin's MaxObjectSize (the error then also wraps kolomoq.ErrObjectTooLarge).
ErrFrameTooLarge = errors.New("kolomedia: frame too large")
// ErrClosed means the playout, broadcast, track publisher or watcher was closed.
ErrClosed = errors.New("kolomedia: closed")
// ErrNoMatch means no track of the catalog fits the receiver's capabilities.
ErrNoMatch = errors.New("kolomedia: no track matches the capabilities")
// ErrBroadcastEnded means the broadcast's catalog track ended: the publisher ended it, or a relay
// ended it with a kolomoq.PublishDoneError, which the error then wraps.
ErrBroadcastEnded = errors.New("kolomedia: broadcast ended")
// ErrSessionEnded means the MoQ session ended; the error wraps the session's reason when it has one.
ErrSessionEnded = errors.New("kolomedia: session ended")
// ErrTrackEnded means a track the watcher was playing ended: the publisher ended it, or a relay
// ended it with a kolomoq.PublishDoneError, which the error then wraps.
ErrTrackEnded = errors.New("kolomedia: track ended")
// ErrBroadcastNotFound means the peer has no broadcast under the namespace; the error wraps the kolomoq request error.
ErrBroadcastNotFound = errors.New("kolomedia: broadcast not found")
// ErrBroadcastExists means the origin already has a broadcast under the namespace; the error wraps kolomoq.ErrTrackExists.
ErrBroadcastExists = errors.New("kolomedia: broadcast already exists")
// ErrTooManyTracks means the origin has no room for another track; the error wraps kolomoq.ErrTooManyTracks.
ErrTooManyTracks = errors.New("kolomedia: too many tracks")
)Funciones
func FromDuration
func FromDuration(d time.Duration, timescale uint64) (uint64, error)FromDuration converts a non-negative duration to a timestamp in the given timescale.
func Rescale
func Rescale(ts, from, to uint64) (uint64, error)Rescale converts a timestamp from one timescale to another, rounding to the nearest unit.
func ToDuration
func ToDuration(ts, timescale uint64) (time.Duration, error)ToDuration converts a timestamp in the given timescale to a duration.
Tipos
type AudioLevel
type AudioLevel struct {
// Voice reports voice activity.
Voice bool
// Level is the magnitude in -dBov, from 0 (loudest) to 127 (silence).
Level uint8
}AudioLevel is the level of an audio frame as RFC 6464 defines it.
type Broadcast
type Broadcast struct {
// contains filtered or unexported fields
}Broadcast publishes the tracks of one broadcast and its catalog under a namespace of an origin. Its methods are safe for concurrent use.
func NewBroadcast
func NewBroadcast(origin *kolomoq.Origin, ns kolomoq.Namespace) (*Broadcast, error)NewBroadcast creates the catalog track under ns in origin and publishes an empty catalog, version 0. Catalog versions are the catalog track's group IDs.
func NewSecureBroadcast
func NewSecureBroadcast(origin *kolomoq.Origin, s *secobj.Sender) (*Broadcast, error)NewSecureBroadcast is NewBroadcast with every object, the catalog included, sealed by s under s.Namespace(). Protected audio tracks carry no AUDIO_LEVEL.
func (Broadcast) AddTrack
func (b *Broadcast) AddTrack(t Track, opts PackagerOptions) (*TrackPublisher, error)AddTrack adds t to the broadcast and publishes the new catalog. A zero t.Priority takes AudioPriority or VideoPriority. The catalog must fit the origin's MaxObjectSize, else the error wraps ErrInvalidCatalog and kolomoq.ErrObjectTooLarge and the track is not added.
func (Broadcast) Catalog
func (b *Broadcast) Catalog() *CatalogCatalog returns the catalog last published.
func (Broadcast) Close
func (b *Broadcast) Close() errorClose ends every track and the catalog; subscribers see the broadcast end.
func (Broadcast) RemoveTrack
func (b *Broadcast) RemoveTrack(name string) errorRemoveTrack removes the named track, publishes the new catalog and ends the track for its subscribers.
type Capabilities
type Capabilities struct {
// Codecs lists the codecs the receiver decodes. Without an audio or video codec, that kind is not selected.
Codecs []Codec
// MaxWidth, MaxHeight and MaxFrameRate bound video tracks.
MaxWidth uint32
MaxHeight uint32
MaxFrameRate float64
// MaxBitrate bounds each selected track. A track of unknown bitrate passes.
MaxBitrate uint64
// VideoGroup, if set, limits video to the tracks of this rendition group.
VideoGroup string
}Capabilities describes what a receiver can decode. A zero limit means no limit.
type Catalog
type Catalog struct {
Version uint64
Tracks []Track
}Catalog describes one broadcast. Version increases with every change.
func ParseCatalog
func ParseCatalog(b []byte, lim CatalogLimits) (*Catalog, error)ParseCatalog decodes and validates an encoded catalog. It accepts only the canonical encoding, never panics and allocates in proportion to len(b).
func (Catalog) MarshalBinary
func (c *Catalog) MarshalBinary() ([]byte, error)MarshalBinary validates the catalog against the default limits and returns its canonical encoding.
type CatalogLimits
type CatalogLimits struct {
// MaxTracks defaults to 1024, the renditions per broadcast a player keeps.
MaxTracks int
// MaxNameLen bounds track and group names in bytes. It defaults to 4096, the MoQ bound on a full track name.
MaxNameLen int
// MaxConfigLen defaults to 65508, the largest config that fits one object property.
MaxConfigLen int
}CatalogLimits bounds what ParseCatalog accepts. A field outside 1 to its default takes the default, so whatever ParseCatalog accepts, MarshalBinary encodes again.
type Clock
type Clock struct {
// contains filtered or unexported fields
}Clock gives the tracks of one sender one time base: Unix time read once by NewClock, then advanced by the monotonic clock. Use NewClock; a Clock is safe for concurrent use.
func NewClock
func NewClock() *ClockNewClock returns a clock that starts now.
func (Clock) After
func (c *Clock) After(d time.Duration, timescale uint64) (uint64, error)After returns the timestamp of the instant d after the clock's start in the given timescale.
func (Clock) At
func (c *Clock) At(t time.Time, timescale uint64) (uint64, error)At returns the timestamp of capture instant t in the given timescale.
func (Clock) Start
func (c *Clock) Start() time.TimeStart returns the instant the clock was made.
type Codec
type Codec stringCodec names the encoding of a track's frames.
const (
Opus Codec = "opus"
PCMS16LE Codec = "pcm-s16le"
VP8 Codec = "vp8"
VP9 Codec = "vp9"
)Supported codecs.
type Frame
type Frame struct {
// Timestamp is the capture time in the track's timescale.
Timestamp uint64
// Duration is the frame's length in the track's timescale, 0 if unknown.
Duration uint64
// Keyframe marks a video frame that decodes without earlier frames. Every audio frame is one.
Keyframe bool
// AudioLevel is the optional level of an audio frame.
AudioLevel *AudioLevel
// Data is the codec's frame as is. It must not be empty.
Data []byte
}Frame is one encoded audio or video frame of a track, in decode order.
type Kind
type Kind uint8Kind is the media kind of a track.
const (
Audio Kind = 1
Video Kind = 2
)Track kinds.
func (Kind) String
func (k Kind) String() stringString returns "audio", "video" or "unknown".
type Object
type Object struct {
Group uint64
ID uint64
Properties []Property
Payload []byte
}Object is a frame packaged for MoQ: its place in the track, its properties in ascending type order and its payload. Payload and Bytes share memory with the frame and track; do not modify them.
type Packager
type Packager struct {
// contains filtered or unexported fields
}Packager turns the frames of one track into LOC objects and decides the group boundaries: a video track starts a group at each keyframe, an audio track per frame or per AudioGroupDuration. A Packager is not safe for concurrent use.
func NewPackager
func NewPackager(t Track, opts PackagerOptions) (*Packager, error)NewPackager returns a Packager for track t, which must be valid.
func (Packager) Pack
func (p *Packager) Pack(f Frame) (Object, error)Pack returns the object for the next frame. Timestamps must increase and a video track must start with a keyframe.
type PackagerOptions
type PackagerOptions struct {
// AudioGroupDuration starts a new audio group once the current one spans this long.
// Zero puts every audio frame in its own group.
AudioGroupDuration time.Duration
}PackagerOptions configures a Packager.
type Playout
type Playout struct {
// contains filtered or unexported fields
}Playout buffers the received frames of one broadcast and releases each when it is due, keeping the tracks in sync; video follows the audio actually played. It is safe for concurrent use.
func NewPlayout
func NewPlayout(tracks []Track, cfg PlayoutConfig) (*Playout, error)NewPlayout returns a Playout for the tracks of one broadcast, which share one time base. At most one track may be audio: it paces the others.
func (Playout) Close
func (p *Playout) Close() errorClose drops every buffered frame and makes blocked and later calls return ErrClosed.
func (Playout) Next
func (p *Playout) Next(ctx context.Context, track string) (Frame, error)Next returns the next frame of the named track when it is due, blocking until then. It returns ctx.Err() if ctx ends first and ErrClosed once the Playout is closed.
func (Playout) Push
func (p *Playout) Push(track string, f Frame, arrival time.Time) errorPush copies a received frame of the named track into its buffer; arrival is when it was received, the zero time meaning now. Dropped frames are counted in Stats, not reported as errors.
func (Playout) SetOutputLatency
func (p *Playout) SetOutputLatency(track string, d time.Duration) errorSetOutputLatency reports how long the application holds frames of the named track after Next, such as an audio device buffer. The other tracks are delayed to match.
func (Playout) Stats
func (p *Playout) Stats() PlayoutStatsStats returns a snapshot of the delay and the counters of every track.
type PlayoutConfig
type PlayoutConfig struct {
// MinDelay is the least playout delay, 100 ms by default: the jitter allowance of an interactive call.
MinDelay time.Duration
// MaxDelay caps the delay, 400 ms (a Wi-Fi retransmission burst) or MinDelay if larger by default.
MaxDelay time.Duration
// MaxBehind is how late past its due time a frame may still play, 50 ms by default. Later audio is
// dropped; late video jumps to its newest due keyframe, or plays at once if there is none.
MaxBehind time.Duration
// MaxFrames bounds the frames buffered per track, 8192 by default.
MaxFrames int
// MaxBytes bounds the frame data buffered per track, 16 MiB by default.
MaxBytes int
// OnKeyframeNeeded, if set, is called once when a video track drops a delta frame while it waits
// for a keyframe, at start or after a gap. It runs on the goroutine calling Next and must not block.
OnKeyframeNeeded func(track string)
}PlayoutConfig configures a Playout. A zero field takes its default.
type PlayoutStats
type PlayoutStats struct {
// Delay is the current playout delay.
Delay time.Duration
// Jitter is the measured 95th percentile of arrival lateness.
Jitter time.Duration
// Tracks holds the counters of each track by name.
Tracks map[string]TrackStats
}PlayoutStats is a snapshot of a Playout.
type Property
type Property struct {
Type uint64
Value uint64
Bytes []byte
}Property is one MoQ object property: Value when Type is even, Bytes when Type is odd.
type PropertyError
type PropertyError struct {
Type uint64
Err error
}PropertyError reports a malformed, missing, duplicate or mismatched LOC property of an object.
func (PropertyError) Error
func (e *PropertyError) Error() stringError returns the message with the property type in hex.
func (PropertyError) Unwrap
func (e *PropertyError) Unwrap() errorUnwrap returns the sentinel error.
type Selection
type Selection struct {
Audio *Track
Video *Track
}Selection holds the tracks to subscribe to. A kind with no matching track is nil.
func Select
func Select(c *Catalog, caps Capabilities) (Selection, error)Select picks at most one audio and one video track of c that fit caps, preferring the lowest Priority number, then the highest quality, then catalog order. It returns ErrNoMatch if it picks nothing.
type Track
type Track struct {
// Name is the MoQ track name: not empty, unique in the catalog and not CatalogTrack.
Name string
// Kind is Audio or Video and must match the codec.
Kind Kind
// Codec is one of the supported codecs.
Codec Codec
// Timescale is the number of timestamp units per second, usually DefaultTimescale.
Timescale uint64
// Priority is the MoQ publisher priority: a lower number is sent first.
Priority uint8
// Group names a rendition group: tracks with the same non-empty Group are alternatives of one source.
Group string
// Config is the optional codec configuration a decoder needs.
Config []byte
// Bitrate is in bits per second, 0 if unknown.
Bitrate uint64
// SampleRate, Channels and FrameDuration describe an audio track and are required for one.
SampleRate uint32
Channels uint8
FrameDuration time.Duration
// Width and Height in pixels are required for a video track; FrameRate in frames per second is 0 if unknown.
Width uint32
Height uint32
FrameRate float64
}Track describes one track of a broadcast.
type TrackPublisher
type TrackPublisher struct {
// contains filtered or unexported fields
}TrackPublisher publishes the frames of one track of a Broadcast. Its methods are safe for concurrent use.
func (TrackPublisher) Close
func (p *TrackPublisher) Close() errorClose removes the track from its broadcast, as Broadcast.RemoveTrack. Closing it again, or after the broadcast closed, does nothing.
func (TrackPublisher) KeyframeRequests
func (p *TrackPublisher) KeyframeRequests() <-chan struct{}KeyframeRequests receives when a watcher asks, with WatchOptions.RequestKeyframes, for a new group. The next frame written must then be a keyframe. Signals merge. Answer with at most one keyframe a second: watchers add up.
func (TrackPublisher) Track
func (p *TrackPublisher) Track() TrackTrack returns the track's description as published in the catalog.
func (TrackPublisher) WriteFrame
func (p *TrackPublisher) WriteFrame(f Frame) errorWriteFrame packages f and publishes it, starting a new group where the Packager does. It never waits for subscribers. A failed write leaves only a new group for the next frame, which on a video track must be a keyframe (ErrNeedKeyframe). On a protected broadcast f.AudioLevel is checked and dropped, and the catalog is published again under each new key; a failure there is not the frame's error.
type TrackStats
type TrackStats struct {
// Received counts the valid frames pushed.
Received uint64
// Played counts the frames returned by Next.
Played uint64
// Late counts frames dropped for being older than a frame already played or skipped.
Late uint64
// Duplicate counts frames dropped for a timestamp already buffered or just played.
Duplicate uint64
// Ahead counts frames dropped for arriving more than 2 s earlier than the reference allows.
Ahead uint64
// Overflow counts frames dropped because the buffer was over MaxFrames or MaxBytes.
Overflow uint64
// Skipped counts frames dropped for being more than MaxBehind late (skip to live).
Skipped uint64
// NoKeyframe counts video frames dropped while waiting for a keyframe.
NoKeyframe uint64
// Buffered is the number of buffered frames.
Buffered int
// BufferedBytes is the size of the buffered frames' data.
BufferedBytes int
// WaitingKeyframe reports a video track that needs a keyframe before it can play again.
WaitingKeyframe bool
}TrackStats counts the frames of one track.
type TrackWatchStats
type TrackWatchStats struct {
// Track is the name of the track played, empty if none.
Track string
// Subscriptions counts the subscriptions started for this kind, switches and restarts included.
Subscriptions uint64
// Gaps counts video groups cut short because an object was missing or malformed.
Gaps uint64
// Malformed counts objects that failed Unpack or did not fit the playout.
Malformed uint64
// Dropped counts groups the transport dropped because the reader fell behind.
Dropped uint64
// NoKey counts objects dropped because their key did not arrive in time.
NoKey uint64
// Retired counts objects under a key already retired: later than Retain after a newer key, or
// under a Key ID older than the keys held.
Retired uint64
// Unauthenticated counts objects that failed authentication, were not protected or were replays.
Unauthenticated uint64
// KeyframeRequests counts the requests for a new group sent for this kind.
KeyframeRequests uint64
// Err is why the last subscription ended, or nil while it runs. Once it ended, Next for its kind
// blocks until a catalog update lists the track again or selects another, unless the catalog in
// use still lists it: then it subscribes again at once, under the same catalog only once.
Err error
}TrackWatchStats describes the subscription of one kind.
type Unpackager
type Unpackager struct {
// contains filtered or unexported fields
}Unpackager turns the LOC objects of one track back into frames. It is safe for concurrent use.
func NewUnpackager
func NewUnpackager(t Track) (*Unpackager, error)NewUnpackager returns an Unpackager for track t, which must be valid.
func (Unpackager) Unpack
func (u *Unpackager) Unpack(id uint64, props []Property, payload []byte) (Frame, error)Unpack returns the frame in the object with the given ID in its group; Data is the payload itself and Duration comes from the catalog. Unknown property types are ignored.
type WatchOptions
type WatchOptions struct {
// Capabilities chooses the tracks to play, as in Select; with no codecs nothing plays.
Capabilities Capabilities
// Playout configures the playout; zero fields take their defaults.
Playout PlayoutConfig
// CatalogLimits bounds each received catalog; zero fields take their defaults.
CatalogLimits CatalogLimits
// Keys, if set, opens every object with its sender's key, drops objects without one, and
// refuses a session that neither owns the namespace nor is a listed relay. Each subscription
// opens through its own secobj.Opener, so several watches can share one Keyring.
Keys *secobj.Keyring
// RequestKeyframes asks the publisher for a new group, which starts with a keyframe, when the video track
// waits for one, lost the rest of a group, or gets no frame for 500 ms. Requests are bounded: a request for
// silence doubles the silence the next needs, and an unanswered one is repeated after 1, 2, 4 and 8 s, then
// dropped until a frame plays. The publisher must serve it (TrackPublisher.KeyframeRequests). Off by default.
RequestKeyframes bool
}WatchOptions configures Watch.
type WatchStats
type WatchStats struct {
// Playout holds the playout's counters, with the tracks named "audio" and "video".
Playout PlayoutStats
// Catalog is the version of the catalog in use; BadCatalogs counts catalog objects that were ignored.
Catalog uint64
BadCatalogs uint64
Audio TrackWatchStats
Video TrackWatchStats
}WatchStats is a snapshot of a Watcher.
type Watcher
type Watcher struct {
// contains filtered or unexported fields
}Watcher plays one broadcast received over a MoQ session. Its methods are safe for concurrent use.
func Watch
func Watch(ctx context.Context, s *kolomoq.Session, ns kolomoq.Namespace, opts WatchOptions) (*Watcher, error)Watch subscribes to the catalog of the broadcast under ns, plays the tracks Select picks and follows catalog updates. It returns once the first catalog arrived, even if it selects nothing yet, and fails if the catalog selects tracks and none of their subscriptions starts. The session stays the caller's. With opts.Keys, Watch fails with an error wrapping secobj.ErrWrongSession unless the session's peer owns ns or is a listed relay, and returns once a catalog that opens arrives.
func (Watcher) Catalog
func (w *Watcher) Catalog() *CatalogCatalog returns a copy of the catalog in use.
func (Watcher) Close
func (w *Watcher) Close() errorClose stops every subscription and goroutine of the watch; blocked and later Next calls return ErrClosed.
func (Watcher) Next
func (w *Watcher) Next(ctx context.Context, kind Kind) (Frame, Track, error)Next returns the next frame of the given kind when it is due, and the track it belongs to, whose Config the caller must not modify. It blocks while no track of that kind is selected. After the watch ended it returns an error wrapping ErrBroadcastEnded or ErrSessionEnded, or ErrClosed.
func (Watcher) Stats
func (w *Watcher) Stats() WatchStatsStats returns a snapshot of the playout and the subscriptions.
func (Watcher) Tracks
func (w *Watcher) Tracks() SelectionTracks returns the tracks being played.
Conviene saber
Cómo viaja un frame
- La aplicación captura y codifica un frame.
Clocklo marca yWriteFramelo empaqueta como un objeto LOC en un grupo.- kolo-moq publica el objeto en el track, y un relay lo reenvía.
Watchlo recibe, restablece el orden dentro de un grupo de video y se lo entrega alPlayout.Nextlo devuelve cuando le toca, con el audio y el video sincronizados.- La aplicación lo decodifica y lo muestra.
Con NewSecureBroadcast, el objeto se sella antes del paso 3, y Watch lo abre antes del paso 4. Consulta Medios protegidos.
Publicar
NewBroadcast(origin, ns)crea el track de catálogo bajonsen unOriginde kolo-moq y publica la versión 0 del catálogo.AddTrack(track, opts)añade un track y publica la siguiente versión del catálogo,RemoveTrack(name)quita uno,Catalogdevuelve el catálogo actual yClosecierra todos los tracks y el catálogo.TrackPublisher.WriteFrame(frame)empaqueta el frame y lo publica sin esperar a los suscriptores. kolo-moq encola por suscriptor y descarta grupos enteros para uno lento.Closequita el track.- Marca todos los tracks con un solo
Clock:clock.At(time.Now(), timescale)para un instante de captura yclock.After(d, timescale)para un desplazamiento. Las marcas de tiempo deben crecer estrictamente en cada track, oWriteFramedevuelveErrTimestampOrder. - Un track de video empieza con un keyframe. Tras una escritura fallida, el frame siguiente empieza un grupo nuevo, y en un track de video tiene que ser un keyframe (
ErrNeedKeyframe). TrackPublisher.KeyframeRequestses un canal que se dispara cuando un observador pide un grupo nuevo (mira Ver). El publicador escribe entonces un keyframe, que empieza un grupo nuevo, así que quien se une tarde o un observador que perdió un grupo recibe una imagen en un tiempo de ida y vuelta en lugar de esperar al siguiente grupo. Un track por el que nadie pregunta nunca se dispara. Todos los que miran piden, así que responde con un keyframe por segundo como mucho.- Un
Track.Priorityen cero tomaAudioPriority(48) oVideoPriority(68), y el catálogo usaCatalogPriority(28). Un número menor se envía antes, y los tres van por delante de un track de kolo-moq con la prioridad por defecto, 128. AddTrackdevuelve un error que envuelveErrInvalidCatalogykolomoq.ErrObjectTooLargecuando el catálogo no cabe en elMaxObjectSizedel origin. El catálogo anterior sigue siendo el actual.- La sesión de kolo-moq y el relay siguen siendo tuyos:
Broadcastsolo escribe en elOrigin. NewSecureBroadcast(origin, sender)esNewBroadcastcon cada objeto, el catálogo incluido, sellado por unsecobj.Senderde kolo-moq. Consulta Medios protegidos.
Ver
Watch(ctx, session, ns, opts)se suscribe al catálogo, espera la primera versión, reproduce los tracks queSelectelige paraopts.Capabilitiesy sigue las actualizaciones del catálogo. Un track que se va se detiene, y se pasa a uno mejor empezando en un keyframe.Next(ctx, kind)devuelve el siguiente frame que toca deAudiooVideoy suTrack. Se bloquea mientras no haya un track de ese tipo elegido.CatalogyTracksdevuelven una copia del catálogo en uso y de la selección.Statsinforma del playout, de la versión del catálogo, de los catálogos ignorados y, por tipo, de las suscripciones, los grupos de video cortados, los objetos mal formados, los grupos descartados y por qué terminó la última suscripción.Closedetiene la visualización y deja la sesión utilizable. La sesión sigue siendo tuya.ErrBroadcastEndedsignifica que el publicador cerró el catálogo, o que un relay lo cerró con un estado PUBLISH_DONE. Un error que envuelveErrSessionEndedsignifica que la sesión terminó, yErrClosedsigue aClose.Watchfalla si el catálogo elige tracks y ninguna de sus suscripciones arranca.- Las suscripciones de medios piden a kolo-moq un timeout de entrega de objetos de
MaxDelaymásMaxBehind, porque un frame posterior ya no se puede reproducir. El audio se suscribe desde el siguiente objeto, y el catálogo y el video desde el grupo actual, así que quien llega tarde empieza en un keyframe. WatchOptions.RequestKeyframeshace que una visualización pida al publicador un grupo nuevo, que empieza con un keyframe, cuando su track de video lo espera (al empezar, o tras frames que no pudo usar), pierde el resto de un grupo o no entrega ningún frame durante 500 ms, medianteSubscription.RequestNewGroupde kolo-moq, que un relay reenvía al publicador. Las peticiones están acotadas, así que a un track que solo está quieto (una pantalla compartida fija, una cámara en pausa) no se le pide para siempre: cada petición hecha por silencio duplica el silencio que necesita la siguiente (500 ms, 1 s, 2 s, 4 s, 8 s), y tras cinco de ellas el silencio deja de contar hasta que llegan 30 frames seguidos o se informa de una pérdida. Una petición que no obtiene ningún frame reproducible se repite tras 1 s, 2 s, 4 s y 8 s, y cinco peticiones sin respuesta seguidas detienen las peticiones hasta que se reproduce un frame. Una visualización no pide mientras el catálogo no lista ningún track de video.Stats().Video.KeyframeRequestscuenta las peticiones enviadas. Viene desactivado, porque un publicador que no atiende la petición recibe un REQUEST_UPDATE que no le sirve.
Piezas sueltas
Funcionan sin kolo-moq.
CatalogyTrackdescriben un broadcast.MarshalBinaryvalida y codifica.ParseCatalog(b, limits)decodifica, acepta solo la codificación canónica y nunca entra en pánico. Los códecs sonOpus,PCMS16LE,VP8yVP9.Clockda a todos los tracks de quien envía una sola base de tiempo.Rescale,ToDurationyFromDurationconvierten entre escalas de tiempo, redondeando a la unidad más cercana e informando del desbordamiento conErrTimestampRange.NewPackager(track, opts)yPack(frame)devuelven unObject: grupo, ID de objeto, propiedades en orden ascendente de tipo y los datos del frame como payload.NewUnpackager(track)yUnpack(id, properties, payload)devuelven el frame, o un*PropertyError.NewPlayout(tracks, config)reproduce los tracks de un broadcast, como máximo uno de ellos de audio.Push(track, frame, arrival)copia un frame recibido en su búfer, yNext(ctx, track)se bloquea hasta que toca el siguiente frame.SetOutputLatencyretrasa los demás tracks según el búfer de un dispositivo.Statscuenta los frames reproducidos, tardíos, duplicados, adelantados, desbordados, saltados y sin keyframe.Closedespierta conErrClosedcadaNextbloqueado.Select(catalog, capabilities)elige un track de audio y uno de video que el receptor decodifica dentro de sus límites de tamaño, de frecuencia de frames y de bitrate: primero el número de prioridad más bajo, luego la mayor calidad y luego el orden del catálogo. DevuelveErrNoMatchcuando nada encaja.
Reproducción
- La referencia es la llegada más temprana menos el tiempo del medio, en los últimos 2 s de llegadas, entre todos los tracks. Un frame marcado con T le toca en la referencia más T más el retardo.
- El retardo es el percentil 95 de la tardanza medida en la misma ventana, entre
MinDelayyMaxDelay. Los valores atípicos de menos del 5% no lo suben. - El video también espera el retraso del último frame de audio reproducido, así que el audio marca el reloj y el video lo sigue.
- El audio que llega con más de
MaxBehindde retraso se descarta (Skipped). El video tardío salta a su keyframe más reciente que ya toca, o reproduce de golpe sus frames tardíos si no hay ninguno. - Un frame que llega con más de 2 s de adelanto sobre lo que permite la referencia se descarta (
Ahead). Un primer frame marcado muy adelante no se distingue de uno honesto: se convierte en la referencia, y los frames que siguen se descartan comoLatehasta que pasa la ventana de 2 s, así que el track queda en silencio de 2 a 3 s y luego suena. Solo afecta al track del propio emisor. Un frame más antiguo que uno ya reproducido se descarta comoLate, y una marca de tiempo repetida comoDuplicate. Si durante 2 s solo llegan frames más antiguos, se toma el último frame reproducido como el erróneo y los frames más antiguos se reproducen, así que, tras un corte de entrega que se reanuda desde un punto anterior, un frame puede reproducirse después de uno posterior. Un búfer lleno expulsa su frame más antiguo (Overflow). - Un track de video espera un keyframe al empezar y después de expulsar un frame, descarta entretanto los frames delta (
NoKeyframe) y llama una vez aOnKeyframeNeeded, para que la aplicación pueda pedir un grupo nuevo al publicador.
Formatos
- Un broadcast es un namespace de kolo-moq. Su catálogo es el track llamado
catalog(CatalogTrack, un nombre reservado): un grupo por cada versión del catálogo, cuyo ID de grupo es la versión, con el catálogo codificado como objeto 0. Una versión nueva repite el catálogo entero, sin actualizaciones delta. Cada track de medios es el track que nombra suTrack.Nameen el mismo namespace. - La codificación del catálogo es canónica, sobre kolo-codec: un catálogo tiene exactamente una codificación. Byte de formato 1, luego la versión y el número de tracks, luego cada track con su nombre, tipo, códec, escala de tiempo, prioridad, grupo, config y bitrate, y los parámetros de audio o de video.
ParseCatalogrechaza los varints no mínimos, los bytes sobrantes, los tipos y códecs desconocidos, un byte de formato desconocido (ErrCatalogFormat) y cualquier campo que el tipo no use. - Los tracks con el mismo
Groupno vacío son alternativas de una misma fuente, de un tipo y una escala de tiempo, y quien recibe puede cambiar entre ellos en los límites de grupo. Cambiar la config del códec de un track implica una versión nueva del catálogo. - Los objetos siguen draft-ietf-moq-loc-04, y el payload es el frame del códec tal cual. Las propiedades son TIMESTAMP, TIMESCALE (cuando la escala de tiempo no es 1000000), AUDIO_LEVEL (según el RFC 6464), VIDEO_CONFIG y AUDIO_CONFIG (en el primer objeto de un grupo), escritas en orden ascendente de tipo. Un grupo de video empieza en cada keyframe, y un grupo de audio contiene un frame, o los frames de
AudioGroupDuration. - VIDEO_FRAME_MARKING no se escribe ni se lee: LOC deja su disposición de bits a otro RFC. Los keyframes se conocen por la estructura de los grupos.
Unpackignora las Immutable Properties (0x0B), que kolo-moq entrega como una sola propiedad con su contenido serializado, así que una propiedad LOC dentro de ellas no se lee.- Un objeto protegido es la forma sellada del mismo objeto. El texto plano es la longitud vi64 del payload, el payload (el frame del códec o el catálogo codificado) y, cuando hay propiedades, la marca
00 0A, una longitud vi64 y las propiedades LOC en orden ascendente de tipo. Un relay ve una propiedad visible, las Immutable Properties (0x0B) con el Key ID en el tipo 0x78, y el payload como texto cifrado con su etiqueta de 16 bytes. AUDIO_LEVEL no se escribe en un track protegido, porque su tamaño revelaría la voz, y el catálogo no tiene propiedades. Un objeto protegido sigue el perfil de Kolo de draft-ietf-moq-secure-objects-01 y no interopera con otras implementaciones de Secure Objects.
Medios protegidos
NewSecureBroadcast(origin, sender) es NewBroadcast para el namespace de un secobj.Sender de kolo-moq. Cada objeto, el catálogo incluido, se sella antes de que kolo-moq lo escriba, así que un relay de kolo-moq lo reenvía sin leerlo. WatchOptions.Keys, un secobj.Keyring, hace que Watch abra cada objeto antes de que nada lo use. El sellado y las claves se describen en Objetos protegidos, en kolo-moq.
Este programa es el inicio rápido con el broadcast sellado. Alice entrega su clave a Bob por la sesión que ya tienen, y Bob acepta claves para su namespace solo de ella. Están conectados directamente, sin relay.
package main
import (
"context"
"crypto/ed25519"
"errors"
"fmt"
"log"
"time"
koloid "github.com/ciranda-dev/kolo-id"
kolomedia "github.com/ciranda-dev/kolo-media"
kolomoq "github.com/ciranda-dev/kolo-moq"
"github.com/ciranda-dev/kolo-moq/secobj"
kolosecure "github.com/ciranda-dev/kolo-secure"
)
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
alice, bob := must(koloid.Generate()), must(koloid.Generate())
ns := kolomoq.Namespace{"room", "alice"}
// Alice seals every object with a key that only Bob receives, on a track of its own.
origin := must(kolomoq.NewOrigin(nil))
sender := must(secobj.NewSender(origin, ns, nil))
defer sender.Close()
broadcast := must(kolomedia.NewSecureBroadcast(origin, sender))
defer broadcast.Close()
mic := must(broadcast.AddTrack(kolomedia.Track{
Name: "mic", Kind: kolomedia.Audio, Codec: kolomedia.PCMS16LE, Timescale: 48000,
SampleRate: 48000, Channels: 1, FrameDuration: 20 * time.Millisecond,
}, kolomedia.PackagerOptions{}))
if err := sender.SetMembers([]ed25519.PublicKey{bob.PublicKey()}); err != nil {
log.Fatal(err)
}
ln := must(kolosecure.Listen(ctx, "127.0.0.1:0", alice, nil))
defer ln.Close()
go func() {
if conn, err := ln.Accept(ctx); err == nil {
if s, err := kolomoq.NewServer(ctx, conn, &kolomoq.Config{Origin: origin}); err == nil {
<-s.Done()
}
}
}()
clock := kolomedia.NewClock()
go func() {
for range time.Tick(20 * time.Millisecond) {
ts, err := clock.At(time.Now(), 48000)
if err != nil || mic.WriteFrame(kolomedia.Frame{Timestamp: ts, Data: make([]byte, 1920)}) != nil {
return
}
}
}()
// Bob accepts keys for alice's namespace only from alice, and opens every object with them.
keys := must(secobj.NewKeyring(secobj.KeyringConfig{
Authorize: func(peer ed25519.PublicKey, _ kolomoq.Namespace) error {
if !peer.Equal(alice.PublicKey()) {
return errors.New("not the owner of the namespace")
}
return nil
},
}))
conn := must(kolosecure.Dial(ctx, ln.Addr().String(), bob, alice.PublicKey(), nil))
session := must(kolomoq.NewClient(ctx, conn, nil))
defer session.Close()
go func() {
if err := keys.Receive(ctx, session, bob.PublicKey(), ns); err != nil && !errors.Is(err, kolomoq.ErrClosed) && ctx.Err() == nil {
log.Print(err)
}
}()
caps := kolomedia.Capabilities{Codecs: []kolomedia.Codec{kolomedia.PCMS16LE}}
watcher := must(kolomedia.Watch(ctx, session, ns, kolomedia.WatchOptions{Capabilities: caps, Keys: keys}))
defer watcher.Close()
for range 5 {
frame, track, err := watcher.Next(ctx, kolomedia.Audio)
if err != nil {
log.Fatal(err)
}
fmt.Println("play", track.Name, len(frame.Data), "bytes")
}
audio := watcher.Stats().Audio
fmt.Println("no key", audio.NoKey, "retired", audio.Retired, "unauthenticated", audio.Unauthenticated)
}Imprime:
play mic 1920 bytes
play mic 1920 bytes
play mic 1920 bytes
play mic 1920 bytes
play mic 1920 bytes
no key 0 retired 0 unauthenticated 0Publicar:
- Crea un
secobj.Senderpara tu namespace en el origin que leen tus peers y llama aNewSecureBroadcast(origin, sender). El Sender sigue siendo tuyo:Broadcast.Closeno lo cierra. sender.SetMembers(members)recibe los participantes que tu aplicación autoriza. Cada cambio rota la clave y envía la nueva a cada miembro por tu sesión con él, antes de usarla. Un miembro retirado no abre nada sellado después de queSetMembersdevolviera. No hay una lista de miembros acordada, así que dile al usuario "X ya no recibe tus medios".- Escribe los frames como siempre.
Frame.AudioLevelse comprueba y después se descarta en un track protegido, porque sus 1 o 2 bytes revelarían la voz por el tamaño del texto cifrado. Los receptores calculan los niveles a partir del audio decodificado. Usa Opus con tasa de bits constante y DTX desactivado, para que los tamaños de los paquetes tampoco revelen la voz. - Después de una rotación, el broadcast publica el catálogo de nuevo con la clave nueva enseguida, aunque no se escriba ningún frame, para que un miembro que acaba de entrar pueda leerlo. Si eso falla, el siguiente frame lo intenta otra vez. Fuerza un keyframe en cada track de video cuando cambie
sender.KeyID()(sender.Changed()avisa), o quien entra espera al siguiente. - Quitar un track y volver a añadirlo reinicia sus IDs de grupo. El Sender rota antes de sellar el track nuevo, así que no se repite ningún nonce.
- Los tracks de datos de tu aplicación, como reacciones, manos levantadas y chat, van en tracks propios del mismo namespace. Escríbelos con
sender.Writey léelos conkeys.Opener(session, ns, track), uno por suscripción. Falla consecobj.ErrWrongSessionsalvo que el peer de la sesión sea el dueño denso un relay incluido en la lista, igual queWatch.
Ver:
- Crea un solo
secobj.Keyring. SuAuthorizedice qué peer es dueño de qué namespace (en una reunión,{room, hex(peer)}), yRelayslista los relays de kolo-moq que usas. Ejecutakeys.Receivepara cada emisor en tu sesión con ese emisor: las claves nunca viajan por un relay de kolo-moq. Watchfalla con un error que envuelvesecobj.ErrWrongSessionsalvo que el peer de la sesión sea el dueño denso un relay incluido en la lista, así que un miembro no puede servir el namespace de otro miembro en su propia sesión directa. Devuelve cuando llega un catálogo que se abre con la clave del emisor.- Cada objeto se abre antes de usar sus metadatos. Las propiedades LOC salen solo de la lista descifrada. Las propiedades visibles y las propiedades del track, que un relay puede añadir, se ignoran.
- No hay degradación: un objeto sin Key ID se descarta y se cuenta. Decide si un participante está protegido solo a partir de las claves recibidas por la sesión autenticada, nunca por lo que muestra un relay, y no reproduzcas nada de un participante sin claves ("esperando claves").
- Un objeto con un Key ID más nuevo que todas las claves que se tienen puede esperar un mensaje de clave en camino. Se retiene como máximo
PlayoutConfig.MaxDelay, dentro deMaxFramesyMaxBytes, y se reintenta cuando cambia el keyring. Solo se descarta si su clave sigue faltando cuando se reintenta pasadoMaxDelay. Los estados de objeto y el final de la suscripción esperan detrás de los objetos retenidos, así que nunca los adelantan. Un objeto de catálogo, el de la versión más nueva, espera su clave hasta que lo reemplaza uno más nuevo. Un objeto con una clave retirada se descarta de inmediato. Statscuenta por tipoNoKey(la clave no llegó a tiempo),Retired(el objeto llegó después de retirada su clave, o nombra un Key ID más antiguo que las claves que se tienen) yUnauthenticated(falló la autenticación, no estaba protegido, o era una repetición). Los objetos de catálogo que no se abren cuentan enWatchStats.BadCatalogs.- Cada suscripción abre sus objetos con su propio
secobj.Opener, con su propia ventana de repeticiones. Varias visualizaciones de un mismo namespace, y una suscripción reiniciada en un track que ya leyó, comparten un Keyring. - End of Track, End of Group y el PUBLISH_DONE detrás de
ErrBroadcastEndedyErrTrackEndedno están autenticados: muéstralos como "los medios se detuvieron", nunca como "salió de la llamada". La presencia sale de la sesión entre participantes.
Qué sigue viendo y haciendo un relay de kolo-moq:
- La dirección, la clave pública de kolo-id y las horas de conexión de cada participante. Los namespaces, o sea el identificador de la sala (usa uno opaco) y quién publica qué tracks, y quién ve a quién. Los Group ID y Object ID, las prioridades y los Key ID, o sea cuándo rotó cada emisor y cuándo entró o salió la gente.
- El tamaño y los tiempos de cada objeto: cuándo envía cada persona, la longitud de los mensajes de chat, el movimiento del video y los keyframes. Silenciar el micrófono y apagar la cámara se ven como tracks que se detienen o terminan.
- Puede descartar, retrasar, reordenar o retener objetos, terminar tracks y servir objetos a cualquiera. Sin las claves eso no produce nada legible, y todo objeto que cambia falla la autenticación.
Qué no dan las bibliotecas:
- Cada miembro tiene la clave de cada emisor, y los objetos no se firman por emisor. Un miembro que controla el relay, lo ejecuta o se coluda con su operador puede crear audio, video, catálogos y datos que parecen venir de cualquier otro miembro, sin que se detecte. Con un relay honesto con
kolomoq.RoomPolicy, y en una sesión directa, un miembro no puede. - No hay secreto hacia adelante dentro de una generación de clave ni recuperación tras un compromiso. Cualquiera en la llamada puede leer los medios de todos.
- Las claves nunca se escriben en disco. Las claves base y las sales se sobrescriben al reemplazarlas, quitarlas o cerrar. Los key schedules de AES y los mensajes de clave que quedan en cachés de tracks de claves y en buffers del transporte se liberan, no se sobrescriben, y Go no garantiza que no quede ninguna copia en memoria. El AES-GCM de Go es de tiempo constante solo en su ensamblador para CPUs amd64 y arm64 con instrucciones AES, ppc64x y s390x. En otras CPUs es código genérico que no es de tiempo constante, mientras que el TLS de Go entonces prefiere ChaCha20, así que la protección de objetos es el eslabón más débil ahí.
Límites
Un campo en cero de una config toma el valor por defecto. Las tablas completas están en Límites.
CatalogLimits: 1024 tracks, nombres de 4096 bytes y configs de 65508 bytes por defecto, lo máximo que cabe en una propiedad de objeto. Solo puede bajarlos.PlayoutConfig:MinDelay100 ms,MaxDelay400 ms (oMinDelaysi es mayor),MaxBehind50 ms,MaxFrames8192 por track yMaxBytes16 MiB por track. Un valor negativo, oMinDelaymayor queMaxDelay, esErrInvalidConfig.- El track de catálogo y cada track de medios cuentan para el
MaxTracksdel origin (1000 por defecto en kolo-moq), así que un origin por defecto detieneAddTracken 999 tracks de medios conErrTooManyTracks. MediaGroupTimeout, 30 s: un grupo que no se envió 30 s después de terminar no sirve a un suscriptor en vivo y se descarta.- Un track de video retiene hasta el doble de
MaxFramesyMaxBytes, 32 MiB por defecto, porque el ensamblador de grupos cuenta sus objetos retenidos aparte del búfer del playout. - Como máximo un track de audio por
Playout. - Medios protegidos: un objeto cuya clave puede estar en camino se retiene como máximo
MaxDelay, 400 ms por defecto. Los objetos retenidos por track están acotados porMaxFramesyMaxBytes, los estados retenidos porMaxFrames, y se retiene un objeto de catálogo hasta que llegue su clave o lo reemplace uno más nuevo. Con el ensamblador de grupos y el playout, un track de video protegido puede retener hasta tres vecesMaxFramesyMaxBytes, 48 MiB por defecto. - Un objeto de audio protegido pesa 24 bytes más que uno sin proteger, 9,6 kbit/s a 50 objetos por segundo, y la sobrecarga es de menos del 1 por ciento en video. Las claves están acotadas por
secobjde kolo-moq (Límites). Se prueban llamadas de hasta 20 participantes. Es un límite de pruebas, no criptográfico, y la biblioteca no fija ninguno. - Memoria por participante remoto: un track de audio retiene hasta 16 MiB en el playout, 32 MiB si está protegido, y un track de video 32 MiB, 48 MiB si está protegido. Un participante protegido con audio y video ocupa así hasta 80 MiB en kolo-media, más el
MaxBufferedBytesde kolo-moq (32 MiB por defecto) por cada una de sus suscripciones. Un emisor hostil que mantiene llenos todos los límites cuesta todo eso.
Seguridad
- Todo búfer está acotado: el búfer del playout por
MaxFramesyMaxBytes, los objetos de video retenidos por los mismos límites y el catálogo porCatalogLimits. Un frame marcado demasiado adelante se descarta, y un primer frame marcado muy adelante solo silencia el track del propio emisor, de 2 a 3 s. - Un objeto de catálogo que no se puede interpretar, que no es el objeto 0 o cuya versión difiere de su ID de grupo se ignora y se cuenta en
WatchStats.BadCatalogs, y también un objeto de catálogo protegido que no se abre. - Los analizadores tienen fuzz targets.
- Una visualización protegida abre cada objeto antes de usarlo. Un objeto que falla la autenticación, no tiene Key ID o repite uno ya abierto en su suscripción se descarta y se cuenta en
Unauthenticated.
Estado
- Hecho: catálogo, empaquetado LOC, reloj, playout, selección, publicar y ver sobre kolo-moq, con fuzz targets y tests sobre conexiones reales en 127.0.0.1.
- Hecho: broadcasts y visualizaciones protegidos con
secobjde kolo-moq. Se midieron llamadas protegidas de 4, 8 y 20 participantes en un portátil por loopback, y la página de límites del repositorio da las cifras y las condiciones. - Probada en macOS arm64: pasan
go vet,go testygo test -race, y los ejemplos funcionan. Linux y Windows no se ejecutaron, solo se comprobaron congo vetentre plataformas. - No hecho: VIDEO_FRAME_MARKING.
- Experimental. La API puede cambiar antes de v1.0.0.
Errores
| Error | Mensaje |
|---|---|
ErrBroadcastEnded | kolomedia: broadcast ended |
ErrBroadcastExists | kolomedia: broadcast already exists |
ErrBroadcastNotFound | kolomedia: broadcast not found |
ErrCatalogFormat | kolomedia: unsupported catalog format |
ErrClosed | kolomedia: closed |
ErrDuplicateProperty | kolomedia: duplicate property |
ErrFrameTooLarge | kolomedia: frame too large |
ErrInvalidCatalog | kolomedia: invalid catalog |
ErrInvalidConfig | kolomedia: invalid configuration |
ErrInvalidFrame | kolomedia: invalid frame |
ErrInvalidTimescale | kolomedia: invalid timescale |
ErrInvalidTrack | kolomedia: invalid track |
ErrMalformedProperty | kolomedia: malformed property |
ErrMissingProperty | kolomedia: missing property |
ErrNeedKeyframe | kolomedia: video track needs a keyframe |
ErrNoMatch | kolomedia: no track matches the capabilities |
ErrPropertyMismatch | kolomedia: property does not match the catalog |
ErrSessionEnded | kolomedia: session ended |
ErrTimestampOrder | kolomedia: timestamp not after the previous frame |
ErrTimestampRange | kolomedia: timestamp out of range |
ErrTooManyTracks | kolomedia: too many tracks |
ErrTrackEnded | kolomedia: track ended |
ErrUnknownTrack | kolomedia: unknown track |
Todos los errores empiezan por kolomedia:. Usa errors.Is y errors.As. Un error de kolo-moq mantiene su causa en la cadena bajo el prefijo, así que errors.Is(err, kolomoq.ErrObjectTooLarge) y errors.As(err, &requestError) siguen funcionando. ErrBroadcastNotFound es un Watch de un namespace que el peer no publica, y envuelve el kolomoq.RequestError con DOES_NOT_EXIST. ErrBroadcastExists es un NewBroadcast donde el origin ya tiene el track de catálogo, y un frame cuyo objeto supera el MaxObjectSize del origin es ErrFrameTooLarge. NewSecureBroadcast con un Sender nil es ErrInvalidConfig, un Watch protegido sobre una sesión que no puede llevar el namespace envuelve secobj.ErrWrongSession, y un frame que no se puede sellar mantiene en la cadena el error de secobj o de kolo-moq (kolomoq.ErrClosed cuando el Sender está cerrado). No se escribe nada de él.
Referencias
- Low Overhead Media Container, draft-ietf-moq-loc-04 (Internet-Draft, julio de 2026, expira el 21 de enero de 2027).
- Toma: las propiedades de objeto LOC.
- No implementa: VIDEO_FRAME_MARKING. Existe la revisión 05 (2 de noviembre de 2026) y no se sigue.
- RFC 6464, RTP Header Extension for Client-to-Mixer Audio Level Indication (Proposed Standard, diciembre de 2011).
- Toma: el valor AUDIO_LEVEL: bandera de voz 0x80, nivel de 0 a 127 en -dBov.
- No implementa: la extensión de cabecera RTP.
- RFC 9626, Video Frame Marking RTP Header Extension (Experimental, marzo de 2025).
- Toma: nada.
- No implementa: todo. No se escribe ni se lee.
- Media over QUIC Transport, draft-ietf-moq-transport-22 (Internet-Draft, octubre de 2026, expira el 4 de abril de 2027).
- Toma: el transporte, a través de kolo-moq.
- No implementa: véanse las Referencias de kolo-moq.
- End-to-End Secure Objects for Media over QUIC Transport, draft-ietf-moq-secure-objects-01 (Internet-Draft, julio de 2026, expira el 7 de enero de 2027, sigue siendo la revisión vigente).
- Toma: el perfil de Kolo de objetos protegidos, a través de kolo-moq.
- No implementa: véanse las Referencias de kolo-moq.
- RFC 6716, Definition of the Opus Audio Codec (Proposed Standard, septiembre de 2012, actualizada por la RFC 8251).
- Toma: la identidad del códec Opus en el catálogo.
- No implementa: nada.