1use std::sync::{Arc, Mutex, PoisonError};
2use std::time::Duration;
3
4use moq_net::Timestamp;
5
6const RATE_WINDOW: Duration = Duration::from_secs(1);
8
9const 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
26const FRAMERATE_TOLERANCE: f64 = 0.0005;
29
30#[derive(Clone, Default, Debug, PartialEq)]
36#[non_exhaustive]
37pub struct Estimate {
38 pub jitter: Option<Duration>,
40 pub bitrate: Option<u64>,
42 pub delay: Option<Duration>,
51 pub framerate: Option<f64>,
53}
54
55impl Estimate {
56 pub fn with_jitter(mut self, jitter: impl Into<Option<Duration>>) -> Self {
58 self.jitter = jitter.into();
59 self
60 }
61
62 pub fn with_bitrate(mut self, bitrate: impl Into<Option<u64>>) -> Self {
64 self.bitrate = bitrate.into();
65 self
66 }
67
68 pub fn with_delay(mut self, delay: impl Into<Option<Duration>>) -> Self {
70 self.delay = delay.into();
71 self
72 }
73
74 pub fn with_framerate(mut self, framerate: impl Into<Option<f64>>) -> Self {
76 self.framerate = framerate.into();
77 self
78 }
79}
80
81#[derive(Default)]
107pub(crate) struct Estimator {
108 jitter: Jitter,
109 bitrate: Bitrate,
110 window: Window,
112 seat: Seat,
114}
115
116impl Estimator {
117 pub fn new() -> Self {
119 Self::default()
120 }
121
122 pub(crate) fn with_order(order: Order) -> Self {
124 Self {
125 seat: order.seat(),
126 ..Self::default()
127 }
128 }
129
130 pub fn write(&mut self, timestamp: Timestamp, bytes: usize) {
134 self.rate(timestamp, bytes);
135 self.order(timestamp);
136 }
137
138 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 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 pub fn cut(&mut self, end: Option<Timestamp>) {
172 self.bitrate.cut(end.and_then(nanos));
173 self.window.cut();
174 }
175
176 pub fn discontinuity(&mut self) {
183 self.bitrate.discontinuity();
184 self.window.discontinuity();
185 self.seat.discontinuity();
186 }
187
188 pub fn reorder(&mut self, delay: Duration) {
192 self.burst(delay);
193 }
194
195 pub(crate) fn burst(&mut self, duration: Duration) {
197 self.jitter.max = self.jitter.max.max(duration);
198 }
199
200 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 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 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 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 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#[derive(Clone, Debug, Default)]
252pub(crate) struct Reading {
253 pub estimate: Estimate,
254 pub period: Option<Duration>,
257 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
271fn nanos(timestamp: Timestamp) -> Option<u128> {
282 timestamp.as_nanos().ok()
283}
284
285fn elapsed(start: u128, end: u128) -> Option<Duration> {
288 let delta = end.checked_sub(start).filter(|delta| *delta > 0)?;
289 Some(Duration::from_nanos(u64::try_from(delta).unwrap_or(u64::MAX)))
292}
293
294#[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 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#[derive(Default)]
382struct Window {
383 high: Option<u128>,
385 open: Option<u128>,
387 frames: u64,
389 trail: Option<Duration>,
391 framerate: Option<f64>,
392 delay: Option<Duration>,
393 shortest: Option<Duration>,
396 cut: Option<u128>,
398 group: Option<Duration>,
400 interval: Option<Duration>,
402 start: Option<u128>,
404 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 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 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 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 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
482struct Span {
484 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#[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#[derive(Clone, Default)]
527pub(crate) struct Order(Arc<Mutex<Highs>>);
528
529impl Order {
530 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#[derive(Default)]
543struct Highs {
544 seats: Vec<Option<Option<u128>>>,
547 first: Option<(usize, u128)>,
549 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 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 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 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 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
627struct 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 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 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 fn send(estimator: &mut Estimator, millis: u64) {
692 estimator.write(micros(millis * 1_000), 1);
693 estimator.cut(None);
694 }
695
696 #[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 #[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 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 #[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 #[test]
756 fn a_window_lasts_a_group_when_the_group_is_longer_than_a_second() {
757 let [mut audio, mut video] = tracks();
758 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 #[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 #[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 assert_eq!(video.partial_interval(), Some(ms(600)));
808
809 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 #[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 fn lockstep(declare_reorder: bool, late: &[usize]) -> [Estimate; 3] {
850 let mut tracks: [Estimator; 3] = tracks();
851 if declare_reorder {
852 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 #[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 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 #[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 #[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 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 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 #[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 #[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 #[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 #[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 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 #[test]
1054 fn unbounded_cuts_never_drop_bytes() {
1055 let mut estimator = Estimator::new();
1056
1057 for i in 0..40u64 {
1059 let ts = micros(i * 40_000);
1060 estimator.cut(Some(ts));
1062 estimator.write(ts, 5_000);
1063 estimator.cut(None);
1065 }
1066
1067 assert_eq!(estimator.estimate().bitrate, Some(1_000_000));
1068 }
1069
1070 #[test]
1074 fn mixed_timescales_still_measure() {
1075 let mut estimator = Estimator::new();
1076
1077 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 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 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 #[test]
1122 fn framerate_counts_reordered_groups() {
1123 let mut estimator = Estimator::new();
1124 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 #[test]
1139 fn framerate_counts_leading_pictures() {
1140 let mut estimator = Estimator::new();
1141 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 #[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 #[test]
1165 fn framerate_skips_nonstandard_rates() {
1166 let mut estimator = Estimator::new();
1167 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 #[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 #[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 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 #[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 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}