Skip to main content

moq_mux/container/
cts.rs

1//! CTS hang container: QUIC varint composition time offset (in track timescale) plus codec payload.
2//!
3//! Each MoQ frame begins with an unsigned QUIC varint CTS measured in the track's timescale,
4//! followed by the raw codec payload. Presentation timestamp is `transport_timestamp + CTS`.
5//! Requires a timed track.
6
7use crate::container::{Container, Frame, Kind};
8
9/// CTS hang wire format configured for the track's media role.
10pub struct Wire(
11	/// The kind of content carried by the track.
12	pub Kind,
13);
14
15impl Container for Wire {
16	type Error = crate::Error;
17
18	fn end(&self, frame: &Frame) -> Option<moq_net::Timestamp> {
19		(self.0 != Kind::Data && frame.payload.is_empty()).then_some(frame.timestamp)
20	}
21
22	fn kind(&self) -> Kind {
23		self.0
24	}
25
26	fn decode_order(&self) -> bool {
27		true
28	}
29
30	// The writer waits on the cts-encoders quest: the binding frame APIs carry no decode time,
31	// and a draft-18..22 hop stamps every object at its Group ID, losing the decode time the
32	// offset counts from.
33	fn writable(&self) -> Result<(), Self::Error> {
34		Err(moq_net::Error::Unsupported.into())
35	}
36
37	fn finish_group(
38		&self,
39		_group: &mut crate::container::Writer<'_>,
40		_end: Option<moq_net::Timestamp>,
41	) -> Result<(), Self::Error> {
42		// Refused for the reasons on `writable`.
43		Err(moq_net::Error::Unsupported.into())
44	}
45
46	fn write(&self, _group: &mut crate::container::Writer<'_>, _frames: &[Frame]) -> Result<(), Self::Error> {
47		// Refused for the reasons on `writable`.
48		Err(moq_net::Error::Unsupported.into())
49	}
50
51	fn decode(&self, mut frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
52		// CTS is relative to the transport timestamp in the track's timescale, so an untimed track is malformed.
53		let Some(scale) = frame.timestamp.scale() else {
54			return Err(moq_net::Error::TimestampMismatch.into());
55		};
56
57		// On a data track an object with no bytes is its discontinuity marker, not a frame.
58		// Elsewhere it is malformed, so it fails to decode below.
59		if self.0 == Kind::Data && frame.payload.is_empty() {
60			return Ok(Vec::new());
61		}
62
63		let cts = moq_net::varint::decode_quic(&mut frame.payload).map_err(moq_net::Error::from)?;
64		let pts = frame
65			.timestamp
66			.value()
67			.checked_add(cts)
68			.ok_or(moq_net::Error::Decode(moq_net::DecodeError::BoundsExceeded))?;
69		let timestamp = moq_net::Timestamp::new(pts, scale).map_err(hang::Error::from)?;
70
71		Ok(vec![Frame {
72			timestamp,
73			decode: (cts != 0).then_some(frame.timestamp),
74			payload: frame.payload,
75			keyframe: false,
76			duration: None,
77		}])
78	}
79}
80
81#[cfg(test)]
82mod tests {
83	use super::*;
84	use crate::container::test_util::Lazy;
85	use bytes::{Bytes, BytesMut};
86	use moq_net::{Timescale, Timestamp};
87
88	fn cts_payload(cts: u64, body: &[u8]) -> Bytes {
89		let mut buf = BytesMut::new();
90		moq_net::varint::encode_quic(cts, &mut buf).unwrap();
91		buf.extend_from_slice(body);
92		buf.freeze()
93	}
94
95	#[test]
96	fn decodes_cts_in_track_timescale() {
97		let scale = Timescale::new(90_000).unwrap();
98		// DTS = 3000 (33.3ms), CTS = 6000 (66.7ms) -> PTS = 9000 (100ms).
99		let wire = moq_net::frame::Frame::new(Timestamp::new(3_000, scale).unwrap(), cts_payload(6_000, b"bframe"));
100		let frames = Wire(Kind::Video).decode(wire).unwrap();
101		assert_eq!(frames.len(), 1);
102		assert_eq!(frames[0].timestamp, Timestamp::new(9_000, scale).unwrap());
103		assert_eq!(frames[0].payload, Bytes::from_static(b"bframe"));
104	}
105
106	#[test]
107	fn rejects_untimed_track_and_empty_media_object() {
108		let untimed = moq_net::frame::Frame::new(Timestamp::unscaled(0), cts_payload(0, b"frame"));
109		assert!(Wire(Kind::Video).decode(untimed).is_err());
110
111		let empty = moq_net::frame::Frame::new(Timestamp::from_millis(100).unwrap(), Bytes::new());
112		assert!(Wire(Kind::Video).decode(empty).is_err());
113	}
114
115	#[test]
116	fn empty_codec_payload_and_data_discontinuity() {
117		let ts = Timestamp::from_millis(500).unwrap();
118		let marker = Wire(Kind::Video)
119			.decode(moq_net::frame::Frame::new(ts, cts_payload(33, b"")))
120			.unwrap();
121		assert_eq!(marker.len(), 1);
122		assert_eq!(
123			Wire(Kind::Video).end(&marker[0]),
124			Some(Timestamp::from_millis(533).unwrap())
125		);
126
127		let data = Wire(Kind::Data)
128			.decode(moq_net::frame::Frame::new(ts, Bytes::new()))
129			.unwrap();
130		assert!(data.is_empty());
131	}
132
133	/// A buffering producer refuses the first CTS write on entry, so it never opens a group it
134	/// could not flush.
135	#[test]
136	fn a_buffered_producer_refuses_before_opening_a_group() {
137		let broadcast = moq_net::broadcast::Info::new().produce();
138		let track = broadcast
139			.create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
140			.unwrap();
141		let mut producer = crate::container::Producer::new(track, crate::catalog::hang::Wire::cts(Kind::Video))
142			.with_buffer(std::time::Duration::from_secs(1));
143		let err = producer.write(Frame {
144			timestamp: Timestamp::from_millis(0).unwrap(),
145			decode: None,
146			payload: Bytes::from_static(b"pkt"),
147			keyframe: true,
148			duration: None,
149		});
150		assert!(
151			matches!(err, Err(crate::Error::Moq(moq_net::Error::Unsupported))),
152			"{err:?}"
153		);
154		assert!(producer.track().largest().is_none(), "opened a group");
155	}
156
157	#[test]
158	fn write_and_finish_group_return_unsupported() {
159		let broadcast = moq_net::broadcast::Info::new().produce();
160		let track = broadcast
161			.create_track(
162				"video",
163				moq_net::track::Info::default().with_timescale(Timescale::MILLI),
164			)
165			.unwrap();
166		let mut group = Lazy::appending(&track);
167		let frame = Frame {
168			timestamp: Timestamp::from_millis(33).unwrap(),
169			decode: None,
170			payload: Bytes::from_static(b"pkt"),
171			keyframe: true,
172			duration: None,
173		};
174		assert!(
175			Wire(Kind::Video)
176				.write(&mut group.writer(), std::slice::from_ref(&frame))
177				.is_err()
178		);
179		assert!(
180			Wire(Kind::Video)
181				.finish_group(&mut group.writer(), Some(frame.timestamp))
182				.is_err()
183		);
184	}
185}