Skip to main content

hang/container/
frame.rs

1use super::MAX_AGE;
2use bytes::{Buf, BufMut, Bytes, BytesMut};
3use derive_more::Debug;
4
5use crate::Error;
6
7pub use moq_net::{Timescale, Timestamp};
8
9/// Canonical timescale for the hang legacy wire format: microseconds.
10///
11/// The legacy container's on-wire timestamp is a single varint with no scale tag,
12/// so encoders normalize to this scale and decoders attach it.
13pub const TIMESCALE: Timescale = Timescale::MICRO;
14
15/// Track properties for creating a track that carries [`Frame`]s, via
16/// [`create_track`](moq_net::broadcast::Producer::create_track) or
17/// [`accept`](moq_net::track::Request::accept).
18///
19/// Pins the track's timescale to [`TIMESCALE`], since `moq_net::track::Info::default()` is
20/// untimed and refuses timestamped frames. Microseconds match the container prefix, so the
21/// net-level frame timestamps that moq-lite-05 and later delta-encode on the wire aren't
22/// quantized. Chain
23/// [`with_timescale`](moq_net::track::Info::with_timescale) for a container that carries the
24/// source's own scale instead (CMAF and Matroska both do).
25///
26/// Also declares [`MAX_AGE`], long enough for a segmented egress to serve a full playlist window,
27/// which is why every media track should start here rather than at `Info::default()`, whose max
28/// age is zero. It bounds how long a superseded group stays fresh and caps what a subscriber may
29/// ask to wait for, so it never makes anyone play further behind live: the default subscription
30/// joins at [`Start::LATEST`](moq_net::track::Start::LATEST), whose `max` is zero (skip the moment
31/// a newer group arrives).
32///
33/// `priority` is the publisher's tie-break priority, and should come from
34/// [`PRIORITY`](crate::catalog::PRIORITY) so every publisher orders its kinds the
35/// same way (`PRIORITY.video` for a video track, and so on). It's a parameter
36/// rather than a default because there is no correct value for "some media
37/// track": leaving it at the unset 0 is what puts audio and video in one undifferentiated
38/// tier, both on the wire and in
39/// [`bandwidth::Allocator`](moq_net::bandwidth::Allocator).
40pub fn track_info(priority: i8) -> moq_net::track::Info {
41	moq_net::track::Info::default()
42		.with_timescale(TIMESCALE)
43		.with_max_age(MAX_AGE)
44		.with_priority(priority)
45}
46
47/// A media frame with a timestamp and codec-specific payload.
48///
49/// Frames are the fundamental unit of media data in hang. Each frame contains:
50/// - A timestamp when they should be rendered.
51/// - A codec-specific payload.
52#[derive(Clone, Debug)]
53pub struct Frame {
54	/// The presentation timestamp for this frame.
55	///
56	/// This indicates when the frame should be displayed relative to the
57	/// start of the stream or some other reference point.
58	/// This is NOT a wall clock time.
59	pub timestamp: Timestamp,
60
61	/// The encoded media data for this frame.
62	///
63	/// The format depends on the codec being used (H.264, AV1, Opus, etc.).
64	/// The debug implementation shows only the payload length for brevity.
65	#[debug("{} bytes", payload.len())]
66	pub payload: Bytes,
67}
68
69impl Frame {
70	/// Encode the frame: varint timestamp prefix followed by the raw codec payload.
71	///
72	/// The timestamp is normalized to [`TIMESCALE`] (microseconds) so peers using a
73	/// different source scale (e.g. nanoseconds from MKV) can decode without knowing
74	/// the producer's internal scale. Inverse of [`Self::decode`].
75	pub fn encode(&self, buf: &mut impl BufMut) -> Result<(), Error> {
76		self.encode_header(buf)?;
77		buf.put_slice(&self.payload);
78		Ok(())
79	}
80
81	/// Decode a frame from raw bytes (varint timestamp prefix + payload).
82	///
83	/// Attaches [`TIMESCALE`] (microseconds) to the decoded timestamp, matching what
84	/// [`Self::encode`] writes. Inverse of [`Self::encode`].
85	pub fn decode(mut buf: impl Buf) -> Result<Self, Error> {
86		let value: u64 = moq_net::varint::decode_quic(&mut buf).map_err(moq_net::Error::from)?;
87		let timestamp = Timestamp::new(value, TIMESCALE)?;
88		let payload = buf.copy_to_bytes(buf.remaining());
89
90		Ok(Self { timestamp, payload })
91	}
92
93	/// Write the frame to `group` as a single moq-lite frame, in the [`Self::encode`] format.
94	///
95	/// Prefer this over [`Self::encode`] when writing to a group: it stamps the moq-net frame
96	/// timestamp so moq-lite-05 and later can delta-encode it on the wire independently of the
97	/// container-level prefix.
98	pub fn write_to(&self, group: &mut moq_net::group::Producer) -> Result<(), Error> {
99		// The header and payload share one buffer: a frame written in chunks is copied into
100		// one anyway, so building it here costs the same copy.
101		let mut buf = BytesMut::with_capacity(8 + self.payload.len());
102		self.encode_header(&mut buf)?;
103		buf.extend_from_slice(&self.payload);
104
105		// The prefix keeps the presentation time, while the transport time never decreases within
106		// a group: a B-frame rides at the newest time so far. `write_frame` converts it into the
107		// track's timescale.
108		let transport = match group.latest() {
109			Some(latest) if self.timestamp < latest => latest,
110			_ => self.timestamp,
111		};
112		group.write_frame(moq_net::frame::Frame::new(transport, buf.freeze()))?;
113		Ok(())
114	}
115
116	/// Write the varint timestamp prefix, normalized to [`TIMESCALE`].
117	fn encode_header(&self, buf: &mut impl BufMut) -> Result<(), Error> {
118		let timestamp = self.timestamp.convert(TIMESCALE)?;
119		moq_net::varint::encode_quic(timestamp.value(), buf).map_err(moq_net::Error::from)?;
120
121		Ok(())
122	}
123}
124
125#[cfg(test)]
126mod test {
127	use super::*;
128
129	#[test]
130	fn encode_decode_roundtrip() {
131		let frame = Frame {
132			timestamp: Timestamp::from_micros(1_234_567).expect("timestamp"),
133			payload: Bytes::from_static(b"hello"),
134		};
135
136		let mut buf = BytesMut::new();
137		frame.encode(&mut buf).expect("encode");
138
139		let decoded = Frame::decode(buf.freeze()).expect("decode");
140		assert_eq!(decoded.timestamp, frame.timestamp);
141		assert_eq!(decoded.payload, frame.payload);
142	}
143
144	#[test]
145	fn encode_normalizes_timescale() {
146		// A nanosecond-scale source (e.g. MKV) still lands on the wire as microseconds.
147		let frame = Frame {
148			timestamp: Timestamp::new(1_234_567_000, Timescale::NANO).expect("timestamp"),
149			payload: Bytes::from_static(b"hello"),
150		};
151
152		let mut buf = BytesMut::new();
153		frame.encode(&mut buf).expect("encode");
154
155		let decoded = Frame::decode(buf.freeze()).expect("decode");
156		assert_eq!(decoded.timestamp, Timestamp::from_micros(1_234_567).expect("timestamp"));
157	}
158
159	#[test]
160	fn media_tracks_declare_their_max_age() {
161		// A media track is read as history (a segmented egress FETCHes segments a playlist
162		// advertised), so it declares a finite max age, kept through a retimescale.
163		let max_age = Some(MAX_AGE);
164		assert_eq!(track_info(crate::catalog::PRIORITY.video).max_age, max_age);
165		let at = track_info(crate::catalog::PRIORITY.video).with_timescale(Timescale::MILLI);
166		assert_eq!(at.timescale, Some(Timescale::MILLI));
167		assert_eq!(at.max_age, max_age);
168	}
169}