Skip to main content

moq_mux/container/
raw.rs

1//! Raw hang container: zero-byte header, presentation timestamp equals the MoQ transport timestamp.
2//!
3//! Each MoQ frame carries the raw codec payload directly with no container prefix. Suitable for
4//! tracks without frame reordering (audio, text, data, or I/P-only video). Requires a timed track.
5
6use crate::container::{Container, Frame, Kind};
7
8/// Raw hang wire format configured for the track's media role.
9pub struct Wire(
10	/// The kind of content carried by the track.
11	pub Kind,
12);
13
14impl Wire {
15	/// The bytes preceding a frame's payload: none.
16	pub(crate) fn prefix(&self) -> bytes::Bytes {
17		bytes::Bytes::new()
18	}
19}
20
21impl Container for Wire {
22	type Error = crate::Error;
23
24	fn end(&self, frame: &Frame) -> Option<moq_net::Timestamp> {
25		(self.0 != Kind::Data && frame.payload.is_empty()).then_some(frame.timestamp)
26	}
27
28	fn kind(&self) -> Kind {
29		self.0
30	}
31
32	fn decode_order(&self) -> bool {
33		true
34	}
35
36	fn finish_group(
37		&self,
38		group: &mut crate::container::Writer<'_>,
39		end: Option<moq_net::Timestamp>,
40	) -> Result<(), Self::Error> {
41		if self.0 == Kind::Video
42			&& let Some(timestamp) = end
43		{
44			group.write_frame(timestamp, bytes::Bytes::new())?;
45		}
46		Ok(())
47	}
48
49	fn check(&self, frame: &Frame) -> Result<(), Self::Error> {
50		// A data track's zero-byte object is its discontinuity marker, so an empty frame has no
51		// encoding.
52		if self.0 == Kind::Data && frame.payload.is_empty() {
53			return Err(crate::Error::EmptyRawPayload);
54		}
55		// The transport timestamp is both times, so a reordered frame has no encoding.
56		match frame.decode.is_some_and(|decode| decode != frame.timestamp) {
57			true => Err(moq_net::Error::TimestampMismatch.into()),
58			false => Ok(()),
59		}
60	}
61
62	fn write(&self, group: &mut crate::container::Writer<'_>, frames: &[Frame]) -> Result<(), Self::Error> {
63		// Checked up front so a refused batch writes nothing.
64		for frame in frames {
65			self.check(frame)?;
66		}
67		for frame in frames {
68			group.write_frame(frame.timestamp, frame.payload.clone())?;
69		}
70		Ok(())
71	}
72
73	fn decode(&self, frame: moq_net::frame::Frame) -> Result<Vec<Frame>, Self::Error> {
74		// Raw relies on the transport timestamp, so an untimed track is malformed.
75		if frame.timestamp.scale().is_none() {
76			return Err(moq_net::Error::TimestampMismatch.into());
77		}
78
79		// On a data track a zero-byte object is only ever the discontinuity marker (decodes to no
80		// frames), so one sharing its group is malformed. On audio/video it is an endpoint frame.
81		if self.0 == Kind::Data && frame.payload.is_empty() {
82			return Ok(Vec::new());
83		}
84
85		Ok(vec![Frame {
86			timestamp: frame.timestamp,
87			decode: None,
88			payload: frame.payload,
89			keyframe: false,
90			duration: None,
91		}])
92	}
93}
94
95#[cfg(test)]
96mod tests {
97	use super::*;
98	use bytes::Bytes;
99	use moq_net::{Timescale, Timestamp};
100
101	#[test]
102	fn decodes_transport_timestamp_and_payload() {
103		let wire = moq_net::frame::Frame::new(
104			Timestamp::new(90_000, Timescale::new(90_000).unwrap()).unwrap(),
105			Bytes::from_static(b"opus"),
106		);
107		let frames = Wire(Kind::Audio).decode(wire).unwrap();
108		assert_eq!(frames.len(), 1);
109		assert_eq!(
110			frames[0].timestamp,
111			Timestamp::new(90_000, Timescale::new(90_000).unwrap()).unwrap()
112		);
113		assert_eq!(frames[0].payload, Bytes::from_static(b"opus"));
114	}
115
116	#[test]
117	fn rejects_untimed_track() {
118		let wire = moq_net::frame::Frame::new(Timestamp::unscaled(7), Bytes::from_static(b"opus"));
119		assert!(Wire(Kind::Audio).decode(wire).is_err());
120	}
121
122	#[test]
123	fn empty_payload_semantics() {
124		let ts = Timestamp::from_millis(500).unwrap();
125		// Audio/video: empty payload decodes as an endpoint/discontinuity marker frame.
126		let video = Wire(Kind::Video)
127			.decode(moq_net::frame::Frame::new(ts, Bytes::new()))
128			.unwrap();
129		assert_eq!(video.len(), 1);
130		assert_eq!(Wire(Kind::Video).end(&video[0]), Some(ts));
131
132		// Data: empty object is the discontinuity marker (decodes to no frames).
133		let data = Wire(Kind::Data)
134			.decode(moq_net::frame::Frame::new(ts, Bytes::new()))
135			.unwrap();
136		assert!(data.is_empty());
137	}
138
139	/// An empty frame refused on entry changes nothing: its keyframe bit doesn't cut the open group,
140	/// and the cues buffered in that group still flush with the ones that follow.
141	#[tokio::test]
142	async fn a_refused_empty_payload_leaves_the_group_and_buffer() {
143		type Hang = crate::catalog::hang::Wire;
144		let broadcast = moq_net::broadcast::Info::new().produce();
145		let track = broadcast.create_track("data", hang::container::track_info(0)).unwrap();
146		let consumer = broadcast.consume();
147		let mut producer = crate::container::Producer::new(track, Hang::raw(Kind::Data))
148			.with_buffer(std::time::Duration::from_secs(1));
149		let cue = |millis: u64, payload: &'static [u8], keyframe: bool| Frame {
150			timestamp: Timestamp::from_millis(millis).unwrap(),
151			decode: None,
152			payload: Bytes::from_static(payload),
153			keyframe,
154			duration: None,
155		};
156
157		producer.write(cue(0, b"a", true)).unwrap();
158		producer.write(cue(10, b"b", false)).unwrap();
159		let err = producer.write(cue(20, b"", true));
160		assert!(matches!(err, Err(crate::Error::EmptyRawPayload)), "{err:?}");
161		producer.write(cue(30, b"c", false)).unwrap();
162		let _finished = producer.finish().unwrap();
163
164		let group = consumer.track("data").unwrap().fetch_group(0, None).await.unwrap();
165		let mut group = crate::container::GroupConsumer::new(group, Hang::raw(Kind::Data));
166		for payload in [b"a", b"b", b"c"] {
167			assert_eq!(group.read().await.unwrap().unwrap().payload, payload.as_slice());
168		}
169		assert!(group.read().await.unwrap().is_none());
170	}
171}