Skip to content

Produce a Track

Producing a track involves writing media data to a moqt.TrackWriter, which manages the creation of groups and frames for transmission. moqt.TrackWriter is responsible for handling the track’s lifecycle, including opening and closing groups. moqt.TrackWriter is created when being subscribed to a track from the peer on the session. Created moqt.TrackWriter is then routed via the session’s moqt.TrackMux and can be used to publish media data.

Overview
mux := moqt.NewTrackMux(0)
// Set the mux to a session
// This differs from if it is client-side or server-side
mux.PublishFunc(ctx, "/broadcast_path", func(tw *moqt.TrackWriter) {
defer tw.Close() // Always close when done
for {
gw, err := tw.OpenGroup(ctx) // Create a new group
if err != nil {
// Handle error
return
}
frame := moqt.NewFrame(1024)
payload := []byte("sample data")
frame.Write(payload)
err = gw.WriteFrame(frame)
if err != nil {
// Handle error
return
}
}
})

When the other side (client or server) subscribes to a broadcast path, the registered moqt.TrackHandler is invoked to serve the subscription. The handler receives a moqt.TrackWriter and is responsible for sending the appropriate track data for the requested track name.

var mux *moqt.TrackMux
// Register the track handler with PublishFunc
mux.PublishFunc(ctx, "/broadcast_path", func(tw *moqt.TrackWriter) {
defer tw.Close() // Always close when done
// Handle track subscription
})
// trackHandler implements moqt.TrackHandler
var _ moqt.TrackHandler = (*trackHandler)(nil)
type trackHandler struct{}
func (h *trackHandler) ServeTrack(tw *moqt.TrackWriter) {
defer tw.Close() // Always close when done
// Handle track subscription
}
var mux *moqt.TrackMux
// Register the track handler
mux.Publish(ctx, "/broadcast_path", &trackHandler{})
// Register the track handler using an Announcement
var ann *moqt.Announcement
mux.Announce(ann, &trackHandler{})

To start a new group within a track, use TrackWriter.OpenGroup method. This creates a new group with an automatically incremented sequence number and returns a moqt.GroupWriter for writing frames to that group.

For explicit sequence control, use TrackWriter.OpenGroupAt method with a specific moqt.GroupSequence.

var tw *moqt.TrackWriter
gw, err := tw.OpenGroup(context.Background()) // Auto-incrementing sequence
if err != nil {
// Handle error
return
}
defer gw.Close() // Always close when done
// Use gw to write frames
// Or use OpenGroupAt for explicit sequence control
gw, err := tw.OpenGroupAt(context.Background(), moqt.GroupSequence(42))
if err != nil {
// Handle error
return
}

To add media data to a group, use GroupWriter.WriteFrame method. Each frame represents a chunk of media data (audio, video, etc.) to be sent as part of the group.

var gw *moqt.GroupWriter
frame := moqt.NewFrame(0)
payload := []byte("sample payload")
frame.Write(payload) // Populate payload
err := gw.WriteFrame(frame)
if err != nil {
// Handle error
}

Create frames with moqt.NewFrame(capacity), reuse the buffer with Reset (which also clears Timestamp, so set it afterwards), and append payload via Write or by manipulating Body() when needed.

frame := moqt.NewFrame(1024)
frame.Write([]byte("Good Morning"))
fmt.Println(string(frame.Body())) // "Good Morning"
frame.Reset() // Reuse buffer for next frame
frame.Write([]byte("Good Evening"))
fmt.Println(string(frame.Body())) // "Good Evening"

Frames are reused for efficiency; clone with frame.Clone() when you need to retain a copy after the next write.

Relays MUST NOT combine, split, or otherwise modify object payloads.
— MOQT WG1

To finalize a group and indicate that no more frames will be sent, call GroupWriter.Close method.

var gw *moqt.GroupWriter
gw.Close()

To cancel a group and stop sending frames, call GroupWriter.CancelWrite method with an error code.

var group *moqt.GroupWriter
var code moqt.GroupErrorCode
group.CancelWrite(code)

To stop a track and indicate that no more groups will exist, call TrackWriter.Close method.

var tw *moqt.TrackWriter
tw.Close()

To abort a track and indicate that no more groups will exist due to an error, call TrackWriter.CloseWithError method with an error code.

var tw *moqt.TrackWriter
var code moqt.SubscribeErrorCode
tw.CloseWithError(code)
  • Subscribe Error Code: The subscribe error code is used to indicate the reason for closing the track subscription. It helps the publisher understand why the subscription finished.

If any groups belong to the track, they will be closed automatically with an error code moqt.InternalGroupErrorCode when the track is closed with an error. This ensures that all resources are released properly and no data is lost.

A subscriber can ask about a track’s immutable publisher properties — priority, ordering preference, max latency, and timescale — via Session.TrackInfo, without subscribing to it. By default, TrackMux answers TRACK_INFO requests with zero-valued properties (zero priority, unordered, no retention, DefaultTimescale).

To advertise real properties, implement TrackInfoProvider on your TrackHandler:

type trackHandler struct{}
var _ moqt.TrackHandler = (*trackHandler)(nil)
var _ moqt.TrackInfoProvider = (*trackHandler)(nil)
func (h *trackHandler) ServeTrack(tw *moqt.TrackWriter) {
defer tw.Close()
// Handle track subscription
}
// TrackInfo returns the publisher properties for the named track of the
// broadcast at path and whether the track exists.
func (h *trackHandler) TrackInfo(path moqt.BroadcastPath, name moqt.TrackName) (moqt.PublishInfo, bool) {
return moqt.PublishInfo{
Priority: 128,
MaxAge: 2 * time.Second,
Timescale: 90_000, // units of Frame.Timestamp on this track
}, true
}

Frame.Timestamp is a number of the track’s Timescale units, which a relay passes on as it is. To work in time, convert at the edges with moqt.MediaTime, a timestamp together with its timescale. It computes each conversion in 128 bits and rounds once, so a timestamp computed from its position does not drift the way adding up an interval does:

frame.Timestamp = moqt.MediaTimeOf(elapsed, info.Timescale).Timestamp() // a time.Duration as a timestamp
at := moqt.NewMediaTime(frame.Timestamp, info.Timescale).Duration() // a timestamp as a time.Duration
frame.Timestamp = moqt.NewMediaTime(n*1001, 30_000).In(info.Timescale).Timestamp() // frame n at 29.97 fps
us := moqt.NewMediaTime(rtpTimestamp, 48_000).In(1_000_000).Timestamp() // another timescale
later := moqt.NewMediaTime(frame.Timestamp, info.Timescale).Add(20 * time.Second) // 20 s later
lag := audio.Sub(video) // a time.Duration, across timescales

Add rounds its duration to a unit on each call, so add a total from a fixed base (base.Add(time.Duration(n) * interval)) rather than an interval again and again. A zero timescale is DefaultTimescale. A subscriber that needs the timescale asks for it with Session.TrackInfo.

TRACK_INFO is intentionally out-of-band from the catalog: catalog fields (msf.Track) describe content, while PublishInfo carries transport scheduling hints, and the two live in different layers by design — msf.Track has no Priority field to source it from.

The TrackInfoProvider type assertion runs against the handler registered with mux.Publish for the broadcast path — not against the per-track handler passed to RegisterTrack. msf.Broadcast does not implement TrackInfoProvider itself, so publishing one directly means every track reports the default zero-valued properties. To supply real ones, embed *msf.Broadcast in your own type and implement TrackInfo on it, then publish that type instead of the *msf.Broadcast value:

type broadcast struct {
*msf.Broadcast
info map[moqt.TrackName]moqt.PublishInfo
}
// TrackInfo implements moqt.TrackInfoProvider. *msf.Broadcast already
// satisfies moqt.TrackHandler (ServeTrack is promoted), so this is the
// only method the wrapper needs to add.
func (b *broadcast) TrackInfo(_ moqt.BroadcastPath, name moqt.TrackName) (moqt.PublishInfo, bool) {
info, ok := b.info[name]
return info, ok
}
// mux.Publish(ctx, "/broadcast_path", &broadcast{Broadcast: msfBroadcast, info: infoByTrack})

msf.Track has spec-defined TargetLatency/Timescale fields that already carry the same meaning as PublishInfo.MaxAge/Timescale, so a wrapper can forward those straight from the catalog. Priority has no catalog equivalent to source from — they are tracked in issue #420 as a possible future vendor extension to the catalog.

  1. IETF Draft - The Media Over QUIC Transport (moqtransport) ↩