1#![forbid(unsafe_code)]
23#![deny(missing_docs)]
24
25pub mod sync;
26pub use sync::{AlignedSample, StreamAligner, StreamSpec, SyncConfig};
27
28pub const DEFAULT_SMOOTHING_HALFTIME: f64 = 90.0;
32
33pub const SAMPLES_BETWEEN_CLOCKSYNCS: u8 = 50;
37
38pub const MIN_CLOCKSYNC_INTERVAL: f64 = 0.5;
42
43pub mod flags {
49 pub const NONE: u32 = 0;
51 pub const CLOCKSYNC: u32 = 1;
53 pub const DEJITTER: u32 = 2;
55 pub const MONOTONIZE: u32 = 4;
57 pub const THREADSAFE: u32 = 8;
59 pub const ALL: u32 = 1 | 2 | 4 | 8;
61 pub const DRIFT: u32 = 16;
66 pub const DEVICE_DELAY: u32 = 32;
71}
72
73#[derive(Debug, Clone, PartialEq)]
77pub struct Dejitterer {
78 pub t0: u32,
84 pub samples_since_t0: u32,
86 pub w0: f64,
88 pub w1: f64,
90 pub p00: f64,
92 pub p11: f64,
94 pub p01: f64,
96 pub lam: f64,
98}
99
100impl Default for Dejitterer {
101 fn default() -> Self {
105 Dejitterer {
106 t0: 0,
107 samples_since_t0: 0,
108 w0: 0.0,
109 w1: 0.0,
110 p00: 1e10,
111 p11: 1e10,
112 p01: 0.0,
113 lam: 0.0,
114 }
115 }
116}
117
118impl Dejitterer {
119 pub fn new(t0: f64, srate: f64, halftime: f64) -> Self {
125 let mut d = Dejitterer {
126 t0: t0 as u32,
127 ..Default::default()
128 };
129 if srate > 0.0 {
130 d.w1 = 1. / srate;
131 d.lam = 2f64.powf(-1. / (srate * halftime));
132 }
133 d
134 }
135
136 pub fn is_initialized(&self) -> bool {
142 self.t0 != 0
143 }
144
145 pub fn smoothing_applicable(&self) -> bool {
147 self.lam > 0.0
148 }
149
150 pub fn dejitter(&mut self, t: f64) -> f64 {
155 if !self.smoothing_applicable() {
156 return t;
157 }
158
159 let t = t - self.t0 as f64;
161
162 let u1 = self.samples_since_t0 as f64;
163 self.samples_since_t0 = self.samples_since_t0.wrapping_add(1);
164
165 let pi0 = self.p00 + u1 * self.p01;
166 let pi1 = self.p01 + u1 * self.p11;
167 let al = t - (self.w0 + u1 * self.w1);
168 let g_inv = 1. / (self.lam + pi0 + pi1 * u1);
169 let il_ = 1. / self.lam;
170
171 self.p00 = il_ * (self.p00 - pi0 * pi0 * g_inv);
172 self.p01 = il_ * (self.p01 - pi0 * pi1 * g_inv);
173 self.p11 = il_ * (self.p11 - pi1 * pi1 * g_inv);
174 self.w0 += al * (self.p00 + self.p01 * u1);
175 self.w1 += al * (self.p01 + self.p11 * u1);
176
177 self.w0 + u1 * self.w1 + self.t0 as f64
178 }
179
180 pub fn skip_samples(&mut self, skipped: u32) {
184 self.samples_since_t0 = self.samples_since_t0.wrapping_add(skipped);
185 }
186}
187
188const DRIFT_WINDOW: usize = 64;
190
191const MIN_DRIFT_SPAN: f64 = 0.5;
193
194const MAX_DRIFT_RATE: f64 = 0.01;
196
197#[derive(Debug, Clone, Copy, PartialEq)]
199struct DriftObs {
200 local_time: f64,
202 offset: f64,
204 rtt: f64,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq)]
213pub struct DriftFit {
214 pub t_ref: f64,
216 pub offset: f64,
218 pub drift: f64,
220}
221
222impl DriftFit {
223 #[inline]
229 pub fn offset_for_remote(self, remote_ts: f64) -> f64 {
230 let denom = 1.0 - self.drift;
231 if denom.abs() < 0.5 {
232 return self.offset;
233 }
234 (self.offset + self.drift * (remote_ts - self.t_ref)) / denom
235 }
236
237 #[inline]
239 pub fn offset_at_local(self, local_t: f64) -> f64 {
240 self.offset + self.drift * (local_t - self.t_ref)
241 }
242}
243
244#[derive(Debug, Default, Clone)]
252pub struct DriftModel {
253 obs: Vec<DriftObs>,
254 fit: Option<DriftFit>,
255}
256
257impl DriftModel {
258 pub fn new() -> Self {
260 Self::default()
261 }
262
263 pub fn reset(&mut self) {
266 self.obs.clear();
267 self.fit = None;
268 }
269
270 pub fn len(&self) -> usize {
272 self.obs.len()
273 }
274
275 pub fn is_empty(&self) -> bool {
277 self.obs.is_empty()
278 }
279
280 pub fn fit(&self) -> Option<DriftFit> {
282 self.fit
283 }
284
285 pub fn drift(&self) -> Option<f64> {
288 self.fit.map(|f| f.drift)
289 }
290
291 pub fn offset_for_remote(&self, remote_ts: f64) -> Option<f64> {
293 self.fit.map(|f| f.offset_for_remote(remote_ts))
294 }
295
296 pub fn update(&mut self, local_time: f64, offset: f64, rtt: f64) -> DriftFit {
302 if !local_time.is_finite() || !offset.is_finite() || !rtt.is_finite() {
303 return self.fit.unwrap_or(DriftFit {
304 t_ref: 0.0,
305 offset: 0.0,
306 drift: 0.0,
307 });
308 }
309 let rtt = rtt.max(1e-6);
310 if self.obs.len() >= DRIFT_WINDOW {
311 self.obs.remove(0);
312 }
313 self.obs.push(DriftObs {
314 local_time,
315 offset,
316 rtt,
317 });
318 let fit = self.compute_fit();
319 self.fit = Some(fit);
320 fit
321 }
322
323 fn compute_fit(&self) -> DriftFit {
324 let last = self.obs[self.obs.len() - 1];
325 if self.obs.len() == 1 {
326 return DriftFit {
327 t_ref: last.local_time,
328 offset: last.offset,
329 drift: 0.0,
330 };
331 }
332 let t_min = self
333 .obs
334 .iter()
335 .map(|o| o.local_time)
336 .fold(f64::INFINITY, f64::min);
337 let t_max = self
338 .obs
339 .iter()
340 .map(|o| o.local_time)
341 .fold(f64::NEG_INFINITY, f64::max);
342 if t_max - t_min < MIN_DRIFT_SPAN {
343 let mut sw = 0.0;
345 let mut sy = 0.0;
346 for o in &self.obs {
347 let w = 1.0 / (o.rtt * o.rtt);
348 sw += w;
349 sy += w * o.offset;
350 }
351 return DriftFit {
352 t_ref: last.local_time,
353 offset: sy / sw,
354 drift: 0.0,
355 };
356 }
357
358 let t_ref = last.local_time;
360 let first = weighted_line(&self.obs, t_ref, None);
361
362 if self.obs.len() >= 4 {
365 let mut res: Vec<f64> = self
366 .obs
367 .iter()
368 .map(|o| (o.offset - first.offset_at_local(o.local_time)).abs())
369 .collect();
370 res.sort_by(f64::total_cmp);
371 let mad = res[res.len() / 2];
372 let refined = weighted_line(&self.obs, t_ref, Some((first, mad)));
373 if refined.drift.is_finite() && refined.offset.is_finite() {
374 return refined;
375 }
376 }
377 first
378 }
379}
380
381fn weighted_line(obs: &[DriftObs], t_ref: f64, reject: Option<(DriftFit, f64)>) -> DriftFit {
382 let mut sw = 0.0;
383 let mut sx = 0.0;
384 let mut sy = 0.0;
385 let mut sxx = 0.0;
386 let mut sxy = 0.0;
387 let mut kept = 0usize;
388 for o in obs {
389 let mut w = 1.0 / (o.rtt * o.rtt);
390 if let Some((prev, mad)) = reject {
391 let err = (o.offset - prev.offset_at_local(o.local_time)).abs();
392 let limit = (3.0 * mad).max(2.0 * o.rtt).max(1e-5);
393 if err > limit {
394 w *= (limit / err) * (limit / err);
397 }
398 }
399 let x = o.local_time - t_ref;
400 sw += w;
401 sx += w * x;
402 sy += w * o.offset;
403 sxx += w * x * x;
404 sxy += w * x * o.offset;
405 kept += 1;
406 }
407 if kept < 2 || sw <= 0.0 {
408 let last = obs[obs.len() - 1];
409 return DriftFit {
410 t_ref,
411 offset: last.offset,
412 drift: 0.0,
413 };
414 }
415 let det = sw * sxx - sx * sx;
416 if det.abs() < 1e-18 {
417 return DriftFit {
418 t_ref,
419 offset: sy / sw,
420 drift: 0.0,
421 };
422 }
423 let raw_drift = (sw * sxy - sx * sy) / det;
424 let drift = raw_drift.clamp(-MAX_DRIFT_RATE, MAX_DRIFT_RATE);
425 let offset = (sy - drift * sx) / sw;
426 DriftFit {
427 t_ref,
428 offset,
429 drift,
430 }
431}
432
433pub trait OffsetSource {
438 fn correction(&mut self) -> f64;
440 fn smooth_correction(&mut self, _remote_ts: f64) -> f64 {
443 self.correction()
444 }
445 fn srate(&mut self) -> f64;
447 fn was_reset(&mut self) -> bool;
449 fn clock(&mut self) -> f64;
451}
452
453pub struct PostProcessor {
455 options: u32,
456 halftime: f64,
457 device_delay: f64,
458 dejitter: Dejitterer,
459 samples_since_last_clocksync: u8,
460 next_query_time: f64,
461 last_offset: f64,
462 last_value: f64,
463}
464
465impl PostProcessor {
466 pub fn new() -> Self {
471 PostProcessor {
472 options: flags::NONE,
473 halftime: DEFAULT_SMOOTHING_HALFTIME,
474 device_delay: 0.0,
475 dejitter: Dejitterer::default(),
476 samples_since_last_clocksync: SAMPLES_BETWEEN_CLOCKSYNCS,
477 next_query_time: 0.0,
478 last_offset: 0.0,
479 last_value: f64::MIN,
480 }
481 }
482
483 pub fn set_halftime(&mut self, halftime: f64) {
485 self.halftime = halftime;
486 }
487
488 pub fn set_device_delay(&mut self, delay_s: f64) {
491 if delay_s.is_finite() {
492 self.device_delay = delay_s;
493 }
494 }
495
496 pub fn device_delay(&self) -> f64 {
498 self.device_delay
499 }
500
501 pub fn options(&self) -> u32 {
503 self.options
504 }
505
506 pub fn dejitterer(&self) -> &Dejitterer {
508 &self.dejitter
509 }
510
511 pub fn set_options(&mut self, options: u32) {
516 let changed = self.options ^ options;
517 if changed & flags::DEJITTER != 0 {
518 self.dejitter = Dejitterer::default();
519 }
520 if changed & flags::MONOTONIZE != 0 {
521 self.last_value = f64::MIN;
522 }
523 self.options = options;
524 }
525
526 pub fn process(&mut self, value: f64, src: &mut impl OffsetSource) -> f64 {
531 let mut value = value;
532
533 if self.options & flags::DRIFT != 0 {
534 if src.was_reset() {
537 self.last_value = f64::MIN;
538 self.dejitter = Dejitterer::default();
539 }
540 value += src.smooth_correction(value);
541 } else if self.options & flags::CLOCKSYNC != 0 {
542 self.samples_since_last_clocksync = self.samples_since_last_clocksync.saturating_add(1);
545 if self.samples_since_last_clocksync > SAMPLES_BETWEEN_CLOCKSYNCS
546 && src.clock() > self.next_query_time
547 {
548 self.last_offset = src.correction();
549 self.samples_since_last_clocksync = 0;
550 if src.was_reset() {
551 self.last_offset = src.correction();
552 self.last_value = f64::MIN;
553 self.dejitter = Dejitterer::default();
554 }
555 self.next_query_time = src.clock() + MIN_CLOCKSYNC_INTERVAL;
556 }
557 value += self.last_offset;
558 }
559
560 if self.options & flags::DEVICE_DELAY != 0 {
561 value -= self.device_delay;
562 }
563
564 if self.options & flags::DEJITTER != 0 {
565 if !self.dejitter.is_initialized() {
566 let srate = src.srate();
567 self.dejitter = Dejitterer::new(value, srate, self.halftime);
568 }
569 value = self.dejitter.dejitter(value);
570 }
571
572 if self.options & flags::MONOTONIZE != 0 {
573 if value < self.last_value {
574 value = self.last_value;
575 } else {
576 self.last_value = value;
577 }
578 }
579
580 value
581 }
582
583 pub fn skip_samples(&mut self, skipped: u32) {
585 if self.options & flags::DEJITTER != 0 && self.dejitter.smoothing_applicable() {
586 self.dejitter.skip_samples(skipped);
587 }
588 }
589}
590
591impl Default for PostProcessor {
592 fn default() -> Self {
593 Self::new()
594 }
595}
596
597#[derive(Debug, Clone)]
599pub struct FixedSource {
600 pub offset: f64,
602 pub srate: f64,
604 pub reset: bool,
606 pub now: f64,
608}
609
610impl OffsetSource for FixedSource {
611 fn correction(&mut self) -> f64 {
612 self.offset
613 }
614 fn srate(&mut self) -> f64 {
615 self.srate
616 }
617 fn was_reset(&mut self) -> bool {
618 self.reset
619 }
620 fn clock(&mut self) -> f64 {
621 self.now
622 }
623}
624
625#[cfg(test)]
626mod tests {
627 use super::*;
628
629 fn src(srate: f64) -> FixedSource {
630 FixedSource {
631 offset: 0.0,
632 srate,
633 reset: false,
634 now: 1e9,
635 }
636 }
637
638 #[test]
639 fn no_stage_changes_a_timestamp() {
640 let mut p = PostProcessor::new();
641 let mut s = src(1.0);
642 for t in [2.0, 3.1, 3.0, 5.0, 5.9, 7.1] {
643 assert_eq!(p.process(t, &mut s), t);
644 }
645 }
646
647 #[test]
648 fn clock_sync_adds_the_offset() {
649 let mut p = PostProcessor::new();
651 p.set_options(flags::CLOCKSYNC);
652 let mut s = src(1.0);
653 s.offset = -50.0;
654 for t in [2.0, 3.1, 3.0, 5.0, 5.9, 7.1] {
655 assert!((p.process(t, &mut s) - (t - 50.0)).abs() < 1e-12);
656 }
657 }
658
659 #[test]
660 fn the_clamp_never_lets_a_timestamp_go_backward() {
661 let mut p = PostProcessor::new();
663 p.set_options(flags::MONOTONIZE);
664 let mut s = src(1.0);
665 let input = [2.0, 3.1, 3.0, 5.0, 5.9, 7.1];
666 let want = [2.0, 3.1, 3.1, 5.0, 5.9, 7.1];
667 for (i, t) in input.iter().enumerate() {
668 assert!(
669 (p.process(*t, &mut s) - want[i]).abs() < 1e-12,
670 "sample {i}"
671 );
672 }
673 }
674
675 #[test]
676 fn a_stage_change_clears_that_state() {
677 let mut p = PostProcessor::new();
678 p.set_options(flags::MONOTONIZE);
679 let mut s = src(1.0);
680 p.process(100.0, &mut s);
681 p.set_options(flags::NONE);
683 p.set_options(flags::MONOTONIZE);
684 assert_eq!(p.process(2.0, &mut s), 2.0);
685 }
686
687 #[test]
688 fn a_rate_of_zero_leaves_the_filter_off() {
689 let d = Dejitterer::new(1000.0, 0.0, 90.0);
690 assert!(!d.smoothing_applicable());
691 let mut d = d;
692 assert_eq!(d.dejitter(1234.5), 1234.5);
693 }
694
695 #[test]
696 fn the_baseline_truncates_to_a_whole_number() {
697 let d = Dejitterer::new(1000.75, 100.0, 90.0);
699 assert_eq!(d.t0, 1000);
700 assert!(d.is_initialized());
701 }
702
703 #[test]
704 fn a_first_timestamp_below_one_reads_as_uninitialized() {
705 let d = Dejitterer::new(0.5, 100.0, 90.0);
708 assert_eq!(d.t0, 0);
709 assert!(!d.is_initialized());
710 }
711
712 #[test]
713 fn the_filter_converges_on_a_clean_ramp() {
714 let srate = 100.0;
715 let t0 = 5000.0;
716 let mut d = Dejitterer::new(t0, srate, 90.0);
717 d.dejitter(t0);
718 for i in 0..2000 {
719 let t = t0 + i as f64 / srate;
720 d.dejitter(t);
721 }
722 assert!((d.w1 - 1.0 / srate).abs() < 1e-6, "slope {}", d.w1);
724 assert!(d.w0.abs() < 0.1, "intercept {}", d.w0);
725 }
726
727 #[test]
728 fn the_filter_removes_a_constant_latency_from_the_slope() {
729 let srate = 100.0;
731 let t0 = 5000.0;
732 let latency = 0.05;
733 let mut d = Dejitterer::new(t0, srate, 90.0);
734 d.dejitter(t0);
735 for i in 0..5000 {
736 d.dejitter(t0 + i as f64 / srate + latency);
737 }
738 assert!((d.w1 - 1.0 / srate).abs() < 1e-6);
739 assert!((d.w0 - latency).abs() < 0.1, "intercept {}", d.w0);
740 }
741
742 #[test]
743 fn skipped_samples_move_the_counter() {
744 let mut d = Dejitterer::new(1000.0, 100.0, 90.0);
745 d.dejitter(1000.0);
746 let before = d.samples_since_t0;
747 d.skip_samples(7);
748 assert_eq!(d.samples_since_t0, before + 7);
749 }
750
751 #[test]
752 fn loss_aware_skip_keeps_first_timestamp_after_100_sample_gap_accurate() {
753 let srate = 100.0;
754 let dt = 1.0 / srate;
755 let t0 = 5000.0;
756
757 let mut with_skip = PostProcessor::new();
758 with_skip.set_options(flags::DEJITTER);
759 let mut without_skip = PostProcessor::new();
760 without_skip.set_options(flags::DEJITTER);
761 let mut s = src(srate);
762
763 for i in 0..200 {
765 let t = t0 + i as f64 * dt;
766 let a = with_skip.process(t, &mut s);
767 let b = without_skip.process(t, &mut s);
768 assert_eq!(a.to_bits(), b.to_bits(), "bit-exact with zero loss at {i}");
769 }
770
771 let true_after = t0 + 300.0 * dt;
773 with_skip.skip_samples(100);
774 let smoothed_with = with_skip.process(true_after, &mut s);
775 let smoothed_without = without_skip.process(true_after, &mut s);
776
777 assert!(
778 (smoothed_with - true_after).abs() < dt,
779 "expected error < {dt} s, got {}",
780 (smoothed_with - true_after).abs()
781 );
782 assert!(
784 (true_after - smoothed_without) > 50.0 * dt,
785 "expected large lag without skip_samples, got {}",
786 true_after - smoothed_without
787 );
788 }
789
790 #[test]
791 fn clock_sync_refreshes_at_most_twice_per_second() {
792 let mut p = PostProcessor::new();
793 p.set_options(flags::CLOCKSYNC);
794 let mut s = src(1.0);
795 s.offset = 1.0;
796 s.now = 100.0;
797 p.process(0.0, &mut s);
799 s.offset = 99.0;
800 for _ in 0..50 {
802 let got = p.process(0.0, &mut s);
803 assert!((got - 1.0).abs() < 1e-12, "the offset changed too early");
804 }
805 assert!((p.process(0.0, &mut s) - 1.0).abs() < 1e-12);
807 s.now = 101.0;
809 assert!((p.process(0.0, &mut s) - 99.0).abs() < 1e-12);
810 }
811
812 #[test]
813 fn a_reset_gives_the_filter_a_new_baseline() {
814 let mut p = PostProcessor::new();
818 p.set_options(flags::CLOCKSYNC | flags::DEJITTER);
819 let mut s = src(100.0);
820 s.now = 100.0;
821
822 p.process(5000.0, &mut s);
823 assert_eq!(p.dejitterer().t0, 5000);
824
825 for i in 1..60 {
828 p.process(5000.0 + i as f64 / 100.0, &mut s);
829 }
830 assert_eq!(p.dejitterer().t0, 5000, "no query fired yet");
831
832 s.reset = true;
834 s.now = 101.0;
835 p.process(9000.0, &mut s);
836 assert_eq!(p.dejitterer().t0, 9000, "the reset gives a new baseline");
837 }
838
839 #[test]
840 fn the_clamp_state_clears_on_a_reset() {
841 let mut p = PostProcessor::new();
847 p.set_options(flags::CLOCKSYNC | flags::MONOTONIZE);
848 let mut s = src(100.0);
849 s.now = 100.0;
850
851 p.process(500.0, &mut s);
852 for _ in 0..55 {
853 p.process(500.0, &mut s);
854 }
855 assert!((p.process(10.0, &mut s) - 500.0).abs() < 1e-12);
858
859 s.reset = true;
862 s.now = 101.0;
863 assert!((p.process(10.0, &mut s) - 10.0).abs() < 1e-12);
864 }
865
866 #[test]
867 fn drift_model_recovers_slope_rejects_rtt_spikes_and_removes_burst_steps() {
868 let mut model = DriftModel::new();
869 let true_offset = |t: f64| 10.0 + 50e-6 * (t - 1000.0);
871
872 for k in 0..20 {
873 let t = 1000.0 + (k as f64) * 2.0;
874 let (noise, rtt) = if k == 5 {
876 (0.008, 0.020)
877 } else if k == 12 {
878 (-0.006, 0.015)
879 } else {
880 (((k % 3) as f64 - 1.0) * 15e-6, 0.0005)
881 };
882 model.update(t, true_offset(t) + noise, rtt);
883 }
884
885 let fit = model.fit().expect("fitted drift model");
886 assert!(
887 (fit.drift - 50e-6).abs() < 1e-6,
888 "expected drift ~50 ppm, got {:.3} ppm",
889 fit.drift * 1e6
890 );
891 let t_local = 1039.0;
895 let true_off = true_offset(t_local);
896 let remote_ts = t_local - true_off;
897 let pred_off = fit.offset_for_remote(remote_ts);
898 assert!(
899 (pred_off - true_off).abs() < 20e-6,
900 "expected smooth error < 20 us, got {:.1} us",
901 (pred_off - true_off).abs() * 1e6
902 );
903
904 let before = model
907 .offset_for_remote(1039.99 - true_offset(1039.99))
908 .unwrap();
909 model.update(1040.0, true_offset(1040.0), 0.0005);
910 let after = model
911 .offset_for_remote(1040.01 - true_offset(1040.01))
912 .unwrap();
913 let jump = ((after - before) - 50e-6 * 0.02).abs();
914 assert!(
915 jump < 10e-6,
916 "expected smooth burst transition (< 10 us), got {:.1} us",
917 jump * 1e6
918 );
919 }
920
921 #[test]
922 fn device_delay_is_opt_in_and_default_timestamps_are_unchanged() {
923 let mut default_pp = PostProcessor::new();
924 default_pp.set_device_delay(0.025);
925 let mut s = src(100.0);
926 assert_eq!(
928 default_pp.process(500.0, &mut s).to_bits(),
929 500.0f64.to_bits()
930 );
931
932 default_pp.set_options(flags::DEVICE_DELAY);
934 assert!((default_pp.process(500.025, &mut s) - 500.0).abs() < 1e-12);
935 }
936}