Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/lib/c/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,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 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

Expand Down
4 changes: 0 additions & 4 deletions quest/m1/c/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
30 changes: 0 additions & 30 deletions quest/m1/c/api-gaps.md

This file was deleted.

10 changes: 10 additions & 0 deletions rs/moq-c/MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ 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.

### Announcements are a listing ([#7678](https://github.com/moq-dev/moq/pull/7678))

`moq_announce_kind` is `MOQ_ANNOUNCE_KIND_PRESENT` (0) or `MOQ_ANNOUNCE_KIND_ABSENT` (1), and `moq_announce_event` loses `predecessor` and `predecessor_len`, changing the C ABI.
Expand Down
21 changes: 21 additions & 0 deletions rs/moq-c/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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` on every frame,
including while disabled. It returns 0 or a negative error; `target.changed`
is true for a new target and false to hold the last one. 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.
16 changes: 16 additions & 0 deletions rs/moq-c/c-tests/rate-control.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Exercise rate-control records and handle ownership across the generated C ABI.
#include <moq.h>
#include <assert.h>

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};
// 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(0, &target) < 0);
assert(moq_rate_control_update(0, &target) < 0);
assert(moq_rate_control_close(0) < 0);
return 0;
}
19 changes: 19 additions & 0 deletions rs/moq-c/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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].
Expand Down Expand Up @@ -2622,6 +2625,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()?))
}

Expand Down Expand Up @@ -2849,6 +2858,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 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 {
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,
Expand Down
185 changes: 185 additions & 0 deletions rs/moq-c/src/bandwidth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,26 @@ pub(crate) struct Bandwidth {
reservations: NonZeroSlab<Arc<moq_net::bandwidth::Reservation>>,
consumers: NonZeroSlab<Arc<Consumer>>,
viewers: NonZeroSlab<moq_net::bandwidth::Viewers>,
controls: NonZeroSlab<RateControl>,
viewer: NonZeroSlab<moq_net::bandwidth::Viewer>,
}

struct RateControl {
inner: moq_mux::rate::Control,
grant: moq_net::bandwidth::Consumer,
}

impl RateControl {
fn update(&mut self) -> Option<moq_mux::rate::Target> {
self.apply(self.grant.peek(), self.grant.probed())
}

fn apply(&mut self, grant: Option<moq_net::bandwidth::Rate>, probed: bool) -> Option<moq_mux::rate::Target> {
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<Id, Error> {
self.allocators.insert(allocator)
Expand Down Expand Up @@ -403,8 +420,176 @@ pub extern "C" fn moq_bandwidth_consumer_close(consumer: u32) -> i32 {
})
}

/// 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,
/// Whether `moq_rate_control_update` changed the target; always false from `moq_rate_control_target`.
pub changed: bool,
}

impl From<moq_mux::rate::Target> 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(),
changed: false,
},
moq_mux::rate::Target::Disabled => Self {
enabled: false,
bitrate_bps: 0,
changed: false,
},
}
}
}

/// Create a rate control following this reservation, starting at the policy's maximum bitrate.
///
/// A zero `max_bps` is rejected with `MOQ_ERROR_INVALID_CONFIG`.
#[unsafe(no_mangle)]
pub extern "C" fn moq_rate_control_create(reservation: u32, policy: moq_rate_policy) -> i32 {
ffi::enter(move || {
if policy.max_bps == 0 {
return Err(Error::InvalidConfig("max_bps must be nonzero".into()));
}
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));
Comment thread
kixelated marked this conversation as resolved.
Resolved
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,
})
})
}

/// 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)?
.inner
.target()
.into();
Ok(())
})
}

/// Follow the bound reservation's grant on every frame, returning zero or a negative error.
///
/// `target.changed` is true when the target changed and false to hold the last target.
///
/// 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`. Closing the reservation holds
/// the last target; the control owns neither the reservation nor media.
///
/// # Safety
/// - `target` must point to writable storage; its other fields are written only when `changed` is true.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn moq_rate_control_update(control: u32, target: *mut moq_rate_target) -> i32 {
Comment thread
kixelated marked this conversation as resolved.
Resolved
ffi::enter(move || {
let target = unsafe { target.as_mut() }.ok_or(Error::InvalidPointer)?;
let mut state = State::lock();
let control = state
.bandwidth
.controls
.get_mut(ffi::parse_id(control)?)
.ok_or(Error::NotFound)?;
match control.update() {
Some(next) => {
*target = next.into();
target.changed = true;
}
None => target.changed = false,
}
Ok(())
})
}

/// 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(())
})
}

#[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;

Expand Down
Loading
Loading