From 13632ff9ee53aeee1a0c29ff4120a48d27ab7756 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 10:25:31 -0700 Subject: [PATCH 01/12] chore(quest): claim quest/m1/broadcast-lifecycle/stateless.md Quest-Claim: 3d222efa25edb8c0 From b6b951feea50b4cdb4adfd305ac483b3c34c8a38 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 10:55:41 -0700 Subject: [PATCH 02/12] fix(net): a relay finishes an ended lite subscription when its session dies A lite-03 or lite-04 publisher declares no end, so the relay waits out a tail grace after the subscription's FIN. A session ending during that grace aborted the track, and a downstream subscriber still behind lost every group the relay held. The FIN already said the track is over, so finish it. Adds a relay test proving a finished track reaches existing downstream subscribers after the upstream session closes or aborts, on lite and moq-transport. Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/lite/subscriber.rs | 15 +- rs/moq-net/src/tail.rs | 14 ++ rs/moq-net/tests/integration/main.rs | 1 + .../tests/integration/relay_upstream_close.rs | 190 ++++++++++++++++++ 4 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 rs/moq-net/tests/integration/relay_upstream_close.rs diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index a4436f442e7..1b29fa75217 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -549,14 +549,24 @@ struct SubscriptionCleanup(Lock>); impl SubscriptionCleanup { /// End every active subscription with the session's error. Group machines own /// their cleanup independently; this records the track's terminal state. + /// + /// A subscription the publisher already ended finishes instead, here and on + /// [`Self::close`]: its track is over, and what arrived stays servable to readers + /// still behind rather than handed to another route. fn abort(&self, err: &Error) { for (_, entry) in self.0.lock().drain() { - let _ = entry.producer.abort(err.clone()); + let _ = match entry.tail.read().is_ended() { + true => entry.producer.finish(), + false => entry.producer.abort(err.clone()), + }; } } fn close(&self) { for (_, entry) in self.0.lock().drain() { - let _ = entry.producer.close(); + let _ = match entry.tail.read().is_ended() { + true => entry.producer.finish(), + false => entry.producer.close(), + }; } } } @@ -7518,6 +7528,7 @@ impl ServeLoop { // (it bounds presentation-time drift), but it is how long the // subscriber was willing to wait for a late group anyway. if let Ok(mut tail) = active.tail.write() { + tail.end(); tail.set_grace(tail::grace( subscription.map(|sub| sub.max_delay).unwrap_or_default(), )); diff --git a/rs/moq-net/src/tail.rs b/rs/moq-net/src/tail.rs index 8e8a8b41f26..b1173ab0ef0 100644 --- a/rs/moq-net/src/tail.rs +++ b/rs/moq-net/src/tail.rs @@ -25,6 +25,9 @@ pub(crate) struct Tail { streams: u64, // Streams whose header arrived and that are still being read. active: u64, + // The publisher ended the subscription, so the track is over even if the session + // dies before the tail settles. + ended: bool, } impl Default for Tail { @@ -40,9 +43,20 @@ impl Tail { ledger: Ledger::new(grace), streams: 0, active: 0, + ended: false, } } + /// Record that the publisher ended the subscription. + pub fn end(&mut self) { + self.ended = true; + } + + /// Whether the publisher ended the subscription. + pub fn is_ended(&self) -> bool { + self.ended + } + /// Change the grace, for a subscription whose max delay changed. pub fn set_grace(&mut self, grace: Duration) { self.ledger.set_grace(grace); diff --git a/rs/moq-net/tests/integration/main.rs b/rs/moq-net/tests/integration/main.rs index beba1f08794..4fabab8afd5 100644 --- a/rs/moq-net/tests/integration/main.rs +++ b/rs/moq-net/tests/integration/main.rs @@ -45,6 +45,7 @@ mod quiet_catalog; mod range_anchors; mod received_rewind; mod refresh; +mod relay_upstream_close; mod rejoin; mod replacement; mod request_caps; diff --git a/rs/moq-net/tests/integration/relay_upstream_close.rs b/rs/moq-net/tests/integration/relay_upstream_close.rs new file mode 100644 index 00000000000..8cd84b1f37a --- /dev/null +++ b/rs/moq-net/tests/integration/relay_upstream_close.rs @@ -0,0 +1,190 @@ +#![cfg(feature = "async")] + +//! A finished track keeps reaching a relay's existing subscribers after the publisher's +//! session to the relay ends, cleanly or not. +//! +//! A broadcast has no finished state: a publisher ends its content with a track FIN and +//! goes offline by closing. So nothing keeps the upstream session up for a downstream +//! subscriber still behind: the relay has to serve the tail from its own copy. +//! +//! Deterministic: simulated time over the mock transport. The relay's group streams to +//! the subscriber are held, with a one-message stream buffer, so the relay still holds +//! most of the track when the upstream session ends. + +use crate::support; + +use std::time::Duration; + +use moq_net::track::Subscription; +use moq_net::{Error, Hop, Timestamp, Version}; +use support::harness::{MockConnectOptions, connect_mock}; + +/// A millisecond track: the frames written here carry timestamps. +fn timed() -> moq_net::track::Info { + moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI) +} + +const TIMEOUT: Duration = Duration::from_secs(10); +/// Lite03 and Lite04 declare no end, so each hop waits this long for a group still owed. +const MAX_DELAY: Duration = Duration::from_secs(1); +const GROUPS: u64 = 4; +const FRAMES: u64 = 8; + +const VERSIONS: &[&str] = &[ + "moq-lite-03", + "moq-lite-04", + "moq-lite-05", + "moq-lite-06", + "moq-lite-07-wip", + "moq-transport-14", + "moq-transport-17", + "moq-transport-22", +]; + +fn produce_origin(hop: u64) -> moq_net::origin::Producer { + let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + support::harness::spawn(driver); + producer +} + +/// How the publisher's session to the relay ends. +#[derive(Clone, Copy, Debug)] +enum End { + /// `Session::close`, which drains the tail first. + Close, + /// `Session::abort`, once the relay has the whole track. + Abort, +} + +/// Publish a finished track through a relay, end the publisher's session while the +/// subscriber has read none of it, and return the frames it then reads and how it ended. +async fn round(name: &str, end: End) -> (Vec<(u64, u64)>, Result<(), Error>) { + let version: Version = name.parse().unwrap(); + let publisher = produce_origin(1); + let broadcast = publisher.create_broadcast("bcast").unwrap(); + let track = broadcast.create_track("video", timed()).unwrap(); + broadcast.announce(Default::default()).unwrap(); + + let relay = produce_origin(2); + let mut options = MockConnectOptions::new(version); + options.server_publish = Some(publisher.consume()); + options.client_subscribe = Some(relay.clone()); + let upstream = connect_mock(options).await; + + let subscriber = produce_origin(3); + let mut options = MockConnectOptions::new(version); + options.transport.stream_buffer = 0; + options.server_publish = Some(relay.consume()); + options.client_subscribe = Some(subscriber.clone()); + let downstream = connect_mock(options).await; + + let consumer = subscriber.consume(); + moq_clock::timeout(TIMEOUT, consumer.routed("bcast")) + .await + .expect("announce timeout") + .expect("routed"); + let remote = moq_clock::timeout(TIMEOUT, consumer.request_broadcast("bcast", None)) + .await + .expect("resolve timeout") + .expect("broadcast resolves"); + + let (ready, active) = futures::channel::oneshot::channel(); + let reader = moq_clock::sim::spawn(async move { + let subscription = Subscription::default().with_max_delay(MAX_DELAY).with_groups(0..); + let mut sub = remote + .track("video") + .unwrap() + .subscribe(subscription) + .await + .expect("subscribe"); + let _ = ready.send(()); + let mut got = Vec::new(); + loop { + let mut group = match sub.recv_group().await { + Ok(Some(group)) => group, + Ok(None) => return (got, Ok(())), + Err(err) => return (got, Err(err)), + }; + loop { + match group.read_frame().await { + Ok(Some(frame)) => { + let index: u64 = std::str::from_utf8(&frame.payload).unwrap().parse().unwrap(); + got.push((group.sequence, index)); + } + Ok(None) => break, + Err(err) => return (got, Err(err)), + } + } + } + }); + + moq_clock::timeout(TIMEOUT, support::harness::subscribed(&track)) + .await + .expect("no subscriber appeared"); + moq_clock::timeout(TIMEOUT, active) + .await + .expect("the subscription never became active") + .expect("reader alive"); + + // The subscriber now reads nothing until the upstream session is gone. + downstream.server_transport.hold_unis(); + for sequence in 0..GROUPS { + let mut group = track.append_group().unwrap(); + for index in 0..FRAMES { + let at = Timestamp::from_millis(sequence * FRAMES + index).unwrap(); + group.write_frame(at, index.to_string().into_bytes()).unwrap(); + } + group.finish().unwrap(); + } + track.finish().unwrap(); + + match end { + End::Close => moq_clock::timeout(TIMEOUT, upstream.server.clone().close()) + .await + .expect("close timed out") + .expect("the close drains"), + End::Abort => { + // Simulated time advances only once every task is idle: the relay has read + // everything the unheld upstream hop carried. + moq_clock::sleep(Duration::from_millis(100)).await; + upstream.server.abort(Error::Cancel); + } + } + drop((track, broadcast, publisher, upstream)); + // The relay sees the session and its broadcast go before the subscriber reads on. + moq_clock::sleep(Duration::from_millis(100)).await; + downstream.server_transport.release_unis(); + + let outcome = moq_clock::timeout(TIMEOUT, reader) + .await + .unwrap_or_else(|_| panic!("{name} {end:?}: the track never ended")) + .expect("reader panicked"); + drop((downstream, relay, subscriber)); + outcome +} + +/// Every frame, then a clean end. Lite03 and Lite04 declare no end, so the relay is still +/// waiting out its tail grace when the session goes. +/// +/// Their close is left out: it drains on the transport's acknowledgement of the +/// subscription's FIN, which the relay may not have read when the session closes, and +/// without a declared end nothing else says the track is over. +#[moq_clock::test] +async fn relay_delivers_a_finished_track_after_upstream_closes() { + let want: Vec<(u64, u64)> = (0..GROUPS) + .flat_map(|group| (0..FRAMES).map(move |frame| (group, frame))) + .collect(); + for version in VERSIONS { + let ends: &[End] = match *version { + "moq-lite-03" | "moq-lite-04" => &[End::Abort], + _ => &[End::Close, End::Abort], + }; + for &end in ends { + let (mut got, result) = round(version, end).await; + // Groups arrive in any order; each one's frames arrive in order. + got.sort_by_key(|&(group, _)| group); + assert_eq!(got, want, "{version} {end:?}: result={result:?}"); + assert!(result.is_ok(), "{version} {end:?}: ended with {result:?}"); + } + } +} From bce2d4ea2b871916f3eef612b5cb5337749b9c48 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 11:12:37 -0700 Subject: [PATCH 03/12] feat(net)!: broadcasts have no finished state (WIP) Co-Authored-By: Claude Opus 5.5 --- rs/moq-c/src/api.rs | 45 ++-- rs/moq-c/src/audio.rs | 4 +- rs/moq-c/src/publish.rs | 47 ++-- rs/moq-c/src/test.rs | 23 +- rs/moq-c/src/video.rs | 4 +- rs/moq-ffi/src/producer.rs | 113 ++-------- rs/moq-ffi/src/test.rs | 140 ++---------- rs/moq-ffi/uniffi.toml | 4 +- rs/moq-net/src/model/broadcast.rs | 320 +--------------------------- rs/moq-net/src/model/listing.rs | 22 -- rs/moq-net/src/model/origin.rs | 142 ------------ rs/moq-net/src/model/track.rs | 43 ---- test/interop/clients/rust/finish.rs | 14 +- 13 files changed, 90 insertions(+), 831 deletions(-) diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 4d87b92c0e0..b50e95c1fb4 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -2193,37 +2193,18 @@ pub extern "C" fn moq_publish_close(broadcast: u32) -> i32 { }) } -/// End a broadcast cleanly and release its handle, keeping it servable until its media is stale. +/// End a broadcast's content by finishing its catalog. /// -/// Finish every track first: the returned finish handle holds the tracks finished by now and -/// keeps the broadcast announced, so a subscriber still catching up can drain them. A track still -/// live is not held. `linger_us` receives how long to keep the handle, in microseconds: the -/// longest max age among the held tracks, or zero. Keep it that long on your own clock, then -/// [moq_publish_finish_close]; closing it sooner is how an interrupt ends the linger. -/// -/// Returns a non-zero finish handle on success, or a negative code on failure. -/// -/// # Safety -/// - `linger_us` must be a valid pointer. -#[unsafe(no_mangle)] -pub unsafe extern "C" fn moq_publish_finish(broadcast: u32, linger_us: *mut u64) -> i32 { - ffi::enter(move || { - let broadcast = ffi::parse_id(broadcast)?; - let linger_us = unsafe { linger_us.as_mut() }.ok_or(Error::InvalidPointer)?; - let (finish, linger) = State::lock().publish.finish(broadcast)?; - *linger_us = u64::try_from(linger.as_micros()).unwrap_or(u64::MAX); - Ok(finish) - }) -} - -/// Close a finished broadcast and release its handle, ending its linger. +/// Finish every track first. The broadcast stays announced and keeps serving its finished +/// tracks, so a subscriber that arrives late can still read them, until [moq_publish_close] +/// takes it offline. How long to keep it up is yours to decide. /// /// Returns a zero on success, or a negative code on failure. #[unsafe(no_mangle)] -pub extern "C" fn moq_publish_finish_close(finish: u32) -> i32 { +pub extern "C" fn moq_publish_finish(broadcast: u32) -> i32 { ffi::enter(move || { - let finish = ffi::parse_id(finish)?; - State::lock().publish.finish_close(finish) + let broadcast = ffi::parse_id(broadcast)?; + State::lock().publish.finish(broadcast) }) } @@ -2353,8 +2334,8 @@ pub extern "C" fn moq_publish_media_seek(media: u32, sequence: u64) -> i32 { /// Finish a media track, flushing any buffered frames. No more frames can be written. /// -/// The broadcast keeps the finished track, catalog rendition included, until it closes or its -/// [moq_publish_finish] linger ends, so a late subscriber can still drain it. +/// The broadcast keeps the finished track, catalog rendition included, until it closes, so a +/// late subscriber can still drain it. /// /// Returns a zero on success, or a negative code on failure. #[unsafe(no_mangle)] @@ -2480,8 +2461,8 @@ pub extern "C" fn moq_publish_container_seek(container: u32, sequence: u64) -> i /// Finish every track the container publishes and release the handle. /// -/// The broadcast keeps the finished tracks, catalog renditions included, until it closes or its -/// [moq_publish_finish] linger ends, so a late subscriber can still drain them. +/// The broadcast keeps the finished tracks, catalog renditions included, until it closes, so a +/// late subscriber can still drain them. /// /// Returns zero on success, or a negative code on failure. #[unsafe(no_mangle)] @@ -2868,8 +2849,8 @@ pub unsafe extern "C" fn moq_publish_track_datagram( /// Finish a raw track and release its handle. No more groups or frames can be written. /// -/// The broadcast keeps the finished track until it closes or its [moq_publish_finish] linger -/// ends, so a late subscriber can still drain it. +/// The broadcast keeps the finished track until it closes, so a late subscriber can still +/// drain it. /// /// Returns a zero on success, or a negative code on failure. #[unsafe(no_mangle)] diff --git a/rs/moq-c/src/audio.rs b/rs/moq-c/src/audio.rs index c141d16f1aa..a658fc10584 100644 --- a/rs/moq-c/src/audio.rs +++ b/rs/moq-c/src/audio.rs @@ -446,8 +446,8 @@ pub unsafe extern "C" fn moq_encode_audio_frame(producer: u32, frame: *const moq /// Flush any pending samples and finalize an audio producer. /// -/// The broadcast keeps the finished track, catalog rendition included, until it closes or its -/// `moq_publish_finish` linger ends, so a late subscriber can still drain it. +/// The broadcast keeps the finished track, catalog rendition included, until it closes, so a +/// late subscriber can still drain it. #[unsafe(no_mangle)] pub extern "C" fn moq_encode_audio_finish(producer: u32) -> i32 { ffi::enter(move || { diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index 2df5ad18df0..222cee989e2 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -50,6 +50,8 @@ struct Broadcast { video: BTreeMap, audio: BTreeMap, finished: Finished, + /// Set by [`Publish::finish`]: the catalog is final, so a close leaves it alone. + ended: bool, } impl Drop for Broadcast { @@ -63,9 +65,9 @@ type Keeping = Option>>; /// Finished producers a broadcast keeps until it ends. /// -/// A track unlists once its last producer drops, and a finish holds only listed tracks. A -/// `*_finish` call frees its handle, so the broadcast keeps the finished producer here instead, -/// and [`Publish::finish`] still holds the track. +/// A finished track stops being served once its last producer drops. A `*_finish` call frees +/// its handle, so the broadcast keeps the finished producer here instead, and a subscriber +/// arriving after the end still finds the track until [`Publish::close`]. #[derive(Clone)] pub struct Finished(std::sync::Arc>); @@ -196,8 +198,6 @@ pub struct Publish { /// Group requests delivered to a handler, freed on accept, abort, or free. group_request: NonZeroSlab, - /// Finished broadcasts, serving their finished tracks until closed. - finishes: NonZeroSlab, } impl Publish { @@ -230,6 +230,7 @@ impl Publish { video: BTreeMap::new(), audio: BTreeMap::new(), finished: Finished::default(), + ended: false, })?; Ok(id) } @@ -284,6 +285,10 @@ impl Publish { /// End the broadcast for good and release it, finalizing the catalog stream. pub fn close(&mut self, broadcast: Id) -> Result<(), Error> { let mut broadcast = self.broadcasts.remove(broadcast).ok_or(Error::BroadcastNotFound)?; + if broadcast.ended { + broadcast.producer.close(); + return broadcast.driver.check(); + } let result = (|| { // Retire caller-authored entries while the catalog track is still open. { @@ -305,30 +310,14 @@ impl Publish { result } - /// End the broadcast cleanly and release it, returning a finish handle and its linger. - /// - /// The catalog finishes with its entries still listed, so a late subscriber finds the - /// finished tracks the handle holds. - pub fn finish(&mut self, broadcast: Id) -> Result<(Id, std::time::Duration), Error> { - let mut broadcast = self.broadcasts.remove(broadcast).ok_or(Error::BroadcastNotFound)?; - // On failure the handle is gone, so close the broadcast rather than leave a dynamic holding it. - let ready = broadcast.catalog.finish().map_err(Error::from); - if let Err(err) = ready.and_then(|()| broadcast.driver.check()) { - broadcast.producer.close(); - return Err(err); - } - // Released only once the finish holds their tracks. - let finished = broadcast.finished.release(); - let finish = broadcast.producer.clone().finish(); - drop(finished); - let linger = finish.linger(); - Ok((self.finishes.insert(finish)?, linger)) - } - - /// Close a finished broadcast, ending its linger. - pub fn finish_close(&mut self, finish: Id) -> Result<(), Error> { - self.finishes.remove(finish).ok_or(Error::BroadcastNotFound)?; - Ok(()) + /// End the broadcast's content by finishing its catalog, with its entries still listed, so + /// a late subscriber finds the finished tracks until [`Self::close`]. + pub fn finish(&mut self, broadcast: Id) -> Result<(), Error> { + let broadcast = self.broadcast_mut(broadcast)?; + let result = broadcast.catalog.finish(); + broadcast.ended |= result.is_ok(); + broadcast.driver.check()?; + Ok(result?) } /// Where a broadcast keeps the producers finished on it. diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index bd55cdacc5b..b848280dd82 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -2310,7 +2310,7 @@ fn close_invalid_or_zero_ids() { } /// A finished broadcast serves its finished tracks to a late subscriber, even after their -/// handles were freed, and reports the longest max age among them as its linger. +/// handles were freed, until it closes. #[test] fn publish_finish_serves_finished_tracks_until_closed() { let origin = id(moq_origin_create()); @@ -2320,8 +2320,8 @@ fn publish_finish_serves_finished_tracks_until_closed() { let name = b"data"; let info = moq_track_info { priority: 0, - max_age_us: 5_000_000, - max_age_present: true, + max_age_us: 0, + max_age_present: false, timescale: 0, timescale_present: false, refresh: 0, @@ -2349,16 +2349,7 @@ fn publish_finish_serves_finished_tracks_until_closed() { ); assert_eq!(moq_publish_media_finish(media), 0); - // A NULL out-pointer is refused before the broadcast is consumed. - assert!(unsafe { moq_publish_finish(broadcast, std::ptr::null_mut()) } < 0); - let mut linger_us = 0; - let finish = id(unsafe { moq_publish_finish(broadcast, &mut linger_us) }); - // The media track's default max age outlasts the raw track's. - assert!(linger_us >= 5_000_000, "linger {linger_us}us"); - assert!( - moq_publish_close(broadcast) < 0, - "a finished broadcast handle is released" - ); + assert_eq!(moq_publish_finish(broadcast), 0); let consume = request_broadcast(origin, path); let frame_cb = Callback::new(); @@ -2396,9 +2387,9 @@ fn publish_finish_serves_finished_tracks_until_closed() { assert_eq!(frame_cb.recv_terminal(), 0); assert_eq!(moq_consume_close(consume), 0); - assert_eq!(moq_publish_finish_close(finish), 0); - assert!(moq_publish_finish_close(finish) < 0, "a closed finish is released"); - assert!(request_once(origin, path) < 0, "a closed finish is unroutable"); + assert_eq!(moq_publish_close(broadcast), 0); + assert!(moq_publish_close(broadcast) < 0, "a closed broadcast is released"); + assert!(request_once(origin, path) < 0, "a closed broadcast is unroutable"); assert_eq!(moq_origin_close(origin), 0); } diff --git a/rs/moq-c/src/video.rs b/rs/moq-c/src/video.rs index 1906cefd98d..8c5ebe20a34 100644 --- a/rs/moq-c/src/video.rs +++ b/rs/moq-c/src/video.rs @@ -893,8 +893,8 @@ pub extern "C" fn moq_encode_video_bitrate(producer: u32, bitrate: u64) -> i32 { /// Flush any frames the codec is still holding and finalize the video track. /// /// The handle is released, so nothing can be published to it afterwards. -/// The broadcast keeps the finished track, catalog rendition included, until it closes or its -/// `moq_publish_finish` linger ends, so a late subscriber can still drain it. +/// The broadcast keeps the finished track, catalog rendition included, until it closes, so a +/// late subscriber can still drain it. #[unsafe(no_mangle)] pub extern "C" fn moq_encode_video_finish(producer: u32) -> i32 { ffi::enter(move || { diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index 646bae7fc5b..43009e9f4f4 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -97,6 +97,8 @@ pub(crate) struct BroadcastProducer { pub(crate) timebases: std::collections::HashMap>, pub(crate) driver: Background, pub(crate) finished: Finished, + /// Set by [`MoqBroadcastProducer::finish`]: the catalog is final, so a close leaves it alone. + pub(crate) ended: bool, } impl Drop for BroadcastProducer { @@ -110,10 +112,10 @@ type Keeping = Option>>; /// Finished producers a broadcast keeps until it ends. /// -/// A track unlists once its last producer drops, and a finish holds only listed tracks. An -/// importer lets go of its producer when it finishes, and a binding may release a raw track's -/// handle whenever its garbage collector runs, so the broadcast keeps them here instead, and -/// [`MoqBroadcastProducer::finish`] still holds the track. +/// A finished track stops being served once its last producer drops. An importer lets go of +/// its producer when it finishes, and a binding may release a raw track's handle whenever its +/// garbage collector runs, so the broadcast keeps them here instead, and a subscriber arriving +/// after the end still finds the track until the broadcast closes. #[derive(Clone)] pub(crate) struct Finished(Arc>); @@ -208,6 +210,7 @@ impl MoqBroadcastProducer { timebases: Default::default(), driver, finished: Default::default(), + ended: false, })), }) } @@ -336,100 +339,26 @@ impl MoqBroadcastProducer { }; // Close the broadcast first so it ends even if finalizing the catalog fails. state.broadcast.close(); - let result = state.catalog.finish().map_err(Into::into); + let result = match state.ended { + true => Ok(()), + false => state.catalog.finish().map_err(Into::into), + }; state.driver.check()?; result } - /// End the broadcast cleanly, keeping it servable until its media goes stale. - /// - /// Finish every track first: the returned handle holds the tracks finished by now and keeps - /// the broadcast announced, so a subscriber still catching up can drain them. A track still - /// live is not held and adds nothing to the linger. Await [`MoqBroadcastFinish::wait`], or keep - /// the handle for [`MoqBroadcastFinish::linger_us`] on your own clock and then close it. + /// End the broadcast's content: finish its catalog, the hang end of content. /// - /// Every later call on this producer fails with `Closed`, as after [`close`](Self::close). - pub fn finish(&self) -> Result, MoqError> { + /// Finish every track first. The broadcast stays announced and keeps serving its finished + /// tracks, so a subscriber that arrives late can still read them, until + /// [`close`](Self::close) takes it offline. How long to keep it up is yours to decide. + pub fn finish(&self) -> Result<(), MoqError> { let _guard = crate::ffi::enter(); - let mut state = self.state.lock().unwrap().take().ok_or(MoqError::Closed)?; - // Finished before the broadcast is, so the catalog lingers with the media. On failure the - // producer is gone, so close the broadcast rather than leave a dynamic handle holding it. - let ready = state.catalog.finish().map_err(MoqError::from); - if let Err(err) = ready.and_then(|()| state.driver.check()) { - state.broadcast.close(); - return Err(err); - } - let broadcast = state.broadcast.clone(); - // Released only once the finish holds their tracks. - let finished = state.finished.release(); - let finish = state.broadcast.clone().finish(); - drop(finished); - Ok(Arc::new(MoqBroadcastFinish { - linger: finish.linger(), - until: moq_clock::now().checked_add(finish.linger()), - broadcast, - finish: std::sync::Mutex::new(Some(finish)), - })) - } -} - -/// A cleanly ended broadcast, still announced and serving its finished tracks. -/// -/// Returned by [`MoqBroadcastProducer::finish`]. Closing or dropping it closes the broadcast, -/// which is how an interrupt ends the linger early. A garbage-collected language (Kotlin, Go, -/// Dart) drops it only when the collector reclaims it, possibly long after the last reference -/// goes, so wait on or close it rather than leave it for the collector. -#[derive(uniffi::Object)] -pub struct MoqBroadcastFinish { - linger: std::time::Duration, - // The linger counts from the finish, as a C caller's own clock would, not from the first - // poll of a wait; `None` when it overflows the clock. - until: Option, - // Closes the broadcast from any thread, ending a wait that took `finish`. - broadcast: moq_net::broadcast::Producer, - // Taken by `wait` or `close`. - finish: std::sync::Mutex>, -} - -#[uniffi::export] -impl MoqBroadcastFinish { - /// How long to keep the broadcast, in microseconds: the longest max age of the held tracks. - /// - /// Tracks still live at the finish, and tracks without a max age, add nothing. - pub fn linger_us(&self) -> u64 { - u64::try_from(self.linger.as_micros()).unwrap_or(u64::MAX) - } - - /// Keep the broadcast up for its linger, or until [`close`](Self::close), then close it. - /// - /// Cancelling the wait closes the broadcast at once. Errors with `Closed` once another wait - /// or a close took the handle. - pub async fn wait(&self) -> Result<(), MoqError> { - let finish = self.finish.lock().unwrap().take().ok_or(MoqError::Closed)?; - let until = self.until; - crate::ffi::detached(async move { - let closed = kio::wait(|waiter| finish.poll_closed(waiter)); - match until { - Some(until) => { - tokio::select! { - _ = moq_clock::sleep_until(until) => {} - _ = closed => {} - } - } - None => closed.await, - } - // Dropping the finish is what closes the broadcast. - drop(finish); - Ok::<_, MoqError>(()) + self.with_state(|state| { + state.catalog.finish()?; + state.ended = true; + Ok(()) }) - .await - } - - /// Close the broadcast now, ending the linger and any wait. Closing again is a no-op. - pub fn close(&self) { - let _guard = crate::ffi::enter(); - self.broadcast.close(); - drop(self.finish.lock().unwrap().take()); } } @@ -744,7 +673,7 @@ impl MoqTrackProducer { /// /// [`finish_at`](Self::finish_at) declares the boundary ahead of time, so this keeps /// that boundary. The handle remains so a later [`abort`](Self::abort) can still run, and - /// the broadcast keeps the finished track until it ends, so its finish still holds it. + /// the broadcast keeps the finished track until it closes. pub fn finish(&self) -> Result<(), MoqError> { let _guard = crate::ffi::enter(); let mut guard = self.inner.lock().unwrap(); diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 0c3b41e0e7f..cc6c8a5e8c9 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -4075,14 +4075,6 @@ fn close_twice_is_a_noop() { ); } -/// A raw track with a millisecond max age, which is what a finish lingers for. -fn aged_info(max_age_ms: u64) -> MoqTrackInfo { - MoqTrackInfo { - max_age_us: Some(max_age_ms * 1_000), - ..timed_info() - } -} - /// Wait for the announcement of `path` to end, failing the test if it doesn't. async fn await_unannounced(announced: &MoqAnnounceConsumer) { match next_event(announced).await { @@ -4092,35 +4084,26 @@ async fn await_unannounced(announced: &MoqAnnounceConsumer) { } /// A finished broadcast stays announced and serves its finished tracks to a late subscriber, -/// lingering for the longest max age among them; a live track adds nothing. +/// even once their handles are released, until it closes. #[tokio::test] -async fn finish_serves_finished_tracks_to_a_late_subscriber() { +async fn finish_serves_finished_tracks_until_close() { let origin = MoqOriginProducer::new(MoqOriginConfig::default()); let consumer = origin.consume(); let announced = consumer.announced(MoqAnnounceConfig::default()).unwrap(); let broadcast = create_announced(&origin, "finish"); next_announced(&announced).await; - let video = broadcast.publish_track("video".into(), Some(aged_info(2_000))).unwrap(); - let audio = broadcast.publish_track("audio".into(), Some(aged_info(5_000))).unwrap(); - let live = broadcast.publish_track("live".into(), Some(aged_info(60_000))).unwrap(); - for track in [&video, &audio, &live] { - track - .write_frame(MoqFrame { - payload: b"tail".to_vec(), - timestamp_us: Some(0), - }) - .unwrap(); - } - video.finish().unwrap(); + let audio = broadcast.publish_track("audio".into(), Some(timed_info())).unwrap(); + audio + .write_frame(MoqFrame { + payload: b"tail".to_vec(), + timestamp_us: Some(0), + }) + .unwrap(); audio.finish().unwrap(); - // A binding's garbage collector may release a finished handle before the broadcast finishes. - drop((video, audio)); - - let finish = broadcast.finish().unwrap(); - assert_eq!(finish.linger_us(), 5_000_000); - assert!(matches!(broadcast.consume(), Err(MoqError::Closed))); - broadcast.close().unwrap(); + // A binding's garbage collector may release a finished handle before the broadcast closes. + drop(audio); + broadcast.finish().unwrap(); let late = await_announced(&consumer, "finish").await; let track = late.subscribe_track("audio".into(), None).await.unwrap(); @@ -4131,104 +4114,9 @@ async fn finish_serves_finished_tracks_to_a_late_subscriber() { .expect("expected the finished track's frame"); assert_eq!(frame.payload, b"tail"); - finish.close(); - await_unannounced(&announced).await; - finish.close(); - assert!(matches!(finish.wait().await, Err(MoqError::Closed))); - live.finish().unwrap(); -} - -/// Media tracks finish through their importer handles, which a finish must still hold. -#[tokio::test] -async fn finish_holds_finished_media_tracks() { - let broadcast = MoqBroadcastProducer::new().unwrap(); - let media = MoqMediaTrackProducer::audio( - &broadcast, - MoqMediaTarget::Named { name: None }, - audio_init(MoqAudioFormat::Opus, opus_head()), - ) - .unwrap(); - media - .write_frame(MoqFrame { - payload: b"opus frame".to_vec(), - timestamp_us: Some(0), - }) - .unwrap(); - media.finish().unwrap(); - drop(media); - - let finish = broadcast.finish().unwrap(); - assert!(finish.linger_us() > 0, "the finished media track was not held"); - finish.close(); -} - -/// Without a max age nothing lingers: the wait closes the broadcast at once. -#[tokio::test] -async fn finish_without_a_max_age_closes_on_wait() { - let origin = MoqOriginProducer::new(MoqOriginConfig::default()); - let consumer = origin.consume(); - let announced = consumer.announced(MoqAnnounceConfig::default()).unwrap(); - let broadcast = create_announced(&origin, "finish"); - next_announced(&announced).await; - let track = broadcast.publish_track("status".into(), Some(timed_info())).unwrap(); - track.finish().unwrap(); - - let finish = broadcast.finish().unwrap(); - assert_eq!(finish.linger_us(), 0); - tokio::time::timeout(TIMEOUT, finish.wait()) - .await - .expect("the wait outlived a zero linger") - .unwrap(); - await_unannounced(&announced).await; -} - -/// Closing the handle, the interrupt, ends a wait in progress and the broadcast with it. -#[tokio::test] -async fn closing_finish_ends_the_wait() { - let origin = MoqOriginProducer::new(MoqOriginConfig::default()); - let consumer = origin.consume(); - let announced = consumer.announced(MoqAnnounceConfig::default()).unwrap(); - let broadcast = create_announced(&origin, "finish"); - next_announced(&announced).await; - let track = broadcast - .publish_track("status".into(), Some(aged_info(3_600_000))) - .unwrap(); - track.finish().unwrap(); - - let finish = broadcast.finish().unwrap(); - let wait = spawn_parked({ - let finish = finish.clone(); - async move { finish.wait().await } - }) - .await; - finish.close(); - tokio::time::timeout(TIMEOUT, wait) - .await - .expect("the wait outlived the close") - .expect("the wait panicked") - .unwrap(); - await_unannounced(&announced).await; -} - -/// Dropping a wait in progress, as a cancelled foreign future does, closes the broadcast. -#[tokio::test] -async fn cancelling_the_wait_closes_the_broadcast() { - let origin = MoqOriginProducer::new(MoqOriginConfig::default()); - let consumer = origin.consume(); - let announced = consumer.announced(MoqAnnounceConfig::default()).unwrap(); - let broadcast = create_announced(&origin, "finish"); - next_announced(&announced).await; - let track = broadcast - .publish_track("status".into(), Some(aged_info(3_600_000))) - .unwrap(); - track.finish().unwrap(); - - let finish = broadcast.finish().unwrap(); - let mut wait = Box::pin(finish.wait()); - let first = std::future::poll_fn(|cx| std::task::Poll::Ready(wait.as_mut().poll(cx))).await; - assert!(first.is_pending()); - drop(wait); + broadcast.close().unwrap(); await_unannounced(&announced).await; + assert!(matches!(broadcast.finish(), Err(MoqError::Closed))); } #[tokio::test] diff --git a/rs/moq-ffi/uniffi.toml b/rs/moq-ffi/uniffi.toml index 5d42f15377b..4dda0865a5a 100644 --- a/rs/moq-ffi/uniffi.toml +++ b/rs/moq-ffi/uniffi.toml @@ -1,7 +1,5 @@ # Kotlin objects are AutoCloseable, and `close()` there releases the handle, # which ends the broadcast only once no `dynamic()` handle remains. The -# generated forced end is `end()` so it doesn't collide with it. A finish handle's -# `close()` ends the linger even while a wait holds the handle, so it is `end()` too. +# generated forced end is `end()` so it doesn't collide with it. [bindings.kotlin.rename] "MoqBroadcastProducer.close" = "end" -"MoqBroadcastFinish.close" = "end" diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index f1a8ef2512e..0ea145f3114 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -3,9 +3,8 @@ //! A [Producer] creates tracks on demand: a [Consumer] subscribes by name, and the //! producer either serves a track it already has or is handed a [`track::Request`] to //! fill. Both handles are refcounted clones of one broadcast, which ends on -//! [`Producer::close`], when the last producer drops, or when the [`Finish`] that -//! [`Producer::finish`] returns drops, having kept its finished tracks up until their -//! media is stale. +//! [`Producer::close`] or when the last producer drops. A broadcast has no finished state: +//! a publisher ends its content by finishing its tracks, and goes offline by closing. //! //! [Info] is the broadcast's static metadata, fixed for its lifetime. use crate::{cache, stats, track}; @@ -13,7 +12,6 @@ use std::{ collections::HashMap, sync::Arc, task::{Poll, ready}, - time::Duration, }; use crate::Error; @@ -28,7 +26,7 @@ mod listing; #[cfg(feature = "async")] pub(crate) use listing::Owner; pub(super) use listing::{ListOnAccept, Unlist}; -// Only sessions answer a peer's listings; `finish` does not end a custom handler's answer. +// Only sessions answer a peer's listings. pub(crate) use listing::Lister; pub use listing::{Tracks, TracksEvent}; @@ -128,14 +126,6 @@ struct BroadcastState { // Set once the broadcast ends: `Producer::close()` or the last producer-side // handle dropping. Every lookup after it answers `Unroutable`. closing: bool, - - // Set by `Producer::finish`: only a finished broadcast can be superseded, since a live - // one serves again once the newer route at its path withdraws. - finished: bool, - - // Set once a finished broadcast's origin advertises a newer epoch at its path, which - // ends its `Finish` at once. - superseded: bool, } impl BroadcastState { @@ -222,8 +212,8 @@ impl BroadcastState { /// /// A broadcast lives until [`Self::close`] or until the last [`Producer`] (or /// [`Dynamic`]) drops, whichever comes first; both end it the same way. A publisher -/// whose input ended cleanly calls [`Self::finish`] instead, so a subscriber still -/// catching up can drain what it published. Children +/// whose input ended cleanly finishes its tracks first: a subscriber still catching up +/// drains them after the close. Children /// do *not* keep it alive: cloning a [`Consumer`] or holding a [`track::Producer`] /// does nothing for the broadcast's lifetime. #[derive(Clone)] @@ -488,37 +478,6 @@ impl Producer { self.alive.close(); } - /// End the broadcast cleanly, keeping it servable until its media goes stale. - /// - /// A subscriber still catching up, one that read the final catalog late or is draining a - /// backlog, can still request and drain the finished tracks. The returned [`Finish`] keeps - /// the broadcast announced and holds every track finished by now, so their producers can - /// drop. A held track takes no more groups, not even one below its end, so nothing lands - /// after the linger is fixed. Keep it for its [`linger`](Finish::linger), then drop it to [close](Self::close) - /// the broadcast; `Finish::wait` does both on a runtime. Dropping it early is how an - /// interrupt ends the linger, and a newer epoch at its path ends it too; see - /// [`Finish::poll_closed`]. - pub fn finish(self) -> Finish { - // Marked before asking the origin, so a newer epoch announced meanwhile either - // supersedes the finished broadcast or is in the table by the time it is asked. - self.state.lock().finished = true; - let superseded = self.alive.announcer.lock().as_ref().is_some_and(Announcer::superseded); - if superseded { - self.state.lock().superseded = true; - } - - let tracks: Vec = self.state.read().tracks.values().cloned().collect(); - // Held outside the lock: a track whose last producer drops meanwhile unlists itself - // under it. - let held: Vec = tracks.iter().filter_map(track::TrackWeak::hold_finished).collect(); - let linger = held.iter().filter_map(|hold| hold.max_age).max().unwrap_or_default(); - Finish { - producer: self, - _held: held, - linger, - } - } - /// Whether any [`Consumer`] handle exists, unlike [`Self::demand`], which counts tracks. pub(super) fn is_held(&self) -> bool { self.alive.token.is_used() @@ -547,85 +506,6 @@ impl Producer { } } -/// A cleanly ended broadcast, still announced and serving its finished tracks. -/// -/// Returned by [`Producer::finish`]. Dropping it closes the broadcast, then lets the held -/// tracks go, so a late lookup answers [`Error::Unroutable`]. -pub struct Finish { - producer: Producer, - // Dropped after `Drop::drop` closes the broadcast. - _held: Vec, - linger: Duration, -} - -impl Finish { - /// How long to keep this handle: the longest [`max_age`](track::Info::max_age) of the - /// held tracks, each capped by the broadcast's [`cache_duration`](Info::cache_duration). - /// Tracks still live, including one whose declared end the live edge has yet to reach - /// or with a group still open, and tracks without a max-age, add nothing. - pub fn linger(&self) -> Duration { - self.linger - } - - /// `Ready` once the broadcast closed elsewhere, or its origin advertises a newer - /// [epoch](crate::origin::Route::epoch) at its path, so the linger is over early. - /// - /// A request for the path resolves to the newer instance, so this one has nothing left - /// to serve, and keeping it announced would bring it back if the newer one ends. - pub fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<()> { - if self.producer.alive.token.poll_closed(waiter).is_ready() { - return Poll::Ready(()); - } - self.producer - .state - .poll(waiter, |state| match state.superseded { - true => Poll::Ready(()), - false => Poll::Pending, - }) - .map(|_| ()) - } - - /// Keep the broadcast up for [`Self::linger`] on the ambient runtime's clock, or until - /// [`Self::poll_closed`] ends it early, then close it. The linger counts from the first poll. - #[cfg(feature = "async")] - pub async fn wait(self) { - let linger = Linger { - finish: self, - until: None, - }; - crate::time::run(linger).await; - } -} - -impl Drop for Finish { - fn drop(&mut self) { - // Closed before `_held` drops, so no lookup finds a track after the linger. - self.producer.close(); - } -} - -/// Drives [`Finish::wait`] with the time it is polled with. -#[cfg(feature = "async")] -struct Linger { - finish: Finish, - // Set on the first poll; `Some(None)` when the linger overflows the clock. - until: Option>, -} - -#[cfg(feature = "async")] -impl crate::time::Driver for Linger { - fn poll(&mut self, now: crate::time::Instant, waiter: &kio::Waiter) -> Result, Error> { - if self.finish.poll_closed(waiter).is_ready() { - return Err(Error::Closed); - } - let linger = self.finish.linger; - match *self.until.get_or_insert_with(|| now.checked_add(linger)) { - Some(until) if now >= until => Err(Error::Closed), - until => Ok(until), - } - } -} - /// Ends the broadcast on [`Producer::close`] or when the last [`Producer`] or /// [`Dynamic`] drops, closing the liveness channel every [`Consumer`] watches. /// @@ -1292,18 +1172,6 @@ impl Demand { } } -impl Consumer { - /// End the broadcast's [`Finish`] early, if it has one: its origin now advertises a - /// newer epoch at its path. - pub(super) fn supersede(&self) { - let state = self.state.read(); - if state.finished && !state.superseded { - drop(state); - self.state.lock().superseded = true; - } - } -} - #[cfg(test)] #[expect(missing_docs, reason = "test-only assertion helpers")] impl Consumer { @@ -2340,182 +2208,4 @@ mod test { assert!(track.abort_unused(Error::Cancel).is_ok()); producer.close(); } - - /// A finished broadcast keeps serving its finished tracks after their producers drop, - /// so a late subscriber still gets the media, and closes once the longest max-age passes. - /// A live track, a track whose declared end is still ahead of its live edge, and a track - /// without a max-age add nothing to the wait. - #[moq_clock::test] - #[cfg(feature = "async")] - async fn finish_serves_finished_tracks_until_stale() { - let producer = Info::new().produce(); - let consumer = producer.consume(); - let secs = |secs| crate::track::Info::timed().with_max_age(Duration::from_secs(secs)); - let video = producer.create_track("video", secs(2)).unwrap(); - let audio = producer.create_track("audio", secs(5)).unwrap(); - let catalog = producer.create_track("catalog", None).unwrap(); - let live = producer.create_track("live", secs(60)).unwrap(); - let mut tail = producer.create_track("tail", secs(60)).unwrap(); - for track in [&video, &audio, &catalog, &tail] { - track.append_group().unwrap().finish().unwrap(); - } - for track in [&video, &audio, &catalog] { - track.finish().unwrap(); - } - tail.finish_at(crate::track::Position::group(2)).unwrap(); - - let start = moq_clock::now(); - let finish = producer.finish(); - assert_eq!(finish.linger(), Duration::from_secs(5)); - let finish = moq_clock::sim::spawn(finish.wait()); - drop((video, audio, catalog)); - - moq_clock::sleep(Duration::from_secs(4)).await; - let mut late = consumer.track("audio").unwrap().subscribe(None).await.unwrap(); - late.assert_group(); - assert!(!consumer.is_closed()); - - finish.await.unwrap(); - assert_eq!(moq_clock::now() - start, Duration::from_secs(5)); - assert!(consumer.is_closed()); - assert!(matches!(consumer.track("audio"), Err(Error::Unroutable))); - live.finish().unwrap(); - drop(tail); - } - - /// Dropping the handle, the library's interrupt, closes the broadcast at once, even - /// while another producer handle is alive. - #[test] - fn dropping_finish_closes_early() { - let producer = Info::new().produce(); - let consumer = producer.consume(); - let track = producer - .create_track( - "video", - crate::track::Info::timed().with_max_age(Duration::from_secs(30)), - ) - .unwrap(); - track.finish().unwrap(); - - let finish = producer.clone().finish(); - assert!(!consumer.is_closed()); - drop(finish); - assert!(consumer.is_closed()); - } - - /// The linger is the local retention window, so an origin's `cache_duration` below a - /// track's max-age ends it sooner. - #[test] - fn finish_clamps_the_linger_to_the_cache_duration() { - let producer = Info { - cache_duration: Duration::from_secs(5), - ..Default::default() - } - .produce(); - let secs = |secs| crate::track::Info::timed().with_max_age(Duration::from_secs(secs)); - let tracks = [("video", 30), ("audio", 2)].map(|(name, age)| producer.create_track(name, secs(age)).unwrap()); - for track in &tracks { - track.finish().unwrap(); - } - assert_eq!(producer.finish().linger(), Duration::from_secs(5)); - } - - /// A track with a group still open takes frames past the linger, so it is not held. - #[test] - fn finish_skips_a_track_with_an_open_group() { - let producer = Info::new().produce(); - let track = producer - .create_track( - "video", - crate::track::Info::timed().with_max_age(Duration::from_secs(30)), - ) - .unwrap(); - let _group = track.append_group().unwrap(); - track.finish().unwrap(); - assert_eq!(producer.finish().linger(), Duration::ZERO); - } - - /// A held track takes no more groups, even one below its end, so nothing lands after - /// the linger was fixed. - #[test] - fn finish_seals_the_held_tracks() { - let producer = Info::new().produce(); - let track = producer - .create_track( - "video", - crate::track::Info::timed().with_max_age(Duration::from_secs(30)), - ) - .unwrap(); - track - .create_group(crate::group::Info { sequence: 2 }) - .unwrap() - .finish() - .unwrap(); - track.finish().unwrap(); - track - .create_group(crate::group::Info { sequence: 1 }) - .unwrap() - .finish() - .unwrap(); - - let _finish = producer.finish(); - assert!(matches!( - track.create_group(crate::group::Info { sequence: 0 }), - Err(Error::Closed) - )); - } - - /// A caller without a runtime keeps the handle until its own clock passes the linger, - /// serving the finished track until then, and drops it to close the broadcast. - #[test] - fn a_runtime_free_caller_drops_finish_on_its_own_clock() { - let producer = Info::new().produce(); - let consumer = producer.consume(); - let track = producer - .create_track( - "video", - crate::track::Info::timed().with_max_age(Duration::from_secs(3)), - ) - .unwrap(); - track.append_group().unwrap().finish().unwrap(); - track.finish().unwrap(); - - let start = crate::time::Instant::now(); - let finish = producer.finish(); - drop(track); - let deadline = start + finish.linger(); - let mut now = start; - while now < deadline { - assert!(finish.poll_closed(&kio::Waiter::noop()).is_pending()); - assert!(consumer.track("video").is_ok(), "served {:?} in", now - start); - now += Duration::from_secs(1); - } - drop(finish); - assert!(consumer.is_closed()); - assert!(matches!(consumer.track("video"), Err(Error::Unroutable))); - } - - /// A close elsewhere ends the linger early, for a poller and for [`Finish::wait`]. - #[moq_clock::test] - #[cfg(feature = "async")] - async fn closing_elsewhere_ends_the_linger() { - let producer = Info::new().produce(); - let track = producer - .create_track( - "video", - crate::track::Info::timed().with_max_age(Duration::from_secs(30)), - ) - .unwrap(); - track.finish().unwrap(); - let other = producer.clone(); - let finish = producer.finish(); - assert!(finish.poll_closed(&kio::Waiter::noop()).is_pending()); - - let start = moq_clock::now(); - let wait = moq_clock::sim::spawn(finish.wait()); - moq_clock::sleep(Duration::from_secs(1)).await; - other.close(); - wait.await.unwrap(); - assert_eq!(moq_clock::now() - start, Duration::from_secs(1)); - } } diff --git a/rs/moq-net/src/model/listing.rs b/rs/moq-net/src/model/listing.rs index 0fa9caad3f1..332040b8ba5 100644 --- a/rs/moq-net/src/model/listing.rs +++ b/rs/moq-net/src/model/listing.rs @@ -783,28 +783,6 @@ mod tests { assert!(matches!(lister.finish("up"), Err(Error::NotFound))); } - #[test] - fn a_finished_track_is_listed_while_held() { - let broadcast = Info::new().produce(); - let a = broadcast.create_track("a", None).unwrap(); - a.finish().unwrap(); - drop(a); - // Nothing holds it once its producer is gone. - let mut tracks = broadcast.consume().tracks().unwrap(); - assert_eq!(drain(&mut tracks), ["synced"]); - - let broadcast = Info::new().produce(); - let a = broadcast.create_track("a", None).unwrap(); - a.finish().unwrap(); - let mut tracks = broadcast.consume().tracks().unwrap(); - assert_eq!(drain(&mut tracks), ["+a", "synced"]); - let finish = broadcast.finish(); - drop(a); - assert_eq!(drain(&mut tracks), NONE, "held by the finish"); - drop(finish); - assert_eq!(drain(&mut tracks), ["end"]); - } - #[test] fn a_recreated_track_is_removed_before_it_is_added_again() { let broadcast = Info::new().produce(); diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index e1787be71de..79e707b8e82 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -2555,7 +2555,6 @@ impl Announcing { } let mut entries = Vec::with_capacity(self.prefixes.len()); - let mut superseded = Vec::new(); for (prefix, claim) in &self.prefixes { shared.reannounced(prefix, &route.hops); let id = shared.next_route; @@ -2582,14 +2581,9 @@ impl Announcing { reach: reach(&self.scope, claim), }); shared.sync_route(prefix, claim); - superseded.extend(shared.routes.superseded(prefix)); entries.push((prefix.clone(), id)); } drop(shared); - // Outside the table lock, which never nests a broadcast's. - for broadcast in superseded { - broadcast.supersede(); - } // Ingress announce guard: held while the route is advertised. let guard = serving @@ -2654,11 +2648,6 @@ impl Announcer { pub(super) fn route(&self) -> Option { self.entry.route() } - - /// Whether a live route at the broadcast's path carries a newer epoch. - pub(super) fn superseded(&self) -> bool { - self.entry.superseded() - } } /// The write half of an advertisement: a live claim that paths under a @@ -2708,8 +2697,6 @@ impl AnnounceProducer { // The requests an epoch change released, refused once the table lock is gone: the // refusal wakes their fronts, which read the table. let mut released = Vec::new(); - // The broadcasts a newer epoch now replaces, told outside the table lock too. - let mut superseded = Vec::new(); for (prefix, id) in &self.entries { shared.reannounced(prefix, &route.hops); let stale = shared.withdrawn_through(prefix, &route.hops); @@ -2743,7 +2730,6 @@ impl AnnounceProducer { } shared.sync_route(prefix, &claim); shared.prune_withdrawn(prefix); - superseded.extend(shared.routes.superseded(prefix)); } drop(shared); for producer in released { @@ -2751,9 +2737,6 @@ impl AnnounceProducer { request.resolved.get_or_insert(Err(Error::Unroutable)); } } - for broadcast in superseded { - broadcast.supersede(); - } Ok(true) } @@ -2772,18 +2755,6 @@ impl AnnounceProducer { }) } - /// Whether a live route at any of the entries' prefixes carries a newer epoch than theirs. - fn superseded(&self) -> bool { - let shared = self.shared.lock(); - self.entries.iter().any(|(prefix, id)| { - shared - .routes - .entry(prefix, *id) - .and_then(|entry| entry.epoch.as_ref()) - .is_some_and(|epoch| shared.routes.newest_epoch(prefix).is_some_and(|newest| epoch < newest)) - }) - } - /// Hide the entries from everyone, local and remote alike: cursors see a /// retraction and requests stop resolving through them. The entries stay, /// so announcing again restores the same route. What @@ -4651,26 +4622,6 @@ impl RouteTable { nodes.into_iter().flat_map(|node| node.entries.iter()) } - /// The newest epoch a live route at `prefix` carries. - fn newest_epoch(&self, prefix: &Path) -> Option<&Epoch> { - self.at(prefix) - .filter(|entry| entry.live()) - .filter_map(|entry| entry.epoch.as_ref()) - .max() - } - - /// The broadcasts published exactly at `prefix` under an epoch older than the newest one - /// advertised there. See [`broadcast::Finish::poll_closed`]. - fn superseded(&self, prefix: &Path) -> Vec { - let Some(newest) = self.newest_epoch(prefix) else { - return Vec::new(); - }; - self.at(prefix) - .filter(|entry| entry.epoch.as_ref().is_some_and(|epoch| epoch < newest)) - .filter_map(|entry| entry.source.clone()) - .collect() - } - /// Add a route at its prefix, creating the nodes down to it. fn insert(&mut self, entry: RouteEntry) { let node = self.root.reach(entry.prefix.parts(), Below::NONE); @@ -11476,99 +11427,6 @@ mod tests { assert!(!replaced.is_clone(&resolved), "rejoined the first instance's front"); } - /// A newer epoch at the path ends a finished broadcast's linger at once, so the finished - /// instance neither stands next to its replacement nor returns when the replacement ends. - #[moq_clock::test] - #[cfg(feature = "async")] - async fn a_newer_epoch_ends_the_linger() { - let producer = origin(1).produce(); - let old = producer - .publish("room/alice", Route::default().with_epoch(crate::Epoch::mint())) - .unwrap(); - let track = old - .create_track("video", track::Info::timed().with_max_age(Duration::from_secs(30))) - .unwrap(); - track.finish().unwrap(); - let watch = old.consume(); - let start = moq_clock::now(); - let wait = moq_clock::sim::spawn(old.finish().wait()); - - moq_clock::sleep(Duration::from_secs(1)).await; - assert!(!watch.is_closed()); - let _new = producer - .publish("room/alice", Route::default().with_epoch(crate::Epoch::mint())) - .unwrap(); - wait.await.unwrap(); - assert_eq!(moq_clock::now() - start, Duration::from_secs(1)); - assert!(watch.is_closed()); - } - - /// Only a newer epoch ends a linger: an older instance arriving late, or one at - /// another path, leaves it to run out. - #[moq_clock::test] - #[cfg(feature = "async")] - async fn an_older_epoch_leaves_the_linger() { - let producer = origin(1).produce(); - let (older, newer) = (crate::Epoch::mint(), crate::Epoch::mint()); - let finished = producer - .publish("room/alice", Route::default().with_epoch(newer)) - .unwrap(); - let track = finished - .create_track("video", track::Info::timed().with_max_age(Duration::from_secs(5))) - .unwrap(); - track.finish().unwrap(); - let start = moq_clock::now(); - let wait = moq_clock::sim::spawn(finished.finish().wait()); - - let _late = producer - .publish("room/alice", Route::default().with_epoch(older)) - .unwrap(); - let _elsewhere = producer - .publish("room/bob", Route::default().with_epoch(crate::Epoch::mint())) - .unwrap(); - wait.await.unwrap(); - assert_eq!(moq_clock::now() - start, Duration::from_secs(5)); - } - - /// Supersession is decided when the broadcast finishes: a newer epoch that came and went - /// while it was live leaves its linger, and one still live cuts it at once. - #[moq_clock::test] - #[cfg(feature = "async")] - async fn a_live_newer_epoch_at_finish_ends_the_linger() { - let producer = origin(1).produce(); - let (older, newer) = (crate::Epoch::mint(), crate::Epoch::mint()); - let publish = |epoch: &crate::Epoch| { - let broadcast = producer - .publish("room/alice", Route::default().with_epoch(epoch.clone())) - .unwrap(); - let track = broadcast - .create_track("video", track::Info::timed().with_max_age(Duration::from_secs(5))) - .unwrap(); - track.finish().unwrap(); - (broadcast, track) - }; - - let (restored, _track) = publish(&older); - drop(publish(&newer)); - let start = moq_clock::now(); - restored.finish().wait().await; - assert_eq!( - moq_clock::now() - start, - Duration::from_secs(5), - "the withdrawn epoch left it" - ); - - let (cut, _track) = publish(&older); - let _live = publish(&newer); - let start = moq_clock::now(); - cut.finish().wait().await; - assert_eq!( - moq_clock::now() - start, - Duration::ZERO, - "the live epoch ends it at once" - ); - } - /// Announce cursors follow the newest epoch over a cheaper one, and deliver a /// change of epoch as a restart: a different broadcast. #[moq_clock::test] diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 7c58c1e0736..c731ec8b73b 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -3382,7 +3382,6 @@ impl Producer { TrackWeak { name: self.name.clone(), state: self.state.weak(), - alive: Arc::downgrade(&self.alive), } } @@ -3842,50 +3841,9 @@ fn clamp_combined(combined: Option, bound: Option) -> Op pub(super) struct TrackWeak { name: Arc, state: kio::ProducerWeak, - // The producers' teardown guard, upgraded by [`Self::hold_finished`]. - alive: std::sync::Weak, -} - -/// Keeps a finished track servable after its producers drop; see [`TrackWeak::hold_finished`]. -pub(in crate::model) struct Hold { - _alive: Arc, - /// The track's [`Info::max_age`], clamped to the broadcast's `cache_duration`. - pub max_age: Option, } impl TrackWeak { - /// Hold the track open if it finished cleanly, so lookups keep finding it after its - /// producers drop. `None` for a track still live (even one with a declared end ahead of - /// its live edge, or a group still open), aborted, never published, or gone. - /// - /// Seals a held track: a lower group a surviving producer creates afterward would - /// outlive the linger fixed here, so it is refused instead. - pub(in crate::model) fn hold_finished(&self) -> Option { - let alive = self.alive.upgrade()?; - if !alive.published.load(Ordering::Relaxed) { - return None; - } - let mut state = alive.state.write().ok()?; - // A declared end the live edge has yet to reach still has groups to come. - if !state.is_complete() || state.abort.is_some() { - return None; - } - // An open group still takes frames, which could land after the linger fixed here. - let open = |group: &group::Handle| !group.is_finished() && !group.is_aborted(); - if state.lookup.values().any(|slot| slot.copies().any(open)) { - return None; - } - state.sealed = true; - let ceiling = state.broadcast.cache_duration; - let max_age = state - .info - .as_ref() - .and_then(|info| info.max_age) - .map(|age| age.min(ceiling)); - drop(state); - Some(Hold { _alive: alive, max_age }) - } - /// Join the cached track's demand, or `None` once it has closed. /// /// The count moves under the same lock the close takes, which is the other half @@ -7721,7 +7679,6 @@ impl Request { TrackWeak { name: self.name.clone(), state: self.state.weak(), - alive: Arc::downgrade(&self.alive), } } } diff --git a/test/interop/clients/rust/finish.rs b/test/interop/clients/rust/finish.rs index 4fdd6b69ff6..adf582877a0 100644 --- a/test/interop/clients/rust/finish.rs +++ b/test/interop/clients/rust/finish.rs @@ -7,6 +7,9 @@ use moq_mux::catalog::Stream; use moq_tokio::moq_net; use tokio::io::{AsyncBufReadExt, AsyncReadExt}; +/// How long the publisher keeps its finished broadcast up for the late readers. +const LINGER: Duration = Duration::from_secs(10); + struct Args { role: String, url: url::Url, @@ -87,13 +90,10 @@ async fn main() -> anyhow::Result<()> { media.finish()?; catalog.finish()?; broadcast.announce(Default::default())?; - let started = moq_clock::now(); - let finish = broadcast.finish(); - let linger = finish.linger(); - ensure!(!linger.is_zero(), "finished media has no linger"); - println!("finish ready linger_us={}", finish.linger().as_micros()); - finish.wait().await; - ensure!(started.elapsed() >= linger, "finish wait ended before its linger"); + // Keep the finished broadcast up for the late readers, then take it offline. + let linger = moq_mux::Linger::new([broadcast], (media, catalog), LINGER); + println!("finish ready linger_us={}", LINGER.as_micros()); + linger.wait().await; println!("finish ended"); let health = origin.create_broadcast(format!("{}.health", args.broadcast))?; let mut track = health.create_track("live", moq_net::track::Info::default())?; From b6857ba506986e4a1368af3831d98e4bbbf44404 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 11:26:26 -0700 Subject: [PATCH 04/12] feat!: drop broadcast Finish from @moq/net and every binding Finishing a binding broadcast finishes its catalog and leaves it up until close; interop publishers keep a finished broadcast up for a fixed 10s. Docs describe the model, and stale MIGRATE finish entries are fixed. Co-Authored-By: Claude Opus 5.5 --- cpp/moq/test/probe.cpp | 16 +- dart/moq/MIGRATE.md | 4 +- dart/moq/lib/src/aliases.dart | 4 - dart/moq/lib/src/durations.dart | 6 - dart/moq/test/moq_test.dart | 24 +-- dart/moq_ffi/lib/src/moq.dart | 177 +----------------- doc/concept/moq-lite.md | 8 + doc/lib/c/index.md | 2 +- doc/lib/cpp/index.md | 10 +- doc/lib/dart/index.md | 2 +- doc/lib/go/index.md | 2 +- doc/lib/js/net.md | 2 +- doc/lib/kt/index.md | 2 +- doc/lib/py/index.md | 2 +- doc/lib/rs/moq-net.md | 2 +- doc/lib/swift/index.md | 2 +- go/wrapper/MIGRATE.md | 4 +- go/wrapper/moq_test.go | 54 +----- go/wrapper/publish.go | 52 +---- js/net/src/broadcast.test.ts | 119 +----------- js/net/src/broadcast.ts | 94 +--------- js/net/src/internal.ts | 8 - js/net/src/track.ts | 5 - kt/moq/MIGRATE.md | 4 +- .../kotlin/dev/moq/Aliases.kt | 2 - .../kotlin/dev/moq/Durations.kt | 4 - .../kotlin/dev/moq/SmokeTest.kt | 23 +-- py/moq-rs/MIGRATE.md | 4 +- py/moq-rs/moq/__init__.py | 2 - py/moq-rs/moq/publish.py | 81 +------- py/moq-rs/tests/test_local.py | 46 +---- py/moq-rs/tests/test_testing_clock.py | 47 ----- quest/m1/broadcast-lifecycle/README.md | 1 - quest/m1/broadcast-lifecycle/stateless.md | 42 ----- rs/moq-c/MIGRATE.md | 2 +- rs/moq-ffi/MIGRATE.md | 4 +- rs/moq-net/MIGRATE.md | 14 +- swift/MIGRATE.md | 4 +- swift/Sources/Moq/Broadcast.swift | 41 +--- swift/Tests/MoqTests/SmokeTests.swift | 18 +- test/interop/clients/cpp/main.cpp | 17 +- test/interop/clients/go/main.go | 25 ++- test/interop/clients/js/src/finish.ts | 16 +- test/interop/clients/python/interop.py | 18 +- test/interop/interop.sh | 2 +- 45 files changed, 157 insertions(+), 861 deletions(-) delete mode 100644 quest/m1/broadcast-lifecycle/stateless.md diff --git a/cpp/moq/test/probe.cpp b/cpp/moq/test/probe.cpp index 2642ebeb00e..ea36f64d86c 100644 --- a/cpp/moq/test/probe.cpp +++ b/cpp/moq/test/probe.cpp @@ -172,17 +172,13 @@ int main() { CHECK(!moq::MediaTimebase::init(timebase_owner)); ok(timebase_other->close(), "close timebase other"); - // A finished broadcast lingers for its longest max age; closing the handle ends the wait early. + // A finished broadcast stays up, still serving its finished tracks, until it closes. auto finished = ok(moq::BroadcastProducer::init(), "finished broadcast"); - moq::TrackInfo aged; - aged.max_age_us = 3600000000; - ok(ok(finished->publish_track("status", aged), "publish aged track")->finish(), "finish aged track"); - auto finish = ok(finished->finish(), "broadcast finish"); - CHECK(finish->linger_us() == 3600000000); - CHECK(!finished->publish_track("events", {})); - auto lingering = finish->wait(); - finish->close(); - ok(lingering.get(), "finish wait"); + ok(ok(finished->publish_track("status", {}), "publish track")->finish(), "finish track"); + ok(finished->finish(), "broadcast finish"); + ok(finished->consume(), "consume a finished broadcast"); + ok(finished->close(), "close finished broadcast"); + CHECK(!finished->finish()); // A synchronous error is a returned value, not an exception. auto unbound = ok(moq::Server::init({}), "server init"); diff --git a/dart/moq/MIGRATE.md b/dart/moq/MIGRATE.md index 7c5ee352a58..e9bc81ec5cb 100644 --- a/dart/moq/MIGRATE.md +++ b/dart/moq/MIGRATE.md @@ -48,7 +48,7 @@ Audio and video init records no longer carry a track name. Pass that name on the ### Broadcast `finish` no longer closes -`BroadcastProducer.finish()` was a deprecated alias for `close()`; it no longer ends the broadcast at once. +`BroadcastProducer.finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. Call `BroadcastProducer.close()` where you called `finish()`. ### JSON snapshot `deltaRatio` is `deltas` @@ -89,7 +89,7 @@ Clamp timestamps you build from unbounded input to `2^61 - 1`. ### Finished tracks stay until the broadcast ends (#6157) -A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes or the new `BroadcastProducer.finish()` lets go. +A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes. Publish a replacement under a new name, and expect a finished track's demand watch to end with the broadcast. ### A claim answers by publishing (#5678) diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index 1a66918b8e4..228756b2d7e 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -90,10 +90,6 @@ typedef BroadcastConsumer = MoqBroadcastConsumer; /// Receives tracks requested from a dynamically served broadcast. typedef BroadcastDynamic = MoqBroadcastDynamic; -/// A cleanly ended broadcast, still announced and serving its finished tracks -/// until its linger ends; close it to end the linger early. -typedef BroadcastFinish = MoqBroadcastFinish; - /// The write side of a raw track: append groups of frames. typedef TrackProducer = MoqTrackProducer; diff --git a/dart/moq/lib/src/durations.dart b/dart/moq/lib/src/durations.dart index 0738ec44e14..be84757c8a2 100644 --- a/dart/moq/lib/src/durations.dart +++ b/dart/moq/lib/src/durations.dart @@ -47,12 +47,6 @@ extension TrackInfoDuration on MoqTrackInfo { maxAgeUs == null ? null : Duration(microseconds: maxAgeUs!); } -/// Duration view over how long a finished broadcast stays up. -extension BroadcastFinishDuration on MoqBroadcastFinish { - /// The longest max age of the finished tracks the broadcast holds. - Duration get linger => Duration(microseconds: lingerUs()); -} - /// Duration view over a raw frame's presentation time. extension FrameDuration on MoqFrame { /// Presentation timestamp, or null for an untimed frame. diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index 3aeffca31c4..c92471bfa40 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -385,24 +385,14 @@ void main() { second.close(); }); - test('a finished broadcast lingers until closed', () async { + test('a finished broadcast stays up until closed', () { final broadcast = BroadcastProducer(); - final track = broadcast.publishTrack( - name: 'status', - info: TrackInfo(maxAgeUs: 3600000000), - ); - track.finish(); - final finish = broadcast.finish(); - expect(finish.linger, const Duration(hours: 1)); - expect( - () => broadcast.publishTrack(name: 'events', info: null), - throwsA(isA()), - ); - // A Dart future can't be cancelled, so closing is the interrupt: the wait - // ends instead of lingering for an hour. - final wait = finish.wait(); - finish.close(); - await wait.timeout(timeout); + broadcast.publishTrack(name: 'status', info: null).finish(); + broadcast.finish(); + // Finishing the content leaves the broadcast up until it closes. + broadcast.consume(); + broadcast.close(); + expect(() => broadcast.finish(), throwsA(isA())); }); test('microsecond fields read back as Durations', () { diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index 809e8b5e944..5ae13469193 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -12135,112 +12135,12 @@ class FfiConverterMoqBroadcastDynamic { } } -abstract class MoqBroadcastFinishInterface { - void close(); - int lingerUs(); - UniffiRustFuture wait(); -} - -final _MoqBroadcastFinishFinalizer = Finalizer>((ptr) { - rustCall((status) => uniffi_moq_ffi_fn_free_moqbroadcastfinish(ptr, status)); -}); - -class MoqBroadcastFinish implements MoqBroadcastFinishInterface { - late final Pointer _ptr; - bool _isDisposed = false; - MoqBroadcastFinish._(this._ptr) { - _MoqBroadcastFinishFinalizer.attach(this, _ptr, detach: this); - } - factory MoqBroadcastFinish.lift(Pointer ptr) { - return MoqBroadcastFinish._(ptr); - } - Pointer uniffiClonePointer() { - if (_isDisposed) { - throw StateError("Object has already been disposed"); - } - return rustCall( - (status) => uniffi_moq_ffi_fn_clone_moqbroadcastfinish(_ptr, status), - ); - } - - void dispose() { - if (_isDisposed) { - return; - } - _isDisposed = true; - _MoqBroadcastFinishFinalizer.detach(this); - rustCall( - (status) => uniffi_moq_ffi_fn_free_moqbroadcastfinish(_ptr, status), - ); - } - - void close() { - return rustCall((status) { - uniffi_moq_ffi_fn_method_moqbroadcastfinish_close( - uniffiClonePointer(), - status, - ); - }, null); - } - - int lingerUs() { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqbroadcastfinish_linger_us( - uniffiClonePointer(), - status, - ), - FfiConverterUInt64.lift, - null, - ); - } - - UniffiRustFuture wait() { - return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqbroadcastfinish_wait( - uniffiClonePointer(), - ), - ffi_moq_ffi_rust_future_poll_void, - ffi_moq_ffi_rust_future_complete_void, - ffi_moq_ffi_rust_future_cancel_void, - ffi_moq_ffi_rust_future_free_void, - (_) {}, - moqExceptionErrorHandler, - ); - } -} - -class FfiConverterMoqBroadcastFinish { - static MoqBroadcastFinish lift(Pointer ptr) { - return MoqBroadcastFinish.lift(ptr); - } - - static Pointer lower(MoqBroadcastFinish value) { - return value.uniffiClonePointer(); - } - - static int allocationSize(MoqBroadcastFinish value) { - return 8; - } - - static LiftRetVal read(Uint8List buf) { - final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); - final pointer = Pointer.fromAddress(handle); - return LiftRetVal(MoqBroadcastFinish.lift(pointer), 8); - } - - static int write(MoqBroadcastFinish value, Uint8List buf) { - final handle = lower(value); - buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); - return 8; - } -} - abstract class MoqBroadcastProducerInterface { void announce({required MoqAnnounceRoute route}); void close(); MoqBroadcastConsumer consume(); MoqBroadcastDynamic dynamic_(); - MoqBroadcastFinish finish(); + void finish(); MoqTrackProducer publishTrack({ required String name, required MoqTrackInfo? info, @@ -12332,15 +12232,13 @@ class MoqBroadcastProducer implements MoqBroadcastProducerInterface { ); } - MoqBroadcastFinish finish() { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqbroadcastproducer_finish( + void finish() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqbroadcastproducer_finish( uniffiClonePointer(), status, - ), - FfiConverterMoqBroadcastFinish.lift, - moqExceptionErrorHandler, - ); + ); + }, moqExceptionErrorHandler); } MoqTrackProducer publishTrack({ @@ -18170,43 +18068,6 @@ external void uniffi_moq_ffi_fn_method_moqbroadcastdynamic_cancel( external Pointer uniffi_moq_ffi_fn_method_moqbroadcastdynamic_requested_track(Pointer ptr); -@Native Function(Pointer, Pointer)>( - assetId: _uniffiAssetId, -) -external Pointer uniffi_moq_ffi_fn_clone_moqbroadcastfinish( - Pointer handle, - Pointer uniffiStatus, -); - -@Native, Pointer)>( - assetId: _uniffiAssetId, -) -external void uniffi_moq_ffi_fn_free_moqbroadcastfinish( - Pointer handle, - Pointer uniffiStatus, -); - -@Native, Pointer)>( - assetId: _uniffiAssetId, -) -external void uniffi_moq_ffi_fn_method_moqbroadcastfinish_close( - Pointer ptr, - Pointer uniffiStatus, -); - -@Native, Pointer)>( - assetId: _uniffiAssetId, -) -external int uniffi_moq_ffi_fn_method_moqbroadcastfinish_linger_us( - Pointer ptr, - Pointer uniffiStatus, -); - -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqbroadcastfinish_wait( - Pointer ptr, -); - @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -18263,10 +18124,10 @@ external Pointer uniffi_moq_ffi_fn_method_moqbroadcastproducer_dynamic( Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqbroadcastproducer_finish( +external void uniffi_moq_ffi_fn_method_moqbroadcastproducer_finish( Pointer ptr, Pointer uniffiStatus, ); @@ -19806,15 +19667,6 @@ external int uniffi_moq_ffi_checksum_method_moqbroadcastdynamic_cancel(); external int uniffi_moq_ffi_checksum_method_moqbroadcastdynamic_requested_track(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqbroadcastfinish_close(); - -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqbroadcastfinish_linger_us(); - -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqbroadcastfinish_wait(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_announce(); @@ -20515,15 +20367,6 @@ void _checkApiChecksums() { 5884) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbroadcastfinish_close() != 21540) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqbroadcastfinish_linger_us() != 30748) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqbroadcastfinish_wait() != 36521) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_announce() != 3965) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -20536,7 +20379,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_dynamic() != 55635) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_finish() != 50394) { + if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_finish() != 57551) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_publish_track() != @@ -20603,7 +20446,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqtrackproducer_dynamic() != 58584) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqtrackproducer_finish() != 38052) { + if (uniffi_moq_ffi_checksum_method_moqtrackproducer_finish() != 63940) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqtrackproducer_finish_at() != 24581) { diff --git a/doc/concept/moq-lite.md b/doc/concept/moq-lite.md index df852c3d62b..71cc410e61f 100644 --- a/doc/concept/moq-lite.md +++ b/doc/concept/moq-lite.md @@ -84,6 +84,14 @@ and leaves subscriptions already in flight alone until each track ends or its last subscriber leaves. A graceful session close withdraws its announcements and waits up to one second for them to be delivered. An abort skips that. +A broadcast has no finished state. Online means announced, and offline means +no route is left. The end of content is a track FIN: the publisher finishes +each track, and a hang broadcast also finishes its catalog. A finished track +stays servable to the subscribers it already has, including through a relay +whose upstream session has since gone. How long a finished broadcast stays +announced for late readers is the application's retention policy, such as the +`--linger` of [`moq import`](/bin/cli), not a protocol state. + ### Publisher epochs A route may carry an epoch: a UUIDv7 naming the publisher instance behind it. diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index 63160ab3f18..74330c51d62 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -67,7 +67,7 @@ inside. The header is the reference: each function carries a doc comment. - **Compressed tracks.** `moq_track_info.compress` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. `@moq/net` cannot read a compressed track yet. - **fMP4 import.** `MOQ_CONTAINER_FORMAT_FMP4` splits each fragment into one frame per sample; `MOQ_CONTAINER_FORMAT_CMAF` republishes it whole. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `moq_publish_media_cut`: after every frame, or at a segment cadence to align with video. -- **Ending cleanly.** When the input ends, finish every track, then call `moq_publish_finish()`. It consumes the broadcast and returns a finish handle that keeps it announced and serving the finished tracks, writing the linger, their longest max age, to `linger_us`. Keep the handle for that long on your own clock so a subscriber still catching up can drain them, then `moq_publish_finish_close()` it; closing early is the interrupt. `moq_publish_close()` stays the abrupt end. +- **Ending cleanly.** When the input ends, finish every track, then call `moq_publish_finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `moq_publish_close()` takes it offline. How long to keep it up is yours to decide. - **Timeline breaks.** On a seek or pause, call `moq_publish_media_discontinuity`, then keep timestamps moving forward and resume video on a keyframe. - **JSON values.** `moq_consume_json_value` fills `moq_json_value` with the document and its frame's `timestamp_us`, rounded down to a whole microsecond; `timestamp_present` is false on an untimed track. A snapshot consumer's callback fires for each state in order, but a group superseded before it is read is skipped. - **Decoded frames hold decoder buffers.** Free each frame id with `moq_decode_video_frame_free` promptly, or the decoder stalls. diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index 41fe064fb50..ef82c44e8d0 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -218,12 +218,10 @@ Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. Finish or abort live tracks first. -To end a broadcast cleanly, finish every track, then call `broadcast->finish()`. -The returned `moq::BroadcastFinish` keeps the broadcast announced and serving the -finished tracks for `linger_us()`, their longest max age, so a subscriber still -catching up can drain them. `finish->wait()` resolves once the linger passes, and -`finish->close()` closes the broadcast at once, resolving the wait. -`broadcast->close()` stays the abrupt end. +To end a broadcast cleanly, finish every track, then call `broadcast->finish()` +to finish the catalog. The broadcast stays announced and keeps serving the +finished tracks, so a subscriber still catching up can drain them, until +`broadcast->close()` takes it offline. How long to keep it up is yours to decide. `moq::shutdown()` stops the `moq-ffi` runtime workers, then the executor. Pending calls resolve `Cancelled`, and every object stays safe to drop. Call diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 31519133ba5..0935e905249 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -142,7 +142,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `dispose()` each frame from a `video.Consumer` promptly rather than waiting for the garbage collector, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `await moq.close()` drains for up to one second and reports its result. `session.shutdown()` requests the drain synchronously; `await session.closed()` waits for its result. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Awaiting cancellation of an announcement, grant, or request subscription releases its pending native read. Announcements also release their cursor; authorization and server listeners leave their shared owner usable. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `linger`, their longest max age, so a subscriber still catching up can drain them. `await finish.wait()` completes once the linger passes, and `finish.close()` closes the broadcast at once, completing the wait. `broadcast.close()` stays the abrupt end. An unreferenced `BroadcastFinish` closes the broadcast only when the garbage collector reclaims it, possibly long after, so wait on or close it rather than dropping it. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), listen to `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. `await auth().add(token: ...)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index a050c7d0c14..23768688ae6 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -132,7 +132,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `Discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `Close` each `VideoDecodedFrame` promptly, or the decoder stalls. `Resize` is best effort, so read each frame's `Width()` and `Height()`. - **Closing.** `client.Close()` drains for up to one second and returns an error on failure. `session.Shutdown()` requests that drain immediately; `session.Closed(ctx)` waits for its result, and `session.Cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.Finish()`. The returned `*BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `Linger()`, their longest max age, so a subscriber still catching up can drain them. `finish.Wait(ctx)` returns once the linger passes; ending `ctx`, or `finish.Close()`, closes the broadcast at once. `broadcast.Close()` stays the abrupt end. An unreferenced `*BroadcastFinish` closes the broadcast only when the garbage collector reclaims it, possibly long after, so wait on or close it rather than dropping it. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.Finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.Close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`). A field is nil when the transport does not report it, which is not the same as zero. `Version` names the negotiated protocol. `Dial` returns a connecting session; read `Session().State()` and wait with `StateChanged(ctx, state.Revision)` to observe first-dial failures and reconnects. Hold the owned `BandwidthConsumer` returned by `Session().RecvBandwidth()` to receive bandwidth estimates. `Rate()` reads the current estimate in bits per second and `RateChanged(ctx)` waits for a new one. Calling `Close()` on the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig.Versions`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `Session().Auth().Grant()` is the `Grant` the relay sent back, nil until it answers and while a client session reconnects; `GrantChanged(ctx)` waits for the next one. `Add(ctx, token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `Close()`, and is presented again on every reconnect. A refusal returns the relay's code. - **Errors.** Read diagnostic payloads from `Reason` and structured protocol failures from `Details`. diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index 421fdb294de..1d4319751e4 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -35,7 +35,7 @@ broadcast.announce(); - **The origin holds the broadcasts, not the connection.** Closing a session unannounces them and leaves them created for the next one. A broadcast is invisible, locally and remotely, until `announce()`. - **Answer claimed paths with `using`.** `dynamic(prefix)` claims a prefix and yields each requested path. Use `using prepared = request.prepare(epoch)`, fill its broadcast, then `prepared.publish()` to answer with a new publisher instance. Leaving the scope without publishing, including on a throw, refuses the request as unroutable. Explicit `prepared.close()` or closing its unpublished broadcast does the same; disposal after publishing leaves the returned producer live. Reject before preparing with `request.reject(err)`. A retained, unclosed prepared answer keeps the request pending; JavaScript garbage collection provides no prompt cleanup guarantee. -- **End a broadcast with `finish()`.** When the input ends, close the tracks, then call `broadcast.finish()`. The returned handle keeps the broadcast announced and serving its cleanly closed tracks for `linger`, their longest max-age capped at the 30s cache window, so a subscriber still catching up can drain them. `await finish.wait()` closes it after that. A finished broadcast refuses further changes, such as a new track or announce. `finish.close()` is the interrupt, and `close()` on the broadcast also ends it at once. +- **End content by closing tracks.** A broadcast has no finished state. When the input ends, close each track cleanly; the broadcast stays announced and keeps serving them until you `close()` it. How long to keep it up for late readers is yours to decide. - **Requests can pin an epoch.** `consumer.request(path, { epoch })` resolves only through a route announcing that [publisher epoch](/concept/moq-lite#publisher-epochs). The resolved broadcast's `epoch` names the route it came through, pinned or not. - **Follow restarts.** `origin.request(path, { announced: true })` follows whichever publisher instance serves the path: its `active` changes to a fresh broadcast on a restart, clears on an end, and resolves again on the next start, so read it reactively and close the request when done. Instances are never stitched, so subscribe again to each new broadcast. Another route of the same epoch taking over (epochs travel only on `moq-lite-07-wip`) keeps `active` as is, and each track subscription resumes there from the first group it lacks. A refusal ends the request. Add `epoch` to pin one instance; a plain `request(path)` keeps its accepted instance, can resolve blindly, and ends once that instance stops serving. To list what is live, iterate `announced(scope)`. - **Discovery follows what you watch.** A `consume` origin asks the relay for announcements only under the prefixes its readers watch with `announced(scope)` or `request(path, { announced: true })`, stops asking about a prefix 2s after nothing at or beneath it is watched, and asks again on reconnect. A plain `request(path)` asks nothing and subscribes blind, but once it resolves through a discovered route it watches its path until closed, so it outlives the listing that found it. A relay that refuses an announce request turns that session's announced requests blind too. diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index 54975d98651..a98c1af42ba 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `close()` each frame from a `dev.moq.video.Consumer` promptly (or `use { }` it), or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `moq.shutdown()` requests a drain immediately; suspending `moq.session.closed()` waits up to one second and reports its result. `Moq.close()`, and so `use { }`, cancels at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `linger`, their longest max age, so a subscriber still catching up can drain them. Suspending `finish.wait()` returns once the linger passes; cancelling its coroutine, or `finish.end()`, closes the broadcast at once. `broadcast.end()` stays the abrupt end. An unreferenced `BroadcastFinish` closes the broadcast only when the garbage collector reclaims it, possibly long after, so wait on or close it rather than dropping it. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.end()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), collect `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. Suspending `auth().add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 9e17b03a976..79081cb4b7a 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -116,7 +116,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Drop each frame from a `moq.video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `session.shutdown()` requests a drain immediately; `await session.closed()` waits up to one second and reports its result. `cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `linger`, their longest max age, so a subscriber still catching up can drain them. `await finish.wait()` returns once the linger passes; cancelling it, or `finish.close()`, closes the broadcast at once. `broadcast.close()` stays the abrupt end. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rtt`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). A field is `None` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recv_bandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rate_changed()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `None` until it answers and while a client session reconnects; `await auth.grant_changed()` waits for the next one. `await auth.add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal raises with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index 600abb11c1e..9ee959e26ea 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -21,7 +21,7 @@ What you use it for, beyond what the concept page already describes: - **Follow restarts.** `consumer.announced_broadcast(path, None)` hands out each publisher instance serving a path from `available()`: the first once announced, then each one that takes over or returns after an end, like JS `request(path, { announced: true })`. A broadcast already resolved stays on the old instance until dropped or its route goes. `consumer.follow(path)` yields the underlying start, update, restart, and end of the route a request resolves. - **Discovery follows what you watch.** On moq-lite, a client session asks the relay for announcements only under the prefixes its subscribe origin's readers watch, with `announced()`, `routed_broadcast`, or `announced_broadcast`, stops asking about a prefix 2s after nothing at or beneath it is watched, and asks again on reconnect. A broadcast resolved through a discovered route keeps its path watched until dropped. `request_broadcast` watches nothing, so a path nobody watches is unroutable. A server session, or a client fed into an origin handle marked `with_link(origin::Link::Peer)` or `Link::Upstream`, asks for everything it may, so a relay discovers everything. An HTTP gateway (the moq-hls `Server`, the moq-rtc WHEP router) watches its whole scope while it lives, so the paths its callers name never open a request each. moq-transport sessions, and moq-lite-03/04 sessions (whose announcements mark no initial set), still ask for everything. - **One track per name.** Concurrent subscriptions share one request and producer. The application owns sequence numbers: a producer that replaces an ended one gets `Error::Duplicate` from an append that would reuse a sequence the name already wrote, so it starts with `create_group` at an explicit sequence. Only a new broadcast starts over. Readers of an aborted track resume onto the replacement only when the broadcast announces an epoch; otherwise their subscription ends with the error. -- **End a broadcast with `finish()`.** When the input ends, finish the tracks, then call `broadcast.finish()`. The returned handle keeps the broadcast announced and serving its finished tracks for `linger()`, their longest max-age, so a subscriber still catching up can drain them. Await `wait()` on a runtime, or drop the handle once your own clock passes `linger()`. Dropping it early is the interrupt, and `close()` on another handle ends it at once. +- **End content by finishing tracks.** A broadcast has no finished state. When the input ends, finish each track; the broadcast stays announced and keeps serving them until you close it or drop its last producer. How long to keep it up for late readers is yours to decide: `moq_mux::Linger` holds a hang broadcast for a fixed window. - **Publish only while someone is watching.** `demand()` on a track, group, or broadcast says whether a subscriber is attached, which is how capture and transcode skip work nobody asked for. Holding a broadcast or track consumer is not demand: a track consumer requests nothing until it queries, subscribes, or fetches, and those count until dropped. A shared fetch stays up until its last reader leaves. - **Use the model without a runtime.** Disable default features on `moq-net` to use its `poll_*` APIs and origin driver with caller-supplied time. The default `async` feature adds async helpers, `time::run`, and both wire sessions. - **You drive the session, or `moq-tokio` does.** `connect` and `accept` return a session plus a driver that never reads the clock itself. `moq_net::time::run` polls it on tokio or in the browser. `moq-tokio` and `moq-wasm` hide that. A custom transport implements `moq_net::transport::poll`, and `moq_net::transport::memory::pair` links two sessions in one process with no sockets, for tests or in-process links. diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index 5a8f3e3dd5d..c94223f65d0 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Release each frame from a `Video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `session.shutdown()` requests a drain immediately; `try await session.closed()` waits up to one second and reports its result. `session.cancel(code:)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `try broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `lingerUs`, their longest max age, so a subscriber still catching up can drain them. `try await finish.wait()` returns once the linger passes; cancelling its task, or `finish.close()`, closes the broadcast at once. `broadcast.close()` stays the abrupt end. +- **Ending cleanly.** When the input ends, finish every track, then call `try broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `nil` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `nil` until it answers and while a client session reconnects; `try await auth.grantChanged()` waits for the next one. `try await auth.add(token:)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Diagnostic cases use the `reason:` argument label; match their associated value to inspect it. Protocol errors carry `details`. diff --git a/go/wrapper/MIGRATE.md b/go/wrapper/MIGRATE.md index eda0c862f21..6cbcea60adc 100644 --- a/go/wrapper/MIGRATE.md +++ b/go/wrapper/MIGRATE.md @@ -41,7 +41,7 @@ Audio and video init records no longer carry a track name. Pass that name on the ### Broadcast `Finish` no longer closes -`BroadcastProducer.Finish()` was a deprecated alias for `Close()`; it no longer ends the broadcast at once. +`BroadcastProducer.Finish()` was a deprecated alias for `Close()`; it now finishes only the catalog, and the broadcast stays up until `Close()`. Call `BroadcastProducer.Close()` where you called `Finish()`. ### JSON snapshot `DeltaRatio` is `Deltas` @@ -82,7 +82,7 @@ Clamp timestamps you build from unbounded input to `2^61 - 1`. ### Finished tracks stay until the broadcast ends (#6157) -A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes or the new `BroadcastProducer.Finish()` lets go. +A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes. Publish a replacement under a new name, and expect a finished track's demand watch to end with the broadcast. ### A claim answers by publishing (#5678) diff --git a/go/wrapper/moq_test.go b/go/wrapper/moq_test.go index a0e858d367a..7e5088eb474 100644 --- a/go/wrapper/moq_test.go +++ b/go/wrapper/moq_test.go @@ -143,66 +143,30 @@ func TestPublishAudioLifecycle(t *testing.T) { } } -func TestBroadcastFinishLingersUntilCancelled(t *testing.T) { +func TestBroadcastFinishThenClose(t *testing.T) { broadcast, err := moq.NewBroadcastProducer() if err != nil { t.Fatal(err) } - maxAge := time.Hour - track, err := broadcast.PublishTrack("status", &moq.TrackInfo{MaxAge: &maxAge}) + track, err := broadcast.PublishTrack("status", nil) if err != nil { t.Fatal(err) } if err := track.Finish(); err != nil { t.Fatal(err) } - finish, err := broadcast.Finish() - if err != nil { - t.Fatal(err) - } - if got := finish.Linger(); got != time.Hour { - t.Fatalf("Linger = %v, want 1h", got) - } - if _, err := broadcast.Consume(); err == nil { - t.Fatal("Consume after Finish succeeded") - } - - // A cancelled wait is the interrupt: it returns at once instead of lingering. - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - if err := finish.Wait(ctx); !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("Wait = %v, want the deadline", err) - } - finish.Close() -} - -func TestBroadcastFinishWaitOnDoneContextCloses(t *testing.T) { - broadcast, err := moq.NewBroadcastProducer() - if err != nil { - t.Fatal(err) - } - maxAge := time.Hour - track, err := broadcast.PublishTrack("status", &moq.TrackInfo{MaxAge: &maxAge}) - if err != nil { + if err := broadcast.Finish(); err != nil { t.Fatal(err) } - if err := track.Finish(); err != nil { - t.Fatal(err) + // Finishing the content leaves the broadcast up until it closes. + if _, err := broadcast.Consume(); err != nil { + t.Fatalf("Consume after Finish = %v", err) } - finish, err := broadcast.Finish() - if err != nil { + if err := broadcast.Close(); err != nil { t.Fatal(err) } - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if err := finish.Wait(ctx); !errors.Is(err, context.Canceled) { - t.Fatalf("Wait = %v, want cancelled", err) - } - // Closed by the cancelled wait, so a second wait fails at once instead of lingering. - ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := finish.Wait(ctx); !errors.Is(err, moq.ErrClosed) { - t.Fatalf("second Wait = %v, want closed", err) + if err := broadcast.Finish(); !errors.Is(err, moq.ErrClosed) { + t.Fatalf("Finish after Close = %v, want closed", err) } } diff --git a/go/wrapper/publish.go b/go/wrapper/publish.go index 7add3e867f6..79650cf147a 100644 --- a/go/wrapper/publish.go +++ b/go/wrapper/publish.go @@ -3,8 +3,6 @@ package moq import ( "context" "iter" - "math" - "time" ffi "moq.dev/moq-ffi/moq" "moq.dev/moq/internal/bridge" @@ -81,51 +79,13 @@ func (b *BroadcastProducer) Close() error { return b.inner.Close() } -// Finish ends the broadcast cleanly, keeping it servable until its media goes stale. +// Finish ends the broadcast's content by finishing its catalog. // -// Finish every track first: the returned handle holds the tracks finished by now -// and keeps the broadcast announced, so a subscriber still catching up can drain -// them. A track still live is not held. Every later call on this producer fails, -// as after [BroadcastProducer.Close]. -func (b *BroadcastProducer) Finish() (*BroadcastFinish, error) { - inner, err := b.inner.Finish() - if err != nil { - return nil, err - } - return &BroadcastFinish{inner: inner}, nil -} - -// BroadcastFinish is a cleanly ended broadcast, still announced and serving its -// finished tracks. Closing it, or cancelling a [BroadcastFinish.Wait], closes -// the broadcast at once. An unreferenced one closes the broadcast only when the -// garbage collector reclaims it, possibly long after, so wait on or close it. -type BroadcastFinish struct { - inner *ffi.MoqBroadcastFinish -} - -// Linger is how long to keep the broadcast: the longest max age of the held tracks. -func (f *BroadcastFinish) Linger() time.Duration { - us := f.inner.LingerUs() - if us > math.MaxInt64/uint64(time.Microsecond) { - return math.MaxInt64 - } - return time.Duration(us) * time.Microsecond -} - -// Wait keeps the broadcast up for its linger, or until [BroadcastFinish.Close], -// then closes it. Cancelling ctx closes the broadcast at once. -func (f *BroadcastFinish) Wait(ctx context.Context) error { - // The bridge starts no call on a done ctx, so it would never reach the close. - if err := ctx.Err(); err != nil { - f.inner.Close() - return err - } - return bridge.CallErr(ctx, f.inner.Close, f.inner.Wait) -} - -// Close closes the broadcast now, ending the linger and any wait. Closing again is a no-op. -func (f *BroadcastFinish) Close() { - f.inner.Close() +// Finish every track first. The broadcast stays announced and keeps serving its +// finished tracks to late subscribers until [BroadcastProducer.Close] takes it +// offline; how long to keep it up is yours to decide. +func (b *BroadcastProducer) Finish() error { + return b.inner.Finish() } // BroadcastDynamic is a stream of subscriber-requested tracks. diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index 3902fe761ab..a3024baaabc 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -1,12 +1,10 @@ import { expect, setSystemTime, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Milli } from "@moq/clock"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { GroupTooLarge, NotFound, ProtocolViolation, TimestampMismatch } from "./error.ts"; import { Producer as GroupProducer, MAX_GROUP_FRAMES } from "./group.ts"; import { TrackSequences } from "./internal.ts"; import { textFrame } from "./mock.ts"; -import { Producer as OriginProducer } from "./origin.ts"; -import * as Path from "./path.ts"; import { Timescale, Timestamp } from "./time.ts"; import type { Request as TrackRequest } from "./track.ts"; import { unwanted } from "./util/demand.ts"; @@ -947,118 +945,3 @@ test("removeTrack stops counting the removed track's demand at once", async () = video.close(); broadcast.close(); }); - -// A track holding one finished group, with the given max-age in seconds. -function finishedTrack(broadcast: BroadcastProducer, name: string, maxAge?: number) { - const track = broadcast.createTrack(name, { - timescale: Timescale.MILLI, - maxAge: maxAge === undefined ? undefined : Milli(maxAge * 1_000), - }); - const group = track.appendGroup(); - group.writeFrame(textFrame(name, Timestamp.fromMillis(0))); - group.close(); - return track; -} - -// A finished broadcast keeps serving its finished tracks, so a late subscriber still gets the media, -// and closes once the longest max-age passes. A live track, an aborted one, and a track without a -// max-age add nothing to the wait. -test("finish serves finished tracks until stale", async () => { - const clock = new Manual(); - const installed = clock.install(); - const origin = new OriginProducer(); - try { - const broadcast = origin.createBroadcast(Path.from("finish")); - const consumer = broadcast.consume(); - const live = finishedTrack(broadcast, "live", 60); - const aborted = finishedTrack(broadcast, "aborted", 60); - aborted.close(new Error("gone")); - for (const [name, age] of [ - ["video", 2], - ["audio", 5], - ["catalog", undefined], - ] as const) { - finishedTrack(broadcast, name, age).close(); - } - broadcast.announce(); - - const finish = broadcast.finish(); - expect(finish.linger).toBe(Milli(5_000)); - let done = false; - const wait = finish.wait().then(() => { - done = true; - }); - - await clock.advance(Nano.fromMilli(Milli(4_000))); - const late = consumer.track("audio").subscribe().ordered(); - expect(await late.readString()).toBe("audio"); - expect(done).toBe(false); - expect(broadcast.route).toBeDefined(); - - await clock.advance(Nano.fromMilli(Milli(1_000))); - await wait; - expect(Number(clock.now())).toBe(Nano.fromMilli(Milli(5_000))); - expect(consumer.closed.peek()).toBeNull(); - expect(broadcast.route).toBeUndefined(); - expect(() => consumer.track("audio").subscribe()).toThrow("broadcast is closed"); - late.close(); - live.close(); - } finally { - origin.close(); - installed.close(); - } -}); - -// The linger is the local retention window, so the cache window caps a longer max-age. -test("finish caps the linger at the cache window", () => { - const broadcast = new BroadcastProducer(); - finishedTrack(broadcast, "video", 600).close(); - expect(broadcast.finish().linger).toBe(Milli(30_000)); - broadcast.close(); -}); - -// Closing the handle, the interrupt, closes the broadcast at once. -test("closing a finish closes the broadcast early", () => { - const broadcast = new BroadcastProducer(); - finishedTrack(broadcast, "video", 30).close(); - const finish = broadcast.finish(); - expect(finish.closed.peek()).toBeUndefined(); - finish.close(); - expect(broadcast.closed.peek()).toBeNull(); - finish.close(); -}); - -// The linger is fixed at finish, so the broadcast refuses any change that could outlast it. -test("a finished broadcast refuses changes", () => { - const origin = new OriginProducer(); - const broadcast = origin.createBroadcast(Path.from("finish")); - finishedTrack(broadcast, "video", 30).close(); - broadcast.announce(); - const finish = broadcast.finish(); - expect(() => broadcast.createTrack("audio")).toThrow("broadcast is finished"); - expect(() => broadcast.removeTrack("video")).toThrow("broadcast is finished"); - expect(() => broadcast.announce()).toThrow("broadcast is finished"); - expect(() => broadcast.unannounce()).toThrow("broadcast is finished"); - expect(() => broadcast.finish()).toThrow("broadcast is finished"); - expect(broadcast.route).toBeDefined(); - finish.close(); - origin.close(); -}); - -// A close elsewhere ends the linger early. -test("closing the broadcast elsewhere ends the linger", async () => { - const clock = new Manual(); - const installed = clock.install(); - try { - const broadcast = new BroadcastProducer(); - finishedTrack(broadcast, "video", 30).close(); - const finish = broadcast.finish(); - const wait = finish.wait(); - await clock.advance(Nano.fromMilli(Milli(1_000))); - broadcast.close(); - await wait; - expect(Number(clock.now())).toBe(Nano.fromMilli(Milli(1_000))); - } finally { - installed.close(); - } -}); diff --git a/js/net/src/broadcast.ts b/js/net/src/broadcast.ts index a88f71cd283..a9d6e31af4c 100644 --- a/js/net/src/broadcast.ts +++ b/js/net/src/broadcast.ts @@ -3,8 +3,7 @@ * * @module */ -import { Milli, sleep } from "@moq/clock"; -import { type Dispose, type GetPromise, type Getter, Once, race, Signal } from "@moq/signals"; +import { type Dispose, type GetPromise, type Getter, Once, Signal } from "@moq/signals"; import type * as Epoch from "./epoch.ts"; import { NotFound } from "./error.ts"; import type { Consumer as GroupConsumer } from "./group.ts"; @@ -367,8 +366,6 @@ export class Producer { #demand = makeDemand(this.#state); #announcer?: Announcer; #path = Path.empty(); - // Set by `finish()`, which fixes the linger, so nothing may change the broadcast afterward. - #finished = false; constructor() { registerWire(this, { @@ -431,13 +428,12 @@ export class Producer { * from the returned producer. A request a handler has already taken stays a duplicate. * An append on the track throws if it would reuse a sequence an earlier track of the name * wrote in this broadcast, so a replacement writes its first group explicitly. Throws if an - * open track or a live request already holds the name, or once the broadcast is finished. + * open track or a live request already holds the name. */ createTrack(name: string, info: Partial = {}): track.Producer { if (this.#state.closed.peek() !== undefined) { throw new Error("broadcast is closed"); } - this.#assertUnfinished(); const request = takeQueued(this.#state, name); if (request) { @@ -465,10 +461,9 @@ export class Producer { /** * Remove a statically inserted track, including a finished cached one: stop counting it - * toward {@link demand} and listing it at once. Throws once the broadcast is finished. + * toward {@link demand} and listing it at once. */ removeTrack(name: string): void { - this.#assertUnfinished(); const track = this.#state.tracks.get(name); if (!track) return; this.#state.tracks.delete(name); @@ -496,8 +491,7 @@ export class Producer { * Call it once the tracks a subscriber needs first (a catalog) exist. Until then the * broadcast exists for nobody, on its own origin or at a peer. Retracts on * {@link unannounce} or {@link close}. Throws if this producer was not created through an - * origin, is a claim answer still being prepared, or if the broadcast is already closed or - * finished. + * origin, is a claim answer still being prepared, or if the broadcast is already closed. */ announce( route: @@ -512,17 +506,15 @@ export class Producer { if (this.#state.closed.peek() !== undefined) { throw new Error("broadcast is closed"); } - this.#assertUnfinished(); if (!this.#announcer) throw new Error("broadcast is not attached to an origin"); this.#announcer.announce(Route.normalize(route)); } /** * Retract the advertisement of this broadcast's path, if any, from local consumers and - * peers alike. {@link announce} brings it back. Throws once the broadcast is finished. + * peers alike. {@link announce} brings it back. */ unannounce(): void { - this.#assertUnfinished(); this.#announcer?.unannounce(); } @@ -532,82 +524,6 @@ export class Producer { this.#announcer = undefined; closeState(this.#state); } - - /** - * End the broadcast cleanly, keeping it servable until its media goes stale. - * - * A subscriber still catching up, one that read the final catalog late or is draining a - * backlog, can still request and drain the tracks closed cleanly by now. The returned - * {@link Finish} keeps the broadcast announced: keep it for its {@link Finish.linger}, then - * {@link Finish.close} it, or let {@link Finish.wait} do both. Closing it early is the - * interrupt. Close the tracks first; one still open adds nothing. From here the broadcast - * takes no more changes: creating or removing a track, announcing, unannouncing, or finishing - * again throws. - */ - finish(): Finish { - this.#assertUnfinished(); - this.#finished = true; - let linger = Milli.zero; - for (const track of this.#state.tracks.values()) linger = Milli(Math.max(linger, hooks.linger(track))); - return makeFinish(this, linger); - } - - #assertUnfinished(): void { - if (this.#finished) throw new Error("broadcast is finished"); - } -} - -let makeFinish: (producer: Producer, linger: Milli) => Finish; - -/** - * A cleanly ended broadcast, still announced and serving its finished tracks. - * - * Returned by {@link Producer.finish}. Closing it closes the broadcast. - * - * @public - */ -export class Finish { - /** - * How long to keep this handle: the longest {@link track.Info.maxAge} of the tracks closed - * cleanly before {@link Producer.finish}, each capped by the cache window. Open or aborted - * tracks, and tracks without a max-age, add nothing. - */ - readonly linger: Milli; - - #producer: Producer; - - private constructor(producer: Producer, linger: Milli) { - this.#producer = producer; - this.linger = linger; - } - - static { - makeFinish = (producer, linger) => new Finish(producer, linger); - } - - /** Settles with `null` once the broadcast closes, here or elsewhere, which ends the linger early. */ - get closed(): GetPromise { - return this.#producer.closed; - } - - /** - * Keep the broadcast up for {@link linger} on the installed clock, or until it closes - * elsewhere, then close it. The linger counts from this call. - */ - async wait(): Promise { - const timer = new AbortController(); - try { - await race([sleep(Milli.toNano(this.linger), { signal: timer.signal }), this.closed]); - } finally { - timer.abort(); - this.close(); - } - } - - /** Close the broadcast now, ending the linger early. Idempotent. */ - close(): void { - this.#producer.close(); - } } // What a new consumer handle inherits: the shared broadcast plus the path naming it. diff --git a/js/net/src/internal.ts b/js/net/src/internal.ts index 9a70079e402..ca9dfc0f53b 100644 --- a/js/net/src/internal.ts +++ b/js/net/src/internal.ts @@ -423,11 +423,6 @@ export const hooks: { bindSequence: (producer: Producer, sequence: TrackSequence) => void; /** The newest frame a producer's cache holds, read without subscribing; assigned by `track.ts`. */ cachedLargest: (producer: Producer) => Position | undefined; - /** - * How long a broadcast finishing now keeps this track servable: its max-age capped by the - * cache window once it closed cleanly, else zero; assigned by `track.ts`. - */ - linger: (producer: Producer) => Milli; /** The publisher priority from a demanded track's committed {@link Info}; assigned by `track.ts`. */ demandPriority: (demand: Demand) => number; /** Seed a received track from the publisher's reported edge; assigned by `track.ts`. */ @@ -596,9 +591,6 @@ export const hooks: { cachedLargest: () => { throw new Error("track.ts not loaded"); }, - linger: () => { - throw new Error("track.ts not loaded"); - }, demandPriority: () => { throw new Error("track.ts not loaded"); }, diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 1e825df913b..a06faaeaf2f 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -826,11 +826,6 @@ export class Producer { }; hooks.bindSequence = bindProducerSequence; hooks.cachedLargest = (producer) => producer.#cachedLargest(); - hooks.linger = (producer) => { - const maxAge = producer.#state.info.peek()?.maxAge; - if (producer.#state.closed.peek() !== null || maxAge === undefined) return Milli.zero; - return Milli(Math.min(maxAge, Milli.fromNano(CACHE_WINDOW))); - }; hooks.reportedLargest = (producer, largest) => producer.#advanceLargest(largest); cachedHolds = (producer, sequence) => { const entry = producer.#cached.get(sequence); diff --git a/kt/moq/MIGRATE.md b/kt/moq/MIGRATE.md index 1f3c1289afb..2f3d510de48 100644 --- a/kt/moq/MIGRATE.md +++ b/kt/moq/MIGRATE.md @@ -42,7 +42,7 @@ Audio and video init records no longer carry a track name. Pass that name on the ### Broadcast `finish` no longer closes -`BroadcastProducer.finish()` was a deprecated alias for `end()`; it no longer ends the broadcast at once. +`BroadcastProducer.finish()` was a deprecated alias for `end()`; it now finishes only the catalog, and the broadcast stays up until `end()`. Call `BroadcastProducer.end()` where you called `finish()`. ### JSON snapshot `deltaRatio` is `deltas` @@ -83,7 +83,7 @@ Clamp timestamps you build from unbounded input to `2^61 - 1`. ### Finished tracks stay until the broadcast ends (#6157) -A finished track now stays listed, with its catalog rendition and demand, until its broadcast ends or the new `BroadcastProducer.finish()` lets go. +A finished track now stays listed, with its catalog rendition and demand, until its broadcast ends. Publish a replacement under a new name, and expect a finished track's demand watch to end with the broadcast. ### A claim answers by publishing (#5678) diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index eb38b34963b..36cdb63a6c7 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -75,8 +75,6 @@ typealias BroadcastProducer = uniffi.moq.MoqBroadcastProducer typealias BroadcastConsumer = uniffi.moq.MoqBroadcastConsumer /** Receives tracks requested from a dynamically served broadcast. */ typealias BroadcastDynamic = uniffi.moq.MoqBroadcastDynamic -/** A cleanly ended broadcast, still announced and serving its finished tracks until its linger ends. */ -typealias BroadcastFinish = uniffi.moq.MoqBroadcastFinish /** The write side of a raw track: append groups of frames. */ typealias TrackProducer = uniffi.moq.MoqTrackProducer /** A subscriber-requested track not yet accepted: accept it for a [TrackProducer] or abort it. */ diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt index e58584abbe3..33b01f90d4c 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt @@ -69,10 +69,6 @@ val AudioDecoderOutput.maxDelay: Duration? val AudioDecoderOutput.delay: Duration? get() = delayUs?.toLong()?.microseconds -/** How long to keep a finished broadcast: the longest max age of the tracks it holds. */ -val BroadcastFinish.linger: Duration - get() = lingerUs().coerceAtMost(Long.MAX_VALUE.toULong()).toLong().microseconds - /** Playout delay to hold ahead of the playhead: the fixed one, or the estimate from every frame read so far. */ val dev.moq.audio.Consumer.delay: Duration get() = delayUs().toLong().microseconds diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index 4bc7cdc0d2e..9df63a3dd6b 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -14,7 +14,6 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runTest -import kotlinx.coroutines.yield import dev.moq.json.SnapshotConfig import dev.moq.json.SnapshotConsumer import dev.moq.json.SnapshotProducer @@ -40,7 +39,6 @@ import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue -import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.microseconds import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration @@ -244,19 +242,14 @@ class SmokeTest { } @Test - fun `finishing a broadcast lingers until the wait is cancelled`() = runTest { - val broadcast = BroadcastProducer() - val track = broadcast.publishTrack("status", TrackInfo(maxAgeUs = 3_600_000_000uL)) - track.finish() - broadcast.finish().use { finish -> - assertEquals(1.hours, finish.linger) - assertFailsWith { broadcast.consume() } - // Cancelling the wait is the interrupt: it ends instead of lingering for an hour. - val wait = async { finish.wait() } - yield() - wait.cancel() - wait.join() - finish.end() + fun `a finished broadcast stays up until it ends`() { + BroadcastProducer().use { broadcast -> + broadcast.publishTrack("status", null).finish() + broadcast.finish() + // Finishing the content leaves the broadcast up until it ends. + broadcast.consume().close() + broadcast.end() + assertFailsWith { broadcast.finish() } } } diff --git a/py/moq-rs/MIGRATE.md b/py/moq-rs/MIGRATE.md index 66c1f00e880..a946a10c8a9 100644 --- a/py/moq-rs/MIGRATE.md +++ b/py/moq-rs/MIGRATE.md @@ -42,7 +42,7 @@ Audio and video init records no longer carry a track name. Pass that name on the ### Broadcast `finish` no longer closes -`BroadcastProducer.finish()` was a deprecated alias for `close()`; it no longer ends the broadcast at once. +`BroadcastProducer.finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. Call `BroadcastProducer.close()` where you called `finish()`. ### JSON snapshot `delta_ratio` is `deltas` @@ -83,7 +83,7 @@ Clamp timestamps you build from unbounded input to `2^61 - 1`. ### Finished tracks stay until the broadcast ends (#6157) -A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes or the new `BroadcastProducer.finish()` lets go. +A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes. Publish a replacement under a new name, and expect a finished track's demand watch to end with the broadcast. ### A claim answers by publishing (#5678) diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index 97c24aa1f3b..e0de57a5bec 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -32,7 +32,6 @@ ) from .publish import ( BroadcastDynamic, - BroadcastFinish, BroadcastProducer, GroupProducer, GroupRequest, @@ -101,7 +100,6 @@ "Bandwidth", "BroadcastConsumer", "BroadcastDynamic", - "BroadcastFinish", "BroadcastPrepared", "BroadcastProducer", "BroadcastRequest", diff --git a/py/moq-rs/moq/publish.py b/py/moq-rs/moq/publish.py index 79db88f262f..fcf3f608554 100644 --- a/py/moq-rs/moq/publish.py +++ b/py/moq-rs/moq/publish.py @@ -2,14 +2,11 @@ from __future__ import annotations -import asyncio -from collections.abc import Coroutine, Generator from datetime import timedelta -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from moq_ffi import ( MoqBroadcastDynamic, - MoqBroadcastFinish, MoqBroadcastProducer, MoqGroupProducer, MoqGroupRequest, @@ -19,7 +16,7 @@ MoqTrackRequest, ) -from ._records import _from_us, _subscription, _track_info +from ._records import _subscription, _track_info from ._stream import _Stream from .types import ( AnnounceRoute, @@ -312,73 +309,11 @@ def close(self) -> None: """ self._inner.close() - def finish(self) -> BroadcastFinish: - """End the broadcast cleanly, keeping it servable until its media goes stale. + def finish(self) -> None: + """End the broadcast's content by finishing its catalog. - Finish every track first: the returned handle holds the tracks finished by now and - keeps the broadcast announced, so a subscriber still catching up can drain them. A - track still live is not held. Every later call on this producer fails, as after - :meth:`close`. + Finish every track first. The broadcast stays announced and keeps serving its + finished tracks to late subscribers until :meth:`close` takes it offline; how long + to keep it up is yours to decide. """ - return BroadcastFinish(self._inner.finish()) - - -class BroadcastFinish: - """A cleanly ended broadcast, still announced and serving its finished tracks. - - Await :meth:`wait` to keep it up for its :attr:`linger`. Cancelling the wait, or - :meth:`close`, closes the broadcast at once. - """ - - def __init__(self, inner: MoqBroadcastFinish) -> None: - self._inner = inner - - @property - def linger(self) -> timedelta: - """How long to keep the broadcast: the longest max age of the held tracks.""" - return _from_us(self._inner.linger_us()) - - def wait(self) -> Coroutine[Any, Any, None]: - """Keep the broadcast up for its linger, or until :meth:`close`, then close it.""" - return _FinishWait(self._inner) - - def close(self) -> None: - """Close the broadcast now, ending the linger and any wait. Closing again is a no-op.""" - self._inner.close() - - -class _FinishWait(Coroutine[Any, Any, None]): - """A finish's wait that closes the broadcast when cancelled. - - A coroutine body never runs when its task is cancelled before the first step, so the - close hooks the cancellation thrown in rather than an ``except`` inside the body. - """ - - def __init__(self, inner: MoqBroadcastFinish) -> None: - self._inner = inner - self._wait = inner.wait() - - def __await__(self) -> Generator[Any, None, None]: - return self - - def __iter__(self) -> Generator[Any, None, None]: - return self - - def __next__(self) -> Any: - return self.send(None) - - def send(self, value: Any) -> Any: - return self._wait.send(value) - - def throw(self, typ: Any, val: Any = None, tb: Any = None) -> Any: - error = typ if val is None else val - if isinstance(error, asyncio.CancelledError) or ( - isinstance(error, type) and issubclass(error, asyncio.CancelledError) - ): - self._inner.close() - if val is None and tb is None: - return self._wait.throw(typ) - return self._wait.throw(typ, val, tb) - - def close(self) -> None: - self._wait.close() + self._inner.finish() diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index ae0b6a811b2..cdfbd310c45 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -411,56 +411,28 @@ async def test_announced_epoch_restarts(): broadcast.close() -async def test_finish_lingers_until_closed(): +async def test_finish_serves_until_closed(): origin = moq.OriginProducer() consumer = origin.consume() announced = consumer.announced() broadcast = create_announced(origin, "finish") assert isinstance(await next_route(announced), moq.AnnounceEventStart) - track = broadcast.publish_track("status", moq.TrackInfo(max_age=timedelta(hours=1))) + track = broadcast.publish_track("status") track.write_frame(b"tail") track.finish() - finish = broadcast.finish() - assert finish.linger == timedelta(hours=1) - with pytest.raises(moq.Error.Closed): - broadcast.consume() - - # Cancelling the wait is the interrupt: the broadcast closes at once. - wait = asyncio.ensure_future(finish.wait()) - await asyncio.sleep(0) - wait.cancel() - with pytest.raises(asyncio.CancelledError): - await wait - assert isinstance(await next_route(announced), moq.AnnounceEventEnd) - finish.close() - + broadcast.finish() -async def test_finish_wait_cancelled_before_it_starts_closes(): - origin = moq.OriginProducer() - consumer = origin.consume() - announced = consumer.announced() - broadcast = create_announced(origin, "finish") - assert isinstance(await next_route(announced), moq.AnnounceEventStart) + # A late subscriber still drains the finished track while the broadcast is up. + late = await consumer.request_broadcast("finish") + reader = await late.subscribe_track("status") + frame = await asyncio.wait_for(reader.read_frame(), timeout=5) + assert frame is not None and frame.payload == b"tail" - broadcast.publish_track("status", moq.TrackInfo(max_age=timedelta(hours=1))).finish() - finish = broadcast.finish() - # Cancelled before the loop first steps it, so the wait's body never runs. - wait = asyncio.create_task(finish.wait()) - wait.cancel() - with pytest.raises(asyncio.CancelledError): - await wait + broadcast.close() assert isinstance(await next_route(announced), moq.AnnounceEventEnd) -async def test_finish_without_a_max_age_closes_on_wait(): - broadcast = moq.BroadcastProducer() - broadcast.publish_track("status").finish() - finish = broadcast.finish() - assert finish.linger == timedelta(0) - await asyncio.wait_for(finish.wait(), timeout=5.0) - - def test_publish_lifecycle(): broadcast = moq.BroadcastProducer() track = broadcast.publish_track("status") diff --git a/py/moq-rs/tests/test_testing_clock.py b/py/moq-rs/tests/test_testing_clock.py index 8dd4a345221..10f6256de7d 100644 --- a/py/moq-rs/tests/test_testing_clock.py +++ b/py/moq-rs/tests/test_testing_clock.py @@ -60,53 +60,6 @@ async def main(): ) -def test_a_finished_broadcast_lingers_for_its_max_age() -> None: - _run( - """ - import asyncio - from datetime import timedelta - - import moq - from moq.testing import Clock - - clock = Clock() - - async def main(): - origin = moq.OriginProducer() - consumer = origin.consume() - announced = consumer.announced() - broadcast = origin.create_broadcast("linger") - broadcast.announce() - start = await asyncio.wait_for(anext(announced), timeout=5) - assert isinstance(start, moq.AnnounceEventStart) - track = broadcast.publish_track("track", moq.TrackInfo(max_age=timedelta(seconds=2))) - track.write_frame(b"tail") - track.finish() - - finish = broadcast.finish() - assert finish.linger == timedelta(seconds=2) - done = asyncio.ensure_future(finish.wait()) - - # A late subscriber within the max age still drains the finished track. - clock.advance(1.999) - late = await consumer.request_broadcast("linger") - reader = await late.subscribe_track("track") - frame = await asyncio.wait_for(reader.read_frame(), timeout=5) - assert frame is not None and frame.payload == b"tail" - await asyncio.sleep(0.05) - assert not done.done() - - # Once the max age passes, the broadcast closes. - clock.advance(0.001) - await asyncio.wait_for(done, timeout=5) - end = await asyncio.wait_for(anext(announced), timeout=5) - assert isinstance(end, moq.AnnounceEventEnd) - - asyncio.run(main()) - """ - ) - - def test_clock_refuses_invalid_advances() -> None: _run( """ diff --git a/quest/m1/broadcast-lifecycle/README.md b/quest/m1/broadcast-lifecycle/README.md index 04554384a88..f7fa285b3b0 100644 --- a/quest/m1/broadcast-lifecycle/README.md +++ b/quest/m1/broadcast-lifecycle/README.md @@ -46,7 +46,6 @@ timer on main at 1582fdc07d: ## Required -- [Stateless broadcasts](/quest/m1/broadcast-lifecycle/stateless.md) - `Finish`, its linger, and finished-only supersession are gone from moq-net, `@moq/net`, moq-ffi, moq-c, and every binding - [TS export follows by cause](/quest/m1/broadcast-lifecycle/ts-follow.md) - `export ts|srt --linger` becomes `--follow `, a replacement's catalog has no separate deadline, and a track failure is classified by its cause instead of a 1s grace - [SRT tells a clean end from a failure](/quest/m1/broadcast-lifecycle/srt-end.md) - an SRT ingest whose peer goes silent aborts instead of finishing as if it had shut down - [Timer cleanups](/quest/m1/broadcast-lifecycle/timers.md) - `ConnectionProps.linger` is gone and stale linger references are fixed diff --git a/quest/m1/broadcast-lifecycle/stateless.md b/quest/m1/broadcast-lifecycle/stateless.md deleted file mode 100644 index a95d03ff791..00000000000 --- a/quest/m1/broadcast-lifecycle/stateless.md +++ /dev/null @@ -1,42 +0,0 @@ -# [L] Stateless broadcasts - -## Goal - -moq-net and `@moq/net` broadcasts have no finished state. `Producer::finish`, -`Finish`, `Finish::linger`, `Finish::wait`, and the origin's finished-only -supersession (`Consumer::supersede`, `routes.superseded`, `Announcer::superseded`, -`BroadcastState.finished`/`superseded`) are deleted, along with moq-ffi's -`MoqBroadcastFinish` and moq-c's `moq_publish_finish` and -`moq_publish_finish_close`, and their wrappers in every binding. A publisher -ends its content by finishing its tracks (hang: the catalog) and goes offline -by closing the broadcast. - -## Plan - -Decided with the maintainer on 2026-10-23; see the epic for why. - -- Keep the epoch routing that lets a restarted publisher win - (#6452); only supersession of a finished broadcast goes. -- Prove the property this relies on before deleting: a relay keeps - delivering a finished track to its existing downstream subscribers after - the upstream publisher's session closes, on lite and moq-transport. Fix - it at the source if it does not. -- The interop `finish` case must keep passing on lite. Each interop - publisher (Rust through the moq-mux helper; JS, C, C++ and the bindings by - holding their finished broadcast open) keeps its broadcast up long enough - for the late readers. -- `js/publish` drops its `Finish` bookkeeping - (`js/publish/src/broadcast.ts`, the catalog's `Number.MAX_SAFE_INTEGER` - max-age only if nothing else needs it). `js/net` drops `hooks.linger` and - its `CACHE_WINDOW` use there. -- Update `doc/concept` with one paragraph on the model (online = announced, - end of content = track FIN, retention = app policy), plus `doc/lib/*`, and - the Impact bullet says how to migrate every affected package. It - supersedes the `MIGRATE.md` entries on `finish` (#5795, #6157, and the - binding entries measured against release's `finish()` alias for - `close()`), for the cut to collapse. -- Coordinate with [publication owner](/quest/m1/api-audit/announce-owner.md), - which touches the same handles. - -Public API: breaking in moq-net, `@moq/net`, moq-ffi, moq-c, and every -binding. Wire: none. diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index 2139f8017c6..89e475006f6 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -61,7 +61,7 @@ Clamp timestamps you build from unbounded input to `2^61 - 1`. ### Finished tracks stay until the broadcast ends (#6157) -`moq_publish_track_finish`, `moq_publish_media_finish`, `moq_publish_container_finish`, and the encoder finishes now release the handle while the broadcast keeps the finished track listed, with its catalog rendition and demand, until `moq_publish_close` or the new `moq_publish_finish_close`. +`moq_publish_track_finish`, `moq_publish_media_finish`, `moq_publish_container_finish`, and the encoder finishes now release the handle while the broadcast keeps the finished track listed, with its catalog rendition and demand, until `moq_publish_close`. Publish a replacement under a new name, and expect a finished track's demand terminal callback when the broadcast closes rather than at the finish. ### A claim answers by publishing (#5678) diff --git a/rs/moq-ffi/MIGRATE.md b/rs/moq-ffi/MIGRATE.md index 43c4ed58feb..52cf15af8e8 100644 --- a/rs/moq-ffi/MIGRATE.md +++ b/rs/moq-ffi/MIGRATE.md @@ -48,7 +48,7 @@ Pass that name through `MoqMediaTarget::Named { name }` when constructing `MoqMe ### Broadcast `finish` no longer closes -`MoqBroadcastProducer::finish()` was a deprecated alias for `close()`; it no longer ends the broadcast at once. +`MoqBroadcastProducer::finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. Call `MoqBroadcastProducer::close()` where you called `finish()`. ### JSON snapshot `delta_ratio` is `deltas` @@ -89,7 +89,7 @@ Clamp timestamps you build from unbounded input to `2^61 - 1`. ### Finished tracks stay until the broadcast ends (#6157) -A finished track, raw or media, now stays listed, with its catalog rendition and demand, until its broadcast closes or the new `MoqBroadcastProducer::finish` lets go, instead of unlisting when its producer finishes or is released. +A finished track, raw or media, now stays listed, with its catalog rendition and demand, until its broadcast closes, instead of unlisting when its producer finishes or is released. Publish a replacement under a new name, and expect a finished track's demand watch to end with the broadcast. ### A claim answers by publishing (#5678) diff --git a/rs/moq-net/MIGRATE.md b/rs/moq-net/MIGRATE.md index 5217703883f..c1203ef085d 100644 --- a/rs/moq-net/MIGRATE.md +++ b/rs/moq-net/MIGRATE.md @@ -281,17 +281,11 @@ A track received over moq-lite-05/06 arrives untimed, since its timestamps may b One received over moq-transport keeps its timestamps unchecked, and a relay serves it to moq-lite untimed. A publisher whose timeline restarts, such as an HLS `EXT-X-DISCONTINUITY` that resets decode times, publishes a new broadcast instead. -### Broadcast `finish` returns a linger handle (#5795) +### Broadcast `finish` is gone -`finish()` ends the broadcast cleanly and returns a `Finish` that keeps its finished tracks servable until their media is stale. -Dropping the `Finish` closes the broadcast, so `close()` still ends it now. - -```rust -// Close now -producer.close(); -// Serve late subscribers until the media is stale -producer.finish().wait().await; -``` +`broadcast::Producer::finish()`, a deprecated alias for `close()`, is removed: a broadcast has no finished state. +Call `close()` where you called `finish()`. +To end content cleanly, finish each track, keep the producer for as long as late readers should find it, then close it; `moq_mux::Linger` does this for a hang broadcast. ### `auth::Token` is `auth::Auth` (#5695) diff --git a/swift/MIGRATE.md b/swift/MIGRATE.md index 8b430f73027..b6929a8a539 100644 --- a/swift/MIGRATE.md +++ b/swift/MIGRATE.md @@ -35,7 +35,7 @@ Audio and video init records no longer carry a track name. Pass that name on the ### Broadcast `finish` no longer closes -`BroadcastProducer.finish()` was a deprecated alias for `close()`; it no longer ends the broadcast at once. +`BroadcastProducer.finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. Call `BroadcastProducer.close()` where you called `finish()`. ### JSON snapshot `deltaRatio` is `deltas` @@ -76,7 +76,7 @@ Clamp timestamps you build from unbounded input to `2^61 - 1`. ### Finished tracks stay until the broadcast ends (#6157) -A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes or the new `BroadcastProducer.finish()` lets go. +A finished track now stays listed, with its catalog rendition and demand, until its broadcast closes. Publish a replacement under a new name, and expect a finished track's demand watch to end with the broadcast. ### A claim answers by publishing (#5678) diff --git a/swift/Sources/Moq/Broadcast.swift b/swift/Sources/Moq/Broadcast.swift index 0ea57cb0ee7..40579ee8778 100644 --- a/swift/Sources/Moq/Broadcast.swift +++ b/swift/Sources/Moq/Broadcast.swift @@ -100,41 +100,12 @@ public final class BroadcastProducer: Sendable { try ffi.close() } - /// End the broadcast cleanly, keeping it servable until its media goes stale. + /// End the broadcast's content by finishing its catalog. /// - /// Finish every track first: the returned handle holds the tracks finished by now and - /// keeps the broadcast announced, so a subscriber still catching up can drain them. A - /// track still live is not held. Every later call on this producer throws, as after - /// `close()`. - public func finish() throws -> BroadcastFinish { - BroadcastFinish(try ffi.finish()) - } -} - -/// A cleanly ended broadcast, still announced and serving its finished tracks. -/// -/// Closing it, or cancelling the task in `wait()`, closes the broadcast at once. -public final class BroadcastFinish: Sendable { - let ffi: MoqBroadcastFinish - - init(_ ffi: MoqBroadcastFinish) { - self.ffi = ffi - } - - /// How long to keep the broadcast, in microseconds: the longest max age of the held tracks. - public var lingerUs: UInt64 { ffi.lingerUs() } - - /// Keep the broadcast up for its linger, or until `close()`, then close it. - public func wait() async throws { - try await withTaskCancellationHandler { - try await ffi.wait() - } onCancel: { - ffi.close() - } - } - - /// Close the broadcast now, ending the linger and any wait. Closing again is a no-op. - public func close() { - ffi.close() + /// Finish every track first. The broadcast stays announced and keeps serving its finished + /// tracks to late subscribers until `close()` takes it offline; how long to keep it up is + /// yours to decide. + public func finish() throws { + try ffi.finish() } } diff --git a/swift/Tests/MoqTests/SmokeTests.swift b/swift/Tests/MoqTests/SmokeTests.swift index dfea8dc9c3d..f642f1ce652 100644 --- a/swift/Tests/MoqTests/SmokeTests.swift +++ b/swift/Tests/MoqTests/SmokeTests.swift @@ -263,19 +263,15 @@ final class SmokeTests: XCTestCase { XCTAssertThrowsError(try broadcast.publishTrack(name: "events")) } - func testFinishedBroadcastLingersUntilTheWaitIsCancelled() async throws { + func testFinishedBroadcastStaysUpUntilClosed() throws { let broadcast = try BroadcastProducer() - let track = try broadcast.publishTrack(name: "status", info: TrackInfo(maxAgeUs: 3_600_000_000)) + let track = try broadcast.publishTrack(name: "status") try track.finish() - let finish = try broadcast.finish() - XCTAssertEqual(finish.lingerUs, 3_600_000_000) - XCTAssertThrowsError(try broadcast.publishTrack(name: "events")) - // Cancelling the wait is the interrupt: it ends instead of lingering for an hour. - let wait = Task { try await finish.wait() } - await Task.yield() - wait.cancel() - _ = await wait.result - finish.close() + try broadcast.finish() + // Finishing the content leaves the broadcast up until it closes. + _ = try broadcast.consume() + try broadcast.close() + XCTAssertThrowsError(try broadcast.finish()) } func testVideoHintsReachMediaPublishApi() throws { diff --git a/test/interop/clients/cpp/main.cpp b/test/interop/clients/cpp/main.cpp index 376077846c9..1cf160e14ec 100644 --- a/test/interop/clients/cpp/main.cpp +++ b/test/interop/clients/cpp/main.cpp @@ -241,14 +241,17 @@ int publish( ok(audio->finish(), "audio finish"); ok(media->finish(), "video finish"); if (!finish_ack.empty()) { - const auto started = Clock::now(); - auto finish = ok(broadcast->finish(), "broadcast finish"); - const auto linger = std::chrono::microseconds(finish->linger_us()); - if (linger.count() <= 0) fail("finished media has no linger"); - std::printf("finish ready linger_us=%llu\n", static_cast(finish->linger_us())); + // Finishing finalizes the catalog; the broadcast stays up for the late readers until the + // close takes it offline. + ok(broadcast->finish(), "broadcast finish"); + const auto linger = std::chrono::seconds(10); + std::printf( + "finish ready linger_us=%llu\n", + static_cast(std::chrono::microseconds(linger).count()) + ); std::fflush(stdout); - ok(finish->wait().get(), "finish linger"); - if (Clock::now() - started < linger) fail("finish wait ended before its linger"); + std::this_thread::sleep_for(linger); + ok(broadcast->close(), "broadcast close"); std::puts("finish ended"); std::fflush(stdout); auto health = ok(session->publish()->create_broadcast(path + ".health"), "health broadcast"); diff --git a/test/interop/clients/go/main.go b/test/interop/clients/go/main.go index 36add74524e..c6d0ab216f9 100644 --- a/test/interop/clients/go/main.go +++ b/test/interop/clients/go/main.go @@ -44,6 +44,9 @@ const readChunk = 64 * 1024 // media.TrackConsumer max delay: how much reordering the jitter buffer tolerates. const maxDelay = time.Second +// finishLinger is how long a finished publisher stays up for the late readers. +const finishLinger = 10 * time.Second + // durationPtr is d as the optional duration the wrapper's options take. func durationPtr(d time.Duration) *time.Duration { return &d } @@ -218,24 +221,20 @@ func publish(ctx context.Context, url, broadcast string, opts dialOptions, timeo if finishAck == "" { return nil } - // Finish also finalizes the catalog. ACK never controls the real linger. - started := time.Now() - finished, err := producer.Finish() - if err != nil { + // Finish finalizes the catalog; the broadcast stays up for the late readers until Close + // takes it offline. ACK never controls the linger. + if err := producer.Finish(); err != nil { return err } - defer finished.Close() - linger := finished.Linger() - if linger <= 0 { - return errors.New("finished media has no linger") + fmt.Printf("finish ready linger_us=%d\n", finishLinger.Microseconds()) + select { + case <-time.After(finishLinger): + case <-ctx.Done(): + return ctx.Err() } - fmt.Printf("finish ready linger_us=%d\n", linger.Microseconds()) - if err := finished.Wait(ctx); err != nil { + if err := producer.Close(); err != nil { return err } - if time.Since(started) < linger { - return errors.New("finish wait ended before its linger") - } health, err := client.CreateBroadcast(broadcast + ".health") if err != nil { return err diff --git a/test/interop/clients/js/src/finish.ts b/test/interop/clients/js/src/finish.ts index b80fa18e03a..57c4b99b751 100644 --- a/test/interop/clients/js/src/finish.ts +++ b/test/interop/clients/js/src/finish.ts @@ -1,5 +1,5 @@ // Finite media fixture and finish observations for the existing browser client. -import { Instant, Micro, Milli, Nano, now } from "@moq/clock"; +import { Micro, Milli, Nano, sleep } from "@moq/clock"; import * as Catalog from "@moq/hang/catalog"; import * as Container from "@moq/hang/container"; import * as Moq from "@moq/net"; @@ -7,6 +7,9 @@ import { CatalogProducer } from "@moq/publish"; import { Effect } from "@moq/signals"; import { readFinish } from "../../js-native/finish"; +/** How long the publisher keeps its finished broadcast up for the late readers. */ +const LINGER = Milli(10_000); + interface State { ready: boolean; ended: boolean; @@ -130,14 +133,11 @@ export function finish( ); serving.close(); broadcast.announce(); - const started = now(); - const finishing = broadcast.finish(); - const linger = Nano.fromMilli(finishing.linger); - if (linger <= 0) throw new Error("finished media has no linger"); - state.lingerUs = finishing.linger * 1000; + // Keep the finished broadcast up for the late readers, then take it offline. + state.lingerUs = LINGER * 1000; state.ready = true; - await finishing.wait(); - if (Instant.durationSince(now(), started) < linger) throw new Error("finish wait ended before its linger"); + await sleep(Nano.fromMilli(LINGER)); + broadcast.close(); const health = origin.createBroadcast(Moq.Path.from(`${path}.health`)); const healthTrack = health.createTrack("live"); const group = healthTrack.appendGroup(); diff --git a/test/interop/clients/python/interop.py b/test/interop/clients/python/interop.py index 66b9be77098..81d6bf8ae76 100644 --- a/test/interop/clients/python/interop.py +++ b/test/interop/clients/python/interop.py @@ -27,13 +27,13 @@ import math import struct import sys -import time from datetime import timedelta import moq READ_CHUNK = 64 * 1024 MAX_DELAY = timedelta(seconds=1) # container consumer congestion-control / lookahead window +LINGER = timedelta(seconds=10) # how long a finished publisher stays up for the late readers # Synthetic audio: a 48 kHz tone per channel at 0.5 amplitude, encoded as Opus. AUDIO_TRACK = "tone" @@ -143,16 +143,12 @@ async def publish( audio.finish() media.finish() if finish_ack is not None: - # finish() also finalizes the catalog. ACK never controls the real linger. - started = time.monotonic_ns() - finished = producer.finish() - linger_us = finished.linger // timedelta(microseconds=1) - if linger_us <= 0: - raise RuntimeError("finished media has no linger") - print(f"finish ready linger_us={linger_us}", flush=True) - await finished.wait() - if time.monotonic_ns() - started < linger_us * 1000: - raise RuntimeError("finish wait ended before its linger") + # finish() finalizes the catalog; the broadcast stays up for the late readers until + # close() takes it offline. ACK never controls the linger. + producer.finish() + print(f"finish ready linger_us={LINGER // timedelta(microseconds=1)}", flush=True) + await asyncio.sleep(LINGER.total_seconds()) + producer.close() health = client.create_broadcast(f"{broadcast}.health") live = health.publish_track("live") live.write_frame(b"session-alive") diff --git a/test/interop/interop.sh b/test/interop/interop.sh index 2eecb6bd1cb..7e110ae546b 100755 --- a/test/interop/interop.sh +++ b/test/interop/interop.sh @@ -1001,7 +1001,7 @@ run_publisher() { client_flags "$lang" case "$lang" in rust) - # A finished import stays up for its max-age; `stop_publisher` allows 10 s to close. + # A finished import lingers for late readers; `stop_publisher` interrupts it and allows 10 s to close. # The wire-compat FETCH lanes keep the video-only Annex-B input. if [[ "$AUDIO" -eq 1 ]]; then ffmpeg_fmp4 "$tone" "$(publisher_codecs rust)" | RUST_LOG="$CLI_LOG" "$MOQ" --connect "$url" --connect-version "$(cell_version rust)" \ From ecf492909a02ec24c10283ecaa33cb6fe0b4c45c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 11:31:11 -0700 Subject: [PATCH 05/12] style: format and lint fixes Co-Authored-By: Claude Opus 5.5 --- rs/moq-c/src/publish.rs | 1 - rs/moq-ffi/src/audio.rs | 2 +- rs/moq-net/tests/integration/main.rs | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index 222cee989e2..67d5cddca3f 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -197,7 +197,6 @@ pub struct Publish { /// Group requests delivered to a handler, freed on accept, abort, or free. group_request: NonZeroSlab, - } impl Publish { diff --git a/rs/moq-ffi/src/audio.rs b/rs/moq-ffi/src/audio.rs index fb678b709b0..881c92ddf4f 100644 --- a/rs/moq-ffi/src/audio.rs +++ b/rs/moq-ffi/src/audio.rs @@ -761,7 +761,7 @@ mod tests { }) .unwrap(); } - let _finished = broadcast.finish().unwrap(); + broadcast.finish().unwrap(); for index in 0..4 { let mut track = reader .track(&format!("audio-{index}")) diff --git a/rs/moq-net/tests/integration/main.rs b/rs/moq-net/tests/integration/main.rs index 4fabab8afd5..0949ee9b124 100644 --- a/rs/moq-net/tests/integration/main.rs +++ b/rs/moq-net/tests/integration/main.rs @@ -45,8 +45,8 @@ mod quiet_catalog; mod range_anchors; mod received_rewind; mod refresh; -mod relay_upstream_close; mod rejoin; +mod relay_upstream_close; mod replacement; mod request_caps; mod restart; From 1d77bc96fdf346a8609ea102f547ddc41bbcb3b9 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 11:36:07 -0700 Subject: [PATCH 06/12] test: a failed finish leaves the broadcast for its close Co-Authored-By: Claude Opus 5.5 --- rs/moq-c/src/publish.rs | 5 ++++- rs/moq-ffi/src/origin.rs | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index 67d5cddca3f..a7ed686913f 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -1122,7 +1122,7 @@ mod supervision_tests { } #[tokio::test] - async fn a_finish_after_a_driver_panic_closes_the_broadcast() { + async fn a_finish_after_a_driver_panic_reports_it_until_the_close() { let (origin, completion, trigger) = crate::ffi::panicking_origin(); let mut publish = Publish::default(); let broadcast = publish @@ -1137,6 +1137,9 @@ mod supervision_tests { .unwrap_or_else(|_| unreachable!("test keeps its panic trigger open")) = true; assert!(matches!(completion.finished().await, Err(Error::Panic))); assert!(matches!(publish.finish(broadcast), Err(Error::Panic))); + // The handle stays the caller's to close, and the close still ends the broadcast. + assert!(!consumer.is_closed()); + assert!(matches!(publish.close(broadcast), Err(Error::Panic))); assert!(consumer.is_closed()); } } diff --git a/rs/moq-ffi/src/origin.rs b/rs/moq-ffi/src/origin.rs index 66ece34585a..49648042036 100644 --- a/rs/moq-ffi/src/origin.rs +++ b/rs/moq-ffi/src/origin.rs @@ -697,7 +697,7 @@ mod supervision_tests { } #[tokio::test] - async fn a_finish_after_a_driver_panic_closes_the_broadcast() { + async fn a_finish_after_a_driver_panic_reports_it_until_the_close() { let (inner, completion, trigger) = crate::ffi::panicking_origin(); let origin = MoqOriginProducer::from_inner(Origin { inner, @@ -712,6 +712,9 @@ mod supervision_tests { .unwrap_or_else(|_| unreachable!("test keeps its panic trigger open")) = true; assert!(matches!(completion.finished().await, Err(MoqError::Task { .. }))); assert!(matches!(broadcast.finish(), Err(MoqError::Task { .. }))); + // The handle stays the caller's to close, and the close still ends the broadcast. + assert!(!consumer.is_closed()); + assert!(matches!(broadcast.close(), Err(MoqError::Task { .. }))); assert!(consumer.is_closed()); } From 6d42b6945d687127fed7edf82db381ac72892acd Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 11:58:08 -0700 Subject: [PATCH 07/12] docs: moq_publish_finish keeps its released signature but no longer closes The moq-c MIGRATE entry still said moq_publish_finish was removed, but it is back with the released signature and finishes only the catalog, so a release caller compiles and never releases the broadcast. Also capitalize the binding docs' new sentence. Co-Authored-By: Claude Opus 5.5 --- doc/lib/c/index.md | 2 +- doc/lib/dart/index.md | 2 +- doc/lib/go/index.md | 2 +- doc/lib/kt/index.md | 2 +- doc/lib/py/index.md | 2 +- doc/lib/swift/index.md | 2 +- rs/moq-c/MIGRATE.md | 5 +++-- 7 files changed, 9 insertions(+), 8 deletions(-) diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index 74330c51d62..86ee5697a0c 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -67,7 +67,7 @@ inside. The header is the reference: each function carries a doc comment. - **Compressed tracks.** `moq_track_info.compress` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. `@moq/net` cannot read a compressed track yet. - **fMP4 import.** `MOQ_CONTAINER_FORMAT_FMP4` splits each fragment into one frame per sample; `MOQ_CONTAINER_FORMAT_CMAF` republishes it whole. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `moq_publish_media_cut`: after every frame, or at a segment cadence to align with video. -- **Ending cleanly.** When the input ends, finish every track, then call `moq_publish_finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `moq_publish_close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `moq_publish_finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `moq_publish_close()` takes it offline. How long to keep it up is yours to decide. - **Timeline breaks.** On a seek or pause, call `moq_publish_media_discontinuity`, then keep timestamps moving forward and resume video on a keyframe. - **JSON values.** `moq_consume_json_value` fills `moq_json_value` with the document and its frame's `timestamp_us`, rounded down to a whole microsecond; `timestamp_present` is false on an untimed track. A snapshot consumer's callback fires for each state in order, but a group superseded before it is read is skipped. - **Decoded frames hold decoder buffers.** Free each frame id with `moq_decode_video_frame_free` promptly, or the decoder stalls. diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 0935e905249..3b2797bdce6 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -142,7 +142,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `dispose()` each frame from a `video.Consumer` promptly rather than waiting for the garbage collector, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `await moq.close()` drains for up to one second and reports its result. `session.shutdown()` requests the drain synchronously; `await session.closed()` waits for its result. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Awaiting cancellation of an announcement, grant, or request subscription releases its pending native read. Announcements also release their cursor; authorization and server listeners leave their shared owner usable. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), listen to `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. `await auth().add(token: ...)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index 23768688ae6..d396877f106 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -132,7 +132,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `Discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `Close` each `VideoDecodedFrame` promptly, or the decoder stalls. `Resize` is best effort, so read each frame's `Width()` and `Height()`. - **Closing.** `client.Close()` drains for up to one second and returns an error on failure. `session.Shutdown()` requests that drain immediately; `session.Closed(ctx)` waits for its result, and `session.Cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.Finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.Close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.Finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.Close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`). A field is nil when the transport does not report it, which is not the same as zero. `Version` names the negotiated protocol. `Dial` returns a connecting session; read `Session().State()` and wait with `StateChanged(ctx, state.Revision)` to observe first-dial failures and reconnects. Hold the owned `BandwidthConsumer` returned by `Session().RecvBandwidth()` to receive bandwidth estimates. `Rate()` reads the current estimate in bits per second and `RateChanged(ctx)` waits for a new one. Calling `Close()` on the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig.Versions`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `Session().Auth().Grant()` is the `Grant` the relay sent back, nil until it answers and while a client session reconnects; `GrantChanged(ctx)` waits for the next one. `Add(ctx, token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `Close()`, and is presented again on every reconnect. A refusal returns the relay's code. - **Errors.** Read diagnostic payloads from `Reason` and structured protocol failures from `Details`. diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index a98c1af42ba..5e7a8e23349 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `close()` each frame from a `dev.moq.video.Consumer` promptly (or `use { }` it), or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `moq.shutdown()` requests a drain immediately; suspending `moq.session.closed()` waits up to one second and reports its result. `Moq.close()`, and so `use { }`, cancels at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.end()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.end()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), collect `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. Suspending `auth().add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 79081cb4b7a..0f50adba2a2 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -116,7 +116,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Drop each frame from a `moq.video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `session.shutdown()` requests a drain immediately; `await session.closed()` waits up to one second and reports its result. `cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rtt`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). A field is `None` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recv_bandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rate_changed()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `None` until it answers and while a client session reconnects; `await auth.grant_changed()` waits for the next one. `await auth.add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal raises with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index c94223f65d0..368aa893ec8 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Release each frame from a `Video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `session.shutdown()` requests a drain immediately; `try await session.closed()` waits up to one second and reports its result. `session.cancel(code:)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `try broadcast.finish()` to finish the catalog. the broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `try broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `nil` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `nil` until it answers and while a client session reconnects; `try await auth.grantChanged()` waits for the next one. `try await auth.add(token:)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Diagnostic cases use the `reason:` argument label; match their associated value to inspect it. Protocol errors carry `details`. diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index 89e475006f6..491a88ac7bd 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -196,9 +196,10 @@ if (frame.timestamp_present) use(frame.timestamp_us); `moq_route.cold` and `has_cold` are removed; drop them. -### `moq_publish_finish` is removed (#4152) +### `moq_publish_finish` no longer closes (#4152) -Close the broadcast with `moq_publish_close`. +`moq_publish_finish(broadcast)` was a deprecated alias for `moq_publish_close`; it now finishes only the catalog and leaves the handle valid, so the broadcast stays up until `moq_publish_close`. +Call `moq_publish_close` where you called `moq_publish_finish`, or the broadcast and its handle are never released. ### A decoded frame can fail on its own (#4094) From 26b3737210298dab51718115186fb41416a24a42 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 17:05:12 -0700 Subject: [PATCH 08/12] test: follow main's with_range rename in relay_upstream_close Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/tests/integration/relay_upstream_close.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rs/moq-net/tests/integration/relay_upstream_close.rs b/rs/moq-net/tests/integration/relay_upstream_close.rs index 8cd84b1f37a..ee3096ca8dd 100644 --- a/rs/moq-net/tests/integration/relay_upstream_close.rs +++ b/rs/moq-net/tests/integration/relay_upstream_close.rs @@ -90,7 +90,7 @@ async fn round(name: &str, end: End) -> (Vec<(u64, u64)>, Result<(), Error>) { let (ready, active) = futures::channel::oneshot::channel(); let reader = moq_clock::sim::spawn(async move { - let subscription = Subscription::default().with_max_delay(MAX_DELAY).with_groups(0..); + let subscription = Subscription::default().with_max_delay(MAX_DELAY).with_range(0..); let mut sub = remote .track("video") .unwrap() From 3b49ef304f7c0b53aa1af2494802ad879ad78867 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 17:17:54 -0700 Subject: [PATCH 09/12] feat(ffi,c)!: finish the catalog through its own handle moq_publish_finish keeps the released signature of the old moq_publish_close alias, so a release caller compiled against the catalog-only finish and never released its broadcast. It is now moq_publish_catalog_finish, mirrored by MoqMediaCatalogProducer::finish and CatalogProducer.finish in every binding, and BroadcastProducer.finish is gone, so release callers fail to build. Co-Authored-By: Claude Opus 5.5 --- cpp/moq/test/probe.cpp | 7 +-- dart/moq/MIGRATE.md | 5 +- dart/moq/test/moq_test.dart | 7 +-- dart/moq_ffi/lib/src/moq.dart | 49 ++++++++++--------- doc/lib/c/index.md | 2 +- doc/lib/cpp/index.md | 9 ++-- doc/lib/dart/index.md | 2 +- doc/lib/go/index.md | 2 +- doc/lib/kt/index.md | 2 +- doc/lib/py/index.md | 2 +- doc/lib/swift/index.md | 2 +- go/wrapper/MIGRATE.md | 5 +- go/wrapper/media/media.go | 7 +++ go/wrapper/moq_test.go | 12 +++-- go/wrapper/publish.go | 9 ---- kt/moq/MIGRATE.md | 5 +- .../kotlin/dev/moq/SmokeTest.kt | 7 +-- py/moq-rs/MIGRATE.md | 5 +- py/moq-rs/moq/media.py | 9 ++++ py/moq-rs/moq/publish.py | 9 ---- py/moq-rs/tests/test_local.py | 2 +- quest/m1/listing-clean-end.md | 6 +-- rs/moq-c/MIGRATE.md | 6 +-- rs/moq-c/src/api.rs | 6 +-- rs/moq-c/src/publish.rs | 6 +-- rs/moq-c/src/test.rs | 2 +- rs/moq-ffi/MIGRATE.md | 5 +- rs/moq-ffi/src/audio.rs | 2 +- rs/moq-ffi/src/media.rs | 14 ++++++ rs/moq-ffi/src/origin.rs | 3 +- rs/moq-ffi/src/producer.rs | 17 +------ rs/moq-ffi/src/test.rs | 5 +- swift/MIGRATE.md | 5 +- swift/Sources/Moq/Broadcast.swift | 9 ---- swift/Sources/Moq/Media.swift | 6 +++ swift/Tests/MoqTests/SmokeTests.swift | 7 +-- test/interop/clients/cpp/main.cpp | 6 +-- test/interop/clients/go/main.go | 6 +-- test/interop/clients/python/interop.py | 6 +-- 39 files changed, 143 insertions(+), 133 deletions(-) diff --git a/cpp/moq/test/probe.cpp b/cpp/moq/test/probe.cpp index ea36f64d86c..027d0b25b50 100644 --- a/cpp/moq/test/probe.cpp +++ b/cpp/moq/test/probe.cpp @@ -172,13 +172,14 @@ int main() { CHECK(!moq::MediaTimebase::init(timebase_owner)); ok(timebase_other->close(), "close timebase other"); - // A finished broadcast stays up, still serving its finished tracks, until it closes. + // A finished catalog leaves the broadcast up, still serving its finished tracks, until it closes. auto finished = ok(moq::BroadcastProducer::init(), "finished broadcast"); + auto finished_catalog = ok(moq::MediaCatalogProducer::init(finished), "finished catalog"); ok(ok(finished->publish_track("status", {}), "publish track")->finish(), "finish track"); - ok(finished->finish(), "broadcast finish"); + ok(finished_catalog->finish(), "catalog finish"); ok(finished->consume(), "consume a finished broadcast"); ok(finished->close(), "close finished broadcast"); - CHECK(!finished->finish()); + CHECK(!finished_catalog->finish()); // A synchronous error is a returned value, not an exception. auto unbound = ok(moq::Server::init({}), "server init"); diff --git a/dart/moq/MIGRATE.md b/dart/moq/MIGRATE.md index e9bc81ec5cb..b20e5bbafb8 100644 --- a/dart/moq/MIGRATE.md +++ b/dart/moq/MIGRATE.md @@ -46,10 +46,11 @@ Where you skipped such a rendition on that error, bound the call yourself: add a Audio and video init records no longer carry a track name. Pass that name on the media producer's named target instead; init records describe only the codec and media. -### Broadcast `finish` no longer closes +### Broadcast `finish` is removed -`BroadcastProducer.finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. +`BroadcastProducer.finish()`, a deprecated alias for `close()`, is removed. Call `BroadcastProducer.close()` where you called `finish()`. +To end the content first, call `CatalogProducer.finish()`; the broadcast stays up until `close()`. ### JSON snapshot `deltaRatio` is `deltas` diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index c92471bfa40..e6d674a2a76 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -385,14 +385,15 @@ void main() { second.close(); }); - test('a finished broadcast stays up until closed', () { + test('a finished catalog leaves the broadcast up until closed', () { final broadcast = BroadcastProducer(); + final catalog = moq_media.CatalogProducer(broadcast: broadcast); broadcast.publishTrack(name: 'status', info: null).finish(); - broadcast.finish(); + catalog.finish(); // Finishing the content leaves the broadcast up until it closes. broadcast.consume(); broadcast.close(); - expect(() => broadcast.finish(), throwsA(isA())); + expect(() => catalog.finish(), throwsA(isA())); }); test('microsecond fields read back as Durations', () { diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index fe68f9b5149..31ae7d5d07e 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -10537,6 +10537,7 @@ class FfiConverterMoqMediaCatalogConsumer { } abstract class MoqMediaCatalogProducerInterface { + void finish(); int now(); void removeSection({required String name}); void setSection({required String name, required String json}); @@ -10588,6 +10589,15 @@ class MoqMediaCatalogProducer implements MoqMediaCatalogProducerInterface { ); } + void finish() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqmediacatalogproducer_finish( + uniffiClonePointer(), + status, + ); + }, moqExceptionErrorHandler); + } + int now() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqmediacatalogproducer_now( @@ -12138,7 +12148,6 @@ abstract class MoqBroadcastProducerInterface { void close(); MoqBroadcastConsumer consume(); MoqBroadcastDynamic dynamic_(); - void finish(); MoqTrackProducer publishTrack({ required String name, required MoqTrackInfo? info, @@ -12230,15 +12239,6 @@ class MoqBroadcastProducer implements MoqBroadcastProducerInterface { ); } - void finish() { - return rustCall((status) { - uniffi_moq_ffi_fn_method_moqbroadcastproducer_finish( - uniffiClonePointer(), - status, - ); - }, moqExceptionErrorHandler); - } - MoqTrackProducer publishTrack({ required String name, required MoqTrackInfo? info, @@ -17521,6 +17521,14 @@ uniffi_moq_ffi_fn_constructor_moqmediacatalogproducer_new( Pointer uniffiStatus, ); +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqmediacatalogproducer_finish( + Pointer ptr, + Pointer uniffiStatus, +); + @Native, Pointer)>( assetId: _uniffiAssetId, ) @@ -18232,14 +18240,6 @@ external Pointer uniffi_moq_ffi_fn_method_moqbroadcastproducer_dynamic( Pointer uniffiStatus, ); -@Native, Pointer)>( - assetId: _uniffiAssetId, -) -external void uniffi_moq_ffi_fn_method_moqbroadcastproducer_finish( - Pointer ptr, - Pointer uniffiStatus, -); - @Native< Pointer Function( Pointer, @@ -19711,6 +19711,9 @@ external int uniffi_moq_ffi_checksum_method_moqmediacatalogconsumer_cancel(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqmediacatalogconsumer_next(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqmediacatalogproducer_finish(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqmediacatalogproducer_now(); @@ -19857,9 +19860,6 @@ external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_consume(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_dynamic(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_finish(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_publish_track(); @@ -20431,6 +20431,10 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqmediacatalogconsumer_next() != 43296) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqmediacatalogproducer_finish() != + 62353) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqmediacatalogproducer_now() != 14140) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -20584,9 +20588,6 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_dynamic() != 55635) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_finish() != 57551) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_publish_track() != 44452) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index f3dbd6f0037..4174047f9c0 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -67,7 +67,7 @@ inside. The header is the reference: each function carries a doc comment. - **Compressed tracks.** `moq_track_info.compress` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. `@moq/net` cannot read a compressed track yet. - **fMP4 import.** `MOQ_CONTAINER_FORMAT_FMP4` splits each fragment into one frame per sample. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `moq_publish_media_cut`: after every frame, or at a segment cadence to align with video. -- **Ending cleanly.** When the input ends, finish every track, then call `moq_publish_finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `moq_publish_close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `moq_publish_catalog_finish()` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `moq_publish_close()` takes it offline. How long to keep it up is yours to decide. - **Timeline breaks.** On a seek or pause, call `moq_publish_media_discontinuity`, then keep timestamps moving forward and resume video on a keyframe. - **JSON values.** `moq_consume_json_value` fills `moq_json_value` with the document and its frame's `timestamp_us`, rounded down to a whole microsecond; `timestamp_present` is false on an untimed track. A snapshot consumer's callback fires for each state in order, but a group superseded before it is read is skipped. - **Decoded frames hold decoder buffers.** Free each frame id with `moq_decode_video_frame_free` promptly, or the decoder stalls. diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index f2d033601d0..d26680b96e6 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -218,10 +218,11 @@ Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. Finish or abort live tracks first. -To end a broadcast cleanly, finish every track, then call `broadcast->finish()` -to finish the catalog. The broadcast stays announced and keeps serving the -finished tracks, so a subscriber still catching up can drain them, until -`broadcast->close()` takes it offline. How long to keep it up is yours to decide. +To end a broadcast cleanly, finish every track, then call `catalog->finish()` on +its `moq::MediaCatalogProducer` to finish the catalog, which ends the content. +The broadcast stays announced and keeps serving the finished tracks, so a +subscriber still catching up can drain them, until `broadcast->close()` takes it +offline. How long to keep it up is yours to decide. `moq::shutdown()` stops the `moq-ffi` runtime workers, then the executor. Pending calls resolve `Cancelled`, and every object stays safe to drop. Call diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 0d83263163a..f9aafe9df3b 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -142,7 +142,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `dispose()` each frame from a `video.Consumer` promptly rather than waiting for the garbage collector, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `await moq.close()` drains for up to one second and reports its result. `session.shutdown()` requests the drain synchronously; `await session.closed()` waits for its result. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Awaiting cancellation of an announcement, grant, or request subscription releases its pending native read. Announcements also release their cursor; authorization and server listeners leave their shared owner usable. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `finish()` on its `CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), listen to `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. `await auth().add(token: ...)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index 7d561a4b9df..703a20b27c7 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -132,7 +132,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `Discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `Close` each `VideoDecodedFrame` promptly, or the decoder stalls. `Resize` is best effort, so read each frame's `Width()` and `Height()`. - **Closing.** `client.Close()` drains for up to one second and returns an error on failure. `session.Shutdown()` requests that drain immediately; `session.Closed(ctx)` waits for its result, and `session.Cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.Finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.Close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `Finish()` on its `media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.Close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`). A field is nil when the transport does not report it, which is not the same as zero. `Version` names the negotiated protocol. `Dial` returns a connecting session; read `Session().State()` and wait with `StateChanged(ctx, state.Revision)` to observe first-dial failures and reconnects. Hold the owned `BandwidthConsumer` returned by `Session().RecvBandwidth()` to receive bandwidth estimates. `Rate()` reads the current estimate in bits per second and `RateChanged(ctx)` waits for a new one. Calling `Close()` on the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig.Versions`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `Session().Auth().Grant()` is the `Grant` the relay sent back, nil until it answers and while a client session reconnects; `GrantChanged(ctx)` waits for the next one. `Add(ctx, token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `Close()`, and is presented again on every reconnect. A refusal returns the relay's code. - **Errors.** Read diagnostic payloads from `Reason` and structured protocol failures from `Details`. diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index 8a2e7a3c4b5..781f0fb57f7 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `close()` each frame from a `dev.moq.video.Consumer` promptly (or `use { }` it), or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `moq.shutdown()` requests a drain immediately; suspending `moq.session.closed()` waits up to one second and reports its result. `Moq.close()`, and so `use { }`, cancels at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.end()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `finish()` on its `CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.end()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), collect `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. Suspending `auth().add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 43726941f16..1799e4881d2 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -116,7 +116,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Drop each frame from a `moq.video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `session.shutdown()` requests a drain immediately; `await session.closed()` waits up to one second and reports its result. `cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `finish()` on its `moq.media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rtt`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). A field is `None` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recv_bandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rate_changed()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `None` until it answers and while a client session reconnects; `await auth.grant_changed()` waits for the next one. `await auth.add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal raises with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index 937ff132165..b237f59c900 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Release each frame from a `Video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `session.shutdown()` requests a drain immediately; `try await session.closed()` waits up to one second and reports its result. `session.cancel(code:)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. -- **Ending cleanly.** When the input ends, finish every track, then call `try broadcast.finish()` to finish the catalog. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. +- **Ending cleanly.** When the input ends, finish every track, then call `try finish()` on its `Media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `nil` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `nil` until it answers and while a client session reconnects; `try await auth.grantChanged()` waits for the next one. `try await auth.add(token:)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Diagnostic cases use the `reason:` argument label; match their associated value to inspect it. Protocol errors carry `details`. diff --git a/go/wrapper/MIGRATE.md b/go/wrapper/MIGRATE.md index 6cbcea60adc..c1f214e6a81 100644 --- a/go/wrapper/MIGRATE.md +++ b/go/wrapper/MIGRATE.md @@ -39,10 +39,11 @@ Call `Session.Closed(ctx)` to wait for the drain and receive delivery failures, Audio and video init records no longer carry a track name. Pass that name on the media producer's named target instead; init records describe only the codec and media. -### Broadcast `Finish` no longer closes +### Broadcast `Finish` is removed -`BroadcastProducer.Finish()` was a deprecated alias for `Close()`; it now finishes only the catalog, and the broadcast stays up until `Close()`. +`BroadcastProducer.Finish()`, a deprecated alias for `Close()`, is removed. Call `BroadcastProducer.Close()` where you called `Finish()`. +To end the content first, call `media.CatalogProducer.Finish()`; the broadcast stays up until `Close()`. ### JSON snapshot `DeltaRatio` is `Deltas` diff --git a/go/wrapper/media/media.go b/go/wrapper/media/media.go index 15f41c52e50..47213957588 100644 --- a/go/wrapper/media/media.go +++ b/go/wrapper/media/media.go @@ -158,6 +158,13 @@ func (c *CatalogProducer) SetSection(name string, value any) error { // RemoveSection removes an application catalog section if present. func (c *CatalogProducer) RemoveSection(name string) error { return c.inner.RemoveSection(name) } +// Finish finishes the catalog, which ends the broadcast's content. +// +// Finish every track first. The broadcast stays announced and keeps serving its +// finished tracks to late subscribers until [moq.BroadcastProducer.Close] takes it +// offline; how long to keep it up is yours to decide. +func (c *CatalogProducer) Finish() error { return c.inner.Finish() } + // NewAudioTrackProducer imports encoded audio frames on target. func NewAudioTrackProducer(broadcast *moq.BroadcastProducer, target Target, init AudioInit) (*TrackProducer, error) { resolved, err := targetFFI(target) diff --git a/go/wrapper/moq_test.go b/go/wrapper/moq_test.go index 71e243ced9a..a99fdd267c6 100644 --- a/go/wrapper/moq_test.go +++ b/go/wrapper/moq_test.go @@ -143,11 +143,15 @@ func TestPublishAudioLifecycle(t *testing.T) { } } -func TestBroadcastFinishThenClose(t *testing.T) { +func TestCatalogFinishThenClose(t *testing.T) { broadcast, err := moq.NewBroadcastProducer() if err != nil { t.Fatal(err) } + catalog, err := moqmedia.NewCatalogProducer(broadcast) + if err != nil { + t.Fatal(err) + } track, err := broadcast.PublishTrack("status", nil) if err != nil { t.Fatal(err) @@ -155,7 +159,7 @@ func TestBroadcastFinishThenClose(t *testing.T) { if err := track.Finish(); err != nil { t.Fatal(err) } - if err := broadcast.Finish(); err != nil { + if err := catalog.Finish(); err != nil { t.Fatal(err) } // Finishing the content leaves the broadcast up until it closes. @@ -165,8 +169,8 @@ func TestBroadcastFinishThenClose(t *testing.T) { if err := broadcast.Close(); err != nil { t.Fatal(err) } - if err := broadcast.Finish(); !errors.Is(err, moq.ErrClosed) { - t.Fatalf("Finish after Close = %v, want closed", err) + if err := catalog.Finish(); !errors.Is(err, moq.ErrClosed) { + t.Fatalf("catalog Finish after Close = %v, want closed", err) } } diff --git a/go/wrapper/publish.go b/go/wrapper/publish.go index c6769c080e8..3afb73d6911 100644 --- a/go/wrapper/publish.go +++ b/go/wrapper/publish.go @@ -79,15 +79,6 @@ func (b *BroadcastProducer) Close() error { return b.inner.Close() } -// Finish ends the broadcast's content by finishing its catalog. -// -// Finish every track first. The broadcast stays announced and keeps serving its -// finished tracks to late subscribers until [BroadcastProducer.Close] takes it -// offline; how long to keep it up is yours to decide. -func (b *BroadcastProducer) Finish() error { - return b.inner.Finish() -} - // BroadcastDynamic is a stream of subscriber-requested tracks. type BroadcastDynamic struct { inner *ffi.MoqBroadcastDynamic diff --git a/kt/moq/MIGRATE.md b/kt/moq/MIGRATE.md index 2f3d510de48..c42780b3615 100644 --- a/kt/moq/MIGRATE.md +++ b/kt/moq/MIGRATE.md @@ -40,10 +40,11 @@ If you adopted the release line's async `drain()`, call `shutdown()` and then aw Audio and video init records no longer carry a track name. Pass that name on the media producer's named target instead; init records describe only the codec and media. -### Broadcast `finish` no longer closes +### Broadcast `finish` is removed -`BroadcastProducer.finish()` was a deprecated alias for `end()`; it now finishes only the catalog, and the broadcast stays up until `end()`. +`BroadcastProducer.finish()`, a deprecated alias for `end()`, is removed. Call `BroadcastProducer.end()` where you called `finish()`. +To end the content first, call `CatalogProducer.finish()`; the broadcast stays up until `end()`. ### JSON snapshot `deltaRatio` is `deltas` diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index 9df63a3dd6b..e9d7321f5d5 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -242,14 +242,15 @@ class SmokeTest { } @Test - fun `a finished broadcast stays up until it ends`() { + fun `a finished catalog leaves the broadcast up until it ends`() { BroadcastProducer().use { broadcast -> + val catalog = CatalogProducer(broadcast) broadcast.publishTrack("status", null).finish() - broadcast.finish() + catalog.finish() // Finishing the content leaves the broadcast up until it ends. broadcast.consume().close() broadcast.end() - assertFailsWith { broadcast.finish() } + assertFailsWith { catalog.finish() } } } diff --git a/py/moq-rs/MIGRATE.md b/py/moq-rs/MIGRATE.md index a946a10c8a9..1ce345d17f7 100644 --- a/py/moq-rs/MIGRATE.md +++ b/py/moq-rs/MIGRATE.md @@ -40,10 +40,11 @@ If you adopted the release line's async `drain()`, call `session.shutdown()` and Audio and video init records no longer carry a track name. Pass that name on the media producer's named target instead; init records describe only the codec and media. -### Broadcast `finish` no longer closes +### Broadcast `finish` is removed -`BroadcastProducer.finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. +`BroadcastProducer.finish()`, a deprecated alias for `close()`, is removed. Call `BroadcastProducer.close()` where you called `finish()`. +To end the content first, call `moq.media.CatalogProducer.finish()`; the broadcast stays up until `close()`. ### JSON snapshot `delta_ratio` is `deltas` diff --git a/py/moq-rs/moq/media.py b/py/moq-rs/moq/media.py index 49398cebe43..f7385003264 100644 --- a/py/moq-rs/moq/media.py +++ b/py/moq-rs/moq/media.py @@ -137,6 +137,15 @@ def remove_section(self, name: str) -> None: """Remove an application catalog section if present.""" self._inner.remove_section(name) + def finish(self) -> None: + """Finish the catalog, which ends the broadcast's content. + + Finish every track first. The broadcast stays announced and keeps serving its + finished tracks to late subscribers until its ``close`` takes it offline; how long + to keep it up is yours to decide. + """ + self._inner.finish() + class TrackProducer: """Publish encoded media frames on a single track, one payload at a time. diff --git a/py/moq-rs/moq/publish.py b/py/moq-rs/moq/publish.py index 597f558259a..34476c454eb 100644 --- a/py/moq-rs/moq/publish.py +++ b/py/moq-rs/moq/publish.py @@ -362,12 +362,3 @@ def close(self) -> None: Tracks already subscribed carry on to their own end. Closing again is a no-op. """ self._inner.close() - - def finish(self) -> None: - """End the broadcast's content by finishing its catalog. - - Finish every track first. The broadcast stays announced and keeps serving its - finished tracks to late subscribers until :meth:`close` takes it offline; how long - to keep it up is yours to decide. - """ - self._inner.finish() diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index 1ae50dcf1b0..0f1ec0a5543 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -416,7 +416,7 @@ async def test_finish_serves_until_closed(): track = broadcast.publish_track("status") track.write_frame(b"tail") track.finish() - broadcast.finish() + moq.media.CatalogProducer(broadcast).finish() # A late subscriber still drains the finished track while the broadcast is up. late = await consumer.request_broadcast("finish") diff --git a/quest/m1/listing-clean-end.md b/quest/m1/listing-clean-end.md index 78a4d012265..886dfe8b6cf 100644 --- a/quest/m1/listing-clean-end.md +++ b/quest/m1/listing-clean-end.md @@ -2,8 +2,7 @@ ## Goal -When a broadcast ends right after its tracks finish, by `close()` or by a -clean `finish()`, each IETF SUBSCRIBE_TRACKS PUBLISH for a finished track +When a broadcast closes right after its tracks finish, each IETF SUBSCRIBE_TRACKS PUBLISH for a finished track ends with TRACK_ENDED, not INTERNAL_ERROR, in Rust and JS. A track left unfinished still ends in error. @@ -26,9 +25,6 @@ Why a "finished cleanly" check on the PUBLISH's track handle can't work: source listing's end it drops the reader (`rs/moq-net/src/model/origin.rs`, the `Step::Listed` `Ok(None)` arm, around lines 3966-3973), and the source's queued `Finished` is lost. -- `broadcast.finish()` is no better: a finished track is listed while held, - and the listing closes before the holds drop, so no `Finished` is queued at - all. Open design (maintainer to decide): diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index 491a88ac7bd..27fed02ed2a 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -196,10 +196,10 @@ if (frame.timestamp_present) use(frame.timestamp_us); `moq_route.cold` and `has_cold` are removed; drop them. -### `moq_publish_finish` no longer closes (#4152) +### `moq_publish_finish` is removed (#4152) -`moq_publish_finish(broadcast)` was a deprecated alias for `moq_publish_close`; it now finishes only the catalog and leaves the handle valid, so the broadcast stays up until `moq_publish_close`. -Call `moq_publish_close` where you called `moq_publish_finish`, or the broadcast and its handle are never released. +Close the broadcast with `moq_publish_close`. +To end its content first, call `moq_publish_catalog_finish`; the broadcast stays up until `moq_publish_close`. ### A decoded frame can fail on its own (#4094) diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 028ff5f5763..638a412ca7a 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -2189,7 +2189,7 @@ pub extern "C" fn moq_publish_close(broadcast: u32) -> i32 { }) } -/// End a broadcast's content by finishing its catalog. +/// Finish a broadcast's catalog, which ends its content. /// /// Finish every track first. The broadcast stays announced and keeps serving its finished /// tracks, so a subscriber that arrives late can still read them, until [moq_publish_close] @@ -2197,10 +2197,10 @@ pub extern "C" fn moq_publish_close(broadcast: u32) -> i32 { /// /// Returns a zero on success, or a negative code on failure. #[unsafe(no_mangle)] -pub extern "C" fn moq_publish_finish(broadcast: u32) -> i32 { +pub extern "C" fn moq_publish_catalog_finish(broadcast: u32) -> i32 { ffi::enter(move || { let broadcast = ffi::parse_id(broadcast)?; - State::lock().publish.finish(broadcast) + State::lock().publish.catalog_finish(broadcast) }) } diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index 1fa6cbf7671..aac4d2e2c0e 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -60,7 +60,7 @@ struct Broadcast { video: BTreeMap, audio: BTreeMap, finished: Finished, - /// Set by [`Publish::finish`]: the catalog is final, so a close leaves it alone. + /// Set by [`Publish::catalog_finish`]: the catalog is final, so a close leaves it alone. ended: bool, } @@ -321,7 +321,7 @@ impl Publish { /// End the broadcast's content by finishing its catalog, with its entries still listed, so /// a late subscriber finds the finished tracks until [`Self::close`]. - pub fn finish(&mut self, broadcast: Id) -> Result<(), Error> { + pub fn catalog_finish(&mut self, broadcast: Id) -> Result<(), Error> { let broadcast = self.broadcast_mut(broadcast)?; let result = broadcast.catalog.finish(); broadcast.ended |= result.is_ok(); @@ -1183,7 +1183,7 @@ mod supervision_tests { .write() .unwrap_or_else(|_| unreachable!("test keeps its panic trigger open")) = true; assert!(matches!(completion.finished().await, Err(Error::Panic))); - assert!(matches!(publish.finish(broadcast), Err(Error::Panic))); + assert!(matches!(publish.catalog_finish(broadcast), Err(Error::Panic))); // The handle stays the caller's to close, and the close still ends the broadcast. assert!(!consumer.is_closed()); assert!(matches!(publish.close(broadcast), Err(Error::Panic))); diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 38c288660ec..825e714606f 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -2349,7 +2349,7 @@ fn publish_finish_serves_finished_tracks_until_closed() { ); assert_eq!(moq_publish_media_finish(media), 0); - assert_eq!(moq_publish_finish(broadcast), 0); + assert_eq!(moq_publish_catalog_finish(broadcast), 0); let consume = request_broadcast(origin, path); let frame_cb = Callback::new(); diff --git a/rs/moq-ffi/MIGRATE.md b/rs/moq-ffi/MIGRATE.md index 52cf15af8e8..056aa8a1fe4 100644 --- a/rs/moq-ffi/MIGRATE.md +++ b/rs/moq-ffi/MIGRATE.md @@ -46,10 +46,11 @@ If you adopted the release line's async `drain()`, call `shutdown()` and then aw `MoqAudioInit::track` and `MoqVideoInit::track` are removed. Pass that name through `MoqMediaTarget::Named { name }` when constructing `MoqMediaTrackProducer::audio` or `video`; init records describe the codec and media only. -### Broadcast `finish` no longer closes +### Broadcast `finish` is removed -`MoqBroadcastProducer::finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. +`MoqBroadcastProducer::finish()`, a deprecated alias for `close()`, is removed. Call `MoqBroadcastProducer::close()` where you called `finish()`. +To end the content first, call `MoqMediaCatalogProducer::finish()`; the broadcast stays up until `close()`. ### JSON snapshot `delta_ratio` is `deltas` diff --git a/rs/moq-ffi/src/audio.rs b/rs/moq-ffi/src/audio.rs index 881c92ddf4f..84c4bbc4f1f 100644 --- a/rs/moq-ffi/src/audio.rs +++ b/rs/moq-ffi/src/audio.rs @@ -761,7 +761,7 @@ mod tests { }) .unwrap(); } - broadcast.finish().unwrap(); + catalog.finish().unwrap(); for index in 0..4 { let mut track = reader .track(&format!("audio-{index}")) diff --git a/rs/moq-ffi/src/media.rs b/rs/moq-ffi/src/media.rs index c5c92b3c0a3..bcada5ecd56 100644 --- a/rs/moq-ffi/src/media.rs +++ b/rs/moq-ffi/src/media.rs @@ -777,6 +777,20 @@ impl MoqMediaCatalogProducer { Ok(()) }) } + + /// Finish the catalog, which ends the broadcast's content. + /// + /// Finish every track first. The broadcast stays announced and keeps serving its finished + /// tracks, so a subscriber that arrives late can still read them, until the broadcast's + /// `close` takes it offline. How long to keep it up is yours to decide. + pub fn finish(&self) -> Result<(), MoqError> { + let _guard = crate::ffi::enter(); + self.broadcast.upgrade().ok_or(MoqError::Closed)?.with_state(|state| { + state.catalog.finish()?; + state.ended = true; + Ok(()) + }) + } } /// A whole-frame importer for one codec track. diff --git a/rs/moq-ffi/src/origin.rs b/rs/moq-ffi/src/origin.rs index 77c58c85dba..f25a243a251 100644 --- a/rs/moq-ffi/src/origin.rs +++ b/rs/moq-ffi/src/origin.rs @@ -707,11 +707,12 @@ mod supervision_tests { // A dynamic handle outlives the consumed producer, so only an explicit close ends it. let _dynamic = broadcast.dynamic().unwrap(); let consumer = broadcast.state.lock().unwrap().as_ref().unwrap().broadcast.consume(); + let catalog = crate::media::MoqMediaCatalogProducer::new(broadcast.clone()).unwrap(); *trigger .write() .unwrap_or_else(|_| unreachable!("test keeps its panic trigger open")) = true; assert!(matches!(completion.finished().await, Err(MoqError::Task { .. }))); - assert!(matches!(broadcast.finish(), Err(MoqError::Task { .. }))); + assert!(matches!(catalog.finish(), Err(MoqError::Task { .. }))); // The handle stays the caller's to close, and the close still ends the broadcast. assert!(!consumer.is_closed()); assert!(matches!(broadcast.close(), Err(MoqError::Task { .. }))); diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index e9b9cc781a9..1ee3187f961 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -97,7 +97,8 @@ pub(crate) struct BroadcastProducer { pub(crate) timebases: std::collections::HashMap>, pub(crate) driver: Background, pub(crate) finished: Finished, - /// Set by [`MoqBroadcastProducer::finish`]: the catalog is final, so a close leaves it alone. + /// Set by [`MoqMediaCatalogProducer::finish`](crate::media::MoqMediaCatalogProducer::finish): the + /// catalog is final, so a close leaves it alone. pub(crate) ended: bool, } @@ -346,20 +347,6 @@ impl MoqBroadcastProducer { state.driver.check()?; result } - - /// End the broadcast's content: finish its catalog, the hang end of content. - /// - /// Finish every track first. The broadcast stays announced and keeps serving its finished - /// tracks, so a subscriber that arrives late can still read them, until - /// [`close`](Self::close) takes it offline. How long to keep it up is yours to decide. - pub fn finish(&self) -> Result<(), MoqError> { - let _guard = crate::ffi::enter(); - self.with_state(|state| { - state.catalog.finish()?; - state.ended = true; - Ok(()) - }) - } } // ---- Dynamic Broadcast Producer ---- diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 3c91a2093dd..61b6160b941 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -4129,7 +4129,8 @@ async fn finish_serves_finished_tracks_until_close() { audio.finish().unwrap(); // A binding's garbage collector may release a finished handle before the broadcast closes. drop(audio); - broadcast.finish().unwrap(); + let catalog = crate::media::MoqMediaCatalogProducer::new(broadcast.clone()).unwrap(); + catalog.finish().unwrap(); let late = await_announced(&consumer, "finish").await; let track = late.subscribe_track("audio".into(), None).await.unwrap(); @@ -4142,7 +4143,7 @@ async fn finish_serves_finished_tracks_until_close() { broadcast.close().unwrap(); await_unannounced(&announced).await; - assert!(matches!(broadcast.finish(), Err(MoqError::Closed))); + assert!(matches!(catalog.finish(), Err(MoqError::Closed))); } #[tokio::test] diff --git a/swift/MIGRATE.md b/swift/MIGRATE.md index b6929a8a539..998978ed32a 100644 --- a/swift/MIGRATE.md +++ b/swift/MIGRATE.md @@ -33,10 +33,11 @@ Where you skipped such a rendition on that error, bound the call yourself: cance Audio and video init records no longer carry a track name. Pass that name on the media producer's named target instead; init records describe only the codec and media. -### Broadcast `finish` no longer closes +### Broadcast `finish` is removed -`BroadcastProducer.finish()` was a deprecated alias for `close()`; it now finishes only the catalog, and the broadcast stays up until `close()`. +`BroadcastProducer.finish()`, a deprecated alias for `close()`, is removed. Call `BroadcastProducer.close()` where you called `finish()`. +To end the content first, call `Media.CatalogProducer.finish()`; the broadcast stays up until `close()`. ### JSON snapshot `deltaRatio` is `deltas` diff --git a/swift/Sources/Moq/Broadcast.swift b/swift/Sources/Moq/Broadcast.swift index 40579ee8778..9f963e88303 100644 --- a/swift/Sources/Moq/Broadcast.swift +++ b/swift/Sources/Moq/Broadcast.swift @@ -99,13 +99,4 @@ public final class BroadcastProducer: Sendable { public func close() throws { try ffi.close() } - - /// End the broadcast's content by finishing its catalog. - /// - /// Finish every track first. The broadcast stays announced and keeps serving its finished - /// tracks to late subscribers until `close()` takes it offline; how long to keep it up is - /// yours to decide. - public func finish() throws { - try ffi.finish() - } } diff --git a/swift/Sources/Moq/Media.swift b/swift/Sources/Moq/Media.swift index 4ddd39209e0..a2aef431448 100644 --- a/swift/Sources/Moq/Media.swift +++ b/swift/Sources/Moq/Media.swift @@ -91,6 +91,12 @@ public enum Media { public func setSection(name: String, json: String) throws { try ffi.setSection(name: name, json: json) } /// Remove an application catalog section if present. public func removeSection(name: String) throws { try ffi.removeSection(name: name) } + /// Finish the catalog, which ends the broadcast's content. + /// + /// Finish every track first. The broadcast stays announced and keeps serving its finished + /// tracks to late subscribers until its `close()` takes it offline; how long to keep it up + /// is yours to decide. + public func finish() throws { try ffi.finish() } } /// Read side of a broadcast's catalog. Iterating yields catalog updates as the diff --git a/swift/Tests/MoqTests/SmokeTests.swift b/swift/Tests/MoqTests/SmokeTests.swift index f642f1ce652..af8e2deeaba 100644 --- a/swift/Tests/MoqTests/SmokeTests.swift +++ b/swift/Tests/MoqTests/SmokeTests.swift @@ -263,15 +263,16 @@ final class SmokeTests: XCTestCase { XCTAssertThrowsError(try broadcast.publishTrack(name: "events")) } - func testFinishedBroadcastStaysUpUntilClosed() throws { + func testFinishedCatalogLeavesTheBroadcastUpUntilClosed() throws { let broadcast = try BroadcastProducer() + let catalog = try Media.CatalogProducer(broadcast: broadcast) let track = try broadcast.publishTrack(name: "status") try track.finish() - try broadcast.finish() + try catalog.finish() // Finishing the content leaves the broadcast up until it closes. _ = try broadcast.consume() try broadcast.close() - XCTAssertThrowsError(try broadcast.finish()) + XCTAssertThrowsError(try catalog.finish()) } func testVideoHintsReachMediaPublishApi() throws { diff --git a/test/interop/clients/cpp/main.cpp b/test/interop/clients/cpp/main.cpp index 1cf160e14ec..e80f78e374b 100644 --- a/test/interop/clients/cpp/main.cpp +++ b/test/interop/clients/cpp/main.cpp @@ -241,9 +241,9 @@ int publish( ok(audio->finish(), "audio finish"); ok(media->finish(), "video finish"); if (!finish_ack.empty()) { - // Finishing finalizes the catalog; the broadcast stays up for the late readers until the - // close takes it offline. - ok(broadcast->finish(), "broadcast finish"); + // Finishing the catalog ends the content; the broadcast stays up for the late readers + // until the close takes it offline. + ok(catalog->finish(), "catalog finish"); const auto linger = std::chrono::seconds(10); std::printf( "finish ready linger_us=%llu\n", diff --git a/test/interop/clients/go/main.go b/test/interop/clients/go/main.go index c6d0ab216f9..af5dddeec9d 100644 --- a/test/interop/clients/go/main.go +++ b/test/interop/clients/go/main.go @@ -221,9 +221,9 @@ func publish(ctx context.Context, url, broadcast string, opts dialOptions, timeo if finishAck == "" { return nil } - // Finish finalizes the catalog; the broadcast stays up for the late readers until Close - // takes it offline. ACK never controls the linger. - if err := producer.Finish(); err != nil { + // Finishing the catalog ends the content; the broadcast stays up for the late readers + // until Close takes it offline. ACK never controls the linger. + if err := catalog.Finish(); err != nil { return err } fmt.Printf("finish ready linger_us=%d\n", finishLinger.Microseconds()) diff --git a/test/interop/clients/python/interop.py b/test/interop/clients/python/interop.py index 81d6bf8ae76..419278c3025 100644 --- a/test/interop/clients/python/interop.py +++ b/test/interop/clients/python/interop.py @@ -143,9 +143,9 @@ async def publish( audio.finish() media.finish() if finish_ack is not None: - # finish() finalizes the catalog; the broadcast stays up for the late readers until - # close() takes it offline. ACK never controls the linger. - producer.finish() + # Finishing the catalog ends the content; the broadcast stays up for the late readers + # until close() takes it offline. ACK never controls the linger. + catalog.finish() print(f"finish ready linger_us={LINGER // timedelta(microseconds=1)}", flush=True) await asyncio.sleep(LINGER.total_seconds()) producer.close() From 2af22eaf707d0adeb8a6f78a288a11f3f8e77046 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 17:17:54 -0700 Subject: [PATCH 10/12] fix(net): a tail the session ends finishes its track A lite subscription the publisher already ended still handed its track back with the session's error when its serve loop saw the session close before the driver's cleanup, which finishes it. Finish in that arm too, so the outcome no longer depends on poll order. Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/lite/subscriber.rs | 91 ++++++++++++++++++------------- 1 file changed, 53 insertions(+), 38 deletions(-) diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 5e50b10aec9..299c22a3318 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -4300,44 +4300,56 @@ mod tests { } } + /// A session that dies hands a live track back with the session's error, but finishes one + /// whose subscription the publisher already ended, as the driver's cleanup does. #[moq_clock::test] - async fn internal_tail_settle_preserves_the_session_error() { + async fn internal_session_end_gives_back_live_and_finishes_ended() { use crate::transport::poll::Session as _; - let (session, mut peer) = crate::transport::memory::pair(Default::default()); - let subscriber = Subscriber::new(SubscriberConfig { - runtime: crate::time::sim(), - session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), - recv_bandwidth: None, - version: VERSION, - peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Binding::InBand), - peer_hop: None, - cost: None, - going_away: Default::default(), - auth: crate::auth::Link::new(false), - }); - let serve = TrackServe { - validity: Default::default(), - route: None, - subscriber, - path: Path::new("room").to_owned(), - epoch: None, - name: "video".into(), - }; - let broadcast = crate::broadcast::Info::new().produce(); - let mut serving = ServeLoop::new(&serve, broadcast.reserve_track("video").unwrap(), Default::default()); - let _reader = serving.serving.subscribe(None); - let tail = kio::Producer::new(Tail::default()); - serving.mode = ServeMode::Tail { - settle: Settle::new(&serve.subscriber.runtime, tail.consume()), - owed: Some(0..1), - }; - assert!(serving.poll(&serve, &kio::Waiter::noop()).is_pending()); - peer.close(crate::SessionError::Unauthorized.to_code(), "revoked"); - assert!(matches!( - serving.poll(&serve, &kio::Waiter::noop()), - Poll::Ready(ServeEnd::GiveBack(Error::Session(crate::SessionError::Unauthorized))) - )); + for ended in [false, true] { + let (session, mut peer) = crate::transport::memory::pair(Default::default()); + let subscriber = Subscriber::new(SubscriberConfig { + runtime: crate::time::sim(), + session: crate::driver::Transport::new(session.clone()), + origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + recv_bandwidth: None, + version: VERSION, + peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Binding::InBand), + peer_hop: None, + cost: None, + going_away: Default::default(), + auth: crate::auth::Link::new(false), + }); + let serve = TrackServe { + validity: Default::default(), + route: None, + subscriber, + path: Path::new("room").to_owned(), + epoch: None, + name: "video".into(), + }; + let broadcast = crate::broadcast::Info::new().produce(); + let mut serving = ServeLoop::new(&serve, broadcast.reserve_track("video").unwrap(), Default::default()); + let _reader = serving.serving.subscribe(None); + assert!(serving.poll(&serve, &kio::Waiter::noop()).is_pending()); + // Held for the whole round: a dropped tail settles at once. + let tail = kio::Producer::new(Tail::default()); + if ended { + serving.mode = ServeMode::Tail { + settle: Settle::new(&serve.subscriber.runtime, tail.consume()), + owed: Some(0..1), + }; + assert!(serving.poll(&serve, &kio::Waiter::noop()).is_pending()); + } + peer.close(crate::SessionError::Unauthorized.to_code(), "revoked"); + let end = serving.poll(&serve, &kio::Waiter::noop()); + match ended { + true => assert!(matches!(end, Poll::Ready(ServeEnd::Finished))), + false => assert!(matches!( + end, + Poll::Ready(ServeEnd::GiveBack(Error::Session(crate::SessionError::Unauthorized))) + )), + } + } } /// A publisher that finishes the track stops reading its subscribe stream, so a @@ -7421,9 +7433,12 @@ impl ServeLoop { if self.fetches.is_empty() && crate::util::poll_unwanted(&mut self.demand, waiter).is_ready() { return Poll::Ready(ServeEnd::Idle); } + // The publisher already ended the subscription, so a session that dies now + // finishes the track, as `SubscriptionCleanup` does, rather than hand it + // to another route. let mut cx = std::task::Context::from_waker(waiter.waker()); - if let Poll::Ready(err) = self.closed.poll_closed(&mut cx) { - return Poll::Ready(ServeEnd::GiveBack(crate::lite::error::from_transport(err))); + if self.closed.poll_closed(&mut cx).is_ready() { + return Poll::Ready(ServeEnd::Finished); } return Poll::Pending; } From 736627ba5025d5459854bf286d4351e1d5af66a2 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 17:36:24 -0700 Subject: [PATCH 11/12] fix: restore imports main's Fill wrappers use The merge dropped the Go time import and the Python _opt_from_us import along with the finish linger helpers, but main's Fill.MaxDelay needs them. Co-Authored-By: Claude Opus 5.5 --- go/wrapper/publish.go | 1 + py/moq-rs/moq/publish.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/go/wrapper/publish.go b/go/wrapper/publish.go index 3afb73d6911..4244c48c8b0 100644 --- a/go/wrapper/publish.go +++ b/go/wrapper/publish.go @@ -3,6 +3,7 @@ package moq import ( "context" "iter" + "time" ffi "moq.dev/moq-ffi/moq" "moq.dev/moq/internal/bridge" diff --git a/py/moq-rs/moq/publish.py b/py/moq-rs/moq/publish.py index 34476c454eb..8d006df0d5d 100644 --- a/py/moq-rs/moq/publish.py +++ b/py/moq-rs/moq/publish.py @@ -17,7 +17,7 @@ MoqTrackRequest, ) -from ._records import _subscription, _track_info +from ._records import _opt_from_us, _subscription, _track_info from ._stream import _Stream from .types import ( AnnounceRoute, From b53e8f6fca6aa65260726a851c1a83397677ffd7 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 24 Oct 2026 18:33:38 -0700 Subject: [PATCH 12/12] quest: drop the last broadcast finish reference in listing-clean-end Co-Authored-By: Claude Opus 5.5 --- quest/m1/listing-clean-end.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/quest/m1/listing-clean-end.md b/quest/m1/listing-clean-end.md index 886dfe8b6cf..1391be79dde 100644 --- a/quest/m1/listing-clean-end.md +++ b/quest/m1/listing-clean-end.md @@ -40,8 +40,7 @@ Open design (maintainer to decide): still needs the forwarder, close, and publisher changes from option 1. Starting point: this test in `rs/moq-net/src/ietf/publisher/tracks.rs` fails -on drafts 18-22 (the finished track gets status 0, not 2). Swapping -`h.broadcast.close()` for a dropped `finish()` fails the same way. +on drafts 18-22 (the finished track gets status 0, not 2). ```rust #[moq_clock::test]