From fc66df68d60908b9d3034d94274cdcc4fa255e4a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:25:57 -0800 Subject: [PATCH 1/3] chore(quest): claim quest/m2/gateway-ingest.md Quest-Claim: c123023006aac22a From 3c82003800d9fdd5d0e2e356fbd34e8941996b51 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 11:12:31 -0800 Subject: [PATCH 2/3] feat(gateways)!: share one moq_mux::Ingest and moq_net::bandwidth::Limit Every protocol gateway takes ingest settings as one moq_mux::Ingest instead of per-gateway max-age, bandwidth, and linger setters, and the live rate cap moves from moq-webrtc to moq_net::bandwidth. WHIP, WHEP, and SRT dial-out pushes take request structs so later per-session knobs are fields, and moq-webrtc's server config names its socket. Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 1 - quest/m2/api-shape/apps.md | 2 +- quest/m2/gateway-ingest.md | 37 -------- quest/m3/release/api-review.md | 2 +- quest/m3/rtc-pacing.md | 14 ++- quest/m3/srt-rate-handle.md | 9 +- quest/m3/stats/rust.md | 2 +- rs/moq-cli/src/hls.rs | 18 +--- rs/moq-cli/src/main.rs | 22 ++--- rs/moq-cli/src/moq.rs | 18 +--- rs/moq-cli/src/rtc.rs | 19 ++-- rs/moq-cli/src/rtmp.rs | 26 ++---- rs/moq-cli/src/rtsp.rs | 5 +- rs/moq-cli/src/srt.rs | 31 ++----- rs/moq-mux/src/ingest.rs | 46 ++++++++++ rs/moq-mux/src/lib.rs | 4 + rs/moq-net/src/model/bandwidth.rs | 137 ++++++++++++++++++++++++++++ rs/moq-rtmp/src/dial.rs | 109 ++++++++-------------- rs/moq-rtmp/src/server.rs | 75 +++++----------- rs/moq-srt/src/dial.rs | 100 +++++++-------------- rs/moq-srt/src/server.rs | 88 ++++-------------- rs/moq-webrtc/src/client/mod.rs | 44 +++------ rs/moq-webrtc/src/client/whep.rs | 12 +-- rs/moq-webrtc/src/lib.rs | 41 +++++---- rs/moq-webrtc/src/rate.rs | 144 ++++-------------------------- rs/moq-webrtc/src/server/mod.rs | 69 ++++++-------- rs/moq-webrtc/src/server/whep.rs | 44 ++++++--- rs/moq-webrtc/src/server/whip.rs | 90 +++++++++++-------- rs/moq-webrtc/src/session.rs | 38 ++++---- 29 files changed, 542 insertions(+), 705 deletions(-) delete mode 100644 quest/m2/gateway-ingest.md create mode 100644 rs/moq-mux/src/ingest.rs diff --git a/quest/m2/README.md b/quest/m2/README.md index 1ae9ab6e886..8ce6e8f1127 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -198,7 +198,6 @@ quests that require them. - [moq-quic drops inherited surfaces with no consumer](/quest/m2/moq-quic-unused-surface.md) - unused accept, connection, and stream-id surfaces leave moq-quic's public API before the cut - [No sentinel values in public API](/quest/m2/no-sentinels.md) - receive windows, cache durations, reconnect timeouts, and the FFI test clock use `Option` instead of a huge value or zero - [moq-video takes devices, not environment variables](/quest/m2/video-devices.md) - VA-API and V4L2 device paths are config fields, and `moq_video::ENV` never ships -- [Gateways share one ingest config and one rate cap](/quest/m2/gateway-ingest.md) - `moq_mux::Ingest` replaces 18 per-gateway setters, and the live rate cap moves to `moq_net::bandwidth` - [Native playout sync keeps tracks decoupled](/quest/m2/mux-sync.md) - `moq_mux::timeline` becomes `moq_mux::sync`, and one slow track no longer stalls or moves another - [JS time values are types, not numbers](/quest/m2/js-time-types.md) - every public JS duration and instant is a `Clock.Duration` or `Clock.Instant` object, so a unit mistake fails to compile - [Small API fixes before the cut](/quest/m2/api-shape/README.md) - one path and one spelling per item, names by role, and no dead or wrong-role public surface across net, transport, media, native, apps, JS, and bindings diff --git a/quest/m2/api-shape/apps.md b/quest/m2/api-shape/apps.md index 64ffd89b20a..ad37ffc45db 100644 --- a/quest/m2/api-shape/apps.md +++ b/quest/m2/api-shape/apps.md @@ -37,5 +37,5 @@ Found by the 2026-11-07 API shape audit (apps); see the [epic](/quest/m2/api-shape/README.md). Decided 2026-11-07 (maintainer): ✅ hide `p2p` until m4 (rejected: keep it public; delete it). Gateway ingest -is [gateway-ingest](/quest/m2/gateway-ingest.md). Downstream code that +shares `moq_mux::Ingest` already. Downstream code that matches the deleted webrtc variants loses only dead arms. diff --git a/quest/m2/gateway-ingest.md b/quest/m2/gateway-ingest.md deleted file mode 100644 index 1316f2fd5ee..00000000000 --- a/quest/m2/gateway-ingest.md +++ /dev/null @@ -1,37 +0,0 @@ -# [M] Gateways share one ingest config and one rate cap - -## Goal - -Every protocol gateway configures ingest the same way, and no setter applies -to a direction it cannot affect: - -- `moq_mux::Ingest { max_age, bandwidth, linger }` (`#[non_exhaustive]`, - `Default`) replaces the 18 `with_max_age`/`with_bandwidth`/`with_linger` - setters and fields on moq-rtmp's and moq-srt's `Client` and `Publish`, and - moq-webrtc's `server::Config` and `client::Config`. It is taken by - `rtmp::Publish::accept`, `rtmp::Client::pull`, `srt::Publish::accept`, - `srt::Client::pull`, `moq_webrtc::whip::Request`, and - `moq_rtsp::Client::pull`. Egress keeps its own setters on `publish`. -- `moq_webrtc::rate::{Cap, Limit}` move to `moq_net::bandwidth` beside - `Rate`, so WHIP, WHEP, SRT, and the relay's grant caps share one live cap - handle. - -## Plan - -Found by the 2026-11-07 API shape audit (apps). Today a bidirectional client -documents its ingest setters as "pull direction only", so setting -`with_linger` and then calling `publish` is silently ignored. moq-rtsp -publishes with fixed defaults and gains the same knobs. Land before the cut -so moq-webrtc never ships its own `Cap`/`Limit` and moq-srt never copies -them: [srt-rate-handle](/quest/m3/srt-rate-handle.md) and -[rtc-pacing](/quest/m3/rtc-pacing.md) take `bandwidth::Limit`. moq-cli's -`import --max-age`/`--linger` build one `Ingest`. Whether -`moq_quic::limits::Rate`'s `Unlimited` variant can become `Option` is -out of scope. - -Added 2026-11-07 (maintainer, /quest-plan from the API sweep of open PRs and remaining quests): the per-session request shapes settle here too, so m3's rate, report, and wire work adds fields instead of `with_*` setters after the cut. - -- `whep::accept` takes a `whep::Request` (`#[non_exhaustive]`), mirroring `whip::Request`, moved here from [rtc-pacing](/quest/m3/rtc-pacing.md), so its rate handle is additive. -- moq-webrtc's `server::Config.udp_bind` becomes `socket: server::Socket` (`#[non_exhaustive]`, only `Bind(SocketAddr)` today), so a fed socket from [one port](/quest/m3/one-port/README.md) is additive. -- moq-srt's dial-out `Client::publish` (`rs/moq-srt/src/dial.rs`), an egress that takes neither `Ingest` nor a request today, takes a `#[non_exhaustive]` `dial::Publish` request (the path, with room for m3's rate `Limit`), so [srt-rate-handle](/quest/m3/srt-rate-handle.md) reaches egress additively. -- Per-session knobs m3 adds (the rate `Limit`, report and echo, the SRT `Wire`) are fields on these request structs or on `Ingest`, never new setters on `Client` or `Publish`. diff --git a/quest/m3/release/api-review.md b/quest/m3/release/api-review.md index 67bdabc584e..90b543a53c5 100644 --- a/quest/m3/release/api-review.md +++ b/quest/m3/release/api-review.md @@ -38,7 +38,7 @@ consumers in this repository and its downstream applications. Mean 6.9; three clusters were restrictive (the native playout clock, JS duration units, and moq-video's environment knobs). Its approved changes are m2 quests (route-roles, js-time-types, mux-sync, no-sentinels, video-devices, -gateway-ingest, and the [api-shape epic](/quest/m2/api-shape/README.md)), +gateway-ingest (landed), and the [api-shape epic](/quest/m2/api-shape/README.md)), two m1 quests, and plan edits. Check first, next run: surfaces `just api-diff` cannot see (GStreamer properties, CLI flags and env, MIGRATE drift) and publish versions of packages exempt from the cut's version. `just diff --git a/quest/m3/rtc-pacing.md b/quest/m3/rtc-pacing.md index 5b8b589dcea..62b21304542 100644 --- a/quest/m3/rtc-pacing.md +++ b/quest/m3/rtc-pacing.md @@ -58,16 +58,14 @@ WHEP enforcement needs it and nobody owned it. Public API: a rate handle on moq-webrtc's WHEP server. Decided 2026-10-30 (maintainer): `whep::accept` takes the same shape as `whip::accept`, a -`whep::Request` struct, rather than a fifth argument. That struct lands -first in [gateway-ingest](/quest/m2/gateway-ingest.md), `#[non_exhaustive]`, -so this quest adds a `rate: Option` field to it, never a +`whep::Request` struct, rather than a fifth argument. That struct exists, +`#[non_exhaustive]`, so this quest adds a `rate: Option` +field to it, as `whip::Request` has, never a `with_rate` setter (2026-11-07, maintainer, /quest-plan from the API sweep of open PRs and remaining quests). The handle -is `moq_net::bandwidth::Limit`, which replaces moq-webrtc's -`rate::{Cap, Limit}` in [gateway-ingest](/quest/m2/gateway-ingest.md) -(2026-11-07, maintainer, /quest-plan from the API shape audit). Wire: none. - -Changed 2026-11-07 (maintainer, /quest-plan from the API sweep of open PRs and remaining quests): `whep::Request` itself lands before the cut in [gateway-ingest](/quest/m2/gateway-ingest.md); this quest adds its rate field. +is `moq_net::bandwidth::Limit`, which replaced moq-webrtc's own +`rate::{Cap, Limit}` (2026-11-07, maintainer, /quest-plan from the API shape +audit). Wire: none. ## Related diff --git a/quest/m3/srt-rate-handle.md b/quest/m3/srt-rate-handle.md index c28d78420d5..f083c0c9811 100644 --- a/quest/m3/srt-rate-handle.md +++ b/quest/m3/srt-rate-handle.md @@ -52,10 +52,11 @@ enforcement needs it and nobody owned it. included, stays under the cap is untouched; under the cap nothing changes. Public API: a rate handle and a rate-limit close reason on moq-srt's server. -The handle is `moq_net::bandwidth::Limit`, shared with WHIP, WHEP, and the -relay's grant caps since [gateway-ingest](/quest/m2/gateway-ingest.md) -(2026-11-07, maintainer, /quest-plan from the API shape audit), not a -moq-srt copy. Wire: none. +The handle is `moq_net::bandwidth::Limit`, the one WHIP takes in +`whip::Request.rate` (2026-11-07, maintainer, /quest-plan from the API shape +audit), not a moq-srt copy. It reaches a server ingest as a field on +`moq_mux::Ingest` or a new `#[non_exhaustive]` request, and a dial-out push +as a field on `moq_srt::dial::Publish`, never as a `with_*` setter. Wire: none. ## Required diff --git a/quest/m3/stats/rust.md b/quest/m3/stats/rust.md index a6c57e0ce9a..c57054f68b5 100644 --- a/quest/m3/stats/rust.md +++ b/quest/m3/stats/rust.md @@ -63,7 +63,7 @@ TS release section holds the drops (from [moq-dev/moq#6654](https://github.com/moq-dev/moq/pull/6654)). -Changed 2026-11-07 (maintainer, /quest-plan from the API sweep of open PRs and remaining quests): a gateway takes its report and echo as fields on its request struct or on `moq_mux::Ingest` ([gateway-ingest](/quest/m2/gateway-ingest.md)), not as `with_report` and `with_echo` builders. +Changed 2026-11-07 (maintainer, /quest-plan from the API sweep of open PRs and remaining quests): a gateway takes its report and echo as fields on its request struct or on `moq_mux::Ingest`, not as `with_report` and `with_echo` builders. ## Related diff --git a/rs/moq-cli/src/hls.rs b/rs/moq-cli/src/hls.rs index fee57d0b649..fd14692eacd 100644 --- a/rs/moq-cli/src/hls.rs +++ b/rs/moq-cli/src/hls.rs @@ -163,13 +163,7 @@ impl Tls { /// Pull a remote HLS/LL-HLS playlist (URL or file path) into the Origin under `target.name`, /// announced under `instance`. Once the playlist ends, serve the finished broadcast for the linger. pub async fn import(target: ImportTarget, args: ImportArgs, instance: moq_net::Instance) -> anyhow::Result<()> { - let ImportTarget { - origin, - name, - max_age, - linger, - bandwidth, - } = target; + let ImportTarget { origin, name, ingest } = target; // Held through the linger, so the finished broadcast stays announced while it serves the tail. let route = origin .route( @@ -178,10 +172,7 @@ pub async fn import(target: ImportTarget, args: ImportArgs, instance: moq_net::I ) .context("failed to create broadcast")?; - let config = moq_mux::catalog::Config::default() - .with_max_age(max_age) - .with_bandwidth(bandwidth); - let catalog = moq_mux::catalog::Producer::new(&mut route.broadcast().clone(), config)?; + let catalog = moq_mux::catalog::Producer::new(&mut route.broadcast().clone(), ingest.catalog())?; // Announced once the catalog first goes out, which waits for every rendition's init: a // relay queries a broadcast's tracks the moment it is announced, and keeps the refusals of a // publisher that cannot serve its declared tracks yet. @@ -209,6 +200,7 @@ pub async fn import(target: ImportTarget, args: ImportArgs, instance: moq_net::I // The playlist ended: serve the finished broadcast for the linger, so a subscriber that // arrives after the end still gets the tail. An interrupt drops it at once. importer.finish()?; + let linger = ingest.linger; tracing::info!(?linger, "playlist ended; serving the finished broadcast"); moq_mux::Linger::new([route.broadcast().clone()], importer, linger) .wait() @@ -519,9 +511,7 @@ mod test { let target = ImportTarget { origin, name: "hls".to_string(), - max_age: None, - linger: moq_mux::Linger::DEFAULT, - bandwidth: Default::default(), + ingest: moq_mux::Ingest::default(), }; let args = ImportArgs { playlist: playlist.to_str().unwrap().to_string(), diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index 0a8a4d2590b..77bd8904921 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -752,25 +752,27 @@ fn spawn_import( reject_listener_cors(&rtc.cors, "import rtc")?; } - let max_age = Some(import.max_age.map_or(hang::container::MAX_AGE, Into::into)); - let linger = import.linger.map_or(moq_mux::Linger::DEFAULT, Into::into); + let mut ingest = moq_mux::Ingest::default(); + if let Some(max_age) = import.max_age { + ingest.max_age = Some(max_age.into()); + } + if let Some(linger) = import.linger { + ingest.linger = linger.into(); + } + ingest.bandwidth = bandwidth; // The MoQ side every gateway publishes into, minted per source since each takes it // by value onto its own task. let target = |name: String| crate::moq::ImportTarget { origin: origin.clone(), name, - max_age, - linger, - bandwidth: bandwidth.clone(), + ingest: ingest.clone(), }; let mut local = None; if let Some(format) = import.source.stdin_format() { warn_if_missing_format(&name); - let config = moq_mux::catalog::Config::default() - .with_max_age(max_age) - .with_bandwidth(bandwidth.clone()); + let config = ingest.catalog(); let mut publish = if let ImportSource::Ts(TsImport { program: Some(TsProgram::All), .. @@ -781,7 +783,7 @@ fn spawn_import( } else { Publish::stdin(origin, &name, instance, &format, config)? } - .with_linger(linger); + .with_linger(ingest.linger); publish.announce()?; local = Some(publish); } else { @@ -844,7 +846,7 @@ fn spawn_import( moq_net::origin::RouteOptions::hidden().with_instance(instance, 0), ) .context("failed to create broadcast")?; - let mut publish = Publish::capture(route, &capture, bandwidth.clone(), max_age)?; + let mut publish = Publish::capture(route, &capture, ingest.bandwidth.clone(), ingest.max_age)?; publish.announce()?; local = Some(publish); } diff --git a/rs/moq-cli/src/moq.rs b/rs/moq-cli/src/moq.rs index 55b7c505b96..da9213ffdfa 100644 --- a/rs/moq-cli/src/moq.rs +++ b/rs/moq-cli/src/moq.rs @@ -6,9 +6,8 @@ use hang::moq_net; -/// The MoQ side of an import: where a gateway publishes, under what name, the -/// max age it declares on the media tracks it mints, how long a clean end stays -/// up, and the connection allocator those tracks claim on. +/// The MoQ side of an import: where a gateway publishes, under what name, and how +/// (`--max-age`, `--linger`, and the uplink's allocator). /// /// They travel together rather than as loose arguments per entry point. #[derive(Clone)] @@ -19,17 +18,8 @@ pub struct ImportTarget { /// The broadcast name to publish under. pub name: String, - /// How long a superseded group of the published media tracks stays fresh - /// (`--max-age`, else hang's 30 s media max age), or `None` for no publisher limit. - pub max_age: Option, - - /// How long a cleanly ended broadcast stays up (`--linger`). - pub linger: std::time::Duration, - - /// Connection allocator each passthrough track claims its peak-hold bitrate on, - /// so a co-resident encoder targets what is left. Unlimited when there is no - /// uplink estimate. - pub bandwidth: moq_net::bandwidth::Allocator, + /// How the gateway publishes the broadcast. + pub ingest: moq_mux::Ingest, } /// Set once the process takes a shutdown signal: it is draining from then on, not starting. diff --git a/rs/moq-cli/src/rtc.rs b/rs/moq-cli/src/rtc.rs index fd0353bb7ea..d9e0cd78f4e 100644 --- a/rs/moq-cli/src/rtc.rs +++ b/rs/moq-cli/src/rtc.rs @@ -58,12 +58,8 @@ pub struct Listen { /// WHIP server: accept incoming WebRTC publishes into the Origin as `target.name` (import). pub async fn listen_import(target: ImportTarget, listen: Listen) -> anyhow::Result<()> { let publisher = scope_producer(&target.origin, &target.name)?; - let mut config = server_config(&listen); - config.max_age = target.max_age; - config.bandwidth = target.bandwidth; - config.linger = target.linger; - let server = moq_webrtc::Server::new(config); - serve(server.publish_router(publisher), "WHIP", listen).await + let server = moq_webrtc::Server::new(server_config(&listen)); + serve(server.publish_router(publisher, target.ingest), "WHIP", listen).await } /// WHEP server: serve WebRTC plays of `name` from the Origin (export). @@ -105,11 +101,10 @@ pub async fn connect_import(target: ImportTarget, url: Url, instance: moq_net::I tracing::info!(url = %RedactedUrl::new(&url), %name, "WHEP client pulling"); notify_ready(); - let mut config = moq_webrtc::client::Config::default(); - config.max_age = target.max_age; - config.bandwidth = target.bandwidth; - let client = moq_webrtc::Client::new(config)?; - client.subscribe(url, route.broadcast().clone()).await?; + let client = moq_webrtc::Client::new(moq_webrtc::client::Config::default())?; + client + .subscribe(url, route.broadcast().clone(), target.ingest.catalog()) + .await?; Ok(()) } @@ -135,7 +130,7 @@ pub async fn connect_export(origin: moq_net::origin::Consumer, url: Url, name: S fn server_config(listen: &Listen) -> moq_webrtc::server::Config { let mut config = moq_webrtc::server::Config::default(); - config.udp_bind = listen.udp_bind; + config.socket = moq_webrtc::server::Socket::Bind(listen.udp_bind); config.ice_candidates.clone_from(&listen.public_addr); config } diff --git a/rs/moq-cli/src/rtmp.rs b/rs/moq-cli/src/rtmp.rs index 38f7fdac36a..8c41675ca80 100644 --- a/rs/moq-cli/src/rtmp.rs +++ b/rs/moq-cli/src/rtmp.rs @@ -66,13 +66,7 @@ impl ExportArgs { /// Accept incoming RTMP publishes into the Origin as `target.name`; reject plays (import). pub async fn listen_import(target: ImportTarget, addr: SocketAddr) -> anyhow::Result<()> { - let ImportTarget { - origin, - name, - max_age, - linger, - bandwidth, - } = target; + let ImportTarget { origin, name, ingest } = target; let name = moq_net::Path::new(&name)?; let mut server = Server::bind(addr).await?; tracing::info!(%addr, %name, "RTMP listening (import)"); @@ -83,15 +77,9 @@ pub async fn listen_import(target: ImportTarget, addr: SocketAddr) -> anyhow::Re Request::Publish(publish) => { let origin = origin.clone(); let name = name.clone(); - let bandwidth = bandwidth.clone(); + let ingest = ingest.clone(); tokio::spawn(async move { - if let Err(err) = publish - .with_max_age(max_age) - .with_bandwidth(bandwidth) - .with_linger(linger) - .accept(&origin, &name) - .await - { + if let Err(err) = publish.accept(&origin, &name, &ingest).await { tracing::warn!(%name, %err, "RTMP ingest ended with error"); } }); @@ -153,12 +141,8 @@ pub async fn connect_import(target: ImportTarget, url: Url) -> anyhow::Result<() tracing::info!(%addr, %app, %name, "RTMP client pulling"); notify_ready(); - let client = Client::connect(addr, &app) - .await? - .with_max_age(target.max_age) - .with_bandwidth(target.bandwidth) - .with_linger(target.linger); - Ok(client.pull(&key, &target.origin, name).await?) + let client = Client::connect(addr, &app).await?; + Ok(client.pull(&key, &target.origin, name, &target.ingest).await?) } /// Push a broadcast from the Origin to a remote RTMP server (export). diff --git a/rs/moq-cli/src/rtsp.rs b/rs/moq-cli/src/rtsp.rs index 5cbbb41d7c8..098ac9f8424 100644 --- a/rs/moq-cli/src/rtsp.rs +++ b/rs/moq-cli/src/rtsp.rs @@ -74,10 +74,7 @@ async fn run(target: &ImportTarget, client: &moq_rtsp::Client, published: &mut b .origin .route(&target.name, moq_net::origin::RouteOptions::hidden()) .context("failed to create broadcast")?; - let config = moq_mux::catalog::Config::default() - .with_max_age(target.max_age) - .with_bandwidth(target.bandwidth.clone()); - let mut catalog = moq_mux::catalog::Producer::new(&mut route.broadcast().clone(), config)?; + let mut catalog = moq_mux::catalog::Producer::new(&mut route.broadcast().clone(), target.ingest.catalog())?; // A relay asks for a broadcast's tracks the moment it is announced, so wait for the // first keyframe to put them in the catalog. diff --git a/rs/moq-cli/src/srt.rs b/rs/moq-cli/src/srt.rs index d2217f26e8f..5d252200102 100644 --- a/rs/moq-cli/src/srt.rs +++ b/rs/moq-cli/src/srt.rs @@ -95,13 +95,7 @@ pub async fn listen_import( latency: Duration, program: Option, ) -> anyhow::Result<()> { - let ImportTarget { - origin, - name, - max_age, - linger, - bandwidth, - } = target; + let ImportTarget { origin, name, ingest } = target; let name = moq_net::Path::new(&name)?; let mut server = Server::bind(addr, latency).await?; tracing::info!(%addr, %name, "SRT listening (import)"); @@ -112,16 +106,9 @@ pub async fn listen_import( Request::Publish(publish) => { let origin = origin.clone(); let name = name.clone(); - let bandwidth = bandwidth.clone(); + let ingest = ingest.clone(); tokio::spawn(async move { - if let Err(err) = publish - .with_max_age(max_age) - .with_bandwidth(bandwidth) - .with_program(program) - .with_linger(linger) - .accept(&origin, &name) - .await - { + if let Err(err) = publish.with_program(program).accept(&origin, &name, &ingest).await { let err = suggest_program(err); tracing::warn!(%name, err = format!("{err:#}"), "SRT ingest ended with error"); } @@ -190,11 +177,11 @@ pub async fn connect_import( let client = moq_srt::Client::new(addr, resource) .with_latency(latency) - .with_max_age(target.max_age) - .with_bandwidth(target.bandwidth) - .with_program(program) - .with_linger(target.linger); - client.pull(&target.origin, name).await.map_err(suggest_program) + .with_program(program); + client + .pull(&target.origin, name, &target.ingest) + .await + .map_err(suggest_program) } /// Push a broadcast from the Origin to a remote SRT server (export). @@ -213,7 +200,7 @@ pub async fn connect_export( .with_latency(args.endpoint.latency.into()) .with_follow(args.follow.into()) .with_stitch(args.stitch); - Ok(client.publish(&origin, &name).await?) + Ok(client.publish(&origin, moq_srt::dial::Publish::new(name)).await?) } /// Parse `srt://host:port?streamid=` into a resolved address and resource. diff --git a/rs/moq-mux/src/ingest.rs b/rs/moq-mux/src/ingest.rs new file mode 100644 index 00000000000..bb9fa95cfd9 --- /dev/null +++ b/rs/moq-mux/src/ingest.rs @@ -0,0 +1,46 @@ +//! How a gateway publishes the broadcasts it ingests. + +use std::time::Duration; + +/// How a gateway publishes what it ingests: the media tracks' max age, the allocator they +/// claim on, and how long a cleanly ended broadcast stays up. +/// +/// Every protocol gateway takes one per ingest, so the same knobs mean the same thing on +/// RTMP, SRT, and WHIP. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct Ingest { + /// How long a superseded group of an ingested media track stays fresh, or `None` for no + /// publisher limit. Defaults to [`MAX_AGE`](hang::container::MAX_AGE); see + /// [`catalog::Config::with_max_age`](crate::catalog::Config::with_max_age). + pub max_age: Option, + + /// The connection allocator each ingested track claims its peak-hold bitrate on, so a + /// co-resident encoder targets what is left. Defaults to unlimited; see + /// [`catalog::Config::with_bandwidth`](crate::catalog::Config::with_bandwidth). + pub bandwidth: moq_net::bandwidth::Allocator, + + /// How long a broadcast whose source ended cleanly stays up, so a subscriber that + /// arrives after the end still gets the tail. Defaults to [`Linger::DEFAULT`](crate::Linger::DEFAULT); + /// zero closes it at once. + pub linger: Duration, +} + +impl Ingest { + /// The catalog config the ingested tracks are minted under. + pub fn catalog(&self) -> crate::catalog::Config { + crate::catalog::Config::default() + .with_max_age(self.max_age) + .with_bandwidth(self.bandwidth.clone()) + } +} + +impl Default for Ingest { + fn default() -> Self { + Self { + max_age: Some(hang::container::MAX_AGE), + bandwidth: moq_net::bandwidth::Allocator::unlimited(), + linger: crate::Linger::DEFAULT, + } + } +} diff --git a/rs/moq-mux/src/lib.rs b/rs/moq-mux/src/lib.rs index 9247b609a88..fd3bf12c826 100644 --- a/rs/moq-mux/src/lib.rs +++ b/rs/moq-mux/src/lib.rs @@ -35,6 +35,8 @@ //! serve it, for a reader that restarts on each one. //! - [`Linger`] keeps a cleanly ended broadcast up for a fixed time, so a //! subscriber that arrives after the end still gets its tail. +//! - [`Ingest`] is how a protocol gateway publishes what it ingests: max age, +//! allocator, and linger. //! //! The `poll_*` methods are always available. Enable the `async` feature for their generated //! async wrappers and the async constructors with no poll of their own; it is off by default. @@ -53,6 +55,7 @@ pub mod follow; #[doc(hidden)] pub mod fuzz; pub mod import; +mod ingest; mod jitter; pub mod json; mod linger; @@ -65,6 +68,7 @@ pub mod timeline; pub use clock::Clock; pub use error::*; +pub use ingest::Ingest; pub use linger::Linger; pub use pace::Pacer; pub use source::{Binding, Source}; diff --git a/rs/moq-net/src/model/bandwidth.rs b/rs/moq-net/src/model/bandwidth.rs index cd509137de7..75b9206240c 100644 --- a/rs/moq-net/src/model/bandwidth.rs +++ b/rs/moq-net/src/model/bandwidth.rs @@ -15,6 +15,9 @@ //! The receive direction mirrors it: [Viewers] divides the receive estimate among the //! broadcasts watched over one connection, and their ceilings summed are the PROBE //! target the session asks its peer to probe up to. +//! +//! A [Limit] is the other side: a live [Cap] an embedder puts on one session's media, +//! which a gateway enforces however its protocol allows. use std::{ collections::BTreeMap, @@ -83,6 +86,121 @@ impl Rate { } } +/// A rate cap: the sustained rate media may arrive or leave at, and the burst above it. +/// +/// What it counts is up to whoever enforces it: a WebRTC ingest counts depacketized media +/// payload, leaving RTP, SRTP, and UDP overhead outside it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Cap { + /// The sustained rate. + pub rate: Rate, + /// How far ahead of `rate` media may run, as time at `rate`. Defaults to + /// [`Cap::DEFAULT_BURST`], as on QUIC. + pub burst: std::time::Duration, +} + +impl Cap { + /// About one second of the cap. + pub const DEFAULT_BURST: std::time::Duration = std::time::Duration::from_secs(1); + + /// A cap at `rate` with the default burst. + pub const fn new(rate: Rate) -> Self { + Self { + rate, + burst: Self::DEFAULT_BURST, + } + } + + /// This cap with a burst of `burst` at its rate. + pub const fn with_burst(mut self, burst: std::time::Duration) -> Self { + self.burst = burst; + self + } +} + +impl From for Cap { + fn from(rate: Rate) -> Self { + Self::new(rate) + } +} + +/// A live cap for one session, uncapped while it holds `None`. +/// +/// Clones share the cap, so an embedder keeps one and hands another to the session, which +/// follows each [`set`](Self::set) at once. [`Default`] is uncapped. +pub struct Limit { + cap: kio::Producer>, + /// The cap [`poll_changed`](Self::poll_changed) last reported through this handle. + last: Option, +} + +impl Limit { + /// A handle starting at `cap`, or uncapped for `None`. + pub fn new(cap: impl Into>) -> Self { + let cap = cap.into(); + Self { + cap: kio::Producer::new(cap), + last: cap, + } + } + + /// Replace the cap; `None` lifts it. + pub fn set(&self, cap: impl Into>) { + let cap = cap.into(); + // Only a dropped producer closes the channel, and this handle is one. + if let Ok(mut state) = self.cap.write() + && *state != cap + { + *state = cap; + } + } + + /// The current cap, if any. + pub fn get(&self) -> Option { + *self.cap.read() + } + + /// The cap once it differs from the one this handle last saw: at its creation or clone, + /// or its last report. + #[cfg_attr(feature = "async", kio::wrapper)] + pub fn poll_changed(&mut self, waiter: &kio::Waiter) -> Poll> { + let last = self.last; + match self.cap.poll_ref(waiter, |cap| match **cap { + cap if cap != last => Poll::Ready(cap), + _ => Poll::Pending, + }) { + Poll::Ready(Ok(cap)) => { + self.last = cap; + Poll::Ready(cap) + } + // This handle holds the producer, so the channel never closes under it. + Poll::Ready(Err(_)) | Poll::Pending => Poll::Pending, + } + } +} + +impl Clone for Limit { + fn clone(&self) -> Self { + Self { + cap: self.cap.clone(), + last: self.get(), + } + } +} + +impl Default for Limit { + fn default() -> Self { + Self::new(None) + } +} + +impl std::fmt::Debug for Limit { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("Limit").field(&self.get()).finish() + } +} + #[derive(Default)] struct State { bitrate: Option, @@ -1210,6 +1328,25 @@ mod tests { use super::*; use crate::broadcast; + #[test] + fn a_limit_reports_each_change_to_every_clone() { + let cap = Cap::new(Rate::from_kbps(8)); + let limit = Limit::default(); + let mut watch = limit.clone(); + assert_eq!(watch.get(), None); + assert!(watch.poll_changed(&kio::Waiter::noop()).is_pending()); + + limit.set(cap); + assert_eq!(watch.poll_changed(&kio::Waiter::noop()), Poll::Ready(Some(cap))); + assert!(watch.poll_changed(&kio::Waiter::noop()).is_pending()); + + // A clone starts at the current cap. + let mut late = limit.clone(); + assert!(late.poll_changed(&kio::Waiter::noop()).is_pending()); + limit.set(None); + assert_eq!(late.poll_changed(&kio::Waiter::noop()), Poll::Ready(None)); + } + /// Priorities matching `hang`'s, which is what the allocator sees in practice. const AUDIO: i8 = 80; const VIDEO: i8 = 60; diff --git a/rs/moq-rtmp/src/dial.rs b/rs/moq-rtmp/src/dial.rs index 395f215bfa1..3a55d69dd2e 100644 --- a/rs/moq-rtmp/src/dial.rs +++ b/rs/moq-rtmp/src/dial.rs @@ -70,13 +70,6 @@ pub struct Client { /// How long [`publish`](Self::publish)'s FLV muxer waits for a stalled group /// before skipping. delay: Duration, - /// Max age declared on the media tracks [`pull`](Self::pull) publishes, or `None` for - /// no publisher limit. - max_age: Option, - /// Connection allocator each track [`pull`](Self::pull) ingests claims its peak-hold bitrate on. - bandwidth: moq_net::bandwidth::Allocator, - /// How long a broadcast [`pull`](Self::pull) finished stays up. - linger: Duration, /// Script data [`pull`](Self::pull) discards, including any sent before Play.Start. metadata: crate::metadata::Dropped, } @@ -176,9 +169,6 @@ impl Client { work, app: app.to_string(), delay: crate::DEFAULT_DELAY, - max_age: Some(hang::container::MAX_AGE), - bandwidth: moq_net::bandwidth::Allocator::unlimited(), - linger: moq_mux::Linger::DEFAULT, metadata: Default::default(), }) } @@ -186,52 +176,13 @@ impl Client { /// Set the FLV release delay and stalled-group budget for [`publish`](Self::publish). /// Defaults to 500 ms; zero releases available frames immediately without deadline drops. /// - /// The publish (egress) direction only; [`pull`](Self::pull) takes - /// [`with_max_age`](Self::with_max_age) instead. + /// The publish (egress) direction only; [`pull`](Self::pull) takes a + /// [`moq_mux::Ingest`] instead. pub fn with_delay(mut self, delay: Duration) -> Self { self.delay = delay; self } - /// Set how long a superseded group of the media tracks [`pull`](Self::pull) publishes - /// stays fresh, or `None` for no publisher limit. Defaults to - /// [`MAX_AGE`](hang::container::MAX_AGE). - /// - /// A freshness bound, not a delivery one: it never makes a subscriber play further - /// behind live, it caps how far back a FETCH can still reach. The default suits a - /// segmented egress (HLS/DASH) reading the broadcast downstream, which may only - /// advertise segments that are still fetchable. Lower it when nothing reads history. - /// - /// The pull (ingest) direction only; [`publish`](Self::publish) reads a broadcast - /// someone else declared, and takes [`with_delay`](Self::with_delay) instead. - pub fn with_max_age(mut self, max_age: impl Into>) -> Self { - self.max_age = max_age.into(); - self - } - - /// Claim each ingested track's peak-hold catalog bitrate on `bandwidth`. - /// - /// A passthrough import has no configured ceiling, so it reserves the measured - /// maximum instead. A co-resident encoder then targets what is left of the - /// uplink. Unlimited (the default) claims nothing a sender can follow. - /// - /// The pull (ingest) direction only; [`publish`](Self::publish) reads a - /// broadcast someone else declared. - pub fn with_bandwidth(mut self, bandwidth: moq_net::bandwidth::Allocator) -> Self { - self.bandwidth = bandwidth; - self - } - - /// Keep the broadcast [`pull`](Self::pull) publishes up for `linger` after the remote - /// completes the play, so a subscriber that arrives after the end still gets the tail. - /// Defaults to [`moq_mux::Linger::DEFAULT`]; zero closes it at once. - /// - /// The pull (ingest) direction only. - pub fn with_linger(mut self, linger: Duration) -> Self { - self.linger = linger; - self - } - /// Push a MoQ broadcast out to the remote: request `publish` on `stream_key`, /// mux the broadcast to FLV, and send each tag as an RTMP audio/video message /// until the broadcast ends or the connection drops. @@ -314,21 +265,22 @@ impl Client { } /// Pull a remote stream into `origin`: request `play` on `stream_key`, receive - /// its FLV tags, demux them, and publish the result at `path` until the remote + /// its FLV tags, demux them, and publish the result at `path` as `ingest` says until the remote /// stops or the connection drops. /// /// This future resolves when the remote stream ends, so callers usually run it /// on its own task. /// /// A remote that completes the play (`NetStream.Play.Complete` or `NetStream.Play.Stop`) - /// ends cleanly: the finished broadcast stays up for the [linger](Self::with_linger), and - /// the future resolves after that. Dropping the future ends the linger early. A - /// connection that drops first closes the broadcast at once. + /// ends cleanly: the finished broadcast stays up for the ingest's + /// [linger](moq_mux::Ingest::linger), and the future resolves after that. Dropping the + /// future ends the linger early. A connection that drops first closes the broadcast at once. pub async fn pull( mut self, stream_key: &str, origin: &origin::Producer, path: impl Into, + ingest: &moq_mux::Ingest, ) -> Result<()> { let path: moq_net::Path = path.into(); let request = self @@ -339,10 +291,7 @@ impl Client { self.metadata = crate::metadata::Dropped::new(path.as_str()); self.await_event(Direction::Play).await?; - let config = moq_mux::catalog::Config::default() - .with_max_age(self.max_age) - .with_bandwidth(self.bandwidth.clone()); - let mut publisher = Publisher::new(origin, path.as_str(), config)?; + let mut publisher = Publisher::new(origin, path.as_str(), ingest.catalog())?; // The stream key is the ingest credential (`rtmp://host//`), so the // app and broadcast path stand in for it. @@ -353,7 +302,7 @@ impl Client { // A clean end: serve the finished broadcast for the linger, so a subscriber that // arrives after the end still gets the tail. The remote is done, so hang up first. Ok(true) => { - let linger = self.linger; + let linger = ingest.linger; drop(self); match publisher.finish(linger) { Ok(publisher) => { @@ -667,9 +616,6 @@ mod tests { work: VecDeque::new(), app: "live".into(), delay: crate::DEFAULT_DELAY, - max_age: None, - bandwidth: Default::default(), - linger: Duration::ZERO, metadata: Default::default(), }; let start = kio::clock::Instant::now(); @@ -713,9 +659,6 @@ mod tests { work, app: "live".into(), delay: crate::DEFAULT_DELAY, - max_age: None, - bandwidth: Default::default(), - linger: Duration::ZERO, metadata: crate::metadata::Dropped::new("metadata"), }; let origin = moq_tokio::origin::spawn(); @@ -782,6 +725,11 @@ mod tests { async fn a_finished_broadcast_lingers_across_rtmp() { let peer = "127.0.0.1:1935".parse().unwrap(); let linger = Duration::from_secs(10); + let lingering = |linger| { + let mut ingest = moq_mux::Ingest::default(); + ingest.linger = linger; + ingest + }; for push in [true, false] { let upstream = moq_tokio::origin::spawn(); let downstream = moq_tokio::origin::spawn(); @@ -794,8 +742,7 @@ mod tests { let server = tokio::spawn(async move { match accept_stream(server_io, peer).await.unwrap().unwrap() { Request::Publish(publish) => publish - .with_linger(linger) - .accept(&ingest, moq_net::Path::from_static("live/cam0")) + .accept(&ingest, moq_net::Path::from_static("live/cam0"), &lingering(linger)) .await .unwrap(), Request::Play(play) => play @@ -810,8 +757,12 @@ mod tests { match push { true => client.publish("cam0", exported(origin).await).await.unwrap(), false => client - .with_linger(linger) - .pull("cam0", &pulled, moq_net::Path::from_static("live/cam0")) + .pull( + "cam0", + &pulled, + moq_net::Path::from_static("live/cam0"), + &lingering(linger), + ) .await .unwrap(), } @@ -868,7 +819,12 @@ mod tests { } false => { client - .pull("cam0", &upstream, moq_net::Path::from_static("live/cam0")) + .pull( + "cam0", + &upstream, + moq_net::Path::from_static("live/cam0"), + &Default::default(), + ) .await } } @@ -930,7 +886,9 @@ mod tests { else { panic!("expected a publish request"); }; - let _ = publish.accept(&ingest, moq_net::Path::from_static("live/cam0")).await; + let _ = publish + .accept(&ingest, moq_net::Path::from_static("live/cam0"), &Default::default()) + .await; }); let origin = upstream.consume(); let pushed = tokio::spawn(async move { @@ -1037,7 +995,12 @@ mod tests { let pull = tokio::spawn(async move { let client = Client::connect(addr, "live").await.unwrap(); client - .pull("cam0", &pull_origin, moq_net::Path::from_static("pulled/cam0")) + .pull( + "cam0", + &pull_origin, + moq_net::Path::from_static("pulled/cam0"), + &Default::default(), + ) .await .unwrap(); }); diff --git a/rs/moq-rtmp/src/server.rs b/rs/moq-rtmp/src/server.rs index ffc4990937d..4297e87b875 100644 --- a/rs/moq-rtmp/src/server.rs +++ b/rs/moq-rtmp/src/server.rs @@ -574,14 +574,6 @@ pub struct Publish { stream_key: String, tc_url: Option, peer: SocketAddr, - /// Max age declared on the media tracks this publish mints, or `None` for no publisher - /// limit. Override with [`with_max_age`](Self::with_max_age). - max_age: Option, - /// Connection allocator each passthrough track claims its peak-hold bitrate on. - /// Override with [`with_bandwidth`](Self::with_bandwidth). - bandwidth: moq_net::bandwidth::Allocator, - /// How long an unpublished broadcast stays up. Override with [`with_linger`](Self::with_linger). - linger: Duration, } impl Publish { @@ -610,39 +602,8 @@ impl Publish { self.peer } - /// Set how long a superseded group of this publish's media tracks stays fresh, or - /// `None` for no publisher limit. Defaults to - /// [`MAX_AGE`](hang::container::MAX_AGE). - /// - /// A freshness bound, not a delivery one: it never makes a subscriber play further - /// behind live, it caps how far back a FETCH can still reach. The default suits a - /// segmented egress (HLS/DASH) reading the broadcast downstream, which may only - /// advertise segments that are still fetchable. Lower it when nothing reads history. - pub fn with_max_age(mut self, max_age: impl Into>) -> Self { - self.max_age = max_age.into(); - self - } - - /// Claim each ingested track's peak-hold catalog bitrate on `bandwidth`. - /// - /// A passthrough import has no configured ceiling, so it reserves the measured - /// maximum instead. A co-resident encoder then targets what is left of the - /// uplink. Unlimited (the default) claims nothing a sender can follow. - pub fn with_bandwidth(mut self, bandwidth: moq_net::bandwidth::Allocator) -> Self { - self.bandwidth = bandwidth; - self - } - - /// Keep the broadcast up for `linger` after the client unpublishes, so a subscriber that - /// arrives after the end still gets the tail. Defaults to [`moq_mux::Linger::DEFAULT`]; - /// zero closes it at once. - pub fn with_linger(mut self, linger: Duration) -> Self { - self.linger = linger; - self - } - /// Accept the publish: announce a broadcast at `path` in `origin` and pump the - /// RTMP media into it until the client disconnects. + /// RTMP media into it, published as `ingest` says, until the client disconnects. /// /// `origin` is whatever the caller wants the media published into (e.g. a /// relay's shared origin, optionally re-rooted/scoped per the authenticated @@ -650,18 +611,20 @@ impl Publish { /// run it on its own task. /// /// A client that unpublishes (`deleteStream`) ends cleanly: the finished broadcast - /// stays up for the [linger](Self::with_linger), and the future resolves after that. - /// Dropping the future ends the linger early. A connection that drops without + /// stays up for the ingest's [linger](moq_mux::Ingest::linger), and the future resolves + /// after that. Dropping the future ends the linger early. A connection that drops without /// unpublishing closes the broadcast at once. - pub async fn accept(mut self, origin: &origin::Producer, path: impl Into) -> Result<()> { + pub async fn accept( + mut self, + origin: &origin::Producer, + path: impl Into, + ingest: &moq_mux::Ingest, + ) -> Result<()> { let path: moq_net::Path = path.into(); // Reserve the broadcast path before telling the client the publish succeeded: // if the origin refuses `path`, reject cleanly instead of accepting and then // dropping the connection a moment later. - let config = moq_mux::catalog::Config::default() - .with_max_age(self.max_age) - .with_bandwidth(self.bandwidth); - let mut publisher = match Publisher::new(origin, path.as_str(), config) { + let mut publisher = match Publisher::new(origin, path.as_str(), ingest.catalog()) { Ok(publisher) => publisher, Err(err) => { tracing::warn!(peer = %self.peer, %path, %err, "rejecting RTMP publish: broadcast unavailable"); @@ -701,9 +664,9 @@ impl Publish { // arrives after the end still gets the tail. The encoder is done, so hang up first. Ok(End::Unpublished) => { drop(self.stream); - match publisher.finish(self.linger) { + match publisher.finish(ingest.linger) { Ok(linger) => { - tracing::info!(%peer, %path, linger = ?self.linger, "rtmp publish ended, serving the finished broadcast"); + tracing::info!(%peer, %path, linger = ?ingest.linger, "rtmp publish ended, serving the finished broadcast"); linger.wait().await; } Err(err) => tracing::debug!(%peer, %err, "error finishing RTMP publish"), @@ -1199,9 +1162,6 @@ async fn accept_until_request(mut stream: S, peer: SocketAddr) -> any stream_key, tc_url, peer, - max_age: Some(hang::container::MAX_AGE), - bandwidth: moq_net::bandwidth::Allocator::unlimited(), - linger: moq_mux::Linger::DEFAULT, }))); } // The client wants to play: hand control back to the caller. @@ -1851,9 +1811,10 @@ mod tests { let Some(Request::Publish(publish)) = accept_stream(stream, peer).await.unwrap() else { panic!("expected a publish request"); }; + let mut ingest = moq_mux::Ingest::default(); + ingest.linger = linger; publish - .with_linger(linger) - .accept(&origin, moq_net::Path::from_static("live/cam0")) + .accept(&origin, moq_net::Path::from_static("live/cam0"), &ingest) .await .unwrap(); } @@ -2811,7 +2772,11 @@ mod tests { panic!("expected a publish request"); }; let origin = origin.clone(); - tokio::spawn(async move { publish.accept(&origin, moq_net::Path::from_static("live/cam0")).await }); + tokio::spawn(async move { + publish + .accept(&origin, moq_net::Path::from_static("live/cam0"), &Default::default()) + .await + }); } }); diff --git a/rs/moq-srt/src/dial.rs b/rs/moq-srt/src/dial.rs index a86b04062c9..b3def054b03 100644 --- a/rs/moq-srt/src/dial.rs +++ b/rs/moq-srt/src/dial.rs @@ -43,26 +43,9 @@ pub struct Client { /// for loss recovery. It doubles as [`publish`]'s egress skip threshold. latency: Duration, - /// How long a superseded group of an ingested media track stays fresh, or `None` for - /// no publisher limit. Defaults to [`MAX_AGE`](hang::container::MAX_AGE). - /// - /// A freshness bound, not a delivery one: it never makes a subscriber play further - /// behind live, it caps how far back a FETCH can still reach. The default suits a - /// segmented egress (HLS/DASH) reading the broadcast downstream, which may only - /// advertise segments that are still fetchable. Lower it when nothing reads history. [`pull`] only; [`publish`] reads a broadcast someone else - /// declared. - max_age: Option, - - /// Connection allocator each ingested track claims its peak-hold bitrate on. - /// [`pull`] only; [`publish`] reads a broadcast someone else declared. - bandwidth: moq_net::bandwidth::Allocator, - /// The programs of a multi-program remote [`pull`] publishes, or `None` to refuse one. program: Option, - /// How long a broadcast [`pull`] finished stays up. [`pull`] only. - linger: Duration, - /// How long [`publish`] waits for the same publisher instance to come back once its /// broadcast ends. [`publish`] only. follow: Duration, @@ -73,17 +56,13 @@ pub struct Client { } impl Client { - /// Dial `addr` for `resource`, with the default SRT latency (500ms) and the - /// authored media max age. + /// Dial `addr` for `resource`, with the default SRT latency (500ms). pub fn new(addr: SocketAddr, resource: impl Into) -> Self { Self { addr, resource: resource.into(), latency: DEFAULT_LATENCY, - max_age: Some(hang::container::MAX_AGE), - bandwidth: moq_net::bandwidth::Allocator::unlimited(), program: None, - linger: moq_mux::Linger::DEFAULT, follow: Duration::ZERO, stitch: false, } @@ -99,23 +78,6 @@ impl Client { self } - /// Set how long non-latest groups created by [`pull`](Self::pull) remain fetchable. - /// - /// The pull (ingest) direction only; [`publish`](Self::publish) reads a broadcast - /// someone else declared. - pub fn with_max_age(mut self, max_age: impl Into>) -> Self { - self.max_age = max_age.into(); - self - } - - /// Claim each track ingested by [`pull`](Self::pull) on `bandwidth`. - /// - /// The pull (ingest) direction only. - pub fn with_bandwidth(mut self, bandwidth: moq_net::bandwidth::Allocator) -> Self { - self.bandwidth = bandwidth; - self - } - /// Publish one program of a multi-program stream [`pull`](Self::pull) receives, or each as /// its own broadcast under the pulled path. `None` (the default) refuses a multiplex. pub fn with_program(mut self, program: impl Into>) -> Self { @@ -123,16 +85,6 @@ impl Client { self } - /// Keep the broadcast [`pull`](Self::pull) publishes up for `linger` after the remote - /// stream ends, so a subscriber that arrives after the end still gets the tail. Defaults to - /// [`moq_mux::Linger::DEFAULT`]; zero closes it at once. - /// - /// The pull (ingest) direction only. - pub fn with_linger(mut self, linger: Duration) -> Self { - self.linger = linger; - self - } - /// Wait up to `follow` for the same publisher instance, or when stitching a replacement, to /// come back once the broadcast [`publish`](Self::publish) reads ends, carrying on with the /// same stream. Zero (the default) follows only an instance already serving. @@ -149,9 +101,10 @@ impl Client { self } - /// Push a MoQ broadcast out to the remote as MPEG-TS until the broadcast ends. - pub async fn publish(&self, origin: &origin::Consumer, path: impl Into) -> Result<()> { - let path: moq_net::Path = path.into(); + /// Push the broadcast `request` names in `origin` out to the remote as MPEG-TS until the + /// broadcast ends. + pub async fn publish(&self, origin: &origin::Consumer, request: Publish) -> Result<()> { + let Publish { path } = request; let socket = self.call(Mode::Publish).await?; let options = crate::ts::Options { latency: self.latency, @@ -161,21 +114,20 @@ impl Client { serve_subscribe(origin, path.as_str(), socket, options).await } - /// Pull a remote MPEG-TS stream into `origin` at `path` until the remote ends. + /// Pull a remote MPEG-TS stream into `origin` at `path`, published as `ingest` says, until + /// the remote ends. /// - /// The finished broadcast then stays up for the [linger](Self::with_linger), as - /// [`Publish::accept`](crate::Publish::accept) describes, and the future resolves after that. - pub async fn pull(&self, origin: &origin::Producer, path: impl Into) -> Result<()> { + /// The finished broadcast then stays up for the ingest's [linger](moq_mux::Ingest::linger), + /// as [`Publish::accept`](crate::Publish::accept) describes, and the future resolves after that. + pub async fn pull( + &self, + origin: &origin::Producer, + path: impl Into, + ingest: &moq_mux::Ingest, + ) -> Result<()> { let path: moq_net::Path = path.into(); let socket = self.call(Mode::Request).await?; - let ingest = crate::server::Ingest { - config: moq_mux::catalog::Config::default() - .with_max_age(self.max_age) - .with_bandwidth(self.bandwidth.clone()), - program: self.program, - linger: self.linger, - }; - serve_publish(origin, path.as_str(), socket, ingest).await + serve_publish(origin, path.as_str(), socket, ingest, self.program).await } async fn call(&self, mode: Mode) -> Result { @@ -193,6 +145,21 @@ impl Client { } } +/// What [`Client::publish`] pushes: the broadcast to read. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct Publish { + /// The broadcast to push, relative to the origin's root. + pub path: moq_net::Path, +} + +impl Publish { + /// Push the broadcast at `path`. + pub fn new(path: impl Into) -> Self { + Self { path: path.into() } + } +} + /// The SRT stream-id `m=` mode sent to the remote, i.e. the remote's role. #[derive(Clone, Copy)] enum Mode { @@ -261,9 +228,10 @@ mod tests { let is_publish = matches!(request, Request::Publish(_)); if let Request::Publish(publish) = request { // Runs until the caller disconnects, then closes at once. + let mut ingest = moq_mux::Ingest::default(); + ingest.linger = Duration::ZERO; publish - .with_linger(Duration::ZERO) - .accept(&origin, moq_net::Path::from_static("ingested/cam0")) + .accept(&origin, moq_net::Path::from_static("ingested/cam0"), &ingest) .await .ok(); } diff --git a/rs/moq-srt/src/server.rs b/rs/moq-srt/src/server.rs index 8c008bd2b2c..6a332618c5a 100644 --- a/rs/moq-srt/src/server.rs +++ b/rs/moq-srt/src/server.rs @@ -247,10 +247,7 @@ impl Server { stream_id, peer, latency: self.latency, - max_age: Some(hang::container::MAX_AGE), - bandwidth: moq_net::bandwidth::Allocator::unlimited(), program: None, - linger: moq_mux::Linger::DEFAULT, follow: Duration::ZERO, stitch: false, }; @@ -279,16 +276,8 @@ struct Pending { peer: SocketAddr, /// The SRT receive latency, reused as the egress delay (at least a second) on a subscribe. latency: Duration, - /// Max age declared on the media tracks an ingest mints, or `None` for no publisher - /// limit. Override with [`Publish::with_max_age`]. - max_age: Option, - /// Connection allocator each ingested track claims its peak-hold bitrate on. - /// Override with [`Publish::with_bandwidth`]. - bandwidth: moq_net::bandwidth::Allocator, /// The programs of a multiplex an ingest publishes. Override with [`Publish::with_program`]. program: Option, - /// How long an ended ingest stays up. Override with [`Publish::with_linger`]. - linger: Duration, /// How long an egress waits for the same instance to return. Override with /// [`Subscribe::with_follow`]. follow: Duration, @@ -366,32 +355,6 @@ impl Publish { self.0.peer } - /// Set how long a superseded group of this publish's media tracks stays fresh, or - /// `None` for no publisher limit. Defaults to - /// [`MAX_AGE`](hang::container::MAX_AGE). - /// - /// A freshness bound, not a delivery one: it never makes a subscriber play further - /// behind live, it caps how far back a FETCH can still reach. The default suits a - /// segmented egress (HLS/DASH) reading the broadcast downstream, which may only - /// advertise segments that are still fetchable. Lower it when nothing reads history. - /// - /// Unrelated to the SRT receive latency [`Server::bind`] negotiates, which is a - /// transport buffer on this hop. - pub fn with_max_age(mut self, max_age: impl Into>) -> Self { - self.0.max_age = max_age.into(); - self - } - - /// Claim each ingested track's peak-hold catalog bitrate on `bandwidth`. - /// - /// A passthrough import has no configured ceiling, so it reserves the measured - /// maximum instead. A co-resident encoder then targets what is left of the - /// uplink. Unlimited (the default) claims nothing a sender can follow. - pub fn with_bandwidth(mut self, bandwidth: moq_net::bandwidth::Allocator) -> Self { - self.0.bandwidth = bandwidth; - self - } - /// Publish one program of a multi-program feed, or each as its own broadcast under the /// accepted path. `None` (the default) fails an ingest whose PAT lists more than one. pub fn with_program(mut self, program: impl Into>) -> Self { @@ -399,38 +362,30 @@ impl Publish { self } - /// Keep the broadcast up for `linger` after the stream ends, so a subscriber that arrives - /// after the end still gets the tail. Defaults to [`moq_mux::Linger::DEFAULT`]; zero closes - /// it at once. - pub fn with_linger(mut self, linger: Duration) -> Self { - self.0.linger = linger; - self - } - /// Accept the publish: announce a broadcast at `path` in `origin` and pump the - /// connection's MPEG-TS into it until the client disconnects. + /// connection's MPEG-TS into it, published as `ingest` says, until the client disconnects. /// /// `origin` is whatever the caller wants the media published into (e.g. a /// relay's shared origin, optionally scoped per the authenticated token). This /// future resolves when the connection ends, so callers usually run it on its /// own task. /// - /// Once the stream ends, the finished broadcast stays up for the - /// [linger](Self::with_linger), and the future resolves after that. Dropping the future - /// ends the linger early. A socket or demux error closes the broadcast at once. - pub async fn accept(self, origin: &origin::Producer, path: impl Into) -> Result<()> { + /// Once the stream ends, the finished broadcast stays up for the ingest's + /// [linger](moq_mux::Ingest::linger), and the future resolves after that. Dropping the + /// future ends the linger early. A socket or demux error closes the broadcast at once. + /// + /// The ingest's max age is unrelated to the SRT receive latency [`Server::bind`] + /// negotiates, which is a transport buffer on this hop. + pub async fn accept( + self, + origin: &origin::Producer, + path: impl Into, + ingest: &moq_mux::Ingest, + ) -> Result<()> { let path: moq_net::Path = path.into(); let socket = self.0.request.accept(None).await?; tracing::info!(peer = %self.0.peer, %path, "SRT publish accepted"); - let config = moq_mux::catalog::Config::default() - .with_max_age(self.0.max_age) - .with_bandwidth(self.0.bandwidth); - let ingest = Ingest { - config, - program: self.0.program, - linger: self.0.linger, - }; - serve_publish(origin, path.as_str(), socket, ingest).await + serve_publish(origin, path.as_str(), socket, ingest, self.0.program).await } /// Reject the publish with a verdict the client can distinguish on the wire. @@ -522,23 +477,18 @@ async fn reject_log(request: ConnectionRequest, reason: Reject, peer: SocketAddr } } -/// How an ingest publishes: its catalog, which programs, and how long a clean end stays up. -pub(crate) struct Ingest { - pub config: moq_mux::catalog::Config, - pub program: Option, - pub linger: Duration, -} - -/// Pump one accepted SRT socket's MPEG-TS payload into the origin (`m=publish`). +/// Pump one accepted SRT socket's MPEG-TS payload into the origin (`m=publish`), publishing +/// `program` of a multiplex. pub(crate) async fn serve_publish( origin: &origin::Producer, path: &str, mut socket: SrtSocket, - ingest: Ingest, + ingest: &moq_mux::Ingest, + program: Option, ) -> Result<()> { use futures::TryStreamExt; - let mut publisher = crate::ts::Publisher::new(origin, path, ingest.config, ingest.program)?; + let mut publisher = crate::ts::Publisher::new(origin, path, ingest.catalog(), program)?; // Run the read/feed loop so an error surfaces here instead of unwinding past // the publisher, which would drop it (and its tracks) with a bare Error::Dropped. diff --git a/rs/moq-webrtc/src/client/mod.rs b/rs/moq-webrtc/src/client/mod.rs index 1a2eb9af40b..a7300daedd4 100644 --- a/rs/moq-webrtc/src/client/mod.rs +++ b/rs/moq-webrtc/src/client/mod.rs @@ -9,40 +9,16 @@ mod whep; mod whip; use std::net::SocketAddr; -use std::time::Duration; use url::Url; /// Configuration shared by both `client publish` and `client subscribe`. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] #[non_exhaustive] pub struct Config { /// Public UDP socket addresses to advertise as ICE host candidates in /// our outbound offer. Same semantics as [`crate::server::Config::ice_candidates`]. pub ice_candidates: Vec, - - /// How long a superseded group of an ingested media track stays fresh, or `None` for - /// no publisher limit. Same semantics as [`crate::server::Config::max_age`]. - /// - /// Ingest only ([`subscribe`](Client::subscribe) / WHEP): a WHIP - /// [`publish`](Client::publish) reads a broadcast someone else declared, so it - /// ignores this. - pub max_age: Option, - - /// Connection allocator each ingested track claims its peak-hold bitrate on. - /// Ingest only ([`subscribe`](Client::subscribe) / WHEP); a WHIP - /// [`publish`](Client::publish) ignores this. - pub bandwidth: moq_net::bandwidth::Allocator, -} - -impl Default for Config { - fn default() -> Self { - Self { - ice_candidates: Vec::new(), - max_age: Some(hang::container::MAX_AGE), - bandwidth: moq_net::bandwidth::Allocator::unlimited(), - } - } } /// Outbound WHIP/WHEP dialer. @@ -81,10 +57,18 @@ impl Client { &self.http } - /// `client subscribe`: pull a remote WHEP feed and publish it as - /// `broadcast` on the local origin, until the session ends. - pub async fn subscribe(&self, url: Url, broadcast: moq_net::broadcast::Producer) -> crate::Result<()> { - whep::dial(self, url, broadcast).await + /// `client subscribe`: pull a remote WHEP feed and publish it as `broadcast`, its tracks + /// minted under `catalog`, until the session ends. + /// + /// The caller owns the broadcast, so its announcement and any linger after the end are + /// the caller's too. + pub async fn subscribe( + &self, + url: Url, + broadcast: moq_net::broadcast::Producer, + catalog: moq_mux::catalog::Config, + ) -> crate::Result<()> { + whep::dial(self, url, broadcast, catalog).await } /// `client publish`: push the broadcast `source` resolved to a remote WHIP endpoint, @@ -118,7 +102,7 @@ mod tests { .expect("WHEP URL"); let err = Client::new(Config::default()) .unwrap() - .subscribe(url, broadcast.broadcast().clone()) + .subscribe(url, broadcast.broadcast().clone(), Default::default()) .await .expect_err("dial a closed port"); diff --git a/rs/moq-webrtc/src/client/whep.rs b/rs/moq-webrtc/src/client/whep.rs index cea48a0c579..94104e30e8b 100644 --- a/rs/moq-webrtc/src/client/whep.rs +++ b/rs/moq-webrtc/src/client/whep.rs @@ -16,11 +16,13 @@ use url::Url; use crate::{Error, Result, client::Client, ingest::IngestSink, session}; -pub(crate) async fn dial(client: &Client, url: Url, broadcast: moq_net::broadcast::Producer) -> Result<()> { - let config = moq_mux::catalog::Config::default() - .with_max_age(client.config().max_age) - .with_bandwidth(client.config().bandwidth.clone()); - let sink = Box::new(IngestSink::new(broadcast, config)?); +pub(crate) async fn dial( + client: &Client, + url: Url, + broadcast: moq_net::broadcast::Producer, + catalog: moq_mux::catalog::Config, +) -> Result<()> { + let sink = Box::new(IngestSink::new(broadcast, catalog)?); let socket = session::bind_udp(&client.config().ice_candidates).await?; let mut rtc = session::rtc_config()?.build(kio::clock::now().into_std()); diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index bd576e7a46a..15dc9d36f72 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -42,7 +42,7 @@ pub mod client; #[cfg(feature = "p2p")] pub mod p2p; -pub mod rate; +mod rate; pub mod server; // Implementation detail modules: these carry the WebRTC/str0m plumbing (str0m @@ -209,9 +209,12 @@ mod tests { let origin = whep_origin.clone(); let sessions = sessions_tx.clone(); async move { - let response = server::whep::accept(&server, &origin, moq_net::Path::from_static("source"), &offer) - .await - .unwrap(); + let response = server::whep::accept( + &server, + server::whep::Request::new(&origin, moq_net::Path::from_static("source"), &offer), + ) + .await + .unwrap(); let answer = response.answer.clone(); sessions.send(tokio::spawn(response.run())).await.unwrap(); answer @@ -228,7 +231,7 @@ mod tests { let client = Client::new(client::Config::default()).unwrap(); let url = format!("http://{address}/whep/source").parse().expect("WHEP URL"); let fill = output.broadcast().clone(); - let viewer = tokio::spawn(async move { client.subscribe(url, fill).await }); + let viewer = tokio::spawn(async move { client.subscribe(url, fill, Default::default()).await }); let session = kio::clock::timeout(TIMEOUT, sessions.recv()) .await .expect("WHEP negotiation timed out") @@ -321,7 +324,7 @@ mod tests { /// Serve WHIP at `/whip/ingested` under `rate`, sending each session's task out. async fn serve_capped_whip( - rate: crate::rate::Limit, + rate: moq_net::bandwidth::Limit, ) -> ( std::net::SocketAddr, tokio::task::JoinHandle<()>, @@ -336,8 +339,9 @@ mod tests { let (server, origin, rate, sessions) = (server.clone(), origin.clone(), rate.clone(), sessions_tx.clone()); async move { - let request = server::whip::Request::new(&origin, moq_net::Path::from_static("ingested"), &offer) - .with_rate(rate); + let mut request = + server::whip::Request::new(&origin, moq_net::Path::from_static("ingested"), &offer); + request.rate = Some(rate); let response = server::whip::accept(&server, request).await.unwrap(); let answer = response.answer.clone(); sessions.send(tokio::spawn(response.run())).await.unwrap(); @@ -394,13 +398,13 @@ mod tests { &[0x10, 0x00, 0x00, 0x9d, 0x01, 0x2a, 0x40, 0x01, 0xf0, 0x00], ); - let rate = crate::rate::Limit::new(crate::rate::Cap::new(moq_net::bandwidth::Rate::from_mbps(2))); + let rate = moq_net::bandwidth::Limit::new(moq_net::bandwidth::Cap::new(moq_net::bandwidth::Rate::from_mbps(2))); let (address, http, mut sessions) = serve_capped_whip(rate.clone()).await; let pushed = push_whip(&origin, address).await; let session = kio::clock::timeout(TIMEOUT, sessions.recv()).await.unwrap().unwrap(); logged("bps=1800000").await; - rate.set(crate::rate::Cap::new(moq_net::bandwidth::Rate::from_mbps(1))); + rate.set(moq_net::bandwidth::Cap::new(moq_net::bandwidth::Rate::from_mbps(1))); logged("bps=900000").await; // Lifting the cap lifts the publisher's ceiling rather than leaving the last one. rate.set(None); @@ -419,8 +423,9 @@ mod tests { let origin = moq_tokio::origin::spawn(); let (_route, mut opus, _catalog) = publish_opus(&origin, moq_net::Instance::random()); // 8 kbps with a tenth of a second of burst allows 100 bytes up front. - let cap = crate::rate::Cap::new(moq_net::bandwidth::Rate::from_kbps(8)).with_burst(Duration::from_millis(100)); - let (address, http, mut sessions) = serve_capped_whip(crate::rate::Limit::new(cap)).await; + let cap = + moq_net::bandwidth::Cap::new(moq_net::bandwidth::Rate::from_kbps(8)).with_burst(Duration::from_millis(100)); + let (address, http, mut sessions) = serve_capped_whip(moq_net::bandwidth::Limit::new(cap)).await; push(&mut *opus, 20_000, &[0xfc; 1000]); let pushed = push_whip(&origin, address).await; @@ -504,10 +509,12 @@ mod tests { let origin = whep_origin.clone(); let sources = sources_tx.clone(); async move { - let response = - server::whep::accept(&server, &origin, moq_net::Path::from_static("ingested"), &offer) - .await - .unwrap(); + let response = server::whep::accept( + &server, + server::whep::Request::new(&origin, moq_net::Path::from_static("ingested"), &offer), + ) + .await + .unwrap(); let answer = response.answer.clone(); let id = response.resource_id.clone(); let task = tokio::spawn(response.run()); @@ -547,7 +554,7 @@ mod tests { .parse() .expect("WHEP URL"); let fill = output.broadcast().clone(); - let whep_client = tokio::spawn(async move { client.subscribe(whep, fill).await }); + let whep_client = tokio::spawn(async move { client.subscribe(whep, fill, Default::default()).await }); let (whep_id, whep_task) = kio::clock::timeout(TIMEOUT, sources_rx.recv()) .await .expect("WHEP negotiation timed out") diff --git a/rs/moq-webrtc/src/rate.rs b/rs/moq-webrtc/src/rate.rs index 225e81701af..7b6f397aecf 100644 --- a/rs/moq-webrtc/src/rate.rs +++ b/rs/moq-webrtc/src/rate.rs @@ -1,20 +1,17 @@ -//! Bitrate caps for WHIP ingest. +//! Holding a WHIP ingest to its [`Cap`]. //! -//! An embedder hands [`whip::accept`](crate::whip::accept) a [`Limit`] through -//! [`Request::with_rate`](crate::whip::Request::with_rate), and moq-webrtc steers the -//! publisher's encoder under its [`Cap`]: a `b=TIAS` -//! line in the SDP answer, and periodic REMB where the publisher negotiated -//! it. WebRTC has no receiver backpressure, so a publisher that ignores both is metered -//! and closed with [`Error::RateLimited`](crate::Error::RateLimited) past the cap plus its -//! burst. +//! An embedder hands [`whip::accept`](crate::whip::accept) a +//! [`Limit`](moq_net::bandwidth::Limit) in its [`Request`](crate::whip::Request), and +//! moq-webrtc steers the publisher's encoder under the cap: a `b=TIAS` line in the SDP +//! answer, and periodic REMB where the publisher negotiated it. WebRTC has no receiver +//! backpressure, so a publisher that ignores both is metered here and closed with +//! [`Error::RateLimited`](crate::Error::RateLimited) past the cap plus its burst. use std::collections::VecDeque; -use std::sync::Arc; use std::time::Duration; use kio::clock::Instant; -use moq_net::bandwidth::Rate; -use tokio::sync::watch; +use moq_net::bandwidth::{Cap, Rate}; /// The share of the cap moq-webrtc steers the encoder to. /// @@ -30,106 +27,14 @@ const STEER: f64 = 0.9; /// packet, 2 seconds by default, which moq-webrtc keeps; audio waits half that. const ASSEMBLY: Duration = Duration::from_secs(2); -/// A bitrate cap: the sustained rate media may arrive at, and the burst above it. -/// -/// The cap counts media payload, the depacketized frames a publisher sends. RTP, SRTP, -/// and UDP overhead sits outside it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub struct Cap { - /// The sustained rate. - pub rate: Rate, - /// How far ahead of `rate` media may run, as time at `rate`. Defaults to - /// [`Cap::DEFAULT_BURST`], as on QUIC. - pub burst: Duration, -} - -impl Cap { - /// About one second of the cap. - pub const DEFAULT_BURST: Duration = Duration::from_secs(1); - - /// A cap at `rate` with the default burst. - pub const fn new(rate: Rate) -> Self { - Self { - rate, - burst: Self::DEFAULT_BURST, - } - } - - /// This cap with a burst of `burst` at its rate. - pub const fn with_burst(mut self, burst: Duration) -> Self { - self.burst = burst; - self - } - - /// The rate the encoder is steered to, in the answer and in REMB: never above the cap. - pub(crate) fn steer(self) -> Rate { - self.rate.scaled(STEER) - } - - /// The burst in bytes. - fn burst_bytes(self) -> f64 { - self.rate.as_bps() as f64 / 8.0 * self.burst.as_secs_f64() - } -} - -impl From for Cap { - fn from(rate: Rate) -> Self { - Self::new(rate) - } +/// The rate the encoder is steered to, in the answer and in REMB: never above the cap. +pub(crate) fn steer(cap: Cap) -> Rate { + cap.rate.scaled(STEER) } -/// A live cap for one WHIP session. -/// -/// Clones share the cap. [`Limit::set`] applies to a running session at once: the -/// meter switches to the new cap, and the next REMB goes out immediately, lifting its -/// ceiling when the cap is lifted. The SDP answer's TIAS is fixed at the cap set when the -/// offer was accepted, since moq-webrtc never renegotiates: a session that starts uncapped -/// steers only through REMB, and raising or lifting a starting cap frees the publisher -/// only as far as that TIAS allows. -#[derive(Clone)] -pub struct Limit { - cap: Arc>>, -} - -impl Limit { - /// A handle starting at `cap`, or uncapped for `None`. - pub fn new(cap: impl Into>) -> Self { - Self { - cap: Arc::new(watch::Sender::new(cap.into())), - } - } - - /// An uncapped handle. - pub fn unlimited() -> Self { - Self::new(None) - } - - /// Replace the cap; `None` lifts it. - pub fn set(&self, cap: impl Into>) { - self.cap.send_replace(cap.into()); - } - - /// The current cap, if any. - pub fn get(&self) -> Option { - *self.cap.borrow() - } - - pub(crate) fn subscribe(&self) -> watch::Receiver> { - self.cap.subscribe() - } -} - -impl Default for Limit { - fn default() -> Self { - Self::unlimited() - } -} - -impl std::fmt::Debug for Limit { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_tuple("Limit").field(&self.get()).finish() - } +/// The cap's burst in bytes. +fn burst_bytes(cap: Cap) -> f64 { + cap.rate.as_bps() as f64 / 8.0 * cap.burst.as_secs_f64() } /// A token bucket over received media payload: full at the burst, refilled at the rate. @@ -163,7 +68,7 @@ impl Meter { pub fn new(cap: Option, now: Instant) -> Self { Self { cap, - tokens: cap.map_or(0.0, Cap::burst_bytes), + tokens: cap.map_or(0.0, burst_bytes), last: now, full: VecDeque::new(), } @@ -179,8 +84,8 @@ impl Meter { self.refill(now); self.tokens = match (self.cap, cap) { (_, None) => 0.0, - (None, Some(cap)) => cap.burst_bytes(), - (Some(_), Some(cap)) => self.tokens.min(cap.burst_bytes()), + (None, Some(cap)) => burst_bytes(cap), + (Some(_), Some(cap)) => self.tokens.min(burst_bytes(cap)), }; if cap.is_none() { self.full.clear(); @@ -215,7 +120,7 @@ impl Meter { }; let rate = cap.rate.as_bps() as f64 / 8.0; - let burst = cap.burst_bytes(); + let burst = burst_bytes(cap); let tokens = self.tokens + rate * elapsed.as_secs_f64(); if tokens > burst { // The bucket filled partway through and discarded credit from then until now. @@ -284,7 +189,7 @@ mod tests { fn steering_never_exceeds_the_cap() { for bps in [0, 1, 8_000, 2_500_000, u64::MAX] { let cap = Cap::new(Rate::from_bps(bps)); - assert!(cap.steer() <= cap.rate, "{bps}"); + assert!(steer(cap) <= cap.rate, "{bps}"); } } @@ -446,15 +351,4 @@ mod tests { assert!(meter.charge_at(1000, t0 + Duration::from_secs(1)).is_ok()); assert!(meter.charge_at(1, t0 + Duration::from_secs(1)).is_err()); } - - #[test] - fn the_handle_shares_live_updates() { - let limit = Limit::unlimited(); - let mut rx = limit.clone().subscribe(); - assert_eq!(limit.get(), None); - limit.clone().set(cap()); - assert!(rx.has_changed().unwrap()); - assert_eq!(*rx.borrow_and_update(), Some(cap())); - assert_eq!(limit.get(), Some(cap())); - } } diff --git a/rs/moq-webrtc/src/server/mod.rs b/rs/moq-webrtc/src/server/mod.rs index ba76f6d12bc..a89428196b2 100644 --- a/rs/moq-webrtc/src/server/mod.rs +++ b/rs/moq-webrtc/src/server/mod.rs @@ -62,6 +62,8 @@ struct AcceptedSession { session: Option, registration: Option, cancel: Option>, + /// How long an ingest the peer ended with a `DELETE` stays up. + linger: Duration, role: &'static str, } @@ -94,7 +96,7 @@ impl AcceptedSession { // gets the tail; dropping this future ends that early. A peer that vanishes instead // closes the broadcast at once. tracing::debug!(role = self.role, "webrtc session terminated by DELETE"); - let linger = self.server.config().linger; + let linger = self.linger; if let Some(finished) = session.finish(linger)? { tracing::info!(role = self.role, ?linger, "serving the finished broadcast"); finished.wait().await; @@ -126,6 +128,7 @@ pub(crate) fn session_location(uri: &Uri, resource_id: &str) -> Option, - /// Address the shared WebRTC media socket binds to. Every WHIP/WHEP session - /// shares this one UDP port (demuxed by ICE ufrag), so a deployment opens - /// exactly one media port in its firewall. `0.0.0.0:0` (the default) lets - /// the OS pick a port, which is fine for dev/loopback; production pins it. - pub udp_bind: SocketAddr, + /// The shared WebRTC media socket. Every WHIP/WHEP session shares this one UDP port + /// (demuxed by ICE ufrag), so a deployment opens exactly one media port in its firewall. + /// Defaults to binding `0.0.0.0:0`, letting the OS pick a port, which is fine for + /// dev/loopback; production pins it. + pub socket: Socket, +} - /// How long a superseded group of an ingested media track stays fresh, or `None` for no - /// publisher limit. - /// - /// A freshness bound, not a delivery one: it never makes a subscriber play further - /// behind live, it caps how far back a FETCH can still reach. Defaults to - /// [`MAX_AGE`](hang::container::MAX_AGE), which suits a segmented - /// egress (HLS/DASH) reading the broadcast downstream: it may only advertise segments - /// that are still fetchable. Lower it when nothing reads history. - /// - /// Ingest only (`server publish` / WHIP): WHEP egress reads a broadcast someone else - /// declared, so it ignores this. - pub max_age: Option, - - /// Connection allocator each ingested track claims its peak-hold bitrate on. - /// Ingest only (`server publish` / WHIP); WHEP egress ignores this. - pub bandwidth: moq_net::bandwidth::Allocator, - - /// How long an ingest the peer ended with a `DELETE` stays up, so a subscriber that - /// arrives after the end still gets the tail. Defaults to [`moq_mux::Linger::DEFAULT`]; - /// zero closes it at once. Ingest only (`server publish` / WHIP). - pub linger: Duration, +/// Where the shared WebRTC media socket comes from. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum Socket { + /// Bind a UDP socket at this address on the first accept. + Bind(SocketAddr), } -impl Default for Config { +impl Default for Socket { fn default() -> Self { - Self { - ice_candidates: Vec::new(), - udp_bind: SocketAddr::from(([0, 0, 0, 0], 0)), - max_age: Some(hang::container::MAX_AGE), - bandwidth: moq_net::bandwidth::Allocator::unlimited(), - linger: moq_mux::Linger::DEFAULT, - } + Self::Bind(SocketAddr::from(([0, 0, 0, 0], 0))) } } @@ -210,20 +193,22 @@ impl Server { pub(crate) async fn mux(&self) -> Result<&Mux> { self.inner .mux - .get_or_try_init(|| Mux::bind(self.inner.config.udp_bind, &self.inner.config.ice_candidates)) + .get_or_try_init(|| match self.inner.config.socket { + Socket::Bind(addr) => Mux::bind(addr, &self.inner.config.ice_candidates), + }) .await } - /// Router for `server publish` (WHIP). Mount under whichever HTTP path - /// the deployment prefers (`/whip`, `/`, ...). + /// Router for `server publish` (WHIP), publishing each session as `ingest` says. Mount + /// under whichever HTTP path the deployment prefers (`/whip`, `/`, ...). /// /// The router derives the broadcast name from the request path and performs /// no authentication. To own the route and authorize requests yourself /// (resolving the broadcast name from a verified token), skip the router and /// call [`whip::accept`] directly from your own handler. Only with the `server` feature. #[cfg(feature = "server")] - pub fn publish_router(&self, publisher: moq_net::origin::Producer) -> Router { - whip::router(self.clone(), publisher) + pub fn publish_router(&self, publisher: moq_net::origin::Producer, ingest: moq_mux::Ingest) -> Router { + whip::router(self.clone(), publisher, ingest) } /// Router for `server subscribe` (WHEP). Mount under whichever HTTP path @@ -238,10 +223,6 @@ impl Server { whep::router(self.clone(), subscriber) } - pub(crate) fn config(&self) -> &Config { - &self.inner.config - } - /// Register a session under its resource id, returning the cancel receiver. /// Called by [`whip::accept`] / [`whep::accept`] before returning the /// negotiated session runner. diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index 9ebe397464d..880ad015fe4 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -97,7 +97,7 @@ async fn accept_offer( return Err(Error::InvalidSdp("expected Content-Type: application/sdp".into())); } let offer = std::str::from_utf8(&body).map_err(|err| Error::InvalidSdp(err.to_string()))?; - accept(server, subscriber, moq_net::Path::new(path)?, offer).await + accept(server, Request::new(subscriber, moq_net::Path::new(path)?, offer)).await } #[cfg(feature = "server")] @@ -105,8 +105,31 @@ async fn delete(State(state): State, Path(path): Path) -> S crate::server::delete(&state.server, &path) } -/// Accept a WHEP SDP offer and egress the MoQ broadcast `broadcast` (a path -/// relative to `subscriber`'s root) to the negotiated WebRTC peer. +/// A WHEP play for [`accept`]: the raw SDP offer, and the consumer and broadcast its media +/// comes from. +#[non_exhaustive] +pub struct Request<'a> { + /// The consumer the broadcast is read from. + pub subscriber: &'a moq_net::origin::Consumer, + /// The broadcast to play, relative to the consumer's root. + pub broadcast: moq_net::Path, + /// The raw SDP offer. + pub offer: &'a str, +} + +impl<'a> Request<'a> { + /// Play `broadcast` (a path relative to `subscriber`'s root) to the peer that sent `offer`. + pub fn new(subscriber: &'a moq_net::origin::Consumer, broadcast: impl Into, offer: &'a str) -> Self { + Self { + subscriber, + broadcast: broadcast.into(), + offer, + } + } +} + +/// Accept a WHEP SDP offer and egress the [`Request`]'s broadcast to the negotiated WebRTC +/// peer. /// /// This is the negotiation core behind [`Server::subscribe_router`], exposed so an embedder can own /// the HTTP route and authentication: verify the request, resolve the authorized @@ -129,15 +152,15 @@ async fn delete(State(state): State, Path(path): Path) -> S /// `Content-Type: application/sdp` request header. Fails with [`Error::InvalidSdp`] /// on a malformed offer, and surfaces a broadcast still unannounced after 5s (or one /// outside `subscriber`'s scope) as [`Error::Moq`]. -pub async fn accept( - server: &Server, - subscriber: &moq_net::origin::Consumer, - broadcast: impl Into, - offer: &str, -) -> Result { +pub async fn accept(server: &Server, request: Request<'_>) -> Result { + let Request { + subscriber, + broadcast, + offer, + } = request; let offer = sdp::parse_offer(offer)?; - let source = resolve(subscriber, broadcast.into()).await?; + let source = resolve(subscriber, broadcast).await?; let codecs = source.catalog_codecs(); if codecs.is_empty() { return Err(Error::NoRenditions); @@ -175,6 +198,7 @@ pub async fn accept( session: Some(session), registration: Some(registration), cancel: Some(cancel), + linger: Duration::ZERO, role: "whep server", }, }) diff --git a/rs/moq-webrtc/src/server/whip.rs b/rs/moq-webrtc/src/server/whip.rs index a9da35fdeb8..1da2a31e2bf 100644 --- a/rs/moq-webrtc/src/server/whip.rs +++ b/rs/moq-webrtc/src/server/whip.rs @@ -25,14 +25,19 @@ pub use crate::server::Response; struct RouterState { server: Server, publisher: moq_net::origin::Producer, + ingest: moq_mux::Ingest, } /// Build the WHIP axum router. Only with the `server` feature. #[cfg(feature = "server")] -pub(crate) fn router(server: Server, publisher: moq_net::origin::Producer) -> Router { +pub(crate) fn router(server: Server, publisher: moq_net::origin::Producer, ingest: moq_mux::Ingest) -> Router { Router::new() .route("/{*path}", post(handle).delete(delete)) - .with_state(RouterState { server, publisher }) + .with_state(RouterState { + server, + publisher, + ingest, + }) } #[cfg(feature = "server")] @@ -43,7 +48,7 @@ async fn handle( headers: HeaderMap, body: Bytes, ) -> HttpResponse { - match accept_offer(&state.server, &state.publisher, &path, &headers, body).await { + match accept_offer(&state, &path, &headers, body).await { Ok(response) => { let Response { resource_id, @@ -71,19 +76,15 @@ async fn handle( /// Router glue: enforce the WHIP `Content-Type` then hand the raw offer to /// [`accept`], using the request path as the (unauthenticated) broadcast name. #[cfg(feature = "server")] -async fn accept_offer( - server: &Server, - publisher: &moq_net::origin::Producer, - path: &str, - headers: &HeaderMap, - body: Bytes, -) -> Result { +async fn accept_offer(state: &RouterState, path: &str, headers: &HeaderMap, body: Bytes) -> Result { if !is_sdp(headers) { return Err(Error::InvalidSdp("expected Content-Type: application/sdp".into())); } let offer = std::str::from_utf8(&body).map_err(|err| Error::InvalidSdp(err.to_string()))?; let broadcast = moq_net::Path::new(path)?; - accept(server, Request::new(publisher, broadcast, offer)).await + let mut request = Request::new(&state.publisher, broadcast, offer); + request.ingest = state.ingest.clone(); + accept(&state.server, request).await } #[cfg(feature = "server")] @@ -92,31 +93,33 @@ async fn delete(State(state): State, Path(path): Path) -> S } /// A WHIP publish for [`accept`]: the raw SDP offer, the producer and broadcast its media -/// goes to, and an optional bitrate cap. +/// goes to, how it is published, and an optional bitrate cap. +#[non_exhaustive] pub struct Request<'a> { - publisher: &'a moq_net::origin::Producer, - broadcast: moq_net::Path, - offer: &'a str, - rate: rate::Limit, + /// The producer the media is published into. + pub publisher: &'a moq_net::origin::Producer, + /// The broadcast to publish, relative to the producer's root. + pub broadcast: moq_net::Path, + /// The raw SDP offer. + pub offer: &'a str, + /// How the ingested broadcast is published. + pub ingest: moq_mux::Ingest, + /// A live cap on the session's media (see [`accept`]), or `None` to never cap it. + pub rate: Option, } impl<'a> Request<'a> { - /// Publish the media negotiated by `offer` into `publisher` under `broadcast` (a path - /// relative to that producer's root), uncapped. + /// Publish the media negotiated by `offer` into `publisher` under `broadcast` with the + /// default [`Ingest`](moq_mux::Ingest), uncapped. pub fn new(publisher: &'a moq_net::origin::Producer, broadcast: impl Into, offer: &'a str) -> Self { Self { publisher, broadcast: broadcast.into(), offer, - rate: rate::Limit::unlimited(), + ingest: moq_mux::Ingest::default(), + rate: None, } } - - /// Cap the session's media at `rate`, a live handle (see [`accept`]). - pub fn with_rate(mut self, rate: rate::Limit) -> Self { - self.rate = rate; - self - } } /// Accept a WHIP SDP offer and publish the negotiated WebRTC media into the @@ -142,17 +145,24 @@ impl<'a> Request<'a> { /// [`moq_net::Error::Unauthorized`] if the broadcast is /// outside the producer's scope. /// -/// [`Request::with_rate`] caps the session's media; a request is uncapped by default. The answer +/// [`Request::rate`] caps the session's media; a request is uncapped by default. The answer /// carries a `b=TIAS` line at the cap it holds when the offer is accepted, and the session -/// repeats a REMB on every video line that negotiated one, following [`rate::Limit::set`] -/// at once. Both steer to nine tenths of the cap, leaving room for audio and keyframe -/// overshoot. A publisher that ignores them, sending media past the cap plus its burst, -/// ends [`Response::run`] with [`Error::RateLimited`]. +/// repeats a REMB on every video line that negotiated one, following +/// [`Limit::set`](moq_net::bandwidth::Limit::set) at once. Both steer to nine tenths of the +/// cap, leaving room for audio and keyframe overshoot. A publisher that ignores them, sending +/// media past the cap plus its burst, ends [`Response::run`] with [`Error::RateLimited`]. +/// moq-webrtc never renegotiates, so the TIAS stays at the starting cap: a session that +/// starts uncapped steers only through REMB, and raising or lifting a starting cap frees the +/// publisher only as far as that TIAS allows. +/// +/// A peer that ends the session with a `DELETE` leaves its finished broadcast up for the +/// ingest's [linger](moq_mux::Ingest::linger). pub async fn accept(server: &Server, request: Request<'_>) -> Result { let Request { publisher, broadcast, offer, + ingest, rate, } = request; let offer = sdp::parse_offer(offer)?; @@ -161,10 +171,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { // any mux work. It announces only once negotiation succeeds (below). // The session's sink holds the route, so it stays announced until the session ends. let route = publisher.route(&broadcast, moq_net::origin::RouteOptions::hidden())?; - let config = moq_mux::catalog::Config::default() - .with_max_age(server.config().max_age) - .with_bandwidth(server.config().bandwidth.clone()); - let sink = Box::new(IngestSink::routed(route.clone(), config)?); + let sink = Box::new(IngestSink::routed(route.clone(), ingest.catalog())?); // Register a session on the shared media mux: known ICE credentials (so the // demux routes this peer's STUN by ufrag), an inbox to read datagrams from, @@ -191,17 +198,20 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { let resource_id = sdp::new_resource_id(); let socket = crate::ice::Socket::new(mux.socket(), mux.candidates().to_vec(), inbound)?; - let session = session::Session::ingest(rtc, socket, sink)?.with_rate(&rate); + let mut session = session::Session::ingest(rtc, socket, sink)?; + if let Some(rate) = &rate { + session = session.with_rate(rate); + } // Register before returning so a DELETE that races the first packet still // finds the session; Response::run unregisters itself when it ends. let cancel = server.register_session(resource_id.clone()); - let cap = rate.get(); + let cap = rate.as_ref().and_then(moq_net::bandwidth::Limit::get); tracing::info!(%broadcast, %instance, cap = cap.map(|cap| cap.rate.as_bps()), "whip publish accepted"); let mut answer = sdp::render_answer(&answer); if let Some(cap) = cap { - answer = sdp::cap_answer(&answer, cap.steer()); + answer = sdp::cap_answer(&answer, rate::steer(cap)); } Ok(Response { resource_id: resource_id.clone(), @@ -212,6 +222,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { session: Some(session), registration: Some(registration), cancel: Some(cancel), + linger: ingest.linger, role: "whip server", }, }) @@ -261,10 +272,11 @@ mod tests { async fn a_capped_answer_carries_tias() { let server = Server::new(crate::server::Config::default()); let origin = moq_tokio::origin::spawn(); - let cap = rate::Cap::new(moq_net::bandwidth::Rate::from_mbps(1)); + let cap = moq_net::bandwidth::Cap::new(moq_net::bandwidth::Rate::from_mbps(1)); let offer = offer(); let path = moq_net::Path::from_static("live/capped"); - let capped = Request::new(&origin, path, &offer).with_rate(rate::Limit::new(cap)); + let mut capped = Request::new(&origin, path, &offer); + capped.rate = Some(moq_net::bandwidth::Limit::new(cap)); let capped = accept(&server, capped).await.unwrap(); assert!(capped.answer.contains("\r\nb=TIAS:900000\r\n"), "{}", capped.answer); str0m::change::SdpAnswer::from_sdp_string(&capped.answer).expect("str0m parses the capped answer"); diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index 385472754b5..c1b2d31ef07 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -21,7 +21,7 @@ use tokio::net::UdpSocket; use tokio::sync::mpsc; use crate::egress::{EgressClock, EgressSource, Format, WriteRequest}; -use crate::rate::{self, Cap, Meter}; +use crate::rate::{self, Meter}; use crate::{Error, Result, codec}; /// str0m's outbound video buffer depth (packets), which also backs NACK resends. @@ -150,12 +150,12 @@ impl Session { /// Meter an ingest against `limit`'s cap, following its updates, and steer the /// publisher under it with REMB on every video line that negotiated it. - pub(crate) fn with_rate(mut self, limit: &rate::Limit) -> Self { - let limit = limit.subscribe(); - let cap = *limit.borrow(); + pub(crate) fn with_rate(mut self, limit: &moq_net::bandwidth::Limit) -> Self { + let limit = limit.clone(); + let cap = limit.get(); self.rate = Some(IngestRate { meter: Meter::new(cap, Instant::now()), - limit: Some(limit), + limit, remb: Vec::new(), next_remb: Instant::now(), steered: cap.is_some(), @@ -226,24 +226,18 @@ impl Session { crate::egress::dispatch(&mut self.agent.rtc_mut(), req, wallclock); } - changed = async { - match self.rate.as_mut().and_then(|rate| rate.limit.as_mut()) { - Some(limit) => limit.changed().await.map(|()| *limit.borrow_and_update()), + cap = async { + match self.rate.as_mut() { + Some(rate) => rate.limit.changed().await, None => std::future::pending().await, } } => { let rate = self.rate.as_mut().expect("only a rated session watches its cap"); - match changed { - Ok(cap) => { - tracing::debug!(?cap, "ingest cap updated"); - rate.meter.set(cap, Instant::now()); - rate.steered |= cap.is_some(); - // REMB follows an update at once. - rate.next_remb = Instant::now(); - } - // Every handle is gone, so the cap can no longer change: keep the last one. - Err(_) => rate.limit = None, - } + tracing::debug!(?cap, "ingest cap updated"); + rate.meter.set(cap, Instant::now()); + rate.steered |= cap.is_some(); + // REMB follows an update at once. + rate.next_remb = Instant::now(); } _ = async { @@ -396,7 +390,7 @@ impl Session { // A REMB ceiling holds until the next one replaces it, so a lifted cap keeps sending // the largest REMB can carry rather than going quiet and leaving the old ceiling. let bitrate = match rate.meter.cap() { - Some(cap) => str0m::bwe::Bitrate::bps(cap.steer().as_bps()), + Some(cap) => str0m::bwe::Bitrate::bps(rate::steer(cap).as_bps()), None => str0m::bwe::Bitrate::MAX, }; let mut rtc = self.agent.rtc_mut(); @@ -421,8 +415,8 @@ impl Session { /// steers the publisher under it. struct IngestRate { meter: Meter, - /// Live cap updates; `None` once every handle is dropped. - limit: Option>>, + /// Live cap updates. + limit: moq_net::bandwidth::Limit, /// Video lines that negotiated REMB. remb: Vec, next_remb: Instant, From 1402bf2d48753e5f1198721a30f897a9ddf0a904 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 17:30:54 -0800 Subject: [PATCH 3/3] fix(net,webrtc,rtmp,srt,mux): address review threads on gateway ingest - Limit::get marks the cap seen, so a session's meter and change cursor come from one read and a set-and-restore between them is still reported. - RTMP and SRT README examples pass an Ingest to Publish::accept. - Scope the Ingest doc to RTMP, SRT, and WHIP; merge Config's derives. Co-Authored-By: Claude Opus 5.5 --- rs/moq-mux/src/ingest.rs | 4 ++-- rs/moq-net/src/model/bandwidth.rs | 27 +++++++++++++++++++++------ rs/moq-rtmp/README.md | 2 +- rs/moq-srt/README.md | 8 ++++++-- rs/moq-webrtc/src/server/mod.rs | 3 +-- rs/moq-webrtc/src/server/whip.rs | 5 +++-- rs/moq-webrtc/src/session.rs | 4 ++-- 7 files changed, 36 insertions(+), 17 deletions(-) diff --git a/rs/moq-mux/src/ingest.rs b/rs/moq-mux/src/ingest.rs index bb9fa95cfd9..e5310966d2b 100644 --- a/rs/moq-mux/src/ingest.rs +++ b/rs/moq-mux/src/ingest.rs @@ -5,8 +5,8 @@ use std::time::Duration; /// How a gateway publishes what it ingests: the media tracks' max age, the allocator they /// claim on, and how long a cleanly ended broadcast stays up. /// -/// Every protocol gateway takes one per ingest, so the same knobs mean the same thing on -/// RTMP, SRT, and WHIP. +/// RTMP, SRT, and WHIP each take one per ingest, so the same knobs mean the same thing +/// across them. #[derive(Clone, Debug)] #[non_exhaustive] pub struct Ingest { diff --git a/rs/moq-net/src/model/bandwidth.rs b/rs/moq-net/src/model/bandwidth.rs index 75b9206240c..f3d71e0eac6 100644 --- a/rs/moq-net/src/model/bandwidth.rs +++ b/rs/moq-net/src/model/bandwidth.rs @@ -156,13 +156,14 @@ impl Limit { } } - /// The current cap, if any. - pub fn get(&self) -> Option { - *self.cap.read() + /// The current cap, if any, which [`poll_changed`](Self::poll_changed) then counts as seen. + pub fn get(&mut self) -> Option { + self.last = *self.cap.read(); + self.last } /// The cap once it differs from the one this handle last saw: at its creation or clone, - /// or its last report. + /// its last [`get`](Self::get), or its last report. #[cfg_attr(feature = "async", kio::wrapper)] pub fn poll_changed(&mut self, waiter: &kio::Waiter) -> Poll> { let last = self.last; @@ -184,7 +185,7 @@ impl Clone for Limit { fn clone(&self) -> Self { Self { cap: self.cap.clone(), - last: self.get(), + last: *self.cap.read(), } } } @@ -197,7 +198,7 @@ impl Default for Limit { impl std::fmt::Debug for Limit { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_tuple("Limit").field(&self.get()).finish() + f.debug_tuple("Limit").field(&*self.cap.read()).finish() } } @@ -1347,6 +1348,20 @@ mod tests { assert_eq!(late.poll_changed(&kio::Waiter::noop()), Poll::Ready(None)); } + #[test] + fn a_limit_get_marks_the_cap_seen() { + let low = Cap::new(Rate::from_kbps(8)); + let high = Cap::new(Rate::from_kbps(16)); + let limit = Limit::new(low); + let mut watch = limit.clone(); + + // A cap read between the clone and a restore still reports the restore. + limit.set(high); + assert_eq!(watch.get(), Some(high)); + limit.set(low); + assert_eq!(watch.poll_changed(&kio::Waiter::noop()), Poll::Ready(Some(low))); + } + /// Priorities matching `hang`'s, which is what the allocator sees in practice. const AUDIO: i8 = 80; const VIDEO: i8 = 60; diff --git a/rs/moq-rtmp/README.md b/rs/moq-rtmp/README.md index e08e391d9e6..b689d73380a 100644 --- a/rs/moq-rtmp/README.md +++ b/rs/moq-rtmp/README.md @@ -45,7 +45,7 @@ while let Some(request) = server.accept().await { // per token with `with_root` / `scope`. match request { moq_rtmp::Request::Publish(publish) => match authorize(publish.app(), publish.stream_key()).await { - Ok(path) => { let _ = publish.accept(&origin, &path).await; } + Ok(path) => { let _ = publish.accept(&origin, &path, &moq_mux::Ingest::default()).await; } Err(err) => { let _ = publish.reject(&err.to_string()).await; } }, moq_rtmp::Request::Play(play) => match authorize(play.app(), play.stream_key()).await { diff --git a/rs/moq-srt/README.md b/rs/moq-srt/README.md index d729b7b4215..ce10eb5da47 100644 --- a/rs/moq-srt/README.md +++ b/rs/moq-srt/README.md @@ -41,10 +41,14 @@ while let Some(request) = server.accept().await { // as a token if you like), verify it, and pick the broadcast path. match request { moq_srt::Request::Publish(publish) => { - tokio::spawn(publish.accept(&origin, "live/cam0")); + let origin = origin.clone(); + tokio::spawn(async move { + publish.accept(&origin, "live/cam0", &moq_mux::Ingest::default()).await + }); } moq_srt::Request::Subscribe(subscribe) => { - tokio::spawn(subscribe.accept(&consumer, "live/cam0")); + let consumer = consumer.clone(); + tokio::spawn(async move { subscribe.accept(&consumer, "live/cam0").await }); } } // ...or call `.reject(moq_srt::Reject::Forbidden)` on the `Publish` / diff --git a/rs/moq-webrtc/src/server/mod.rs b/rs/moq-webrtc/src/server/mod.rs index a89428196b2..54a85e81bd3 100644 --- a/rs/moq-webrtc/src/server/mod.rs +++ b/rs/moq-webrtc/src/server/mod.rs @@ -126,9 +126,8 @@ pub(crate) fn session_location(uri: &Uri, resource_id: &str) -> Option) -> Result { let resource_id = sdp::new_resource_id(); let socket = crate::ice::Socket::new(mux.socket(), mux.candidates().to_vec(), inbound)?; let mut session = session::Session::ingest(rtc, socket, sink)?; - if let Some(rate) = &rate { + let mut cap = None; + if let Some(mut rate) = rate { + cap = rate.get(); session = session.with_rate(rate); } // Register before returning so a DELETE that races the first packet still // finds the session; Response::run unregisters itself when it ends. let cancel = server.register_session(resource_id.clone()); - let cap = rate.as_ref().and_then(moq_net::bandwidth::Limit::get); tracing::info!(%broadcast, %instance, cap = cap.map(|cap| cap.rate.as_bps()), "whip publish accepted"); let mut answer = sdp::render_answer(&answer); diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index c4c18216103..3834e1d7570 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -150,8 +150,8 @@ impl Session { /// Meter an ingest against `limit`'s cap, following its updates, and steer the /// publisher under it with REMB on every video line that negotiated it. - pub(crate) fn with_rate(mut self, limit: &moq_net::bandwidth::Limit) -> Self { - let limit = limit.clone(); + pub(crate) fn with_rate(mut self, mut limit: moq_net::bandwidth::Limit) -> Self { + // One read sets both the meter and the cap `changed` compares against. let cap = limit.get(); self.rate = Some(IngestRate { meter: Meter::new(cap, Instant::now()),