From b4b96c9ae0d6fa5a12febaee956e9949ca0b16d2 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 29 Oct 2026 08:49:59 -0700 Subject: [PATCH 1/9] chore(quest): claim quest/m1/c/api-gaps.md Quest-Claim: 5f0e027391ea1986 From 69360a4279bc0a1d41122ea0194612cfd5ec9a62 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 29 Oct 2026 09:02:21 -0700 Subject: [PATCH 2/9] feat(c)!: expose audio enablement and normalize epoch errors Co-Authored-By: GPT-6.1 --- doc/lib/c/index.md | 2 +- quest/m1/c/README.md | 1 - quest/m1/c/api-gaps.md | 32 ---- rs/moq-c/README.md | 1 + rs/moq-c/c-tests/audio-decode-output.c | 7 + rs/moq-c/src/api.rs | 30 +++- rs/moq-c/src/consume.rs | 17 +- rs/moq-c/src/test.rs | 216 ++++++++++++++++++++++++- 8 files changed, 255 insertions(+), 51 deletions(-) delete mode 100644 quest/m1/c/api-gaps.md diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index a491cde3189..c056e53fdfb 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -108,7 +108,7 @@ inside. The header is the reference: each function carries a doc comment. - **Decoded reads.** `moq_decode_audio` and `moq_decode_video` deliver read ids in order: a frame, a gap where media was lost, or an end where the publisher stopped its encoder. Check `kind` on what `moq_decode_audio_read` or `moq_decode_video_read` writes. Free each id with `moq_decode_audio_read_free` or `moq_decode_video_read_free` promptly: a held video frame holds a decoder buffer, and the decoder stalls. - **Stats.** `moq_session_stats()` fills `moq_connection_stats` with `rtt_us`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). Each has a `_valid` flag, false when the transport does not report it, which is not the same as zero. `moq_session_snapshot()` adds the negotiated `protocol`. A failed dial or dropped connection reaches the session's `on_state` with its `failure` code, and `moq_error()` gives the reason during that callback. Hold the handle returned by `moq_session_recv_bandwidth()` to request receive estimates. `moq_bandwidth_consumer_peek()` reads the estimate and `moq_bandwidth_consumer_changed()` waits for a change. `moq_bandwidth_consumer_close()` releases demand; the last consumer stops PROBE. Stats snapshots do not request it. - **Demand.** A watcher from `moq_publish_track_demand()` (or the media, video, and audio variants) calls back `MOQ_DEMAND_USED` or `MOQ_DEMAND_UNUSED`, again whenever the wanted group moves. `moq_publish_demand_wanted()` reads that group: start a new one once it passes your largest. Set `refresh` in `moq_track_info` to have a joining subscriber ask for a new group once the newest has grown past `refresh` times its first frame. -- **Disabled renditions.** A rendition with `enabled: false` has no frames coming until its publisher re-enables it. Select an enabled rendition from the latest catalog before opening a decoder. Keep one already playing while every rendition of its kind is disabled: the convenience decoders accept a disabled configuration, and a re-enable, such as an unmute, then plays without a resubscribe. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. +- **Disabled renditions.** A rendition with `enabled: false` has no frames coming until its publisher re-enables it. Query the latest catalog with `moq_consume_audio_enabled` or `moq_consume_video_enabled` before selecting a rendition and opening a decoder. Keep one already playing while every rendition of its kind is disabled: the convenience decoders accept a disabled configuration, and a re-enable, such as an unmute, then plays without a resubscribe. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. ## Reference diff --git a/quest/m1/c/README.md b/quest/m1/c/README.md index bd8de26d5df..af4cbf2d370 100644 --- a/quest/m1/c/README.md +++ b/quest/m1/c/README.md @@ -31,4 +31,3 @@ Public API: moq-c gains each m1 binding feature. Wire: none. - [moq-c decode start](/quest/m1/c/decode-start.md) - a moq-c decoder can read a finished track from its start - [JSON windows](/quest/m1/c/json-window.md) - moq-c publishes and reads moq-json windows, as moq-ffi does -- [API gaps](/quest/m1/c/api-gaps.md) - one malformed-epoch error code, an audio enabled query, and a relay hops test diff --git a/quest/m1/c/api-gaps.md b/quest/m1/c/api-gaps.md deleted file mode 100644 index e545717de76..00000000000 --- a/quest/m1/c/api-gaps.md +++ /dev/null @@ -1,32 +0,0 @@ -# [S] moq-c closes its small API gaps - -## Goal - -moq-c reports a malformed epoch the same way everywhere, lets a C consumer see -that audio is disabled as it can for video, and has a test of the hops on a -route received through a relay. - -## Plan - -Found 2026-10-28 by [moq-dev/moq#7151](https://github.com/moq-dev/moq/pull/7151) -and [moq-dev/moq#7156](https://github.com/moq-dev/moq/pull/7156). - -Decided 2026-10-28 (maintainer): one PR for all three. moq-c already breaks -at this cut (0.6 to 0.7), so the error-code change rides that break. - -- `moq_broadcast_request_prepare` reports a malformed epoch as - `MOQ_ERROR_INVALID_CODE`, while `moq_publication_announce`, which takes an - epoch in `moq_announce_route` since - [moq-dev/moq#7151](https://github.com/moq-dev/moq/pull/7151), reports a - malformed one as `MOQ_ERROR_INVALID_CONFIG`. Use - `MOQ_ERROR_INVALID_CONFIG` for both, with an Impact migration note. -- Add an audio counterpart to `moq_consume_video_enabled`, so a C app can tell - that a held audio rendition is disabled. -- Add a moq-c test that announces through a relay session and checks the - received route's `hops`. - -Update `moq.h`, `rs/moq-c/README.md` and `doc/lib/c` as needed. - -Public API: moq-c gains an audio enabled query and changes one error code. -Wire: none. - diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index 3eabf2ec079..56a67a3fb09 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -124,6 +124,7 @@ int32_t moq_consume_catalog_free(uint32_t catalog); int32_t moq_consume_video_config(uint32_t catalog, uint32_t index, moq_video_config *dst); int32_t moq_consume_video_enabled(uint32_t catalog, uint32_t index, bool *dst); int32_t moq_consume_audio_config(uint32_t catalog, uint32_t index, moq_audio_config *dst); +int32_t moq_consume_audio_enabled(uint32_t catalog, uint32_t index, bool *dst); // Consuming: Video int32_t moq_consume_video(uint32_t catalog, uint32_t index, uint64_t max_delay_us, moq_status_callback on_frame, void *user_data); diff --git a/rs/moq-c/c-tests/audio-decode-output.c b/rs/moq-c/c-tests/audio-decode-output.c index 4799a02940e..608aea7f787 100644 --- a/rs/moq-c/c-tests/audio-decode-output.c +++ b/rs/moq-c/c-tests/audio-decode-output.c @@ -128,6 +128,13 @@ int main(void) { wait_until(&c, &c.catalog); pthread_mutex_unlock(&c.mutex); + bool enabled = false; + CHECK(moq_consume_audio_enabled((uint32_t)c.catalog, 0, &enabled) == 0); + CHECK(enabled); + CHECK(moq_consume_audio_enabled((uint32_t)c.catalog, 1, &enabled) == MOQ_ERROR_NO_INDEX); + CHECK(enabled); // An error preserves the destination. + CHECK(moq_consume_audio_enabled((uint32_t)c.catalog, 0, NULL) == MOQ_ERROR_INVALID_POINTER); + // Each decode reads the finished track from the start. Its budget is the track's whole // retention, since the budget ages groups by wall clock and a stalled host would skip them. const uint32_t formats[] = {MOQ_AUDIO_SAMPLE_FORMAT_F32, MOQ_AUDIO_SAMPLE_FORMAT_F32_PLANAR, MOQ_AUDIO_SAMPLE_FORMAT_S16}; diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index cf5e9a123f2..c2203e1739c 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -1912,6 +1912,7 @@ pub unsafe extern "C" fn moq_broadcast_request_path(request: u32, dst: *mut moq_ /// Consumes the request handle, writes the new broadcast handle to `broadcast` /// (which cannot announce itself; only [moq_broadcast_prepared_publish] does), /// and returns a positive prepared-answer handle or a negative error. +/// A malformed epoch returns `MOQ_ERROR_INVALID_CONFIG` without consuming the request. /// /// # Safety /// - `epoch` must point at `epoch_len` readable bytes containing a UUIDv7 epoch. @@ -1925,9 +1926,10 @@ pub unsafe extern "C" fn moq_broadcast_request_prepare( ) -> i32 { ffi::enter(move || { let request = ffi::parse_id(request)?; - let epoch = unsafe { ffi::parse_str(epoch, epoch_len)? } + let epoch = unsafe { ffi::parse_str(epoch, epoch_len)? }; + let epoch = epoch .parse() - .map_err(|_| Error::InvalidCode)?; + .map_err(|_| Error::InvalidConfig(format!("epoch {epoch:?} is not canonical UUIDv7 text")))?; let broadcast_out = unsafe { broadcast.as_mut() }.ok_or(Error::InvalidPointer)?; let mut state = State::lock(); let (pending, driver) = state.origin.broadcast_request_take(request)?; @@ -3555,6 +3557,30 @@ pub unsafe extern "C" fn moq_consume_audio_config(catalog: u32, index: u32, dst: }) } +/// Query whether the publisher is serving an audio rendition. +/// +/// False means no frames are coming until it re-enables. Pick an enabled rendition, but keep one +/// already playing while every audio rendition is disabled, so a re-enable plays without a +/// resubscribe. A catalog that omits the optional field reads as true. +/// +/// Returns zero on success, or a negative code on failure. +/// +/// # Safety +/// - The caller must ensure that `dst` points to properly aligned, writable storage for a `bool`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_consume_audio_enabled(catalog: u32, index: u32, dst: *mut bool) -> i32 { + ffi::enter(move || { + let catalog = ffi::parse_id(catalog)?; + if dst.is_null() { + return Err(Error::InvalidPointer); + } + + let enabled = State::lock().consume.audio_enabled(catalog, index as usize)?; + unsafe { dst.write(enabled) }; + Ok(()) + }) +} + /// Number of untyped application catalog sections in a catalog snapshot. /// /// These are the top-level catalog keys beyond `video`/`audio`, carried through diff --git a/rs/moq-c/src/consume.rs b/rs/moq-c/src/consume.rs index 8ac5ce54f7b..8b4123ba1f9 100644 --- a/rs/moq-c/src/consume.rs +++ b/rs/moq-c/src/consume.rs @@ -337,16 +337,15 @@ impl Consume { Ok(()) } - /// Return whether a video rendition may be selected. + /// Return whether the publisher is serving a video rendition. pub fn video_enabled(&self, catalog: Id, index: usize) -> Result { - let consume = self.catalog.get(catalog).ok_or(Error::CatalogNotFound)?; - let (_, config) = consume - .catalog - .video - .renditions - .iter() - .nth(index) - .ok_or(Error::NoIndex)?; + let (_, _, config) = self.select::(catalog, index)?; + Ok(config.enabled) + } + + /// Return whether the publisher is serving an audio rendition. + pub fn audio_enabled(&self, catalog: Id, index: usize) -> Result { + let (_, _, config) = self.select::(catalog, index)?; Ok(config.enabled) } diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index ec7ea65798d..3d1eb672b62 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -938,6 +938,118 @@ fn publish_catalog_config_null_pointer() { assert_eq!(moq_publish_close(broadcast), 0); } +/// Enablement belongs to each catalog snapshot; holding a disabled rendition keeps its subscription usable. +#[test] +fn audio_enabled_snapshots_preserve_a_held_consumer() { + let origin = id(moq_origin_create()); + let path = b"audio-enabled"; + let broadcast = publish_broadcast(origin, path); + let media = id(publish_audio( + broadcast, + moq_audio_format::MOQ_AUDIO_FORMAT_OPUS, + &opus_head(), + None, + )); + let consume = request_broadcast(origin, path); + let catalogs = Callback::new(); + let catalog_task = id(unsafe { moq_consume_catalog(consume, Some(channel_callback), catalogs.ptr) }); + let initial = id(catalogs.recv()); + let mut enabled = std::mem::MaybeUninit::::uninit(); + assert_eq!( + unsafe { moq_consume_audio_enabled(initial, 0, enabled.as_mut_ptr()) }, + 0 + ); + assert!(unsafe { enabled.assume_init() }, "omitted enabled defaults to true"); + + let set_enabled = |enabled| { + let mut state = State::lock(); + let catalog = state.publish.target(Id::try_from(broadcast).unwrap()).unwrap().catalog; + catalog + .modify() + .unwrap() + .audio + .renditions + .values_mut() + .next() + .unwrap() + .enabled = enabled; + }; + set_enabled(false); + let disabled = id(catalogs.recv()); + assert_eq!( + unsafe { moq_consume_audio_enabled(disabled, 0, enabled.as_mut_ptr()) }, + 0 + ); + assert!(!unsafe { enabled.assume_init() }); + assert_eq!( + unsafe { moq_consume_audio_enabled(initial, 0, enabled.as_mut_ptr()) }, + 0 + ); + assert!(unsafe { enabled.assume_init() }, "an older snapshot remains unchanged"); + + let mut preserved = true; + assert_eq!( + unsafe { moq_consume_audio_enabled(disabled, 1, &mut preserved) }, + MOQ_ERROR_NO_INDEX + ); + assert!(preserved); + assert_eq!( + unsafe { moq_consume_audio_enabled(disabled, 0, std::ptr::null_mut()) }, + MOQ_ERROR_INVALID_POINTER + ); + + // A held rendition may be opened from a disabled snapshot, then re-enabled without resubscribing. + let frames = Callback::new(); + let track = id(unsafe { moq_consume_audio(disabled, 0, 10_000_000, Some(channel_callback), frames.ptr) }); + set_enabled(true); + let resumed = id(catalogs.recv()); + assert_eq!( + unsafe { moq_consume_audio_enabled(resumed, 0, enabled.as_mut_ptr()) }, + 0 + ); + assert!(unsafe { enabled.assume_init() }); + assert_eq!( + unsafe { moq_consume_audio_enabled(disabled, 0, enabled.as_mut_ptr()) }, + 0 + ); + assert!(!unsafe { enabled.assume_init() }); + let payload = b"resumed-audio"; + assert_eq!( + unsafe { moq_publish_media_frame(media, payload.as_ptr(), payload.len(), 0) }, + 0 + ); + let read = id(frames.recv()); + let mut frame: moq_frame = unsafe { std::mem::zeroed() }; + assert_eq!(unsafe { encoded_frame(read, &mut frame) }, 0); + assert_eq!( + unsafe { std::slice::from_raw_parts(frame.payload, frame.payload_size) }, + payload + ); + assert_eq!(moq_consume_read_free(read), 0); + + assert_eq!(moq_consume_audio_cancel(track), 0); + assert_eq!(frames.recv_terminal(), 0); + for catalog in [initial, disabled, resumed] { + assert_eq!(moq_consume_catalog_free(catalog), 0); + } + assert_eq!( + unsafe { moq_consume_audio_enabled(i32::MAX as u32, 0, &mut preserved) }, + MOQ_ERROR_CATALOG_NOT_FOUND + ); + assert!(preserved); + assert_eq!( + unsafe { moq_consume_audio_enabled(0, 0, &mut preserved) }, + MOQ_ERROR_INVALID_ID + ); + assert!(preserved); + assert_eq!(moq_consume_catalog_cancel(catalog_task), 0); + assert_eq!(catalogs.recv_catalog_terminal(), 0); + assert_eq!(moq_consume_close(consume), 0); + assert_eq!(moq_publish_media_finish(media), 0); + assert_eq!(moq_publish_close(broadcast), 0); + assert_eq!(moq_origin_close(origin), 0); +} + #[test] fn publish_catalog_roundtrip() { let origin = id(moq_origin_create()); @@ -2907,11 +3019,15 @@ fn announce_route_carries_cost_and_epoch_without_hops() { assert_eq!(moq_origin_announced_free(announced), 0); // Anything but canonical UUIDv7 text is refused. - let upper = mint_epoch().to_uppercase(); - for bad in ["6ba7b810-9dad-41d1-80b4-00c04fd430c8", upper.as_str(), "not-an-epoch"] { + for bad in [ + "6ba7b810-9dad-41d1-80b4-00c04fd430c8", + "00000000-0000-7000-8000-00000000000A", + "not-an-epoch", + ] { let route = announce_route(0, bad); - assert!( - unsafe { moq_publication_announce(publication, &route) } < 0, + assert_eq!( + unsafe { moq_publication_announce(publication, &route) }, + MOQ_ERROR_INVALID_CONFIG, "{bad:?} is not an epoch" ); } @@ -2997,8 +3113,22 @@ fn dynamic_serves_a_request_under_a_prefix() { let got = unsafe { std::str::from_utf8(std::slice::from_raw_parts(info.data.cast::(), info.len)).unwrap() }; assert_eq!(got, "live/cam"); - let epoch = moq_net::Epoch::mint().to_string(); - let mut served = 0; + // Invalid input leaves the request and destination intact, so it can still be answered. + let mut served = u32::MAX; + for bad in [ + "", + "not-an-epoch", + "6ba7b810-9dad-41d1-80b4-00c04fd430c8", + "00000000-0000-7000-8000-00000000000A", + ] { + assert_eq!( + unsafe { moq_broadcast_request_prepare(request, bad.as_ptr().cast(), bad.len(), &mut served) }, + MOQ_ERROR_INVALID_CONFIG, + "{bad:?} is not an epoch" + ); + assert_eq!(served, u32::MAX); + } + let epoch = mint_epoch(); let prepared = id(unsafe { moq_broadcast_request_prepare(request, epoch.as_ptr().cast(), epoch.len(), &mut served) }); let publication = id(moq_broadcast_prepared_publish(prepared)); @@ -6309,6 +6439,80 @@ fn dial_pinned(url: &str, fingerprint: &str, consume: u32, user_data: *mut c_voi }) } +/// Received routes expose each traversed origin in order, rather than an empty local path. +#[test] +fn announce_route_hops_cross_a_relay_session() { + let source = id(moq_origin_create()); + let relay = id(moq_origin_create()); + let sink = id(moq_origin_create()); + let hops = { + let state = State::lock(); + [source, relay].map(|origin| state.origin.get(Id::try_from(origin).unwrap()).unwrap().hop().id()) + }; + let server_cb = Callback::new(); + let (server, addr, fingerprint) = listen(&server_cb); + let url = format!("https://{addr}/"); + + let upstream_client_cb = States::new(); + let upstream_client = dial_pinned(&url, &fingerprint, relay, upstream_client_cb.ptr); + let upstream_cb = States::new(); + let upstream = id(unsafe { + moq_session_request_accept(id(server_cb.recv()), source, 0, Some(state_callback), upstream_cb.ptr) + }); + let downstream_client_cb = States::new(); + let downstream_client = dial_pinned(&url, &fingerprint, sink, downstream_client_cb.ptr); + let downstream_cb = States::new(); + let downstream = id(unsafe { + moq_session_request_accept(id(server_cb.recv()), relay, 0, Some(state_callback), downstream_cb.ptr) + }); + for cb in [&upstream_client_cb, &upstream_cb, &downstream_client_cb, &downstream_cb] { + assert_eq!(cb.recv().phase, moq_connection_phase::MOQ_CONNECTION_PHASE_CONNECTED); + } + + let announced_cb = Callback::new(); + let task = id(unsafe { moq_origin_announced(sink, std::ptr::null(), Some(channel_callback), announced_cb.ptr) }); + let (publication, broadcast) = create_broadcast(source, b"relayed"); + let route = moq_announce_route { + cost: 7, + epoch: std::ptr::null(), + epoch_len: 0, + }; + assert_eq!(unsafe { moq_publication_announce(publication, &route) }, 0); + let (announced, info) = announced_cb.recv_route(); + assert_eq!(info.kind, moq_announce_kind::MOQ_ANNOUNCE_KIND_START); + assert_eq!( + borrowed_string(info.prefix, info.prefix_len).as_deref(), + Some("relayed") + ); + assert_eq!(info.route.hops_len, hops.len()); + assert_eq!( + unsafe { std::slice::from_raw_parts(info.route.hops, info.route.hops_len) }, + hops + ); + assert_eq!(info.route.cost, 9, "each session adds its default cost of one"); + assert_eq!(route_epoch(&info.route), None); + assert_eq!(moq_origin_announced_free(announced), 0); + + assert_eq!(moq_origin_announced_cancel(task), 0); + assert_eq!(announced_cb.recv_announce_terminal(), 0); + for (session, cb) in [ + (downstream, &downstream_cb), + (downstream_client, &downstream_client_cb), + (upstream, &upstream_cb), + (upstream_client, &upstream_client_cb), + ] { + assert_eq!(moq_session_close(session), 0); + cb.recv_terminal(); + } + assert_eq!(moq_server_close(server), 0); + assert_eq!(server_cb.recv_terminal(), 0); + assert_eq!(moq_publication_free(publication), 0); + assert_eq!(moq_publish_close(broadcast), 0); + for origin in [source, relay, sink] { + assert_eq!(moq_origin_close(origin), 0); + } +} + #[test] fn server_accepts_a_session() { let served = id(moq_origin_create()); From 38969e5fdc365a102cc0fbd7bbddc0a436a94915 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 29 Oct 2026 09:17:33 -0700 Subject: [PATCH 3/9] chore(quest): preserve C API validation blockers Co-Authored-By: GPT-6.1 Sol --- quest/m1/c/README.md | 1 + quest/m1/c/api-gaps.md | 44 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 quest/m1/c/api-gaps.md diff --git a/quest/m1/c/README.md b/quest/m1/c/README.md index af4cbf2d370..bd8de26d5df 100644 --- a/quest/m1/c/README.md +++ b/quest/m1/c/README.md @@ -31,3 +31,4 @@ Public API: moq-c gains each m1 binding feature. Wire: none. - [moq-c decode start](/quest/m1/c/decode-start.md) - a moq-c decoder can read a finished track from its start - [JSON windows](/quest/m1/c/json-window.md) - moq-c publishes and reads moq-json windows, as moq-ffi does +- [API gaps](/quest/m1/c/api-gaps.md) - one malformed-epoch error code, an audio enabled query, and a relay hops test diff --git a/quest/m1/c/api-gaps.md b/quest/m1/c/api-gaps.md new file mode 100644 index 00000000000..253d5ea1aaa --- /dev/null +++ b/quest/m1/c/api-gaps.md @@ -0,0 +1,44 @@ +# [S] moq-c closes its small API gaps + +## Goal + +moq-c reports a malformed epoch the same way everywhere, lets a C consumer see +that audio is disabled as it can for video, and has a test of the hops on a +route received through a relay. + +## Plan + +Found 2026-10-28 by [moq-dev/moq#7151](https://github.com/moq-dev/moq/pull/7151) +and [moq-dev/moq#7156](https://github.com/moq-dev/moq/pull/7156). + +Decided 2026-10-28 (maintainer): one PR for all three. moq-c already breaks +at this cut (0.6 to 0.7), so the error-code change rides that break. +Use `MOQ_ERROR_INVALID_CONFIG` for malformed epochs in both +`moq_broadcast_request_prepare` and `moq_publication_announce`, add the audio +enabled query, and test received relay hops. + +Implementation is checkpointed in [moq-dev/moq#7246](https://github.com/moq-dev/moq/pull/7246): +`moq_consume_audio_enabled` mirrors the video query, epoch validation uses the +settled error code, and tests cover snapshot enablement, a consumer opened +from a disabled snapshot resuming, and ordered hops over two C sessions. +The README and C guide are updated; a C audio fixture calls the new query. +The PR Impact records the error-code migration and new query. + +Remaining work is validation before marking ready and deleting this quest: +run the moq-c tests, compile and run the C fixtures against the generated +`moq.h` and `libmoq.a`, and pass the local CI gate. Resolve any relevant +failures and review findings. + +Reproduced 2026-10-29: a malformed request epoch returned -15 instead of -40, +and compiling the C fixture against the original header failed because the +audio query was undeclared. Formatting, quest validation, and the gate's +other static checks passed. `just ci` failed before Rust validation because +mbx could not launch Cargo (`Argument list too long`); the CI tooling test +failed through the same wrapper. Merely prepending pinned Cargo still hit +mbx because `BASH_ENV` reinjected it in child shells. Omitting that hook +verified the pinned Cargo path, but its validation run remained waiting at +`quest gate` for host capacity and was stopped with exit 143 before tests +started. No successful run of the new tests or C fixture is claimed. + +Public API: moq-c gains an audio enabled query and changes one error code. +Wire: none. From c5b37c87d40072c9dc582365b3d6b1f4c7aca7f0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 23:24:52 -0800 Subject: [PATCH 4/9] chore(quest): claim quest/m1/c/api-gaps.md Quest-Claim: 38b31164e86fff37 From 9bfd74a411c267a5d2ac19378606c1dd363b1b7e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 23:32:31 -0800 Subject: [PATCH 5/9] feat(c)!: expose pre-encoded simulcast rate control Co-Authored-By: GPT-6.1 Sol --- doc/lib/c/index.md | 2 +- quest/m1/c/README.md | 4 -- quest/m1/c/api-gaps.md | 30 -------- rs/moq-c/MIGRATE.md | 11 +++ rs/moq-c/README.md | 21 ++++++ rs/moq-c/c-tests/rate-control.c | 17 +++++ rs/moq-c/src/api.rs | 19 +++++ rs/moq-c/src/bandwidth.rs | 124 ++++++++++++++++++++++++++++++++ rs/moq-c/src/publish.rs | 62 +++++++++++++--- rs/moq-c/src/test.rs | 83 +++++++++++++++++++++ 10 files changed, 329 insertions(+), 44 deletions(-) delete mode 100644 quest/m1/c/api-gaps.md create mode 100644 rs/moq-c/c-tests/rate-control.c diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index f59d7597dde..d3d62b75d85 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -88,7 +88,7 @@ across restarts, and raise `epoch` on each: readers stitch every route of one in together, so restarting the sequences under an old instance splices unrelated groups into their tracks. -Raw video encoders take an exact numerator/denominator frame rate, such as 30000/1001. Publication track names stay separate from codec settings. For simulcast, give each rendition the next one down as the `lower` handle in its `moq_video_encode_options`: it stops encoding, advertised as disabled, while its bandwidth grant cannot fund it, and resumes once the grant recovers. A rung only disables while the session probes for bandwidth, which on native transports takes moq-quic with BBR3. +Raw video encoders take an exact numerator/denominator frame rate, such as 30000/1001. Publication track names stay separate from codec settings. For simulcast, give each rendition the next one down as the `lower` handle in its `moq_video_encode_options`: it stops encoding, advertised as disabled, while its bandwidth grant cannot fund it, and resumes once the grant recovers. A rung only disables while the session probes for bandwidth, which on native transports takes moq-quic with BBR3. For pre-encoded video, publish from the lowest rendition up and set `moq_video_init.lower` to the next lower media handle. Reserve each track with `moq_allocator_reserve_media`, then feed its reservation to `moq_rate_control_update` on every frame. Apply changed targets to your encoder and `moq_publish_media_set_enabled`, resuming video on a keyframe; close the control and reservation separately when done. ## Things to know diff --git a/quest/m1/c/README.md b/quest/m1/c/README.md index 7e1845fc16c..1b6313edb19 100644 --- a/quest/m1/c/README.md +++ b/quest/m1/c/README.md @@ -26,7 +26,3 @@ twice (0.6 to 0.7, then to the generated 0.8); that is the accepted cost. release produces the C archive the samples are checked against. Public API: moq-c gains each m1 binding feature. Wire: none. - -## Required - -- [API gaps](/quest/m1/c/api-gaps.md) - disabling pre-encoded simulcast rungs after the shared importer support lands diff --git a/quest/m1/c/api-gaps.md b/quest/m1/c/api-gaps.md deleted file mode 100644 index 9f8e318afd8..00000000000 --- a/quest/m1/c/api-gaps.md +++ /dev/null @@ -1,30 +0,0 @@ -# [S] moq-c disables pre-encoded simulcast rungs - -## Goal - -moq-c can disable a simulcast rung on pre-encoded media, with its lower -rendition's priority and a rate control driven by the reservation. - -## Plan - -- Add C ABI support for disabling simulcast rungs on pre-encoded media on - [moq-dev/moq#7029](https://github.com/moq-dev/moq/pull/7029)'s shared - importer support. It merged as - [61cb70456d](https://github.com/moq-dev/moq/commit/61cb70456dd0d70909bc2a1c18916331e90b51ea), - so this work is unblocked: main has `moq_mux::import::Track::set_enabled`, - `import::VideoInit.priority`, the AV1/VP8/VP9 importer setters, and the - moq-ffi `MoqRateControl`, `MoqVideoInit.lower`, and media producer - `set_enabled` interfaces. -- Expose media `set_enabled`, lower-rendition ordering, and - a rate control over the C reservation. Inspect the final shared interfaces - first. Decided 2026-10-30 (maintainer, /quest-plan of the 2026-10-30 - /quest-complete follow-ups): the C epic's rule (every m1 binding feature - missing from `moq.h` lands before the cut) overrides that PR's decision 4, - which parked it until a C consumer asked: ✅ add to m1 C gaps / exempt it. - -Update the generated `moq.h`, `rs/moq-c/README.md` and `doc/lib/c` as needed. -The independent JSON window caller timestamp gap is implemented in -[moq-dev/moq#7614](https://github.com/moq-dev/moq/pull/7614). - -Public API: moq-c gains pre-encoded rung disable, lower-rendition ordering, -and reservation rate control. Wire: none. diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index 143245df61b..9c2d4ee136e 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -4,6 +4,17 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Pre-encoded simulcast + +`moq_video_init` gains `lower`, changing its C ABI layout. Rebuild against the +regenerated `moq.h` and matching library, zero-initialize the struct, and set +`lower` to the next lower pre-encoded video media handle (0 for none). +Use `moq_publish_media_set_enabled` to advertise disabled video renditions, +and `moq_allocator_reserve_media` with the new `moq_rate_control_*` handles to +adapt an external encoder to its reservation. Close controls and reservations +separately. No wire format changes. + + ### Separate datagram tracks Create a separate producer with `moq_publish_datagrams` and `moq_datagram_info`; replace `moq_publish_track_datagram` with `moq_publish_datagrams_append` on that handle, or `moq_publish_datagrams_insert` for an explicit sequence. `moq_consume_datagrams` now takes a subscriber priority before its callback and never subscribes to a stream track. Use `moq_publish_datagrams_demand` and `moq_datagram_demand_priority` for aggregate priority, and `moq_publish_datagrams_requests` / `moq_datagram_request_accept` for on-demand publishing. Finish or abort datagram producers separately. A zeroed datagram info is untimed, unlike the microsecond default of stream-track info. `moq_consume_datagrams` returns a negative code at once when the broadcast has neither the datagram track nor a datagram request handler, and a remote name without one ends its callback with a not-found error. diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index 445f6e51427..8d48018e4f7 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -172,3 +172,24 @@ converted to the track's milliseconds; pass NULL to stamp the broadcast clock. int32_t moq_publish_json_window_push(uint32_t window, const char *value, uintptr_t value_len, const moq_timestamp *timestamp); int32_t moq_publish_json_window_pop(uint32_t window, uint64_t count, const moq_timestamp *timestamp); ``` + +### Pre-encoded simulcast + +Publish video renditions from lowest to highest, passing the next lower media +handle in `moq_video_init.lower` (0 for the lowest). This orders delivery so +higher renditions yield to lower ones. `moq_publish_media_set_enabled` updates +the catalog and marks a discontinuity when disabling; resume on a keyframe. +Audio importers do not support this toggle. + +Reserve each media track with `moq_allocator_reserve_media`. Create a +`moq_rate_control_create` handle with `moq_rate_policy.max_bps` and, for higher +rungs, `has_lower` and `lower_bps`. Read its initial `moq_rate_control_target`, +then call `moq_rate_control_update` with the reservation on every frame, +including while disabled. A return of 1 writes a changed target; 0 holds the +last target; a negative return is an error. Apply the target's `bitrate_bps` +to your encoder and `enabled` through `moq_publish_media_set_enabled`. +The shared controller drops immediately, ramps raises, ignores small changes, +and holds without an estimate. A rung disables only with a probing session, +which on native transports requires moq-quic with BBR3, so bandwidth can recover. +Close controls with `moq_rate_control_close` and reservations with +`moq_reservation_close`; neither owns or closes the media track. diff --git a/rs/moq-c/c-tests/rate-control.c b/rs/moq-c/c-tests/rate-control.c new file mode 100644 index 00000000000..983d53b2e63 --- /dev/null +++ b/rs/moq-c/c-tests/rate-control.c @@ -0,0 +1,17 @@ +// Exercise rate-control records and handle ownership across the generated C ABI. +#include +#include + +int main(void) { + moq_video_init video = {0}; + assert(video.lower == 0); + moq_rate_policy policy = {.max_bps = 4000000, .lower_bps = 2000000, .has_lower = true}; + int32_t control = moq_rate_control_create(policy); + assert(control > 0); + moq_rate_target target = {0}; + assert(moq_rate_control_target((uint32_t)control, &target) == 0); + assert(target.enabled && target.bitrate_bps == policy.max_bps); + assert(moq_rate_control_close((uint32_t)control) == 0); + assert(moq_rate_control_target((uint32_t)control, &target) < 0); + return 0; +} diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index b7190ab3e67..efbec7b9644 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -269,6 +269,9 @@ pub struct moq_video_init { /// Catalog fields the bitstream cannot reveal itself. Zeroed means none. pub hint: moq_video_hint, + /// Next lower pre-encoded video media handle, or 0 for the lowest rendition. + /// Publish it first; this track gets one priority below it, saturating at -128. + pub lower: u32, } /// Optional catalog fields for [moq_video_init::hint]. @@ -2619,6 +2622,12 @@ unsafe fn parse_video_init( let mut video = moq_mux::import::VideoInit::new(video_format_from_u32(config.format)?, init.to_vec()); video.label = label.map(str::to_string); video.hint = config.hint.resolve()?; + if config.lower != 0 { + video.priority = State::lock() + .publish + .media_video_priority(ffi::parse_id(config.lower)?)? + .saturating_sub(1); + } Ok((video, config.hint.group_duration()?)) } @@ -2846,6 +2855,16 @@ pub unsafe extern "C" fn moq_publish_media_frame( }) } +/// Enable or disable a pre-encoded media rendition in its catalog. +/// +/// Disabling publishes a discontinuity and stops frames; resume video on a keyframe. +/// Audio currently returns an unsupported-format error, as in the shared importer. +/// Returns zero on success or a negative error. +#[unsafe(no_mangle)] +pub extern "C" fn moq_publish_media_set_enabled(media: u32, enabled: bool) -> i32 { + ffi::enter(move || State::lock().publish.media_set_enabled(ffi::parse_id(media)?, enabled)) +} + /// Mark a timeline break without lowering the advertised jitter or delay. /// /// Publishes a discontinuity marker; resumed frames must continue the broadcast media clock, diff --git a/rs/moq-c/src/bandwidth.rs b/rs/moq-c/src/bandwidth.rs index 19a1d2170ca..99b08584a31 100644 --- a/rs/moq-c/src/bandwidth.rs +++ b/rs/moq-c/src/bandwidth.rs @@ -13,6 +13,7 @@ pub(crate) struct Bandwidth { reservations: NonZeroSlab>, consumers: NonZeroSlab>, viewers: NonZeroSlab, + controls: NonZeroSlab, viewer: NonZeroSlab, } @@ -480,3 +481,126 @@ mod consumer_tests { State::lock().bandwidth.consumers.remove(id); } } + +/// Reserve up to `max_bps` for a pre-encoded media track, returning a reservation handle. +/// Close it with `moq_reservation_close`; it does not own the media handle. +#[unsafe(no_mangle)] +pub extern "C" fn moq_allocator_reserve_media(allocator: u32, media: u32, max_bps: u64) -> i32 { + ffi::enter(move || { + let mut state = State::lock(); + let demand = state.publish.media_demand(ffi::parse_id(media)?)?; + state.bandwidth.reserve(ffi::parse_id(allocator)?, &demand, max_bps) + }) +} + +/// How a rate control maps a reservation grant onto a sender's bitrate. +#[repr(C)] +pub struct moq_rate_policy { + /// Maximum bitrate the sender produces, in bits per second. + pub max_bps: u64, + /// Next lower rendition's maximum bitrate, when `has_lower` is true. + pub lower_bps: u64, + /// Whether this sender has a lower rendition; the lowest never disables. + pub has_lower: bool, +} + +/// What the sender should produce until its rate control changes again. +#[repr(C)] +pub struct moq_rate_target { + /// Whether to produce frames and advertise the rendition as enabled. + pub enabled: bool, + /// Bitrate to produce in bits per second, or 0 when disabled. + pub bitrate_bps: u64, +} + +impl From for moq_rate_target { + fn from(target: moq_mux::rate::Target) -> Self { + match target { + moq_mux::rate::Target::Enabled(rate) => Self { + enabled: true, + bitrate_bps: rate.as_bps(), + }, + moq_mux::rate::Target::Disabled => Self { + enabled: false, + bitrate_bps: 0, + }, + } + } +} + +/// Create a rate control starting at the policy's maximum bitrate. +#[unsafe(no_mangle)] +pub extern "C" fn moq_rate_control_create(policy: moq_rate_policy) -> i32 { + ffi::enter(move || { + let mut native = moq_mux::rate::Policy::new(moq_net::bandwidth::Rate::from_bps(policy.max_bps)); + native.lower = policy + .has_lower + .then(|| moq_net::bandwidth::Rate::from_bps(policy.lower_bps)); + State::lock() + .bandwidth + .controls + .insert(moq_mux::rate::Control::new(native)) + }) +} + +/// Read the current sender target, returning zero or a negative error. +/// +/// # Safety +/// - `target` must point to writable storage for one target. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_rate_control_target(control: u32, target: *mut moq_rate_target) -> i32 { + ffi::enter(move || { + let target = unsafe { target.as_mut() }.ok_or(Error::InvalidPointer)?; + *target = State::lock() + .bandwidth + .controls + .get(ffi::parse_id(control)?) + .ok_or(Error::NotFound)? + .target() + .into(); + Ok(()) + }) +} + +/// Feed a reservation's grant on every frame, returning 1 for a changed target, 0 to hold, or a negative error. +/// +/// Drops apply immediately; raises ramp and small moves are ignored. No estimate holds the +/// target. Disabling requires a probing session so the grant can recover. Apply a changed +/// target to your encoder and `moq_publish_media_set_enabled`; the control owns neither. +/// +/// # Safety +/// - `target` must point to writable storage, written only when the return value is 1. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_rate_control_update(control: u32, reservation: u32, target: *mut moq_rate_target) -> i32 { + ffi::enter(move || { + let target = unsafe { target.as_mut() }.ok_or(Error::InvalidPointer)?; + let mut state = State::lock(); + let reservation = state.bandwidth.reservation(ffi::parse_id(reservation)?)?; + let grant = reservation.consume(); + let control = state + .bandwidth + .controls + .get_mut(ffi::parse_id(control)?) + .ok_or(Error::NotFound)?; + control.set_probed(grant.probed()); + if let Some(next) = control.update(grant.peek(), kio::clock::now()) { + *target = next.into(); + Ok(1i32) + } else { + Ok(0i32) + } + }) +} + +/// Release a rate control without closing its reservation or media. +#[unsafe(no_mangle)] +pub extern "C" fn moq_rate_control_close(control: u32) -> i32 { + ffi::enter(move || { + State::lock() + .bandwidth + .controls + .remove(ffi::parse_id(control)?) + .ok_or(Error::NotFound)?; + Ok(()) + }) +} diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index 9eb045961a6..9fc5eddc906 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -196,9 +196,27 @@ impl Kept { } } -impl Abort for Kept> { +struct Media { + track: Box, + video_priority: Option, +} + +impl std::ops::Deref for Media { + type Target = import::Track; + fn deref(&self) -> &Self::Target { + &self.track + } +} + +impl std::ops::DerefMut for Media { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.track + } +} + +impl Abort for Kept { fn abort(self, err: moq_net::Error) { - self.inner.abort(err); + self.inner.track.abort(err); } } @@ -285,7 +303,7 @@ pub struct Publish { /// Single-codec media importers, fed timestamped frames. // Boxed because the codec splitters/imports are much larger than the container ones. - media: NonZeroSlab>>, + media: NonZeroSlab>, /// Container importers, fed whole chunks. A separate space from `media` because a /// container publishes several tracks and carries its own timing, so it takes no @@ -525,9 +543,17 @@ impl Publish { } /// Insert a media importer as a child of the broadcast `children` belongs to. - fn insert_media(&mut self, track: import::Track, children: Children) -> Result { + fn insert_media( + &mut self, + track: import::Track, + children: Children, + video_priority: Option, + ) -> Result { let media = Kept { - inner: Box::new(track), + inner: Media { + track: Box::new(track), + video_priority, + }, children: children.clone(), }; children.insert(&mut self.media, media, Child::Media) @@ -555,7 +581,7 @@ impl Publish { let track = import::Track::audio(request, catalog.reserve().with_interval(interval), init)?; let children = children.clone(); - self.insert_media(track, children) + self.insert_media(track, children, None) } /// `interval` as in [`Self::audio`]. @@ -575,9 +601,10 @@ impl Publish { let name = broadcast.unique_name(&format!(".{}", init.format)); let request = broadcast.reserve_track(name)?; + let priority = init.priority; let track = import::Track::video(request, catalog.reserve().with_interval(interval), init)?; let children = children.clone(); - self.insert_media(track, children) + self.insert_media(track, children, Some(priority)) } pub fn container(&mut self, broadcast: Id, init: import::ContainerInit) -> Result { @@ -598,6 +625,22 @@ impl Publish { children.insert(&mut self.containers, container, Child::Container) } + pub fn media_video_priority(&self, media: Id) -> Result { + self.media + .get(media) + .ok_or(Error::MediaNotFound)? + .video_priority + .ok_or_else(|| Error::InvalidConfig("the lower rendition is not video".into())) + } + + pub fn media_set_enabled(&mut self, media: Id, enabled: bool) -> Result<(), Error> { + self.media + .get_mut(media) + .ok_or(Error::MediaNotFound)? + .set_enabled(enabled)?; + Ok(()) + } + pub fn media_frame(&mut self, media: Id, data: &[u8], timestamp: hang::container::Timestamp) -> Result<(), Error> { let track = self.media.get_mut(media).ok_or(Error::MediaNotFound)?; track.decode(data, Some(timestamp))?; @@ -1057,7 +1100,7 @@ impl Publish { } = self.track_request.remove(request).ok_or(Error::NotFound)?; let catalog = self.catalog(broadcast)?; let track = import::Track::audio(request, catalog.reserve().with_interval(interval), init)?; - self.insert_media(track, children) + self.insert_media(track, children, None) } /// Accept a track request as a video track, returning a media handle like [`Self::video`]. @@ -1073,8 +1116,9 @@ impl Publish { request, } = self.track_request.remove(request).ok_or(Error::NotFound)?; let catalog = self.catalog(broadcast)?; + let priority = init.priority; let track = import::Track::video(request, catalog.reserve().with_interval(interval), init)?; - self.insert_media(track, children) + self.insert_media(track, children, Some(priority)) } /// Reject a track request, failing every subscriber waiting on it with `error_code`. diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index dc416e220b2..02c59a6874c 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -387,6 +387,7 @@ fn publish_audio(broadcast: u32, format: moq_audio_format, init: &[u8], label: O fn publish_video(broadcast: u32, format: moq_video_format, init: &[u8], label: Option<&[u8]>) -> i32 { let (label, label_len) = label_ptr(label); let config = moq_video_init { + lower: 0, format: format as u32, init: init_ptr(init), init_len: init.len(), @@ -8166,6 +8167,7 @@ fn track_request_media_carries_hints() { let request = id(request_cb.recv()); let h264 = h264_init(); let video_config = moq_video_init { + lower: 0, format: moq_video_format::MOQ_VIDEO_FORMAT_AVC3 as u32, init: h264.as_ptr(), init_len: h264.len(), @@ -8220,6 +8222,7 @@ fn invalid_hints_are_refused() { }; let video = |hint: moq_video_hint| { let config = moq_video_init { + lower: 0, format: moq_video_format::MOQ_VIDEO_FORMAT_AVC3 as u32, init: h264.as_ptr(), init_len: h264.len(), @@ -8329,3 +8332,83 @@ fn group_duration_hint_declares_the_join_interval() { assert_eq!(moq_publish_close(broadcast), 0); assert_eq!(moq_origin_close(origin), 0); } + +#[test] +fn preencoded_rungs_and_rate_control() { + let origin = id(moq_origin_create()); + let broadcast = publish_broadcast(origin, b"preencoded-rungs"); + let init = h264_init(); + let config = |lower| moq_video_init { + format: moq_video_format::MOQ_VIDEO_FORMAT_AVC3 as u32, + init: init.as_ptr(), + init_len: init.len(), + label: std::ptr::null(), + label_len: 0, + hint: moq_video_hint::default(), + lower, + }; + let low = id(unsafe { moq_publish_video(broadcast, &config(0)) }); + let high = id(unsafe { moq_publish_video(broadcast, &config(low)) }); + { + let state = State::lock(); + assert_eq!( + state + .publish + .media_video_priority(crate::ffi::parse_id(high).unwrap()) + .unwrap(), + state + .publish + .media_video_priority(crate::ffi::parse_id(low).unwrap()) + .unwrap() - 1 + ); + } + assert_eq!(moq_publish_media_set_enabled(high, false), 0); + assert_eq!( + published_catalog(broadcast) + .video + .renditions + .values() + .filter(|r| !r.enabled) + .count(), + 1 + ); + assert_eq!(moq_publish_media_set_enabled(high, true), 0); + assert!( + published_catalog(broadcast) + .video + .renditions + .values() + .all(|r| r.enabled) + ); + let (allocator, estimate) = test_allocator(); + let reservation = id(moq_allocator_reserve_media(allocator, high, 4_000_000)); + let control = id(moq_rate_control_create(moq_rate_policy { + max_bps: 4_000_000, + lower_bps: 2_000_000, + has_lower: true, + })); + let mut target = moq_rate_target { + enabled: false, + bitrate_bps: 0, + }; + assert_eq!(unsafe { moq_rate_control_target(control, &mut target) }, 0); + assert!(target.enabled); + assert_eq!(target.bitrate_bps, 4_000_000); + assert_eq!(unsafe { moq_rate_control_update(control, reservation, &mut target) }, 0); + estimate + .set(Some(moq_net::bandwidth::Rate::from_bps(1_000_000))) + .unwrap(); + assert_eq!(unsafe { moq_rate_control_update(control, reservation, &mut target) }, 1); + // Without a probing session a rung must stay on so its grant can recover. + assert!(target.enabled); + assert_eq!(target.bitrate_bps, 1_000_000); + assert_eq!(unsafe { moq_rate_control_update(control, reservation, &mut target) }, 0); + assert_eq!(moq_reservation_close(reservation), 0); + assert_eq!(moq_rate_control_close(control), 0); + assert_eq!(moq_allocator_close(allocator), 0); + assert_eq!(moq_publish_media_finish(high), 0); + assert!(unsafe { moq_publish_video(broadcast, &config(high)) } < 0); + assert_eq!(moq_publish_media_finish(low), 0); + assert_eq!(moq_publish_close(broadcast), 0); + assert_eq!(moq_origin_close(origin), 0); +} From 8d90d3c2fef36af277567b9799d6236c956c09b6 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 23:34:47 -0800 Subject: [PATCH 6/9] fix(c): keep public rate-control exports before tests --- rs/moq-c/src/bandwidth.rs | 156 +++++++++++++++++++------------------- 1 file changed, 78 insertions(+), 78 deletions(-) diff --git a/rs/moq-c/src/bandwidth.rs b/rs/moq-c/src/bandwidth.rs index 99b08584a31..488693d99f7 100644 --- a/rs/moq-c/src/bandwidth.rs +++ b/rs/moq-c/src/bandwidth.rs @@ -404,84 +404,6 @@ pub extern "C" fn moq_bandwidth_consumer_close(consumer: u32) -> i32 { }) } -#[cfg(test)] -mod consumer_tests { - use super::*; - use crate::ffi::ReturnCode; - - extern "C" fn changed(user_data: *mut std::ffi::c_void, code: i32) { - let sender = unsafe { Box::from_raw(user_data as *mut tokio::sync::mpsc::UnboundedSender) }; - sender.send(code).unwrap(); - } - - #[tokio::test] - async fn consumer_close_releases_demand_and_completes_pending_callback() { - tokio::time::pause(); - let producer = moq_net::bandwidth::Producer::new(); - let id = State::lock() - .bandwidth - .consumers - .insert(Arc::new(Consumer { - inner: std::sync::Mutex::new(Some(producer.consume())), - changed: Default::default(), - })) - .unwrap(); - let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); - let user_data = || Box::into_raw(Box::new(sender.clone())) as *mut std::ffi::c_void; - assert!(producer.demand().wanted()); - assert_eq!( - unsafe { moq_bandwidth_consumer_changed(id.into(), user_data(), Some(changed)) }, - 0 - ); - producer.set(Some(moq_net::bandwidth::Rate::from_bps(321))).unwrap(); - assert_eq!(receiver.recv().await, Some(1)); - let (mut bps, mut present) = (0, false); - assert_eq!( - unsafe { moq_bandwidth_consumer_peek(id.into(), &mut bps, &mut present) }, - 0 - ); - assert!(present); - assert_eq!(bps, 321); - assert_eq!( - unsafe { moq_bandwidth_consumer_changed(id.into(), user_data(), Some(changed)) }, - 0 - ); - assert_eq!(moq_bandwidth_consumer_close(id.into()), 0); - assert!( - !producer.demand().wanted(), - "closing releases demand before the callback runs" - ); - assert!(receiver.recv().await.unwrap() < 0); - } - - #[tokio::test] - async fn changed_cleanup_panic_still_delivers_callback() { - let producer = moq_net::bandwidth::Producer::new(); - let consumer = Arc::new(Consumer { - inner: std::sync::Mutex::new(Some(producer.consume())), - changed: Default::default(), - }); - let id = State::lock().bandwidth.consumers.insert(consumer.clone()).unwrap(); - let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); - let user_data = Box::into_raw(Box::new(sender)) as *mut std::ffi::c_void; - assert_eq!( - unsafe { moq_bandwidth_consumer_changed(id.into(), user_data, Some(changed)) }, - 0 - ); - // Poison the slot the wait clears once it completes. - let poisoner = consumer.clone(); - std::thread::spawn(move || { - let _pending = poisoner.changed.lock().unwrap(); - panic!("poison the pending wait"); - }) - .join() - .unwrap_err(); - producer.set(Some(moq_net::bandwidth::Rate::from_bps(321))).unwrap(); - assert_eq!(receiver.recv().await, Some(Error::Panic.code())); - State::lock().bandwidth.consumers.remove(id); - } -} - /// Reserve up to `max_bps` for a pre-encoded media track, returning a reservation handle. /// Close it with `moq_reservation_close`; it does not own the media handle. #[unsafe(no_mangle)] @@ -604,3 +526,81 @@ pub extern "C" fn moq_rate_control_close(control: u32) -> i32 { Ok(()) }) } + +#[cfg(test)] +mod consumer_tests { + use super::*; + use crate::ffi::ReturnCode; + + extern "C" fn changed(user_data: *mut std::ffi::c_void, code: i32) { + let sender = unsafe { Box::from_raw(user_data as *mut tokio::sync::mpsc::UnboundedSender) }; + sender.send(code).unwrap(); + } + + #[tokio::test] + async fn consumer_close_releases_demand_and_completes_pending_callback() { + tokio::time::pause(); + let producer = moq_net::bandwidth::Producer::new(); + let id = State::lock() + .bandwidth + .consumers + .insert(Arc::new(Consumer { + inner: std::sync::Mutex::new(Some(producer.consume())), + changed: Default::default(), + })) + .unwrap(); + let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + let user_data = || Box::into_raw(Box::new(sender.clone())) as *mut std::ffi::c_void; + assert!(producer.demand().wanted()); + assert_eq!( + unsafe { moq_bandwidth_consumer_changed(id.into(), user_data(), Some(changed)) }, + 0 + ); + producer.set(Some(moq_net::bandwidth::Rate::from_bps(321))).unwrap(); + assert_eq!(receiver.recv().await, Some(1)); + let (mut bps, mut present) = (0, false); + assert_eq!( + unsafe { moq_bandwidth_consumer_peek(id.into(), &mut bps, &mut present) }, + 0 + ); + assert!(present); + assert_eq!(bps, 321); + assert_eq!( + unsafe { moq_bandwidth_consumer_changed(id.into(), user_data(), Some(changed)) }, + 0 + ); + assert_eq!(moq_bandwidth_consumer_close(id.into()), 0); + assert!( + !producer.demand().wanted(), + "closing releases demand before the callback runs" + ); + assert!(receiver.recv().await.unwrap() < 0); + } + + #[tokio::test] + async fn changed_cleanup_panic_still_delivers_callback() { + let producer = moq_net::bandwidth::Producer::new(); + let consumer = Arc::new(Consumer { + inner: std::sync::Mutex::new(Some(producer.consume())), + changed: Default::default(), + }); + let id = State::lock().bandwidth.consumers.insert(consumer.clone()).unwrap(); + let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + let user_data = Box::into_raw(Box::new(sender)) as *mut std::ffi::c_void; + assert_eq!( + unsafe { moq_bandwidth_consumer_changed(id.into(), user_data, Some(changed)) }, + 0 + ); + // Poison the slot the wait clears once it completes. + let poisoner = consumer.clone(); + std::thread::spawn(move || { + let _pending = poisoner.changed.lock().unwrap(); + panic!("poison the pending wait"); + }) + .join() + .unwrap_err(); + producer.set(Some(moq_net::bandwidth::Rate::from_bps(321))).unwrap(); + assert_eq!(receiver.recv().await, Some(Error::Panic.code())); + State::lock().bandwidth.consumers.remove(id); + } +} From 645ef1392fa567ab61e6dcfb0c6a886ee3a031f8 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 23:36:05 -0800 Subject: [PATCH 7/9] docs(c): format simulcast migration notes --- rs/moq-c/MIGRATE.md | 1 - 1 file changed, 1 deletion(-) diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index 9c2d4ee136e..dcec0fcaa34 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -14,7 +14,6 @@ and `moq_allocator_reserve_media` with the new `moq_rate_control_*` handles to adapt an external encoder to its reservation. Close controls and reservations separately. No wire format changes. - ### Separate datagram tracks Create a separate producer with `moq_publish_datagrams` and `moq_datagram_info`; replace `moq_publish_track_datagram` with `moq_publish_datagrams_append` on that handle, or `moq_publish_datagrams_insert` for an explicit sequence. `moq_consume_datagrams` now takes a subscriber priority before its callback and never subscribes to a stream track. Use `moq_publish_datagrams_demand` and `moq_datagram_demand_priority` for aggregate priority, and `moq_publish_datagrams_requests` / `moq_datagram_request_accept` for on-demand publishing. Finish or abort datagram producers separately. A zeroed datagram info is untimed, unlike the microsecond default of stream-track info. `moq_consume_datagrams` returns a negative code at once when the broadcast has neither the datagram track nor a datagram request handler, and a remote name without one ends its callback with a not-found error. From b86d6ece669bf4097f9f6f2efa3b432aad93546d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 23:37:24 -0800 Subject: [PATCH 8/9] docs(c): clarify audio enablement refusal --- rs/moq-c/src/api.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index efbec7b9644..9dcf04a87f5 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -2858,7 +2858,7 @@ pub unsafe extern "C" fn moq_publish_media_frame( /// Enable or disable a pre-encoded media rendition in its catalog. /// /// Disabling publishes a discontinuity and stops frames; resume video on a keyframe. -/// Audio currently returns an unsupported-format error, as in the shared importer. +/// Audio importers reject this operation. /// Returns zero on success or a negative error. #[unsafe(no_mangle)] pub extern "C" fn moq_publish_media_set_enabled(media: u32, enabled: bool) -> i32 { From 0259171f38f01d9305ff00c60fa1f4622ce96e52 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 23:45:24 -0800 Subject: [PATCH 9/9] fix(c): bind rate controls to a reservation and cover probing transitions --- doc/lib/c/index.md | 2 +- rs/moq-c/README.md | 4 +- rs/moq-c/c-tests/rate-control.c | 11 +++-- rs/moq-c/src/bandwidth.rs | 76 +++++++++++++++++++++++++++------ rs/moq-c/src/test.rs | 19 +++++---- 5 files changed, 81 insertions(+), 31 deletions(-) diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index d3d62b75d85..d70e0812f5e 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -88,7 +88,7 @@ across restarts, and raise `epoch` on each: readers stitch every route of one in together, so restarting the sequences under an old instance splices unrelated groups into their tracks. -Raw video encoders take an exact numerator/denominator frame rate, such as 30000/1001. Publication track names stay separate from codec settings. For simulcast, give each rendition the next one down as the `lower` handle in its `moq_video_encode_options`: it stops encoding, advertised as disabled, while its bandwidth grant cannot fund it, and resumes once the grant recovers. A rung only disables while the session probes for bandwidth, which on native transports takes moq-quic with BBR3. For pre-encoded video, publish from the lowest rendition up and set `moq_video_init.lower` to the next lower media handle. Reserve each track with `moq_allocator_reserve_media`, then feed its reservation to `moq_rate_control_update` on every frame. Apply changed targets to your encoder and `moq_publish_media_set_enabled`, resuming video on a keyframe; close the control and reservation separately when done. +Raw video encoders take an exact numerator/denominator frame rate, such as 30000/1001. Publication track names stay separate from codec settings. For simulcast, give each rendition the next one down as the `lower` handle in its `moq_video_encode_options`: it stops encoding, advertised as disabled, while its bandwidth grant cannot fund it, and resumes once the grant recovers. A rung only disables while the session probes for bandwidth, which on native transports takes moq-quic with BBR3. For pre-encoded video, publish from the lowest rendition up and set `moq_video_init.lower` to the next lower media handle. Reserve each track with `moq_allocator_reserve_media`, then bind its reservation with `moq_rate_control_create` and call `moq_rate_control_update` on every frame. Apply changed targets to your encoder and `moq_publish_media_set_enabled`, resuming video on a keyframe; close the control and reservation separately when done. ## Things to know diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index 8d48018e4f7..b87d27ffb80 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -182,9 +182,9 @@ the catalog and marks a discontinuity when disabling; resume on a keyframe. Audio importers do not support this toggle. Reserve each media track with `moq_allocator_reserve_media`. Create a -`moq_rate_control_create` handle with `moq_rate_policy.max_bps` and, for higher +`moq_rate_control_create` handle bound to the reservation, with `moq_rate_policy.max_bps` and, for higher rungs, `has_lower` and `lower_bps`. Read its initial `moq_rate_control_target`, -then call `moq_rate_control_update` with the reservation on every frame, +then call `moq_rate_control_update` on every frame, including while disabled. A return of 1 writes a changed target; 0 holds the last target; a negative return is an error. Apply the target's `bitrate_bps` to your encoder and `enabled` through `moq_publish_media_set_enabled`. diff --git a/rs/moq-c/c-tests/rate-control.c b/rs/moq-c/c-tests/rate-control.c index 983d53b2e63..89bb5ad3e65 100644 --- a/rs/moq-c/c-tests/rate-control.c +++ b/rs/moq-c/c-tests/rate-control.c @@ -6,12 +6,11 @@ int main(void) { moq_video_init video = {0}; assert(video.lower == 0); moq_rate_policy policy = {.max_bps = 4000000, .lower_bps = 2000000, .has_lower = true}; - int32_t control = moq_rate_control_create(policy); - assert(control > 0); + // A control refuses an invalid reservation at setup. + assert(moq_rate_control_create(0, policy) < 0); moq_rate_target target = {0}; - assert(moq_rate_control_target((uint32_t)control, &target) == 0); - assert(target.enabled && target.bitrate_bps == policy.max_bps); - assert(moq_rate_control_close((uint32_t)control) == 0); - assert(moq_rate_control_target((uint32_t)control, &target) < 0); + assert(moq_rate_control_target(0, &target) < 0); + assert(moq_rate_control_update(0, &target) < 0); + assert(moq_rate_control_close(0) < 0); return 0; } diff --git a/rs/moq-c/src/bandwidth.rs b/rs/moq-c/src/bandwidth.rs index 488693d99f7..0f8faa7c75c 100644 --- a/rs/moq-c/src/bandwidth.rs +++ b/rs/moq-c/src/bandwidth.rs @@ -13,10 +13,26 @@ pub(crate) struct Bandwidth { reservations: NonZeroSlab>, consumers: NonZeroSlab>, viewers: NonZeroSlab, - controls: NonZeroSlab, + controls: NonZeroSlab, viewer: NonZeroSlab, } +struct RateControl { + inner: moq_mux::rate::Control, + grant: moq_net::bandwidth::Consumer, +} + +impl RateControl { + fn update(&mut self) -> Option { + self.apply(self.grant.peek(), self.grant.probed()) + } + + fn apply(&mut self, grant: Option, probed: bool) -> Option { + self.inner.set_probed(probed); + self.inner.update(grant, kio::clock::now()) + } +} + impl Bandwidth { pub fn insert(&mut self, allocator: moq_net::bandwidth::Allocator) -> Result { self.allocators.insert(allocator) @@ -450,18 +466,20 @@ impl From for moq_rate_target { } } -/// Create a rate control starting at the policy's maximum bitrate. +/// Create a rate control following this reservation, starting at the policy's maximum bitrate. #[unsafe(no_mangle)] -pub extern "C" fn moq_rate_control_create(policy: moq_rate_policy) -> i32 { +pub extern "C" fn moq_rate_control_create(reservation: u32, policy: moq_rate_policy) -> i32 { ffi::enter(move || { let mut native = moq_mux::rate::Policy::new(moq_net::bandwidth::Rate::from_bps(policy.max_bps)); native.lower = policy .has_lower .then(|| moq_net::bandwidth::Rate::from_bps(policy.lower_bps)); - State::lock() - .bandwidth - .controls - .insert(moq_mux::rate::Control::new(native)) + let mut state = State::lock(); + let grant = state.bandwidth.reservation(ffi::parse_id(reservation)?)?.consume(); + state.bandwidth.controls.insert(RateControl { + inner: moq_mux::rate::Control::new(native), + grant, + }) }) } @@ -478,34 +496,33 @@ pub unsafe extern "C" fn moq_rate_control_target(control: u32, target: *mut moq_ .controls .get(ffi::parse_id(control)?) .ok_or(Error::NotFound)? + .inner .target() .into(); Ok(()) }) } -/// Feed a reservation's grant on every frame, returning 1 for a changed target, 0 to hold, or a negative error. +/// Follow the bound reservation's grant on every frame, returning 1 for a changed target, 0 to hold, or a negative error. /// /// Drops apply immediately; raises ramp and small moves are ignored. No estimate holds the /// target. Disabling requires a probing session so the grant can recover. Apply a changed -/// target to your encoder and `moq_publish_media_set_enabled`; the control owns neither. +/// target to your encoder and `moq_publish_media_set_enabled`. Closing the reservation holds +/// the last target; the control owns neither the reservation nor media. /// /// # Safety /// - `target` must point to writable storage, written only when the return value is 1. #[unsafe(no_mangle)] -pub unsafe extern "C" fn moq_rate_control_update(control: u32, reservation: u32, target: *mut moq_rate_target) -> i32 { +pub unsafe extern "C" fn moq_rate_control_update(control: u32, target: *mut moq_rate_target) -> i32 { ffi::enter(move || { let target = unsafe { target.as_mut() }.ok_or(Error::InvalidPointer)?; let mut state = State::lock(); - let reservation = state.bandwidth.reservation(ffi::parse_id(reservation)?)?; - let grant = reservation.consume(); let control = state .bandwidth .controls .get_mut(ffi::parse_id(control)?) .ok_or(Error::NotFound)?; - control.set_probed(grant.probed()); - if let Some(next) = control.update(grant.peek(), kio::clock::now()) { + if let Some(next) = control.update() { *target = next.into(); Ok(1i32) } else { @@ -529,6 +546,37 @@ pub extern "C" fn moq_rate_control_close(control: u32) -> i32 { #[cfg(test)] mod consumer_tests { + #[tokio::test(start_paused = true)] + async fn rate_control_probing_disables_and_recovers() { + use moq_mux::rate::{Control, Policy, Target}; + use moq_net::bandwidth::Rate; + let estimate = moq_net::bandwidth::Producer::new(); + let mut policy = Policy::new(Rate::from_bps(6_000_000)); + policy.lower = Some(Rate::from_bps(2_000_000)); + let mut control = RateControl { + inner: Control::new(policy), + grant: estimate.consume(), + }; + assert_eq!( + control.apply(Some(Rate::from_bps(3_000_000)), true), + Some(Target::Disabled) + ); + assert_eq!(control.apply(None, true), None); + tokio::time::advance(std::time::Duration::from_secs(4)).await; + assert!(matches!( + control.apply(Some(Rate::from_bps(6_000_000)), true), + Some(Target::Enabled(_)) + )); + assert_eq!( + control.apply(Some(Rate::from_bps(3_000_000)), true), + Some(Target::Disabled) + ); + assert!(matches!( + control.apply(Some(Rate::from_bps(3_000_000)), false), + Some(Target::Enabled(_)) + )); + } + use super::*; use crate::ffi::ReturnCode; diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 02c59a6874c..fd5bd073ac7 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -8382,11 +8382,14 @@ fn preencoded_rungs_and_rate_control() { ); let (allocator, estimate) = test_allocator(); let reservation = id(moq_allocator_reserve_media(allocator, high, 4_000_000)); - let control = id(moq_rate_control_create(moq_rate_policy { - max_bps: 4_000_000, - lower_bps: 2_000_000, - has_lower: true, - })); + let control = id(moq_rate_control_create( + reservation, + moq_rate_policy { + max_bps: 4_000_000, + lower_bps: 2_000_000, + has_lower: true, + }, + )); let mut target = moq_rate_target { enabled: false, bitrate_bps: 0, @@ -8394,15 +8397,15 @@ fn preencoded_rungs_and_rate_control() { assert_eq!(unsafe { moq_rate_control_target(control, &mut target) }, 0); assert!(target.enabled); assert_eq!(target.bitrate_bps, 4_000_000); - assert_eq!(unsafe { moq_rate_control_update(control, reservation, &mut target) }, 0); + assert_eq!(unsafe { moq_rate_control_update(control, &mut target) }, 0); estimate .set(Some(moq_net::bandwidth::Rate::from_bps(1_000_000))) .unwrap(); - assert_eq!(unsafe { moq_rate_control_update(control, reservation, &mut target) }, 1); + assert_eq!(unsafe { moq_rate_control_update(control, &mut target) }, 1); // Without a probing session a rung must stay on so its grant can recover. assert!(target.enabled); assert_eq!(target.bitrate_bps, 1_000_000); - assert_eq!(unsafe { moq_rate_control_update(control, reservation, &mut target) }, 0); + assert_eq!(unsafe { moq_rate_control_update(control, &mut target) }, 0); assert_eq!(moq_reservation_close(reservation), 0); assert_eq!(moq_rate_control_close(control), 0); assert_eq!(moq_allocator_close(allocator), 0);