Skip to main content

moq_mux/container/ts/
release.rs

1//! Writes a [`Passthrough`](super::Passthrough) track back out as the multiplex it carries.
2
3use std::pin::Pin;
4use std::task::Poll;
5use std::time::Duration;
6
7use kio::clock::{Instant, Sleep};
8
9use super::error::unsupported;
10use super::export;
11
12use crate::catalog::hang::Catalog;
13use crate::catalog::{CatalogFormat, Stream};
14use crate::container::consumer::Event;
15use crate::container::{ExportSource, Frame, Resume};
16use crate::jitter::{self, Arrival, Push};
17
18/// The packets a release writes at once: a UDP datagram's worth, as SRT and RTP senders take them.
19const RUN: usize = 7 * 188;
20
21/// The longest PCR interval a release spreads an object across, ISO 13818-1's limit.
22const SPREAD: Duration = Duration::from_millis(100);
23
24/// Writes the multiplex a broadcast's [passthrough track](super::Mpegts::passthrough) carries
25/// back out byte-identical, each packet a fixed delay after its time on the source's PCR, like
26/// an SRT receiver.
27///
28/// The [importer](super::Passthrough) stamps each object, the packets from one PCR to the
29/// next, with the PCR time of its first byte on the catalog clock. The release holds every
30/// object until that time plus the delay on the jitter buffer's clock, which follows the
31/// source's, then spreads its packets evenly up to the next object's time, seven at a time
32/// (a UDP datagram's worth), so the output keeps the source's rate whatever the arrival jitter.
33/// An object whose successor is not yet buffered when it comes due, follows a loss, or is more
34/// than ISO 13818-1's 100 ms PCR interval ahead, goes out whole, as does every object under no
35/// delay.
36/// Two releases that each receive every object before its deadline write the same bytes; where
37/// each held an object's successor when it came due, at the same times
38/// too, so a delay longer than the arrival jitter by a PCR interval keeps them in step. An
39/// object that arrives past its deadline is dropped and counted; the output shows a continuity
40/// error there, since nothing is rewritten, and carries on with the next object. A PCR clock
41/// break, which the importer declares with a discontinuity marker, opens a new clock, so the
42/// output does not wait out a jump; the bytes carry the break as the source sent it.
43///
44/// A [`Follower`](super::Follower) carries it across its broadcast's returns and, when
45/// stitching, onto another publisher identity, whose track it reads from the first group its
46/// live subscription delivers, after what was already buffered has gone out. Its packets follow
47/// verbatim, so the output shows the seam as each PID's continuity break, as the source would
48/// show a splice, and they go out on a clock of their own, as after an encoder changeover.
49pub struct Release {
50	source: crate::Source,
51	/// The format of the catalog being read, kept for following another identity.
52	format: CatalogFormat,
53	/// The identity of the broadcast being read, `None` for one not resolved through an origin.
54	identity: Option<moq_net::Identity>,
55	catalog: Option<crate::catalog::Consumer<super::Ext>>,
56	/// The catalog last subscribed has delivered a snapshot.
57	cataloged: bool,
58	/// The passthrough track, once a catalog names it.
59	track: Option<(String, ExportSource)>,
60	/// When the track was subscribed. Nothing it delivers reached the release before then,
61	/// however long the cache held it.
62	subscribed: Instant,
63	finished: bool,
64	/// Where the track read before its identity went stopped, for that identity's return.
65	resume: Option<Resume>,
66	/// The publisher left with this error; it is reported once what the jitter buffer holds
67	/// has gone out on its clock.
68	failed: Option<crate::Error>,
69	/// An object has gone out.
70	released: bool,
71	/// Timeline restarts and gaps counted by tracks read before the current one, whose own
72	/// counts start over.
73	restarts: u64,
74	gaps: u64,
75	delay: Duration,
76	jitter: jitter::Buffer<(), Held>,
77	/// The path lost something since the last object read: a group cut short or skipped, an
78	/// object dropped late, or a switch of track, so the next one read is no successor to spread
79	/// up to.
80	lost: bool,
81	/// The track's gaps when the last object was read.
82	skipped: u64,
83	/// The object going out, a run at a time.
84	spread: Option<Spread>,
85	timer: Option<Pin<Box<Sleep>>>,
86	replay: bool,
87}
88
89/// An object waiting in the jitter buffer.
90struct Held {
91	frame: Frame,
92	/// It follows a loss, so the object before it on the wire is not its predecessor.
93	after_loss: bool,
94}
95
96/// An object's runs, each due at its first byte's time on the way from the object's time to the next's.
97pub(super) struct Spread {
98	frame: Frame,
99	start: Instant,
100	span: Duration,
101	/// The next object's timestamp, from which each run's own is interpolated.
102	end: Option<moq_net::Timestamp>,
103	runs: usize,
104	sent: usize,
105}
106
107impl Spread {
108	/// Spread `frame` from `start` to `next`, the successor's deadline and timestamp, if its
109	/// interval on the source's clock is a PCR interval and the jitter clock, which runs within
110	/// [`MAX_DRIFT`](jitter::MAX_DRIFT) of the source's, has not stretched it further.
111	pub(super) fn new(frame: Frame, start: Instant, next: Option<(Instant, moq_net::Timestamp)>) -> Self {
112		let next = next.filter(|(at, end)| {
113			*at >= start
114				&& at.duration_since(start) <= SPREAD.mul_f64(1.0 + jitter::MAX_DRIFT)
115				&& end.scale() == frame.timestamp.scale()
116				&& end
117					.checked_sub(frame.timestamp)
118					.and_then(|interval| interval.as_micros())
119					.is_ok_and(|micros| micros <= SPREAD.as_micros())
120		});
121		let runs = match next {
122			Some(_) => frame.payload.len().div_ceil(RUN).max(1),
123			None => 1,
124		};
125		Self {
126			span: next.map_or(Duration::ZERO, |(at, _)| at.duration_since(start)),
127			end: next.map(|(_, end)| end),
128			frame,
129			start,
130			runs,
131			sent: 0,
132		}
133	}
134
135	/// How far into the object run `i` starts, as a fraction of its bytes.
136	fn share(&self, i: usize, of: u128) -> u128 {
137		of * (i * RUN) as u128 / self.frame.payload.len().max(1) as u128
138	}
139
140	/// When run `i` is due: the time of its first byte, at the object's rate to the next.
141	fn due(&self, i: usize) -> Instant {
142		let offset = self.share(i, self.span.as_nanos());
143		self.start.saturating_add(Duration::from_nanos(offset as u64))
144	}
145
146	/// Every run due by `now`, as one frame stamped with the first one's time.
147	pub(super) fn take(&mut self, now: Instant) -> Option<Frame> {
148		let due = (self.sent..self.runs).take_while(|&i| self.due(i) <= now).count();
149		if due == 0 {
150			return None;
151		}
152		if self.runs == 1 {
153			self.sent = 1;
154			return Some(self.frame.clone());
155		}
156		let (from, to) = (self.sent * RUN, ((self.sent + due) * RUN).min(self.frame.payload.len()));
157		let mut timestamp = self.frame.timestamp;
158		if let (Some(end), Some(scale)) = (self.end, timestamp.scale()) {
159			let (start, end) = (timestamp.value(), end.value());
160			let value = start + self.share(self.sent, (end - start) as u128) as u64;
161			timestamp = moq_net::Timestamp::new(value, scale).unwrap_or(timestamp);
162		}
163		self.sent += due;
164		Some(Frame {
165			timestamp,
166			decode: None,
167			duration: None,
168			payload: self.frame.payload.slice(from..to),
169			keyframe: self.frame.keyframe && from == 0,
170		})
171	}
172
173	fn done(&self) -> bool {
174		self.sent == self.runs
175	}
176}
177
178impl Release {
179	/// Subscribe to the catalog of `source`, in either format, waiting for the `mpegts` section to
180	/// name its passthrough track.
181	///
182	/// Each object is written `delay` after its PCR time; late objects are dropped.
183	#[cfg(feature = "async")]
184	pub async fn new(source: crate::Source, catalog_format: CatalogFormat, delay: Duration) -> crate::Result<Self> {
185		let mut subscribing = crate::catalog::Subscribing::new(&source.broadcast(), catalog_format);
186		let catalog = kio::wait(|waiter| subscribing.poll_ok(waiter)).await?;
187		let mut jitter = jitter::Buffer::new(delay);
188		jitter.expect([()]);
189		let release = Self {
190			identity: source.broadcast().info().identity.clone(),
191			source,
192			format: catalog_format,
193			catalog: Some(catalog),
194			cataloged: false,
195			track: None,
196			subscribed: kio::clock::now(),
197			finished: false,
198			resume: None,
199			failed: None,
200			released: false,
201			restarts: 0,
202			gaps: 0,
203			delay,
204			jitter,
205			lost: false,
206			skipped: 0,
207			spread: None,
208			timer: None,
209			replay: false,
210		};
211		Ok(release)
212	}
213
214	/// Read the track from the oldest group the delay still reaches instead of the live edge,
215	/// and anchor the clock on the first object, for a test that writes a broadcast whole first.
216	#[cfg(test)]
217	pub(super) fn with_replay(mut self) -> Self {
218		self.replay = true;
219		self.jitter = self.jitter();
220		self
221	}
222
223	#[cfg(test)]
224	fn jitter(&self) -> jitter::Buffer<(), Held> {
225		let mut jitter = jitter::Buffer::new(self.delay);
226		#[cfg(test)]
227		if self.replay {
228			jitter = jitter.replay();
229		}
230		jitter.expect([()]);
231		jitter
232	}
233
234	/// How many objects were dropped for missing their deadline.
235	pub fn dropped(&self) -> u64 {
236		self.jitter.dropped()
237	}
238
239	/// The source's clock rate off ours, as last measured, as a fraction: positive runs fast.
240	pub fn drift(&self) -> Option<f64> {
241		self.jitter.drift()
242	}
243
244	/// How many times the source's clock was measured further off ours than the release follows.
245	pub fn out_of_tolerance(&self) -> u64 {
246		self.jitter.out_of_tolerance()
247	}
248
249	/// Snapshot how the release clock is keeping up with the source.
250	pub fn stats(&self) -> super::stats::Release {
251		let mut stats = super::stats::Release::of(&self.jitter);
252		stats.gaps = self.gaps;
253		if let Some((_, track)) = &self.track {
254			stats.gaps += track.skips() - track.markers();
255		}
256		stats
257	}
258
259	/// How many objects are waiting in the jitter buffer.
260	#[cfg(test)]
261	pub(super) fn buffered(&self) -> usize {
262		self.jitter.len()
263	}
264
265	/// The next run of packets, at its time: whole TS packets, verbatim, stamped with the PCR
266	/// time of its first byte. Returns `None` once the track, or a catalog that never named one,
267	/// ends.
268	#[cfg_attr(feature = "async", kio::wrapper)]
269	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>> {
270		while let Some(catalog) = self.catalog.as_mut() {
271			match catalog.poll_next(waiter) {
272				Poll::Ready(Ok(Some(snapshot))) => {
273					self.cataloged = true;
274					self.update_catalog(&snapshot.value)?
275				}
276				Poll::Ready(Ok(None)) => self.catalog = None,
277				Poll::Ready(Err(err)) => self.leave(err)?,
278				Poll::Pending => break,
279			}
280		}
281
282		if !self.finished
283			&& let Some((name, track)) = self.track.as_mut()
284		{
285			loop {
286				if self.jitter.full(&(), waiter) {
287					let _ = track.poll_received(waiter);
288					break;
289				}
290				let (frame, arrived) = match track.poll_event(waiter) {
291					Poll::Ready(Ok(Some(Event::Frame { frame, arrived }))) => (frame, arrived),
292					Poll::Ready(Ok(Some(Event::Cut { .. }))) => {
293						self.lost = true;
294						continue;
295					}
296					Poll::Ready(Ok(Some(Event::GroupEnd | Event::FrameEnd { .. }))) => continue,
297					Poll::Ready(Ok(None)) => {
298						self.finished = true;
299						break;
300					}
301					Poll::Ready(Err(err)) => {
302						self.leave(err)?;
303						break;
304					}
305					Poll::Pending => break,
306				};
307				let skipped = track.skips() - track.markers();
308				let after_loss = std::mem::take(&mut self.lost) || skipped != self.skipped;
309				self.skipped = skipped;
310				// Judged on when the object landed, so a sink that leaves arrived objects unread
311				// does not make them late, and a stall of the whole path does not hide that they are.
312				let arrival = Arrival {
313					arrived: arrived.max(self.subscribed),
314					read: kio::clock::now(),
315					decode: frame.timestamp.try_into()?,
316					restart: self.restarts + track.markers(),
317					// The output opens on a group, at a random access point; from then on every
318					// object goes out on its own, so one dropped late is a gap of its packets only.
319					sync: frame.keyframe || self.released,
320					leading: false,
321					bytes: frame.payload.len(),
322					item: Held { frame, after_loss },
323				};
324				if self.jitter.push((), arrival)? == Push::Late {
325					self.lost = true;
326					tracing::warn!(track = %name, dropped = self.jitter.dropped(), "object missed its deadline; dropped");
327				}
328			}
329		}
330
331		if self.spread.is_none()
332			&& let Poll::Ready(ready) = self.jitter.poll_next(waiter)
333		{
334			self.released = true;
335			// No delay releases an object as it arrives, ahead of its deadline, and none is spread
336			// up to an object that follows a loss, whose interval the source spent elsewhere.
337			let (start, next) = match self.delay.is_zero() {
338				true => (kio::clock::now(), None),
339				false => (
340					ready.deadline,
341					self.jitter.front_deadline().zip(
342						self.jitter
343							.peek(&())
344							.filter(|held| !held.after_loss)
345							.map(|held| held.frame.timestamp),
346					),
347				),
348			};
349			self.spread = Some(Spread::new(ready.item.frame, start, next));
350		}
351		if let Some(spread) = self.spread.as_mut() {
352			loop {
353				if let Some(run) = spread.take(kio::clock::now()) {
354					if spread.done() {
355						self.spread = None;
356						self.timer = None;
357					}
358					return Poll::Ready(Ok(Some(run)));
359				}
360				let wake = spread.due(spread.sent);
361				let timer = self
362					.timer
363					.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(wake)));
364				if timer.deadline() != wake {
365					timer.as_mut().reset(wake);
366				}
367				if waiter.poll_future(timer.as_mut()).is_pending() {
368					return Poll::Pending;
369				}
370			}
371		}
372		let ended = match &self.track {
373			Some(_) => self.finished,
374			None => self.catalog.is_none(),
375		};
376		if !(ended && self.jitter.is_empty()) {
377			return Poll::Pending;
378		}
379		match self.failed.take() {
380			Some(err) => Poll::Ready(Err(err)),
381			None => Poll::Ready(Ok(None)),
382		}
383	}
384
385	/// The catalog or track failed with `err`. Only a publisher that left is survivable: reading
386	/// stops at once, what the jitter buffer holds goes out on its clock, and then the release
387	/// reports `err`, so a [`Follower`](super::Follower) waits for a return only once the output
388	/// before the gap has gone out, rather than leaving it buffered to go out late behind the gap.
389	fn leave(&mut self, err: crate::Error) -> crate::Result<()> {
390		if !super::follower::left(&err) {
391			return Err(err);
392		}
393		self.catalog = None;
394		self.finished = true;
395		self.failed = Some(err);
396		Ok(())
397	}
398
399	/// Subscribe to the passthrough track the catalog names, the first time it names one.
400	fn update_catalog(&mut self, catalog: &Catalog<super::Ext>) -> crate::Result<()> {
401		let Some(passthrough) = &catalog.ext.mpegts.passthrough else {
402			if self.track.is_none() && !(catalog.video.renditions.is_empty() && catalog.audio.renditions.is_empty()) {
403				return Err(
404					unsupported!("the broadcast is demultiplexed, with no passthrough track to release").into(),
405				);
406			}
407			return Ok(());
408		};
409		match &self.track {
410			None => {
411				let source =
412					ExportSource::for_stream(&self.source, &passthrough.track, export::subscribed(self.delay))?;
413				let source = export::skipping(source, self.delay);
414				// The identity returning carries on after the group it was reading, which it
415				// would otherwise replay, rather than at its live edge, which would skip the
416				// groups after it that the delay may still reach.
417				let source = match (self.resume.take(), self.replay) {
418					(Some(resume), _) => source.resuming(&resume),
419					(None, true) => source,
420					(None, false) => source.live(),
421				};
422				self.track = Some((passthrough.track.clone(), source));
423				self.subscribed = kio::clock::now();
424			}
425			Some((name, _)) if *name != passthrough.track => {
426				return Err(
427					unsupported!("the passthrough track moved from `{name}` to `{}`", passthrough.track).into(),
428				);
429			}
430			Some(_) => {}
431		}
432		Ok(())
433	}
434}
435
436impl super::follower::sealed::Followed for Release {
437	type Ext = super::Ext;
438
439	fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>> {
440		Release::poll_next(self, waiter)
441	}
442
443	fn cataloged(&self) -> bool {
444		self.cataloged
445	}
446
447	fn source(&self) -> &crate::Source {
448		&self.source
449	}
450
451	fn identity(&self) -> Option<&moq_net::Identity> {
452		self.identity.as_ref()
453	}
454
455	fn departed(&self) -> Option<&crate::Error> {
456		self.failed.as_ref()
457	}
458
459	fn depart(&mut self, err: crate::Error) -> crate::Result<()> {
460		self.leave(err)
461	}
462
463	/// Drop the track being read and read the passthrough track `catalog` names next. What the
464	/// jitter buffer holds still goes out on its clock. The same identity returning carries on
465	/// past the group it was reading; another opens a new timeline, whose clock owes the old
466	/// one nothing.
467	fn followed(
468		&mut self,
469		broadcast: &moq_net::broadcast::Consumer,
470		catalog: crate::catalog::Consumer<super::Ext>,
471		_follow: Duration,
472	) -> crate::Result<()> {
473		let same = self.identity.is_some() && broadcast.info().identity == self.identity;
474		let track = self.track.take();
475		if let Some((_, track)) = &track {
476			self.gaps += track.skips() - track.markers();
477			self.restarts += track.markers();
478		}
479		// The next track's counts start over, and its first object follows whatever the switch lost.
480		self.skipped = 0;
481		self.lost = true;
482		if same {
483			self.source.pin(broadcast);
484			// A track never read has no cursor, but an earlier one still might.
485			if let Some((_, track)) = &track {
486				self.resume = Some(track.resume());
487			}
488		} else {
489			self.source = self.source.switched(broadcast);
490			self.identity = broadcast.info().identity.clone();
491			self.resume = None;
492			self.restarts += 1;
493		}
494		self.catalog = Some(catalog);
495		self.cataloged = false;
496		self.finished = false;
497		self.failed = None;
498		Ok(())
499	}
500
501	fn catalog_format(&self) -> CatalogFormat {
502		self.format
503	}
504}