From 9089586a7aa37ad72c70f8a32ea710c755fa472d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 09:17:34 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m1/rendition-move-follow.md Quest-Claim: 14ff300ba470cb36 From 70f8d50f4b0a6214f571e81bfa4fdf7556ad8cca Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 09:33:37 -0700 Subject: [PATCH 2/2] fix: catalog readers follow a moved rendition The WebRTC egress keyed its serving rendition by catalog ID and `moq play` only re-picked once a track ended, so a catalog update moving a rendition to another track (or sibling broadcast) left both on the old one. The egress now compares the resolved track and switches like any other pick; `moq play` retires the moved rendition (audio plays out its sink's tail) and picks again. moqsrc already restarted a reshaped rendition on its pad; a test now covers it. Co-Authored-By: Claude Opus 5.5 --- quest/m1/README.md | 1 - quest/m1/rendition-move-follow.md | 24 ---- rs/moq-cli/src/play/media.rs | 223 +++++++++++++++++++++++++++--- rs/moq-cli/src/play/playback.rs | 8 +- rs/moq-gst/src/source/imp.rs | 88 ++++++++++-- rs/moq-rtc/src/egress.rs | 124 +++++++++++++++-- 6 files changed, 399 insertions(+), 69 deletions(-) delete mode 100644 quest/m1/rendition-move-follow.md diff --git a/quest/m1/README.md b/quest/m1/README.md index b94fb4ecc84..ca77af0deae 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -93,7 +93,6 @@ audit's receive-memory, priority, and lease bugs rank ahead of that reshape. - [Every close records its cause](/quest/m1/close-cause.md) - protocol-violation closes and abandoned SETUP replies record why - [Empty segments refused](/quest/m1/empty-segments.md) - `room//cam` fails loud instead of naming `room/cam` - [Readers follow restarts](/quest/m1/sink-restart-follow.md) - every moq-cli and moq-gst reader, moqsrc and `moq play` included, follows instances through `announced_broadcast` and an epochless `Restart` where its output can mark it; otherwise it stays on the old instance and fails once that route dies -- [Readers follow a moved rendition](/quest/m1/rendition-move-follow.md) - moq-rtc, moq-ffi, moq-gst and `moq play` follow a rendition the catalog moves to a new track - [In-band auth](/quest/m1/auth/README.md) - a session tells its peer what it may publish and subscribe to, unions tokens presented in band, and fails loud on an out-of-scope publish - [Cluster routing](/quest/m1/cluster-routing/README.md) - prove shared routing contracts, implement per-origin routes, and connect outbound local clusters - [Stats groups as tracks](/quest/m1/stats-group-tracks.md) - one stable node broadcast per stats producer, with each group a produced track listed by TRACKS diff --git a/quest/m1/rendition-move-follow.md b/quest/m1/rendition-move-follow.md deleted file mode 100644 index 77723f728f7..00000000000 --- a/quest/m1/rendition-move-follow.md +++ /dev/null @@ -1,24 +0,0 @@ -# [M] Catalog readers follow a moved rendition - -## Goal - -When a catalog moves a rendition to a new track, every reader that picked -it keeps playing from the new track, not only the exporters. - -## Plan - -[moq-dev/moq#6276](https://github.com/moq-dev/moq/pull/6276) made the -exporters rebind. Other readers resolve a rendition's track once: -`rs/moq-rtc/src/egress.rs` subscribes per pick, and moq-ffi's audio and video -consumers, moq-gst's source, and `moq play` are candidates to check. Audit -each, make the ones that resolve once follow catalog updates, and test a move -mid-playback for each. - -[Readers follow restarts](/quest/m1/sink-restart-follow.md) covers broadcast -restarts, not track moves inside one broadcast. - -Public API: none expected. Wire: none. - -## Related - -- [One Annex-B exporter](/quest/m1/annexb-export.md) - its shared lifecycle also follows a rebound rendition diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index 691db14fdc2..338be3c6f5a 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -128,8 +128,8 @@ impl Media { let selection = self.args.select.selection(None); let mut tasks = tokio::task::JoinSet::new(); let mut playback = Playback::default(); - let mut video_demand: Option<(String, tokio::sync::oneshot::Sender<()>)> = None; - let mut audio_demand: Option<(String, tokio::sync::oneshot::Sender<()>)> = None; + let mut video_demand: Option = None; + let mut audio_demand: Option = None; // Shared by an audio rendition and the retired tails still playing beside // it, so their sinks mix on one stream: a second stream on an exclusive // device would fail to open. Released once none of them is left, so an @@ -185,6 +185,16 @@ impl Media { stop_disabled(&mut video_demand, snapshot.video.renditions.iter().filter(|(_, config)| !config.enabled).map(|(name, _)| name)); stop_disabled(&mut audio_demand, snapshot.audio.renditions.iter().filter(|(_, config)| !config.enabled).map(|(name, _)| name)); selection.retain(&mut snapshot); + if let Some(demand) = &mut video_demand + && demand.retire_moved(&source, snapshot.video.renditions.get(&demand.name)) + { + playback.retire(Kind::Video); + } + if let Some(demand) = &mut audio_demand + && demand.retire_moved(&source, snapshot.audio.renditions.get(&demand.name)) + { + playback.retire(Kind::Audio); + } playback.received(snapshot); }, None => { @@ -273,8 +283,22 @@ impl Media { max_delay, }; let (stop, stopped) = tokio::sync::oneshot::channel(); - video_demand = Some((name.clone(), stop)); + let (retire, retired) = tokio::sync::oneshot::channel(); + video_demand = Some(Demand { + name: name.clone(), + track: reference.clone(), + stop, + retire: Some(retire), + }); tasks.spawn(async move { + // Video holds no tail beyond the frames already queued for the window, + // so a retirement stops it too. + let stopped = async { + tokio::select! { + _ = stopped => {} + Ok(()) = retired => {} + } + }; let result = until_stopped(video.run(track, decoder), stopped).await; (Kind::Video, result.map(|(finished, _)| (finished, None))) }); @@ -330,9 +354,24 @@ impl Media { output: self.output.clone(), }; let (stop, stopped) = tokio::sync::oneshot::channel(); - audio_demand = Some((name.clone(), stop)); + let (retire, retired) = tokio::sync::oneshot::channel(); + audio_demand = Some(Demand { + name: name.clone(), + track: reference.clone(), + stop, + retire: Some(retire), + }); tasks.spawn(async move { - (Kind::Audio, until_stopped(play_audio(consumer, audio), stopped).await) + // A dropped sender retires nothing. + let retired = async { + if retired.await.is_err() { + std::future::pending().await + } + }; + ( + Kind::Audio, + until_stopped(play_audio(consumer, audio, retired), stopped).await, + ) }); playback.started(Kind::Audio, reference); break; @@ -361,7 +400,7 @@ impl Media { /// rendition can be disabled after its track ended but before the end is joined. async fn until_stopped( play: impl Future>, - stopped: tokio::sync::oneshot::Receiver<()>, + stopped: impl Future, ) -> anyhow::Result<(bool, Option)> { tokio::select! { result = play => result.map(|left| (true, Some(left))), @@ -369,17 +408,35 @@ async fn until_stopped( } } +/// The rendition a half is playing, and what ends it. Dropping it stops the rendition. +struct Demand { + name: String, + track: Track, + stop: tokio::sync::oneshot::Sender<()>, + /// Ends the rendition as though its track finished, taken once sent. + retire: Option>, +} + +impl Demand { + /// Retire the rendition if `config`, its entry in a newer snapshot, moved it to another + /// track, returning whether it did. The half then picks again from that snapshot. + fn retire_moved(&mut self, source: &moq_mux::Source, config: Option<&impl hang::catalog::Reference>) -> bool { + let moved = config.is_some_and(|config| Track::of(source, config, &self.name) != self.track); + let Some(retire) = self.retire.take_if(|_| moved) else { + return false; + }; + let _ = retire.send(()); + true + } +} + // Cancel through the task's own result so it still reports which half ended. -fn stop_disabled<'a>( - playing: &mut Option<(String, tokio::sync::oneshot::Sender<()>)>, - mut disabled: impl Iterator, -) { +fn stop_disabled<'a>(playing: &mut Option, mut disabled: impl Iterator) { if playing .as_ref() - .is_some_and(|(name, _)| disabled.any(|disabled| disabled == name)) + .is_some_and(|playing| disabled.any(|disabled| *disabled == playing.name)) { - let (_, stop) = playing.take().unwrap(); - let _ = stop.send(()); + let _ = playing.take().unwrap().stop.send(()); } } @@ -405,11 +462,12 @@ struct AudioPlayback { output: O, } -/// Play a track until it ends, handing back the sink with the delay it still -/// holds. +/// Play a track until it ends, or until `retired` resolves, which ends it where +/// it stands. Either way it hands back the sink with the delay it still holds. async fn play_audio( mut consumer: moq_audio::decode::Consumer, playback: AudioPlayback, + retired: impl Future, ) -> anyhow::Result<::Sink> { let AudioPlayback { changed, @@ -478,6 +536,7 @@ async fn play_audio( // timeline can declare its end before its first PCM, so ends queue until a // frame crosses them. let receive = async { + let mut retired = std::pin::pin!(retired); // Media went missing since the last frame, so the next one does not continue it. let mut lost = false; let mut ends = VecDeque::new(); @@ -493,7 +552,11 @@ async fn play_audio( { popped.notified().await; } - let event = match consumer.read().await { + let event = tokio::select! { + event = consumer.read() => event, + () = &mut retired => Ok(None), + }; + let event = match event { Err(err) if !matches!(err, moq_audio::Error::Decode(_)) => return Err(err.into()), event => event, }; @@ -762,7 +825,11 @@ mod tests { output: recorder.clone(), }; let task = tokio::spawn(async move { - play_audio(consumer, playback).await.unwrap().finish().await; + play_audio(consumer, playback, std::future::pending()) + .await + .unwrap() + .finish() + .await; }); producer.write(packet(0, 0.25)).unwrap(); tokio::task::yield_now().await; @@ -867,7 +934,11 @@ mod tests { max_delay: delay, }; let audio_task = tokio::spawn(async move { - play_audio(consumer, audio_play).await.unwrap().finish().await; + play_audio(consumer, audio_play, std::future::pending()) + .await + .unwrap() + .finish() + .await; }); let video_task = tokio::spawn(video_play.run( moq_mux::container::Consumer::new(subscriber, Container::Legacy(moq_mux::container::Kind::Video)), @@ -1013,7 +1084,11 @@ mod tests { output: recorder.clone(), }; let task = tokio::spawn(async move { - play_audio(consumer, playback).await.unwrap().finish().await; + play_audio(consumer, playback, std::future::pending()) + .await + .unwrap() + .finish() + .await; }); let pcm = |micros: u64, samples: usize, sample: f32| moq_mux::container::Frame { timestamp: moq_net::Timestamp::from_micros(micros).unwrap(), @@ -1092,7 +1167,11 @@ mod tests { output: recorder.clone(), }; let task = tokio::spawn(async move { - play_audio(consumer, playback).await.unwrap().finish().await; + play_audio(consumer, playback, std::future::pending()) + .await + .unwrap() + .finish() + .await; }); tokio::task::yield_now().await; for index in 3..6 { @@ -1141,7 +1220,11 @@ mod tests { output: recorder.clone(), }; let task = tokio::spawn(async move { - play_audio(consumer, playback).await.unwrap().finish().await; + play_audio(consumer, playback, std::future::pending()) + .await + .unwrap() + .finish() + .await; }); for index in 0..5 { producer.write(packet(index, 0.25)).unwrap(); @@ -1390,6 +1473,104 @@ mod tests { assert_eq!(old_duration, Duration::from_secs(1)); } + /// A catalog moves the rendition to another track while the old one still + /// sends, then back. Each move plays out the retired sink's tail while the new + /// track fills, as a finished track's does, and nothing the track it left sent + /// after the move plays. A track left this way did not finish, so moving back + /// plays it again. + #[tokio::test] + async fn a_moved_audio_rendition_plays_its_new_track() { + tokio::time::pause(); + + const OLD: f32 = 0.25; + const LEFT: f32 = 0.125; + const NEW: f32 = 0.5; + const BACK: f32 = 0.75; + let delay = Duration::from_millis(500); + + let origin = moq_tokio::origin::spawn(); + let mut broadcast = origin.create_broadcast("room").unwrap(); + broadcast.announce(Default::default()).unwrap(); + let mut catalog = catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); + let track = |name: &str| { + let track = broadcast + .create_track(name, hang::container::track_info(hang::catalog::PRIORITY.audio)) + .unwrap(); + moq_mux::container::Producer::new(track, Container::Legacy(moq_mux::container::Kind::Audio)) + }; + let (mut a, mut b) = (track("a"), track("b")); + let point = |catalog: &mut catalog::Producer, track: &str| { + let mut config = AudioConfig::new(AudioCodec::Pcm, SAMPLE_RATE, 1); + config.container = hang::catalog::Container::Legacy; + config.track = Some(track.to_string()); + catalog + .mutate(|catalog| { + catalog.audio.renditions.insert("main".to_string(), config); + }) + .unwrap(); + }; + point(&mut catalog, "a"); + + let recorder = Recorder::default(); + let player = tokio::spawn(media(&origin, delay, recorder.clone()).run()); + + // Paced against absolute deadlines, as in the switch test above. Each move + // lands with only the new track's packet out, so the player takes it before + // the track it left sends again. + let start = Instant::now(); + let mut index = 0; + while index < 150 { + match index { + 0..50 => a.write(packet(index, OLD)).unwrap(), + 50 => { + b.write(packet(index, NEW)).unwrap(); + point(&mut catalog, "b"); + } + 51..100 => { + a.write(packet(index, LEFT)).unwrap(); + b.write(packet(index, NEW)).unwrap(); + } + 100 => { + a.write(packet(index, BACK)).unwrap(); + point(&mut catalog, "a"); + } + _ => a.write(packet(index, BACK)).unwrap(), + } + index += 1; + moq_clock::sleep_until(start + PACKET_DURATION * index as u32).await; + } + + settle(player, &recorder).await; + + let played = recorder.played(); + assert!( + !played.iter().any(|p| p.sample == LEFT), + "the track it left kept playing" + ); + let span = |sample: f32| { + let parts = played.iter().filter(|p| p.sample == sample); + let from = parts.clone().map(|p| p.from).min().unwrap(); + let to = parts.clone().map(|p| p.to).max().unwrap(); + let duration: Duration = parts.map(|p| p.to - p.from).sum(); + (from, to, duration) + }; + let (_, old_end, old) = span(OLD); + let (new_start, new_end, new) = span(NEW); + let (back_start, _, back) = span(BACK); + assert_eq!(old, Duration::from_secs(1), "the retired tail was cut"); + assert_eq!(new, Duration::from_secs(1), "the retired tail was cut"); + assert_eq!( + back, + Duration::from_secs(1), + "the track moved back to did not play in full" + ); + // Tokio rounds the pacing sleep to the next millisecond. + for (end, start) in [(old_end, new_start), (new_end, back_start)] { + let gap = start.saturating_duration_since(end); + assert!(gap <= Duration::from_millis(1), "the move went silent for {gap:?}"); + } + } + /// Publish an audio-only broadcast at `room` under `route`, returning what keeps /// it up and its one rendition. fn publish( diff --git a/rs/moq-cli/src/play/playback.rs b/rs/moq-cli/src/play/playback.rs index 81d2d8a0d9b..6bed70c3bfb 100644 --- a/rs/moq-cli/src/play/playback.rs +++ b/rs/moq-cli/src/play/playback.rs @@ -36,7 +36,7 @@ impl Track { #[derive(Default)] struct Half { playing: bool, - /// The track this half is playing. + /// The track this half is playing, whose end is a finish. Cleared once retired. track: Option, /// The snapshot this half last read. A half reads a snapshot once, so a /// track that ends with nothing newer on offer stays stopped rather than @@ -122,6 +122,12 @@ impl Playback { } } + /// The catalog moved this half's rendition off the track it plays, which it now + /// retires: that track ending is no finish, so a move back can play it again. + pub(super) fn retire(&mut self, kind: Kind) { + self.half_mut(kind).track = None; + } + /// Whether `track` already ended on its own. pub(super) fn finished(&self, track: &Track) -> bool { self.finished.contains(track) diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index bc4e0d5bea2..8e8a03a6da3 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -3099,15 +3099,19 @@ mod session_tests { /// Write a keyframe whose every byte is `tag`, stamped with the time since publishing so a /// synced sink renders it on time. fn write(&mut self, tag: u8) { + let frame = self.frame(tag); + self.video.write(frame).unwrap(); + } + + /// The keyframe [`Self::write`] writes for `tag`. + fn frame(&self, tag: u8) -> moq_mux::container::Frame { let elapsed = self.start.elapsed().as_micros() as u64; - self.video - .write(moq_mux::container::Frame { - timestamp: moq_net::Timestamp::from_micros(elapsed).unwrap(), - payload: bytes::Bytes::from(vec![tag; 64]), - keyframe: true, - duration: None, - }) - .unwrap(); + moq_mux::container::Frame { + timestamp: moq_net::Timestamp::from_micros(elapsed).unwrap(), + payload: bytes::Bytes::from(vec![tag; 64]), + keyframe: true, + duration: None, + } } /// Move the timestamps of later frames `by` ahead. @@ -4197,6 +4201,74 @@ mod session_tests { recorder.assert_one_pad_held(); } + /// A rendition the catalog moves to another track, in its broadcast and then in a sibling one, + /// plays on from it on the same pad, and nothing more from the track it left gets through. + #[test] + fn a_moved_rendition_plays_on_the_same_pad() { + let _pad_ids = pad_ids(); + let element = element(); + let recorder = Recorder::attach(&element); + let origin = origin(); + + let mut room = Publisher::new(&origin, Default::default(), video_rendition()); + let session = follow(&element, &origin); + let pad = recorder.written(&mut room, 1); + + // Moved to another track of the broadcast, which the publisher writes from now on. + let moved = room + .broadcast + .create_track("moved", hang::container::track_info(hang::catalog::PRIORITY.video)) + .unwrap(); + let moved = moq_mux::container::Producer::new( + moved, + moq_mux::catalog::hang::Container::Legacy(moq_mux::container::Kind::Video), + ); + let mut left = std::mem::replace(&mut room.video, moved); + room.catalog + .modify() + .unwrap() + .video + .renditions + .get_mut("video") + .unwrap() + .track = Some("moved".into()); + assert_eq!(recorder.written(&mut room, 2), pad, "the move took another pad"); + left.write(room.frame(1)).unwrap(); + recorder.written(&mut room, 3); + + // Moved to a sibling broadcast on the same clock. + let mut cam = Publisher::sibling(&origin, Default::default()); + cam.start = room.start; + { + let mut guard = room.catalog.modify().unwrap(); + let config = guard.video.renditions.get_mut("video").unwrap(); + config.track = None; + config.broadcast = Some("./cam".into()); + } + assert_eq!(recorder.written(&mut cam, 4), pad, "the move took another pad"); + room.write(3); + recorder.written(&mut cam, 5); + stop(session); + + let seen = recorder.seen(); + let after = |tag: u8| { + let at = seen + .iter() + .position(|seen| *seen == Seen::Buffer(pad.clone(), tag)) + .unwrap(); + &seen[at..] + }; + assert!( + !after(2).contains(&Seen::Buffer(pad.clone(), 1)), + "the track it left kept playing: {seen:?}" + ); + assert!( + !after(4).contains(&Seen::Buffer(pad.clone(), 3)), + "the track it left kept playing: {seen:?}" + ); + recorder.assert_one_pad_held(); + } + /// Re-pricing the same instance is an update, which the run rides out without a new stream. #[test] fn an_update_keeps_the_run() { diff --git a/rs/moq-rtc/src/egress.rs b/rs/moq-rtc/src/egress.rs index 6cfb43c632f..cac3ac03981 100644 --- a/rs/moq-rtc/src/egress.rs +++ b/rs/moq-rtc/src/egress.rs @@ -277,6 +277,21 @@ impl Rendition { } } + /// The track the rendition reads through `source`. + fn target(&self, source: &moq_mux::Source) -> Target { + use hang::catalog::Reference; + + let (name, config): (_, &dyn Reference) = match self { + Self::Audio(name, config) => (name, config), + Self::Video(name, config) => (name, config), + }; + Target { + path: source.resolve_reference(config.broadcast()), + epoch: config.epoch().cloned(), + track: config.track(name).to_string(), + } + } + /// Subscribe to the rendition, honoring its cross-broadcast reference (the catalog /// `broadcast` field). async fn subscribe(self, source: moq_mux::Source) -> Result { @@ -309,9 +324,19 @@ fn pick_audio<'a>( }) } +/// The track a rendition reads: its broadcast's path, the publisher instance that broadcast +/// must be, and the track's name there. A catalog update that changes it moves the rendition. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Target { + path: Option, + epoch: Option, + track: String, +} + /// A subscribed rendition, sent in `format`. struct Serving { name: String, + target: Target, format: Format, track: codec::Track, } @@ -319,18 +344,19 @@ struct Serving { /// A rendition whose subscription is still resolving. struct Subscribing { name: String, + target: Target, format: Format, track: std::pin::Pin> + Send>>, } /// Serves one negotiated media line from the best enabled rendition in its codecs. /// -/// The pump re-picks on every catalog change. A better or newly enabled rendition is -/// subscribed beside the current one, which keeps flowing until the new one reaches a -/// keyframe past the line's playhead, so a switch leaves no gap and never steps back in -/// time: a new subscription starts at the rendition's latest group, which for one re-enabled -/// is the stale group it stopped on. A switch across codecs changes the payload type at that -/// keyframe. With nothing enabled it serves nothing until a +/// The pump re-picks on every catalog change. A better or newly enabled rendition, or the +/// current one moved to another track, is subscribed beside the current one, which keeps +/// flowing until the new one reaches a keyframe past the line's playhead, so a switch leaves +/// no gap and never steps back in time: a new subscription starts at the rendition's latest +/// group, which for one re-enabled is the stale group it stopped on. A switch across codecs +/// changes the payload type at that keyframe. With nothing enabled it serves nothing until a /// rendition re-enables. There is no ABR on the peer, so a re-enabled top rendition wins /// the line back. /// @@ -364,7 +390,8 @@ impl Pump { loop { if repick { repick = false; - let pick = pick(&self.source, &self.catalog.borrow_and_update(), &self.formats); + let pick = pick(&self.source, &self.catalog.borrow_and_update(), &self.formats) + .map(|(pick, format)| (pick.target(&self.source), pick, format)); match pick { None => { if serving.is_some() || next.is_some() || subscribing.is_some() { @@ -375,17 +402,20 @@ impl Pump { subscribing = None; held = Held::default(); } - Some((pick, _)) if serving.as_ref().is_some_and(|s| s.name == pick.name()) => { + // Compared by track rather than by ID: a rendition the catalog moves to + // another track switches to it like any other pick. + Some((target, ..)) if serving.as_ref().is_some_and(|s| s.target == target) => { next = None; subscribing = None; } - Some((pick, _)) - if next.as_ref().is_some_and(|s| s.name == pick.name()) - || subscribing.as_ref().is_some_and(|s| s.name == pick.name()) => {} - Some((pick, format)) => { + Some((target, ..)) + if next.as_ref().is_some_and(|s| s.target == target) + || subscribing.as_ref().is_some_and(|s| s.target == target) => {} + Some((target, pick, format)) => { next = None; subscribing = Some(Subscribing { name: pick.name().to_string(), + target, format, track: Box::pin(pick.subscribe(self.source.clone())), }); @@ -410,10 +440,10 @@ impl Pump { // The session is gone, even if this line is idle. _ = self.tx.closed() => return, subscribed = subscribe(&mut subscribing) => { - let Subscribing { name, format, .. } = subscribing.take().expect("a subscription resolved"); + let Subscribing { name, target, format, .. } = subscribing.take().expect("a subscription resolved"); match subscribed { Ok(track) => { - next = Some(Serving { name, format, track }); + next = Some(Serving { name, target, format, track }); held.reached = None; } Err(err) => tracing::warn!(mid = ?self.mid, rendition = name, %err, "egress track subscribe failed"), @@ -853,6 +883,72 @@ mod tests { assert_eq!(written(&mut writes).await.as_ref(), b"high-1"); } + /// A rendition the catalog moves to another track, in its broadcast or a sibling one, keeps + /// its media line: the line switches to the new track at its first keyframe past the + /// playhead and serves nothing more of the track it left, even while that one still sends. + #[tokio::test(start_paused = true)] + async fn a_moved_rendition_follows_its_new_track() { + let origin = produce_origin(); + let mut live = origin.publish("live", Default::default()).unwrap(); + let mut other = origin.publish("other", Default::default()).unwrap(); + let mut catalog = moq_mux::catalog::Producer::new(&mut live, moq_mux::catalog::Config::default()).unwrap(); + let track = |broadcast: &mut moq_net::broadcast::Producer, name: &str| { + let info = moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI); + moq_mux::container::Producer::new( + broadcast.create_track(name, info).unwrap(), + moq_mux::catalog::hang::Container::Legacy(moq_mux::container::Kind::Video), + ) + }; + let mut a = track(&mut live, "a"); + let mut b = track(&mut live, "b"); + let mut sibling = track(&mut other, "a"); + let point = |catalog: &mut moq_mux::catalog::Producer, track: &str, broadcast: Option<&str>| { + let mut config = VideoConfig::new(VideoCodec::VP8); + config.container = hang::catalog::Container::Legacy; + config.track = Some(track.to_string()); + config.broadcast = broadcast.map(|broadcast| Relative::new(broadcast).into_owned()); + catalog + .modify() + .unwrap() + .video + .renditions + .insert("main".to_string(), config); + }; + point(&mut catalog, "a", None); + + let broadcast = origin.consume().request_broadcast("live", None).await.unwrap(); + let mut egress = EgressSource::new(moq_mux::Source::new(origin.consume(), broadcast)) + .await + .unwrap(); + let mut writes = egress.take_writes(); + egress.on_track(Mid::from("0"), vec![format(Codec::Vp8, 96)]).unwrap(); + + a.write(frame(0, b"a-0", true)).unwrap(); + assert_eq!(written(&mut writes).await.as_ref(), b"a-0"); + + // Moved within the broadcast: the old track is paced to the new one until its keyframe. + point(&mut catalog, "b", None); + idle(&mut writes).await; + a.write(frame(33, b"a-1", false)).unwrap(); + idle(&mut writes).await; + b.write(frame(66, b"b-2", true)).unwrap(); + assert_eq!(written(&mut writes).await.as_ref(), b"a-1"); + assert_eq!(written(&mut writes).await.as_ref(), b"b-2"); + a.write(frame(100, b"a-3", false)).unwrap(); + idle(&mut writes).await; + + // Moved to a sibling broadcast. + point(&mut catalog, "a", Some("other")); + idle(&mut writes).await; + sibling.write(frame(100, b"sibling-3", true)).unwrap(); + assert_eq!(written(&mut writes).await.as_ref(), b"sibling-3"); + a.write(frame(133, b"a-4", false)).unwrap(); + b.write(frame(133, b"b-4", false)).unwrap(); + idle(&mut writes).await; + sibling.write(frame(133, b"sibling-4", false)).unwrap(); + assert_eq!(written(&mut writes).await.as_ref(), b"sibling-4"); + } + /// A line that negotiated both codecs serves the preferred rendition in its payload type, /// and switches payload type when it falls back. #[tokio::test(start_paused = true)]