Skip to main content

hang/catalog/
clock.rs

1use serde::{Deserialize, Deserializer, Serialize};
2
3use crate::Result;
4
5/// The largest integer JSON preserves exactly (2^53 - 1).
6pub const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
7
8fn deserialize_wall<'de, D>(deserializer: D) -> std::result::Result<u64, D::Error>
9where
10	D: Deserializer<'de>,
11{
12	let value = u64::deserialize(deserializer)?;
13	if value > MAX_SAFE_INTEGER {
14		return Err(serde::de::Error::custom(format!("invalid wall clock: {value}")));
15	}
16	Ok(value)
17}
18
19const fn default_timescale() -> u32 {
20	1_000_000
21}
22
23#[derive(Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25struct Wire {
26	#[serde(deserialize_with = "deserialize_wall")]
27	wall: u64,
28	#[serde(
29		default = "default_timescale",
30		deserialize_with = "super::deserialize_timescale_or_default"
31	)]
32	timescale: u32,
33}
34
35/// The broadcast's one continuous clock, advertised at the catalog root.
36///
37/// [`wall`](Self::wall) is the wall-clock time of PTS zero since the moq epoch
38/// ([`moq_net::time::EPOCH`], 2020-01-01). Its embedded timescale is serialized beside it as
39/// `{ wall, timescale }`, preserving the catalog wire shape while keeping the pair inseparable in
40/// Rust. Every media track and every HLS record refer to this mapping after timescale conversion.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Clock {
44	// Private so every value passes `new`'s range and timescale checks.
45	wall: moq_net::Timestamp,
46}
47
48impl Clock {
49	/// Construct a catalog clock from its typed wall timestamp.
50	///
51	/// Refuses a value outside the JSON-safe integer range or a timescale that cannot be represented
52	/// by the catalog's `u32` wire field.
53	pub fn new(wall: moq_net::Timestamp) -> Result<Self> {
54		if wall.value() > MAX_SAFE_INTEGER {
55			return Err(crate::Error::InvalidWall(wall.value()));
56		}
57		// A wall clock needs a scale: an unscaled timestamp has no time.
58		let scale = wall
59			.scale()
60			.ok_or(crate::Error::TimestampOverflow(moq_net::TimeOverflow))?;
61		if scale.as_u64() > u32::MAX as u64 {
62			return Err(crate::Error::InvalidTimescale(scale.as_u64()));
63		}
64		Ok(Self { wall })
65	}
66
67	/// The wall-clock time of PTS zero since the moq epoch.
68	pub fn wall(&self) -> moq_net::Timestamp {
69		self.wall
70	}
71
72	/// The wall-clock time of `pts` under this fixed mapping.
73	///
74	/// Exact down to the nanosecond; an instant finer than that (a 90 kHz tick) is floored.
75	/// Refuses a result past the JSON-safe range or the wall clock's 1970-2554 range, and an
76	/// [unscaled](moq_net::Timestamp::unscaled) `pts` or wall, which has no time.
77	pub fn wall_clock(&self, pts: moq_net::Timestamp) -> Result<kio::clock::Wall> {
78		let overflow = || crate::Error::TimestampOverflow(moq_net::TimeOverflow);
79		let wall_scale = self.wall.scale().ok_or_else(overflow)?.as_u64() as u128;
80		let pts_scale = pts.scale().ok_or_else(overflow)?.as_u64() as u128;
81
82		// Sum as one exact fraction of a second, `num / den`, so neither side is rounded into the
83		// other's units first.
84		let num = (self.wall.value() as u128)
85			.checked_mul(pts_scale)
86			.and_then(|wall| wall.checked_add((pts.value() as u128).checked_mul(wall_scale)?))
87			.ok_or_else(overflow)?;
88		let den = wall_scale.checked_mul(pts_scale).ok_or_else(overflow)?;
89
90		// `num / pts_scale` is the result in the wall's units; any fraction past the limit is past it.
91		if num > MAX_SAFE_INTEGER as u128 * pts_scale {
92			let total = num.div_ceil(pts_scale);
93			return Err(crate::Error::InvalidWall(u64::try_from(total).unwrap_or(u64::MAX)));
94		}
95
96		let secs = u64::try_from(num / den).map_err(|_| overflow())?;
97		let nanos = (num % den).checked_mul(1_000_000_000).ok_or_else(overflow)? / den;
98		let since_moq_epoch = std::time::Duration::new(secs, nanos as u32);
99		// A catalog can name a wall beyond the clock's nanosecond range.
100		moq_net::time::EPOCH.checked_add(since_moq_epoch).ok_or_else(overflow)
101	}
102}
103
104impl Serialize for Clock {
105	fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
106	where
107		S: serde::Serializer,
108	{
109		let scale = self
110			.wall
111			.scale()
112			.ok_or_else(|| serde::ser::Error::custom("an unscaled wall clock has no time"))?;
113		Wire {
114			wall: self.wall.value(),
115			timescale: u32::try_from(scale.as_u64()).map_err(serde::ser::Error::custom)?,
116		}
117		.serialize(serializer)
118	}
119}
120
121impl<'de> Deserialize<'de> for Clock {
122	fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
123	where
124		D: Deserializer<'de>,
125	{
126		let wire = Wire::deserialize(deserializer)?;
127		let wall =
128			moq_net::Timestamp::from_scale(wire.wall, wire.timescale as u64).map_err(serde::de::Error::custom)?;
129		Self::new(wall).map_err(serde::de::Error::custom)
130	}
131}
132
133#[cfg(test)]
134mod test {
135	use super::*;
136
137	#[test]
138	fn defaults_timescale_to_micros() {
139		let decoded: Clock = serde_json::from_str(r#"{"wall":1000}"#).unwrap();
140		assert_eq!(decoded.wall(), moq_net::Timestamp::from_micros(1000).unwrap());
141		assert_eq!(
142			serde_json::to_string(&decoded).unwrap(),
143			r#"{"wall":1000,"timescale":1000000}"#
144		);
145	}
146
147	#[test]
148	fn roundtrip() {
149		let clock = Clock::new(moq_net::Timestamp::from_millis(175_184_640_000).unwrap()).unwrap();
150		let json = serde_json::to_string(&clock).unwrap();
151		assert_eq!(json, r#"{"wall":175184640000,"timescale":1000}"#);
152		assert_eq!(serde_json::from_str::<Clock>(&json).unwrap(), clock);
153	}
154
155	#[test]
156	fn zero_timescale_is_refused() {
157		serde_json::from_str::<Clock>(r#"{"wall":0,"timescale":0}"#).expect_err("a zero timescale must not decode");
158	}
159
160	#[test]
161	fn explicit_null_timescale_is_refused() {
162		serde_json::from_str::<Clock>(r#"{"wall":0,"timescale":null}"#)
163			.expect_err("an explicit null timescale must not decode as the default");
164	}
165
166	#[test]
167	fn wall_beyond_json_safe_integers_is_refused() {
168		serde_json::from_str::<Clock>(r#"{"wall":9007199254740992}"#).expect_err("a wall past 2^53-1 must not decode");
169		let wall = moq_net::Timestamp::new(MAX_SAFE_INTEGER + 1, moq_net::Timescale::MICRO).unwrap();
170		assert!(Clock::new(wall).is_err());
171	}
172
173	/// A fraction of a wall unit past the JSON-safe range is still past it.
174	#[test]
175	fn wall_clock_refuses_a_fraction_past_the_safe_range() {
176		let clock = Clock::new(moq_net::Timestamp::from_micros(MAX_SAFE_INTEGER).unwrap()).unwrap();
177		clock.wall_clock(moq_net::Timestamp::ZERO).unwrap();
178		assert!(matches!(
179			clock.wall_clock(moq_net::Timestamp::from_nanos(1).unwrap()),
180			Err(crate::Error::InvalidWall(_))
181		));
182	}
183
184	/// A JSON-safe catalog wall can still exceed Wall's nanosecond range.
185	#[test]
186	fn wall_clock_past_the_wall_range_is_an_error() {
187		let wall = moq_net::Timestamp::new(MAX_SAFE_INTEGER, moq_net::Timescale::SECOND).unwrap();
188		let clock = Clock::new(wall).unwrap();
189		assert!(matches!(
190			clock.wall_clock(moq_net::Timestamp::ZERO),
191			Err(crate::Error::TimestampOverflow(_))
192		));
193	}
194
195	#[test]
196	fn wall_clock_converts_across_timescales() {
197		let clock = Clock::new(moq_net::Timestamp::from_micros(1_000_000).unwrap()).unwrap();
198		let epoch = moq_net::time::EPOCH + std::time::Duration::from_millis(1_000);
199		assert_eq!(
200			clock.wall_clock(moq_net::Timestamp::from_millis(0).unwrap()).unwrap(),
201			epoch
202		);
203
204		let second = moq_net::time::EPOCH + std::time::Duration::from_millis(2_000);
205		assert_eq!(
206			clock
207				.wall_clock(moq_net::Timestamp::from_millis(1000).unwrap())
208				.unwrap(),
209			second
210		);
211		assert_eq!(
212			clock
213				.wall_clock(moq_net::Timestamp::from_scale(48_000, 48_000).unwrap())
214				.unwrap(),
215			second
216		);
217		assert_eq!(
218			clock
219				.wall_clock(moq_net::Timestamp::from_scale(90_000, 90_000).unwrap())
220				.unwrap(),
221			second
222		);
223	}
224
225	/// Regression: the result was floored to the millisecond, dropping the sub-millisecond part.
226	#[test]
227	fn wall_clock_keeps_sub_millisecond_precision() {
228		let moq_epoch = moq_net::time::EPOCH;
229		let micros = |v| moq_net::Timestamp::from_micros(v).unwrap();
230		let nanos = std::time::Duration::from_nanos;
231
232		let clock = Clock::new(micros(1_000_999)).unwrap();
233		assert_eq!(
234			clock.wall_clock(moq_net::Timestamp::ZERO).unwrap(),
235			moq_epoch + nanos(1_000_999_000)
236		);
237
238		// One 90 kHz tick on a microsecond wall is 11,111.1 ns, floored at the nanosecond.
239		let tick = moq_net::Timestamp::from_scale(1, 90_000).unwrap();
240		assert_eq!(
241			clock.wall_clock(tick).unwrap(),
242			moq_epoch + nanos(1_000_999_000 + 11_111)
243		);
244
245		// A 1 µs pts on a millisecond wall is not lost converting into the wall's units.
246		let clock = Clock::new(moq_net::Timestamp::from_millis(1_000).unwrap()).unwrap();
247		assert_eq!(clock.wall_clock(micros(1)).unwrap(), moq_epoch + nanos(1_000_001_000));
248	}
249}