Skip to main content

moq_mux/
clock.rs

1//! The broadcast's shared clock: one monotonic timeline plus its wall mapping.
2//!
3//! Create one [`Clock`] per broadcast and hand clones to every producer: because they share a
4//! timeline, frames captured at the same instant get the same timestamp, keeping concurrently
5//! produced tracks (e.g. audio and video capture on separate threads) in sync. Cloning is cheap.
6//! Taking the catalog's clock fixes it, so a clone never goes stale.
7//!
8//! A clock reads the ambient clock it was created under (see [`kio::clock::Clock`]), wherever it
9//! is read from later. A broadcast built under one runtime and written from another, or from a
10//! plain thread, stays on one timeline instead of jumping between the two clocks.
11//!
12//! The timeline runs at the host wall clock's rate rather than its monotonic clock's, so `wall + pts`
13//! stays on UTC for any session length. A monotonic clock drifts off UTC by its oscillator's error
14//! (seconds a day on macOS and Windows), so each read nudges the timeline toward the wall clock by at
15//! most 500 ppm, NTP's own slew cap: a wall clock that steps either way is followed that slowly,
16//! and media never jumps. A suspend is a gap instead, which the timeline jumps forward across, since
17//! no media exists for that time: it counts the host's [`suspended`](kio::clock::Clock::suspended)
18//! time, where the monotonic clock stops.
19//!
20//! The clock also owns the broadcast's wall mapping, advertised at the catalog root as
21//! `clock: { wall, timescale }`: `wall` is the wall-clock time of PTS zero in
22//! [`Clock::TIMESCALE`] units since the moq epoch (2020-01-01). A consumer derives any
23//! timestamp's wall time as `wall + pts` after converting it into this timescale. A discontinuity
24//! marker is a delivery event, not a new epoch, and a system-clock adjustment never retimes it.
25//! A host whose wall clock reads before 2020 has not set it yet (a device booted before NTP sync),
26//! so its clock carries no mapping and the catalog omits `clock` rather than advertise a false one.
27//!
28//! A container importer publishes its stream's own timestamps. The first to receive a frame before
29//! anything fixes the clock places the mapping so that frame is live on arrival; any other shifts
30//! onto the clock (see [`catalog::Timebase`](crate::catalog::Timebase)).
31
32use 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
41/// Microseconds from the moq epoch (2020) to `wall`, negative before it.
42fn 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
47/// The host's wall clock, or `None` while it reads before the moq epoch (2020): unset.
48pub(crate) fn host_wall() -> Option<Wall> {
49	set(kio::clock::wall())
50}
51
52/// `now`, or `None` while it reads before the moq epoch (2020): a wall clock not yet set.
53fn 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	/// What [`host_wall`] reads on this thread instead of the system clock.
62	static HOST_WALL: std::cell::Cell<Option<Wall>> = const { std::cell::Cell::new(None) };
63}
64
65/// Make this thread's host wall clock read `now`, so a test can fake one that was never set.
66#[cfg(test)]
67pub(crate) fn fake_host_wall(now: Wall) {
68	HOST_WALL.set(Some(now));
69}
70
71/// The catalog clock for PTS zero at `wall`.
72fn wall_clock(wall: Wall) -> crate::Result<hang::catalog::Clock> {
73	// A time before 2020 cannot be named on the wire; refuse it rather than advertise 2020.
74	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/// A clock for stamping media frames so that tracks produced concurrently, e.g. an audio and a
86/// video capture running on separate threads, land on a single timeline.
87///
88/// It never runs backward, and runs at the host wall clock's rate: each read nudges it toward the
89/// wall clock by at most 500 ppm, and it jumps forward across a suspend.
90/// Clones share the timeline and the wall mapping, so handing them to several producers keeps
91/// the broadcast on one clock. Two clocks are equal only when they are one timeline.
92#[derive(Clone, Debug)]
93pub struct Clock {
94	/// The ambient clock captured where this one was created, read wherever it is read.
95	source: kio::clock::Clock,
96	timeline: Arc<Mutex<Timeline>>,
97	/// `None` when the broadcast has no wall mapping: the host's wall clock was unset at construction, or
98	/// the source advertised none.
99	wall: Option<hang::catalog::Clock>,
100}
101
102/// The most a timeline gains or loses on the host's monotonic time to follow its wall clock, as a
103/// divisor: 500 ppm, the cap NTP slews the host's own clocks by.
104const SLEW: u64 = 2_000;
105
106/// A wall error, in nanoseconds, left alone, so two clocks read a moment apart don't dither the
107/// timeline's rate.
108const SETTLED: i128 = 1_000_000;
109
110/// Nanoseconds from the Unix epoch to `wall`.
111fn unix_nanos(wall: Wall) -> i128 {
112	wall.saturating_duration_since(Wall::UNIX_EPOCH).as_nanos() as i128
113}
114
115/// Where a clock's timeline last read, and the wall clock it follows.
116#[derive(Debug)]
117struct Timeline {
118	/// The host's monotonic instant and the time it had spent suspended at the last read.
119	instant: Instant,
120	suspended: Duration,
121	/// What the clock read then, in nanoseconds.
122	reading: u64,
123	/// The host wall time, in Unix nanoseconds, at which the timeline reads zero; `None` when the
124	/// host's wall clock was unset at the start, leaving nothing to follow.
125	zero: Option<i128>,
126}
127
128impl Timeline {
129	/// A timeline reading `reading` nanoseconds at `instant` on `source`, which may be past or ahead.
130	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	/// What the timeline reads at `instant`, after `suspended` of sleep, with the host wall at `wall`.
143	///
144	/// It advances by the time that passed, suspends included, nudged toward the wall clock by at
145	/// most [`SLEW`] of it, so it never runs backward and a wall step is followed gradually.
146	fn read(&mut self, instant: Instant, suspended: Duration, wall: Option<Wall>) -> u64 {
147		// Each kept at its largest, so a read's jitter is counted once rather than piling up.
148		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		// u128 -> u64 truncation is unreachable: u64 nanoseconds is ~584 years.
153		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		// Within u64: the nudge is at most what elapsed, either way.
166		self.reading = (free as i128 + nudge) as u64;
167		self.reading
168	}
169}
170
171impl Clock {
172	/// Units per second for the broadcast clock: microseconds.
173	///
174	/// Matches the hang container timescale, so media timestamps convert without loss, and fine
175	/// enough that the wall value stays within the JSON-safe integer range until the year 2305.
176	pub const TIMESCALE: moq_net::Timescale = moq_net::Timescale::MICRO;
177
178	/// What a fresh clock reads at construction.
179	///
180	/// Frames stamped beside it can carry slightly earlier timestamps (audio captured a moment
181	/// before the video it is muxed with). Starting the clock this far past zero leaves them room
182	/// instead of landing before the broadcast began.
183	const LEAD: Duration = Duration::from_secs(10);
184
185	/// Start a clock that reads ten seconds now, so PTS zero is ten seconds ago on the wall.
186	///
187	/// Without a wall mapping when the host's wall clock is unset, or reads a time the mapping can't
188	/// name: media needs only the monotonic timeline.
189	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	/// Start a clock at an explicit monotonic epoch and wall time: PTS zero at both.
199	///
200	/// The deterministic constructor: synthetic sources and fixtures pin both ends instead of
201	/// sampling. `epoch` is an instant on the ambient clock, which the clock keeps reading wherever
202	/// it is read from. Refuses an unrepresentable wall.
203	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	/// This clock moved to read `since` now: a source whose first timestamp is `since` is live on
214	/// arrival.
215	///
216	/// Refuses a `since` so large that PTS zero lands before the moq epoch (2020), which the wall
217	/// mapping cannot name. On a host whose wall clock is unset, the clock has no wall mapping.
218	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			// Past the mapping's range, PTS zero is before 2020 for any host before 2305; refusing it
226			// also keeps the readings within a timestamp as the clock advances.
227			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	/// This clock moved so `pts` is the instant `wall`: a source that knows when its timestamps
239	/// happened places them there rather than at their arrival.
240	///
241	/// Refuses a mapping whose PTS zero lands before the moq epoch (2020) or after now, and a host
242	/// whose wall clock is unset, which has no now to place it against.
243	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	/// This clock without its wall mapping: the same timeline, for a broadcast whose source
253	/// advertises no `sync.clock`, so none is invented.
254	pub(crate) fn unmapped(&self) -> Self {
255		Self {
256			wall: None,
257			..self.clone()
258		}
259	}
260
261	/// A catalog root `clock` in [`TIMESCALE`](Self::TIMESCALE), the units [`wall`](Self::wall)
262	/// reports, so equal mappings compare equal.
263	///
264	/// Refuses a wall that is no whole number of those units (some 90 kHz values).
265	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	/// This clock moved onto an [`exact`](Self::exact) catalog root `clock`: a derivative
281	/// republishing its input's timestamps runs on its input's mapping.
282	///
283	/// Refuses a PTS zero after now, and a host whose wall clock is unset.
284	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	/// This clock moved so its PTS zero is `zero`, anchored now at however long ago that was on the
291	/// host.
292	///
293	/// No `Instant` arithmetic, so a PTS zero before this host booted still maps.
294	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		// Saturating would stamp everything early by the skew without saying so.
297		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	/// What this clock reads at `wall`, in microseconds: negative before PTS zero.
308	///
309	/// Pure in the stored mapping, like [`wall_clock`](Self::wall_clock), and refused without one.
310	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	/// The wall mapping, refused when the broadcast has none.
315	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	/// The current timestamp on this clock.
321	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	/// The host's instant now, and what the timeline reads at it.
327	fn read(&self) -> (Instant, u64) {
328		let mut timeline = self.timeline.lock().unwrap_or_else(PoisonError::into_inner);
329		// Read under the lock, so racing reads land on the timeline in order.
330		let now = self.source.now();
331		let reading = timeline.read(now, self.source.suspended(), set(self.source.wall()));
332		(now, reading)
333	}
334
335	/// The instant now on the ambient clock this one was created under, whichever thread or runtime
336	/// asks: what [`capture`](Self::capture) takes, and every re-basing of this clock shares.
337	pub(crate) fn instant(&self) -> Instant {
338		self.source.now()
339	}
340
341	/// Map the instant a payload was captured (a datagram's arrival, a sensor read) onto this clock.
342	///
343	/// `at` is an instant on the ambient clock this one was created under, which is the host's
344	/// outside tests. Refuses an instant ahead of now, which would claim the payload reached the
345	/// transport before it existed, and one before PTS zero, which no timestamp can name.
346	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	/// Units per second for [`wall`](Self::wall): [`TIMESCALE`](Self::TIMESCALE).
356	pub fn timescale(&self) -> moq_net::Timescale {
357		Self::TIMESCALE
358	}
359
360	/// The catalog root section advertising this clock, or `None` if the broadcast has no wall mapping:
361	/// the host's wall clock was unset, or the source advertised none.
362	pub fn wall(&self) -> Option<hang::catalog::Clock> {
363		self.wall
364	}
365
366	/// The wall-clock time of `pts` under this broadcast's mapping.
367	///
368	/// Pure in the stored mapping: a system-clock adjustment after construction changes nothing.
369	/// Exact down to the nanosecond; an instant finer than that (a 90 kHz tick) is floored.
370	/// Refuses an unrepresentable result, and a clock without a mapping.
371	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	/// A capture maps onto the clock's own timeline, and one ahead of now or before the epoch is
407	/// refused rather than clamped.
408	#[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	/// How far `wall + now` reads ahead of the host's wall clock, in nanoseconds.
471	fn error(clock: &Clock) -> i128 {
472		unix_nanos(clock.wall_clock(clock.now()).unwrap()) - unix_nanos(kio::clock::wall())
473	}
474
475	/// How often [`run`] reads the clock.
476	const TICK: Duration = Duration::from_secs(10);
477
478	/// Let `duration` pass a [`TICK`] at a time, checking that each advances the clock by a tick
479	/// give or take the slew, and return the error after it.
480	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	/// The broadcast's wall times stay on the host's wall clock across a day of its monotonic clock
492	/// drifting 500 ppm either way, follow a wall step either way at the slew cap without jumping,
493	/// and jump forward across a suspend.
494	#[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		// A wall step either way is slewed out at the cap: 10 s takes 20,000 s.
508		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		// No media exists while the host sleeps: the clock jumps the gap and stays on the wall clock.
526		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	/// Clones share one timeline, so the slew one applies is the others' too.
535	#[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		// PTS zero at exactly the moq epoch advertises 0.
552		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		// A second later is a second's worth of clock units.
557		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		// One micro past the JSON-safe integer range: browsers would read a different number.
564		let far = moq_net::time::EPOCH + Duration::from_micros(MAX_SAFE_INTEGER + 1);
565		assert!(Clock::at(epoch(), far).is_err());
566
567		// Before 2020 cannot be named on the wire; saturating to the epoch would lie.
568		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		// PTS zero sits before construction, so a frame stamped a little before now still maps,
580		// and the mapping still names the current wall time.
581		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	/// A source whose first timestamp is ten hours in reads that timestamp now, mapped to now.
589	#[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		// A capture from before the arrival still maps, down to PTS zero.
602		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		// PTS zero before 2020 cannot be named on the wire.
608		assert!(matches!(
609			Clock::new().arrival(Duration::from_secs(100 * 365 * 86_400)),
610			Err(crate::Error::UnmappableTimestamp(_))
611		));
612	}
613
614	/// A host wall clock before 2020 is unset: the clock keeps its monotonic timeline without a wall
615	/// mapping, and refuses whatever needs one rather than invent it.
616	#[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		// An importer arriving an hour in still gets a timeline, and placing one has no wall to use.
633		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		// An explicit wall needs no host clock.
644		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		// The mapping is a stored epoch, not a sampled clock: reading it again (after whatever
653		// the system clock did in between) changes nothing, and retained records map identically.
654		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	/// Regression: a wall with a sub-millisecond part came back up to 999 µs early.
663	#[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		// The largest representable broadcast timestamp still maps.
674		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}