Skip to main content

moq_mux/catalog/
timebase.rs

1use std::sync::{Arc, OnceLock};
2
3use super::Producer;
4use super::hang::CatalogExt;
5
6/// One source's timestamp base on a catalog, shared by every importer reading it.
7///
8/// Made via [`Producer::timebase`]. A source on a timeline of its own (a container's, an RTP
9/// session's) [`shift`](Self::shift)s its timestamps onto the catalog's [`Clock`](crate::Clock) by
10/// one offset fixed on its first frame: zero when that frame places the clock (the catalog was not
11/// yet published, nor its clock taken), so the timestamps stay verbatim, and the gap between the
12/// clock's reading and the frame's timestamp otherwise. A source that knows when its timestamps
13/// happened [`place`](Self::place)s them first instead of landing at its first frame's arrival.
14///
15/// Every track shifted through one timebase shares that offset, so renditions on one timestamp
16/// base (an HLS import's variants, or the importer replacing one on a new init segment) stay in
17/// sync, while separate timebases each get their own. A container importer shifts through a fresh
18/// one unless handed a shared one with its `with_timebase`; codec importers and
19/// [`Reserved`](super::Reserved) write timestamps verbatim, already on the catalog's clock.
20///
21/// Clones share the offset. Holding one never withholds the catalog: only a live
22/// [`Reserved`](super::Reserved) does.
23pub struct Timebase<E: CatalogExt = ()> {
24	pub(super) catalog: Producer<E>,
25	offset: Arc<OnceLock<Offset>>,
26}
27
28impl<E: CatalogExt> Timebase<E> {
29	pub(super) fn new(catalog: Producer<E>) -> Self {
30		Self {
31			catalog,
32			offset: Default::default(),
33		}
34	}
35
36	/// Place this timebase's `pts` at the wall-clock instant `wall`, instead of at the arrival of its
37	/// first frame.
38	///
39	/// For a source whose timestamps say when they happened, such as a program clock. Like a first
40	/// frame, this places the catalog's clock if it is not yet fixed and offsets onto it otherwise.
41	/// A placement alone publishes nothing: the clock goes out with the catalog's first track.
42	/// Refused once this timebase has an offset, and when the host's wall clock was unset, leaving no
43	/// wall to place it on.
44	pub fn place(&self, pts: moq_net::Timestamp, wall: kio::clock::Wall) -> crate::Result<()> {
45		self.catalog.clone().anchor(&self.offset, pts, Some(wall))?;
46		Ok(())
47	}
48
49	/// Anchor on the first frame's timestamp `pts`, returning the timebase's offset.
50	///
51	/// The first call from any clone fixes the offset; every later one returns it unchanged.
52	pub(crate) fn anchor(&self, pts: moq_net::Timestamp) -> crate::Result<Offset> {
53		match self.offset.get() {
54			Some(offset) => Ok(*offset),
55			None => self.catalog.clone().anchor(&self.offset, pts, None),
56		}
57	}
58
59	/// The offset, once the timebase anchored.
60	pub(crate) fn offset(&self) -> Option<Offset> {
61		self.offset.get().copied()
62	}
63
64	/// Shift `pts` onto the catalog clock, anchoring on it if it is this timebase's first.
65	///
66	/// Refuses a `pts` that lands before the clock's zero, and one without a timescale.
67	pub fn shift(&self, pts: moq_net::Timestamp) -> crate::Result<moq_net::Timestamp> {
68		self.anchor(pts)?.apply(pts)
69	}
70}
71
72// Manual so a timebase is clonable regardless of whether `E` is.
73impl<E: CatalogExt> Clone for Timebase<E> {
74	fn clone(&self) -> Self {
75		Self {
76			catalog: self.catalog.clone(),
77			offset: self.offset.clone(),
78		}
79	}
80}
81
82/// The signed shift from one timebase's timestamps onto the catalog clock, in microseconds.
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
84pub(crate) struct Offset(i64);
85
86impl Offset {
87	pub(super) fn from_micros(micros: i128) -> crate::Result<Self> {
88		let micros = i64::try_from(micros).map_err(|_| moq_net::TimeOverflow)?;
89		Ok(Self(micros))
90	}
91
92	/// The offset in units of `units_per_second`, rounded down so every track at one scale shifts
93	/// by the same whole number of units.
94	pub(crate) fn ticks(self, units_per_second: u64) -> i128 {
95		(self.0 as i128 * units_per_second as i128).div_euclid(1_000_000)
96	}
97
98	/// Shift `pts`, keeping its scale. Refuses a result below zero rather than clamping it, and an
99	/// [unscaled](moq_net::Timestamp::unscaled) `pts`, which has no time to shift.
100	pub(crate) fn apply(self, pts: moq_net::Timestamp) -> crate::Result<moq_net::Timestamp> {
101		let scale = pts.scale().ok_or(moq_net::TimeOverflow)?;
102		if self.0 == 0 {
103			return Ok(pts);
104		}
105		let value = pts.value() as i128 + self.ticks(scale.as_u64());
106		let value = u64::try_from(value).map_err(|_| {
107			crate::Error::UnmappableTimestamp(format!(
108				"{pts:?} shifted by {} µs lands before the broadcast clock's zero",
109				self.0
110			))
111		})?;
112		Ok(moq_net::Timestamp::new(value, scale)?)
113	}
114}
115
116#[cfg(test)]
117mod test {
118	use super::*;
119
120	fn us(micros: u64) -> moq_net::Timestamp {
121		moq_net::Timestamp::from_micros(micros).unwrap()
122	}
123
124	#[test]
125	fn an_offset_keeps_the_scale_and_refuses_below_zero() {
126		let offset = Offset(-1_500_000);
127		let pts = moq_net::Timestamp::from_scale(270_000, 90_000).unwrap();
128		assert_eq!(
129			offset.apply(pts).unwrap(),
130			moq_net::Timestamp::from_scale(135_000, 90_000).unwrap()
131		);
132		assert_eq!(offset.apply(us(2_000_000)).unwrap(), us(500_000));
133		assert!(matches!(
134			offset.apply(us(1_000_000)),
135			Err(crate::Error::UnmappableTimestamp(_))
136		));
137		assert_eq!(Offset::default().apply(us(7)).unwrap(), us(7));
138		assert!(Offset::default().apply(moq_net::Timestamp::unscaled(7)).is_err());
139	}
140
141	/// A fractional unit rounds down at every scale, so tracks at one scale shift alike.
142	#[test]
143	fn ticks_round_down() {
144		assert_eq!(Offset(15).ticks(90_000), 1);
145		assert_eq!(Offset(-15).ticks(90_000), -2);
146		assert_eq!(Offset(1_000_000).ticks(48_000), 48_000);
147	}
148}