Skip to main content

moq_mux/container/
group.rs

1use std::collections::VecDeque;
2use std::task::Poll;
3
4use super::{Container, Frame};
5
6/// Decode a single [`moq_net::group::Consumer`] into a finite stream of media [`Frame`]s.
7///
8/// This is the group-scoped counterpart to [`Consumer`](super::Consumer). Where that one
9/// subscribes to a track and juggles group ordering, age skipping, and rewinds, this one
10/// reads exactly the group it was handed, in arrival order, and ends. That is what a caller
11/// wants after a FETCH, a group already chosen by start, or for a live group taken from
12/// [`recv_group`](moq_net::track::Subscriber::recv_group), whose frames return as they land.
13///
14/// A batch of frames decoded from one wire frame (a CMAF fragment carrying several samples) is
15/// handed back one frame at a time.
16pub struct GroupConsumer<F: Container> {
17	group: moq_net::group::Consumer,
18	format: F,
19
20	// Frames decoded from the last wire frame but not yet returned.
21	pending: VecDeque<Frame>,
22
23	// How many media frames we have returned, so the first one can be marked a keyframe.
24	index: u64,
25
26	// Whether a read or decode failed, which ends the group.
27	fault: Fault<F::Error>,
28}
29
30enum Fault<E> {
31	// Nothing failed.
32	Clear,
33	// The lookahead failed, returned once the frames before it are.
34	Pending(E),
35	// The failure was returned: nothing past the malformed object is read.
36	Reported,
37}
38
39impl<F: Container> GroupConsumer<F> {
40	/// Decode `group` with the given container format.
41	pub fn new(group: moq_net::group::Consumer, format: F) -> Self {
42		Self {
43			group,
44			format,
45			pending: VecDeque::new(),
46			index: 0,
47			fault: Fault::Clear,
48		}
49	}
50
51	/// Where this group starts within its track, in the track's timescale.
52	pub fn start(&self) -> u64 {
53		self.group.start
54	}
55
56	/// Read the next frame, or `None` once the group ends.
57	///
58	/// Frames that precede a failed read or decode are returned before the error, which ends the
59	/// group: nothing after it is read.
60	#[cfg_attr(feature = "async", kio::wrapper)]
61	pub fn poll_read(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Frame>, F::Error>> {
62		// Peek past an untimed video frame for a marker or successor that times it, but only
63		// at what has already landed: a live group returns the frame now rather than waiting.
64		while matches!(self.fault, Fault::Clear)
65			&& self.pending.front().is_none_or(|frame| {
66				self.format.kind() == super::Kind::Video && frame.duration.is_none() && self.pending.len() < 2
67			}) {
68			let next = match self.group.poll_read_frame(waiter) {
69				Poll::Ready(next) => next,
70				Poll::Pending if self.pending.is_empty() => return Poll::Pending,
71				Poll::Pending => break,
72			};
73			let frames = match next.map_err(F::Error::from).and_then(|next| match next {
74				Some(frame) => self.format.decode(frame).map(Some),
75				None => Ok(None),
76			}) {
77				Ok(Some(frames)) => frames,
78				Ok(None) => break,
79				Err(err) => {
80					self.fault = Fault::Pending(err);
81					break;
82				}
83			};
84			for frame in frames {
85				if let Some(bound) = self.format.end(&frame) {
86					if self.format.kind() == super::Kind::Video
87						&& let Some(last) = self.pending.back_mut()
88					{
89						super::close_duration(last, bound);
90					}
91				} else {
92					self.pending.push_back(frame);
93				}
94			}
95		}
96		match self.pop_media() {
97			Some(frame) => Poll::Ready(Ok(Some(frame))),
98			None => Poll::Ready(match std::mem::replace(&mut self.fault, Fault::Reported) {
99				Fault::Pending(err) => Err(err),
100				fault => {
101					self.fault = fault;
102					Ok(None)
103				}
104			}),
105		}
106	}
107
108	fn pop_media(&mut self) -> Option<Frame> {
109		let mut frame = self.pending.pop_front()?;
110		// First frame of a group is always a keyframe by protocol invariant; trust
111		// the container's flag otherwise so CMAF mid-group keyframes survive.
112		frame.keyframe = frame.keyframe || self.index == 0;
113		self.index += 1;
114		Some(frame)
115	}
116}
117
118#[cfg(test)]
119mod tests {
120	use super::*;
121	use crate::catalog::hang::Wire as Hang;
122	use crate::container::test_util::Lazy;
123
124	/// A millisecond track: the frames written here carry timestamps. It sets no max age, so a
125	/// group finished whole stays readable after its span has passed.
126	fn timed() -> moq_net::track::Info {
127		moq_net::track::Info::default()
128			.with_timescale(moq_net::Timescale::MILLI)
129			.with_max_age(None)
130	}
131
132	fn frame(timestamp_us: u64, payload: &'static [u8], keyframe: bool) -> Frame {
133		Frame {
134			timestamp: moq_net::Timestamp::from_micros(timestamp_us).unwrap(),
135			decode: None,
136			payload: bytes::Bytes::from_static(payload),
137			keyframe,
138			duration: None,
139		}
140	}
141
142	/// Read one retained group end to end, without a subscription.
143	#[tokio::test]
144	async fn reads_a_group_to_completion() {
145		let broadcast = moq_net::broadcast::Info::new().produce();
146		let track = broadcast.create_track("media", timed()).unwrap();
147		let consumer = broadcast.consume();
148
149		let mut media = crate::container::Producer::new(track, Hang::legacy(crate::container::Kind::Data));
150		media.write(frame(1_000_000, b"keyframe", true)).unwrap();
151		media.write(frame(1_020_000, b"delta", false)).unwrap();
152		let _finished = media.finish().unwrap();
153
154		// The group starts at its keyframe, a second in, in the track's milliseconds.
155		let group = consumer.track("media").unwrap().fetch_group(1_000, None).await.unwrap();
156		let mut group = GroupConsumer::new(group, Hang::legacy(crate::container::Kind::Data));
157		assert_eq!(group.start(), 1_000);
158
159		let first = group.read().await.unwrap().unwrap();
160		assert_eq!(first.payload, b"keyframe".as_slice());
161		assert!(first.keyframe);
162
163		let second = group.read().await.unwrap().unwrap();
164		assert_eq!(second.payload, b"delta".as_slice());
165		assert!(!second.keyframe);
166
167		assert!(group.read().await.unwrap().is_none());
168	}
169
170	/// Data frames round-trip through every container that can write them. Raw has no encoding for
171	/// an empty one, since its zero-byte object is the discontinuity marker, so it refuses that write.
172	#[tokio::test]
173	async fn data_frames_survive_subscription_and_fetch() {
174		for config in [
175			hang::catalog::Container::Legacy,
176			hang::catalog::Container::Loc,
177			hang::catalog::Container::Raw,
178		] {
179			let broadcast = moq_net::broadcast::Info::new().produce();
180			let track = broadcast.create_track("data", hang::container::track_info(0)).unwrap();
181			let subscription = track.subscribe(moq_net::track::Subscription::default());
182			let consumer = broadcast.consume();
183			let mut producer =
184				crate::container::Producer::new(track, Hang::new(&config, crate::container::Kind::Data).unwrap());
185			let first: &'static [u8] = match config {
186				hang::catalog::Container::Raw => {
187					let err = producer.write(frame(0, b"", true));
188					assert!(matches!(err, Err(crate::Error::EmptyRawPayload)), "{err:?}");
189					b"cue"
190				}
191				_ => b"",
192			};
193			producer.write(frame(0, first, true)).unwrap();
194			producer.write(frame(10_000, b"data", false)).unwrap();
195			let _finished = producer.finish().unwrap();
196			let mut live = crate::container::Consumer::new(
197				subscription,
198				Hang::new(&config, crate::container::Kind::Data).unwrap(),
199			);
200			let read = live.read_frame().await.unwrap().unwrap();
201			assert_eq!(read.payload, first, "{config:?}");
202			assert!(read.keyframe);
203			assert_eq!(live.read_frame().await.unwrap().unwrap().payload, b"data".as_slice());
204			assert!(live.read_frame().await.unwrap().is_none());
205			let group = consumer.track("data").unwrap().fetch_group(0, None).await.unwrap();
206			let mut fetched = GroupConsumer::new(group, Hang::new(&config, crate::container::Kind::Data).unwrap());
207			assert_eq!(fetched.read().await.unwrap().unwrap().payload, first);
208			assert_eq!(fetched.read().await.unwrap().unwrap().payload, b"data".as_slice());
209			assert!(fetched.read().await.unwrap().is_none());
210		}
211	}
212
213	/// An empty payload times the previous frame and is not returned as media.
214	#[tokio::test]
215	async fn a_duration_marker_times_the_last_frame() {
216		let broadcast = moq_net::broadcast::Info::new().produce();
217		let track = broadcast.create_track("media", timed()).unwrap();
218		let consumer = broadcast.consume();
219
220		let mut media = crate::container::Producer::new(track, Hang::legacy(crate::container::Kind::Video));
221		media.write(frame(1_000_000, b"keyframe", true)).unwrap();
222		media.write(frame(1_020_000, b"delta", false)).unwrap();
223		media
224			.cut(Some(moq_net::Timestamp::from_micros(1_053_000).unwrap()))
225			.unwrap();
226		let _finished = media.finish().unwrap();
227
228		let group = consumer.track("media").unwrap().fetch_group(1_000, None).await.unwrap();
229		let mut group = GroupConsumer::new(group, Hang::legacy(crate::container::Kind::Video));
230
231		let first = group.read().await.unwrap().unwrap();
232		assert_eq!(first.payload, b"keyframe".as_slice());
233		assert_eq!(first.duration, None);
234
235		let second = group.read().await.unwrap().unwrap();
236		assert_eq!(second.payload, b"delta".as_slice());
237		assert_eq!(second.duration, Some(moq_net::Timestamp::from_micros(33_000).unwrap()));
238
239		assert!(group.read().await.unwrap().is_none());
240	}
241
242	/// A live video group hands back each frame as it lands, rather than holding it until a
243	/// successor or the group's end times it.
244	#[tokio::test]
245	async fn a_live_video_frame_is_not_held_for_its_successor() {
246		use futures::FutureExt;
247
248		let broadcast = moq_net::broadcast::Info::new().produce();
249		let track = broadcast.create_track("media", timed()).unwrap();
250		let format = Hang::legacy(crate::container::Kind::Video);
251		let mut group = Lazy::appending(&track);
252		format
253			.write(&mut group.writer(), &[frame(1_000_000, b"keyframe", true)])
254			.unwrap();
255		let mut live = GroupConsumer::new(group.consume(), Hang::legacy(crate::container::Kind::Video));
256		let first = live.read().now_or_never().expect("held the frame").unwrap().unwrap();
257		assert_eq!(first.payload, b"keyframe".as_slice());
258		assert_eq!(first.duration, None);
259
260		format
261			.write(&mut group.writer(), &[frame(1_020_000, b"delta", false)])
262			.unwrap();
263		let second = live.read().now_or_never().expect("held the frame").unwrap().unwrap();
264		assert_eq!(second.payload, b"delta".as_slice());
265		assert!(live.read().now_or_never().is_none(), "the open group has nothing more");
266
267		group.finish().unwrap();
268		assert!(live.read().await.unwrap().is_none());
269	}
270
271	/// A video frame looked ahead of a malformed object is returned before the decode error.
272	#[tokio::test]
273	async fn a_frame_before_a_malformed_object_is_returned_first() {
274		let broadcast = moq_net::broadcast::Info::new().produce();
275		let track = broadcast.create_track("media", timed()).unwrap();
276		let format = Hang::legacy(crate::container::Kind::Video);
277		let mut group = Lazy::appending(&track);
278		format
279			.write(&mut group.writer(), &[frame(1_000_000, b"keyframe", true)])
280			.unwrap();
281		let mut live = GroupConsumer::new(group.consume(), Hang::legacy(crate::container::Kind::Video));
282		// A truncated timestamp varint.
283		group
284			.write_frame(
285				moq_net::Timestamp::from_millis(1_020).unwrap(),
286				bytes::Bytes::from_static(&[0xff]),
287			)
288			.unwrap();
289		// Frames past the malformed object are never returned.
290		format
291			.write(&mut group.writer(), &[frame(1_040_000, b"after", false)])
292			.unwrap();
293		group.finish().unwrap();
294
295		let first = live.read().await.unwrap().unwrap();
296		assert_eq!(first.payload, b"keyframe".as_slice());
297		assert!(live.read().await.is_err());
298		assert!(live.read().await.unwrap().is_none());
299		assert!(live.read().await.unwrap().is_none());
300	}
301
302	/// One CMAF fragment decodes to several samples, which are handed back one at a time.
303	#[tokio::test]
304	async fn hands_back_a_cmaf_batch_one_frame_at_a_time() {
305		let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
306		config.coded_width = Some(320);
307		config.coded_height = Some(240);
308		let muxer = crate::container::fmp4::Muxer::video(&config).unwrap();
309		let init = muxer.init().unwrap().expect("VP8 init should be available");
310		let cmaf = hang::catalog::Container::Cmaf { init };
311		// The format is not Clone, so decode with a second instance built from the same init.
312		let format = Hang::new(&cmaf, crate::container::Kind::Video).unwrap();
313
314		let broadcast = moq_net::broadcast::Info::new().produce();
315		// A CMAF track counts in its init's ticks.
316		let info = moq_net::track::Info::default().with_timescale(muxer.timescale());
317		// The group starts at its keyframe, two seconds in.
318		let start = moq_net::Timestamp::from_secs(2)
319			.unwrap()
320			.convert(muxer.timescale())
321			.unwrap()
322			.value();
323		let track = broadcast.create_track("video", info).unwrap();
324		let consumer = broadcast.consume();
325
326		// Buffer both samples into one moof+mdat, which is what this decodes.
327		let mut media = crate::container::Producer::new(track, format).with_buffer(std::time::Duration::from_secs(1));
328		for (timestamp_us, payload, keyframe) in [
329			(2_000_000, b"keyframe".as_slice(), true),
330			(2_020_000, b"delta".as_slice(), false),
331		] {
332			media
333				.write(Frame {
334					timestamp: moq_net::Timestamp::from_micros(timestamp_us).unwrap(),
335					decode: None,
336					payload: bytes::Bytes::from_static(payload),
337					keyframe,
338					duration: Some(moq_net::Timestamp::from_micros(20_000).unwrap()),
339				})
340				.unwrap();
341		}
342		let _finished = media.finish().unwrap();
343
344		let group = consumer.track("video").unwrap().fetch_group(start, None).await.unwrap();
345		let mut group = GroupConsumer::new(group, Hang::new(&cmaf, crate::container::Kind::Video).unwrap());
346
347		let first = group.read().await.unwrap().unwrap();
348		assert_eq!(first.payload, b"keyframe".as_slice());
349		assert!(first.keyframe);
350
351		let second = group.read().await.unwrap().unwrap();
352		assert_eq!(second.payload, b"delta".as_slice());
353		assert!(!second.keyframe);
354
355		assert!(group.read().await.unwrap().is_none());
356	}
357}