1use std::collections::VecDeque;
2
3use hang::catalog::VideoConfig;
4
5pub(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
25pub(crate) struct DeclaredClock<T> {
42 depth: usize,
43 earliest: Option<u64>,
45 leading: usize,
47 held: VecDeque<(T, u64)>,
49 slots: Vec<u64>,
51 highest: Vec<(u64, u128)>,
54 last: Option<i128>,
56 forced: bool,
59}
60
61impl<T> DeclaredClock<T> {
62 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 pub(crate) fn restart(self) -> Self {
78 Self::new(self.depth)
79 }
80
81 pub(crate) fn forced(&self) -> bool {
84 self.forced
85 }
86
87 #[cfg(test)]
89 pub(crate) fn len(&self) -> usize {
90 self.held.len()
91 }
92
93 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
159#[non_exhaustive]
160pub enum ReorderError {
161 #[error("video reorder depth {reorder} exceeds the {max} that {codec} can reach")]
163 Depth {
164 reorder: u8,
166 max: u32,
168 codec: String,
170 },
171 #[error("video reorder depth {reorder} exceeds the {declared} the track declared")]
173 Deepened {
174 declared: u8,
176 reorder: u8,
178 },
179 #[error("video reorders past its declared depth {0}")]
181 Reordered(usize),
182 #[error("video presentation slots cannot author increasing DTS at or before PTS")]
184 Presentation,
185 #[error("video presents two frames at one timestamp")]
187 Tie,
188 #[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 const PYRAMID: [u64; 9] = [0, 4, 2, 1, 3, 8, 6, 5, 7];
199 const FRAME: u64 = 3_600;
200
201 fn at(pts: u64) -> moq_net::Timestamp {
203 moq_net::Timestamp::from_scale(pts, 90_000).unwrap()
204 }
205
206 #[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 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 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 #[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 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 #[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 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 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 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 released(1, &[0, 10_400, 10_000]).unwrap_err();
324 }
325
326 #[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 (config(h264(40).into(), Some((1920, 1080)), 4), true),
372 (config(h264(40).into(), Some((1920, 1080)), 5), false),
373 (config(h264(40).into(), None, 16), true),
375 (config(h264(40).into(), None, 17), false),
376 (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}