use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::util::time::ticks_to_duration;
const REANCHOR_THRESHOLD: Duration = Duration::from_millis(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tolerance {
pub late: Duration,
pub early: Duration,
}
impl Tolerance {
pub const DEFAULT: Tolerance = Tolerance {
late: Duration::from_millis(100),
early: Duration::from_secs(1),
};
}
#[derive(Debug, Clone, Copy)]
struct Anchor {
at: Instant,
media: Duration,
}
#[derive(Debug, Default)]
pub struct MediaClock {
anchor: Mutex<Option<Anchor>>,
}
impl MediaClock {
pub fn new() -> MediaClock {
MediaClock::default()
}
fn lock(&self) -> std::sync::MutexGuard<'_, Option<Anchor>> {
self.anchor.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn observe(&self, pts: u64, rate: u32) {
self.observe_at(pts, rate, Instant::now());
}
pub fn observe_at(&self, pts: u64, rate: u32, now: Instant) {
let media = ticks_to_duration(pts, rate);
let mut a = self.lock();
match *a {
None => *a = Some(Anchor { at: now, media }),
Some(old) => {
let due = instant_for(old, media);
if let Some(early) = due.checked_duration_since(now) {
if early > REANCHOR_THRESHOLD {
debug!(
"media clock: frame {} ms early, re-anchoring",
early.as_millis()
);
*a = Some(Anchor { at: now, media });
}
}
}
}
}
pub fn reanchor_at(&self, pts: u64, rate: u32, now: Instant) {
let media = ticks_to_duration(pts, rate);
*self.lock() = Some(Anchor { at: now, media });
}
pub fn schedule(&self, pts: u64, rate: u32, now: Instant, tol: Tolerance) -> Instant {
let ok = |late: i128| {
late <= tol.late.as_nanos() as i128 && -late <= tol.early.as_nanos() as i128
};
match (self.lateness(pts, rate, now), self.instant_for(pts, rate)) {
(Some(late), Some(t)) if ok(late) => t,
(late, _) => {
if let Some(late) = late {
debug!(
"media clock: re-anchoring ({} ms {})",
late.unsigned_abs() / 1_000_000,
if late > 0 { "late" } else { "early" }
);
}
self.reanchor_at(pts, rate, now);
now
}
}
}
pub fn is_anchored(&self) -> bool {
self.lock().is_some()
}
pub fn instant_for(&self, pts: u64, rate: u32) -> Option<Instant> {
let media = ticks_to_duration(pts, rate);
self.lock().map(|a| instant_for(a, media))
}
pub fn media_time_at(&self, now: Instant) -> Option<Duration> {
self.lock().map(|a| {
if now >= a.at {
a.media + (now - a.at)
} else {
a.media.saturating_sub(a.at - now)
}
})
}
pub fn lateness(&self, pts: u64, rate: u32, now: Instant) -> Option<i128> {
let due = self.instant_for(pts, rate)?;
Some(if now >= due {
(now - due).as_nanos() as i128
} else {
-((due - now).as_nanos() as i128)
})
}
}
#[derive(Debug, Clone)]
pub struct SessionClock {
clock: Arc<MediaClock>,
pinned: Arc<Mutex<Option<Pinned>>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Pinned {
pts: u64,
rate: u32,
at: Instant,
}
impl SessionClock {
pub fn new(clock: Arc<MediaClock>) -> SessionClock {
SessionClock {
clock,
pinned: Arc::new(Mutex::new(None)),
}
}
pub fn clock(&self) -> &Arc<MediaClock> {
&self.clock
}
pub fn pin(&self, pts: u64, rate: u32, at: Instant) {
*self.pinned.lock().unwrap_or_else(|e| e.into_inner()) = Some(Pinned { pts, rate, at });
}
pub fn instant_for(&self, pts: u64, rate: u32) -> Option<Instant> {
let pinned = *self.pinned.lock().unwrap_or_else(|e| e.into_inner());
match pinned {
Some(p) if p.pts == pts && p.rate == rate => Some(p.at),
_ => self.clock.instant_for(pts, rate),
}
}
}
#[derive(Debug)]
pub struct SinkClock {
session: Option<SessionClock>,
own: MediaClock,
tol: Tolerance,
}
impl SinkClock {
pub fn private(tol: Tolerance) -> SinkClock {
SinkClock {
session: None,
own: MediaClock::new(),
tol,
}
}
pub fn shared(clock: SessionClock) -> SinkClock {
SinkClock {
session: Some(clock),
own: MediaClock::new(),
tol: Tolerance::DEFAULT,
}
}
pub fn new(session: Option<SessionClock>, tol: Tolerance) -> SinkClock {
match session {
Some(c) => SinkClock::shared(c),
None => SinkClock::private(tol),
}
}
pub fn is_shared(&self) -> bool {
self.session.is_some()
}
pub fn instant(&self, pts: u64, rate: u32, now: Instant) -> Instant {
match &self.session {
Some(s) => match s.instant_for(pts, rate) {
Some(t) => t,
None => s.clock.schedule(pts, rate, now, self.tol),
},
None => self.own.schedule(pts, rate, now, self.tol),
}
}
pub fn instant_for(&self, pts: u64, rate: u32) -> Option<Instant> {
match &self.session {
Some(s) => s.instant_for(pts, rate),
None => self.own.instant_for(pts, rate),
}
}
}
fn instant_for(a: Anchor, media: Duration) -> Instant {
if media >= a.media {
a.at + (media - a.media)
} else {
a.at.checked_sub(a.media - media).unwrap_or(a.at)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn anchors_on_first_frame() {
let c = MediaClock::new();
let t0 = Instant::now();
assert!(c.instant_for(0, 90_000).is_none());
c.observe_at(9_000, 90_000, t0); assert_eq!(c.instant_for(9_000, 90_000), Some(t0));
assert_eq!(
c.instant_for(18_000, 90_000),
Some(t0 + Duration::from_millis(100))
);
assert_eq!(
c.instant_for(9_600, 48_000),
Some(t0 + Duration::from_millis(100))
);
assert_eq!(
c.instant_for(0, 48_000),
Some(t0 - Duration::from_millis(100))
);
assert_eq!(
c.media_time_at(t0 + Duration::from_millis(50)),
Some(Duration::from_millis(150))
);
}
#[test]
fn moves_earlier_never_later() {
let c = MediaClock::new();
let t0 = Instant::now();
c.observe_at(0, 90_000, t0 + Duration::from_millis(40));
c.observe_at(3_000, 90_000, t0 + Duration::from_millis(200));
assert_eq!(
c.instant_for(0, 90_000),
Some(t0 + Duration::from_millis(40))
);
assert_eq!(
c.lateness(3_000, 90_000, t0 + Duration::from_millis(200)),
Some(126_666_667) );
c.observe_at(90_000, 90_000, t0 + Duration::from_millis(1010));
assert_eq!(
c.instant_for(0, 90_000),
Some(t0 + Duration::from_millis(10))
);
c.observe_at(180_000, 90_000, t0 + Duration::from_micros(2_009_500));
assert_eq!(
c.instant_for(0, 90_000),
Some(t0 + Duration::from_millis(10))
);
assert!(c.lateness(0, 90_000, t0).unwrap() < 0);
c.reanchor_at(0, 90_000, t0 + Duration::from_secs(5));
assert_eq!(
c.instant_for(90_000, 90_000),
Some(t0 + Duration::from_secs(6))
);
}
#[test]
fn schedule_keeps_early_frames_and_reanchors_far_ones() {
let c = MediaClock::new();
let tol = Tolerance::DEFAULT;
let t0 = Instant::now();
let ms = Duration::from_millis;
assert_eq!(c.schedule(0, 90_000, t0, tol), t0);
assert_eq!(c.schedule(9_000, 90_000, t0 + ms(50), tol), t0 + ms(100));
assert_eq!(c.schedule(18_000, 90_000, t0 + ms(280), tol), t0 + ms(200));
assert_eq!(c.schedule(27_000, 90_000, t0 + ms(600), tol), t0 + ms(600));
assert_eq!(c.instant_for(36_000, 90_000), Some(t0 + ms(700)));
let t = t0 + ms(700);
assert_eq!(c.schedule(36_000 + 900_000, 90_000, t, tol), t);
assert_eq!(c.instant_for(499_200 + 4_800, 48_000), Some(t + ms(100)));
}
#[test]
fn sink_clocks() {
let t0 = Instant::now();
let ms = Duration::from_millis;
let session = Arc::new(MediaClock::new());
let va = SessionClock::new(session.clone());
let a = SinkClock::shared(va.clone());
let b = SinkClock::shared(SessionClock::new(session.clone()));
assert!(a.is_shared());
session.schedule(0, 90_000, t0, Tolerance::DEFAULT);
assert_eq!(a.instant(0, 90_000, t0 + ms(300)), t0);
assert_eq!(b.instant(9_000, 90_000, t0 + ms(5)), t0 + ms(100));
let at = session.instant_for(3_000, 90_000).unwrap();
session.reanchor_at(6_000, 90_000, t0 + ms(500));
va.pin(3_000, 90_000, at);
assert_eq!(a.instant(3_000, 90_000, t0 + ms(510)), at);
assert_eq!(
a.instant_for(3_000, 48_000),
session.instant_for(3_000, 48_000)
);
assert_eq!(
b.instant(3_000, 90_000, t0 + ms(510)),
t0 + ms(466) + Duration::from_micros(666) + Duration::from_nanos(667)
);
let lone = SinkClock::new(
Some(SessionClock::new(Arc::new(MediaClock::new()))),
Tolerance::DEFAULT,
);
assert_eq!(lone.instant(90_000, 90_000, t0), t0);
let p = SinkClock::new(None, Tolerance::DEFAULT);
assert!(!p.is_shared());
assert_eq!(p.instant(0, 90_000, t0), t0);
assert_eq!(p.instant(3_000, 90_000, t0 + ms(400)), t0 + ms(400));
assert_eq!(p.instant_for(3_000, 90_000), Some(t0 + ms(400)));
}
}