Skip to main content

moq_mux/container/
declared.rs

1use std::collections::VecDeque;
2
3use hang::catalog::VideoConfig;
4
5/// The reorder depth `config` declares, or `None` when it declares none.
6///
7/// Refuses a depth its codec and level cannot reach, so a declared clock never holds more frames
8/// than a conforming decoder's picture buffer.
9pub(crate) fn depth(config: &VideoConfig) -> crate::Result<Option<usize>> {
10	let Some(reorder) = config.reorder else {
11		return Ok(None);
12	};
13	let max = crate::codec::video::max_reorder(config);
14	if u32::from(reorder) > max {
15		return Err(ReorderError::Depth {
16			reorder,
17			max,
18			codec: config.codec.to_string(),
19		}
20		.into());
21	}
22	Ok(Some(usize::from(reorder)))
23}
24
25/// One group's decode clock, at its rendition's declared reorder depth.
26///
27/// The n-th frame of a group in decode order decodes at the group's (n - depth)-th presentation
28/// slot. Once the group's first depth + 1 frames are read, no frame still to come can be presented
29/// below the earliest of them, so from then on each frame is released as it is read: it takes the
30/// least slot not yet taken, which a later frame could undercut only by following more than depth
31/// frames in presentation order. The first depth frames decode one tick apart up to that earliest
32/// slot, which needs no frame spacing, so a DTS can fall before the timeline's zero. A tick is the
33/// caller's timescale, the finest its container writes: 90 kHz for MPEG-TS, 1 ms for FLV.
34///
35/// Distinct source timestamps can round onto one tick. A frame then moves up to the tick after
36/// every frame presented before it, so each keeps its own presentation slot and order; identical
37/// source timestamps fail, since no order between them is known.
38///
39/// A clock lives for one group, so its DTS depends on nothing read before the group, and a frame
40/// reordered deeper than declared fails rather than move the timeline.
41pub(crate) struct DeclaredClock<T> {
42	depth: usize,
43	/// The group's earliest PTS, once enough frames are read that none to come can precede it.
44	earliest: Option<u64>,
45	/// Frames still to be released that decode before [`Self::earliest`].
46	leading: usize,
47	/// Frames read but not yet released, in decode order, with their PTS.
48	held: VecDeque<(T, u64)>,
49	/// Presentation slots not yet taken, ascending.
50	slots: Vec<u64>,
51	/// The largest depth + 1 PTS read, ascending, with their source timestamps in nanoseconds:
52	/// all a deeper reorder or a tie is checked against.
53	highest: Vec<(u64, u128)>,
54	/// The last DTS released.
55	last: Option<i128>,
56	/// A flush fixed the group's earliest slot before enough frames were read to know it, so a
57	/// later frame of the group may present below it.
58	forced: bool,
59}
60
61impl<T> DeclaredClock<T> {
62	/// A clock for one group of a rendition reordering at most `depth` frames, from [`depth`].
63	pub(crate) fn new(depth: usize) -> Self {
64		Self {
65			depth,
66			earliest: None,
67			leading: depth,
68			held: VecDeque::new(),
69			slots: Vec::new(),
70			highest: Vec::new(),
71			last: None,
72			forced: false,
73		}
74	}
75
76	/// Restart the clock at the same declared depth.
77	pub(crate) fn restart(self) -> Self {
78		Self::new(self.depth)
79	}
80
81	/// Whether a flush fixed the group's earliest slot before enough frames were read to know it,
82	/// so the rest of the group may no longer fit the clock.
83	pub(crate) fn forced(&self) -> bool {
84		self.forced
85	}
86
87	/// How many frames are held.
88	#[cfg(test)]
89	pub(crate) fn len(&self) -> usize {
90		self.held.len()
91	}
92
93	/// Whether a frame presented at `pts` would follow more than the depth frames read before it
94	/// in presentation order, which [`Self::push`] refuses.
95	pub(crate) fn reorders_past(&self, pts: u64) -> bool {
96		self.highest.len() - self.highest.partition_point(|&(prior, _)| prior <= pts) > self.depth
97	}
98
99	/// Hold the group's next frame in decode order, presented at `pts` ticks, read from `source`.
100	pub(crate) fn push(&mut self, item: T, pts: u64, source: moq_net::Timestamp) -> crate::Result<()> {
101		if self.held.len() > self.depth {
102			return Err(ReorderError::Undrained.into());
103		}
104		let source = source.as_nanos()?;
105		// Only `highest` matters: a frame below all of it reorders past the depth.
106		let mut pts = pts;
107		for &(tick, prior) in &self.highest {
108			if prior < source && tick >= pts {
109				pts = tick.checked_add(1).ok_or(ReorderError::Tie)?;
110			}
111		}
112		if (self.highest.iter()).any(|&(tick, prior)| prior >= source && tick <= pts) {
113			return Err(ReorderError::Tie.into());
114		}
115		if self.reorders_past(pts) {
116			return Err(ReorderError::Reordered(self.depth).into());
117		}
118		let at = self.highest.partition_point(|&(prior, _)| prior <= pts);
119		self.highest.insert(at, (pts, source));
120		if self.highest.len() > self.depth + 1 {
121			self.highest.remove(0);
122		}
123		let at = self.slots.partition_point(|&slot| slot <= pts);
124		self.slots.insert(at, pts);
125		self.held.push_back((item, pts));
126		Ok(())
127	}
128
129	/// The next frame with its DTS in signed ticks and its PTS, past the tick it was pushed at if a
130	/// tie moved it, once the group's earliest slot is known, or at once when `flush` because the
131	/// group ended.
132	pub(crate) fn pop(&mut self, flush: bool) -> crate::Result<Option<(T, i128, u64)>> {
133		if self.held.is_empty() || (self.earliest.is_none() && !flush && self.held.len() <= self.depth) {
134			return Ok(None);
135		}
136		if self.earliest.is_none() && self.held.len() <= self.depth {
137			self.forced = true;
138		}
139		let earliest = *self.earliest.get_or_insert(self.slots[0]);
140		let dts = match self.leading {
141			0 => i128::from(self.slots.remove(0)),
142			leading => {
143				self.leading -= 1;
144				i128::from(earliest) - leading as i128
145			}
146		};
147		let (item, pts) = self.held.pop_front().expect("the held queue is nonempty");
148		if dts > i128::from(pts) || self.last.is_some_and(|last| dts <= last) {
149			return Err(ReorderError::Presentation.into());
150		}
151		self.last = Some(dts);
152		Ok(Some((item, dts, pts)))
153	}
154}
155
156/// Video whose frames do not fit the reorder depth it declares, so no decode clock can be
157/// authored for it.
158#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
159#[non_exhaustive]
160pub enum ReorderError {
161	/// The declared depth is deeper than the codec and level allow.
162	#[error("video reorder depth {reorder} exceeds the {max} that {codec} can reach")]
163	Depth {
164		/// The declared depth.
165		reorder: u8,
166		/// The deepest the codec and level allow.
167		max: u32,
168		/// The codec string.
169		codec: String,
170	},
171	/// A sequence header declares a deeper reorder than the track already declared.
172	#[error("video reorder depth {reorder} exceeds the {declared} the track declared")]
173	Deepened {
174		/// The depth the track declared.
175		declared: u8,
176		/// The deeper depth the sequence header declares.
177		reorder: u8,
178	},
179	/// A frame presents earlier than the declared depth lets it.
180	#[error("video reorders past its declared depth {0}")]
181	Reordered(usize),
182	/// The presentation slots leave no decode time at or before a frame's presentation.
183	#[error("video presentation slots cannot author increasing DTS at or before PTS")]
184	Presentation,
185	/// Two frames present at one timestamp.
186	#[error("video presents two frames at one timestamp")]
187	Tie,
188	/// A frame was read before the clock released the ones ahead of it.
189	#[error("the decode clock must be drained before reading another frame")]
190	Undrained,
191}
192
193#[cfg(test)]
194mod tests {
195	use super::*;
196
197	/// A B-pyramid (`max_num_reorder_frames` 2) in decode order, in 40 ms frames.
198	const PYRAMID: [u64; 9] = [0, 4, 2, 1, 3, 8, 6, 5, 7];
199	const FRAME: u64 = 3_600;
200
201	/// A source timestamp exactly on 90 kHz tick `pts`.
202	fn at(pts: u64) -> moq_net::Timestamp {
203		moq_net::Timestamp::from_scale(pts, 90_000).unwrap()
204	}
205
206	/// A flush before the group's first depth + 1 frames fixes its earliest slot by force; one
207	/// after them, or a release as it reads, does not.
208	#[test]
209	fn a_flush_before_the_lookahead_forces_the_earliest_slot() {
210		let mut early = DeclaredClock::new(2);
211		early.push((), PYRAMID[0], at(PYRAMID[0])).unwrap();
212		while early.pop(true).unwrap().is_some() {}
213		assert!(early.forced());
214
215		let mut late = DeclaredClock::new(2);
216		for &pts in &PYRAMID[..3] {
217			late.push((), pts, at(pts)).unwrap();
218		}
219		while late.pop(true).unwrap().is_some() {}
220		assert!(!late.forced());
221	}
222
223	/// The DTS of one group read through a declared clock of `depth`, released as each frame is
224	/// read, checking it never holds more than `depth` frames between reads.
225	fn declared_dts(depth: usize, read: &[u64]) -> Vec<i128> {
226		let mut clock = DeclaredClock::new(depth);
227		let mut out = Vec::new();
228		for &pts in read {
229			clock.push((), pts, at(pts)).unwrap();
230			while let Some(((), dts, _)) = clock.pop(false).unwrap() {
231				out.push(dts);
232			}
233			assert!(clock.len() <= depth);
234		}
235		while let Some(((), dts, _)) = clock.pop(true).unwrap() {
236			out.push(dts);
237		}
238		out
239	}
240
241	#[test]
242	fn declared_slots_shift_by_count_and_start_before_zero() {
243		let ticks = |frames: &[i128]| frames.iter().map(|i| i * FRAME as i128).collect::<Vec<_>>();
244		let leading = |dts: Vec<i128>| [vec![-2, -1], dts].concat();
245		assert_eq!(
246			declared_dts(2, &PYRAMID.map(|i| i * FRAME)),
247			leading(ticks(&[0, 1, 2, 3, 4, 5, 6]))
248		);
249		// References spaced wider than any frame period still take their slots by count.
250		let far = [0, 6, 10, 1, 2, 3, 4, 5, 7, 8, 9].map(|i| i * FRAME);
251		assert_eq!(declared_dts(2, &far), leading(ticks(&[0, 1, 2, 3, 4, 5, 6, 7, 8])));
252	}
253
254	/// Open-GOP leading pictures present before the keyframe that starts their group, so the
255	/// group's first frames decode below its earliest slot, not the keyframe's.
256	#[test]
257	fn leading_pictures_decode_before_the_keyframe() {
258		let read = [10, 8, 9, 14, 12, 11, 13];
259		assert_eq!(declared_dts(2, &read), [6, 7, 8, 9, 10, 11, 12]);
260		// A group that ends before the lookahead fills still takes its earliest slot.
261		assert_eq!(declared_dts(2, &read[..2]), [6, 7]);
262	}
263
264	#[test]
265	fn a_zero_depth_releases_each_frame_at_its_pts() {
266		let mut clock = DeclaredClock::new(0);
267		for (index, pts) in [0, 1, 90_000, u64::MAX].into_iter().enumerate() {
268			let source = moq_net::Timestamp::from_nanos(index as u64).unwrap();
269			clock.push(pts, pts, source).unwrap();
270			assert_eq!(clock.pop(false).unwrap(), Some((pts, i128::from(pts), pts)));
271			assert_eq!(clock.len(), 0);
272		}
273		clock.push(0, 0, at(0)).unwrap_err();
274	}
275
276	/// Distinct source timestamps that round onto one millisecond tick, as FLV clocks them, move
277	/// the later frame up to the next free tick; identical ones still fail.
278	#[test]
279	fn sub_tick_ties_move_to_the_next_free_tick() {
280		let micros = |micros: u64| moq_net::Timestamp::from_micros(micros).unwrap();
281		let released = |depth: usize, read: &[u64]| {
282			let mut clock = DeclaredClock::new(depth);
283			let mut out = Vec::new();
284			for &source in read {
285				let source = micros(source);
286				clock.push((), source.as_millis().unwrap() as u64, source)?;
287				while let Some(((), dts, pts)) = clock.pop(false)? {
288					out.push((dts, pts));
289				}
290			}
291			while let Some(((), dts, pts)) = clock.pop(true)? {
292				out.push((dts, pts));
293			}
294			crate::Result::Ok(out)
295		};
296		// MPEG-TS can carry a repeated timestamp one 90 kHz tick (11 µs) later.
297		assert_eq!(
298			released(0, &[182_815_000, 182_856_000, 182_856_011, 182_897_000]).unwrap(),
299			[
300				(182_815, 182_815),
301				(182_856, 182_856),
302				(182_857, 182_857),
303				(182_897, 182_897)
304			]
305		);
306		// A tie moved onto the next frame's tick moves that frame up in turn, however many share
307		// the tick.
308		assert_eq!(
309			released(0, &[10_000, 10_400, 11_000, 13_000]).unwrap(),
310			[(10, 10), (11, 11), (12, 12), (13, 13)]
311		);
312		assert_eq!(
313			released(0, &[40_000, 40_011, 40_022, 40_033, 80_000]).unwrap(),
314			[(40, 40), (41, 41), (42, 42), (43, 43), (80, 80)]
315		);
316		// Reordered frames tie the same way: the later-presented one moves.
317		assert_eq!(
318			released(1, &[0, 3_000, 1_000, 1_400, 4_000]).unwrap(),
319			[(-1, 0), (0, 3), (1, 1), (2, 2), (3, 4)]
320		);
321		released(0, &[10_000, 10_000]).unwrap_err();
322		// A frame presented below one already on its tick has nowhere to go.
323		released(1, &[0, 10_400, 10_000]).unwrap_err();
324	}
325
326	/// Flat or backward PTS read past the declared depth fail within depth + 1 frames, however
327	/// many follow and however large they are, rather than accumulate.
328	#[test]
329	fn malformed_presentation_is_refused_without_retaining_its_payload() {
330		for backwards in [false, true] {
331			for count in [16, 128, 1024] {
332				for size in [256, 16_384] {
333					let mut clock = DeclaredClock::new(2);
334					let refused = (0..count).position(|index| {
335						let pts = 90_000 - if backwards { index } else { 0 };
336						let refused = clock.push(vec![0u8; size], pts, at(pts)).is_err()
337							|| std::iter::from_fn(|| clock.pop(false).transpose()).any(|popped| popped.is_err());
338						assert!(clock.len() <= 2);
339						refused
340					});
341					assert!(
342						refused.is_some_and(|index| index <= 3),
343						"backwards={backwards} count={count}"
344					);
345				}
346			}
347		}
348	}
349
350	#[test]
351	fn a_declared_depth_fits_the_codec_level() {
352		use hang::catalog::{H264, VideoCodec};
353
354		let config = |codec: VideoCodec, size: Option<(u32, u32)>, reorder: u8| {
355			let mut config = VideoConfig::new(codec);
356			config.coded_width = size.map(|(width, _)| width);
357			config.coded_height = size.map(|(_, height)| height);
358			config.reorder = Some(reorder);
359			config
360		};
361		let h264 = |level| H264 {
362			profile: 100,
363			constraints: 0,
364			level,
365			inline: false,
366		};
367		let h265: VideoCodec = "hvc1.1.6.L123.B0".parse().unwrap();
368		let vp9: VideoCodec = "vp09.00.10.08".parse().unwrap();
369		let cases = [
370			// Level 4.0's 32768 macroblocks hold four 1920x1088 frames.
371			(config(h264(40).into(), Some((1920, 1080)), 4), true),
372			(config(h264(40).into(), Some((1920, 1080)), 5), false),
373			// Without a size, the deepest buffer any picture of the level gets.
374			(config(h264(40).into(), None, 16), true),
375			(config(h264(40).into(), None, 17), false),
376			// Level 4.1's MaxLumaPs holds six 1920x1080 pictures, one of them the current.
377			(config(h265.clone(), Some((1920, 1080)), 5), true),
378			(config(h265, Some((1920, 1080)), 6), false),
379			(config(vp9.clone(), None, 0), true),
380			(config(vp9, None, 1), false),
381		];
382		for (config, valid) in cases {
383			assert_eq!(depth(&config).is_ok(), valid, "{config:?}");
384		}
385		assert_eq!(depth(&VideoConfig::new(VideoCodec::VP8)).unwrap(), None);
386	}
387}