Skip to main content

hang/catalog/
timeline.rs

1use std::time::Duration;
2
3use serde::{Deserialize, Serialize};
4
5use super::millis::MillisCeil;
6
7/// The broadcast's timeline: the wall-clock time of PTS zero and how often a viewer can join.
8///
9/// Serialized under the catalog root's `sync` key, and omitted when it holds nothing.
10#[serde_with::skip_serializing_none]
11#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
12#[serde(rename_all = "camelCase")]
13#[non_exhaustive]
14pub struct Timeline {
15	/// The broadcast's one continuous clock, if the publisher exposes one.
16	///
17	/// `wall` is the wall-clock time of PTS zero in `timescale` units since the moq epoch
18	/// (2020-01-01); every track refers to this mapping after timescale conversion. See
19	/// [`Clock`](crate::catalog::Clock).
20	#[serde(default, deserialize_with = "crate::catalog::deserialize_some")]
21	pub clock: Option<crate::catalog::Clock>,
22
23	/// The promise that every audio and video track starts a group at least this often outside a
24	/// pause: the longest group (GOP) any of them publishes.
25	///
26	/// It is also the grid an HLS or DASH export numbers its segments on, so every rendition shares
27	/// segment numbers, and it is fixed for the broadcast identity since that numbering depends on
28	/// it. A broadcast without one is not HLS-renderable. Serialized as whole milliseconds, rounded
29	/// up. Zero is no promise: encoding refuses it, and so does a reader.
30	#[serde(
31		default,
32		serialize_with = "serialize_interval",
33		deserialize_with = "deserialize_interval"
34	)]
35	pub interval: Option<Duration>,
36}
37
38impl Timeline {
39	/// Whether the section holds nothing, so the catalog leaves it off the wire.
40	pub fn is_empty(&self) -> bool {
41		self.clock.is_none() && self.interval.is_none()
42	}
43}
44
45/// Encode the interval in whole milliseconds, rounded up, refusing zero.
46fn serialize_interval<S: serde::Serializer>(interval: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error> {
47	<MillisCeil as serde_with::SerializeAs<Option<Duration>>>::serialize_as(interval, serializer)
48}
49
50/// Decode a present `interval`, which must be a positive whole number of milliseconds.
51fn deserialize_interval<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<Duration>, D::Error> {
52	let millis = <crate::snapshot::Number as serde_with::DeserializeAs<'de, u64>>::deserialize_as(deserializer)?;
53	if millis == 0 {
54		return Err(serde::de::Error::custom("a sync interval must be positive"));
55	}
56	Ok(Some(Duration::from_millis(millis)))
57}
58
59#[cfg(test)]
60mod test {
61	use super::*;
62
63	#[test]
64	fn roundtrips_in_milliseconds() {
65		let sync = Timeline {
66			interval: Some(Duration::from_micros(2_000_500)),
67			..Default::default()
68		};
69		let json = serde_json::to_string(&sync).unwrap();
70		assert_eq!(json, r#"{"interval":2001}"#);
71		assert_eq!(
72			serde_json::from_str::<Timeline>(&json).unwrap().interval,
73			Some(Duration::from_millis(2001))
74		);
75	}
76
77	#[test]
78	fn a_zero_interval_is_no_promise() {
79		let zero = Timeline {
80			interval: Some(Duration::ZERO),
81			..Default::default()
82		};
83		serde_json::to_string(&zero).expect_err("a zero interval must not encode");
84
85		// Anything above zero rounds up to a whole millisecond on the wire, which reads back.
86		let tiny = Timeline {
87			interval: Some(Duration::from_nanos(1)),
88			..Default::default()
89		};
90		let sync: Timeline = serde_json::from_str(&serde_json::to_string(&tiny).unwrap()).unwrap();
91		assert_eq!(sync.interval, Some(Duration::from_millis(1)));
92	}
93
94	#[test]
95	fn an_undecodable_interval_refuses() {
96		for interval in ["0", "-1", "1.5", r#""2000""#, "{}", "[2000]", "null"] {
97			serde_json::from_str::<Timeline>(&format!(r#"{{"interval":{interval}}}"#)).expect_err(interval);
98		}
99	}
100}