Skip to main content

moq_mux/catalog/
estimate.rs

1use std::sync::{Arc, Mutex, PoisonError};
2use std::time::Duration;
3
4use moq_net::Timestamp;
5
6/// The window over which bitrate, framerate, and delay are measured before they are reported.
7const RATE_WINDOW: Duration = Duration::from_secs(1);
8
9/// The frame rates a measurement snaps to. Anything else (a variable-rate source's average)
10/// publishes nothing, since consumers size clocks from the value (an fMP4 timescale of
11/// `framerate * 1000`).
12const FRAMERATES: [f64; 11] = [
13	24_000.0 / 1001.0,
14	24.0,
15	25.0,
16	30_000.0 / 1001.0,
17	30.0,
18	48.0,
19	50.0,
20	60_000.0 / 1001.0,
21	60.0,
22	100.0,
23	120.0,
24];
25
26/// How far a measurement may sit from the rate it snaps to: half the 0.1% gap between an NTSC
27/// rate and its integer neighbour, so no measurement is ambiguous between them.
28const FRAMERATE_TOLERANCE: f64 = 0.0005;
29
30/// The catalog fields a producer measures from the frames written to it.
31///
32/// An absent field is one to measure: whatever the config already carries when it reaches
33/// [`container::Producer::set`](crate::container::Producer::set) is authoritative and left alone,
34/// and the rest is detected and kept current.
35#[derive(Clone, Default, Debug, PartialEq)]
36#[non_exhaustive]
37pub struct Estimate {
38	/// The largest batch span or reorder delay written.
39	pub jitter: Option<Duration>,
40	/// The maximum bitrate in bits per second.
41	pub bitrate: Option<u64>,
42	/// How far the track reaches the transport behind the others: the least a frame's timestamp
43	/// trailed the highest one another track had already written, over a window of a second or
44	/// more, and the largest of those windows. Lateness only some frames have, such as B-frames
45	/// written after a later reference picture, is variable and left to `jitter` and the
46	/// receiver's own measurement.
47	///
48	/// Supplied as `Some(Duration::ZERO)`, it states the track trails nothing: nothing is measured,
49	/// and the catalog omits it, as it does an absent one.
50	pub delay: Option<Duration>,
51	/// The maximum frame rate in frames per second, when it is a standard one.
52	pub framerate: Option<f64>,
53}
54
55impl Estimate {
56	/// Set the jitter (or clear it with `None`).
57	pub fn with_jitter(mut self, jitter: impl Into<Option<Duration>>) -> Self {
58		self.jitter = jitter.into();
59		self
60	}
61
62	/// Set the bitrate in bits per second (or clear it with `None`).
63	pub fn with_bitrate(mut self, bitrate: impl Into<Option<u64>>) -> Self {
64		self.bitrate = bitrate.into();
65		self
66	}
67
68	/// Set the delay behind the other tracks (or clear it with `None`).
69	pub fn with_delay(mut self, delay: impl Into<Option<Duration>>) -> Self {
70		self.delay = delay.into();
71		self
72	}
73
74	/// Set the frame rate in frames per second (or clear it with `None`).
75	pub fn with_framerate(mut self, framerate: impl Into<Option<f64>>) -> Self {
76		self.framerate = framerate.into();
77		self
78	}
79}
80
81/// Measures the catalog jitter, bitrate, delay, and framerate of one track from the frames written
82/// to it, without reading a clock.
83///
84/// A [`container::Producer`](crate::container::Producer) created through the catalog owns one,
85/// feeds it as you write, and publishes the result automatically:
86///
87/// ```no_run
88/// # fn example<E: moq_mux::catalog::hang::CatalogExt>(
89/// #     catalog: moq_mux::catalog::Producer<E>,
90/// #     reserved: moq_mux::catalog::Reserved<E>,
91/// #     net: moq_net::track::Producer,
92/// #     config: hang::catalog::VideoConfig,
93/// #     frame: moq_mux::container::Frame,
94/// # ) -> moq_mux::Result<()> {
95/// use moq_mux::catalog::hang::Wire;
96/// use moq_mux::container::Kind;
97/// let mut track = reserved.video(net, Wire::legacy(Kind::Video), config)?;
98/// track.write(frame)?;
99/// # Ok(())
100/// # }
101/// ```
102///
103/// A standalone estimator has no other tracks to order against, so it never measures a delay.
104///
105/// Move-only (not `Clone`): it owns the running measurement for exactly one track.
106#[derive(Default)]
107pub(crate) struct Estimator {
108	jitter: Jitter,
109	bitrate: Bitrate,
110	/// The framerate and delay, measured over the same windows.
111	window: Window,
112	/// This track's place in the write order of every track sharing it.
113	seat: Seat,
114}
115
116impl Estimator {
117	/// Create an empty estimator.
118	pub fn new() -> Self {
119		Self::default()
120	}
121
122	/// Measure `delay` against the other tracks sharing `order`.
123	pub(crate) fn with_order(order: Order) -> Self {
124		Self {
125			seat: order.seat(),
126			..Self::default()
127		}
128	}
129
130	/// Observe a frame of `bytes` encoded bytes at presentation time `timestamp`, as written by
131	/// [`container::Producer::write`](crate::container::Producer::write). An
132	/// [unscaled](Timestamp::unscaled) timestamp has no time, so it measures nothing.
133	pub fn write(&mut self, timestamp: Timestamp, bytes: usize) {
134		self.rate(timestamp, bytes);
135		self.order(timestamp);
136	}
137
138	/// Count a write toward the bitrate and framerate only.
139	pub(crate) fn rate(&mut self, timestamp: Timestamp, bytes: usize) {
140		let Some(timestamp) = nanos(timestamp) else { return };
141		self.bitrate.write(timestamp, bytes);
142		self.window.write(timestamp);
143	}
144
145	/// Place a frame stamped `timestamp` in the write order. It trails by how far the highest
146	/// timestamp another track has already written is ahead of it: a frame the transport carries
147	/// after later media from another track has to be waited for by a consumer playing both.
148	///
149	/// A window's delay is the least of those trails, so one frame that trails nothing clears it.
150	/// Only a track every frame of which trails keeps one; the rest of the lateness varies from
151	/// frame to frame, which the receiver measures and `jitter` floors.
152	///
153	/// A frame with no other track to trail trails nothing, so a window holding frames from before
154	/// another track joined never reports the trail of the few after it.
155	pub(crate) fn order(&mut self, timestamp: Timestamp) {
156		let Some(timestamp) = nanos(timestamp) else { return };
157		let behind = self.seat.write(timestamp).unwrap_or_default();
158		self.window.trail(behind);
159	}
160
161	/// Close the current span at `end`, as [`container::Producer::cut`](crate::container::Producer::cut)
162	/// does for its group.
163	///
164	/// Bitrate is averaged over whole spans so a lone keyframe is never reported as the track
165	/// bitrate on its own. A boundary with no usable duration (an unbounded cut, a span holding one
166	/// frame) leaves the span open to fold into the next one, so nothing is lost by cutting often.
167	///
168	/// Framerate and delay are measured over windows that open and close here, a window closing
169	/// at the first cut once the highest timestamp has advanced a second past where it opened.
170	/// Nothing is reported for either before then.
171	pub fn cut(&mut self, end: Option<Timestamp>) {
172		self.bitrate.cut(end.and_then(nanos));
173		self.window.cut();
174	}
175
176	/// Discard the open bitrate span and this track's place in the write order, so nothing is
177	/// measured across a break in the timeline. See
178	/// [`container::Producer::discontinuity`](crate::container::Producer::discontinuity).
179	///
180	/// The track may resume at another offset from the others, so its delay is measured afresh in
181	/// the next window; the delay already measured stays.
182	pub fn discontinuity(&mut self) {
183		self.bitrate.discontinuity();
184		self.window.discontinuity();
185		self.seat.discontinuity();
186	}
187
188	/// Observe a frame's reorder delay (`PTS - DTS`), which raises the jitter to the decode buffer a
189	/// B-frame stream needs. Only a container knows this; the elementary stream carries no decode
190	/// time.
191	pub fn reorder(&mut self, delay: Duration) {
192		self.burst(delay);
193	}
194
195	/// Record the media duration emitted together by a container importer.
196	pub(crate) fn burst(&mut self, duration: Duration) {
197		self.jitter.max = self.jitter.max.max(duration);
198	}
199
200	/// The longest group seen so far, closed window or not, the open one included up to the
201	/// furthest content end stated, else the whole span written to that end: what a track that ends
202	/// before its first window closes declares as its join interval.
203	pub(crate) fn partial_interval(&self) -> Option<Duration> {
204		let window = &self.window;
205		let end = window.high.map(|high| high.max(window.reach.unwrap_or_default()));
206		match window.interval.max(window.group) {
207			// Measured from the last cut, as every closed group is.
208			Some(closed) => Some(
209				closed.max(
210					window
211						.cut
212						.zip(end)
213						.and_then(|(cut, end)| elapsed(cut, end))
214						.unwrap_or_default(),
215				),
216			),
217			None => elapsed(window.start?, end?),
218		}
219	}
220
221	/// Note that written content reaches `end`, as a fragment or a frame with a duration says.
222	pub(crate) fn reach(&mut self, end: Timestamp) {
223		let Some(end) = nanos(end) else { return };
224		self.window.reach = Some(self.window.reach.map_or(end, |reach| reach.max(end)));
225	}
226
227	/// Everything measured so far, with what a catalog rendition needs to decide when to publish it.
228	pub(crate) fn reading(&self) -> Reading {
229		Reading {
230			estimate: self.estimate(),
231			period: self.window.shortest,
232			interval: self.window.interval,
233		}
234	}
235
236	/// Everything measured so far.
237	///
238	/// Catalog-owned [`container::Producer`](crate::container::Producer) handles publish this
239	/// automatically when they cut or finish a group.
240	pub fn estimate(&self) -> Estimate {
241		Estimate {
242			jitter: self.jitter.current(),
243			bitrate: self.bitrate.current(),
244			delay: self.window.delay.filter(|delay| !delay.is_zero()),
245			framerate: self.window.framerate,
246		}
247	}
248}
249
250/// An [`Estimate`] with the measurements that pace its publishing.
251#[derive(Clone, Debug, Default)]
252pub(crate) struct Reading {
253	pub estimate: Estimate,
254	/// The shortest advance between frames, which a published `jitter` or `delay` rises in whole
255	/// steps of when no framerate says the frame duration.
256	pub period: Option<Duration>,
257	/// The longest group, once a window has closed: the track's measured join interval.
258	pub interval: Option<Duration>,
259}
260
261impl From<Estimate> for Reading {
262	fn from(estimate: Estimate) -> Self {
263		Self {
264			estimate,
265			period: None,
266			interval: None,
267		}
268	}
269}
270
271/// A frame time as scale-free nanoseconds.
272///
273/// Timestamps reaching an estimator can carry different timescales: a track normalizes them into
274/// its own on the way to the wire, but only there. `Timestamp` arithmetic refuses to mix scales, so
275/// a span anchored on one scale could never be timed against a frame on another. Since a span now
276/// survives a boundary it can't time, that would block the bitrate for the life of the track rather
277/// than for one group. Normalizing on the way in is what makes the carry-forward safe.
278///
279/// `None` for a scale-less track's [unscaled](Timestamp::unscaled) key, which has no time to
280/// measure, so every observation of one is skipped.
281fn nanos(timestamp: Timestamp) -> Option<u128> {
282	timestamp.as_nanos().ok()
283}
284
285/// The time from `start` to `end`, or `None` if it didn't advance (a B-frame presenting earlier, a
286/// span holding a single frame).
287fn elapsed(start: u128, end: u128) -> Option<Duration> {
288	let delta = end.checked_sub(start).filter(|delta| *delta > 0)?;
289	// Saturating rather than wrapping. A frame gap over 584 years is nonsense either way, and the
290	// clamp keeps this total instead of silently dropping the span.
291	Some(Duration::from_nanos(u64::try_from(delta).unwrap_or(u64::MAX)))
292}
293
294/// Tracks the maximum bitrate in bits per second, averaged over whole spans.
295///
296/// A span's bytes are only counted once it is closed, and the average is taken over at least
297/// [`RATE_WINDOW`] of media so a lone keyframe doesn't spike the reported value.
298#[derive(Default)]
299struct Bitrate {
300	span: Option<Span>,
301	window_bytes: u64,
302	window_duration: Duration,
303	max: Option<u64>,
304}
305
306impl Bitrate {
307	fn write(&mut self, ts: u128, bytes: usize) {
308		let span = self.span.get_or_insert(Span {
309			start: ts,
310			max: ts,
311			bytes: 0,
312		});
313
314		span.start = span.start.min(ts);
315		span.max = span.max.max(ts);
316		span.bytes = span.bytes.saturating_add(bytes as u64);
317	}
318
319	fn cut(&mut self, end: Option<u128>) {
320		let Some(span) = self.span.as_ref() else {
321			return;
322		};
323
324		let duration = end
325			.and_then(|end| elapsed(span.start, end))
326			.or_else(|| elapsed(span.start, span.max));
327
328		// Nothing to divide by yet. Leave the span open so its bytes join the next one rather than
329		// vanishing: a track cut after every frame (the one-group-per-packet audio shape) reaches
330		// this on every cut, and dropping the span there would leave the bitrate undetectable.
331		let Some(duration) = duration else {
332			return;
333		};
334
335		let span = self.span.take().expect("span is present");
336		self.window_bytes = self.window_bytes.saturating_add(span.bytes);
337		self.window_duration += duration;
338
339		if self.window_duration < RATE_WINDOW {
340			return;
341		}
342
343		let bitrate = bits_per_second(self.window_bytes, self.window_duration);
344		self.window_bytes = 0;
345		self.window_duration = Duration::ZERO;
346
347		if self.max.is_none_or(|max| bitrate > max) {
348			self.max = Some(bitrate);
349		}
350	}
351
352	fn discontinuity(&mut self) {
353		self.span = None;
354	}
355
356	fn current(&self) -> Option<u64> {
357		self.max
358	}
359}
360
361/// Tracks the maximum framerate and delay, measured over the same windows of at least
362/// [`RATE_WINDOW`] of advance in the highest timestamp, so they publish together.
363///
364/// The framerate is frames written per second of that advance, snapped to one of [`FRAMERATES`].
365/// Not per span like [`Bitrate`]: a reordered group spans more than its own frames (an open GOP's
366/// leading pictures present before its keyframe), while the highest timestamp advances one period
367/// per frame whatever the order. Sampled at cuts, so every window starts and ends at the same point
368/// of the group structure.
369///
370/// The interval is the longest advance of the highest timestamp from one cut to the next, a group's
371/// span, reported once a window closes and the largest across windows. A window lasts a second or a
372/// group, whichever is longer, so even one group longer than a second is measured whole.
373///
374/// The delay is the least trail behind the other tracks within a window, and the largest of those
375/// across windows. A constant offset is in every window, so it shows; lateness only some frames
376/// have, such as B-frame reorder, has a frame trailing nothing in every window, so it never does.
377/// Taking the least over a whole window, rather than over everything written so far, is what lets
378/// it only rise: a track that starts measuring on a frame that trails (a late join, a
379/// demand-driven start, a discontinuity) closes no window until a frame trailing less has had its
380/// chance.
381#[derive(Default)]
382struct Window {
383	/// The highest timestamp written, in scale-free nanoseconds.
384	high: Option<u128>,
385	/// The highest timestamp when the window opened.
386	open: Option<u128>,
387	/// Frames written since the window opened.
388	frames: u64,
389	/// The least trail behind the other tracks since the window opened, if any frame was ordered.
390	trail: Option<Duration>,
391	framerate: Option<f64>,
392	delay: Option<Duration>,
393	/// The shortest advance of the highest timestamp: a frame's duration, or a reordered group's
394	/// span of them.
395	shortest: Option<Duration>,
396	/// The highest timestamp at the previous cut, which the next cut's group span is measured from.
397	cut: Option<u128>,
398	/// The longest group span since the window opened.
399	group: Option<Duration>,
400	/// The longest group span of any closed window.
401	interval: Option<Duration>,
402	/// The lowest timestamp written since the timeline last broke.
403	start: Option<u128>,
404	/// The furthest content end a write stated, past its own timestamp, since the timeline last
405	/// broke: a fragment's or a timed frame's.
406	reach: Option<u128>,
407}
408
409impl Window {
410	fn write(&mut self, ts: u128) {
411		if let Some(advance) = self.high.and_then(|high| elapsed(high, ts)) {
412			self.shortest = Some(self.shortest.map_or(advance, |shortest| shortest.min(advance)));
413		}
414		self.high = Some(self.high.map_or(ts, |high| high.max(ts)));
415		self.start = Some(self.start.map_or(ts, |start| start.min(ts)));
416		self.frames += 1;
417	}
418
419	/// Count a frame's trail behind the other tracks toward the open window.
420	fn trail(&mut self, behind: Duration) {
421		if self.open.is_some() {
422			self.trail = Some(self.trail.map_or(behind, |trail| trail.min(behind)));
423		}
424	}
425
426	fn cut(&mut self) {
427		let Some(high) = self.high else {
428			return;
429		};
430		// A cut with nothing written since the last one bounds no group.
431		if let Some(span) = self.cut.and_then(|cut| elapsed(cut, high)) {
432			self.group = self.group.max(Some(span));
433		}
434		if self.cut.is_none_or(|cut| high > cut) {
435			self.cut = Some(high);
436		}
437		// The first window opens at a cut too, not at the first frame, which may be a join that
438		// starts partway into the group structure.
439		let Some(open) = self.open else {
440			self.reopen(high);
441			return;
442		};
443		let Some(duration) = elapsed(open, high).filter(|duration| *duration >= RATE_WINDOW) else {
444			return;
445		};
446		let measured = self.frames as f64 / duration.as_secs_f64();
447		let snapped = FRAMERATES
448			.into_iter()
449			.map(|rate| (rate, (measured - rate).abs() / rate))
450			.filter(|(_, error)| *error <= FRAMERATE_TOLERANCE)
451			.min_by(|a, b| a.1.total_cmp(&b.1))
452			.map(|(rate, _)| rate);
453		if let Some(framerate) = snapped
454			&& self.framerate.is_none_or(|max| framerate > max)
455		{
456			self.framerate = Some(framerate);
457		}
458		self.delay = self.delay.max(self.trail);
459		self.interval = self.interval.max(self.group);
460		self.reopen(high);
461	}
462
463	fn reopen(&mut self, high: u128) {
464		self.open = Some(high);
465		self.frames = 0;
466		self.trail = None;
467		self.group = None;
468	}
469
470	/// Time nothing across a break in the timeline.
471	fn discontinuity(&mut self) {
472		*self = Self {
473			framerate: self.framerate,
474			delay: self.delay,
475			shortest: self.shortest,
476			interval: self.interval,
477			..Self::default()
478		};
479	}
480}
481
482/// An open run of frames: everything written since the last boundary that could be timed.
483struct Span {
484	/// Scale-free nanoseconds, per [`nanos`].
485	start: u128,
486	max: u128,
487	bytes: u64,
488}
489
490fn bits_per_second(bytes: u64, duration: Duration) -> u64 {
491	let nanos = duration.as_nanos();
492	if nanos == 0 {
493		return 0;
494	}
495
496	let bits_per_second = (bytes as u128).saturating_mul(8).saturating_mul(1_000_000_000) / nanos;
497	bits_per_second.min(u64::MAX as u128) as u64
498}
499
500/// The largest batch span or reorder delay. Once advertised it never falls.
501#[derive(Default)]
502struct Jitter {
503	max: Duration,
504}
505
506impl Jitter {
507	fn current(&self) -> Option<Duration> {
508		(!self.max.is_zero()).then_some(self.max)
509	}
510}
511
512/// The highest timestamp each track on one catalog has written, which every frame's `delay` is
513/// measured against.
514///
515/// A frame is compared with the other tracks only: its own track's earlier frames say nothing
516/// about the interleave, and a B-frame trailing its own reference picture is already reorder
517/// jitter.
518///
519/// Every timestamp is a presentation time, written in decode order. A track with B-frames writes
520/// each reference picture before the B-frames presenting ahead of it, so its high runs ahead of
521/// what it writes, and frames of the other tracks written beside it trail that high too: another
522/// rendition's B-frames, and the audio of the same decode slot. The reference pictures, and that
523/// audio when it lines up with them, trail by nothing, which is why a track's `delay` is the
524/// least it trails rather than the most. Only a constant offset between tracks survives, and that
525/// is the one thing a receiver's measurement of each track against itself cannot see.
526#[derive(Clone, Default)]
527pub(crate) struct Order(Arc<Mutex<Highs>>);
528
529impl Order {
530	/// Take a place in the order for a new track.
531	fn seat(&self) -> Seat {
532		let index = self.0.lock().unwrap_or_else(PoisonError::into_inner).join();
533		Seat {
534			order: self.clone(),
535			index,
536		}
537	}
538}
539
540/// Every seated track's highest timestamp, plus the two largest, so a write is constant time
541/// however many tracks share the catalog.
542#[derive(Default)]
543struct Highs {
544	/// Indexed by seat; `None` is a free seat, `Some(None)` a track that has written nothing since
545	/// it joined or broke its timeline.
546	seats: Vec<Option<Option<u128>>>,
547	/// The largest high and its seat.
548	first: Option<(usize, u128)>,
549	/// The largest high on any other seat.
550	second: Option<(usize, u128)>,
551}
552
553impl Highs {
554	fn join(&mut self) -> usize {
555		if let Some(index) = self.seats.iter().position(Option::is_none) {
556			self.seats[index] = Some(None);
557			return index;
558		}
559		self.seats.push(Some(None));
560		self.seats.len() - 1
561	}
562
563	/// Raise `index`'s high to `timestamp` and return how far `timestamp` trails the others' highest.
564	fn write(&mut self, index: usize, timestamp: u128) -> Option<Duration> {
565		let others = match self.first {
566			Some((first, _)) if first == index => self.second,
567			first => first,
568		};
569
570		let high = self.seats[index]
571			.as_mut()
572			.expect("a seated track")
573			.get_or_insert(timestamp);
574		*high = (*high).max(timestamp);
575		let high = *high;
576
577		// Highs only rise, so the top two stay ordered by updating them in place.
578		match (self.first, self.second) {
579			(Some((first, _)), _) if first == index => self.first = Some((index, high)),
580			(Some((_, top)), _) if high > top => {
581				self.second = self.first;
582				self.first = Some((index, high));
583			}
584			(None, _) => self.first = Some((index, high)),
585			(_, Some((second, low))) if second == index || high > low => self.second = Some((index, high)),
586			(_, None) => self.second = Some((index, high)),
587			_ => {}
588		}
589
590		let (_, others) = others?;
591		elapsed(timestamp, others)
592	}
593
594	/// Forget `index`'s high, freeing its seat when `leave` is set.
595	fn clear(&mut self, index: usize, leave: bool) {
596		self.seats[index] = if leave { None } else { Some(None) };
597		if [self.first, self.second]
598			.iter()
599			.flatten()
600			.any(|(seat, _)| *seat == index)
601		{
602			self.rank();
603		}
604	}
605
606	/// Recompute the top two from every seat.
607	fn rank(&mut self) {
608		self.first = None;
609		self.second = None;
610		for (index, seat) in self.seats.iter().enumerate() {
611			let Some(high) = seat.flatten() else { continue };
612			match self.first {
613				Some((_, top)) if high <= top => {
614					if self.second.is_none_or(|(_, low)| high > low) {
615						self.second = Some((index, high));
616					}
617				}
618				first => {
619					self.second = first;
620					self.first = Some((index, high));
621				}
622			}
623		}
624	}
625}
626
627/// One track's place in an [`Order`], released when the track's estimator drops.
628struct Seat {
629	order: Order,
630	index: usize,
631}
632
633impl Default for Seat {
634	fn default() -> Self {
635		Order::default().seat()
636	}
637}
638
639impl Seat {
640	fn write(&self, timestamp: u128) -> Option<Duration> {
641		self.lock().write(self.index, timestamp)
642	}
643
644	/// A break in the timeline may resume anywhere, so the old high must not hold others back.
645	fn discontinuity(&self) {
646		self.lock().clear(self.index, false);
647	}
648
649	fn lock(&self) -> std::sync::MutexGuard<'_, Highs> {
650		self.order.0.lock().unwrap_or_else(PoisonError::into_inner)
651	}
652}
653
654impl Drop for Seat {
655	fn drop(&mut self) {
656		self.lock().clear(self.index, true);
657	}
658}
659
660#[cfg(test)]
661mod tests {
662	use super::*;
663
664	fn micros(value: u64) -> Timestamp {
665		Timestamp::from_micros(value).unwrap()
666	}
667
668	#[test]
669	fn decode_order_pts_gap_never_becomes_provisional_jitter() {
670		let mut estimator = Estimator::new();
671		for pts in [0, 120_000, 40_000, 80_000] {
672			estimator.write(micros(pts), 1);
673		}
674		assert_eq!(estimator.estimate().jitter, None);
675		estimator.reorder(Duration::from_millis(80));
676		assert_eq!(estimator.estimate().jitter, Some(Duration::from_millis(80)));
677	}
678
679	/// Estimators sharing one order, as the tracks of one catalog do.
680	fn tracks<const N: usize>() -> [Estimator; N] {
681		let order = Order::default();
682		std::array::from_fn(|_| Estimator::with_order(order.clone()))
683	}
684
685	fn ms(value: u64) -> Duration {
686		Duration::from_millis(value)
687	}
688
689	/// Write a frame at `millis` and close a group on it, as audio cut after every packet is.
690	/// Delay is measured over windows closed at cuts, so a test that never cuts measures none.
691	fn send(estimator: &mut Estimator, millis: u64) {
692		estimator.write(micros(millis * 1_000), 1);
693		estimator.cut(None);
694	}
695
696	/// Video at 20 ms and audio at 15 ms, interleaved `v0 v20 a0 a15 v40 a30 v60 a45 a60` and on
697	/// for two seconds: audio trails video by anything from nothing to 20 ms, which varies frame to
698	/// frame and so is no constant offset.
699	#[test]
700	fn an_interleave_is_not_delay() {
701		let [mut video, mut audio] = tracks();
702		for cycle in 0..34u64 {
703			let base = cycle * 60;
704			for (video_frame, pts) in [
705				(true, 0),
706				(true, 20),
707				(false, 0),
708				(false, 15),
709				(true, 40),
710				(false, 30),
711				(false, 45),
712			] {
713				let track = if video_frame { &mut video } else { &mut audio };
714				send(track, base + pts);
715			}
716		}
717		assert_eq!(audio.estimate().delay, None);
718		assert_eq!(video.estimate().delay, None);
719	}
720
721	/// A track every frame of which trails keeps the least of those trails: the constant offset,
722	/// without the lateness only some of its frames add.
723	#[test]
724	fn a_constant_offset_is_delay() {
725		let [mut video, mut audio] = tracks();
726		for i in 0..100u64 {
727			send(&mut video, 100 + i * 20);
728			// Every third frame trails a further 10 ms on top of the 100 ms offset.
729			let late = if i % 3 == 1 { 10 } else { 0 };
730			send(&mut audio, i * 20 - late);
731		}
732		assert_eq!(audio.estimate().delay, Some(ms(100)));
733		assert_eq!(video.estimate().delay, None);
734	}
735
736	/// The offset is measured over a whole window before it is reported, never from the first
737	/// frames alone.
738	#[test]
739	fn delay_waits_for_the_window() {
740		let [mut video, mut audio] = tracks();
741		for i in 0..40u64 {
742			send(&mut video, 100 + i * 20);
743			send(&mut audio, i * 20);
744		}
745		assert_eq!(audio.estimate().delay, None, "under a second measured");
746		for i in 40..60u64 {
747			send(&mut video, 100 + i * 20);
748			send(&mut audio, i * 20);
749		}
750		assert_eq!(audio.estimate().delay, Some(ms(100)));
751	}
752
753	/// A window closes at a cut once a second has passed, so a group longer than a second is a
754	/// window of its own: nothing is reported partway through it.
755	#[test]
756	fn a_window_lasts_a_group_when_the_group_is_longer_than_a_second() {
757		let [mut audio, mut video] = tracks();
758		// Video in two-second groups, cut where each opens, written 100 ms behind the audio.
759		for i in 0..250u64 {
760			send(&mut audio, 100 + i * 20);
761			if i % 100 == 0 {
762				video.cut(None);
763			}
764			video.write(micros(i * 20_000), 1);
765			let expected = (i >= 200).then_some(ms(100));
766			assert_eq!(video.estimate().delay, expected, "frame {i}");
767		}
768	}
769
770	/// The join interval is the longest group of the first window, a second or a group, whichever
771	/// is longer: two-second GOPs report two seconds once the second GOP closes, and audio cut every
772	/// frame reports its frame.
773	#[test]
774	fn the_interval_is_the_longest_group_of_a_window() {
775		let [mut audio, mut video] = tracks();
776		for i in 0..250u64 {
777			send(&mut audio, i * 20);
778			if i % 100 == 0 {
779				video.cut(None);
780			}
781			video.write(micros(i * 20_000), 1);
782			let expected = (i >= 200).then_some(ms(2000));
783			assert_eq!(video.reading().interval, expected, "frame {i}");
784		}
785		assert_eq!(audio.reading().interval, Some(ms(20)));
786	}
787
788	/// A track ending before its first window closes declares the longest group it saw, else the
789	/// whole span it wrote, to the furthest end a fragment stated.
790	#[test]
791	fn a_partial_interval_covers_a_lone_fragment() {
792		let mut fragment = Estimator::new();
793		fragment.write(micros(0), 1);
794		assert_eq!(fragment.partial_interval(), None, "a lone timestamp spans nothing");
795		fragment.reach(micros(800_000));
796		assert_eq!(fragment.partial_interval(), Some(ms(800)));
797
798		let mut video = Estimator::new();
799		for (ms, cut) in [(0, false), (300, true), (600, false)] {
800			if cut {
801				video.cut(None);
802			}
803			video.write(micros(ms * 1_000), 1);
804		}
805		video.cut(None);
806		// The second group holds the frames at 300 and 600ms, so with 300ms frames it runs to 900ms.
807		assert_eq!(video.partial_interval(), Some(ms(600)));
808
809		// A final group still open when the track ends counts too, to the end its content states.
810		let mut video = Estimator::new();
811		for ms in [0, 300] {
812			video.write(micros(ms * 1_000), 1);
813			video.cut(None);
814		}
815		video.write(micros(600_000), 1);
816		video.reach(micros(3_000_000));
817		assert_eq!(
818			video.partial_interval(),
819			Some(ms(2700)),
820			"the open group outlasts the closed one"
821		);
822	}
823
824	/// A longer group in a later window raises the interval; a discontinuity keeps it.
825	#[test]
826	fn the_interval_keeps_the_longest_group() {
827		let mut video = Estimator::new();
828		let mut pts = 0;
829		for gop in [1000, 1000, 3000, 1000] {
830			video.cut(None);
831			for _ in 0..gop / 20 {
832				video.write(micros(pts * 1_000), 1);
833				pts += 20;
834			}
835		}
836		video.cut(None);
837		assert_eq!(video.reading().interval, Some(ms(3000)));
838		video.discontinuity();
839		assert_eq!(video.reading().interval, Some(ms(3000)));
840	}
841
842	/// Two renditions of one 50 fps source with two B-frames (I0 P60 B20 B40 P120 B80 B100 …) and
843	/// audio, written in lockstep in decode order for three seconds: one frame of each track per
844	/// 20 ms. Tracks listed in `late` start writing at the third frame, as after a late join or a
845	/// discontinuity, so their first frame is a B-frame or audio trailing one.
846	///
847	/// From [moq-dev/moq#7579](https://github.com/moq-dev/moq/issues/7579). Every estimate along
848	/// the way is checked, since a catalog never lowers a `delay` it has published.
849	fn lockstep(declare_reorder: bool, late: &[usize]) -> [Estimate; 3] {
850		let mut tracks: [Estimator; 3] = tracks();
851		if declare_reorder {
852			// What the MPEG-TS and fMP4 importers report for this GOP: its largest PTS - DTS, with
853			// decoding starting one frame before the first PTS.
854			tracks[0].reorder(Duration::from_millis(60));
855			tracks[1].reorder(Duration::from_millis(60));
856		}
857		let decode_order = [0, 60, 20, 40].into_iter().chain((1..50u64).flat_map(|gop| {
858			let base = gop * 60;
859			[base + 60, base + 20, base + 40]
860		}));
861		for (tick, pts) in decode_order.enumerate() {
862			for (index, pts) in [pts, pts, tick as u64 * 20].into_iter().enumerate() {
863				if tick < 2 && late.contains(&index) {
864					continue;
865				}
866				send(&mut tracks[index], pts);
867				assert_eq!(tracks[index].estimate().delay, None, "track {index} at tick {tick}");
868			}
869		}
870		tracks.each_ref().map(Estimator::estimate)
871	}
872
873	/// B-frame reorder is never `delay`: not on the B-frame tracks, and not on the audio beside
874	/// them. Only some frames trail, by the reorder, which is variable lateness the receiver
875	/// already measures; counting it as `delay` too would buffer it twice.
876	#[test]
877	fn bframe_reorder_is_not_delay() {
878		let [hevc, avc, audio] = lockstep(false, &[]);
879		assert_eq!((hevc.jitter, hevc.delay), (None, None));
880		assert_eq!((avc.jitter, avc.delay), (None, None));
881		assert_eq!((audio.jitter, audio.delay), (None, None));
882
883		// A declared reorder is the video's jitter, and still nobody's delay.
884		let [hevc, avc, audio] = lockstep(true, &[]);
885		assert_eq!((hevc.jitter, hevc.delay), (Some(ms(60)), None));
886		assert_eq!((avc.jitter, avc.delay), (Some(ms(60)), None));
887		assert_eq!((audio.jitter, audio.delay), (None, None));
888	}
889
890	/// A track whose first measured frame trails, by the reorder only, never reports it.
891	#[test]
892	fn a_late_start_measures_no_reorder_delay() {
893		for late in [&[0, 2][..], &[2], &[0]] {
894			for declare_reorder in [false, true] {
895				let estimates = lockstep(declare_reorder, late);
896				assert!(estimates.iter().all(|estimate| estimate.delay.is_none()), "{late:?}");
897			}
898		}
899	}
900
901	/// Frames written before another track joins trail nothing, so the window they share with the
902	/// first frames after it holds no trail; the next window, with both tracks aligned, holds none
903	/// either.
904	#[test]
905	fn a_window_spanning_a_join_measures_no_delay() {
906		let [mut audio, mut video] = tracks();
907		for i in 0..50u64 {
908			send(&mut audio, i * 20);
909		}
910		// A joining video's reference picture lands ahead of the next audio frame.
911		send(&mut video, 1_040);
912		send(&mut audio, 1_000);
913		for i in 51..150u64 {
914			send(&mut video, i * 20);
915			send(&mut audio, i * 20);
916		}
917		assert_eq!(audio.estimate().delay, None);
918	}
919
920	#[test]
921	fn a_lone_track_never_measures_a_delay() {
922		let [mut video] = tracks();
923		// Decode order with B-frames: each trails a reference picture written before it.
924		for gop in 0..10u64 {
925			for pts in [0, 120, 40, 80] {
926				send(&mut video, gop * 160 + pts);
927			}
928		}
929		assert_eq!(video.estimate().delay, None);
930	}
931
932	/// A B-frame trailing its own track is reorder jitter, not a delay behind the other tracks.
933	#[test]
934	fn reorder_within_a_track_is_not_delay() {
935		let [mut video, mut audio] = tracks();
936		for gop in 0..10u64 {
937			send(&mut audio, gop * 160);
938			for pts in [0, 120, 40, 80] {
939				send(&mut video, gop * 160 + pts);
940			}
941		}
942		assert_eq!(video.estimate().delay, None);
943	}
944
945	/// A track that breaks its timeline may resume behind where it was, so its old high no longer
946	/// holds the others back.
947	#[test]
948	fn a_discontinuity_drops_the_tracks_high() {
949		let [mut ahead, mut steady] = tracks();
950		send(&mut ahead, 10_000);
951		ahead.discontinuity();
952		for i in 0..60u64 {
953			send(&mut ahead, 1_000 + i * 20);
954			send(&mut steady, 1_000 + i * 20);
955		}
956		assert_eq!(steady.estimate().delay, None);
957	}
958
959	/// A track that resumes behind where it was trails by its new offset, however little it
960	/// trailed before the break.
961	#[test]
962	fn a_discontinuity_measures_the_new_offset() {
963		let [mut video, mut audio] = tracks();
964		for i in 0..60u64 {
965			send(&mut video, i * 20);
966			send(&mut audio, i * 20);
967		}
968		assert_eq!(audio.estimate().delay, None);
969		audio.discontinuity();
970		for i in 0..60u64 {
971			send(&mut video, 2_000 + i * 20);
972			send(&mut audio, 1_800 + i * 20);
973		}
974		assert_eq!(audio.estimate().delay, Some(ms(200)));
975	}
976
977	#[test]
978	fn a_dropped_track_stops_holding_others_back() {
979		let order = Order::default();
980		let mut ahead = Estimator::with_order(order.clone());
981		send(&mut ahead, 10_000);
982		drop(ahead);
983
984		let mut steady = Estimator::with_order(order.clone());
985		let mut other = Estimator::with_order(order);
986		for i in 0..60u64 {
987			send(&mut other, 1_000 + i * 20);
988			send(&mut steady, 1_000 + i * 20);
989		}
990		assert_eq!(steady.estimate().delay, None);
991	}
992
993	/// The top two kept incrementally agree with a scan over every seat, through joins, leaves,
994	/// and breaks.
995	#[test]
996	fn highs_match_a_full_scan() {
997		let mut highs = Highs::default();
998		let mut live: Vec<usize> = Vec::new();
999		let mut state = 0x9e37_79b9_7f4a_7c15u64;
1000		let mut next = |bound: u64| {
1001			state ^= state << 13;
1002			state ^= state >> 7;
1003			state ^= state << 17;
1004			state % bound
1005		};
1006
1007		for step in 0..10_000u64 {
1008			match next(10) {
1009				0 if live.len() < 6 => live.push(highs.join()),
1010				1 if !live.is_empty() => {
1011					let index = live.swap_remove(next(live.len() as u64) as usize);
1012					highs.clear(index, true);
1013				}
1014				2 if !live.is_empty() => highs.clear(live[next(live.len() as u64) as usize], false),
1015				_ if !live.is_empty() => {
1016					let index = live[next(live.len() as u64) as usize];
1017					let timestamp = (step + next(500)) as u128;
1018					let others = live
1019						.iter()
1020						.filter(|seat| **seat != index)
1021						.filter_map(|seat| highs.seats[*seat].flatten())
1022						.max();
1023					let expected = others.and_then(|others| elapsed(timestamp, others));
1024					assert_eq!(highs.write(index, timestamp), expected, "step {step}");
1025				}
1026				_ => live.push(highs.join()),
1027			}
1028		}
1029	}
1030
1031	#[test]
1032	fn bitrate_waits_for_the_window_and_reports_the_maximum() {
1033		let mut estimator = Estimator::new();
1034
1035		estimator.write(micros(0), 100_000);
1036		estimator.write(micros(500_000), 100_000);
1037		estimator.cut(Some(micros(1_000_000)));
1038		assert_eq!(estimator.estimate().bitrate, Some(1_600_000));
1039
1040		// A quieter second of media doesn't lower the maximum.
1041		estimator.write(micros(1_000_000), 25_000);
1042		estimator.cut(Some(micros(2_000_000)));
1043		assert_eq!(estimator.estimate().bitrate, Some(1_600_000));
1044
1045		estimator.write(micros(2_000_000), 250_000);
1046		estimator.cut(Some(micros(3_000_000)));
1047		assert_eq!(estimator.estimate().bitrate, Some(2_000_000));
1048	}
1049
1050	/// A span that can't be timed stays open instead of being dropped, so a track cut after every
1051	/// frame (one group per packet, how the importer facade drives audio) still measures a bitrate.
1052	/// The unbounded cut is a no-op and the next frame's timestamp closes the span exactly.
1053	#[test]
1054	fn unbounded_cuts_never_drop_bytes() {
1055		let mut estimator = Estimator::new();
1056
1057		// 40 packets of 5 kB at 40ms spacing: 1 Mbps, one group per packet.
1058		for i in 0..40u64 {
1059			let ts = micros(i * 40_000);
1060			// What `container::Producer::write` does for the keyframe opening each group...
1061			estimator.cut(Some(ts));
1062			estimator.write(ts, 5_000);
1063			// ...and what the facade's per-frame close does right after.
1064			estimator.cut(None);
1065		}
1066
1067		assert_eq!(estimator.estimate().bitrate, Some(1_000_000));
1068	}
1069
1070	/// A track whose timestamps change scale mid-stream still measures. `Timestamp` arithmetic
1071	/// refuses to mix scales, and since a span now survives a boundary it can't time, an unnormalized
1072	/// anchor would block the bitrate for the life of the track instead of for one group.
1073	#[test]
1074	fn mixed_timescales_still_measure() {
1075		let mut estimator = Estimator::new();
1076
1077		// The opening frame is millisecond-scale (a clock stamp standing in for a missing PTS); the
1078		// rest are microsecond-scale, as a parsed elementary stream would be.
1079		estimator.write(Timestamp::from_millis(0).unwrap(), 5_000);
1080		for i in 1..40u64 {
1081			let ts = micros(i * 40_000);
1082			estimator.cut(Some(ts));
1083			estimator.write(ts, 5_000);
1084		}
1085
1086		let estimate = estimator.estimate();
1087		assert_eq!(estimate.bitrate, Some(1_000_000));
1088		assert_eq!(estimate.jitter, None);
1089	}
1090
1091	/// Write groups `groups` of `order.len()` frames at 25 fps, in decode order with `order` giving
1092	/// each frame's display offset from its keyframe, cutting at every keyframe like
1093	/// `container::Producer::write`. Group 0 starts a second in, so leading pictures stay positive.
1094	fn feed_groups(estimator: &mut Estimator, groups: std::ops::Range<u64>, order: &[i64]) {
1095		for group in groups {
1096			let keyframe = 25 + (group * order.len() as u64) as i64;
1097			for (i, &offset) in order.iter().enumerate() {
1098				let ts = micros(((keyframe + offset) as u64) * 40_000);
1099				if i == 0 {
1100					estimator.cut(Some(ts));
1101				}
1102				estimator.write(ts, 1_000);
1103			}
1104		}
1105	}
1106
1107	#[test]
1108	fn framerate_waits_for_the_window() {
1109		let mut estimator = Estimator::new();
1110		// Half a second of 25 fps.
1111		let order: Vec<i64> = (0..12).collect();
1112		feed_groups(&mut estimator, 0..1, &order);
1113		estimator.cut(None);
1114		assert_eq!(estimator.estimate().framerate, None);
1115
1116		feed_groups(&mut estimator, 1..5, &order);
1117		assert_eq!(estimator.estimate().framerate, Some(25.0));
1118	}
1119
1120	/// B-frames in decode order: every group presents a frame below the one written before it.
1121	#[test]
1122	fn framerate_counts_reordered_groups() {
1123		let mut estimator = Estimator::new();
1124		// IPBB in a 24-frame closed GOP.
1125		let mut order = vec![0];
1126		for quad in 0..(23 / 3) {
1127			let base = quad * 3;
1128			order.extend([base + 3, base + 1, base + 2]);
1129		}
1130		order.extend(22..24);
1131		assert_eq!(order.len(), 24);
1132		feed_groups(&mut estimator, 0..5, &order);
1133		assert_eq!(estimator.estimate().framerate, Some(25.0));
1134	}
1135
1136	/// An open GOP's leading pictures present before their keyframe, so a group spans more than
1137	/// its own frames: timing groups by their span would read 24 frames over 27 periods.
1138	#[test]
1139	fn framerate_counts_leading_pictures() {
1140		let mut estimator = Estimator::new();
1141		// Keyframe, then three leading B-frames presented before it, then the rest.
1142		let mut order = vec![0, -3, -2, -1];
1143		order.extend(1..21);
1144		assert_eq!(order.len(), 24);
1145		feed_groups(&mut estimator, 0..5, &order);
1146		assert_eq!(estimator.estimate().framerate, Some(25.0));
1147	}
1148
1149	/// 30000/1001 fps on a 90 kHz clock: no period is a whole number of nanoseconds, and the
1150	/// measurement is 0.1% from 30 fps.
1151	#[test]
1152	fn framerate_snaps_to_ntsc() {
1153		let mut estimator = Estimator::new();
1154		for i in 0..300u64 {
1155			let ts = Timestamp::from_scale(i * 3003, 90_000).unwrap();
1156			estimator.cut(Some(ts));
1157			estimator.write(ts, 1_000);
1158			estimator.cut(None);
1159		}
1160		assert_eq!(estimator.estimate().framerate, Some(30_000.0 / 1001.0));
1161	}
1162
1163	/// A variable-rate source whose windows average no standard rate publishes nothing.
1164	#[test]
1165	fn framerate_skips_nonstandard_rates() {
1166		let mut estimator = Estimator::new();
1167		// 27 fps: 37 ms apart, give or take.
1168		for i in 0..100u64 {
1169			let ts = micros(i * 37_037);
1170			estimator.cut(Some(ts));
1171			estimator.write(ts, 1_000);
1172		}
1173		assert_eq!(estimator.estimate().framerate, None);
1174	}
1175
1176	/// The highest rate over any window is reported, and a slower one doesn't lower it.
1177	#[test]
1178	fn framerate_reports_the_maximum() {
1179		let mut estimator = Estimator::new();
1180		let order: Vec<i64> = (0..25).collect();
1181		feed_groups(&mut estimator, 0..3, &order);
1182		assert_eq!(estimator.estimate().framerate, Some(25.0));
1183
1184		for i in 0..40u64 {
1185			let ts = micros(4_000_000 + i * 41_667);
1186			estimator.cut(Some(ts));
1187			estimator.write(ts, 1_000);
1188		}
1189		assert_eq!(estimator.estimate().framerate, Some(25.0), "24 fps doesn't lower it");
1190	}
1191
1192	/// A break in the timeline discards the open span rather than timing it across the gap, and
1193	/// resets the frame spacing so the gap is never mistaken for a frame duration.
1194	#[test]
1195	fn discontinuity_drops_the_open_span() {
1196		let mut estimator = Estimator::new();
1197
1198		estimator.write(micros(0), 100_000);
1199		estimator.discontinuity();
1200
1201		// Resumed 40 minutes later. Without the reset this would time 100 kB across the gap.
1202		estimator.write(micros(2_400_000_000), 100_000);
1203		estimator.cut(Some(micros(2_401_000_000)));
1204
1205		assert_eq!(
1206			estimator.estimate().bitrate,
1207			Some(800_000),
1208			"only the post-break span counts"
1209		);
1210		assert_eq!(estimator.estimate().jitter, None, "the gap is not a frame duration");
1211	}
1212
1213	/// Frames on either side of a break are never timed across it.
1214	#[test]
1215	fn discontinuity_resets_the_framerate_window() {
1216		let mut estimator = Estimator::new();
1217		for i in 0..10u64 {
1218			estimator.write(micros(i * 40_000), 1_000);
1219		}
1220		estimator.discontinuity();
1221
1222		// Resumed 40 minutes later at 25 fps. Timed across the gap it would read ~0 fps.
1223		for i in 0..60u64 {
1224			let ts = micros(2_400_000_000 + i * 40_000);
1225			estimator.cut(Some(ts));
1226			estimator.write(ts, 1_000);
1227		}
1228		assert_eq!(estimator.estimate().framerate, Some(25.0));
1229	}
1230}