Skip to main content

moq_mux/container/ts/
republish.rs

1//! One program of a multiplex, republished on its path whenever the source changes.
2
3use bytes::{Bytes, BytesMut};
4
5use super::error::{Error, Result};
6use super::{Ext, Import, Step, stats};
7use crate::catalog;
8
9/// Imports one program of a multiplex as a broadcast on `origin`, republishing the path under a
10/// new identity each time the source changes.
11///
12/// The single-program sibling of [`Programs`](super::Programs). Each identity is created hidden
13/// and announced once its catalog first goes out: a relay queries a broadcast's tracks the moment
14/// it is announced, so one announced any sooner would be asked for tracks it cannot serve yet.
15///
16/// A change of source is a [`Step`]: the source's clock moving onto another timeline, or its PAT
17/// naming another program, as [`Import::decode`] judges it. [`decode`](Self::decode) then
18/// finishes the identity before the step, withdrawing it, and opens the next under a new
19/// identity, returning the step as [`Republished`]. Nothing crosses it but the measured mux rate:
20/// the new catalog records it from its first media rather than holding for a fresh measurement
21/// window, since the multiplex is the same. The new identity waits for the source's own PAT, PMT
22/// and next keyframe.
23pub struct Republish {
24	target: Target,
25	identity: Identity,
26	/// The input after the last step, which the current identity has not read yet.
27	held: Bytes,
28}
29
30/// The source changed, so [`Republish`] finished the identity before the change and opened the
31/// next one, hidden until its catalog goes out.
32#[derive(Clone, Debug)]
33#[non_exhaustive]
34pub struct Republished {
35	/// How the source changed.
36	pub step: Step,
37	/// What the finished identity's elementary streams delivered; see [`Import::stats`].
38	pub stats: stats::Snapshot,
39}
40
41/// Where and how each identity publishes.
42struct Target {
43	origin: moq_net::origin::Producer,
44	name: moq_net::Path,
45	config: catalog::Config,
46	program: Option<u16>,
47}
48
49impl Target {
50	/// Open an identity with `options`, its catalog recording `mux_rate` when the multiplex was
51	/// measured already.
52	fn open(&self, options: moq_net::origin::RouteOptions, mux_rate: Option<u64>) -> Result<Identity> {
53		let route = self.origin.route(self.name.as_str(), options)?;
54		// TS carries undecoded elementary streams verbatim, so the catalog carries the `mpegts`
55		// extension.
56		let mut initial = catalog::hang::Catalog::<Ext>::default();
57		initial.ext.mpegts.mux_rate = mux_rate;
58		let config = self.config.clone().with_catalog(initial);
59		let catalog = catalog::Producer::new(&mut route.broadcast().clone(), config)?;
60		let mut import = Import::new(route.broadcast().clone(), catalog.reserve());
61		if let Some(program) = self.program {
62			import = import.with_program(program);
63		}
64		let pending = Some(route.broadcast().consume().track(hang::Catalog::DEFAULT_NAME)?);
65		Ok(Identity {
66			route,
67			import,
68			catalog,
69			pending,
70		})
71	}
72}
73
74/// One identity of the broadcast.
75struct Identity {
76	/// Created hidden: dropping it retracts the broadcast the importer fills.
77	route: moq_net::origin::Route,
78	import: Import<Ext>,
79	catalog: catalog::Producer<Ext>,
80	/// The catalog track until the catalog first goes out, when the route announces.
81	pending: Option<moq_net::track::Consumer>,
82}
83
84impl Identity {
85	/// Announce the broadcast once its catalog has gone out, returning whether it has.
86	fn announce_if_listed(&mut self) -> Result<bool> {
87		listed(&mut self.pending, &self.route)
88	}
89
90	/// Finish the media tracks, then the catalog while it still lists them, aborting both with the
91	/// cause of a failure.
92	///
93	/// The `last` identity announces if its drain released the first catalog, and fails when the
94	/// input declared no track. One a step ended is withdrawn as it drops, so it does neither: a
95	/// source can step before its first catalog goes out, such as within the mux rate's window.
96	fn finish(mut self, last: bool) -> Result<Finished> {
97		let import = match self.import.finish() {
98			Ok(import) => import,
99			Err(err) => {
100				self.catalog.abort(moq_net::Error::Transport(format!("{err:#}")));
101				return Err(err);
102			}
103		};
104		// The drain at end of input can release the first catalog. Without one the input declared
105		// no track, and announcing would only advertise an empty broadcast.
106		let declared = match last {
107			true => listed(&mut self.pending, &self.route).and_then(|declared| match declared {
108				true => Ok(()),
109				false => Err(Error::Empty("it declared a track")),
110			}),
111			false => Ok(()),
112		};
113		let declared = declared.and_then(|()| Ok(self.catalog.finish()?));
114		if let Err(err) = declared {
115			let reason = moq_net::Error::Transport(format!("{err:#}"));
116			import.abort(reason.clone());
117			self.catalog.abort(reason);
118			return Err(err);
119		}
120		Ok(Finished {
121			import,
122			_catalog: self.catalog,
123			route: self.route,
124		})
125	}
126}
127
128impl Republish {
129	/// Import the multiplex onto `name`, its catalogs built from `config`, publishing the first
130	/// identity as `identity` and each after it under a fresh one. The first is created now, so
131	/// its [`catalog`](Self::catalog) can be filled before any input.
132	///
133	/// Pass [`Identity::random`](moq_net::Identity::random) unless the identity is shared, such as
134	/// across a run's broadcasts; see [`RouteOptions::with_identity`](moq_net::origin::RouteOptions::with_identity).
135	pub fn new(
136		origin: moq_net::origin::Producer,
137		name: impl Into<moq_net::Path>,
138		identity: moq_net::Identity,
139		config: catalog::Config,
140	) -> Result<Self> {
141		let target = Target {
142			origin,
143			name: name.into(),
144			config,
145			program: None,
146		};
147		let options = moq_net::origin::RouteOptions::hidden().with_identity(identity, 0);
148		let identity = target.open(options, None)?;
149		Ok(Self {
150			target,
151			identity,
152			held: Bytes::new(),
153		})
154	}
155
156	/// Import only the program with this PAT program number; see [`Import::with_program`].
157	pub fn with_program(mut self, program: u16) -> Self {
158		self.target.program = Some(program);
159		self.identity.import = self.identity.import.with_program(program);
160		self
161	}
162
163	/// The current identity's broadcast, such as for a track of the caller's own.
164	pub fn broadcast(&self) -> &moq_net::broadcast::Producer {
165		self.identity.route.broadcast()
166	}
167
168	/// The current identity's catalog. Sections set before the importer declares a track ride
169	/// the first catalog; set them again on each new identity after [`Republished`].
170	pub fn catalog(&self) -> &catalog::Producer<Ext> {
171		&self.identity.catalog
172	}
173
174	/// The current identity's publisher identity.
175	pub fn identity(&self) -> moq_net::Identity {
176		self.identity.route.identity()
177	}
178
179	/// Demux a chunk of the multiplex into the current identity, announcing it once its catalog
180	/// goes out. A trailing partial packet is retained for the next call.
181	///
182	/// A change of source finishes the identity there and opens the next, returning
183	/// [`Republished`] before the next reads anything: the rest of `data` is held for it, read at
184	/// the start of the next call. Call again, with no data if there is none, until it returns
185	/// `None`. A failure to finish the identity before the step returns that failure, with the
186	/// next identity current.
187	pub fn decode(&mut self, data: &[u8]) -> Result<Option<Republished>> {
188		if !self.held.is_empty() {
189			let held = std::mem::take(&mut self.held);
190			if let Some(republished) = self.feed(&held)? {
191				if !data.is_empty() {
192					let mut rest = BytesMut::from(std::mem::take(&mut self.held));
193					rest.extend_from_slice(data);
194					self.held = rest.freeze();
195				}
196				return Ok(Some(republished));
197			}
198		}
199		self.feed(data)
200	}
201
202	/// Demux `data` into the current identity, or republish at the step it reaches.
203	fn feed(&mut self, data: &[u8]) -> Result<Option<Republished>> {
204		let Some(restart) = self.identity.import.decode_or_restart(data)? else {
205			self.identity.announce_if_listed()?;
206			return Ok(None);
207		};
208		self.republish(restart).map(Some)
209	}
210
211	/// No input follows: read what the current identity held while judging a step, and
212	/// republish at a step it reaches.
213	fn settle(&mut self) -> Result<Option<Republished>> {
214		match self.identity.import.settle()? {
215			Some(restart) => self.republish(restart).map(Some),
216			None => Ok(None),
217		}
218	}
219
220	/// Finish the current identity before `restart`'s step and open the next, holding the input
221	/// from the step on for it.
222	fn republish(&mut self, restart: super::Restart) -> Result<Republished> {
223		let mux_rate = self.identity.catalog.snapshot().ext.mpegts.mux_rate;
224		let next = self.target.open(moq_net::origin::RouteOptions::hidden(), mux_rate)?;
225		self.held = restart.remainder;
226		// The finished identity ends as it drops, withdrawing its announcement.
227		let finished = std::mem::replace(&mut self.identity, next).finish(false)?;
228		Ok(Republished {
229			step: restart.step,
230			stats: finished.stats(),
231		})
232	}
233
234	/// What every elementary stream of the current identity has delivered; see [`Import::stats`].
235	pub fn stats(&self) -> stats::Snapshot {
236		self.identity.import.stats()
237	}
238
239	/// Finish the current identity's media tracks, then its catalog while it still lists them,
240	/// and return the [`Finished`] broadcast.
241	///
242	/// Input still held after a [`Republished`], or while a step was judged, is read first,
243	/// republishing again at any step in it. Fails when the input ended before the identity
244	/// declared a track, so nothing was announced. A finish that fails aborts every track with
245	/// the cause.
246	pub fn finish(mut self) -> Result<Finished> {
247		loop {
248			let next = match self.decode(&[]) {
249				Ok(None) => self.settle(),
250				next => next,
251			};
252			match next {
253				Ok(Some(republished)) => {
254					tracing::warn!(step = %republished.step, "the source changed at end of input; republishing")
255				}
256				Ok(None) => return self.identity.finish(true),
257				Err(err) => {
258					self.abort(moq_net::Error::Transport(format!("{err:#}")));
259					return Err(err);
260				}
261			}
262		}
263	}
264
265	/// Abort the current identity's catalog and media tracks with `err`. Consumes the importer.
266	pub fn abort(self, err: moq_net::Error) {
267		let Identity { import, catalog, .. } = self.identity;
268		catalog.abort(err.clone());
269		import.abort(err);
270	}
271}
272
273/// Announce `route` once the catalog track `pending` has a group, returning whether it has.
274pub(super) fn listed(pending: &mut Option<moq_net::track::Consumer>, route: &moq_net::origin::Route) -> Result<bool> {
275	let Some(listed) = pending else {
276		return Ok(true);
277	};
278	if !matches!(
279		listed.poll_largest(&kio::Waiter::noop()),
280		std::task::Poll::Ready(Some(_))
281	) {
282		return Ok(false);
283	}
284	route.announce()?;
285	*pending = None;
286	Ok(true)
287}
288
289/// A [`Republish`] [finished](Republish::finish): every track of its last identity has ended,
290/// and they stay servable while it is held.
291#[must_use = "dropping it releases the tracks and withdraws the broadcast"]
292pub struct Finished {
293	import: super::Finished<Ext>,
294	_catalog: catalog::Producer<Ext>,
295	route: moq_net::origin::Route,
296}
297
298impl Finished {
299	/// The finished broadcast, such as for a [`Linger`](crate::Linger).
300	pub fn broadcast(&self) -> &moq_net::broadcast::Producer {
301		self.route.broadcast()
302	}
303
304	/// What every elementary stream delivered; see [`Import::stats`].
305	pub fn stats(&self) -> stats::Snapshot {
306		self.import.stats()
307	}
308
309	/// Abort every track with `err`. Readers still draining a track get its clean end instead once
310	/// every group below its end finished.
311	pub fn abort(self, err: moq_net::Error) {
312		self.import.abort(err);
313	}
314}
315
316#[cfg(test)]
317mod tests {
318	use super::super::step_test::{SWITCH, flagged_switch, shift};
319	use super::*;
320
321	/// 5 s of H.264 and AAC at a constant 400 kb/s, so the first identity measures a rate.
322	const CLIP: &[u8] = include_bytes!("test_data/bbb5s_cbr.ts");
323
324	/// Whether `stats` counts a delivered unit.
325	fn delivered(stats: &stats::Snapshot) -> bool {
326		stats.streams.values().any(|stream| stream.units > 0)
327	}
328
329	/// A switch to an encoder whose clock started hours earlier comes back from `decode` as a
330	/// value. The identity before it finishes, and the next opens under a new identity, its
331	/// catalog carrying the measured mux rate, hidden until that catalog goes out. However the
332	/// input is split, the next identity reads it from the step on.
333	#[test]
334	fn a_switch_republishes_under_a_new_identity_with_the_rate() {
335		let open = || {
336			let origin = crate::source::produce_origin();
337			Republish::new(
338				origin,
339				moq_net::Path::from_static("demo"),
340				moq_net::Identity::random(),
341				catalog::Config::default(),
342			)
343			.unwrap()
344		};
345		let mut measured = open();
346		assert!(measured.decode(CLIP).unwrap().is_none());
347		let rate = measured.catalog().snapshot().ext.mpegts.mux_rate;
348		assert!(rate.is_some(), "the clip measures a rate");
349
350		let mut data = CLIP.to_vec();
351		data.extend(shift(CLIP, |_| -SWITCH));
352		for chunk in [data.len(), 188 * 7, 1_000] {
353			let mut republish = open();
354			let first = republish.identity();
355			let mut republished = Vec::new();
356			for piece in data.chunks(chunk) {
357				let mut next = republish.decode(piece).unwrap();
358				while let Some(step) = next {
359					assert!(
360						!republish.identity.route.is_announced(),
361						"{chunk}: announced before its catalog"
362					);
363					assert_eq!(
364						republish.catalog().snapshot().ext.mpegts.mux_rate,
365						rate,
366						"{chunk}: the next catalog carries the measured rate"
367					);
368					republished.push(step);
369					next = republish.decode(&[]).unwrap();
370				}
371			}
372			let [step] = &republished[..] else {
373				panic!("{chunk}: one switch: {republished:?}");
374			};
375			assert!(
376				matches!(step.step, Step::Rewind { flagged: false, .. }),
377				"{chunk}: {step:?}"
378			);
379			assert!(delivered(&step.stats), "{chunk}: the first identity's counts");
380			assert_ne!(republish.identity(), first, "{chunk}: a new identity");
381			assert!(
382				republish.identity.route.is_announced(),
383				"{chunk}: the next identity announced with its catalog"
384			);
385			let finished = republish.finish().unwrap();
386			assert!(
387				delivered(&finished.stats()),
388				"{chunk}: the next identity read the input after the step"
389			);
390		}
391	}
392
393	/// A source that steps in the same chunk as its first media, before its first catalog went
394	/// out, republishes rather than failing: only the last identity has to declare a track.
395	#[test]
396	fn a_switch_before_the_first_catalog_republishes() {
397		// 1.5 s of input, then the step, all in one chunk.
398		let mut data = CLIP[..400 * 188].to_vec();
399		data.extend(shift(CLIP, |_| -SWITCH));
400		let origin = crate::source::produce_origin();
401		let mut republish = Republish::new(
402			origin,
403			moq_net::Path::from_static("demo"),
404			moq_net::Identity::random(),
405			catalog::Config::default(),
406		)
407		.unwrap();
408		let first = republish.identity.route.clone();
409		let step = republish.decode(&data).unwrap().expect("a switch");
410		assert!(matches!(step.step, Step::Rewind { .. }), "{step:?}");
411		assert!(!first.is_announced(), "the first identity never went out");
412		assert!(republish.decode(&[]).unwrap().is_none());
413		let finished = republish.finish().unwrap();
414		assert!(delivered(&finished.stats()));
415	}
416
417	/// A switch the input ends while judging is found by `finish`, which republishes the
418	/// broadcast after it rather than drop it.
419	#[test]
420	fn a_switch_found_at_the_end_republishes() {
421		let origin = crate::source::produce_origin();
422		let mut republish = Republish::new(
423			origin,
424			moq_net::Path::from_static("demo"),
425			moq_net::Identity::random(),
426			catalog::Config::default(),
427		)
428		.unwrap();
429		let first = republish.identity();
430		let decoded = republish.decode(&flagged_switch()).unwrap();
431		assert!(decoded.is_none(), "the switch is still judged: {decoded:?}");
432		let finished = republish.finish().unwrap();
433		assert_ne!(finished.route.identity(), first, "the finish republished");
434		assert!(
435			delivered(&finished.stats()),
436			"the next identity read the input after the step"
437		);
438	}
439
440	/// Held input that fails to decode at the finish aborts the identity reading it, so its
441	/// readers get the cause rather than a clean end.
442	#[tokio::test(start_paused = true)]
443	async fn a_failure_in_held_input_aborts_the_identity() {
444		let mut data = CLIP.to_vec();
445		data.extend(shift(CLIP, |_| -SWITCH));
446		// A second program appearing mid-stream ends an import that picked none.
447		data.extend(
448			super::super::fixture::Mux::default()
449				.pat(&[(1, 0x100), (2, 0x200)])
450				.bytes(),
451		);
452		let origin = crate::source::produce_origin();
453		let mut republish = Republish::new(
454			origin,
455			moq_net::Path::from_static("demo"),
456			moq_net::Identity::random(),
457			catalog::Config::default(),
458		)
459		.unwrap();
460		republish.decode(&data).unwrap().expect("a switch");
461		// The next identity's media tracks only exist within the finish, so read its catalog, which
462		// is aborted with them. A held copy keeps a mere drop from ending it.
463		let _copy = republish.catalog().clone();
464		let mut catalog = republish
465			.broadcast()
466			.consume()
467			.track(hang::Catalog::DEFAULT_NAME)
468			.unwrap()
469			.subscribe(None)
470			.await
471			.unwrap();
472		let err = republish.finish().err().expect("two programs");
473		assert!(matches!(err, Error::MultiplePrograms { .. }), "{err}");
474		let ended = kio::clock::timeout(std::time::Duration::from_secs(1), async {
475			loop {
476				if let Err(err) = catalog.recv_group().await.transpose()? {
477					return Some(err);
478				}
479			}
480		})
481		.await
482		.expect("the catalog ends");
483		assert!(ended.is_some(), "the catalog ends with the cause, not cleanly");
484	}
485
486	/// Input that ends before declaring a track fails, and nothing was announced.
487	#[test]
488	fn an_input_with_no_track_fails_unannounced() {
489		let origin = crate::source::produce_origin();
490		let republish = Republish::new(
491			origin,
492			moq_net::Path::from_static("demo"),
493			moq_net::Identity::random(),
494			catalog::Config::default(),
495		)
496		.unwrap();
497		let route = republish.identity.route.clone();
498		let err = republish.finish().err().expect("nothing was declared");
499		assert!(matches!(err, Error::Empty("it declared a track")), "{err}");
500		assert!(!route.is_announced());
501	}
502}