Skip to main content

moq_mux/container/
join.rs

1use std::time::Duration;
2
3/// Rolls an audio track's groups by duration.
4///
5/// Every audio packet decodes on its own, so nothing in the media says where a group ends. A group
6/// per packet costs a QUIC stream per packet, 50 a second at 20 ms, and those tiny streams race each
7/// other and spend the peer's stream credit. This says when a group carries its span of audio, on
8/// the packet (or container unit) that fills it, so the caller cuts right away and the relay sees the
9/// group finish without waiting for the next packet. Packets still forward as they are written.
10#[derive(Clone, Copy, Debug)]
11pub struct Join {
12	span: Duration,
13	/// Where the open group starts, or `None` when the next media opens one.
14	start: Option<Duration>,
15	/// The furthest end of the open group's media, so a rewound packet never cuts below it.
16	reach: Option<moq_net::Timestamp>,
17}
18
19impl Join {
20	/// How much audio a group carries by default: a new group (one QUIC stream) every 100 ms, about
21	/// as much as a player conceals, so a lost group is concealed rather than half silent.
22	pub const DEFAULT: Duration = Duration::from_millis(100);
23
24	/// Roll groups once they carry `span` of audio. A zero span fills every group with its first packet.
25	pub fn new(span: Duration) -> Self {
26		Self {
27			span,
28			start: None,
29			reach: None,
30		}
31	}
32
33	/// Count media from `start` to `end` into the open group, opening one when none is, and return
34	/// where the group ends once it is full, so the caller cuts it there: the furthest end of its
35	/// media, which a rewound packet's own end can fall below.
36	///
37	/// Media starting before the group's start also fills it, since the timeline broke. An
38	/// unscaled timestamp can't be measured, so it fills its group alone.
39	pub fn fill(&mut self, start: moq_net::Timestamp, end: moq_net::Timestamp) -> Option<moq_net::Timestamp> {
40		let reach = self.reach.map_or(end, |reach| super::later(reach, end));
41		let (Ok(start), Ok(end)) = (Duration::try_from(start), Duration::try_from(end)) else {
42			self.reset();
43			return Some(reach);
44		};
45		let opened = *self.start.get_or_insert(start);
46		if start < opened || self.spans(opened, end) {
47			self.reset();
48			return Some(reach);
49		}
50		self.reach = Some(reach);
51		None
52	}
53
54	/// Whether media from `start` can't continue the open group, since it starts a whole span past
55	/// the group's start (a gap) or before it (a rewind), so the caller cuts before writing it.
56	pub fn opens(&self, start: moq_net::Timestamp) -> bool {
57		match (self.start, Duration::try_from(start)) {
58			(Some(opened), Ok(start)) => self.spans(opened, start),
59			(Some(_), Err(_)) => true,
60			(None, _) => false,
61		}
62	}
63
64	/// Whether media from `start` starts a whole span past the open group's start: a gap, not a
65	/// rewind, which [`opens`](Self::opens) also counts.
66	pub(crate) fn gaps(&self, start: moq_net::Timestamp) -> bool {
67		match (self.start, Duration::try_from(start)) {
68			(Some(opened), Ok(start)) => start >= opened && self.spans(opened, start),
69			_ => false,
70		}
71	}
72
73	/// Whether a group from `start` to `end` is full, for a caller that tracks its own group.
74	///
75	/// Ending before it starts is full, since the timeline broke, and so is an unscaled timestamp.
76	pub fn full(&self, start: moq_net::Timestamp, end: moq_net::Timestamp) -> bool {
77		match (Duration::try_from(start), Duration::try_from(end)) {
78			(Ok(start), Ok(end)) => self.spans(start, end),
79			_ => true,
80		}
81	}
82
83	fn spans(&self, start: Duration, end: Duration) -> bool {
84		end < start || end - start >= self.span
85	}
86
87	/// Forget the open group, which the caller closed some other way, such as a discontinuity.
88	pub fn reset(&mut self) {
89		self.start = None;
90		self.reach = None;
91	}
92}
93
94impl Default for Join {
95	fn default() -> Self {
96		Self::new(Self::DEFAULT)
97	}
98}
99
100#[cfg(test)]
101mod tests {
102	use super::*;
103
104	fn micros(micros: u64) -> moq_net::Timestamp {
105		moq_net::Timestamp::from_micros(micros).unwrap()
106	}
107
108	/// Feed back-to-back packets of `frame` µs and return how many each group took.
109	fn groups(join: &mut Join, frame: u64, count: u64) -> Vec<u64> {
110		let mut sizes = vec![0];
111		for index in 0..count {
112			*sizes.last_mut().unwrap() += 1;
113			if join.fill(micros(index * frame), micros((index + 1) * frame)).is_some() {
114				sizes.push(0);
115			}
116		}
117		sizes.pop_if(|last| *last == 0);
118		sizes
119	}
120
121	#[test]
122	fn the_packet_that_reaches_the_span_fills_the_group() {
123		// 20 ms Opus fills a 100 ms group exactly.
124		assert_eq!(groups(&mut Join::default(), 20_000, 15), [5, 5, 5]);
125		// 1024 samples at 48 kHz never land on 100 ms, so a group takes the packet past it.
126		assert_eq!(groups(&mut Join::default(), 21_333, 10), [5, 5]);
127		// A unit longer than the span is a group of its own.
128		assert_eq!(groups(&mut Join::default(), 500_000, 3), [1, 1, 1]);
129		assert_eq!(groups(&mut Join::new(Duration::ZERO), 20_000, 3), [1, 1, 1]);
130	}
131
132	#[test]
133	fn a_reset_restarts_the_span() {
134		let mut join = Join::default();
135		assert_eq!(join.fill(micros(0), micros(80_000)), None);
136		join.reset();
137		// Measured from the media after the reset, not the group the caller closed.
138		assert_eq!(join.fill(micros(1_000_000), micros(1_050_000)), None);
139		assert!(join.fill(micros(1_050_000), micros(1_100_000)).is_some());
140	}
141
142	#[test]
143	fn a_gap_or_rewind_opens_a_group() {
144		let mut join = Join::default();
145		assert!(!join.opens(micros(1_000_000)), "no group is open");
146		assert_eq!(join.fill(micros(1_000_000), micros(1_020_000)), None);
147		assert!(!join.opens(micros(1_020_000)));
148		assert!(join.opens(micros(1_100_000)));
149		assert!(join.opens(micros(999_999)));
150		// Only the gap is one.
151		assert!(join.gaps(micros(1_100_000)));
152		assert!(!join.gaps(micros(1_099_999)));
153		assert!(!join.gaps(micros(999_999)));
154	}
155
156	#[test]
157	fn a_gap_or_rewind_fills_the_group() {
158		let mut join = Join::default();
159		assert_eq!(join.fill(micros(1_000_000), micros(1_020_000)), None);
160		// A jump ahead reaches the span at once.
161		assert!(join.fill(micros(5_000_000), micros(5_020_000)).is_some());
162		assert_eq!(join.fill(micros(5_020_000), micros(5_040_000)), None);
163		// A rewind closes the group it can't continue, even one overlapping the group's start.
164		assert!(join.fill(micros(0), micros(20_000)).is_some());
165		assert_eq!(join.fill(micros(1_000_000), micros(1_020_000)), None);
166		// The group still ends past the media it already holds.
167		assert_eq!(join.fill(micros(1_020_000), micros(1_040_000)), None);
168		assert_eq!(join.fill(micros(990_000), micros(1_010_000)), Some(micros(1_040_000)));
169		assert!(
170			join.fill(moq_net::Timestamp::unscaled(3), moq_net::Timestamp::unscaled(4))
171				.is_some()
172		);
173	}
174}