1use kio::clock::Wall;
33use std::{
34 sync::{Arc, Mutex, PoisonError},
35 time::Duration,
36};
37
38use hang::catalog::MAX_SAFE_INTEGER;
39use kio::clock::Instant;
40
41fn moq_micros(wall: Wall) -> i128 {
43 let since = |from: Wall, to: Wall| to.saturating_duration_since(from).as_micros() as i128;
44 since(moq_net::time::EPOCH, wall) - since(wall, moq_net::time::EPOCH)
45}
46
47pub(crate) fn host_wall() -> Option<Wall> {
49 set(kio::clock::wall())
50}
51
52fn set(now: Wall) -> Option<Wall> {
54 #[cfg(test)]
55 let now = HOST_WALL.get().unwrap_or(now);
56 (moq_micros(now) >= 0).then_some(now)
57}
58
59#[cfg(test)]
60thread_local! {
61 static HOST_WALL: std::cell::Cell<Option<Wall>> = const { std::cell::Cell::new(None) };
63}
64
65#[cfg(test)]
67pub(crate) fn fake_host_wall(now: Wall) {
68 HOST_WALL.set(Some(now));
69}
70
71fn wall_clock(wall: Wall) -> crate::Result<hang::catalog::Clock> {
73 let micros = moq_micros(wall);
75 if micros < 0 {
76 return Err(hang::Error::InvalidWall(0).into());
77 }
78 let wall = u64::try_from(micros).unwrap_or(u64::MAX);
79 if wall > MAX_SAFE_INTEGER {
80 return Err(hang::Error::InvalidWall(wall).into());
81 }
82 Ok(hang::catalog::Clock::new(moq_net::Timestamp::from_micros(wall)?)?)
83}
84
85#[derive(Clone, Debug)]
93pub struct Clock {
94 source: kio::clock::Clock,
96 timeline: Arc<Mutex<Timeline>>,
97 wall: Option<hang::catalog::Clock>,
100}
101
102const SLEW: u64 = 2_000;
105
106const SETTLED: i128 = 1_000_000;
109
110fn unix_nanos(wall: Wall) -> i128 {
112 wall.saturating_duration_since(Wall::UNIX_EPOCH).as_nanos() as i128
113}
114
115#[derive(Debug)]
117struct Timeline {
118 instant: Instant,
120 suspended: Duration,
121 reading: u64,
123 zero: Option<i128>,
126}
127
128impl Timeline {
129 fn start(source: &kio::clock::Clock, instant: Instant, reading: u64) -> Arc<Mutex<Self>> {
131 let now = source.now();
132 let ahead = now.saturating_duration_since(instant).as_nanos() as i128
133 - instant.saturating_duration_since(now).as_nanos() as i128;
134 Arc::new(Mutex::new(Self {
135 instant,
136 suspended: source.suspended(),
137 reading,
138 zero: set(source.wall()).map(|wall| unix_nanos(wall) - ahead - reading as i128),
139 }))
140 }
141
142 fn read(&mut self, instant: Instant, suspended: Duration, wall: Option<Wall>) -> u64 {
147 let elapsed = instant.saturating_duration_since(self.instant) + suspended.saturating_sub(self.suspended);
149 self.instant = self.instant.max(instant);
150 self.suspended = self.suspended.max(suspended);
151
152 let elapsed = elapsed.as_nanos() as u64;
154 let free = self.reading.saturating_add(elapsed);
155 let error = match (self.zero, wall) {
156 (Some(zero), Some(wall)) => unix_nanos(wall) - zero - free as i128,
157 _ => 0,
158 };
159 let cap = (elapsed / SLEW) as i128;
160 let nudge = if error.abs() <= SETTLED {
161 0
162 } else {
163 error.clamp(-cap, cap)
164 };
165 self.reading = (free as i128 + nudge) as u64;
167 self.reading
168 }
169}
170
171impl Clock {
172 pub const TIMESCALE: moq_net::Timescale = moq_net::Timescale::MICRO;
177
178 const LEAD: Duration = Duration::from_secs(10);
184
185 pub fn new() -> Self {
190 let source = kio::clock::Clock::current();
191 Self {
192 timeline: Timeline::start(&source, source.now(), Self::LEAD.as_nanos() as u64),
193 wall: set(source.wall()).and_then(|now| wall_clock(now.checked_sub(Self::LEAD)?).ok()),
194 source,
195 }
196 }
197
198 pub fn at(epoch: Instant, wall: Wall) -> crate::Result<Self> {
204 let wall = Some(wall_clock(wall)?);
205 let source = kio::clock::Clock::current();
206 Ok(Self {
207 timeline: Timeline::start(&source, epoch, 0),
208 source,
209 wall,
210 })
211 }
212
213 pub(crate) fn arrival(&self, since: Duration) -> crate::Result<Self> {
219 let unmappable = || crate::Error::UnmappableTimestamp(format!("{since:?} puts PTS zero before 2020"));
220 let wall = match set(self.source.wall()) {
221 Some(now) => {
222 let zero = now.checked_sub(since).ok_or_else(unmappable)?;
223 Some(wall_clock(zero).map_err(|_| unmappable())?)
224 }
225 None if since.as_micros() > MAX_SAFE_INTEGER as u128 => return Err(unmappable()),
228 None => None,
229 };
230 let reading = u64::try_from(since.as_nanos()).map_err(|_| unmappable())?;
231 Ok(Self {
232 timeline: Timeline::start(&self.source, self.source.now(), reading),
233 source: self.source.clone(),
234 wall,
235 })
236 }
237
238 pub(crate) fn placed(&self, pts: Duration, wall: Wall) -> crate::Result<Self> {
244 let unmappable = |why: &str| crate::Error::UnmappableTimestamp(format!("{pts:?} at {wall:?} {why}"));
245 let zero = wall
246 .checked_sub(pts)
247 .and_then(|zero| wall_clock(zero).ok())
248 .ok_or_else(|| unmappable("puts PTS zero before 2020"))?;
249 self.mapped(zero, unmappable)
250 }
251
252 pub(crate) fn unmapped(&self) -> Self {
255 Self {
256 wall: None,
257 ..self.clone()
258 }
259 }
260
261 pub(crate) fn exact(wall: hang::catalog::Clock) -> crate::Result<hang::catalog::Clock> {
266 let unmappable = |why: &str| crate::Error::UnmappableTimestamp(format!("root clock {wall:?} {why}"));
267 let scale = wall
268 .wall()
269 .scale()
270 .ok_or_else(|| unmappable("has no timescale"))?
271 .as_u64() as u128;
272 let scaled = wall.wall().value() as u128 * Self::TIMESCALE.as_u64() as u128;
273 if !scaled.is_multiple_of(scale) {
274 return Err(unmappable("is no whole microsecond"));
275 }
276 let micros = u64::try_from(scaled / scale).map_err(|_| unmappable("overflows the clock"))?;
277 Ok(hang::catalog::Clock::new(moq_net::Timestamp::from_micros(micros)?)?)
278 }
279
280 pub(crate) fn adopted(&self, wall: hang::catalog::Clock) -> crate::Result<Self> {
285 self.mapped(wall, |why| {
286 crate::Error::UnmappableTimestamp(format!("root clock {wall:?} {why}"))
287 })
288 }
289
290 fn mapped(&self, zero: hang::catalog::Clock, unmappable: impl Fn(&str) -> crate::Error) -> crate::Result<Self> {
295 let now = set(self.source.wall()).ok_or_else(|| unmappable("needs the host wall clock, which is unset"))?;
296 let zero_micros = zero.wall().as_micros().map_err(|_| unmappable("has no timescale"))?;
298 let reading =
299 u64::try_from(moq_micros(now) - zero_micros as i128).map_err(|_| unmappable("puts PTS zero after now"))?;
300 Ok(Self {
301 timeline: Timeline::start(&self.source, self.source.now(), reading * 1_000),
302 source: self.source.clone(),
303 wall: Some(zero),
304 })
305 }
306
307 pub(crate) fn reading(&self, wall: Wall) -> crate::Result<i128> {
311 Ok(moq_micros(wall) - self.mapping()?.wall().as_micros()? as i128)
312 }
313
314 fn mapping(&self) -> crate::Result<hang::catalog::Clock> {
316 self.wall
317 .ok_or_else(|| crate::Error::UnmappableTimestamp("the broadcast has no wall mapping".to_string()))
318 }
319
320 pub fn now(&self) -> moq_net::Timestamp {
322 let (_, reading) = self.read();
323 moq_net::Timestamp::from_micros(reading / 1_000).expect("an instant elapsed duration fits in a timestamp")
324 }
325
326 fn read(&self) -> (Instant, u64) {
328 let mut timeline = self.timeline.lock().unwrap_or_else(PoisonError::into_inner);
329 let now = self.source.now();
331 let reading = timeline.read(now, self.source.suspended(), set(self.source.wall()));
332 (now, reading)
333 }
334
335 pub(crate) fn instant(&self) -> Instant {
338 self.source.now()
339 }
340
341 pub fn capture(&self, at: Instant) -> crate::Result<moq_net::Timestamp> {
347 let (now, reading) = self.read();
348 let before = now.checked_duration_since(at).ok_or(crate::Error::InvalidCapture)?;
349 let nanos = reading
350 .checked_sub(before.as_nanos() as u64)
351 .ok_or(crate::Error::InvalidCapture)?;
352 Ok(moq_net::Timestamp::from_micros(nanos / 1_000).expect("an instant elapsed duration fits in a timestamp"))
353 }
354
355 pub fn timescale(&self) -> moq_net::Timescale {
357 Self::TIMESCALE
358 }
359
360 pub fn wall(&self) -> Option<hang::catalog::Clock> {
363 self.wall
364 }
365
366 pub fn wall_clock(&self, pts: moq_net::Timestamp) -> crate::Result<Wall> {
372 Ok(self.mapping()?.wall_clock(pts)?)
373 }
374}
375
376impl PartialEq for Clock {
377 fn eq(&self, other: &Self) -> bool {
378 Arc::ptr_eq(&self.timeline, &other.timeline)
379 }
380}
381
382impl Eq for Clock {}
383
384impl Default for Clock {
385 fn default() -> Self {
386 Self::new()
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 fn epoch() -> Instant {
395 kio::clock::now()
396 }
397
398 fn moq_epoch() -> Wall {
399 moq_net::time::EPOCH
400 }
401
402 fn us(v: u64) -> moq_net::Timestamp {
403 moq_net::Timestamp::from_micros(v).unwrap()
404 }
405
406 #[kio::test]
409 async fn a_capture_maps_onto_the_clock() {
410 kio::clock::sleep(Duration::from_secs(6)).await;
411 let now = kio::clock::now();
412 let clock = Clock::at(now.saturating_sub(Duration::from_secs(5)), moq_epoch()).unwrap();
413 assert_eq!(
414 clock.capture(now.saturating_sub(Duration::from_secs(2))).unwrap(),
415 us(3_000_000)
416 );
417
418 assert!(matches!(
419 clock.capture(kio::clock::now().saturating_add(Duration::from_secs(1))),
420 Err(crate::Error::InvalidCapture)
421 ));
422 assert!(matches!(
423 clock.capture(now.saturating_sub(Duration::from_secs(6))),
424 Err(crate::Error::InvalidCapture)
425 ));
426 }
427
428 #[kio::test]
429 async fn simulated_clock_preserves_logical_boundaries() {
430 kio::clock::sleep(Duration::from_secs(10)).await;
431 let epoch = kio::clock::now();
432 let clock = Clock::at(epoch, moq_epoch()).unwrap();
433 let fresh = Clock::new();
434 let before = fresh.now();
435 let wall = clock.wall();
436
437 kio::clock::sleep(Duration::from_secs(3)).await;
438 assert_eq!(clock.now(), us(3_000_000));
439 assert_eq!(
440 fresh.now().as_micros().unwrap() - before.as_micros().unwrap(),
441 3_000_000
442 );
443 assert_eq!(clock.wall(), wall);
444 assert_eq!(
445 clock.wall_clock(clock.now()).unwrap(),
446 moq_epoch() + Duration::from_secs(3)
447 );
448
449 let stepped = kio::clock::Manual::WALL_START + Duration::from_secs(3600);
450 kio::clock::sim::step_wall(stepped);
451 assert_eq!(clock.wall(), wall, "a wall correction does not retime archived media");
452 assert_eq!(
453 Clock::new().wall(),
454 wall_clock(stepped - Clock::LEAD).ok(),
455 "a new mapping samples the corrected wall"
456 );
457
458 let captured = epoch.saturating_add(Duration::from_secs(2));
459 assert_eq!(clock.capture(captured).unwrap(), us(2_000_000));
460 assert!(matches!(
461 clock.capture(epoch.saturating_add(Duration::from_secs(4))),
462 Err(crate::Error::InvalidCapture)
463 ));
464 assert!(matches!(
465 clock.capture(epoch.saturating_sub(Duration::from_secs(1))),
466 Err(crate::Error::InvalidCapture)
467 ));
468 }
469
470 fn error(clock: &Clock) -> i128 {
472 unix_nanos(clock.wall_clock(clock.now()).unwrap()) - unix_nanos(kio::clock::wall())
473 }
474
475 const TICK: Duration = Duration::from_secs(10);
477
478 async fn run(clock: &Clock, duration: Duration) -> i128 {
481 let tick = TICK.as_micros();
482 for _ in 0..duration.as_secs() / TICK.as_secs() {
483 let before = clock.now().as_micros().unwrap();
484 kio::clock::sleep(TICK).await;
485 let step = clock.now().as_micros().unwrap() - before;
486 assert!(step.abs_diff(tick) <= tick / SLEW as u128 + 1, "a tick read {step} us");
487 }
488 error(clock)
489 }
490
491 #[kio::test]
495 async fn wall_times_follow_the_host_wall_clock() {
496 let second = 1_000_000_000;
497 let clock = Clock::new();
498 let settled = |error: i128| error.abs() <= SETTLED + TICK.as_nanos() as i128 / SLEW as i128;
499
500 for ppm in [500, -500] {
501 kio::clock::sim::set_drift(ppm);
502 let error = run(&clock, Duration::from_secs(12 * 3600)).await;
503 assert!(settled(error), "{ppm} ppm for 12 h left {error} ns");
504 }
505 kio::clock::sim::set_drift(0);
506
507 for step in [10i128, -10] {
509 let wall = kio::clock::wall();
510 let stepped = match step > 0 {
511 true => wall + Duration::from_secs(10),
512 false => wall - Duration::from_secs(10),
513 };
514 kio::clock::sim::step_wall(stepped);
515 let error = run(&clock, Duration::from_secs(10_000)).await;
516 let half = -step * second / 2;
517 assert!(
518 (error - half).abs() <= SETTLED,
519 "halfway through a {step} s step: {error} ns"
520 );
521 let error = run(&clock, Duration::from_secs(10_100)).await;
522 assert!(settled(error), "after a {step} s step: {error} ns");
523 }
524
525 let before = clock.now().as_micros().unwrap();
527 kio::clock::sim::suspend(Duration::from_secs(3600));
528 let after = clock.now().as_micros().unwrap();
529 assert_eq!(after - before, 3_600_000_000, "a suspend is a gap");
530 assert!(settled(error(&clock)));
531 assert!(settled(run(&clock, Duration::from_secs(60)).await));
532 }
533
534 #[kio::test]
536 async fn clones_share_the_slew() {
537 let clock = Clock::new();
538 let clone = clock.clone();
539 assert_eq!(clock, clone);
540 assert_ne!(clock, Clock::new(), "a new clock is a new timeline");
541
542 kio::clock::sim::step_wall(kio::clock::wall() + Duration::from_secs(5));
543 kio::clock::sleep(Duration::from_secs(100)).await;
544 let slewed = clock.now();
545 assert_eq!(slewed.as_micros().unwrap(), 10_000_000 + 100_000_000 + 50_000);
546 assert_eq!(clone.now(), slewed);
547 }
548
549 #[test]
550 fn section_advertises_wall_in_clock_timescale() {
551 let clock = Clock::at(epoch(), moq_epoch()).unwrap();
553 assert_eq!(clock.wall().unwrap().wall().value(), 0);
554 assert_eq!(clock.wall().unwrap().wall().scale(), Some(Clock::TIMESCALE));
555
556 let clock = Clock::at(epoch(), moq_epoch() + Duration::from_secs(1)).unwrap();
558 assert_eq!(clock.wall().unwrap().wall().value(), 1_000_000);
559 }
560
561 #[test]
562 fn unrepresentable_walls_are_refused() {
563 let far = moq_net::time::EPOCH + Duration::from_micros(MAX_SAFE_INTEGER + 1);
565 assert!(Clock::at(epoch(), far).is_err());
566
567 assert!(Clock::at(epoch(), Wall::UNIX_EPOCH).is_err());
569 assert!(Clock::at(epoch(), moq_epoch() - Duration::from_micros(1)).is_err());
570 assert_eq!(
571 Clock::at(epoch(), moq_epoch()).unwrap().wall().unwrap().wall().value(),
572 0
573 );
574 }
575
576 #[test]
577 fn fresh_clock_leaves_room_before_now() {
578 let clock = Clock::new();
579 assert!(clock.now().as_micros().unwrap() >= Clock::LEAD.as_micros());
582 let now = clock.wall_clock(clock.now()).unwrap();
583 let host = kio::clock::wall();
584 let drift = now.max(host).saturating_duration_since(now.min(host));
585 assert!(drift < Duration::from_secs(1), "wall + now is the current wall time");
586 }
587
588 #[kio::test]
590 async fn arrival_maps_the_first_timestamp_to_now() {
591 kio::clock::sleep(Duration::from_secs(1)).await;
592 let since = Duration::from_secs(10 * 3600);
593 let clock = Clock::new().arrival(since).unwrap();
594 let now = clock.now();
595 assert!(now.as_micros().unwrap() >= since.as_micros());
596 let actual = clock.wall_clock(now).unwrap();
597 let host = kio::clock::wall();
598 let drift = actual.max(host).saturating_duration_since(actual.min(host));
599 assert!(drift < Duration::from_secs(1), "the first timestamp is live on arrival");
600
601 let earlier = clock
603 .capture(kio::clock::now().saturating_sub(Duration::from_secs(1)))
604 .unwrap();
605 assert!(earlier.as_micros().unwrap() < now.as_micros().unwrap());
606
607 assert!(matches!(
609 Clock::new().arrival(Duration::from_secs(100 * 365 * 86_400)),
610 Err(crate::Error::UnmappableTimestamp(_))
611 ));
612 }
613
614 #[test]
617 fn an_unset_host_clock_has_no_wall() {
618 fake_host_wall(Wall::UNIX_EPOCH + Duration::from_secs(86_400));
619
620 let clock = Clock::new();
621 assert_eq!(clock.wall(), None);
622 assert!(clock.now().as_micros().unwrap() >= Clock::LEAD.as_micros());
623 assert!(matches!(
624 clock.wall_clock(clock.now()),
625 Err(crate::Error::UnmappableTimestamp(_))
626 ));
627 assert!(matches!(
628 clock.reading(moq_epoch()),
629 Err(crate::Error::UnmappableTimestamp(_))
630 ));
631
632 assert_eq!(clock.arrival(Duration::from_secs(3600)).unwrap().wall(), None);
634 assert!(matches!(
635 clock.arrival(Duration::from_micros(MAX_SAFE_INTEGER + 1)),
636 Err(crate::Error::UnmappableTimestamp(_))
637 ));
638 assert!(matches!(
639 clock.placed(Duration::from_secs(1), moq_epoch() + Duration::from_secs(60)),
640 Err(crate::Error::UnmappableTimestamp(_))
641 ));
642
643 assert!(Clock::at(epoch(), moq_epoch()).unwrap().wall().is_some());
645 }
646
647 #[test]
648 fn wall_mapping_survives_a_system_clock_adjustment() {
649 let clock = Clock::at(epoch(), moq_epoch()).unwrap();
650 let before = clock.wall_clock(us(2_000_000)).unwrap();
651
652 assert_eq!(clock.wall_clock(us(2_000_000)).unwrap(), before);
655 assert_eq!(
656 before,
657 moq_epoch() + Duration::from_secs(2),
658 "archive records keep their wall times"
659 );
660 }
661
662 #[test]
664 fn wall_clock_roundtrips_a_microsecond_wall() {
665 let wall = moq_epoch() + Duration::from_micros(1_000_999);
666 let clock = Clock::at(epoch(), wall).unwrap();
667 assert_eq!(clock.wall_clock(moq_net::Timestamp::ZERO).unwrap(), wall);
668 }
669
670 #[test]
671 fn wall_clock_validates_bounds() {
672 let clock = Clock::at(epoch(), moq_epoch()).unwrap();
673 let max = moq_net::Timestamp::from_micros((1u64 << 61) - 1).unwrap();
675 assert!(clock.wall_clock(max).is_err(), "past the JSON-safe range is refused");
676 }
677}