1use bytes::{Bytes, BytesMut};
4
5use super::error::{Error, Result};
6use super::{Ext, Import, Step, stats};
7use crate::catalog;
8
9pub struct Republish {
24 target: Target,
25 identity: Identity,
26 held: Bytes,
28}
29
30#[derive(Clone, Debug)]
33#[non_exhaustive]
34pub struct Republished {
35 pub step: Step,
37 pub stats: stats::Snapshot,
39}
40
41struct 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 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 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
74struct Identity {
76 route: moq_net::origin::Route,
78 import: Import<Ext>,
79 catalog: catalog::Producer<Ext>,
80 pending: Option<moq_net::track::Consumer>,
82}
83
84impl Identity {
85 fn announce_if_listed(&mut self) -> Result<bool> {
87 listed(&mut self.pending, &self.route)
88 }
89
90 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 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 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 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 pub fn broadcast(&self) -> &moq_net::broadcast::Producer {
165 self.identity.route.broadcast()
166 }
167
168 pub fn catalog(&self) -> &catalog::Producer<Ext> {
171 &self.identity.catalog
172 }
173
174 pub fn identity(&self) -> moq_net::Identity {
176 self.identity.route.identity()
177 }
178
179 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 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 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 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 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 pub fn stats(&self) -> stats::Snapshot {
236 self.identity.import.stats()
237 }
238
239 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 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
273pub(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#[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 pub fn broadcast(&self) -> &moq_net::broadcast::Producer {
301 self.route.broadcast()
302 }
303
304 pub fn stats(&self) -> stats::Snapshot {
306 self.import.stats()
307 }
308
309 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 const CLIP: &[u8] = include_bytes!("test_data/bbb5s_cbr.ts");
323
324 fn delivered(stats: &stats::Snapshot) -> bool {
326 stats.streams.values().any(|stream| stream.units > 0)
327 }
328
329 #[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 #[test]
396 fn a_switch_before_the_first_catalog_republishes() {
397 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 #[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 #[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 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 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 #[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}