diff --git a/dart/moq/lib/src/durations.dart b/dart/moq/lib/src/durations.dart index 02b39047775..5bd01205610 100644 --- a/dart/moq/lib/src/durations.dart +++ b/dart/moq/lib/src/durations.dart @@ -26,7 +26,7 @@ extension BackoffDuration on MoqBackoff { /// Duration views over the subscription knobs. extension SubscriptionDuration on MoqSubscription { /// Upper bound on buffering before a stalled group is skipped. - Duration get maxAge => Duration(microseconds: maxAgeUs); + Duration get maxDelay => Duration(microseconds: maxDelayUs); } /// Duration views over the publisher-side track settings. diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index c8b5e6337b9..572a36a8792 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -60,12 +60,12 @@ class FfiConverterMoqFetchGroupOptions { class MoqSubscription { final int priority; - final int maxAgeUs; + final int maxDelayUs; final int? groupStart; final int? groupEnd; MoqSubscription({ this.priority = 0, - this.maxAgeUs = 0, + this.maxDelayUs = 0, this.groupStart = null, this.groupEnd = null, }); @@ -83,11 +83,11 @@ class FfiConverterMoqSubscription { ); final priority = priority_lifted.value; new_offset += priority_lifted.bytesRead; - final maxAgeUs_lifted = FfiConverterUInt64.read( + final maxDelayUs_lifted = FfiConverterUInt64.read( Uint8List.view(buf.buffer, new_offset), ); - final maxAgeUs = maxAgeUs_lifted.value; - new_offset += maxAgeUs_lifted.bytesRead; + final maxDelayUs = maxDelayUs_lifted.value; + new_offset += maxDelayUs_lifted.bytesRead; final groupStart_lifted = FfiConverterOptionalUInt64.read( Uint8List.view(buf.buffer, new_offset), ); @@ -101,7 +101,7 @@ class FfiConverterMoqSubscription { return LiftRetVal( MoqSubscription( priority: priority, - maxAgeUs: maxAgeUs, + maxDelayUs: maxDelayUs, groupStart: groupStart, groupEnd: groupEnd, ), @@ -112,7 +112,7 @@ class FfiConverterMoqSubscription { static RustBuffer lower(MoqSubscription value) { final total_length = FfiConverterUInt8.allocationSize(value.priority) + - FfiConverterUInt64.allocationSize(value.maxAgeUs) + + FfiConverterUInt64.allocationSize(value.maxDelayUs) + FfiConverterOptionalUInt64.allocationSize(value.groupStart) + FfiConverterOptionalUInt64.allocationSize(value.groupEnd) + 0; @@ -128,7 +128,7 @@ class FfiConverterMoqSubscription { Uint8List.view(buf.buffer, new_offset), ); new_offset += FfiConverterUInt64.write( - value.maxAgeUs, + value.maxDelayUs, Uint8List.view(buf.buffer, new_offset), ); new_offset += FfiConverterOptionalUInt64.write( @@ -144,7 +144,7 @@ class FfiConverterMoqSubscription { static int allocationSize(MoqSubscription value) { return FfiConverterUInt8.allocationSize(value.priority) + - FfiConverterUInt64.allocationSize(value.maxAgeUs) + + FfiConverterUInt64.allocationSize(value.maxDelayUs) + FfiConverterOptionalUInt64.allocationSize(value.groupStart) + FfiConverterOptionalUInt64.allocationSize(value.groupEnd) + 0; @@ -12554,7 +12554,7 @@ void _checkApiChecksums() { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqbroadcastconsumer_subscribe_media() != - 29917) { + 8119) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqbroadcastconsumer_subscribe_track() != diff --git a/doc/bin/cli.md b/doc/bin/cli.md index 2ad9a9022a3..edd7ae84772 100644 --- a/doc/bin/cli.md +++ b/doc/bin/cli.md @@ -467,8 +467,9 @@ See [Authentication](/bin/relay/auth). ## Retention and latency `import --max-age` (default 30 s) tells relays how long to keep old -groups fetchable, which the [HLS gateway](/bin/hls) depends on. `export --max-age` (default 500 ms) is how long *this* consumer waits for a -stalled group before skipping. Raising the first never delays playback. +groups fetchable, which the [HLS gateway](/bin/hls) depends on. `export --max-delay` (default 500 ms) is how far a stalled group may fall +behind the live edge before *this* consumer skips it. Raising the first never delays playback. +`export ts` still spells its budget `--max-age`. For `export ts`, `--max-age` also bounds how long the muxer holds a leading track for a lagging one. Frames go out in media-time order across all tracks, diff --git a/doc/bin/relay/cluster.md b/doc/bin/relay/cluster.md index eb169faf277..5aba2c0ff5b 100644 --- a/doc/bin/relay/cluster.md +++ b/doc/bin/relay/cluster.md @@ -35,7 +35,7 @@ a cheaper route with that epoch, each subscription continues on the new route from the first frame its readers lack, so they see every frame once, mid-group included. A route that is still up finishes the groups it has open, overlapping the new one. A group neither route delivers is -dropped once the readers' max age has passed it. A route through the subscribing peer +dropped once the readers' max delay has passed it. A route through the subscribing peer itself is never used. A publisher whose groups restart, such as an encoder restarting from group 0, publishes under a new epoch, which replaces the old broadcast instead of resuming it. A route without an epoch, including every diff --git a/doc/concept/audio-jitter.md b/doc/concept/audio-jitter.md index 9aac9465b02..b7c18c0f72e 100644 --- a/doc/concept/audio-jitter.md +++ b/doc/concept/audio-jitter.md @@ -50,7 +50,7 @@ as packets come and lets the playback buffer hold the target, rather than pacing reads to the speaker. A frame dropped by the relay is never observed, which is correct only while the -drop is not the receiver's own doing. The subscription's max age drops groups +drop is not the receiver's own doing. The subscription's max delay drops groups before any container sees them, at the relay and in the receiver's own transport subscriber, so a subscription cut to the target hides every frame later than the target: the estimate creeps up one bucket at a time while the frames it @@ -404,7 +404,7 @@ Supported or refused, not warned about and continued. In the browser this is the numeric `delay` setting; natively it is `decode::Options::delay`, where `None` selects the estimator. The two spell the -same thing the same way on purpose. It is distinct from `max_age`, which is the +same thing the same way on purpose. It is distinct from `max_delay`, which is the live-edge skip budget and not a buffer. ## Constants diff --git a/doc/concept/moq-lite.md b/doc/concept/moq-lite.md index 3a9da934da7..ff5e6d433c1 100644 --- a/doc/concept/moq-lite.md +++ b/doc/concept/moq-lite.md @@ -315,15 +315,15 @@ Each subscription carries the knobs that decide behavior under congestion: | --- | --- | | **Priority** (0..255) | Higher-priority tracks get bandwidth first. Audio above video, base layer above enhancement. | | **Order** | Which group to send first when several are pending. Newest first for live, oldest first for catch-up. | -| **Max age** | How old a non-latest group may get before it is skipped. Zero means "live edge only", and raising it is also what asks for history. | +| **Max delay** | How far a non-latest group may fall behind the live edge before it is skipped. Zero means "live edge only", and raising it is also what asks for history. | -Max age is measured on the media timeline, not the wall clock, so a backlog -delivered as a burst is still old while a congestion stall never expires +Max delay is measured on the media timeline, not the wall clock, so a backlog +delivered as a burst is still late while a congestion stall never expires anything on its own. Both ends apply it: the publisher skips a group rather than sending it, and the subscriber skips it again as it reads, since the publisher only ever sees the most tolerant budget across its subscribers. -A route failover is invisible to max age: a group open across the change carries +A route failover is invisible to max delay: a group open across the change carries on from the new route at the frame where the old one stopped, and a group only a replaced route that went quiet still holds is given up once it falls a full budget behind the new route's live edge. A successor group with no timestamp @@ -349,7 +349,7 @@ IETF carries this value as MAX\_CACHE\_DURATION, received on every supported dra and sent from draft 17 onward. A relay reads it from FETCH\_OK as well as SUBSCRIBE\_OK, so a track it only fetches still learns its window. Drafts 14–16 remain receive-only for compatibility with older implementations. This is an approximate mapping: IETF measures wall -time, while max age uses media timestamps and always keeps the newest group. +time, while the publisher's retention window uses media timestamps and always keeps the newest group. EXPIRES describes subscription lifetime and does not set retention. Lite-07 encodes a finite limit as milliseconds plus one, with zero meaning no limit. @@ -360,7 +360,7 @@ timer cap schedules periodic age checks and does not shorten that window. Put together, a conference might use: -| Track | Priority | Order | Max age | +| Track | Priority | Order | Max delay | | --- | --- | --- | --- | | audio | 100 | ascending | 500 ms | | video | 50 | descending | 2 s | diff --git a/doc/lib/index.md b/doc/lib/index.md index ce003ab4bf4..718627a6467 100644 --- a/doc/lib/index.md +++ b/doc/lib/index.md @@ -38,7 +38,7 @@ how it looks in that language: - **Discover** broadcasts by prefix, wait for a specific one, or request one by path, including a path a prefix claim serves on demand. Advertise an exact path with `create_broadcast` then `announce` / `unannounce` (a broadcast is invisible to local consumers and peers alike until announced), or claim a path prefix with `dynamic(prefix, route)`. - **Publish and subscribe to media** with the hang catalog filled in from the bitstream, plus raw pixels or PCM in and out with the codec running inside the binding (VideoToolbox, Media Foundation, NVENC, openh264, Opus). A publisher follows the connection's send estimate through `session.bandwidth()`: reserve a share for an app-owned encoder, or pass the handle when encoding so the built-in video encoder follows the grant. - **Connection health.** `stats()` snapshots RTT, send/receive estimates, and byte/packet counters. `bandwidth()` divides that send estimate among tracks sharing the connection. -- **Raw tracks** of arbitrary bytes with timestamps, sparse or replayed groups, per-subscriber priority and max age, and best-effort datagrams. +- **Raw tracks** of arbitrary bytes with timestamps, sparse or replayed groups, per-subscriber priority and max delay, and best-effort datagrams. - **JSON tracks** in snapshot mode (latest value, merge-patch deltas, optional compression) or stream mode (append log). - **Fetch** a single group by sequence from the cache, decoded through the container or raw. - **Serve on demand**: accept track and broadcast requests as they arrive instead of publishing up front. diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index a16b9de00c2..0024787febb 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -52,9 +52,9 @@ for (;;) { - **Connections** race WebTransport against WebSocket. `new Connection({ url })` pools one connection per relay URL and reconnects with backoff, which the elements use. Supplying WebTransport/WebSocket options, discovery, delay, `goaway`, or a caller-owned origin selects a private loop; explicit `share: true` refuses those options. On a relay's GOAWAY the connection dials the replacement at once while the old session keeps serving its groups until it closes or the `goaway.handover` cap (default 10s, lowered to the relay's deadline) passes; the handle and its origin stay the same. An empty GOAWAY redials the same URL through a fresh DNS resolve. A redirect is followed onto the same host by default (`goaway.redirect: "follow"` lets the relay pick the host, `"ignore"` never moves), and moves the pooled entry to the new URL; a malformed or refused one, including a host change under a pinned certificate, ends the connection with `Error.RefusedRedirect` instead of reconnecting. `closed` settles when the handle is released (`null` on a clean close); the failure that stopped retrying the current URL is `error`, and a new URL recovers the same handle. A connection owns one send-rate sampler and one `Bandwidth.Allocator`; publishers reserve against it so their encoder targets sum to the estimate instead of each matching it. - **Bandwidth** (`Bandwidth.Allocator`) divides the connection's send-rate estimate by track priority, max-min fair within a tier. An idle track claims nothing. The receive side is untouched. - **Discovery** by any pattern scope (`origin.announced(scope)`, such as `room/*/chat`; default everything). A route event's `kind` says whether the route started, updated, or ended; its `prefix` is the covered prefix relative to the origin, and `captures` reports what the scope's wildcards matched when the prefix pins them. The consumer is an async iterable. `origin.broadcasts(scope)` is a live `Getter>` of the same covered prefixes for UIs that need the current set. A borrowed `Connection.origin` also exposes `dynamic(prefix, route)` for serving paths on demand. -- **Publisher retention** is optional `Track.Info.maxAge`, measured against media timestamps: omission sets no limit, while zero serves only the live edge. It clamps every subscriber's max age, and stalled media does not age out merely because wall time passes. Separately, cached groups nobody writes for 30 seconds are reclaimed, except a live track's newest group, which stays replayable until the track closes. -- **Subscriptions** carry a priority, a `Time.Milli` max age measured against media timestamps, and optional `groups` bounds. Groups arrive out of order and are read frame by frame, with `Error.TooFarBehind` when a reader asks for a frame the group never held and `Error.GroupTooLarge` when a write exceeds the cache budget and aborts the group. -- **Track ends**: `close()` ends a track at its live edge, while `finishAt(n)` declares the exclusive end ahead of it and still accepts the groups below. A subscriber reads the end with `final()` or awaits `finished()`. Group and datagram readers end once the live edge reaches the declared boundary, even while missing lower groups wait out the grace. The `closed` signal settles separately once every group below the end has arrived or was dropped; one reset before its header arrived is skipped after the subscription's max age on moq-lite (one second without one), or after one second on IETF. +- **Publisher retention** is optional `Track.Info.maxAge`, measured against media timestamps: omission sets no limit, while zero serves only the live edge. It clamps every subscriber's max delay, and stalled media does not age out merely because wall time passes. Separately, cached groups nobody writes for 30 seconds are reclaimed, except a live track's newest group, which stays replayable until the track closes. +- **Subscriptions** carry a priority, a `Time.Milli` max delay measured against media timestamps, and optional `groups` bounds. Subscription options use `maxDelay`; supplying the obsolete subscriber `maxAge` key throws a `TypeError` naming its replacement, including on `update()`. Groups arrive out of order and are read frame by frame, with `Error.TooFarBehind` when a reader asks for a frame the group never held and `Error.GroupTooLarge` when a write exceeds the cache budget and aborts the group. +- **Track ends**: `close()` ends a track at its live edge, while `finishAt(n)` declares the exclusive end ahead of it and still accepts the groups below. A subscriber reads the end with `final()` or awaits `finished()`. Group and datagram readers end once the live edge reaches the declared boundary, even while missing lower groups wait out the grace. The `closed` signal settles separately once every group below the end has arrived or was dropped; one reset before its header arrived is skipped after the subscription's max delay on moq-lite (one second without one), or after one second on IETF. - **Datagrams** on moq-lite 05+ and fetch-by-sequence for history. `track.fetchGroup(sequence)` on moq-lite resolves when the publisher sends the first response byte or finishes an empty group. A missing group rejects the fetch with `StreamCode.NotFound`, including every concurrent caller sharing that fetch. `fetchGroup(sequence, { signal })` abandons a pending fetch with the signal's reason; the shared stream is cancelled only once every caller has left. Once resolved, close the group instead. - **Errors**: deliberately closing a connection ends its received tracks cleanly. A peer close ends received tracks and open group readers with the session error and its close code. Errors live under one namespace: a stream reset throws `Error.Stream` with a `StreamCode`, while a session close gives `Error.Session` with a `SessionCode`. The registries are disjoint, so the same number means different things in each, and 64+ is yours. Named conditions such as `Error.TooFarBehind`, `Error.FrameTooLarge`, and `Error.GroupTooLarge` subclass `Error.Stream`, so one `code` check handles a condition raised here or reported by the peer. IETF streams use their own mapping: cancellation sends CANCELLED, other local failures send INTERNAL\_ERROR, and received codes remain opaque. - **Paths** with `Path.relative` for the cross-broadcast catalog references hang uses. A `Broadcast.Consumer` names its broadcast by `path`: the path it was requested at relative to the origin handle's root, or empty for a standalone broadcast. Those references resolve against it. Path patterns (`Path.Pattern`, `Path.Patterns`) are re-exported from [`@moq/pattern`](https://www.npmjs.com/package/@moq/pattern). Literal `Path` stays a coordinate. diff --git a/doc/lib/js/watch.md b/doc/lib/js/watch.md index ded3988fe7c..c4dd05b56b4 100644 --- a/doc/lib/js/watch.md +++ b/doc/lib/js/watch.md @@ -130,7 +130,8 @@ const dispose = el.signals.run((effect) => { Call `dispose()` from your framework's unmount cleanup when this subscription is no longer needed. Removing the element disables playback but keeps its -effects open so the same node can reconnect. +effects open so the same node can reconnect. Its audio graph is released and +rebuilt on return; pausing or muting keeps the graph warm. The effect re-runs whenever the catalog or the active broadcast changes, so a reconnect resubscribes on its own. A publisher that rewrites its catalog often diff --git a/doc/lib/rs/hang.md b/doc/lib/rs/hang.md index dfde9ad1953..7ad276472fd 100644 --- a/doc/lib/rs/hang.md +++ b/doc/lib/rs/hang.md @@ -14,7 +14,7 @@ that carry a timestamp with every frame. - **Catalog producer and consumer.** Typed `VideoConfig`, `AudioConfig` and text renditions, the `json` and `binary` data track sections, shared video properties (display size, rotation, flip), stalled hints, cross-broadcast rendition references, and the `archive` entry (each track's timeline track, optional replay path, store URL, and format version). Extend it with your own sections through a lock or `#[serde(flatten)]`, or read unknown sections as raw JSON. - **Containers.** `legacy`, `cmaf`, and `loc`, decoded for you; unknown kinds pass through untouched. -- **`Ordered`** reads a media track as timestamped frames, reorders groups, and skips ones that fall past your max age. +- **`Ordered`** reads a media track as timestamped frames, reorders groups, and skips ones that fall past your max delay. - **Codecs described**: H.264, H.265, VP8, VP9, AV1, AAC, Opus, PCM. ```bash diff --git a/doc/lib/rs/moq-mux.md b/doc/lib/rs/moq-mux.md index 4cddf9e00f7..8e9b7a838df 100644 --- a/doc/lib/rs/moq-mux.md +++ b/doc/lib/rs/moq-mux.md @@ -21,7 +21,7 @@ Turns existing container formats into hang broadcasts and back. This is what Importers parse the bitstream to fill the catalog (resolution, codec string, `description`), split groups at keyframes, and stamp timestamps. Exporters do -the inverse and skip stalled groups past a max age. Per-codec +the inverse and skip stalled groups past a max delay. Per-codec producers (`import::Opus`, H.264, and so on) are available for feeding frames you already have. diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index ba2a81162b2..53eb52814be 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -19,9 +19,9 @@ above ([hang](/lib/rs/hang)); relays and CDNs implement only this. - **Broadcasts** are created unannounced and invisible to everyone, then announced as an exact route, or served below a prefix with `dynamic`. A consumer of the same origin sees exactly what a peer sees. Discovery accepts pattern unions; events carry the advertised prefix and captures for a complete match. - **Epochs** identify publisher instances with a canonical UUIDv7 carried on each route (`Route::epoch`): the newest wins a path, and only routes with the same epoch resume a subscription; see [publisher epochs](/concept/moq-lite#publisher-epochs). - **Patterns** (`Pattern`, `Patterns`) are re-exported from [`moq-pattern`](https://docs.rs/moq-pattern). Literal `Path` stays a coordinate. -- **Tracks** carry groups with a priority, an optional publisher retention window (`Info::max_age`), and a timescale. Subscribers set their own priority and max age and can change them live. +- **Tracks** carry groups with a priority, an optional publisher retention window (`Info::max_age`), and a timescale. Subscribers set their own priority and max delay and can change them live. - **Groups** are written frame by frame and delivered on independent streams. Old groups are cached for fetch-by-sequence; stale groups are skipped per the subscriber's budget. -- **Track ends**: `finish()` ends a track at its live edge, while `finish_at(n)` declares the exclusive end ahead of it and still accepts the groups below. A subscriber awaits it with `finished()`. A remote track ends only once every group below its end has arrived or was dropped; one reset before its header arrived is skipped after the subscription's max age on moq-lite (one second without one), or after one second on IETF. +- **Track ends**: `finish()` ends a track at its live edge, while `finish_at(n)` declares the exclusive end ahead of it and still accepts the groups below. A subscriber awaits it with `finished()`. A remote track ends only once every group below its end has arrived or was dropped; one reset before its header arrived is skipped after the subscription's max delay on moq-lite (one second without one), or after one second on IETF. - **Datagrams** send a single small frame unreliably on moq-lite 05+ and moq-transport. - **Routes** record the relay hops and a cost, which is what the relay [cluster](/bin/relay/cluster) routes on. A hop of 0 marks the chain anonymous: `Route::is_anonymous()` is true, and that route ranks below every fully identified one. `Route::source()` says where a delivered route entered: `Source::Local`, or `Source::Peer(hop)` when a handle marked `origin::Producer::peer()` announced it. `origin::Consumer::local()` sees only the local ones. A handle marked `origin::Producer::upstream()` announces as a peer, and a consumer taken from it never sees a route another upstream handle announced, so a relay never transits between two upstream links. - **Stats** counters per broadcast and session, drained by [`moq-stats`](https://docs.rs/moq-stats). @@ -178,7 +178,7 @@ for hidden routes, so each local consumer decides. Use `Subscription::default().with_groups(2..=5)` to request only groups 2 through 5. `2..5` excludes group 5, and `..` leaves both ends unbounded. -The range limits the data eligible under the subscription's max-age budget; +The range limits the data eligible under the subscription's max delay budget; it does not fetch historical data by itself. A reader's `set_groups(2..=5)` applies a local limit. It preserves read diff --git a/doc/lib/rs/moq-video.md b/doc/lib/rs/moq-video.md index 7a5400308c3..5b11f376746 100644 --- a/doc/lib/rs/moq-video.md +++ b/doc/lib/rs/moq-video.md @@ -145,7 +145,7 @@ with geometry and color metadata intact; call `I420::into_data()` only when packed bytes are required. `decode::Config::scale_hint` is best effort and only a decoder with a hardware scaler honors it; `Frame::resize` is the exact-size operation. `decode::Consumer` takes `decode::Options`, which carries the -subscription's `start` and `max_age` beside the decoder config. +subscription's `start` and `max_delay` beside the decoder config. Linux/NVIDIA applications with a native Vulkan producer use `frame::vulkan::Importer`. Each reusable image is a dedicated, optimal-tiling diff --git a/doc/setup/upgrade.md b/doc/setup/upgrade.md index 80db25d5bfe..e85540c284b 100644 --- a/doc/setup/upgrade.md +++ b/doc/setup/upgrade.md @@ -87,6 +87,29 @@ These land with the next breaking release, not the 2026-09-23 train. broadcast that ends with media queued behind an undescribed track is an error rather than an empty `Ok(None)`. Restart the export to pick up a new rendition. +- **Subscriber staleness is max delay.** How far a group may fall behind the + live edge before a subscriber skips it is now `max_delay`, so it no longer + shares a name with a publisher's retention, which keeps `max_age`. In Rust, + `track::Subscription::max_age` and `with_max_age` are `max_delay` and + `with_max_delay`; moq-mux's `container::Consumer::set_max_age` and the fMP4, + MKV, FLV, H.264, and H.265 exports' `with_max_age` are `set_max_delay` and + `with_max_delay`; moq-audio's and moq-video's `decode::Options::max_age` is + `max_delay`, as is moq-audio's `decode::Consumer::max_age()`; and moq-rtmp's + `Play::with_max_age`, `Client::with_export_max_age`, + `listen::Config::export_max_age`, and `DEFAULT_MAX_AGE` are `with_max_delay`, + `with_export_max_delay`, `export_max_delay`, and `DEFAULT_MAX_DELAY`. In + TypeScript, `Track.Subscription`'s `maxAge` is `maxDelay`, as are + `Container.Consumer`'s `maxAge` prop and `@moq/watch`'s `Sync.out.maxAge`; + JavaScript refuses a `maxAge` key in subscription options or container consumer + props with a `TypeError` naming `maxDelay`, including when both keys are supplied + or `maxAge` is `undefined`. Untyped callers must rename it. + moq-ffi's `MoqSubscription`, `MoqAudioDecoderOutput`, and + `MoqVideoDecoderOutput` take `max_delay_us` (each binding in its own casing), + and so do C's `moq_subscription`, `moq_audio_decoder_output`, + `moq_video_decoder_output`, `moq_consume_video`, and `moq_consume_audio`. + `moq export fmp4`, `mkv`, `flv`, `h264`, `h265`, and `rtmp` take + `--max-delay`, and refuse `--max-age`. `track::Info::max_age`, + `MoqTrackInfo.max_age_us`, `moq import --max-age`, and `moq export ts --max-age` are unchanged, as is the wire. - **moq-relay auth takes the client-CA answer.** `auth::Config::validate` and `init` take `client_ca: bool`, whether any listener verifies client certificates, and `validate_client_ca` is gone. `moq --listen` with an diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index e9bccd9014e..b5d6ab02fe0 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -145,7 +145,7 @@ Both bounds may be refined to a Frame within their Group, so a subscription can The subscriber and publisher both indicate their delivery preference: - `Priority` indicates if Track A should be transmitted instead of Track B. -- `Subscriber Max Age` indicates the maximum age before a non-latest Group is dropped from live delivery; `Publisher Max Age` indicates the maximum age before a non-latest Group is dropped from the publisher's cache. +- `Subscriber Max Age` indicates how far a non-latest Group may fall behind the latest Group before it is dropped from live delivery; `Publisher Max Age` indicates the maximum age before a non-latest Group is dropped from the publisher's cache. The combination of these preferences enables the most important content to arrive during network degradation while still respecting encoding dependencies. diff --git a/go/wrapper/subscribe.go b/go/wrapper/subscribe.go index cf350a31f2d..6bfa4221408 100644 --- a/go/wrapper/subscribe.go +++ b/go/wrapper/subscribe.go @@ -69,7 +69,7 @@ func (b *BroadcastConsumer) FetchMediaGroup( // SubscribeMedia subscribes to a media track, decoded with the given container. // subscription tunes delivery priority, group range, and -// the max age; pass nil for defaults. Raise Subscription.MaxAgeUs to +// the max delay; pass nil for defaults. Raise Subscription.MaxDelayUs to // buffer instead of skipping a stalled group. func (b *BroadcastConsumer) SubscribeMedia( ctx context.Context, diff --git a/go/wrapper/types.go b/go/wrapper/types.go index 537450011ee..c7d4fdaff7b 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -59,7 +59,7 @@ type ( AnnounceEventUpdate = ffi.MoqAnnounceEventUpdate // AnnounceEventEnd reports that no route covers a prefix any more, carrying its last route. AnnounceEventEnd = ffi.MoqAnnounceEventEnd - // Subscription holds subscriber-side delivery preferences: priority, ordering, max age, and group range. + // Subscription holds subscriber-side delivery preferences: priority, ordering, max delay, and group range. Subscription = ffi.MoqSubscription // TrackInfo holds publisher-side track properties: priority, ordering, max age, and timescale. // A zero Priority is the least urgent, not the default; set 127 for the midpoint a nil TrackInfo uses. @@ -68,7 +68,7 @@ type ( Video = ffi.MoqVideo // VideoHint supplies catalog fields a video stream can't reveal itself, such as bitrate, filling only the gaps. VideoHint = ffi.MoqVideoHint - // VideoDecoderOutput configures what DecodeVideo delivers: an optional resize, a max age, and whether frames keep the decoder's surface (macOS only; refused elsewhere). + // VideoDecoderOutput configures what DecodeVideo delivers: an optional resize, a max delay, and whether frames keep the decoder's surface (macOS only; refused elsewhere). VideoDecoderOutput = ffi.MoqVideoDecoderOutput // VideoSurface is a decoded frame's platform surface, from VideoDecodedFrame.Surface: VideoSurfacePixelBuffer on macOS and iOS. VideoSurface = ffi.MoqVideoSurface diff --git a/js/flate/src/snapshot/snapshot.test.ts b/js/flate/src/snapshot/snapshot.test.ts index 19a68aac199..6de4bf30cc5 100644 --- a/js/flate/src/snapshot/snapshot.test.ts +++ b/js/flate/src/snapshot/snapshot.test.ts @@ -31,7 +31,7 @@ test("one single-frame group per update", async () => { // that arrives after both discards the superseded first group instead of replaying it. expect(await drain(track.subscribe(), false)).toEqual([bytes(2)]); - const subscriber = track.subscribe({ maxAge: REPLAY_LATENCY }).ordered(); + const subscriber = track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered(); const counts: number[] = []; for (;;) { const group = await subscriber.nextGroup(); diff --git a/js/flate/src/stream/stream.test.ts b/js/flate/src/stream/stream.test.ts index ebe4278cac0..ee8e961a5d3 100644 --- a/js/flate/src/stream/stream.test.ts +++ b/js/flate/src/stream/stream.test.ts @@ -4,7 +4,7 @@ import { DEFAULT_MAX_FRAME_SIZE } from "../codec.ts"; import { Consumer, Producer, Rolled } from "./index.ts"; // Ask for a replay window, so the superseded first group is delivered rather than skipped by the -// subscriber's default max-age budget. A rolled log is exactly the case where both groups matter. +// subscriber's default max delay budget. A rolled log is exactly the case where both groups matter. const REPLAY_LATENCY = Time.Milli(30_000); const payloads = (count: number) => Array.from({ length: count }, (_, n) => new Uint8Array(8).fill(n)); @@ -83,7 +83,7 @@ test("a second group is a rolled log, not a continuation", async () => { } track.close(); - const consumer = new Consumer({ track: track.subscribe({ maxAge: REPLAY_LATENCY }) }); + const consumer = new Consumer({ track: track.subscribe({ maxDelay: REPLAY_LATENCY }) }); expect(await consumer.next()).toBeDefined(); expect(await consumer.next()).toBeDefined(); await expect(consumer.next()).rejects.toThrow(Rolled); @@ -115,7 +115,7 @@ test("a second group is reported while the first is still open", async () => { const second = track.appendGroup(); second.writeFrame({ payload: payloads(2)[1], timestamp: Time.Timestamp.now() }); - const consumer = new Consumer({ track: track.subscribe({ maxAge: REPLAY_LATENCY }) }); + const consumer = new Consumer({ track: track.subscribe({ maxDelay: REPLAY_LATENCY }) }); expect(await consumer.next()).toEqual(payloads(1)[0]); await expect(consumer.next()).rejects.toThrow(Rolled); diff --git a/js/hang/bench/slow-group.ts b/js/hang/bench/slow-group.ts index 68773f203eb..b5e8290d913 100644 --- a/js/hang/bench/slow-group.ts +++ b/js/hang/bench/slow-group.ts @@ -6,10 +6,10 @@ import { Format } from "../src/container/legacy.ts"; for (const count of [1, 16, 256, 1024]) { const track = new Track.Producer("tone"); - const maxAge = new Signal(Time.Milli(30_000)); - const consumer = new Consumer(track.subscribe({ maxAge: Time.Milli(30_000) }), { + const maxDelay = new Signal(Time.Milli(30_000)); + const consumer = new Consumer(track.subscribe({ maxDelay: Time.Milli(30_000) }), { format: new Format("data"), - maxAge, + maxDelay, }); const write = (sequence: number) => { const group = new Group.Producer(sequence); @@ -29,7 +29,7 @@ for (const count of [1, 16, 256, 1024]) { try { for (let i = 0; i < count; i++) write(i); await buffered(count - 1); - maxAge.set(Time.Milli.zero); + maxDelay.set(Time.Milli.zero); const started = performance.now(); write(count); await buffered(count); diff --git a/js/hang/src/container/consumer.nonsequential.test.ts b/js/hang/src/container/consumer.nonsequential.test.ts index 018de3b5461..fca4c3f4a76 100644 --- a/js/hang/src/container/consumer.nonsequential.test.ts +++ b/js/hang/src/container/consumer.nonsequential.test.ts @@ -18,7 +18,7 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame // presentation end is unknown until the next group arrives. With non-sequential group ids we // therefore cannot prove the timeline is unbroken across a jump: a large id gap is // indistinguishable from a real missing segment that may still be in transit. So the consumer - // waits (and lets #checkMaxAge / #tryDurationSkip decide once the max age budget or duration + // waits (and lets #checkMaxDelay / #tryDurationSkip decide once the max delay budget or duration // coverage proves the gap too old) rather than eagerly skipping ahead, which would drop an // in-transit group and wreck audio. // @@ -26,7 +26,10 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame // as a trailing frame carrying the group's end timestamp. Until the container carries that, expect // the wait. The CMAF path (per-sample duration in the moof) is covered in consumer.test.ts. const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("data"), maxAge: 5000 as Time.Milli }); + const consumer = new Consumer(track.subscribe(), { + format: new LegacyFormat("data"), + maxDelay: 5000 as Time.Milli, + }); // Group A at a large sequence, completed so the cursor advances past it. const a = new Group.Producer(1_000_000); @@ -55,7 +58,7 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame timestamp: Time.Timestamp.now(), }); - // Within the max age budget (5s), the parked next() stays parked: no duration means no proof of + // Within the max delay budget (5s), the parked next() stays parked: no duration means no proof of // contiguity, so the consumer waits instead of eagerly delivering across the gap. const result = await Promise.race([ pending, diff --git a/js/hang/src/container/consumer.outoforder.test.ts b/js/hang/src/container/consumer.outoforder.test.ts index 37ddbbec68a..6e6a6bebeb4 100644 --- a/js/hang/src/container/consumer.outoforder.test.ts +++ b/js/hang/src/container/consumer.outoforder.test.ts @@ -41,16 +41,16 @@ async function drain(consumer: Consumer): Promise<[number, number | undefined][] return seen; } -// A publisher serving a subscriber's max age hands over the head of the window alongside +// A publisher serving a subscriber's max delay hands over the head of the window alongside // the live edge, and groups go out newest-first, so the head arrives *after* the group // that is already playing. Arriving in that order is not a reason to throw it away: // audio writes into a timestamp-indexed ring and video drops a late frame at render, and the -// subscription's own max age already bounds how far back one can be. +// subscription's own max delay already bounds how far back one can be. test("out-of-order groups are delivered rather than dropped", async () => { const track = new Track.Producer("test").accept({ maxAge: Time.Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ maxAge: Time.Milli(5000) }), { + const consumer = new Consumer(track.subscribe({ maxDelay: Time.Milli(5000) }), { format: new LegacyFormat("data"), - maxAge: 5000 as Time.Milli, + maxDelay: 5000 as Time.Milli, }); // The live edge lands first, and delivery starts there rather than waiting. @@ -78,9 +78,9 @@ test("out-of-order groups are delivered rather than dropped", async () => { // instant silently truncates its tail, so removal must wait for the group to finish. test("a below-cursor group still downloading is not truncated", async () => { const track = new Track.Producer("test").accept({ maxAge: Time.Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ maxAge: Time.Milli(5000) }), { + const consumer = new Consumer(track.subscribe({ maxDelay: Time.Milli(5000) }), { format: new LegacyFormat("data"), - maxAge: 5000 as Time.Milli, + maxDelay: 5000 as Time.Milli, }); // The live edge group arrives first and starts delivery (still open). @@ -112,13 +112,13 @@ test("a below-cursor group still downloading is not truncated", async () => { consumer.close(); }); -// The floor belongs to the latest group, not to delayed history within max age. +// The floor belongs to the latest group, not to delayed history within max delay. test("delayed older groups survive a floor established by two newer groups", async () => { const clock = spyOn(performance, "now").mockReturnValue(200); const track = new Track.Producer("test").accept({ maxAge: Time.Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ maxAge: Time.Milli(5000) }), { + const consumer = new Consumer(track.subscribe({ maxDelay: Time.Milli(5000) }), { format: new LegacyFormat("data"), - maxAge: Time.Milli(5000), + maxDelay: Time.Milli(5000), }); async function nextFrame() { for (;;) { diff --git a/js/hang/src/container/consumer.rewind.test.ts b/js/hang/src/container/consumer.rewind.test.ts index f7b9727f6c6..c826fbe1b58 100644 --- a/js/hang/src/container/consumer.rewind.test.ts +++ b/js/hang/src/container/consumer.rewind.test.ts @@ -11,9 +11,9 @@ afterEach(() => clock.mockRestore()); function setup() { const track = new Track.Producer("rewind"); - const consumer = new Consumer(track.subscribe({ maxAge: Time.Milli(30_000) }), { + const consumer = new Consumer(track.subscribe({ maxDelay: Time.Milli(30_000) }), { format: new Format("video"), - maxAge: Time.Milli(30_000), + maxDelay: Time.Milli(30_000), }); return { track, consumer }; } diff --git a/js/hang/src/container/consumer.skips.test.ts b/js/hang/src/container/consumer.skips.test.ts index dc845c47a4c..591ab00aa1b 100644 --- a/js/hang/src/container/consumer.skips.test.ts +++ b/js/hang/src/container/consumer.skips.test.ts @@ -8,10 +8,10 @@ for (const count of [1, 16, 256]) { test(`Consumer summarizes ${count} skipped groups once per catch-up`, async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const maxAge = new Signal(Time.Milli(30_000)); - const consumer = new Consumer(track.subscribe({ maxAge: Time.Milli(30_000) }), { + const maxDelay = new Signal(Time.Milli(30_000)); + const consumer = new Consumer(track.subscribe({ maxDelay: Time.Milli(30_000) }), { format: new Format("data"), - maxAge, + maxDelay, }); const write = (sequence: number, timestamp: number) => { const group = new Group.Producer(sequence); @@ -27,7 +27,7 @@ for (const count of [1, 16, 256]) { for (let i = 0; i < count; i++) write(i * 2, i * 1000); await buffered(count - 1); expect(warn).not.toHaveBeenCalled(); - maxAge.set(Time.Milli.zero); + maxDelay.set(Time.Milli.zero); const newest = write(count * 2, count * 1000); await buffered(count); expect(warn).toHaveBeenCalledTimes(1); diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index 8c624f29765..26e48de607a 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -46,13 +46,25 @@ function settle(ms = 20): Promise { } // Keep transport drift filtering out of container-consumer tests. These cases -// exercise the consumer's own max age policy against a complete retained track. +// exercise the consumer's own max delay policy against a complete retained track. // These tests write every group up front and only then read, so they ask for history // rather than the live edge. function replay(track: Track.Producer): Track.Subscriber { - return track.subscribe({ maxAge: Time.Milli(30_000) }); + return track.subscribe({ maxDelay: Time.Milli(30_000) }); } +test("Consumer refuses maxAge before taking ownership of the track", () => { + const producer = new Track.Producer("test"); + const track = producer.subscribe(); + for (const maxAge of [Time.Milli(500), undefined]) { + const props = { format: new LegacyFormat("data"), maxAge }; + expect(() => new Consumer(track, props)).toThrow("maxDelay"); + expect(track.closed.peek()).toBeUndefined(); + } + track.close(); + producer.close(); +}); + // --- LegacyFormat --- test("LegacyFormat decodes a valid frame", () => { @@ -132,7 +144,7 @@ test("Legacy Producer accepts open-GOP leading pictures above the previous group test("Legacy Producer writes a duration marker at the next keyframe", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ maxAge: Time.Milli(30_000) }); + const subscriber = track.subscribe({ maxDelay: Time.Milli(30_000) }); const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([0xde, 0xad]), 0 as Time.Micro, true); producer.encode(new Uint8Array([0xbe, 0xef]), 10_000 as Time.Micro, false); @@ -157,7 +169,7 @@ test("Legacy Producer writes a duration marker at the next keyframe", async () = test("Legacy Producer omits a reordered group's presentation endpoint marker", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ maxAge: Time.Milli(30_000) }); + const subscriber = track.subscribe({ maxDelay: Time.Milli(30_000) }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 120_000, 40_000, 80_000].entries()) { producer.encode(new Uint8Array([1]), timestamp as Time.Micro, index === 0); @@ -183,7 +195,7 @@ test("Legacy Producer omits a reordered group's presentation endpoint marker", a test("Legacy Producer estimates the tail from the current cadence", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ maxAge: Time.Milli(30_000) }); + const subscriber = track.subscribe({ maxDelay: Time.Milli(30_000) }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 16_000, 32_000, 65_000, 98_000].entries()) { producer.encode(new Uint8Array([1]), timestamp as Time.Micro, index === 0); @@ -203,7 +215,7 @@ test("Legacy Producer estimates the tail from the current cadence", async () => test("Legacy Producer rejects a backwards discontinuity without closing the group", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ maxAge: Time.Milli(30_000) }); + const subscriber = track.subscribe({ maxDelay: Time.Milli(30_000) }); const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([1]), 20_000 as Time.Micro, true); expect(() => producer.discontinuity(10_000 as Time.Micro)).toThrow(); @@ -222,7 +234,7 @@ test("Legacy Producer rejects a backwards discontinuity without closing the grou test("Legacy Producer keeps the cadence after rejecting a backwards discontinuity", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ maxAge: Time.Milli(30_000) }); + const subscriber = track.subscribe({ maxDelay: Time.Milli(30_000) }); const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([1]), 20_000 as Time.Micro, true); producer.encode(new Uint8Array([2]), 30_000 as Time.Micro, false); @@ -353,7 +365,7 @@ test("Legacy Producer discontinuity keeps pre-pause media from reading as live", producer.encode(new Uint8Array([1]), 5_000_000 as Time.Micro, true); producer.close(); - const subscriber = track.subscribe({ maxAge: Time.Milli(1_000) }); + const subscriber = track.subscribe({ maxDelay: Time.Milli(1_000) }); expect((await readGroups(subscriber, 2)).map(([sequence]) => sequence)).toEqual([1, 2]); }); @@ -513,7 +525,7 @@ async function drainFrames( test("Consumer delivers frames from a single group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro, 33_000 as Time.Micro]); track.close(); @@ -527,7 +539,7 @@ test("Consumer delivers frames from a single group", async () => { test("Consumer forces keyframe true at index 0", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro, 33_000 as Time.Micro]); track.close(); @@ -551,7 +563,7 @@ test("Consumer index spans MoQ frames for keyframe detection", async () => { }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: multiFormat, maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: multiFormat, maxDelay: 500 as Time.Milli }); const group = new Group.Producer(0); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // first MoQ frame → 3 samples @@ -579,7 +591,7 @@ test("Consumer keeps frames decoded before an error (truncated GoP)", async () = }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: truncatingFormat, maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: truncatingFormat, maxDelay: 500 as Time.Milli }); // Group.Producer 0: 2 valid frames then a tail-truncating error. const g0 = new Group.Producer(0); @@ -606,7 +618,7 @@ test("Consumer keeps frames decoded before an error (truncated GoP)", async () = test("Consumer close returns undefined from next()", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); const promise = consumer.next(); consumer.close(); @@ -617,7 +629,7 @@ test("Consumer close returns undefined from next()", async () => { test("Consumer throws on concurrent next() calls", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); // First call blocks waiting for data void consumer.next(); @@ -627,19 +639,19 @@ test("Consumer throws on concurrent next() calls", async () => { consumer.close(); }); -test("Consumer skips groups via PTS-span when over the max age", async () => { +test("Consumer skips groups via PTS-span when over the max delay", async () => { const track = new Track.Producer("test"); - // Zero max age = skip everything that's not the latest - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 0 as Time.Milli }); + // Zero max delay = skip everything that's not the latest + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 0 as Time.Milli }); - // Write groups with increasing timestamps. With a 0 max age, any PTS span > 0 triggers skip. + // Write groups with increasing timestamps. With a 0 max delay, any PTS span > 0 triggers skip. writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro]); writeGroupWithLegacyFrames(track, 1, [100_000 as Time.Micro]); writeGroupWithLegacyFrames(track, 2, [200_000 as Time.Micro]); track.close(); const frames = await drainFrames(consumer, 300); - // With a zero max age, the consumer should skip to the latest group + // With a zero max delay, the consumer should skip to the latest group const groups = [...new Set(frames.map((f) => f.group))]; expect(groups.at(-1)).toBe(2); consumer.close(); @@ -647,7 +659,10 @@ test("Consumer skips groups via PTS-span when over the max age", async () => { test("Consumer measures arrivals as they land", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("audio"), maxAge: 5000 as Time.Milli }); + const consumer = new Consumer(track.subscribe(), { + format: new LegacyFormat("audio"), + maxDelay: 5000 as Time.Milli, + }); // Nothing observed yet: the cold-start estimate. expect(consumer.spread.peek()).toBe(100 as Time.Milli); @@ -668,7 +683,7 @@ test("Consumer measures arrivals as they land", async () => { test("Consumer delivers groups in sequence order regardless of arrival order", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); writeGroupWithLegacyFrames(track, 2, [60_000 as Time.Micro]); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro]); @@ -687,7 +702,7 @@ test("Consumer delivers groups in sequence order regardless of arrival order", a test("Consumer delivers a group that arrives below the cursor", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); // Group.Producer 5 arrives first (sets active = 5) writeGroupWithLegacyFrames(track, 5, [100_000 as Time.Micro]); @@ -695,7 +710,7 @@ test("Consumer delivers a group that arrives below the cursor", async () => { // Group.Producer 3 lands behind it, and Group.Producer 6 ahead of it. Arriving below the // cursor is not what makes content stale: how far behind the live edge a group may be is - // the subscription's own max age, which `replay` deliberately opens wide here. So all + // the subscription's own max delay, which `replay` deliberately opens wide here. So all // three are handed over, in sequence order, since delivery has not passed any of them yet. writeGroupWithLegacyFrames(track, 3, [0 as Time.Micro]); writeGroupWithLegacyFrames(track, 6, [200_000 as Time.Micro]); @@ -712,7 +727,7 @@ test("Consumer delivers a group that arrives below the cursor", async () => { test("Consumer next() returns group-done signals", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro, 33_000 as Time.Micro]); writeGroupWithLegacyFrames(track, 1, [66_000 as Time.Micro]); @@ -741,7 +756,10 @@ test("Consumer next() returns group-done signals", async () => { test("Consumer reports a duration marker as metadata", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(track.subscribe(), { + format: new LegacyFormat("video"), + maxDelay: 500 as Time.Milli, + }); const group = new Group.Producer(0); group.writeFrame({ @@ -770,7 +788,10 @@ test("Consumer reports a duration marker as metadata", async () => { test("Consumer skips a leading marker and keeps the first media keyframe", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(track.subscribe(), { + format: new LegacyFormat("video"), + maxDelay: 500 as Time.Milli, + }); const group = new Group.Producer(0); group.writeFrame({ @@ -802,7 +823,7 @@ test("Consumer skips an empty LOC payload", async () => { producer.encode(new Uint8Array(), 33_000 as Time.Micro, false); producer.close(); - const consumer = new Consumer(replay(track), { format: new LocFormat("video"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LocFormat("video"), maxDelay: 500 as Time.Milli }); await settle(); const media = await consumer.next(); expect(media?.frame?.payload).toEqual(new Uint8Array([0xde, 0xad])); @@ -821,7 +842,7 @@ test("Consumer preserves empty Legacy and LOC data frames", async () => { producer.encode(new Uint8Array(), 0 as Time.Micro, true); producer.close(); const format = kind === "legacy" ? new LegacyFormat("data") : new LocFormat(); - const consumer = new Consumer(replay(track), { format, maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format, maxDelay: 500 as Time.Milli }); const result = await consumer.next(); expect(result?.frame?.payload).toEqual(new Uint8Array()); expect(result?.frame?.keyframe).toBe(true); @@ -842,7 +863,7 @@ async function nextFrame(consumer: Consumer) { test("Consumer aborts a group below the previous group start", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 30_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 30_000 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [10_000_000 as Time.Micro]); writeGroupWithLegacyFrames(track, 1, [0 as Time.Micro, 100_000 as Time.Micro]); @@ -856,7 +877,7 @@ test("Consumer aborts a group below the previous group start", async () => { test("Consumer aborts a rewind carried by a later arrival", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 30_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 30_000 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [10_000_000 as Time.Micro]); await settle(); @@ -876,7 +897,7 @@ test("Consumer aborts a rewind carried by a later arrival", async () => { // rewind, so the detector compares against the previous group's start. test("Consumer treats B-frame reordering within a group as continuous", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 30_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 30_000 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro, 66_000 as Time.Micro, 33_000 as Time.Micro]); await settle(); @@ -901,7 +922,7 @@ test("Consumer treats B-frame reordering within a group as continuous", async () test("Consumer accepts open-GOP leading pictures above the previous group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 30_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 30_000 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro, 33_000 as Time.Micro]); writeGroupWithLegacyFrames(track, 1, [66_000 as Time.Micro, 50_000 as Time.Micro]); @@ -919,7 +940,7 @@ test("Consumer accepts open-GOP leading pictures above the previous group", asyn test("Consumer buffered signal updates as frames arrive", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 500 as Time.Milli }); expect(consumer.buffered.peek()).toEqual([]); @@ -941,7 +962,7 @@ test("Consumer buffered signal updates as frames arrive", async () => { test("Consumer recovers from gap in group sequence numbers", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 100 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 100 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro, 20_000 as Time.Micro]); writeGroupWithLegacyFrames(track, 1, [40_000 as Time.Micro, 60_000 as Time.Micro]); @@ -971,7 +992,7 @@ test("Consumer handles empty decode result without deadlock", async () => { }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: emptyThenValid, maxAge: 500 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: emptyThenValid, maxDelay: 500 as Time.Milli }); const group = new Group.Producer(0); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // empty decode @@ -997,7 +1018,7 @@ test("Consumer preserves empty media from formats without endpoint markers", asy }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format, maxAge: 500 as Time.Milli }); + const consumer = new Consumer(track.subscribe(), { format, maxDelay: 500 as Time.Milli }); const group = new Group.Producer(0); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Time.Timestamp.now() }); group.close(); @@ -1015,7 +1036,7 @@ test("Consumer with CmafFormat delivers correct timestamps", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - maxAge: 500 as Time.Milli, + maxDelay: 500 as Time.Milli, }); const group = new Group.Producer(0); @@ -1089,7 +1110,7 @@ const durationFormat: ContainerFormat = { test("Consumer duration-skips a stalled group once it is covered", async () => { const track = new Track.Producer("test"); // Latency dwarfs the gap, so only duration coverage can trigger the skip. - const consumer = new Consumer(replay(track), { format: durationFormat, maxAge: 10_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: durationFormat, maxDelay: 10_000 as Time.Milli }); // Group.Producer 0: one frame at ts=0 lasting 33ms, never closed (stalled). const g0 = new Group.Producer(0); @@ -1126,7 +1147,7 @@ test("Consumer does not duration-skip when the gap is not covered", async () => }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: shortFormat, maxAge: 10_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: shortFormat, maxDelay: 10_000 as Time.Milli }); // Group.Producer 0 stays open and later receives a second frame; nothing covers the gap, // so that late frame must survive rather than being skipped. @@ -1161,7 +1182,7 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (CMAF) const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - maxAge: 500 as Time.Milli, + maxDelay: 500 as Time.Milli, }); // Group A (seq 1_000_000): one 3000-tick sample, so its content ends at 33_333µs (3000/90000 * 1e6). @@ -1219,10 +1240,10 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (CMAF) // Delivery resumes only once the missing, timeline-continuous group arrives. test("Consumer waits on a PTS gap instead of skipping to a later buffered group (CMAF)", async () => { const track = new Track.Producer("test"); - // Large max age so the gap can't be age-skipped during the test window. + // Large max delay so the gap can't be age-skipped during the test window. const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - maxAge: 10_000 as Time.Milli, + maxDelay: 10_000 as Time.Milli, }); // Group A (seq 1_000_000): content ends at 33_333µs. @@ -1299,7 +1320,7 @@ test("Consumer delivers a contiguous group after one that completed out of order const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - maxAge: 10_000 as Time.Milli, + maxDelay: 10_000 as Time.Milli, }); // A (seq 1_000_000) stays open so it remains the active group. @@ -1347,7 +1368,7 @@ test("Consumer plays the head once a waited-out gap exceeds the budget (CMAF)", const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - maxAge: 100 as Time.Milli, + maxDelay: 100 as Time.Milli, }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). @@ -1382,7 +1403,7 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - maxAge: 100 as Time.Milli, + maxDelay: 100 as Time.Milli, }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). @@ -1419,10 +1440,10 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc // `continuous` is what downstream buffer accounting keys on, so it must be false exactly when the // consumer dropped something. Group numbers can't answer that: they aren't required to be -// sequential, and adjacency doesn't rule out a group the max age check dropped on the way past. +// sequential, and adjacency doesn't rule out a group the max delay check dropped on the way past. test("Consumer reports continuity while nothing is dropped", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 100 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 100 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro, 33_000 as Time.Micro]); await settle(); @@ -1440,7 +1461,7 @@ test("Consumer reports continuity while nothing is dropped", async () => { test("Consumer reports a marker group as a playhead event", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxAge: 2_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 2_000 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro]); writeMarkerGroup(track, 1, 0 as Time.Micro); @@ -1460,7 +1481,7 @@ test("Consumer reports a marker group as a playhead event", async () => { test("Consumer empty groups mean nothing", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxAge: 2_000 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 2_000 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro]); const empty = new Group.Producer(1); @@ -1478,7 +1499,7 @@ test("Consumer empty groups mean nothing", async () => { test("Consumer latency skip bumps playhead generation once", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxAge: 0 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 0 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro]); await settle(); @@ -1497,7 +1518,7 @@ test("Consumer latency skip bumps playhead generation once", async () => { test("Consumer jumps the playhead after a shed marker with a timestamp hole", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxAge: 0 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 0 as Time.Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro]); await settle(); @@ -1516,7 +1537,7 @@ test("Consumer jumps the playhead after a shed marker with a timestamp hole", as test("Consumer zero-budget skip keeps a contiguous marker", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxAge: 0 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 0 as Time.Milli }); const group0 = new Group.Producer(0); track.writeGroup(group0); @@ -1544,7 +1565,7 @@ test("Consumer reports continuity across a PTS-contiguous group id jump (CMAF)", const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - maxAge: 10_000 as Time.Milli, + maxDelay: 10_000 as Time.Milli, }); const a = new Group.Producer(1_000_000); @@ -1570,7 +1591,10 @@ test("Consumer reports continuity across a PTS-contiguous group id jump (CMAF)", test("live duration marker follows an immediately delivered video frame", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), maxAge: 500 as Time.Milli }); + const consumer = new Consumer(track.subscribe(), { + format: new LegacyFormat("video"), + maxDelay: 500 as Time.Milli, + }); const group = track.appendGroup(); group.writeFrame({ payload: encodeLegacyFrame(0 as Time.Micro, new Uint8Array([1])), @@ -1610,7 +1634,7 @@ test("audio discontinuity writes no duration marker", async () => { for (const code of [StreamCode.Cancel, StreamCode.Internal, StreamCode.Old, StreamCode.Evicted, StreamCode(1234)]) { test(`Consumer preserves frames and continues after group reset ${code}`, async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxAge: 0 as Time.Milli }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 0 as Time.Milli }); const error = spyOn(console, "error").mockImplementation(() => {}); try { const group = track.appendGroup(); @@ -1692,7 +1716,7 @@ for (const end of [ const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), - maxAge: 10_000 as Time.Milli, + maxDelay: 10_000 as Time.Milli, }); try { writeGroupWithLegacyFrames(track, 0, [0 as Time.Micro]); diff --git a/js/hang/src/container/consumer.ts b/js/hang/src/container/consumer.ts index 7d81c24edd0..98ccbbbd6ff 100644 --- a/js/hang/src/container/consumer.ts +++ b/js/hang/src/container/consumer.ts @@ -6,7 +6,7 @@ import type { Format } from "./format"; import { Jitter } from "./jitter"; import type { BufferedRanges, Frame } from "./types"; -/** Options for constructing a {@link Consumer}. */ +/** Options for constructing a {@link Consumer}; the obsolete `maxAge` prop is refused. */ export interface ConsumerProps { /** The container format used to decode each MoQ frame. */ format: Format; @@ -15,10 +15,10 @@ export interface ConsumerProps { * * Measured as the span from the oldest buffered frame to the newest, so it bounds how long a * late or missing group is waited for. The local half of the subscription's - * `maxAge`; both measure the same budget, one on the wire and one as frames are read. + * `maxDelay`; both measure the same budget, one on the wire and one as frames are read. */ // Read-only: a Getter (e.g. another component's output) is accepted directly. - maxAge?: GetterInit; + maxDelay?: GetterInit; } interface Group { @@ -67,11 +67,11 @@ function continues(prev: Group, next: Group | undefined): next is Group { ); } -/** Reads frames from a MoQ track in order, buffering groups and skipping ones that age past `maxAge`. */ +/** Reads frames from a MoQ track in order, buffering groups and skipping ones that fall `maxDelay` behind. */ export class Consumer { #track: Moq.Track.Subscriber; #format: Format; - #maxAge: Getter; + #maxDelay: Getter; #groups: Group[] = []; #active?: number; // the active group sequence number // Presentation end (max PTS + duration) of the group we most recently advanced past, so next()'s @@ -81,7 +81,7 @@ export class Consumer { // Group of the last frame next() returned, so it can report whether the following result // continues that frame's timeline. Undefined until the first delivery and after a playhead event. #deliveredGroup?: number; - // Set whenever the consumer throws content away: a group that aged past `maxAge`, + // Set whenever the consumer throws content away: a group that fell `maxDelay` behind, // a group truncated by a decode error. Reported (and // cleared) on the first frame delivered from the next group, which is where the missing span // sits. Only the consumer can know this, which is why next() reports it instead of leaving @@ -118,9 +118,10 @@ export class Consumer { /** Start consuming the given track, decoding frames with `props.format`. */ constructor(track: Moq.Track.Subscriber, props: ConsumerProps) { + if ("maxAge" in props) throw new TypeError("Consumer maxAge is unsupported; use maxDelay"); this.#track = track; this.#format = props.format; - this.#maxAge = getter(props.maxAge ?? Moq.Time.Milli.zero); + this.#maxDelay = getter(props.maxDelay ?? Moq.Time.Milli.zero); this.#signals.spawn(this.#run.bind(this)); this.#signals.cleanup(() => { @@ -155,7 +156,7 @@ export class Consumer { // sent newest-first, so the head of a subscription arrives after the live edge it // was served alongside. Audio can place older groups in its timestamp-indexed ring; // video must reject older groups before decode to preserve codec references. How far back one - // may be is the subscription's own max age, applied before it ever reaches here. + // may be is the subscription's own max delay, applied before it ever reaches here. const group: Group = { consumer, frames: [], @@ -240,9 +241,9 @@ export class Consumer { if (group.consumer.sequence !== this.#active) { // A non-active group can also be too slow to wait for. This runs even when // the group is the delivery head, because that is exactly the stalled case - // (#active sits below every buffered group) where the max age budget is + // (#active sits below every buffered group) where the max delay budget is // what eventually breaks the stall. - this.#checkMaxAge(); + this.#checkMaxDelay(); // A newer group reaching back to where the stalled active group has // already presented means we can advance now instead of waiting. @@ -280,10 +281,10 @@ export class Consumer { // Advance to the next buffered group's actual sequence, but ONLY if it continues this // group's timeline. Some encoders number groups non-sequentially with large gaps (not // +1), so a bare `+= 1` would point #active at a nonexistent sequence and stall next() - // until #checkMaxAge skipped it -- every group through the skip path, i.e. constant + // until #checkMaxDelay skipped it -- every group through the skip path, i.e. constant // stutter. A real PTS gap is different: an intermediate group may still be in transit, // so fall back to +1 there (next()'s promotion guard fixes it up once a continuous - // group arrives) and let #checkMaxAge / #tryDurationSkip skip the gap only once + // group arrives) and let #checkMaxDelay / #tryDurationSkip skip the gap only once // age or duration coverage proves it too old. const next = this.#groups[this.#groups.indexOf(group) + 1]; this.#active = continues(group, next) ? next.consumer.sequence : group.consumer.sequence + 1; @@ -316,24 +317,24 @@ export class Consumer { // Frames within a group are consecutive by protocol, so only a group boundary can break it, and // there it comes down to whether anything was dropped in between. Deliberately not derived from // group numbers: they need not be sequential, so adjacency neither proves continuity nor catches - // a group the max age check truncated on the way past. + // a group the max delay check truncated on the way past. #continuesDelivery(sequence: number): boolean { if (this.#deliveredGroup === undefined) return false; return sequence === this.#deliveredGroup || !this.#gap; } - #checkMaxAge() { + #checkMaxDelay() { if (this.#active === undefined) return; let skipped = 0; const start = this.#groups[0]?.consumer.sequence; let hole = false; - // Keep skipping the oldest group while the buffered span exceeds the max age. + // Keep skipping the oldest group while the buffered span exceeds the max delay. // This also handles gaps in group sequence numbers: if #active points to a missing // group, the span proves the missing content is too old to wait for. while (this.#groups.length >= 2) { - const threshold = Moq.Time.Micro.fromMilli(this.#maxAge.peek()); + const threshold = Moq.Time.Micro.fromMilli(this.#maxDelay.peek()); const first = this.#groups[0]; // Check the difference between the earliest and latest known frames. @@ -450,7 +451,7 @@ export class Consumer { * `continuous` is true when this result picks up exactly where the previous frame left off, so * the span between them can be treated as delivered. It is false on the first frame, after a * playhead event, and whenever the consumer threw content away to keep up: a slow group skipped - * for the max age, a group truncated by a decode error. Use it rather than comparing group + * for the max delay, a group truncated by a decode error. Use it rather than comparing group * numbers, which are not required to be sequential: adjacency neither proves the timeline is * unbroken nor catches a group dropped on the way past. * @@ -489,23 +490,23 @@ export class Consumer { // Promote #active to the first buffered group when it continues the timeline we left off at, // when a completed empty group can be walked (empty groups mean nothing), or when the hole // is proven: the head already reaches past where presentation left off by more than the - // max age, so anything still missing in between would arrive too old to play. Proving it - // here matters: #checkMaxAge would instead drop the head, the very group to play next. + // max delay, so anything still missing in between would arrive too old to play. Proving it + // here matters: #checkMaxDelay would instead drop the head, the very group to play next. // After track termination no missing group can arrive, so drain across any remaining gap. - // Otherwise wait: #checkMaxAge skips once the budget is spent, and #tryDurationSkip once + // Otherwise wait: #checkMaxDelay skips once the budget is spent, and #tryDurationSkip once // the duration covers it. if (this.#active !== undefined && this.#groups.length > 0) { const head = this.#groups[0]; if (head.consumer.sequence > this.#active) { const contiguous = ptsContiguous(this.#presentedEnd, head.frames.at(0)?.timestamp); const empty = head.empty && head.consumer.done; - const maxAge = Moq.Time.Micro.fromMilli(this.#maxAge.peek()); + const maxDelay = Moq.Time.Micro.fromMilli(this.#maxDelay.peek()); const skipHole = head.frames.length > 0 && - (maxAge === 0 || + (maxDelay === 0 || (this.#presentedEnd !== undefined && head.latest !== undefined && - head.latest - this.#presentedEnd > maxAge)); + head.latest - this.#presentedEnd > maxDelay)); if (empty || contiguous || skipHole || ended !== undefined) { if ((skipHole || ended !== undefined) && !contiguous && !empty) this.#markPlayhead(); if (!contiguous) this.#gap = true; @@ -556,7 +557,7 @@ export class Consumer { // a below-#active group (a backlog group admitted behind the live edge) may // still be downloading when its buffer momentarily drains, and removing it // then silently truncates its tail. #runGroup notifies whenever the head - // group gains a frame, so waiting here is woken, and #checkMaxAge bounds + // group gains a frame, so waiting here is woken, and #checkMaxDelay bounds // how long a stalled head can hold delivery up. if (this.#groups[0].done) { if (this.#groups[0].consumer.sequence === this.#active) { diff --git a/js/hang/src/container/types.ts b/js/hang/src/container/types.ts index a70bac26af4..1bab11a26ae 100644 --- a/js/hang/src/container/types.ts +++ b/js/hang/src/container/types.ts @@ -13,7 +13,7 @@ export interface Frame { // per-sample duration; Legacy and LOC report later endpoints through Consumer.next().end. // The consumer adds it to `timestamp` to learn how far a group has presented, // so it can advance to a newer group as soon as the gap is covered instead of - // waiting out the max age budget. + // waiting out the max delay budget. duration?: Time.Micro; } diff --git a/js/json/src/snapshot/compression.test.ts b/js/json/src/snapshot/compression.test.ts index aa792080a55..b0287e5c47a 100644 --- a/js/json/src/snapshot/compression.test.ts +++ b/js/json/src/snapshot/compression.test.ts @@ -46,7 +46,7 @@ test("compressed snapshot per group round-trips", async () => { // Deltas off: one compressed snapshot per group. A consumer joining after the fact // collapses the backlog to the newest value (mirrors the Rust consumer). - expect(await drainCompressed(track.subscribe({ maxAge: REPLAY_LATENCY }))).toEqual([{ a: 2 }]); + expect(await drainCompressed(track.subscribe({ maxDelay: REPLAY_LATENCY }))).toEqual([{ a: 2 }]); }); test("compressed live consumer sees each update in order", async () => { @@ -143,7 +143,7 @@ test("compressed deltas roll on the compressed budget", async () => { }; const layout = new Track.Producer("layout"); - const layoutSub = layout.subscribe({ maxAge: REPLAY_LATENCY }).ordered(); + const layoutSub = layout.subscribe({ maxDelay: REPLAY_LATENCY }).ordered(); fill(layout); expect(await groupCount(layoutSub)).toBeGreaterThan(1); diff --git a/js/json/src/snapshot/snapshot.test.ts b/js/json/src/snapshot/snapshot.test.ts index 8b2f3457c6a..f97ddcc3482 100644 --- a/js/json/src/snapshot/snapshot.test.ts +++ b/js/json/src/snapshot/snapshot.test.ts @@ -43,8 +43,8 @@ test("a cut makes the next update a snapshot group", async () => { // The ratio would have kept every update in one group; the cut rolled it anyway. The replacement // opens with a full snapshot, so it is one frame rather than a delta appended to the first group. - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([2, 1]); - expect((await drain(track.subscribe({ maxAge: REPLAY_LATENCY }))).at(-1)).toEqual({ a: 1, b: 3 }); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([2, 1]); + expect((await drain(track.subscribe({ maxDelay: REPLAY_LATENCY }))).at(-1)).toEqual({ a: 1, b: 3 }); }); test("a cut republishes an unchanged value", async () => { @@ -58,7 +58,7 @@ test("a cut republishes an unchanged value", async () => { producer.update({ a: 1 }); producer.finish(); - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); }); test("a cut opens no replacement group", async () => { @@ -69,7 +69,7 @@ test("a cut opens no replacement group", async () => { producer.finish(); // Cutting closes the open group and stops there: no empty group for a consumer to advance into. - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([1]); }); test("a cut is idempotent", async () => { @@ -87,7 +87,7 @@ test("a cut is idempotent", async () => { producer.update({ a: 2 }); producer.finish(); - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); }); test("a cut is inert without deltas", async () => { @@ -100,7 +100,7 @@ test("a cut is inert without deltas", async () => { producer.update({ a: 2 }); producer.finish(); - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); }); test("deltas off: a snapshot group per change", async () => { @@ -113,7 +113,7 @@ test("deltas off: a snapshot group per change", async () => { // Two changes => two single-frame snapshot groups. A consumer joining after the fact // collapses the backlog to the newest value: older groups only hold superseded state // (mirrors the Rust consumer). The layout itself is asserted via structure() below. - expect(await drain(track.subscribe({ maxAge: REPLAY_LATENCY }))).toEqual([{ a: 2 }]); + expect(await drain(track.subscribe({ maxDelay: REPLAY_LATENCY }))).toEqual([{ a: 2 }]); }); test("deltaRatio 0 disables deltas, like off", async () => { @@ -125,7 +125,7 @@ test("deltaRatio 0 disables deltas, like off", async () => { // `0` is treated as off, not a degenerate "enabled" value that keeps the group open: each change // is its own single-frame snapshot group. - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); }); // A consumer holding a group must jump when a newer snapshot group rolls: the @@ -136,7 +136,7 @@ test("a held group is abandoned when a newer snapshot group rolls", async () => const track = new Track.Producer("test"); // A tiny ratio forces the update after any delta to roll a fresh snapshot group. const producer = new Producer({ track, deltaRatio: 0.001 }); - const consumer = new Consumer({ track: track.subscribe({ maxAge: REPLAY_LATENCY }) }); + const consumer = new Consumer({ track: track.subscribe({ maxDelay: REPLAY_LATENCY }) }); producer.update({ a: 1 }); expect(await consumer.next()).toEqual({ a: 1 }); @@ -260,7 +260,7 @@ test("tight ratio rolls snapshots", async () => { producer.update({ a: 4 }); // budget already exceeded, rolls group 1 producer.finish(); - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([3, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([3, 1]); }); test("deltas stay within ratio times snapshot", async () => { @@ -274,7 +274,7 @@ test("deltas stay within ratio times snapshot", async () => { for (let n = 0; n <= 10; n++) producer.update({ n }); producer.finish(); - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([10, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([10, 1]); }); test("array change is a wholesale delta", async () => { @@ -311,7 +311,7 @@ test("frame cap rolls snapshot", async () => { } producer.finish(); - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([256, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([256, 1]); }); test("a rejected update leaves the previous value readable", async () => { @@ -352,13 +352,13 @@ test("a delta that would overflow the snapshot rolls a new one instead", async ( producer.finish(); // Two groups, a self-contained snapshot each, rather than one whose frame 0 was evicted. - const subscriber = track.subscribe({ maxAge: REPLAY_LATENCY }).ordered(); + const subscriber = track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered(); expect((await subscriber.nextGroup())?.sequence).toBe(0); expect((await subscriber.nextGroup())?.sequence).toBe(1); expect(await subscriber.nextGroup()).toBeUndefined(); // The newest value is readable with no earlier frame to apply it to. - const values = await drain(track.subscribe({ maxAge: REPLAY_LATENCY })); + const values = await drain(track.subscribe({ maxDelay: REPLAY_LATENCY })); expect(values[values.length - 1]).toEqual({ v: "y".repeat(size) }); }); @@ -387,10 +387,10 @@ test("a compressed delta is gated on its encoded size, not its plaintext", async producer.finish(); // The patch rolled into a fresh snapshot rather than joining the first group. - expect(await structure(track.subscribe({ maxAge: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); + expect(await structure(track.subscribe({ maxDelay: REPLAY_LATENCY }).ordered())).toEqual([1, 1]); const consumer = new Consumer({ - track: track.subscribe({ maxAge: REPLAY_LATENCY }), + track: track.subscribe({ maxDelay: REPLAY_LATENCY }), compression: "deflate", }); const values: Value[] = []; diff --git a/js/json/src/stream/stream.test.ts b/js/json/src/stream/stream.test.ts index 1e14c3cb2a9..2b3deea3630 100644 --- a/js/json/src/stream/stream.test.ts +++ b/js/json/src/stream/stream.test.ts @@ -82,8 +82,8 @@ test("a second group is reported while the first is still open", async () => { second.writeFrame({ payload: encode({ n: 1 }), timestamp: Time.Timestamp.now() }); // Ask for a replay window, so the first group is delivered rather than skipped by the - // subscriber's default max-age budget once a newer group exists. - const consumer = new Consumer({ track: track.subscribe({ maxAge: Time.Milli(30_000) }) }); + // subscriber's default max delay budget once a newer group exists. + const consumer = new Consumer({ track: track.subscribe({ maxDelay: Time.Milli(30_000) }) }); expect(await consumer.next()).toEqual({ n: 0 }); await expect(consumer.next()).rejects.toThrow(Rolled); diff --git a/js/net/bench/lite-varint.ts b/js/net/bench/lite-varint.ts index 4338a448e55..148fb937ff7 100644 --- a/js/net/bench/lite-varint.ts +++ b/js/net/bench/lite-varint.ts @@ -71,7 +71,7 @@ const subscribe: Sample = { broadcast: Path.from("room/alice"), track: "video", priority: 2, - maxAge: 10_000, + maxDelay: 10_000, }).encode(w, version), decode: (r, version) => Subscribe.decode(r, version), }; diff --git a/js/net/bench/track.ts b/js/net/bench/track.ts index 184a0383be0..70c4742f965 100644 --- a/js/net/bench/track.ts +++ b/js/net/bench/track.ts @@ -48,7 +48,7 @@ async function measure( // Held rows stay within the idle window while the media budget keeps their frames usable. const window = Milli(held > 0 ? 3_600_000 : retained); const producer = new Producer("bench").accept({ maxAge: window }); - const subscribers = Array.from({ length: subscriberCount }, () => producer.subscribe({ maxAge: window })); + const subscribers = Array.from({ length: subscriberCount }, () => producer.subscribe({ maxDelay: window })); let sequence = 0; // Inserted by sequence, the way the wire hands a subscribed track its groups. const publish = (close: boolean) => { @@ -96,7 +96,7 @@ async function measure( // Ending the track releases the newest group too; idle cleanup reclaims the cache. clock += CACHE_WINDOW_MS + CACHE_WINDOW_MS / 8 + 1; const idleStart = now(); - const replay = producer.subscribe({ maxAge: window }); + const replay = producer.subscribe({ maxDelay: window }); if (replay.tryRecvGroup()) throw new Error("idle cache entries were retained"); const idle = (now() - idleStart) * 1000; replay.close(); diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index 1895c3365ed..a8c7920e207 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -203,19 +203,19 @@ test("a request exposes the aggregate subscription options", async () => { consumer.track("video").subscribe({ priority: 3, - maxAge: Milli(100), + maxDelay: Milli(100), groups: { start: { included: 10 }, end: { excluded: 20 } }, }); consumer.track("video").subscribe({ priority: 7, - maxAge: Milli(250), + maxDelay: Milli(250), groups: { start: { included: 0 }, end: { excluded: 30 } }, }); const request = await pendingRequest(consumer); expect(request?.subscription).toEqual({ priority: 7, - maxAge: Milli(250), + maxDelay: Milli(250), groups: { start: { included: 0 }, end: { excluded: 30 } }, }); expect(request?.priority).toBe(7); @@ -314,11 +314,11 @@ test("two subscribers to one inserted track each get a full copy", async () => { const a = broadcast .track("video") - .subscribe({ maxAge: Milli(5000) }) + .subscribe({ maxDelay: Milli(5000) }) .ordered(); const b = broadcast .track("video") - .subscribe({ maxAge: Milli(5000) }) + .subscribe({ maxDelay: Milli(5000) }) .ordered(); producer.writeString("hello"); @@ -350,7 +350,7 @@ test("a read throws GroupTooLarge on an overflow, then resyncs to the next group const producer = broadcast.createTrack("video"); const sub = broadcast .track("video") - .subscribe({ maxAge: Milli(5000) }) + .subscribe({ maxDelay: Milli(5000) }) .ordered(); // Group 0 overflows its frame cap: the group is aborted. diff --git a/js/net/src/group.ts b/js/net/src/group.ts index b018a690891..58226443ad7 100644 --- a/js/net/src/group.ts +++ b/js/net/src/group.ts @@ -430,7 +430,7 @@ export class Consumer { if (!this.#expiry?.expired()) return false; if (unread) { - this.#terminal = new Error("group exceeded the subscription max age budget"); + this.#terminal = new Error("group exceeded the subscription max delay budget"); } else { this.#ended = true; } diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 0acea570e76..310eb85f945 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -372,7 +372,7 @@ test("a group that goes stale while its stream opens writes nothing", async () = write(2, 20_000); open(); - expect(String(await streamReset)).toContain("max age budget"); + expect(String(await streamReset)).toContain("max delay budget"); expect(writes).toBe(0); await new Promise((resolve) => setTimeout(resolve, 0)); expect(unhandled).toEqual([]); @@ -2469,7 +2469,7 @@ test("REQUEST_UPDATE applies priority and preserves it when omitted", async () = await RequestOk.decode(client.reader, fx.version); expect(track.subscription.peek()?.priority).toBe(245); // Only the priority changes; retention and the group range survive. - expect(track.subscription.peek()?.maxAge).toBe(before?.maxAge); + expect(track.subscription.peek()?.maxDelay).toBe(before?.maxDelay); expect(track.subscription.peek()?.groups).toEqual(before?.groups); await client.writer.write(new Uint8Array([0x02, 0, 2, 4, 0])); expect(await client.reader.u53()).toBe(RequestOk.id); diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index 061b976fe6b..941b6ba67a3 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -359,7 +359,7 @@ export class Publisher { // producer retained and let the receiving subscriber enforce its own budget. // Keep the sentinel encodable if this demand crosses a Lite hop before the // producer's retention bound is known. - maxAge: Milli(Varint.MAX_U53), + maxDelay: Milli(Varint.MAX_U53), }); let cache: TrackSubscriber | undefined; @@ -390,7 +390,7 @@ export class Publisher { // group; the model's `endGroup` is exclusive. track.update({ priority, - maxAge: Milli(Varint.MAX_U53), + maxDelay: Milli(Varint.MAX_U53), groups: { start: range.start ? { included: Number(range.start.group) } : undefined, end: range.end ? { included: Number(range.end.group) } : undefined, @@ -405,7 +405,8 @@ export class Publisher { // asking the broadcast would mint a second producer nobody has accepted. const fill = msg.fill && Filter.isDraft20(version) ? fillRange(msg.fill, msg.filter, edge.largest) : undefined; - cache = fill && fill.kind !== "empty" ? track.fork({ priority, maxAge: Milli(Varint.MAX_U53) }) : undefined; + cache = + fill && fill.kind !== "empty" ? track.fork({ priority, maxDelay: Milli(Varint.MAX_U53) }) : undefined; // Send SUBSCRIBE_OK await stream.writer.u53(SubscribeOk.id); diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index 3f43b53dc92..5df23d00d02 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -58,7 +58,7 @@ async function subscribed() { const reader = subscriber .consume(Path.from("room")) .track("video") - .subscribe({ maxAge: Milli(60_000) }); + .subscribe({ maxDelay: Milli(60_000) }); const peer = await Stream.accept(pair.client, VERSION); if (!peer) throw new Error("the subscriber never opened a subscribe stream"); diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index 3811b540b88..ad88cfc153b 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -170,25 +170,25 @@ test("integration: lite subscription options and updates reach the publisher", a // its encoding of group 0 means "replay from the beginning" instead. const subscriber = remote.track("video").subscribe({ priority: 3, - maxAge: Milli(250), + maxDelay: Milli(250), groups: { start: { included: 1 }, end: { excluded: 9 } }, }); const producer = await accepted; expect(producer.subscription.peek()).toEqual({ priority: 3, - maxAge: Milli(250), + maxDelay: Milli(250), groups: { start: { included: 1 }, end: { excluded: 9 } }, }); const updated = producer.subscription.changed(); subscriber.update({ priority: 8, - maxAge: Milli(500), + maxDelay: Milli(500), groups: { start: { included: 2 }, end: { excluded: 12 } }, }); expect(await updated).toEqual({ priority: 8, - maxAge: Milli(500), + maxDelay: Milli(500), groups: { start: { included: 2 }, end: { excluded: 12 } }, }); @@ -200,7 +200,7 @@ test("integration: lite subscription options and updates reach the publisher", a server.abort(); }); -test("integration: lite carries a fractional maxAge as a whole millisecond", async () => { +test("integration: lite carries a fractional maxDelay as a whole millisecond", async () => { const pair = createMockTransportPair(Lite.ALPN_05); const origin = new OriginProducer(); const [client, server] = await Promise.all([ @@ -227,7 +227,7 @@ test("integration: lite carries a fractional maxAge as a whole millisecond", asy // A varint cannot encode 38.75, so an unrounded value fails the SUBSCRIBE outright and // nothing resubscribes. The publisher must see the budget rounded up instead. A floor // of 1, not 0: a pre-06 wire folds a vacuous floor of 0 back to absent. - const subscriber = remote.track("video").subscribe({ maxAge: Milli(38.75), groups: { start: { included: 1 } } }); + const subscriber = remote.track("video").subscribe({ maxDelay: Milli(38.75), groups: { start: { included: 1 } } }); // A failed subscribe never reaches the publisher, so race its closure to report the // encode error rather than block until the suite times out. @@ -236,11 +236,11 @@ test("integration: lite carries a fractional maxAge as a whole millisecond", asy }); const producer = await Promise.race([accepted, failed]); - expect(producer.subscription.peek()?.maxAge).toBe(Milli(39)); + expect(producer.subscription.peek()?.maxDelay).toBe(Milli(39)); const updated = producer.subscription.changed(); - subscriber.update({ maxAge: Milli(500.25), groups: { start: { included: 1 } } }); - expect((await Promise.race([updated, failed]))?.maxAge).toBe(Milli(501)); + subscriber.update({ maxDelay: Milli(500.25), groups: { start: { included: 1 } } }); + expect((await Promise.race([updated, failed]))?.maxDelay).toBe(Milli(501)); subscriber.close(); remote.close(); @@ -276,7 +276,7 @@ test("integration: lite applies initial and updated group bounds", async () => { const subscriber = remote .track("video") .subscribe({ - maxAge: Milli(REPLAY_LATENCY_MS), + maxDelay: Milli(REPLAY_LATENCY_MS), groups: { start: { included: INITIAL_START_GROUP }, end: { excluded: INITIAL_END_GROUP } }, }) .ordered(); @@ -288,7 +288,7 @@ test("integration: lite applies initial and updated group bounds", async () => { expect(await Promise.race([pending, sleep(PENDING_ASSERT_MS).then(() => "pending")])).toBe("pending"); subscriber.update({ - maxAge: Milli(REPLAY_LATENCY_MS), + maxDelay: Milli(REPLAY_LATENCY_MS), groups: { start: { included: UPDATED_GROUP }, end: { excluded: UPDATED_END_GROUP } }, }); expect((await withTimeout(pending, UPDATE_TIMEOUT_MS, "updated group bound timed out"))?.sequence).toBe( @@ -327,7 +327,7 @@ test("integration: lite refuses an empty requested range on open and on update", try { // Bounds that meet cannot go on the wire: the nearest encoding inverts the range. const empty = video.subscribe({ - maxAge: Milli(REPLAY_LATENCY_MS), + maxDelay: Milli(REPLAY_LATENCY_MS), groups: { start: { included: 2 }, end: { excluded: 2 } }, }); await expect(withTimeout(empty.recvGroup(), TIMEOUT_MS, "empty open never settled")).rejects.toThrow( @@ -338,13 +338,13 @@ test("integration: lite refuses an empty requested range on open and on update", // A live subscription whose demand later collapses to nothing fails the same way. const live = video .subscribe({ - maxAge: Milli(REPLAY_LATENCY_MS), + maxDelay: Milli(REPLAY_LATENCY_MS), groups: { start: { included: 1 }, end: { excluded: 2 } }, }) .ordered(); expect((await live.nextGroup())?.sequence).toBe(1); live.update({ - maxAge: Milli(REPLAY_LATENCY_MS), + maxDelay: Milli(REPLAY_LATENCY_MS), groups: { start: { included: 3 }, end: { excluded: 3 } }, }); await expect(withTimeout(live.nextGroup(), TIMEOUT_MS, "empty update never settled")).rejects.toThrow( diff --git a/js/net/src/lite/connection.test.ts b/js/net/src/lite/connection.test.ts index 5bc9afd83ad..6409c056d5b 100644 --- a/js/net/src/lite/connection.test.ts +++ b/js/net/src/lite/connection.test.ts @@ -278,7 +278,7 @@ async function servedRawSubscription() { broadcast: Path.from("room"), track: "video", priority: 0, - maxAge: 10_000, + maxDelay: 10_000, startGroup: 0, }).encode(subscriber.writer, version); @@ -446,7 +446,7 @@ test("close waits for a request served while withdrawals are in flight", async ( broadcast: Path.from("room"), track: "video", priority: 0, - maxAge: 10_000, + maxDelay: 10_000, startGroup: 0, }).encode(subscriber.writer, version); expect("start" in (await decodeSubscribeResponse(subscriber.reader, version))).toBe(true); diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 81492ed6a91..5ec6325c380 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -24,14 +24,14 @@ function publish(origin: OriginProducer, path: Path.Valid) { } // Scheduling tests intentionally stall groups, so keep latency enforcement out of their scope. -const TEST_MAX_AGE_MS = Milli(30_000); +const TEST_MAX_DELAY_MS = Milli(30_000); function replaySubscribe(props: ConstructorParameters[0]) { - return new Subscribe({ ...props, maxAge: TEST_MAX_AGE_MS }); + return new Subscribe({ ...props, maxDelay: TEST_MAX_DELAY_MS }); } function replayUpdate(props: ConstructorParameters[0]) { - return new SubscribeUpdate({ ...props, maxAge: TEST_MAX_AGE_MS }); + return new SubscribeUpdate({ ...props, maxDelay: TEST_MAX_DELAY_MS }); } test.each([Version.DRAFT_01, Version.DRAFT_03, Version.DRAFT_06])( @@ -926,7 +926,7 @@ test("lite draft-06: scheduling updates apply while SUBSCRIBE_START is blocked", expect(sub.track.subscription.peek()).toEqual({ priority: 9, - maxAge: TEST_MAX_AGE_MS, + maxDelay: TEST_MAX_DELAY_MS, groups: { start: undefined, end: { excluded: 6 } }, }); expect(ranges).not.toHaveBeenCalled(); @@ -1558,7 +1558,7 @@ test("a version without the latency field serves a non-dropping budget", async ( try { // These drafts decode the absent field as zero. The publisher must not turn // that into a live-edge request the peer never made. - expect(sub.track.subscription.peek()?.maxAge).toBe(Milli(Number.MAX_SAFE_INTEGER)); + expect(sub.track.subscription.peek()?.maxDelay).toBe(Milli(Number.MAX_SAFE_INTEGER)); } finally { await sub.close(); } @@ -1611,7 +1611,7 @@ test("lite draft-05: a group that goes stale while its stream opens writes nothi try { process.on("unhandledRejection", onUnhandled); void publisher.runSubscribe( - new Subscribe({ id: 0n, broadcast: Path.from("test"), track: "video", priority: 0, maxAge: 100 }), + new Subscribe({ id: 0n, broadcast: Path.from("test"), track: "video", priority: 0, maxDelay: 100 }), server, ); @@ -1630,7 +1630,7 @@ test("lite draft-05: a group that goes stale while its stream opens writes nothi write(2, 20_000); open(); - expect(String(await streamReset)).toContain("max age budget"); + expect(String(await streamReset)).toContain("max delay budget"); expect(writes).toBe(0); await flush(); expect(unhandled).toEqual([]); diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index 09a67a90a41..b7cafb81d07 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -302,12 +302,12 @@ function waitForSubscription(controls: SubscriptionControls, subscriber: track.S * a legacy subscriber never declined, so fall back to a window wide enough not to drop * and leave enforcement to the receiver, as the IETF path does for the same reason. */ -function servingMaxAge(version: Version, requested: number | undefined): number { - return carriesMaxAge(version) ? (requested ?? 0) : Number.MAX_SAFE_INTEGER; +function servingMaxDelay(version: Version, requested: number | undefined): number { + return carriesMaxDelay(version) ? (requested ?? 0) : Number.MAX_SAFE_INTEGER; } /** Whether this version's SUBSCRIBE carries Subscriber Max Age at all. */ -function carriesMaxAge(version: Version): boolean { +function carriesMaxDelay(version: Version): boolean { return version !== Version.DRAFT_01 && version !== Version.DRAFT_02; } @@ -315,12 +315,12 @@ function carriesMaxAge(version: Version): boolean { * Position a subscription's read cursor for the wire serving it. * * On lite-06 there is nothing to do: the cursor is floored at the group the subscription - * named (or 0), and its Max Age decides what above the floor is worth delivering. + * named (or 0), and its max delay decides what above the floor is worth delivering. * * Pre-06 wires are the exception: their drafts define an absent `Group Start` as the * latest group, so say so explicitly rather than letting the budget reach back. Lite-03/04/05 - * carry a Max Age, but there it is a staleness tolerance only; lite-01/02 additionally get - * an unbounded budget so nothing is dropped under them (see {@link servingMaxAge}), which + * carry a `Subscriber Max Age`, but there it is a staleness tolerance only; lite-01/02 additionally get + * an unbounded budget so nothing is dropped under them (see {@link servingMaxDelay}), which * must not read as a request to replay the whole cache on join. */ function positionCursor(track: track.Subscriber, version: Version, startGroup: number | undefined) { @@ -593,7 +593,7 @@ export class Publisher { const endGroup = exclusiveGroupEnd(msg.endGroup); const track = wireOf(front).subscribe(msg.track, { priority: msg.priority, - maxAge: Milli(servingMaxAge(this.version, msg.maxAge)), + maxDelay: Milli(servingMaxDelay(this.version, msg.maxDelay)), groups: { start: msg.startGroup === undefined ? undefined : { included: msg.startGroup }, end: endGroup === undefined ? undefined : { excluded: endGroup }, @@ -627,7 +627,7 @@ export class Publisher { // Older drafts acknowledge with SUBSCRIBE_OK and stream frames verbatim. const ok = new SubscribeOk({ priority: msg.priority, - maxAge: msg.maxAge, + maxDelay: msg.maxDelay, startGroup: msg.startGroup, endGroup: msg.endGroup, }); @@ -650,7 +650,7 @@ export class Publisher { const end = exclusiveGroupEnd(update.endGroup); track.update({ priority: update.priority, - maxAge: Milli(servingMaxAge(this.version, update.maxAge)), + maxDelay: Milli(servingMaxDelay(this.version, update.maxDelay)), groups: { start: update.startGroup === undefined ? undefined : { included: update.startGroup }, end: end === undefined ? undefined : { excluded: end }, diff --git a/js/net/src/lite/subscribe.test.ts b/js/net/src/lite/subscribe.test.ts index 79c6737f7a6..ea847db0599 100644 --- a/js/net/src/lite/subscribe.test.ts +++ b/js/net/src/lite/subscribe.test.ts @@ -71,7 +71,7 @@ async function encodeMessage( test("SubscribeOk round-trips priority/groups on draft-04", async () => { const got = await responseRoundtrip(Version.DRAFT_04, { - ok: new SubscribeOk({ priority: 7, maxAge: 250, startGroup: 3 }), + ok: new SubscribeOk({ priority: 7, maxDelay: 250, startGroup: 3 }), }); expect("ok" in got).toBe(true); if (!("ok" in got)) throw new Error("expected ok"); @@ -85,7 +85,7 @@ test("Subscribe round-trips every option including startGroup 0", async () => { broadcast: Path.from("test"), track: "video", priority: 7, - maxAge: 250, + maxDelay: 250, startGroup: 0, endGroup: 9, }); @@ -96,7 +96,7 @@ test("Subscribe round-trips every option including startGroup 0", async () => { Version.DRAFT_06, ); expect(got.priority).toBe(7); - expect(got.maxAge).toBe(250); + expect(got.maxDelay).toBe(250); expect(got.startGroup).toBeUndefined(); expect(got.endGroup).toBe(9); @@ -124,7 +124,7 @@ test("Subscribe round-trips every option including startGroup 0", async () => { test("SubscribeUpdate round-trips every option including startGroup 0", async () => { const message = new SubscribeUpdate({ priority: 8, - maxAge: 500, + maxDelay: 500, startGroup: 0, endGroup: 12, }); @@ -133,7 +133,7 @@ test("SubscribeUpdate round-trips every option including startGroup 0", async () Version.DRAFT_06, ); expect(got.priority).toBe(8); - expect(got.maxAge).toBe(500); + expect(got.maxDelay).toBe(500); expect(got.startGroup).toBeUndefined(); expect(got.endGroup).toBe(12); diff --git a/js/net/src/lite/subscribe.ts b/js/net/src/lite/subscribe.ts index 084f68f40ed..ec6b4b13d8a 100644 --- a/js/net/src/lite/subscribe.ts +++ b/js/net/src/lite/subscribe.ts @@ -150,8 +150,8 @@ export function emptyRange({ startGroup, endGroup }: { startGroup?: number; endG export class SubscribeUpdate { priority: number; - /** Subscriber max latency in milliseconds; zero skips once a newer group is available. */ - maxAge: number; + /** Subscriber max delay in milliseconds; zero skips once a newer group is available. */ + maxDelay: number; startGroup?: number; endGroup?: number; /** See {@link Subscribe.startFrame}. */ @@ -161,14 +161,14 @@ export class SubscribeUpdate { constructor(props: { priority: number; - maxAge?: number; + maxDelay?: number; startGroup?: number; endGroup?: number; startFrame?: number; endFrame?: number; }) { this.priority = props.priority; - this.maxAge = props.maxAge ?? 0; + this.maxDelay = props.maxDelay ?? 0; this.startGroup = props.startGroup; this.endGroup = props.endGroup; this.startFrame = props.startFrame ?? 0; @@ -184,7 +184,7 @@ export class SubscribeUpdate { default: await w.u8(this.priority); await padGroupOrder(w, version); - await w.u53(this.maxAge); + await w.u53(this.maxDelay); await encodeStartGroup(w, version, this.startGroup); await w.u53(this.endGroup !== undefined ? this.endGroup + 1 : 0); await encodeFrameBounds(w, version, this); @@ -200,14 +200,14 @@ export class SubscribeUpdate { default: { const priority = await r.u8(); await skipGroupOrder(r, version); - const maxAge = await r.u53(); + const maxDelay = await r.u53(); const startGroup = await decodeStartGroup(r, version); const endGroup = (await r.u53()) || undefined; const end = endGroup !== undefined ? endGroup - 1 : undefined; const frames = await decodeFrameBounds(r, version, startGroup, end); return new SubscribeUpdate({ priority, - maxAge, + maxDelay, startGroup: canonicalStartGroup(version, startGroup, frames.startFrame), endGroup: end, ...frames, @@ -236,8 +236,8 @@ export class Subscribe { epoch?: Epoch.Valid; track: string; priority: number; - /** Subscriber max latency in milliseconds; zero skips once a newer group is available. */ - maxAge: number; + /** Subscriber max delay in milliseconds; zero skips once a newer group is available. */ + maxDelay: number; startGroup?: number; endGroup?: number; @@ -261,7 +261,7 @@ export class Subscribe { epoch?: Epoch.Valid; track: string; priority: number; - maxAge?: number; + maxDelay?: number; startGroup?: number; endGroup?: number; startFrame?: number; @@ -272,7 +272,7 @@ export class Subscribe { this.epoch = props.epoch; this.track = props.track; this.priority = props.priority; - this.maxAge = props.maxAge ?? 0; + this.maxDelay = props.maxDelay ?? 0; this.startGroup = props.startGroup; this.endGroup = props.endGroup; this.startFrame = props.startFrame ?? 0; @@ -292,7 +292,7 @@ export class Subscribe { break; default: await padGroupOrder(w, version); - await w.u53(this.maxAge); + await w.u53(this.maxDelay); await encodeStartGroup(w, version, this.startGroup); await w.u53(this.endGroup !== undefined ? this.endGroup + 1 : 0); await encodeFrameBounds(w, version, this); @@ -313,7 +313,7 @@ export class Subscribe { return new Subscribe({ id, broadcast, track, priority }); default: { await skipGroupOrder(r, version); - const maxAge = await r.u53(); + const maxDelay = await r.u53(); const startGroup = await decodeStartGroup(r, version); const endGroup = (await r.u53()) || undefined; const end = endGroup !== undefined ? endGroup - 1 : undefined; @@ -324,7 +324,7 @@ export class Subscribe { epoch, track, priority, - maxAge, + maxDelay, startGroup: canonicalStartGroup(version, startGroup, frames.startFrame), endGroup: end, ...frames, @@ -350,24 +350,24 @@ export class Subscribe { */ export class SubscribeOk { priority: number; - /** Accepted subscriber max latency in milliseconds. */ - maxAge: number; + /** Accepted subscriber max delay in milliseconds. */ + maxDelay: number; startGroup?: number; endGroup?: number; constructor({ priority = 0, - maxAge = 0, + maxDelay = 0, startGroup = undefined, endGroup = undefined, }: { priority?: number; - maxAge?: number; + maxDelay?: number; startGroup?: number; endGroup?: number; }) { this.priority = priority; - this.maxAge = maxAge; + this.maxDelay = maxDelay; this.startGroup = startGroup; this.endGroup = endGroup; } @@ -385,7 +385,7 @@ export class SubscribeOk { default: await w.u8(this.priority); await padGroupOrder(w, version); - await w.u53(this.maxAge); + await w.u53(this.maxDelay); await w.u53(this.startGroup !== undefined ? this.startGroup + 1 : 0); await w.u53(this.endGroup !== undefined ? this.endGroup + 1 : 0); break; @@ -394,7 +394,7 @@ export class SubscribeOk { static async #decode(version: Version, r: Reader): Promise { let priority: number | undefined; - let maxAge: number | undefined; + let maxDelay: number | undefined; let startGroup: number | undefined; let endGroup: number | undefined; @@ -408,7 +408,7 @@ export class SubscribeOk { default: priority = await r.u8(); await skipGroupOrder(r, version); - maxAge = await r.u53(); + maxDelay = await r.u53(); startGroup = await r.u53(); endGroup = await r.u53(); break; @@ -416,7 +416,7 @@ export class SubscribeOk { return new SubscribeOk({ priority, - maxAge, + maxDelay, startGroup: startGroup !== undefined && startGroup > 0 ? startGroup - 1 : undefined, endGroup: endGroup !== undefined && endGroup > 0 ? endGroup - 1 : undefined, }); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index eb2bae2d213..d63a403aae4 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -534,7 +534,7 @@ export class Subscriber { epoch, track: request.name, priority: subscription.priority ?? 0, - maxAge: subscription.maxAge, + maxDelay: subscription.maxDelay, startGroup: subscription.groups?.start === undefined ? undefined : bounds.start, endGroup: inclusiveGroupEnd(bounds.end), }); @@ -665,13 +665,13 @@ export class Subscriber { const entry: SubscribeEntry = { track: producer, timescale, - // The effective max age is the stopgap grace: the wrong clock (it bounds + // The effective max delay is the stopgap grace: the wrong clock (it bounds // presentation-time drift), but it is how long the subscriber was willing to wait // for a late group anyway. Already the smaller of the subscriber's and the track's. tail: new Tail({ grace: () => { - const maxAge = producer.subscription.peek()?.maxAge ?? Time.Milli.zero; - return maxAge > 0 ? maxAge : TAIL_GRACE_MS; + const maxDelay = producer.subscription.peek()?.maxDelay ?? Time.Milli.zero; + return maxDelay > 0 ? maxDelay : TAIL_GRACE_MS; }, }), requested: msg.startGroup, @@ -998,7 +998,7 @@ export class Subscriber { const stopped: Promise = race([track.closed, stream.reader.closed]).then(() => null); let lastSent: track.Subscription = { priority: msg.priority, - maxAge: Time.Milli(msg.maxAge), + maxDelay: Time.Milli(msg.maxDelay), groups: { start: msg.startGroup === undefined ? undefined : { included: msg.startGroup }, end: msg.endGroup === undefined ? undefined : { excluded: exclusiveGroupEnd(msg.endGroup) ?? 0 }, @@ -1026,10 +1026,10 @@ export class Subscriber { } // Round-trip the other Subscribe parameters so the publisher doesn't - // interpret SUBSCRIBE_UPDATE as a reset of ordered/maxAge/etc. + // interpret SUBSCRIBE_UPDATE as a reset of ordered/maxDelay/etc. const update = new SubscribeUpdate({ priority: current.priority ?? 0, - maxAge: current.maxAge, + maxDelay: current.maxDelay, startGroup: current.groups?.start === undefined ? undefined : bounds.start, endGroup: inclusiveGroupEnd(bounds.end), }); @@ -1044,7 +1044,7 @@ export class Subscriber { const bg = groupBounds(b.groups); return ( (a.priority ?? 0) === (b.priority ?? 0) && - (a.maxAge ?? 0) === (b.maxAge ?? 0) && + (a.maxDelay ?? 0) === (b.maxDelay ?? 0) && ag.start === bg.start && ag.end === bg.end ); diff --git a/js/net/src/lite/tail.test.ts b/js/net/src/lite/tail.test.ts index 5a7d522dd0b..f83ee784800 100644 --- a/js/net/src/lite/tail.test.ts +++ b/js/net/src/lite/tail.test.ts @@ -21,7 +21,7 @@ import { Subscriber } from "./subscriber.ts"; import { TrackInfo, Track as TrackMessage } from "./track.ts"; import { ALPN_05, Version } from "./version.ts"; -// The subscription's max age, which is also how long it waits for a group that never arrives. +// The subscription's max delay, which is also how long it waits for a group that never arrives. const GRACE = Milli(100); /** One lite-05+ frame: a zero timestamp delta, then the length-prefixed payload. */ @@ -52,10 +52,10 @@ function groupStream(subscriber: Subscriber, sequence: number) { * it answers TRACK_INFO, then writes whatever responses the test asks for on the subscribe * stream and FINs it when told. */ -async function subscribed(version: Version, maxAge = GRACE, groups?: Groups) { +async function subscribed(version: Version, maxDelay = GRACE, groups?: Groups) { const pair = createMockTransportPair(ALPN_05); const subscriber = new Subscriber(pair.client, version, randomHop()); - const reader = subscriber.consume(Path.from("room")).track("video").subscribe({ maxAge, groups }); + const reader = subscriber.consume(Path.from("room")).track("video").subscribe({ maxDelay, groups }); const info = await Stream.accept(pair.server, version); if (!info) throw new Error("the subscriber never asked for TRACK_INFO"); @@ -186,7 +186,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const sub = await subscribed(version); subscriber = sub.subscriber; const { reader, respond, fin } = sub; - const ordered = reader.fork({ maxAge: GRACE }).ordered(); + const ordered = reader.fork({ maxDelay: GRACE }).ordered(); await respond({ start: new SubscribeStart(0) }); const group = groupStream(subscriber, 1); group.write("1.0"); @@ -219,7 +219,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test.skipIf(version === Version.DRAFT_07)( "a subscription ends without waiting once every group is accounted for", async () => { - // A max age far past the test's patience: only the accounting may end it. + // A max delay far past the test's patience: only the accounting may end it. const { subscriber, reader, respond, fin } = await subscribed(version, Milli(60_000)); await respond({ start: new SubscribeStart(0) }); await respond({ drop: new SubscribeDrop({ start: 0, end: 0, error: 0 }) }); @@ -277,8 +277,8 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver }); test.skipIf(version === Version.DRAFT_07)("a lowered floor owes the groups it newly asked for", async () => { - const maxAge = Milli(60_000); - const { subscriber, respond, fin } = await subscribed(version, maxAge, { start: { included: 3 } }); + const maxDelay = Milli(60_000); + const { subscriber, respond, fin } = await subscribed(version, maxDelay, { start: { included: 3 } }); await respond({ start: new SubscribeStart(3) }); const group = groupStream(subscriber, 3); group.write("3.0"); @@ -289,7 +289,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const lower = subscriber .consume(Path.from("room")) .track("video") - .subscribe({ maxAge, groups: { start: { included: 1 } } }); + .subscribe({ maxDelay, groups: { start: { included: 1 } } }); await respond({ end: new SubscribeEnd(4, 1) }); await fin(); // Long enough for a subscription that owed nothing more to have ended. diff --git a/js/net/src/tail.test.ts b/js/net/src/tail.test.ts index 972df8faec9..478caa64718 100644 --- a/js/net/src/tail.test.ts +++ b/js/net/src/tail.test.ts @@ -15,7 +15,7 @@ const url = new URL("https://localhost:4443/test"); // Long enough that no group is skipped as stale, and the moq-lite grace for the one group the // IETF case never produces. -const MAX_AGE = Milli(100); +const MAX_DELAY = Milli(100); async function session(protocol: string) { const pair = createMockTransportPair(protocol); @@ -28,7 +28,7 @@ async function session(protocol: string) { broadcast.announce(); const video = broadcast.createTrack("video"); const remote = wireOf(client).consume(Path.from("test")); - const reader = remote.track("video").subscribe({ maxAge: MAX_AGE }).ordered(); + const reader = remote.track("video").subscribe({ maxDelay: MAX_DELAY }).ordered(); return { video, diff --git a/js/net/src/tail.ts b/js/net/src/tail.ts index b732ae11338..dbfd3eab0d6 100644 --- a/js/net/src/tail.ts +++ b/js/net/src/tail.ts @@ -7,7 +7,7 @@ import { Milli } from "./time.ts"; * * A group reset before its header arrived leaves no trace, and QUIC does not order streams, * so a stream opened before the end can still be in flight after it. This bounds the wait on - * IETF, and on moq-lite when the subscription has no max age to bound it with. + * IETF, and on moq-lite when the subscription has no max delay to bound it with. */ export const TAIL_GRACE_MS = Milli(1000); diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 59006030379..96971498307 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -3,7 +3,7 @@ import { TooFarBehind } from "./error.ts"; import { Producer as GroupProducer, MAX_GROUP_FRAMES } from "./group.ts"; import { hooks } from "./internal.ts"; import { Milli, Timescale, Timestamp } from "./time.ts"; -import { infoDefaults, Producer as TrackProducer } from "./track.ts"; +import { infoDefaults, type Subscription, Producer as TrackProducer } from "./track.ts"; const enc = new TextEncoder(); const dec = new TextDecoder(); @@ -189,7 +189,7 @@ test("insertDatagram preserves an explicit sequence", async () => { test("recvDatagram leaves the ordered group cursor alone", async () => { const producer = new TrackProducer("test"); const datagrams = producer.subscribe(); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); producer.insertDatagram(5, Timestamp.fromMillis(5), enc.encode("x")); expect((await datagrams.recvDatagram())?.sequence).toBe(5); @@ -267,50 +267,69 @@ test("subscriber options and updates are forwarded to the producer's aggregate", // The initial options are available before the request is accepted or put on the wire. expect(producer.subscription.peek()).toEqual({ priority: 0, - maxAge: Milli(0), + maxDelay: Milli(0), groups: { start: { included: 0 } }, }); // The wire layer watches the producer's signal to emit SUBSCRIBE_UPDATE. const next = producer.subscription.changed(); - track.update({ priority: 7, maxAge: Milli(250), groups: { start: { included: 2 }, end: { excluded: 9 } } }); + track.update({ priority: 7, maxDelay: Milli(250), groups: { start: { included: 2 }, end: { excluded: 9 } } }); expect(await next).toEqual({ priority: 7, - maxAge: Milli(250), + maxDelay: Milli(250), groups: { start: { included: 2 }, end: { excluded: 9 } }, }); }); -test("a fractional maxAge is rounded up before the wire sees it", async () => { +test("subscriber maxAge is refused before defaults or updates take effect", () => { + const producer = new TrackProducer("test"); + const track = producer.subscribe({ maxDelay: Milli(250) }); + const original = producer.subscription.peek(); + + for (const maxAge of [Milli(500), undefined]) { + expect(() => producer.subscribe({ maxAge } as Subscription)).toThrow("maxDelay"); + const options = { maxDelay: Milli(100), maxAge }; + expect(() => producer.subscribe(options)).toThrow(TypeError); + expect(() => track.update(options)).toThrow("maxDelay"); + expect(producer.subscription.peek()).toEqual(original); + } + + // Publisher retention keeps its distinct maxAge field. + producer.accept({ maxAge: Milli(500) }); + track.close(); + producer.close(); +}); + +test("a fractional maxDelay is rounded up before the wire sees it", async () => { const producer = new TrackProducer("test"); // Subscribers derive this from measurements (a jitter estimate scaled off RTT), so a // fractional millisecond is expected. The wire encodes it as a varint, which throws on a // non-integer, and rounding down would shorten a budget the subscriber asked for. - const track = producer.subscribe({ maxAge: Milli(38.75) }); - expect(producer.subscription.peek()?.maxAge).toBe(Milli(39)); + const track = producer.subscribe({ maxDelay: Milli(38.75) }); + expect(producer.subscription.peek()?.maxDelay).toBe(Milli(39)); const next = producer.subscription.changed(); - track.update({ maxAge: Milli(500.25) }); - expect((await next)?.maxAge).toBe(Milli(501)); + track.update({ maxDelay: Milli(500.25) }); + expect((await next)?.maxDelay).toBe(Milli(501)); // The publisher half of the budget lands on the wire through TRACK_INFO, with the same hazard. producer.accept({ maxAge: Milli(1000.5) }); expect((await producer.info()).maxAge).toBe(Milli(1001)); }); -test("a maxAge that is not a duration is refused, not rounded into one", () => { +test("a maxDelay or maxAge that is not a duration is refused, not rounded into one", () => { const producer = new TrackProducer("test"); // The wire carries an unsigned varint, so rounding these would encode a budget the // caller never asked for: -0.5 would ceil to zero and silently take the live edge. - expect(() => producer.subscribe({ maxAge: Milli(-0.5) })).toThrow(RangeError); - expect(() => producer.subscribe({ maxAge: Milli(-100) })).toThrow(RangeError); - expect(() => producer.subscribe({ maxAge: Milli(Number.NaN) })).toThrow(RangeError); - expect(() => producer.subscribe({ maxAge: Milli(Number.POSITIVE_INFINITY) })).toThrow(RangeError); + expect(() => producer.subscribe({ maxDelay: Milli(-0.5) })).toThrow(RangeError); + expect(() => producer.subscribe({ maxDelay: Milli(-100) })).toThrow(RangeError); + expect(() => producer.subscribe({ maxDelay: Milli(Number.NaN) })).toThrow(RangeError); + expect(() => producer.subscribe({ maxDelay: Milli(Number.POSITIVE_INFINITY) })).toThrow(RangeError); expect(() => producer.accept({ maxAge: Milli(-0.5) })).toThrow(RangeError); expect(() => producer.accept({ maxAge: Milli(Number.MAX_SAFE_INTEGER + 1) })).toThrow(RangeError); - expect(() => producer.subscribe({ maxAge: Milli(Number.MAX_SAFE_INTEGER + 1) })).toThrow(RangeError); + expect(() => producer.subscribe({ maxDelay: Milli(Number.MAX_SAFE_INTEGER + 1) })).toThrow(RangeError); }); test("priority 255 is accepted and 256 is refused", () => { @@ -335,14 +354,14 @@ test("multiple subscriber options aggregate like Rust", async () => { const producer = new TrackProducer("test"); const bounded = producer.subscribe({ priority: 2, - maxAge: Milli(100), + maxDelay: Milli(100), groups: { start: { included: 10 }, end: { excluded: 20 } }, }); - const live = producer.subscribe({ priority: 7, maxAge: Milli(250), groups: { start: { included: 5 } } }); + const live = producer.subscribe({ priority: 7, maxDelay: Milli(250), groups: { start: { included: 5 } } }); expect(producer.subscription.peek()).toEqual({ priority: 7, - maxAge: Milli(250), + maxDelay: Milli(250), groups: { start: { included: 5 } }, }); @@ -350,7 +369,7 @@ test("multiple subscriber options aggregate like Rust", async () => { live.close(); expect(await narrowed).toEqual({ priority: 2, - maxAge: Milli(100), + maxDelay: Milli(100), groups: { start: { included: 10 }, end: { excluded: 20 } }, }); @@ -361,13 +380,13 @@ test("multiple subscriber options aggregate like Rust", async () => { test("the producer aggregate is clamped without changing subscriber options", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(10_000) }); + const track = producer.subscribe({ maxDelay: Milli(10_000) }); const clamped = producer.subscription.changed(); producer.accept({ maxAge: Milli(2_000) }); - expect((await clamped)?.maxAge).toBe(Milli(2_000)); - expect(track.subscription.peek()?.maxAge).toBe(Milli(10_000)); + expect((await clamped)?.maxDelay).toBe(Milli(2_000)); + expect(track.subscription.peek()?.maxDelay).toBe(Milli(10_000)); }); test("nextGroup skips late arrivals", async () => { @@ -390,7 +409,7 @@ test("nextGroup skips late arrivals", async () => { test("nextGroup returns buffered groups in sequence", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); producer.writeGroup(new GroupProducer(3)); producer.writeGroup(new GroupProducer(5)); @@ -404,7 +423,7 @@ test("nextGroup returns buffered groups in sequence", async () => { // its first timestamp would discard exactly the group being filled. test("a long group is not stale while its tail reaches the edge", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(5000) }); - const sub = producer.subscribe({ maxAge: Milli(500) }); + const sub = producer.subscribe({ maxDelay: Milli(500) }); // Group 0 spans 0..2000ms; group 1 starts at 2000ms, where group 0 ends. const long = producer.appendGroup(); @@ -420,7 +439,7 @@ test("a long group is not stale while its tail reaches the edge", async () => { test("a long group is stale once its successor falls behind", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(5000) }); - const sub = producer.subscribe({ maxAge: Milli(500) }); + const sub = producer.subscribe({ maxDelay: Milli(500) }); const long = producer.appendGroup(); for (const ms of [0, 500, 1000]) { @@ -441,7 +460,7 @@ test("a long group is stale once its successor falls behind", async () => { // track using both channels needs one subscription, not two. test("the ordered handle carries datagrams", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); producer.insertDatagram(5, Timestamp.fromMillis(5), enc.encode("x")); producer.writeGroup(new GroupProducer(3)); @@ -466,7 +485,7 @@ test("the latency budget skips a buffered timeline on either cursor", async () = expect((await ordered.nextGroup())?.sequence).toBe(2); // The budget is the only gate: one that spans the backlog bursts it in order. - const replay = producer.subscribe({ maxAge: Milli(30_000) }).ordered(); + const replay = producer.subscribe({ maxDelay: Milli(30_000) }).ordered(); expect((await replay.nextGroup())?.sequence).toBe(0); expect((await replay.nextGroup())?.sequence).toBe(1); expect((await replay.nextGroup())?.sequence).toBe(2); @@ -493,7 +512,7 @@ test("an unstamped immediate successor leaves reach unbounded", async () => { // arrived last. test("a late-arriving successor bounds a group's reach", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(5000) }); - const track = producer.subscribe({ maxAge: Milli(500) }); + const track = producer.subscribe({ maxDelay: Milli(500) }); for (const [sequence, ms] of [ [0, 0], @@ -516,7 +535,7 @@ test("a late-arriving successor bounds a group's reach", async () => { // backlog inside it is drained in full, and what is past it is skipped. test("ordered frame reads follow the budget", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(5000) }); - const ordered = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const ordered = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); const live = producer.subscribe().ordered(); for (const timestamp of [0, 1000, 2000]) { @@ -535,7 +554,7 @@ test("ordered frame reads follow the budget", async () => { // read never runs backwards. test("nextGroup abandons the frame helpers' group when it passes it", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); const zero = new GroupProducer(0); zero.writeString("0.0"); @@ -567,7 +586,7 @@ test("nextGroup abandons the frame helpers' group when it passes it", async () = // after a higher one was read is skipped, never fed to the caller backwards. test("ordered frame reads skip a late lower-sequence group", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); const five = new GroupProducer(5); five.writeString("five"); @@ -604,7 +623,7 @@ test("zero latency takes the latest group when ages are equal", async () => { test("latency budget admits groups within its presentation-time window", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(5000) }); - const track = producer.subscribe({ maxAge: Milli(1500) }); + const track = producer.subscribe({ maxDelay: Milli(1500) }); for (const timestamp of [0, 1000, 2000]) { producer.writeFrame({ payload: enc.encode(`${timestamp}`), timestamp: Timestamp.fromMillis(timestamp) }); @@ -629,7 +648,7 @@ test("a late lower group within the budget is delivered", async () => { group.close(); } - const track = producer.subscribe({ maxAge: Milli(5000) }); + const track = producer.subscribe({ maxDelay: Milli(5000) }); expect((await track.recvGroup())?.sequence).toBe(5); expect((await track.recvGroup())?.sequence).toBe(6); expect((await track.recvGroup())?.sequence).toBe(7); @@ -655,7 +674,7 @@ test("a named start is a floor, not a request", async () => { // The budget is the only thing that asks for data; a named start only bounds how far // back it may reach. - const floored = producer.subscribe({ groups: { start: { included: 3 } }, maxAge: Milli(60_000) }); + const floored = producer.subscribe({ groups: { start: { included: 3 } }, maxDelay: Milli(60_000) }); expect((await floored.recvGroup())?.sequence).toBe(3); expect((await floored.recvGroup())?.sequence).toBe(4); @@ -678,13 +697,13 @@ test("the ordered cursor sheds a stale backlog", async () => { // Only what is provably too old goes. Group 0 reaches 1s, a full 2s behind the 3s // edge; group 1 reaches 2s and could still present inside a 1.5s budget. - const bounded = producer.subscribe({ maxAge: Milli(1500) }).ordered(); + const bounded = producer.subscribe({ maxDelay: Milli(1500) }).ordered(); expect((await bounded.nextGroup())?.sequence).toBe(1); expect((await bounded.nextGroup())?.sequence).toBe(2); expect((await bounded.nextGroup())?.sequence).toBe(3); // A budget spanning the history still bursts it in full, gap-free. - const replay = producer.subscribe({ maxAge: Milli(30_000) }).ordered(); + const replay = producer.subscribe({ maxDelay: Milli(30_000) }).ordered(); for (const sequence of [0, 1, 2, 3]) { expect((await replay.nextGroup())?.sequence).toBe(sequence); } @@ -692,7 +711,7 @@ test("the ordered cursor sheds a stale backlog", async () => { test("the budget is clamped to the publisher's window", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(1500) }); - const track = producer.subscribe({ maxAge: Milli(60_000) }); + const track = producer.subscribe({ maxDelay: Milli(60_000) }); // Spaced so group 0's reach (2s) sits 2s behind the edge (4s): outside the // publisher's 1.5s window, inside the subscriber's requested minute. @@ -783,7 +802,7 @@ test("a budget is measured from the reader's position", async () => { // group's first frame instead makes the drift 2000ms, so a budget shorter than one // GOP would drop the tail of every GOP. const producer = new TrackProducer("test").accept({ maxAge: Milli(60_000) }); - const track = producer.subscribe({ maxAge: Milli(1000) }); + const track = producer.subscribe({ maxDelay: Milli(1000) }); const open = producer.appendGroup(); open.writeFrame({ payload: enc.encode("key"), timestamp: Timestamp.fromMillis(0) }); @@ -834,7 +853,7 @@ test("a handed-out group still expires while its first frame is stalled", async test("committing track info wakes a group newly outside the retention window", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(10_000) }); + const track = producer.subscribe({ maxDelay: Milli(10_000) }); const source = producer.appendGroup(); source.writeFrame({ payload: enc.encode("old"), timestamp: Timestamp.fromMillis(0) }); @@ -869,13 +888,13 @@ test("a handed-out frame cancels its in-flight operation when it expires", async const guarded = hooks.guardGroup(group, () => operation); producer.writeString("new"); - await expect(guarded).rejects.toThrow("max age budget"); + await expect(guarded).rejects.toThrow("max delay budget"); release(); }); test("a guarded write keeps the position of the frame removed from the buffer", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); const source = producer.appendGroup(); source.writeFrame({ payload: enc.encode("old"), timestamp: Timestamp.fromMillis(0) }); source.writeFrame({ payload: enc.encode("future"), timestamp: Timestamp.fromMillis(10_000) }); @@ -895,14 +914,14 @@ test("a guarded write keeps the position of the frame removed from the buffer", // A group beyond the edge, so group 0's reach (1s) is provably behind it: a group is // bounded by where its successor begins, so the successor alone never convicts it. producer.writeFrame({ payload: enc.encode("later"), timestamp: Timestamp.fromMillis(2_000) }); - await expect(guarded).rejects.toThrow("max age budget"); + await expect(guarded).rejects.toThrow("max delay budget"); read.complete(); release(); }); test("clean source closure stays provisional while a frame write can expire", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); const source = producer.appendGroup(); source.writeFrame({ payload: enc.encode("old"), timestamp: Timestamp.fromMillis(0) }); source.close(); @@ -925,7 +944,7 @@ test("clean source closure stays provisional while a frame write can expire", as // See above: a group is bounded by where its successor begins, so convicting group 0 // needs a group beyond that successor. producer.writeFrame({ payload: enc.encode("later"), timestamp: Timestamp.fromMillis(2_000) }); - await expect(guarded).rejects.toThrow("max age budget"); + await expect(guarded).rejects.toThrow("max delay budget"); expect(await closed).toBeInstanceOf(Error); read.complete(); @@ -956,7 +975,7 @@ test("a stalled track retains cached groups past its media maxAge", async () => } // Media time has not advanced, even though wall-clock idleness exceeded maxAge. clock.set(10_200); - const replay = producer.subscribe({ maxAge: Milli(100) }); + const replay = producer.subscribe({ maxDelay: Milli(100) }); expect(replay.tryRecvGroup()?.sequence).toBe(0); expect(replay.tryRecvGroup()?.sequence).toBe(1); replay.close(); @@ -978,7 +997,7 @@ test("a live track retains its newest closed group through idle expiry", () => { producer.writeGroup(group); } clock.advance(10_000 + CACHE_WINDOW_MS + 200); - const replay = producer.subscribe({ maxAge: Milli(100) }); + const replay = producer.subscribe({ maxDelay: Milli(100) }); expect(replay.tryRecvGroup()?.sequence).toBe(2); expect(replay.tryRecvGroup()).toBeUndefined(); replay.close(); @@ -996,7 +1015,7 @@ test("retention eviction surfaces as a gap for a handed-out group", async () => const clock = mockMonotonicTime(10_000); try { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); const source = producer.appendGroup(); source.writeString("first"); source.writeString("tail"); @@ -1019,7 +1038,7 @@ test("idle expiry reclaims an ended track's held mirror", async () => { const clock = mockMonotonicTime(10_000); try { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); const source = producer.appendGroup(); source.writeString("first"); source.writeString("tail"); @@ -1031,7 +1050,7 @@ test("idle expiry reclaims an ended track's held mirror", async () => { producer.close(); clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ maxAge: Milli(100) }); + producer.subscribe({ maxDelay: Milli(100) }); await expect(group.readFrame()).rejects.toBeInstanceOf(TooFarBehind); } finally { @@ -1043,7 +1062,7 @@ test("retention reclaims a group the publisher abandoned open", async () => { const clock = mockMonotonicTime(10_000); try { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); const stalled = producer.appendGroup(); stalled.writeString("first"); // A successor, so the stalled group is not the live edge the publisher is @@ -1055,7 +1074,7 @@ test("retention reclaims a group the publisher abandoned open", async () => { expect(await group.readString()).toBe("first"); clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ maxAge: Milli(100) }); + producer.subscribe({ maxDelay: Milli(100) }); // A gap, not a clean finish: the publisher never ended this group. await expect(group.readFrame()).rejects.toBeInstanceOf(TooFarBehind); @@ -1068,7 +1087,7 @@ test("an idle live edge ages out once a newer group arrives", async () => { const clock = mockMonotonicTime(10_000); try { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); const edge = producer.appendGroup(); edge.writeString("first"); @@ -1078,7 +1097,7 @@ test("an idle live edge ages out once a newer group arrives", async () => { // A prune while it is still the live edge keeps it, and finds nothing else to age out. clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ maxAge: Milli(100) }); + producer.subscribe({ maxDelay: Milli(100) }); // A successor ends the exemption, and the group is long past the window, so the // write evicts it rather than a later wakeup. @@ -1098,7 +1117,7 @@ test("an abandoned open group ages out with no further write", async () => { const clock = mockCacheTime(10_000); const producer = new TrackProducer("test").accept({ maxAge: Milli(30) }); try { - const track = producer.subscribe({ maxAge: Milli(30) }); + const track = producer.subscribe({ maxDelay: Milli(30) }); const stalled = producer.appendGroup(); stalled.writeString("first"); producer.appendGroup(); @@ -1134,7 +1153,7 @@ test("retention pruning preserves clean EOF for a drained mirror", async () => { const clock = mockMonotonicTime(10_000); try { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); const source = producer.appendGroup(); source.writeString("only"); source.close(); @@ -1146,7 +1165,7 @@ test("retention pruning preserves clean EOF for a drained mirror", async () => { producer.close(); clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ maxAge: Milli(100) }); + producer.subscribe({ maxDelay: Milli(100) }); expect(await group.readFrame()).toBeUndefined(); expect(await group.closed).toBeNull(); @@ -1160,7 +1179,7 @@ test("system clock changes do not affect the latency budget", async () => { setSystemTime(new Date(10_000)); try { const producer = new TrackProducer("test").accept({ maxAge: Milli(100) }); - const track = producer.subscribe({ maxAge: Milli(100) }); + const track = producer.subscribe({ maxDelay: Milli(100) }); producer.writeString("old"); setSystemTime(new Date(20_000)); @@ -1176,7 +1195,7 @@ test("system clock changes do not affect the latency budget", async () => { test("frame readiness cancels the losing latency waiter", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(5000) }); - const track = producer.subscribe({ maxAge: Milli(5000) }); + const track = producer.subscribe({ maxDelay: Milli(5000) }); const source = producer.appendGroup(); const group = await track.recvGroup(); if (!group) throw new Error("missing group"); @@ -1227,8 +1246,8 @@ test("an aborted live-edge anchor does not make older content stale", async () = test("setGroups with an excluded end of 0 is the empty range and does not ride another subscriber's demand", async () => { const producer = new TrackProducer("test"); - const everything = producer.subscribe({ maxAge: Milli(5000) }); - const empty = producer.subscribe({ maxAge: Milli(5000), groups: { end: { excluded: 0 } } }); + const everything = producer.subscribe({ maxDelay: Milli(5000) }); + const empty = producer.subscribe({ maxDelay: Milli(5000), groups: { end: { excluded: 0 } } }); empty.setGroups({ end: { excluded: 0 } }); for (let sequence = 0; sequence < 3; sequence++) producer.writeGroup(new GroupProducer(sequence)); @@ -1263,7 +1282,7 @@ test("setGroups caps the live edge used by the latency budget", async () => { // above the cap parks (surviving a clean close) until the cap admits it. test("setGroups caps frame-level reads like the group cursor", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(5000) }); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); track.setGroups({ end: { excluded: 1 } }); producer.writeFrame({ payload: enc.encode("zero"), timestamp: Timestamp.fromMillis(0) }); @@ -1285,7 +1304,7 @@ test("setGroups caps frame-level reads like the group cursor", async () => { test("local cursor bounds can skip, pause, and release buffered groups", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); for (let sequence = 0; sequence < 5; sequence++) producer.writeGroup(new GroupProducer(sequence)); @@ -1308,7 +1327,7 @@ test("local cursor bounds can skip, pause, and release buffered groups", async ( // deliver it; a sequence cursor would skip it permanently. test("recvGroup serves a late arrival after a newer group", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }); + const track = producer.subscribe({ maxDelay: Milli(5000) }); producer.writeGroup(new GroupProducer(2)); expect((await track.recvGroup())?.sequence).toBe(2); @@ -1327,7 +1346,7 @@ test("recvGroup serves a late arrival after a newer group", async () => { // held, not dropped, and a raised cap re-offers them, even after a clean close. test("setGroups parks recvGroup beyond the cap and a raised cap re-offers", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }); + const track = producer.subscribe({ maxDelay: Milli(5000) }); for (let sequence = 0; sequence < 3; sequence++) producer.writeGroup(new GroupProducer(sequence)); @@ -1353,7 +1372,7 @@ test("setGroups parks recvGroup beyond the cap and a raised cap re-offers", asyn // a relay can ingest a burst micro-reordered (newest first). test("recvGroup serves in-range groups that arrive behind a capped one", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }); + const track = producer.subscribe({ maxDelay: Milli(5000) }); track.setGroups({ end: { excluded: 2 } }); @@ -1458,8 +1477,8 @@ test("closing the subscriber releases a recvGroup parked while the producer is l test("the ordered and arrival cursors are independent", async () => { const producer = new TrackProducer("test"); - const ordered = producer.subscribe({ maxAge: Milli(5000) }).ordered(); - const arrival = producer.subscribe({ maxAge: Milli(5000) }); + const ordered = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); + const arrival = producer.subscribe({ maxDelay: Milli(5000) }); producer.writeGroup(new GroupProducer(5)); expect((await ordered.nextGroup())?.sequence).toBe(5); @@ -1477,7 +1496,7 @@ test("the first group read commits the cursor and refuses the other order", asyn const producer = new TrackProducer("test"); // An arrival read commits to arrival order; ordered() is refused afterwards. - const arrival = producer.subscribe({ maxAge: Milli(5000) }); + const arrival = producer.subscribe({ maxDelay: Milli(5000) }); producer.writeGroup(new GroupProducer(5)); expect((await arrival.recvGroup())?.sequence).toBe(5); expect(() => arrival.ordered()).toThrow("arrival order"); @@ -1488,7 +1507,7 @@ test("the first group read commits the cursor and refuses the other order", asyn expect((await arrival.recvGroup())?.sequence).toBe(3); // The other direction: ordered() takes the subscription and arrival reads throw. - const inert = producer.subscribe({ maxAge: Milli(5000) }); + const inert = producer.subscribe({ maxDelay: Milli(5000) }); const ordered = inert.ordered(); expect(inert.recvGroup()).rejects.toThrow("sequence order"); expect(() => inert.ordered()).toThrow("sequence order"); @@ -1500,7 +1519,7 @@ test("the first group read commits the cursor and refuses the other order", asyn // the subscription to a group order. test("recvDatagram does not commit the group cursor", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }); + const track = producer.subscribe({ maxDelay: Milli(5000) }); producer.insertDatagram(0, Timestamp.fromMillis(0), enc.encode("x")); expect((await track.recvDatagram())?.sequence).toBe(0); @@ -1523,7 +1542,7 @@ test("nextGroup returns undefined when track closes", async () => { // the data (mirrors the Rust subscriber). Only a drained closed track reports finished. test("a closed track still delivers a group parked above the cap once the cap is raised", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }).ordered(); + const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); for (let sequence = 0; sequence < 3; sequence++) { const group = new GroupProducer(sequence); @@ -1604,7 +1623,7 @@ test("readFrame does not livelock when a sole group finishes before the next arr // a group: a filter is applied down to the object. test("largest names the newest frame written", async () => { const producer = new TrackProducer("test").accept(); - const subscriber = producer.subscribe({ maxAge: Milli(1_000) }); + const subscriber = producer.subscribe({ maxDelay: Milli(1_000) }); // Nothing published yet. expect(subscriber.largest()).toBeUndefined(); @@ -1652,7 +1671,7 @@ test("largest survives a mirror replay of an aborted group", async () => { test("group ranges preserve progress and spell out inclusion", async () => { const producer = new TrackProducer("test"); const track = producer - .subscribe({ maxAge: Milli(5000) }) + .subscribe({ maxDelay: Milli(5000) }) .withGroups({ start: { included: 1 }, end: { included: 1 } }); for (let sequence = 0; sequence < 4; sequence++) producer.writeGroup(new GroupProducer(sequence)); expect(track.tryRecvGroup()?.sequence).toBe(1); @@ -1667,8 +1686,8 @@ test("group ranges preserve progress and spell out inclusion", async () => { test("serving replaceGroups can lower the floor that setGroups keeps", () => { const producer = new TrackProducer("test"); - const kept = producer.subscribe({ maxAge: Milli(5000), groups: { start: { included: 10 } } }); - const lowered = producer.subscribe({ maxAge: Milli(5000), groups: { start: { included: 10 } } }); + const kept = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 10 } } }); + const lowered = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 10 } } }); for (const sequence of [5, 6, 10]) producer.writeGroup(new GroupProducer(sequence)); kept.setGroups({ start: { included: 5 } }); @@ -1683,7 +1702,7 @@ test("serving replaceGroups can lower the floor that setGroups keeps", () => { test("malformed group bounds do not partially advance the cursor", () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(5000) }); + const track = producer.subscribe({ maxDelay: Milli(5000) }); producer.writeGroup(new GroupProducer(0)); expect(() => track.setGroups({ start: { included: 3 }, end: { excluded: -1 } })).toThrow(); expect(track.tryRecvGroup()?.sequence).toBe(0); @@ -1709,7 +1728,7 @@ test("finishAt refuses an end at or below a produced sequence", () => { test("finishAt declares an end ahead of the live edge without ending the track", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ maxAge: Milli(60_000) }); + const track = producer.subscribe({ maxDelay: Milli(60_000) }); producer.writeGroup(new GroupProducer(5)); const first = await track.recvGroup(); expect(first?.sequence).toBe(5); @@ -1740,7 +1759,7 @@ test("finishAt declares an end ahead of the live edge without ending the track", for (const ordered of [false, true]) { test(`a ${ordered ? "sequence" : "arrival"} reader ends at the declared boundary before closure`, async () => { const producer = new TrackProducer("test"); - const subscriber = producer.subscribe({ maxAge: Milli(60_000) }); + const subscriber = producer.subscribe({ maxDelay: Milli(60_000) }); const track = ordered ? subscriber.ordered() : subscriber; const receive = () => ("nextGroup" in track ? track.nextGroup() : track.recvGroup()); try { @@ -1840,13 +1859,13 @@ test("an omitted publisher limit still ages idle groups out", async () => { source.close(); clock.set(10_000 + CACHE_WINDOW_MS - 1_000); producer.appendGroup(); - const within = producer.subscribe({ maxAge: Milli(100_000) }); + const within = producer.subscribe({ maxDelay: Milli(100_000) }); expect(await (await within.recvGroup())?.readString()).toBe("old"); within.close(); // A scan runs at most once per slice of the window, so step past the next one. clock.set(10_000 + CACHE_WINDOW_MS + CACHE_WINDOW_MS / 8); - const after = producer.subscribe({ maxAge: Milli(100_000) }); + const after = producer.subscribe({ maxDelay: Milli(100_000) }); expect(after.tryRecvGroup()?.sequence).toBe(1); expect(after.tryRecvGroup()).toBeUndefined(); after.close(); @@ -1868,7 +1887,7 @@ test("a live track does not pin an aborted newest group", () => { reset.close(new Error("reset")); clock.set(10_000 + CACHE_WINDOW_MS + CACHE_WINDOW_MS / 8); - const late = producer.subscribe({ maxAge: Milli(100_000) }); + const late = producer.subscribe({ maxDelay: Milli(100_000) }); expect(late.tryRecvGroup()).toBeUndefined(); late.close(); } finally { @@ -1881,7 +1900,7 @@ test("closing a track keeps an idle newest group for subscribers to drain", asyn const clock = mockMonotonicTime(10_000); try { const producer = new TrackProducer("catalog").accept(); - const subscriber = producer.subscribe({ maxAge: Milli(100_000) }); + const subscriber = producer.subscribe({ maxDelay: Milli(100_000) }); const snapshot = producer.appendGroup(); snapshot.writeString("snapshot"); snapshot.close(); @@ -1894,7 +1913,7 @@ test("closing a track keeps an idle newest group for subscribers to drain", asyn // The close restarted its window, which now runs out like any other. clock.set(10_000 + 2 * (CACHE_WINDOW_MS + CACHE_WINDOW_MS / 8)); - const late = producer.subscribe({ maxAge: Milli(100_000) }); + const late = producer.subscribe({ maxDelay: Milli(100_000) }); expect(late.tryRecvGroup()).toBeUndefined(); late.close(); } finally { @@ -1942,8 +1961,8 @@ test("a late subscriber to a closed unlimited track is released once the cache a test("an abort keeps finished groups for a slow reader, then reports it", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(10_000) }); - const arrival = producer.subscribe({ maxAge: Milli(10_000) }); - const ordered = producer.subscribe({ maxAge: Milli(10_000) }).ordered(); + const arrival = producer.subscribe({ maxDelay: Milli(10_000) }); + const ordered = producer.subscribe({ maxDelay: Milli(10_000) }).ordered(); for (let i = 0; i < 2; i++) { const group = producer.appendGroup(); group.writeString(`g${i}`); @@ -1966,8 +1985,8 @@ test("an abort keeps finished groups for a slow reader, then reports it", async test("an abort after the declared end settles ends clean", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(10_000) }); - const arrival = producer.subscribe({ maxAge: Milli(10_000) }); - const ordered = producer.subscribe({ maxAge: Milli(10_000) }).ordered(); + const arrival = producer.subscribe({ maxDelay: Milli(10_000) }); + const ordered = producer.subscribe({ maxDelay: Milli(10_000) }).ordered(); for (let i = 0; i < 2; i++) { const group = producer.appendGroup(); group.writeString(`g${i}`); @@ -1996,7 +2015,7 @@ test("an ended track's buffered groups age out for a stale subscriber", () => { const clock = mockCacheTime(10_000); const producer = new TrackProducer("test").accept({ maxAge: Milli(30) }); try { - const stale = producer.subscribe({ maxAge: Milli(30) }); + const stale = producer.subscribe({ maxDelay: Milli(30) }); const group = producer.appendGroup(); group.writeString("x"); group.close(); @@ -2015,8 +2034,8 @@ test("an ended track's buffered groups age out for a stale subscriber", () => { test("an abort leaves a group already taken readable, then reports the abort", async () => { const producer = new TrackProducer("test").accept({ maxAge: Milli(10_000) }); - const arrival = producer.subscribe({ maxAge: Milli(10_000) }); - const ordered = producer.subscribe({ maxAge: Milli(10_000) }).ordered(); + const arrival = producer.subscribe({ maxDelay: Milli(10_000) }); + const ordered = producer.subscribe({ maxDelay: Milli(10_000) }).ordered(); producer.appendGroup().writeString("held"); const held = [await arrival.recvGroup(), await ordered.nextGroup()]; const boom = new Error("boom"); diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 1ad168ad060..54c42587b90 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -21,7 +21,7 @@ import { type Broadcast as BroadcastWire, registerTrackConsumer } from "./wire.t export type { Datagram } from "./datagram.ts"; // Wall-clock bound for idle cached content, matching Rust cache::DEFAULT_EXPIRY. -// Media maxAge only bounds how far behind the live edge a reader may fall. +// Media maxDelay only bounds how far behind the live edge a reader may fall. const CACHE_WINDOW_MS = 30_000; // The cache scans at most this many times per idle cache window. @@ -77,19 +77,19 @@ export interface Info { priority: number; } -// Normalize a latency budget for the wire, which carries it as an unsigned varint. +// Normalize a duration for the wire, which carries it as an unsigned varint. // // Callers derive it from measurements (a jitter estimate scaled off RTT), so a fractional // millisecond is expected; ceil rather than round, because a budget shortened by rounding // skips a group the subscriber still wants. Anything that is not a duration is refused // here, where the field is named, rather than deep in the encoder. -function maxAgeMillis(value: Milli): Milli { +function wireMillis(field: string, value: Milli): Milli { if (!Number.isFinite(value) || value < 0) { - throw new RangeError(`maxAge must be a non-negative number of milliseconds: ${value}`); + throw new RangeError(`${field} must be a non-negative number of milliseconds: ${value}`); } const millis = Math.ceil(value); if (!Number.isSafeInteger(millis)) { - throw new RangeError(`maxAge exceeds the safe integer millisecond range: ${value}`); + throw new RangeError(`${field} exceeds the safe integer millisecond range: ${value}`); } return Milli(millis); } @@ -105,7 +105,7 @@ function priorityByte(value: number): number { export function infoDefaults(info: Partial = {}): Info { return { timescale: Timescale(info.timescale ?? Timescale.MILLI), - maxAge: info.maxAge === undefined ? undefined : maxAgeMillis(info.maxAge), + maxAge: info.maxAge === undefined ? undefined : wireMillis("maxAge", info.maxAge), priority: priorityByte(info.priority ?? DEFAULT_PRIORITY), }; } @@ -124,21 +124,23 @@ export interface Groups { /** * Per-subscription options, requested when a subscription opens and adjustable later via * {@link Subscriber.update}. Mirrors the Rust `Subscription`. + * The obsolete subscriber `maxAge` field is refused at runtime; use `maxDelay`. */ export interface Subscription { /** Delivery priority relative to this session's other subscriptions (`0..=255`). Defaults to `0`. */ priority?: number; /** - * Maximum age (milliseconds) of a non-latest group before it is skipped. Defaults to `0`. + * How far (milliseconds) a non-latest group may fall behind the live edge before it is + * skipped. Defaults to `0`. * Rounded up to a whole millisecond, so a value derived from a measurement is never * shortened. A negative or non-finite value, or one past `Number.MAX_SAFE_INTEGER` * after rounding, is refused. */ - maxAge?: Milli; + maxDelay?: Milli; /** * The lowest group the publisher may deliver (a floor), or omit for none. * - * A floor, not a request: only {@link maxAge} asks for data, and the floor bounds how + * A floor, not a request: only {@link maxDelay} asks for data, and the floor bounds how * far back it may reach. Omitting it and a floor of 0 mean the same thing, and a floor * above the live edge simply waits there (a resumed subscription naming where it left * off). @@ -149,10 +151,11 @@ export interface Subscription { // Materialize the defaults at the model boundary so every layer observes a complete // subscription rather than interpreting an omitted field differently. function subscriptionDefaults(subscription: Subscription = {}): Subscription { + if ("maxAge" in subscription) throw new TypeError("Subscriber maxAge is unsupported; use maxDelay"); const bounds = groupBounds(subscription.groups ?? {}); return { priority: priorityByte(subscription.priority ?? 0), - maxAge: maxAgeMillis(subscription.maxAge ?? Milli.zero), + maxDelay: wireMillis("maxDelay", subscription.maxDelay ?? Milli.zero), groups: { start: subscription.groups?.start === undefined ? undefined : { included: bounds.start }, end: bounds.end === undefined ? undefined : { excluded: bounds.end }, @@ -172,7 +175,7 @@ function combineSubscriptions(states: Iterable): Subscription | unde } combined.priority = Math.max(combined.priority ?? 0, subscription.priority ?? 0); - combined.maxAge = Milli(Math.max(combined.maxAge ?? Milli.zero, subscription.maxAge ?? Milli.zero)); + combined.maxDelay = Milli(Math.max(combined.maxDelay ?? Milli.zero, subscription.maxDelay ?? Milli.zero)); // A floor only restricts, so a subscriber without one clears the aggregate: // its budget may reach below any floor the others set. @@ -285,7 +288,7 @@ export class Consumer { * Open a live subscription to the track. * * The cursor starts at the group the subscription named (its floor), or 0. - * {@link Subscription.maxAge} is what asks for data: delivery skips everything above + * {@link Subscription.maxDelay} is what asks for data: delivery skips everything above * the floor that the budget convicts, so the default budget of zero delivers only the * latest group and a larger one reaches back over what it can still use. */ @@ -585,7 +588,7 @@ export class Producer { * An independent {@link Subscriber} reading this track's groups. * * Its cursor starts at the group the subscription named (its floor), or 0. - * {@link Subscription.maxAge} is what asks for data: delivery skips everything above + * {@link Subscription.maxDelay} is what asks for data: delivery skips everything above * the floor that the budget convicts, so the default budget of zero delivers only the * latest group and a larger one reaches back over what it can still use. */ @@ -664,7 +667,8 @@ export class Producer { #updateSubscription(): void { const combined = combineSubscriptions(this.#sinks); const retained = this.#state.info.peek()?.maxAge; - if (combined && retained !== undefined) combined.maxAge = Milli.min(combined.maxAge ?? Milli.zero, retained); + if (combined && retained !== undefined) + combined.maxDelay = Milli.min(combined.maxDelay ?? Milli.zero, retained); this.#state.update.set(combined); } @@ -1050,7 +1054,7 @@ export class Subscriber { break; } - const requested = this.#state.update.peek()?.maxAge ?? 0; + const requested = this.#state.update.peek()?.maxDelay ?? 0; const retained = this.#state.info.peek()?.maxAge; return { budget: this.#enforceLatency @@ -1137,7 +1141,7 @@ export class Subscriber { this.name = name; this.#state = state; // The cursor's floor is the group the subscription named, or 0. A floor is the - // only thing a start contributes; {@link Subscription.maxAge} is what asks for + // only thing a start contributes; {@link Subscription.maxDelay} is what asks for // data, and delivery skips everything above the floor that the budget convicts. this.#cursor.set({ start: groupBounds(state.update.peek()?.groups ?? {}).start }); } @@ -1320,7 +1324,7 @@ export class Subscriber { * beyond the cap stays buffered (not dropped) and is offered once the cap rises, even * after a clean close, without blocking in-range groups that arrive behind it. * A group whose presentation time is further behind the live edge than this - * subscriber's `maxAge` is skipped. The default of zero takes the live edge. + * subscriber's `maxDelay` is skipped. The default of zero takes the live edge. * The budget remains attached after return, so a pending frame read rejects if a stalled * group becomes stale while newer data advances. * @@ -1510,7 +1514,7 @@ export class Subscriber { * * Groups are acquired through the same sequence cursor as {@link Ordered.nextGroup}, * so frames never run backwards: a late lower-sequence group is skipped, and so is - * one every frame of which `maxAge` proves is too old. A group the budget abandons + * one every frame of which `maxDelay` proves is too old. A group the budget abandons * mid-stall ends cleanly and the cursor resyncs from the next group; a gap inside a * group still surfaces as {@link TooFarBehind} or {@link GroupTooLarge}. */ @@ -1609,7 +1613,7 @@ export class Subscriber { * Every group this returns has a higher sequence than the last, so a late arrival is * skipped rather than delivered out of turn. * - * `maxAge` applies as this cursor reads, exactly as it does on the arrival cursor: a + * `maxDelay` applies as this cursor reads, exactly as it does on the arrival cursor: a * group is skipped once its reach, where its immediate successor begins, is that far * behind the newest frame on the track. Nothing weaker convicts it, since the reach is * the only proof that every frame it could still hold is past the budget, so a backlog @@ -1687,7 +1691,7 @@ export class Ordered { * Return the next group with a strictly-greater sequence number than the last returned. * * Late arrivals (sequence at or below the last returned) are silently skipped, as is a - * group whose every frame is further behind the live edge than `maxAge` (the default of + * group whose every frame is further behind the live edge than `maxDelay` (the default of * zero keeps only what nothing newer has superseded). Honors the bounds set by * {@link setGroups}. */ @@ -1699,7 +1703,7 @@ export class Ordered { * Read the next frame across groups, in sequence order, with its group and frame numbers. * * Rides the same cursor as {@link nextGroup} and shares this handle's contract: a - * buffered backlog is drained in full up to the point `maxAge` proves it useless. + * buffered backlog is drained in full up to the point `maxDelay` proves it useless. * Treat the returned frame bytes as read-only; they are shared with other consumers. */ readFrame(): Promise<({ group: number; frame: number } & Frame) | undefined> { diff --git a/js/publish/bench/catalog.ts b/js/publish/bench/catalog.ts index 3c488561d4d..616719f9a59 100644 --- a/js/publish/bench/catalog.ts +++ b/js/publish/bench/catalog.ts @@ -60,7 +60,7 @@ async function measure(tracks: number, viewers: number) { for (let index = 0; index < media.length; index++) { // Model the player's changed latency floor with real subscription handles. viewer.media[index].update({ - maxAge: Time.Milli(root?.video?.renditions[media[index].name].jitter ?? 0), + maxDelay: Time.Milli(root?.video?.renditions[media[index].name].jitter ?? 0), }); updates++; } diff --git a/js/watch/src/audio/decoder.test.ts b/js/watch/src/audio/decoder.test.ts index a3858d2f051..4c0f2b5247b 100644 --- a/js/watch/src/audio/decoder.test.ts +++ b/js/watch/src/audio/decoder.test.ts @@ -191,7 +191,9 @@ async function play(initial: Delay) { numberOfChannels: 2, }); const catalog = new Signal({ audio: { renditions: { audio } } }); + const enabled = new Signal(true); const broadcast = new Signal({ + in: { enabled }, out: { catalog }, relativeBroadcast, } as unknown as Broadcast); @@ -216,6 +218,8 @@ async function play(initial: Delay) { return { delay, + enabled, + context: decoder.out.context, play, // Remove the rendition from the catalog, then restore it. remove: () => catalog.set({}), @@ -247,6 +251,29 @@ async function play(initial: Delay) { }; } +describe("Decoder across a broadcast disable", () => { + it("releases the graph when its broadcast is disabled and rebuilds on return", async () => { + const playback = await play(Time.Milli(100)); + try { + await playback.play(); + const [context] = contexts; + + playback.enabled.set(false); + await microtasks(); + expect(context.calls.close).toBe(1); + expect(playback.context.peek()).toBeUndefined(); + + playback.enabled.set(true); + await microtasks(); + expect(contexts).toHaveLength(2); + expect(contexts[1].state).toBe("running"); + expect(playback.context.peek()).toBe(contexts[1] as unknown as AudioContext); + } finally { + playback.close(); + } + }); +}); + describe("Decoder across a delay change", () => { for (const initial of [Time.Milli(100), "auto"] as const) { it(`keeps the subscription and ring when ${initial} becomes a number`, async () => { diff --git a/js/watch/src/audio/decoder.ts b/js/watch/src/audio/decoder.ts index cfcf4553653..e5aa18b8c47 100644 --- a/js/watch/src/audio/decoder.ts +++ b/js/watch/src/audio/decoder.ts @@ -21,7 +21,7 @@ import type { Sync } from "../sync"; import { type AudioBuffer, createAudioBuffer } from "./buffer"; import { type DecoderConfig, frameDuration, type PlaybackIdentity, packetDuration, playbackIdentity } from "./config"; import { Handover } from "./handover"; -import { AUTO_MAX_AGE, ringSamples, target } from "./latency"; +import { AUTO_MAX_DELAY, ringSamples, target } from "./latency"; // A blob: URL, or a hosted file when assets() is set; see vite-plugin-worklet. import RenderWorklet from "./render-worklet.ts?worklet"; import type { Source } from "./source"; @@ -122,8 +122,8 @@ export class Decoder { // The container consumer's arrival estimate, unset while nothing is subscribed. #measured = new Signal(undefined); - // The subscription's max age: the shared budget, raised to the estimator's ceiling in "auto". - #subscribeMaxAge = new Signal(Time.Milli.zero); + // The subscription's max delay: the shared budget, raised to the estimator's ceiling in "auto". + #subscribeMaxDelay = new Signal(Time.Milli.zero); // The codec's frame duration: the catalog constant, refined by each frame's own duration. #frame = new Signal(undefined); @@ -167,7 +167,7 @@ export class Decoder { (effect) => effect.get(this.source.out.config) === undefined && effect.get(this.#out.stalled), ); - this.#signals.run(this.#runSubscribeMaxAge.bind(this)); + this.#signals.run(this.#runSubscribeMaxDelay.bind(this)); this.#signals.run(this.#runShape.bind(this)); this.#signals.run(this.#runWorklet.bind(this)); this.#signals.run(this.#runEnabled.bind(this)); @@ -178,10 +178,10 @@ export class Decoder { // A group the relay expires is never observed, so a subscription cut to the target would cap the // estimate at the target it already holds. The container consumer keeps the shared budget as its // local skip, since it observes each frame before applying it. See doc/concept/audio-jitter.md. - #runSubscribeMaxAge(effect: Effect): void { - const maxAge = effect.get(this.sync.out.maxAge); + #runSubscribeMaxDelay(effect: Effect): void { + const maxDelay = effect.get(this.sync.out.maxDelay); const auto = effect.get(this.sync.in.delay) === "auto"; - this.#subscribeMaxAge.set(auto ? Time.Milli.max(maxAge, AUTO_MAX_AGE) : maxAge); + this.#subscribeMaxDelay.set(auto ? Time.Milli.max(maxDelay, AUTO_MAX_DELAY) : maxDelay); } #runShape(effect: Effect): void { @@ -207,6 +207,9 @@ export class Decoder { // This is less efficient for video-only playback but makes muting/unmuting instant. const shape = effect.get(this.#shape); if (!shape) return; + // Rendition absence keeps the graph warm, but a disabled broadcast releases its resources. + const broadcast = effect.get(this.source.in.broadcast); + if (!broadcast || !effect.get(broadcast.in.enabled)) return; const { sampleRate, channels: channelCount } = shape; @@ -352,7 +355,7 @@ export class Decoder { broadcast: active, track, priority: Catalog.PRIORITY.audio, - maxAge: this.#subscribeMaxAge, + maxDelay: this.#subscribeMaxDelay, }); if (!sub) return; @@ -373,7 +376,7 @@ export class Decoder { // TODO include JITTER_UNDERHEAD const consumer = new Container.Consumer(sub, { format, - maxAge: this.sync.out.maxAge, + maxDelay: this.sync.out.maxDelay, }); effect.cleanup(() => consumer.close()); @@ -491,7 +494,7 @@ export class Decoder { const consumer = new Container.Consumer(sub, { format: new Container.Cmaf.Format(init), - maxAge: this.sync.out.maxAge, + maxDelay: this.sync.out.maxDelay, }); effect.cleanup(() => consumer.close()); diff --git a/js/watch/src/audio/latency.ts b/js/watch/src/audio/latency.ts index 1284f940882..562b47293ee 100644 --- a/js/watch/src/audio/latency.ts +++ b/js/watch/src/audio/latency.ts @@ -28,11 +28,11 @@ export function target(props: Target): Time.Milli { } /** - * The least subscription max age an "auto" track asks for: the estimator's ceiling. + * The least subscription max delay an "auto" track asks for: the estimator's ceiling. * * The measured term saturates at 100 buckets of 20 ms, so a frame later than this adds nothing. */ -export const AUTO_MAX_AGE = 2000 as Time.Milli; +export const AUTO_MAX_DELAY = 2000 as Time.Milli; // An AudioWorkletProcessor renders in fixed 128-sample quanta, so a ring shallower than one can // never be read from. diff --git a/js/watch/src/audio/playout.test.ts b/js/watch/src/audio/playout.test.ts index 4722bcbb5ac..362681f2186 100644 --- a/js/watch/src/audio/playout.test.ts +++ b/js/watch/src/audio/playout.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, spyOn } from "bun:test"; import * as Container from "@moq/hang/container"; import { Group, Time, Track, Varint } from "@moq/net"; -import { AUTO_MAX_AGE, target } from "./latency"; +import { AUTO_MAX_DELAY, target } from "./latency"; import { AudioRingBuffer } from "./ring-buffer"; import { allocSharedRingBuffer, SharedRingBuffer } from "./shared-ring-buffer"; @@ -72,16 +72,16 @@ interface Measured { /** * Feed `t` through the path the decoder measures on: a transport subscription into a container * consumer, on a stubbed monotonic clock, one group per frame. After each arrival `budget` turns the - * current target into the subscription's max age, the way the decoder does. + * current target into the subscription's max delay, the way the decoder does. */ async function measure(t: Arrival[], budget: (target: Time.Milli) => Time.Milli): Promise { let clock = 0; const now = spyOn(performance, "now").mockImplementation(() => clock); const track = new Track.Producer("audio"); - const subscriber = track.subscribe({ maxAge: budget(Time.Milli.zero) }); + const subscriber = track.subscribe({ maxDelay: budget(Time.Milli.zero) }); const consumer = new Container.Consumer(subscriber, { format: new Container.Legacy.Format("audio"), - maxAge: AUTO_MAX_AGE, + maxDelay: AUTO_MAX_DELAY, }); const result: Measured = { targets: [], delivered: 0 }; @@ -110,7 +110,7 @@ async function measure(t: Arrival[], budget: (target: Time.Milli) => Time.Milli) const current = target({ measured: consumer.spread.peek(), frame: CHUNK_MS as Time.Milli }); result.targets.push(current); - subscriber.update({ maxAge: budget(current) }); + subscriber.update({ maxDelay: budget(current) }); } } finally { track.close(); @@ -124,7 +124,7 @@ async function measure(t: Arrival[], budget: (target: Time.Milli) => Time.Milli) /** The target the estimator settles on by the end of `t`, given the subscription "auto" asks for. */ async function settled(t: Arrival[]): Promise { - const { targets } = await measure(t, (target) => Time.Milli.max(target, AUTO_MAX_AGE)); + const { targets } = await measure(t, (target) => Time.Milli.max(target, AUTO_MAX_DELAY)); return targets[targets.length - 1]; } @@ -254,7 +254,7 @@ describe("subscription budget", () => { } it("reaches a flush that starts after the target settled", async () => { - const { targets, delivered } = await measure(t, (target) => Time.Milli.max(target, AUTO_MAX_AGE)); + const { targets, delivered } = await measure(t, (target) => Time.Milli.max(target, AUTO_MAX_DELAY)); expect(targets[PACED - 1]).toBe((2 * CHUNK_MS) as Time.Milli); expect(delivered).toBe(t.length); // Every flush lands whole, so its 100ms reaches the 95th percentile within a few intervals. @@ -262,7 +262,7 @@ describe("subscription budget", () => { }); it("drops the flush it should measure when the budget follows the target", async () => { - // The transport skips a group older than the subscription's max age, before the consumer + // The transport skips a group older than the subscription's max delay, before the consumer // can observe it, so the estimate only ever sees what the target it already holds allows. const { targets, delivered } = await measure(t, (target) => target); expect(delivered).toBeLessThan(t.length); diff --git a/js/watch/src/audio/replay.test.ts b/js/watch/src/audio/replay.test.ts index bd98dfe8f29..e40ac71be16 100644 --- a/js/watch/src/audio/replay.test.ts +++ b/js/watch/src/audio/replay.test.ts @@ -63,7 +63,7 @@ describe.each(["shared", "post"] as const)("%s ring", (ring) => { ).toBe(0); }); - it("holds newer groups behind a missing one until the max age gives up on it", async () => { + it("holds newer groups behind a missing one until the max delay gives up on it", async () => { const trace = paced(10, () => 30).filter((arrival) => arrival.group !== 250); // The consumer delivers in group order, so the ring runs dry for longer than the missing frame // while the groups behind it wait. Writing arrivals straight into the ring plays straight through. diff --git a/js/watch/src/audio/replay.ts b/js/watch/src/audio/replay.ts index a184938d2c6..3c18faf97ba 100644 --- a/js/watch/src/audio/replay.ts +++ b/js/watch/src/audio/replay.ts @@ -2,7 +2,7 @@ * Replay a recorded arrival trace through the player's consumer and rings on a simulated clock. * * Every frame is written into its group at the instant the trace says it arrived, and the player's - * real `Container.Consumer` decides what to deliver, wait for, and skip, at the max age the delay + * real `Container.Consumer` decides what to deliver, wait for, and skip, at the max delay the delay * sets. Delivered frames go into the real ring, and a discontinuity resets it, the way the decoder * does. One render quantum is read every quantum's worth of that same clock, which is what the * AudioWorklet does. A real {@link Sync} resolves the delay from the playout target the decoder @@ -31,9 +31,9 @@ export const QUANTUM = 128; /** * The replay's own subscription passes every recorded group through: the recorder's relay already - * applied a wire max age, so only the consumer's decisions are made again. + * applied a wire max delay, so only the consumer's decisions are made again. */ -const WIRE_MAX_AGE = Time.Milli(Number.MAX_SAFE_INTEGER); +const WIRE_MAX_DELAY = Time.Milli(Number.MAX_SAFE_INTEGER); /** Any non-empty payload: an empty one is the legacy container's end marker. */ const PAYLOAD = new Uint8Array(1); @@ -190,9 +190,9 @@ export async function* replay(trace: Arrival[], options: Options): AsyncGenerato const sync = new Sync({ delay: options.delay }); const track = new Track.Producer("audio"); - const consumer = new Container.Consumer(track.subscribe({ maxAge: WIRE_MAX_AGE }), { + const consumer = new Container.Consumer(track.subscribe({ maxDelay: WIRE_MAX_DELAY }), { format: new Container.Legacy.Format("audio"), - maxAge: sync.out.maxAge, + maxDelay: sync.out.maxDelay, }); // The decoder's "auto" target. A recorded frame has no payload to read an Opus duration from, diff --git a/js/watch/src/media.test.ts b/js/watch/src/media.test.ts index 5f0f00ef09f..1daf88c3502 100644 --- a/js/watch/src/media.test.ts +++ b/js/watch/src/media.test.ts @@ -7,7 +7,7 @@ import { nextMedia, subscribeMedia } from "./media"; const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); -test("media max age is present on the initial subscription and later updates", async () => { +test("media max delay is present on the initial subscription and later updates", async () => { let initial: Moq.Track.Subscription | undefined; const updates: Moq.Track.Subscription[] = []; const subscriber = { @@ -23,20 +23,20 @@ test("media max age is present on the initial subscription and later updates", a }, }), } as unknown as Moq.Broadcast.Consumer; - const maxAge = new Signal(Time.Milli(250)); + const maxDelay = new Signal(Time.Milli(250)); const effect = new Effect(); subscribeMedia(effect, { broadcast, track: "media", priority: 7, - maxAge, + maxDelay, }); - expect(initial).toEqual({ priority: 7, maxAge: Time.Milli(250) }); + expect(initial).toEqual({ priority: 7, maxDelay: Time.Milli(250) }); - maxAge.set(Time.Milli(500)); + maxDelay.set(Time.Milli(500)); await flush(); - expect(updates.at(-1)).toEqual({ priority: 7, maxAge: Time.Milli(500) }); + expect(updates.at(-1)).toEqual({ priority: 7, maxDelay: Time.Milli(500) }); effect.close(); }); @@ -73,7 +73,7 @@ test("media does not subscribe through a closed broadcast handle", () => { broadcast: handle, track: "video", priority: 0, - maxAge: new Signal(Time.Milli(0)), + maxDelay: new Signal(Time.Milli(0)), }), ).toBeUndefined(); } finally { diff --git a/js/watch/src/media.ts b/js/watch/src/media.ts index baa0224bd98..5adde431bcc 100644 --- a/js/watch/src/media.ts +++ b/js/watch/src/media.ts @@ -4,7 +4,7 @@ import { Error as NetError, type Time } from "@moq/net"; import type { Effect, Getter } from "@moq/signals"; /** - * Open a media subscription with its max age on the initial request and every update. + * Open a media subscription with its max delay on the initial request and every update. * * @internal */ @@ -14,16 +14,16 @@ export function subscribeMedia( broadcast: Moq.Broadcast.Consumer; track: string; priority: number; - maxAge: Getter; + maxDelay: Getter; }, ): Moq.Track.Subscriber | undefined { if (effect.get(props.broadcast.closed) !== undefined) return; - const subscription = () => ({ priority: props.priority, maxAge: props.maxAge.peek() }); + const subscription = () => ({ priority: props.priority, maxDelay: props.maxDelay.peek() }); const subscriber = props.broadcast.track(props.track).subscribe(subscription()); effect.cleanup(() => subscriber.close()); effect.run((inner) => { - subscriber.update({ priority: props.priority, maxAge: inner.get(props.maxAge) }); + subscriber.update({ priority: props.priority, maxDelay: inner.get(props.maxDelay) }); }); return subscriber; diff --git a/js/watch/src/retention.test.ts b/js/watch/src/retention.test.ts index 3afeee39ea6..e7de4e13ab5 100644 --- a/js/watch/src/retention.test.ts +++ b/js/watch/src/retention.test.ts @@ -90,10 +90,10 @@ test("a long subscription through the player path leaves nothing behind", async broadcast: broadcast.consume(), track: "audio", priority: 0, - maxAge: sync.out.maxAge, + maxDelay: sync.out.maxDelay, }); if (!sub) throw new Error("no subscription"); - const consumer = new Container.Consumer(sub, { format, maxAge: sync.out.maxAge }); + const consumer = new Container.Consumer(sub, { format, maxDelay: sync.out.maxDelay }); // Presentations overlap, as a decoder's outputs do, so the clock's sleeps are shared. const presenting = new Set>(); diff --git a/js/watch/src/sync.test.ts b/js/watch/src/sync.test.ts index 0f29d2b899e..d0bef3018d8 100644 --- a/js/watch/src/sync.test.ts +++ b/js/watch/src/sync.test.ts @@ -14,12 +14,12 @@ describe("delay and buffer", () => { sync.close(); }); - it("caps maxAge at the delay when no buffer is configured", async () => { + it("caps maxDelay at the delay when no buffer is configured", async () => { const sync = new Sync({ delay: 100 as Time.Milli }); await flush(); expect(sync.out.buffered.peek()).toBe(false); expect(sync.out.delay.peek()).toBe(100 as Time.Milli); - expect(sync.out.maxAge.peek()).toBe(100 as Time.Milli); + expect(sync.out.maxDelay.peek()).toBe(100 as Time.Milli); sync.close(); }); @@ -29,7 +29,7 @@ describe("delay and buffer", () => { const sync = new Sync({ delay: 100 as Time.Milli, buffer: 30_000 as Time.Milli }); await flush(); expect(sync.out.buffered.peek()).toBe(true); - expect(sync.out.maxAge.peek()).toBe(30_100 as Time.Milli); + expect(sync.out.maxDelay.peek()).toBe(30_100 as Time.Milli); sync.close(); }); @@ -37,7 +37,7 @@ describe("delay and buffer", () => { const sync = new Sync({ delay: 200 as Time.Milli, buffer: 0 as Time.Milli }); await flush(); expect(sync.out.buffered.peek()).toBe(false); - expect(sync.out.maxAge.peek()).toBe(200 as Time.Milli); + expect(sync.out.maxDelay.peek()).toBe(200 as Time.Milli); sync.close(); }); @@ -50,7 +50,7 @@ describe("delay and buffer", () => { buffer.set(30_000 as Time.Milli); await flush(); expect(sync.out.buffered.peek()).toBe(true); - expect(sync.out.maxAge.peek()).toBe(30_100 as Time.Milli); + expect(sync.out.maxDelay.peek()).toBe(30_100 as Time.Milli); sync.close(); }); @@ -60,7 +60,7 @@ describe("delay and buffer", () => { expect(sync.out.instant.peek()).toBe(true); expect(sync.out.buffered.peek()).toBe(false); expect(sync.out.delay.peek()).toBe(0 as Time.Milli); - expect(sync.out.maxAge.peek()).toBe(0 as Time.Milli); + expect(sync.out.maxDelay.peek()).toBe(0 as Time.Milli); sync.close(); }); }); diff --git a/js/watch/src/sync.ts b/js/watch/src/sync.ts index 9f3990f7766..048572cf574 100644 --- a/js/watch/src/sync.ts +++ b/js/watch/src/sync.ts @@ -64,12 +64,12 @@ type SyncOutput = { // Derived: true when a lookahead is configured. Buffered playback lets the reference stay // anchored so future-dated frames build up, re-anchoring (skipping ahead) only once they - // would sit further than `maxAge` ahead of the playhead. See `reset()`. + // would sit further than `maxDelay` ahead of the playhead. See `reset()`. buffered: Signal; // Derived: `delay + buffer`, the furthest a held frame may sit ahead of the playhead. Feeds the // transport subscription and the container consumer, which bound the same span. Always finite. - maxAge: Signal; + maxDelay: Signal; }; export class Sync { @@ -82,7 +82,7 @@ export class Sync { jitter: new Signal(Time.Milli.zero), timestamp: new Signal(undefined), buffered: new Signal(false), - maxAge: new Signal(Time.Milli.zero), + maxDelay: new Signal(Time.Milli.zero), }; readonly out = readonlys(this.#out); @@ -102,7 +102,7 @@ export class Sync { this.#signals.run(this.#runInstant.bind(this)); this.#signals.run(this.#runDelay.bind(this)); - this.#signals.run(this.#runMaxAge.bind(this)); + this.#signals.run(this.#runMaxDelay.bind(this)); } /** Hold a decoder's "auto" playout target in the shared playback clock until disposed. */ @@ -116,14 +116,14 @@ export class Sync { this.#out.instant.set(effect.get(this.in.delay) === "instant"); } - // Derive `buffered` / `maxAge` from the resolved delay and the configured lookahead. - #runMaxAge(effect: Effect): void { + // Derive `buffered` / `maxDelay` from the resolved delay and the configured lookahead. + #runMaxDelay(effect: Effect): void { const delay = effect.get(this.#out.delay); // "instant" holds nothing, so a configured lookahead doesn't apply. const buffer = effect.get(this.#out.instant) ? Time.Milli.zero : effect.get(this.in.buffer); this.#out.buffered.set(buffer > 0); - this.#out.maxAge.set(Time.Milli.add(delay, buffer)); + this.#out.maxDelay.set(Time.Milli.add(delay, buffer)); } // A fixed delay is taken literally and "auto" holds the deepest track's target, so every track @@ -145,7 +145,7 @@ export class Sync { } // Fold a newly received frame into the reference. The reference anchors playback to the - // wall clock; we lower it (skip ahead) only when keeping it would push the lookahead past `maxAge`. + // wall clock; we lower it (skip ahead) only when keeping it would push the lookahead past `maxDelay`. received(timestamp: Time.Milli, label = ""): void { this.#out.timestamp.update((current) => (current === undefined || timestamp > current ? timestamp : current)); const now = Time.Milli.now(); @@ -186,7 +186,7 @@ export class Sync { // Frame is earlier (more lookahead). `sleep` is how far ahead of the playhead keeping the // anchor would put it. - const cap = this.#out.maxAge.peek(); + const cap = this.#out.maxDelay.peek(); if (sleep <= cap) return; // within budget: let the buffer grow instead of skipping ahead // Over the cap: re-anchor down so the resulting lookahead is exactly the cap. diff --git a/js/watch/src/text/renderer.ts b/js/watch/src/text/renderer.ts index bd7253c943b..5e0d8405ee7 100644 --- a/js/watch/src/text/renderer.ts +++ b/js/watch/src/text/renderer.ts @@ -258,7 +258,7 @@ export class Renderer { broadcast: active, track, priority: Catalog.PRIORITY.text, - maxAge: this.sync.out.maxAge, + maxDelay: this.sync.out.maxDelay, }); if (!sub) return; const store: CueStore = { cues: [], regions: new Map(), clears: [] }; diff --git a/js/watch/src/video/decoder.ts b/js/watch/src/video/decoder.ts index 56134653c22..65b6b9a48ac 100644 --- a/js/watch/src/video/decoder.ts +++ b/js/watch/src/video/decoder.ts @@ -348,7 +348,7 @@ class DecoderTrack { broadcast: this.broadcast, track: this.track, priority: Catalog.PRIORITY.video, - maxAge: this.sync.out.maxAge, + maxDelay: this.sync.out.maxDelay, }); if (!sub) return; @@ -426,7 +426,7 @@ class DecoderTrack { // Create consumer that reorders groups/frames up to the provided latency. const consumer = new Container.Consumer(sub, { format, - maxAge: this.sync.out.maxAge, + maxDelay: this.sync.out.maxDelay, }); effect.cleanup(() => consumer.close()); @@ -511,7 +511,7 @@ class DecoderTrack { const consumer = new Container.Consumer(sub, { format: new Container.Cmaf.Format(init), - maxAge: this.sync.out.maxAge, + maxDelay: this.sync.out.maxDelay, }); effect.cleanup(() => consumer.close()); diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt index 6631d166e10..23f2f0b47e9 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Durations.kt @@ -26,20 +26,20 @@ val Backoff.timeout: Duration get() = timeoutUs.toLong().microseconds /** Upper bound on buffering before a stalled group is skipped. */ -val Subscription.maxAge: Duration - get() = maxAgeUs.toLong().microseconds +val Subscription.maxDelay: Duration + get() = maxDelayUs.toLong().microseconds /** Maximum age of a non-latest group before the publisher evicts it, or null for the default. */ val TrackInfo.maxAge: Duration? get() = maxAgeUs?.toLong()?.microseconds /** Upper bound on buffering before a stalled group is skipped, or null for the default. */ -val AudioDecoderOutput.maxAge: Duration? - get() = maxAgeUs?.toLong()?.microseconds +val AudioDecoderOutput.maxDelay: Duration? + get() = maxDelayUs?.toLong()?.microseconds /** Upper bound on buffering before a stalled group is skipped, or null for the default. */ -val VideoDecoderOutput.maxAge: Duration? - get() = maxAgeUs?.toLong()?.microseconds +val VideoDecoderOutput.maxDelay: Duration? + get() = maxDelayUs?.toLong()?.microseconds /** Encoded frame duration. */ val AudioEncoderOutput.frameDuration: Duration diff --git a/py/moq-rs/moq/subscribe.py b/py/moq-rs/moq/subscribe.py index 477479337d5..9470cd526af 100644 --- a/py/moq-rs/moq/subscribe.py +++ b/py/moq-rs/moq/subscribe.py @@ -472,8 +472,8 @@ async def subscribe_media( bitstream, or a :class:`Container` directly. Pass a bare container for the dynamic flow, where you subscribe before the catalog exists. ``subscription`` tunes delivery priority, group - range, and the max age; omit for defaults. Raise - :attr:`Subscription.max_age_us` to buffer instead of skipping a + range, and the max delay; omit for defaults. Raise + :attr:`Subscription.max_delay_us` to buffer instead of skipping a stalled group. """ container = track if isinstance(track, Container) else track.container @@ -509,7 +509,7 @@ async def decode_audio( ``await broadcast.catalog()`` followed by ``catalog.audio[name]``). Only Opus and AAC-LC tracks are supported; AAC is decode only, since nothing here encodes it. - Use ``output.max_age_us`` to + Use ``output.max_delay_us`` to control how aggressively stalled groups get skipped. That's the congestion-control knob. (Named ``_max`` to leave room for a future ``min_buffer_us`` jitter-buffer floor, which is a diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index f45efd98814..ac7ed9a3bb4 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -746,7 +746,7 @@ async def test_raw_multiple_frames(): async for announcement in routes(consumer.announced()): broadcast_consumer = await consumer.request_broadcast(announcement.prefix) - raw_consumer = await broadcast_consumer.subscribe_track("commands", moq.Subscription(max_age_us=1_000_000)) + raw_consumer = await broadcast_consumer.subscribe_track("commands", moq.Subscription(max_delay_us=1_000_000)) messages = [ b'{"cmd": "led", "arm": "left", "led": "THUMB", "state": 1}', @@ -771,7 +771,7 @@ async def test_raw_producer_consume_direct(): """Consume a raw track directly from the producer, no origin/broadcast plumbing.""" broadcast = moq.BroadcastProducer() track = broadcast.publish_track("direct") - consumer = track.consume(moq.Subscription(max_age_us=1_000_000)) + consumer = track.consume(moq.Subscription(max_delay_us=1_000_000)) track.write_frame(b"hello", 0) track.write_frame(b"world", 0) @@ -828,7 +828,7 @@ async def test_raw_group_sequence(): async for announcement in routes(consumer.announced()): broadcast_consumer = await consumer.request_broadcast(announcement.prefix) - raw_consumer = await broadcast_consumer.subscribe_track("seq", moq.Subscription(max_age_us=1_000_000)) + raw_consumer = await broadcast_consumer.subscribe_track("seq", moq.Subscription(max_delay_us=1_000_000)) sent_sequences = [] for i in range(3): @@ -859,7 +859,7 @@ async def test_default_iteration_is_sequence_order(): broadcast = create_announced(origin, "track/ordering") raw = broadcast.publish_track("ordering") - subscription = moq.Subscription(max_age_us=1_000_000) + subscription = moq.Subscription(max_delay_us=1_000_000) seq_consumer = raw.consume(subscription) arr_consumer = raw.consume(subscription) @@ -915,7 +915,7 @@ async def test_read_frame_one_per_group(): """read_frame() returns the first frame of each successive group.""" broadcast = moq.BroadcastProducer() track = broadcast.publish_track("status") - consumer = track.consume(moq.Subscription(max_age_us=1_000_000)) + consumer = track.consume(moq.Subscription(max_delay_us=1_000_000)) track.write_frame(b"ready", 0) track.write_frame(b"running", 0) @@ -959,7 +959,7 @@ async def test_read_frame_skips_remaining_frames_in_group(): """read_frame() only returns the first frame of a multi-frame group.""" broadcast = moq.BroadcastProducer() track = broadcast.publish_track("mixed") - consumer = track.consume(moq.Subscription(max_age_us=1_000_000)) + consumer = track.consume(moq.Subscription(max_delay_us=1_000_000)) group = track.append_group() group.write_frame(b"first", 0) @@ -1073,7 +1073,7 @@ def test_optional_binding_records_use_none_defaults(): decoder = moq.AudioDecoderOutput(format=moq.AudioSampleFormat.F32) assert decoder.sample_rate is None assert decoder.channels is None - assert decoder.max_age_us is None + assert decoder.max_delay_us is None def test_encode_audio_with_opus_object(): diff --git a/quest/m1/README.md b/quest/m1/README.md index 21d2307fea9..3afcdfd5dcd 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -69,7 +69,6 @@ blocks. The quests that gated m0 lines moved under them. - [moq-uring tests under load](/quest/m1/uring-tests-under-load.md) - uring tests pass while parallel checks share locked memory - [Media audio-tone check](/quest/m1/media-audio-tone.md) - the media lane's audio-tone check passes under load, fixed at its cause - [CI runner stalls](/quest/m1/ci-runner-stalls.md) - the 0.4 to 0.8 s freezes of both interop tracks on CI are attributed from a week of nightlies and fixed or told apart from playback bugs -- [Subscriber max-delay](/quest/m1/subscriber-max-delay.md) - subscriber staleness becomes `max_delay`; publisher retention stays `max_age` - [Wire compatibility](/quest/m1/wire-compat.md) - a nightly run tests this checkout against the last published release for tokens, session wire, and catalog/container - [Same-epoch importers](/quest/m1/hop-aligned-import.md) - importers sharing one `--epoch` and fed one stream publish identical groups and timestamps, so failover between a redundant pair survives - [Refuse ignored TLS config](/quest/m1/refuse-ignored-tls.md) - TLS options no listener would use fail at load instead of being ignored diff --git a/quest/m1/cache-max-age.md b/quest/m1/cache-max-age.md index 41d02eb89a3..634880342a9 100644 --- a/quest/m1/cache-max-age.md +++ b/quest/m1/cache-max-age.md @@ -119,7 +119,7 @@ encoding change; Max Age semantics in the lite draft change. ## Related -- [Subscriber max-delay](/quest/m1/subscriber-max-delay.md) - renames the subscriber budget to `max_delay`; the rule applies under either name +- [Subscriber max-delay](https://github.com/moq-dev/moq/pull/4917) - renames the subscriber budget to `max_delay`; the rule applies under either name - [JS track handover](/quest/m1/js-group-handover.md) - mirrors the failover rule in JS - [Cache expiry growth](/quest/m1/cache-expiry-growth.md) - relay memory past the expiry window, in the same cache - [Cache shard](/quest/m2/cache-shard.md) - the pool's shared counters under many workers diff --git a/quest/m1/flv-export-delay.md b/quest/m1/flv-export-delay.md index ff3c79ed935..4b595110c6c 100644 --- a/quest/m1/flv-export-delay.md +++ b/quest/m1/flv-export-delay.md @@ -16,8 +16,8 @@ and the same late-frame drop. Update `doc/bin/cli.md`. Decided in the 2026-10-06 audit: `--delay` replaces the staleness flag, as it replaced `--max-age` on TS, so one knob sets both the release delay and the -sources' staleness budget. [Subscriber max-delay](/quest/m1/subscriber-max-delay.md) -(#4917) renames that flag to `--max-delay` first; this quest then replaces +sources' staleness budget. [#4917](https://github.com/moq-dev/moq/pull/4917) +renames that flag to `--max-delay` first; this quest then replaces `--max-delay` with `--delay`. Rejected: excluding flv from the #4917 rename. Public API: breaking, the exporter's staleness setting becomes the delay @@ -25,5 +25,4 @@ setting. Wire: none. ## Required -- [Subscriber max-delay](/quest/m1/subscriber-max-delay.md) - renames the staleness flag first, so this replaces `--max-delay` - [Fixed-delay release](/quest/m1/tstd/delay.md) - builds the shared release stage diff --git a/quest/m1/js-group-handover.md b/quest/m1/js-group-handover.md index 6d5e1315b59..e2e85063f2f 100644 --- a/quest/m1/js-group-handover.md +++ b/quest/m1/js-group-handover.md @@ -8,7 +8,7 @@ the new provider at the first frame it has not delivered. A viewer at the live edge with no latency budget never loses a group across the swap, and never has to notice the swap to keep reading. -Done when `test/drain` passes with the viewer's `MAX_AGE` at zero, the +Done when `test/drain` passes with the viewer's `MAX_DELAY` at zero, the viewer subscribes once instead of following `request.active`, and the run is stable enough for the nightly. diff --git a/quest/m1/lite-late-lower-group.md b/quest/m1/lite-late-lower-group.md index 451ed6ec016..afa0444f7e7 100644 --- a/quest/m1/lite-late-lower-group.md +++ b/quest/m1/lite-late-lower-group.md @@ -3,7 +3,7 @@ ## Goal A moq-lite subscriber with an explicit floor receives every group at or above -that floor that its `max_age` still considers fresh, whatever order the +that floor that its `max_delay` still considers fresh, whatever order the publisher created them in, as moq-transport already does. Today the lite publisher silently drops a group created below the first group it served: the publisher's `create_group` and `write_frame` succeed, and the subscriber sees a @@ -21,7 +21,7 @@ explicit floor. Decided: -- An explicit floor delivers late lower groups within `max_age`, matching +- An explicit floor delivers late lower groups within `max_delay`, matching moq-transport, draft-ietf-moq-transport ("subscriptions without a filter pass all Objects"), and moq-mux's floor handling (#3258). - `start: None` joins where the publisher starts: the first served group diff --git a/quest/m1/mkv-export-delay.md b/quest/m1/mkv-export-delay.md index 4c36da4f164..aa6df2d05a5 100644 --- a/quest/m1/mkv-export-delay.md +++ b/quest/m1/mkv-export-delay.md @@ -16,8 +16,8 @@ and the same late-frame drop. Update `doc/bin/cli.md`. Decided in the 2026-10-06 audit: `--delay` replaces the staleness flag, as it replaced `--max-age` on TS, so one knob sets both the release delay and the -sources' staleness budget. [Subscriber max-delay](/quest/m1/subscriber-max-delay.md) -(#4917) renames that flag to `--max-delay` first; this quest then replaces +sources' staleness budget. [#4917](https://github.com/moq-dev/moq/pull/4917) +renames that flag to `--max-delay` first; this quest then replaces `--max-delay` with `--delay`. Rejected: excluding mkv from the #4917 rename. Public API: breaking, the exporter's staleness setting becomes the delay @@ -25,5 +25,4 @@ setting. Wire: none. ## Required -- [Subscriber max-delay](/quest/m1/subscriber-max-delay.md) - renames the staleness flag first, so this replaces `--max-delay` - [Fixed-delay release](/quest/m1/tstd/delay.md) - builds the shared release stage diff --git a/quest/m1/open-gop-leading-pictures.md b/quest/m1/open-gop-leading-pictures.md index 808f51edca9..1280ca144d4 100644 --- a/quest/m1/open-gop-leading-pictures.md +++ b/quest/m1/open-gop-leading-pictures.md @@ -41,7 +41,7 @@ decode, and the JS test should drive the software decoder. sample of a group to `keyframe`, and `js/watch/src/video/decoder.ts` submits it as `"key"`): for the first group after any non-continuous transition, skip delta frames stamped before that group's keyframe. That covers a - subscribe, a declared discontinuity, and a latency skip: `#checkMaxAge` + subscribe, a declared discontinuity, and a latency skip: `#checkMaxDelay` records the skip through `#gap` and `next()` reports the next frame with `continuous: false`. Latency skip also bumps playhead generation (startup delay) but does not flush the decoder. Leading pictures after that diff --git a/quest/m1/subscribe-live-time.md b/quest/m1/subscribe-live-time.md index b3fe3b09b75..ed6d6a311e6 100644 --- a/quest/m1/subscribe-live-time.md +++ b/quest/m1/subscribe-live-time.md @@ -50,7 +50,7 @@ Decided in planning (2026-10-03): which rewrites the same messages: whichever lands second rebases. - `js/watch/src/sync.ts` stays as it is: its latency range (from #1620) is intended, and only the publisher's estimate uses the least-delayed reference. -- No new docs page: the lite draft and the max-age paragraph in +- No new docs page: the lite draft and the max delay paragraph in `doc/concept/moq-lite.md` are updated inline. ## Related diff --git a/quest/m1/subscribe-ranges/README.md b/quest/m1/subscribe-ranges/README.md index feac5d0355e..7a136ccc3c2 100644 --- a/quest/m1/subscribe-ranges/README.md +++ b/quest/m1/subscribe-ranges/README.md @@ -18,8 +18,9 @@ relay bounds a sparse FETCH only if the model can request ranges: - **Wire (lite-07, unpublished).** SUBSCRIBE carries a list of group ranges (an open end means live) in place of Group Start/End, plus `order: asc | desc` (desc, newest first, is today's rule and the default). - Max Age stays as a cap alongside the ranges, since a group's timestamp isn't - always known. SUBSCRIBE_UPDATE replaces the list. Lite FETCH is removed from + Subscriber Max Age (the model's `max_delay`) stays as a cap alongside the + ranges, since a group's timestamp isn't always known. SUBSCRIBE_UPDATE + replaces the list. Lite FETCH is removed from lite-07; published versions keep it, answered through the same model. - **Holes.** SUBSCRIBE_DROP (restored in lite-07 by [SUBSCRIBE_DROP](/quest/m1/subscribe-drop.md)) names every sequence in the diff --git a/quest/m1/subscribe-ranges/model.md b/quest/m1/subscribe-ranges/model.md index 61488389805..6cbf17070bc 100644 --- a/quest/m1/subscribe-ranges/model.md +++ b/quest/m1/subscribe-ranges/model.md @@ -22,5 +22,5 @@ Guidance: (`fetch_group`, `requested_group`), moq-c (`poll_requested_group`), every binding wrapper and its `doc/lib` page, and `moq fetch` through `moq_relay::fetch_group` (added in the 2026-10-05 audit). -- Max Age caps every range. +- `max_delay` caps every range. - Benchmark range count and span as separate axes (AGENTS.md fan-out rule). diff --git a/quest/m1/subscriber-max-delay.md b/quest/m1/subscriber-max-delay.md deleted file mode 100644 index 2f06d05e961..00000000000 --- a/quest/m1/subscriber-max-delay.md +++ /dev/null @@ -1,50 +0,0 @@ -# [L] Subscriber staleness is max-delay - -## Goal - -Subscriber staleness budgets are named `max_delay` in Rust and -`maxDelay` in JavaScript, mirrored by the bindings and the corresponding CLI -flags. Publisher retention keeps `max_age`/`maxAge` and `--max-age`. The -rename changes no retention, delivery, presentation, or wire behavior. - -## Plan - -Decided with the maintainer on 2026-10-02: subscriber staleness is a delivery -delay, while a publisher's retention ceiling is an age of cached content. -Use different names for these different roles rather than rename both. - -- Rename `moq_net::track::Subscription::max_age` and its builder to - `max_delay`, with `maxDelay` in `@moq/net`, and update every public consumer - option or method that exposes the same subscriber budget in Rust and the - bindings. Keep `track::Info::max_age`, catalog/import retention, and their - publisher-facing options unchanged. Classify each occurrence by its role; - do not perform an indiscriminate search-and-replace. -- Rename subscriber/export staleness CLI flags from `--max-age` to - `--max-delay`, except T-STD export, whose own quest unifies presentation - and staleness under `--delay`. Keep `moq play --delay` unchanged. - Publisher/import retention remains `--max-age`. flv and mkv take the - rename here and move to `--delay` later, in - [FLV export delay](/quest/m1/flv-export-delay.md) and - [MKV export delay](/quest/m1/mkv-export-delay.md) (decided in the - 2026-10-06 audit). -- Keep the wire field identifiers, encoding, and interpretation unchanged. - Describe subscriber staleness consistently in the matching draft and docs; - a terminology edit must not accidentally rename the publisher's field. -- This is a published API and CLI break. - Replace the old APIs and flags instead of adding aliases or compatibility - shims. Follow the existing unsupported-flag error convention. -- Search the whole repository for the affected APIs and binaries. Update the - binding samples, concept documentation, CLI help, recipes, and examples - inline. The maintainer chose existing-document updates, without a separate - explanatory guide quest. -- Use existing subscription/retention tests to verify behavior is unchanged, - and extend CLI parsing tests to distinguish publisher `--max-age` from - subscriber `--max-delay`. Verify examples against `--help` and run the - affected checks plus `just test interop --all` for the binding changes. - -Public API: breaking subscriber option, method, and CLI names; -publisher retention names stay the same. Wire: no encoding or behavior change. - -## Related - -- [T-STD delay](/quest/m1/tstd/delay.md) - TS export already unifies presentation and staleness under `--delay` diff --git a/quest/m1/tstd/delay.md b/quest/m1/tstd/delay.md index 813730f3116..16b355c9cf2 100644 --- a/quest/m1/tstd/delay.md +++ b/quest/m1/tstd/delay.md @@ -100,4 +100,3 @@ report the new counters too, or `moq subscribe` never logs them. Wire: none. - [FLV export delay](/quest/m1/flv-export-delay.md) - adopts the release stage - [MKV export delay](/quest/m1/mkv-export-delay.md) - adopts the release stage - [TS byte schedule](/quest/m1/tstd/byte-schedule.md) - uses this delay as its mux-ahead buffer delay -- [Subscriber max-delay](/quest/m1/subscriber-max-delay.md) - subscriber staleness is renamed; publisher retention stays `max_age` diff --git a/quest/m1/untimed-model.md b/quest/m1/untimed-model.md index 93387fa29c7..03c97b704fb 100644 --- a/quest/m1/untimed-model.md +++ b/quest/m1/untimed-model.md @@ -52,8 +52,8 @@ timestamp draft mandates, and on lite-05 and later a relay forwards those stamps as if they were real. Any route failover then changes them, so the timeline jumps, and the "one clock per broadcast" property breaks. Rejected: first-hop arrival (the failover jump stays), 0 as a -sentinel (collides with a real pts of 0), and `max_age` on max(wall, pts) -(`max_age` stays media-time staleness, so a congestion stall can't age +sentinel (collides with a real pts of 0), and `max_delay` on max(wall, pts) +(`max_delay` stays media-time staleness, so a congestion stall can't age content out, and the pool's wall-clock expiry is the bound). That last rejection is superseded 2026-10-06 by [One max_age meaning](/quest/m1/cache-max-age.md), which lands after this quest. diff --git a/quest/m2/intra-refresh/consumer-warmup.md b/quest/m2/intra-refresh/consumer-warmup.md index 932c5420d7f..3985655fd91 100644 --- a/quest/m2/intra-refresh/consumer-warmup.md +++ b/quest/m2/intra-refresh/consumer-warmup.md @@ -40,14 +40,14 @@ replaces both: the rule is timestamp arithmetic on the group start. in `js/hang`. Other codecs never set `warmup`, so no check is needed there. - Join earlier: the subscription's maximum age becomes the latency target plus `warmup`, so the group start lands `warmup` before the target and the first - presented frame is on time. JS sets the subscription's `maxAge` in `js/net`; - Rust adds it to the decode consumer's `Options::max_age`, which reaches the - subscription through `Subscription::with_max_age` + presented frame is on time. JS sets the subscription's `maxDelay` in `js/net`; + Rust adds it to the decode consumer's `Options::max_delay`, which reaches the + subscription through `Subscription::with_max_delay` (`rs/moq-video/src/decode/consumer.rs`), not `Subscription::start`, which is aggregated across subscribers and rewinds the track for everyone. -- Max-age skipping must not shed the warmup span it deliberately joined: - `#checkMaxAge` in the JS container consumer and the max-age budget in Rust - (`Consumer::poll_read`, set by `set_max_age`) compare the buffered span +- Max-delay skipping must not shed the warmup span it deliberately joined: + `#checkMaxDelay` in the JS container consumer and the max delay budget in Rust + (`Consumer::poll_read`, set by `set_max_delay`) compare the buffered span against the target, and frames still inside a withheld warmup count as decode-only, not buffered. - Tests in both languages: a synthetic three-group track with `warmup` where a diff --git a/quest/m2/teleop/robot.md b/quest/m2/teleop/robot.md index 1932eec47ef..ac5caaa1508 100644 --- a/quest/m2/teleop/robot.md +++ b/quest/m2/teleop/robot.md @@ -57,7 +57,7 @@ The framing is where the guarantee lives, not the subscription flags: stale bytes stop being retransmitted. - A subscriber cannot weaken either class. `clamp_combined` (`rs/moq-net/src/model/track.rs`) clamps the aggregate window down to - `Info::max_age`, and `Subscription::max_age` already defaults to + `Info::max_age`, and `Subscription::max_delay` already defaults to `Duration::ZERO`, so a raw observer subscribing through `moq-net` neither widens the window nor has to be prevented from trying. diff --git a/quest/m3/teleop-browser-package.md b/quest/m3/teleop-browser-package.md index ec5319449bf..c954013824b 100644 --- a/quest/m3/teleop-browser-package.md +++ b/quest/m3/teleop-browser-package.md @@ -15,7 +15,7 @@ There is no `@moq/mux`, so the catalog extension goes through the same seam `js/hang/src/catalog/root.ts` uses to extend the root schema. A browser observer cannot degrade the operator's classes (`clamp_combined` -bounds the window at the publisher, and `Subscription::max_age` already +bounds the window at the publisher, and `Subscription::max_delay` already defaults to `Duration::ZERO`), so this package exists for reuse, not for safety: the catalog schema, the snapshot and append-log shapes, and the instrumentation are the same on both sides and should be written once. diff --git a/rs/hang/examples/subscribe.rs b/rs/hang/examples/subscribe.rs index b213db674db..5416f19cafb 100644 --- a/rs/hang/examples/subscribe.rs +++ b/rs/hang/examples/subscribe.rs @@ -84,7 +84,7 @@ async fn run_subscribe(consumer: moq_net::origin::Consumer) -> anyhow::Result<() .subscribe( moq_net::track::Subscription::default() .with_priority(1) - .with_max_age(latency), + .with_max_delay(latency), ) .await?; let mut ordered = diff --git a/rs/hang/src/container/frame.rs b/rs/hang/src/container/frame.rs index 384f2ed2a30..4c251c33f5d 100644 --- a/rs/hang/src/container/frame.rs +++ b/rs/hang/src/container/frame.rs @@ -26,7 +26,7 @@ pub const TIMESCALE: Timescale = Timescale::MICRO; /// which is why every media track should start here rather than at `Info::default()`. It is a /// retention budget and a CEILING on what a subscriber may ask to wait for, so it never makes /// anyone play further behind live: a subscriber's own -/// [`Subscription::max_age`](moq_net::track::Subscription::max_age) defaults to +/// [`Subscription::max_delay`](moq_net::track::Subscription::max_delay) defaults to /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) (skip the moment a newer group arrives). /// /// `priority` is the publisher's tie-break priority, and should come from diff --git a/rs/moq-archive/src/writer.rs b/rs/moq-archive/src/writer.rs index e0e4cdf8e49..eeb88b4ee64 100644 --- a/rs/moq-archive/src/writer.rs +++ b/rs/moq-archive/src/writer.rs @@ -382,7 +382,7 @@ impl Control { async fn subscribe(&self, name: &str, config: timeline::Config) -> Result<()> { let shared = &self.shared; - let replay = track::Subscription::default().with_max_age(REPLAY); + let replay = track::Subscription::default().with_max_delay(REPLAY); let subscriber = shared .source .track(name) diff --git a/rs/moq-audio/src/decode/consumer.rs b/rs/moq-audio/src/decode/consumer.rs index cdb10d71c31..d594dafe0d1 100644 --- a/rs/moq-audio/src/decode/consumer.rs +++ b/rs/moq-audio/src/decode/consumer.rs @@ -41,14 +41,14 @@ pub struct Options { pub decoder: Config, /// PCM output conversion. pub output: Output, - /// Maximum media age accepted from the subscription. - pub max_age: std::time::Duration, + /// How far a group may fall behind the live edge before the subscription skips it. + pub max_delay: std::time::Duration, /// Initial cached-group policy. pub start: Start, /// A fixed playout delay, or `None` to estimate it from arrival timing. /// /// The jitter buffer a player holds ahead of the playhead, reported by - /// [`Consumer::delay`]. Distinct from [`max_age`](Self::max_age), which is + /// [`Consumer::delay`]. Distinct from [`max_delay`](Self::max_delay), which is /// the live-edge skip budget and adds no buffering. A fixed delay beyond the /// track's retention is refused. pub delay: Option, @@ -75,7 +75,7 @@ pub struct Consumer { /// Converts the decoded layout to the output's, when they differ. remix: Option, options: Options, - max_age: std::time::Duration, + max_delay: std::time::Duration, resolved_sample_rate: u32, resolved_layout: Layout, /// Where the next packet's timestamp should land: the last packet's timestamp @@ -148,7 +148,7 @@ impl Consumer { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.audio) - .with_max_age(options.max_age), + .with_max_delay(options.max_delay), ) .await?; // A decoder often opens on a track that is already cached: a replacement @@ -172,7 +172,7 @@ impl Consumer { } let track = subscriber; let retention = track.info().max_age; - let max_age = options.max_age.min(retention.unwrap_or(Duration::MAX)); + let max_delay = options.max_delay.min(retention.unwrap_or(Duration::MAX)); // Holding more than the publisher keeps would wait on media it has already // discarded, so the caller asked for something impossible. if let (Some(delay), Some(retention)) = (options.delay, retention) @@ -195,7 +195,7 @@ impl Consumer { resampler, remix, options, - max_age, + max_delay, resolved_sample_rate: sample_rate, resolved_layout: layout, next_start: None, @@ -222,9 +222,9 @@ impl Consumer { &self.options } - /// The effective age budget after clamping to the publisher's retention window. - pub fn max_age(&self) -> std::time::Duration { - self.max_age + /// The effective delay budget after clamping to the publisher's retention window. + pub fn max_delay(&self) -> std::time::Duration { + self.max_delay } /// The playout delay to hold ahead of the playhead right now: the fixed @@ -715,7 +715,7 @@ mod tests { sample_rate: Some(48_000), ..Output::default() }, - max_age: std::time::Duration::from_secs(1), + max_delay: std::time::Duration::from_secs(1), ..Options::new() }, ) @@ -849,7 +849,7 @@ mod tests { sample_rate: Some(44_100), ..Output::default() }, - max_age: std::time::Duration::from_secs(1), + max_delay: std::time::Duration::from_secs(1), ..Options::new() }, ) @@ -932,7 +932,7 @@ mod tests { sample_rate: Some(out_rate), ..Output::default() }, - max_age: std::time::Duration::from_secs(1), + max_delay: std::time::Duration::from_secs(1), ..Options::new() }, ) @@ -1175,7 +1175,7 @@ mod tests { &catalog, "audio", Options { - max_age: std::time::Duration::from_secs(1), + max_delay: std::time::Duration::from_secs(1), ..Options::new() }, ) @@ -1384,7 +1384,7 @@ mod tests { } #[tokio::test] - async fn max_age_is_clamped_to_publisher_retention() { + async fn max_delay_is_clamped_to_publisher_retention() { let broadcast = moq_net::broadcast::Info::new().produce(); let info = hang::container::track_info(hang::catalog::PRIORITY.audio) .with_max_age(std::time::Duration::from_millis(100)); @@ -1397,14 +1397,14 @@ mod tests { &catalog, "audio", Options { - max_age: std::time::Duration::from_millis(500), + max_delay: std::time::Duration::from_millis(500), ..Options::new() }, ) .await .unwrap(); - assert_eq!(consumer.max_age(), std::time::Duration::from_millis(100)); + assert_eq!(consumer.max_delay(), std::time::Duration::from_millis(100)); } /// Opus pre-skip is padding before the decoded epoch, not missing media after @@ -1434,7 +1434,7 @@ mod tests { &catalog, "audio", Options { - max_age: std::time::Duration::from_secs(1), + max_delay: std::time::Duration::from_secs(1), ..Options::new() }, ) @@ -1486,7 +1486,7 @@ mod tests { &catalog, "audio", Options { - max_age: std::time::Duration::from_secs(1), + max_delay: std::time::Duration::from_secs(1), ..Options::new() }, ) @@ -1539,19 +1539,19 @@ mod tests { track, moq_mux::catalog::hang::Container::Loc(moq_mux::container::Kind::Audio), ); - let max_age = std::time::Duration::from_millis(250); + let max_delay = std::time::Duration::from_millis(250); let mut consumer = Consumer::new( &subscriber, &catalog, "audio", Options { - max_age, + max_delay, ..Options::new() }, ) .await .unwrap(); - assert_eq!(observed.subscription().unwrap().max_age, max_age); + assert_eq!(observed.subscription().unwrap().max_delay, max_delay); let samples = [0.25f32, -0.5, 0.75, -1.0]; let payload: Vec = samples.iter().flat_map(|sample| sample.to_le_bytes()).collect(); diff --git a/rs/moq-audio/src/encode/capture.rs b/rs/moq-audio/src/encode/capture.rs index 6fe8f9ce282..777555951d3 100644 --- a/rs/moq-audio/src/encode/capture.rs +++ b/rs/moq-audio/src/encode/capture.rs @@ -2137,7 +2137,7 @@ mod tests { .consumer .track("audio") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RETAIN)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RETAIN)) .await .unwrap(); wait_for(&mut self.publication, Status::Live).await; diff --git a/rs/moq-audio/src/encode/producer.rs b/rs/moq-audio/src/encode/producer.rs index 742f5636793..dcf9519c967 100644 --- a/rs/moq-audio/src/encode/producer.rs +++ b/rs/moq-audio/src/encode/producer.rs @@ -603,7 +603,7 @@ mod tests { &decoder_config, "audio", DecodeOptions { - max_age: Duration::from_secs(1), + max_delay: Duration::from_secs(1), ..DecodeOptions::new() }, ) @@ -654,7 +654,7 @@ mod tests { consumer .track("audio") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(), moq_mux::catalog::hang::Container::Legacy(moq_mux::container::Kind::Audio), @@ -781,7 +781,7 @@ mod tests { &decoder_config, "audio", DecodeOptions { - max_age: Duration::from_millis(500), + max_delay: Duration::from_millis(500), ..DecodeOptions::new() }, ) @@ -935,7 +935,7 @@ mod tests { let track = consumer .track("audio") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(); let mut reader = moq_mux::container::Consumer::new( @@ -986,7 +986,7 @@ mod tests { let track = consumer .track("audio") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(); let mut reader = diff --git a/rs/moq-audio/tests/import.rs b/rs/moq-audio/tests/import.rs index 010c1976c4e..a1a5a147e43 100644 --- a/rs/moq-audio/tests/import.rs +++ b/rs/moq-audio/tests/import.rs @@ -25,7 +25,7 @@ async fn ts_surround_opus_decodes() { let mut options = decode::Options::default(); options.output.format = Format::F32; // The whole file is imported before anything decodes it. - options.max_age = Duration::from_secs(30); + options.max_delay = Duration::from_secs(30); let mut consumer = decode::Consumer::new(&broadcast_consumer, config, name, options) .await .unwrap(); diff --git a/rs/moq-audio/tests/roundtrip.rs b/rs/moq-audio/tests/roundtrip.rs index 55e09bfab39..34ba2750638 100644 --- a/rs/moq-audio/tests/roundtrip.rs +++ b/rs/moq-audio/tests/roundtrip.rs @@ -61,7 +61,7 @@ async fn opus_round_trip_48k_stereo() { // The whole clip is encoded before anything decodes it. The default REAL_TIME // budget is enforced on the subscription, so without a tolerance the decoder would // take the live edge and drop the rest of the batch. - options.max_age = Duration::from_secs(30); + options.max_delay = Duration::from_secs(30); let mut consumer = decode::Consumer::new(&broadcast_consumer, cfg, "audio", options) .await .unwrap(); @@ -135,7 +135,7 @@ async fn opus_round_trip_44100_s16_resampled() { config.output.format = Format::S16; config.output.sample_rate = Some(44_100); config.output.layout = Some(Layout::Mono); - config.max_age = Duration::from_millis(500); + config.max_delay = Duration::from_millis(500); let mut consumer = decode::Consumer::new(&broadcast_consumer, cfg, "audio", config) .await diff --git a/rs/moq-bench/src/connection.rs b/rs/moq-bench/src/connection.rs index c90bf21bea1..50e0f3b6a0f 100644 --- a/rs/moq-bench/src/connection.rs +++ b/rs/moq-bench/src/connection.rs @@ -591,7 +591,7 @@ mod tests { } fn replay() -> track::Subscription { - track::Subscription::default().with_max_age(Duration::from_secs(30)) + track::Subscription::default().with_max_delay(Duration::from_secs(30)) } /// A produced group must start with the JSON keyframe describing the rolled diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index 5d70b64d358..efc5fd9ebfe 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -121,11 +121,11 @@ int32_t moq_consume_video_stalled(uint32_t catalog, uint32_t index, bool *dst); int32_t moq_consume_audio_config(uint32_t catalog, uint32_t index, moq_audio_config *dst); // Consuming: Video -int32_t moq_consume_video(uint32_t catalog, uint32_t index, uint64_t max_age_us, moq_status_callback on_frame, void *user_data); +int32_t moq_consume_video(uint32_t catalog, uint32_t index, uint64_t max_delay_us, moq_status_callback on_frame, void *user_data); int32_t moq_consume_video_cancel(uint32_t track); // Consuming: Audio -int32_t moq_consume_audio(uint32_t catalog, uint32_t index, uint64_t max_age_us, moq_status_callback on_frame, void *user_data); +int32_t moq_consume_audio(uint32_t catalog, uint32_t index, uint64_t max_delay_us, moq_status_callback on_frame, void *user_data); int32_t moq_consume_audio_cancel(uint32_t track); // Consuming: Frames diff --git a/rs/moq-c/c-tests/decode-output.c b/rs/moq-c/c-tests/decode-output.c index 663907df4c0..12782232dc9 100644 --- a/rs/moq-c/c-tests/decode-output.c +++ b/rs/moq-c/c-tests/decode-output.c @@ -31,7 +31,7 @@ _Static_assert(MOQ_VIDEO_PIXEL_FORMAT_I420 == 0, "I420 discriminant moved"); _Static_assert(MOQ_VIDEO_PIXEL_FORMAT_RGBA == 1, "RGBA discriminant moved"); -_Static_assert(offsetof(moq_video_decoder_output, max_age_us) == 0, "max_age_us moved"); +_Static_assert(offsetof(moq_video_decoder_output, max_delay_us) == 0, "max_delay_us moved"); _Static_assert(offsetof(moq_video_decoder_output, format) == 8, "format moved"); _Static_assert(offsetof(moq_video_decoder_output, width) == 12, "width moved"); _Static_assert(offsetof(moq_video_decoder_output, height) == 16, "height moved"); diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 1fb01732587..c65b5079a5f 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -500,7 +500,7 @@ pub struct moq_track_info { pub priority: u8, /// Maximum age of a non-latest group before the publisher evicts it, in microseconds. - /// The publisher-side half of `moq_subscription.max_age_us`. + /// The publisher-side half of `moq_subscription.max_delay_us`. pub max_age_us: u64, /// Whether `max_age_us` is set. When false, the publisher imposes no age limit. pub max_age_present: bool, @@ -555,11 +555,11 @@ pub struct moq_subscription { /// Delivery priority. Higher values preempt lower ones under contention. pub priority: u8, - /// Maximum age of a non-latest group before it is skipped, in microseconds. + /// How far a non-latest group may fall behind the live edge before it is skipped, in microseconds. /// Zero skips immediately. Enforced by the publisher's cache and by any local buffering. - pub max_age_us: u64, + pub max_delay_us: u64, - /// The lowest group to deliver (a floor). A floor is not a request: `max_age_us` is + /// The lowest group to deliver (a floor). A floor is not a request: `max_delay_us` is /// what asks for data, and delivery starts at the oldest group at or above the floor /// within that budget (the latest group at the default budget of 0). pub group_start: u64, @@ -577,7 +577,7 @@ impl From<&moq_subscription> for moq_net::track::Subscription { fn from(subscription: &moq_subscription) -> Self { let mut out = moq_net::track::Subscription::default() .with_priority(subscription.priority) - .with_max_age(std::time::Duration::from_micros(subscription.max_age_us)); + .with_max_delay(std::time::Duration::from_micros(subscription.max_delay_us)); if subscription.group_start_present { out = out.with_start(moq_net::track::Position::group(subscription.group_start)); } @@ -3411,7 +3411,7 @@ pub unsafe extern "C" fn moq_consume_catalog_section( /// Consume a video track from a broadcast, delivering frames in order. /// -/// - `max_age_us` controls the maximum amount of buffering allowed before skipping a GoP. +/// - `max_delay_us` controls the maximum amount of buffering allowed before skipping a GoP. /// - `on_frame` is called with a positive frame ID per frame, then exactly once /// more with a terminal code: `0` (closed cleanly) or a negative error. After /// the terminal (`<= 0`) callback, `on_frame` is never called again and @@ -3426,16 +3426,16 @@ pub unsafe extern "C" fn moq_consume_catalog_section( pub unsafe extern "C" fn moq_consume_video( catalog: u32, index: u32, - max_age_us: u64, + max_delay_us: u64, on_frame: ffi::moq_status_callback, user_data: *mut c_void, ) -> i32 { ffi::enter(move || { let catalog = ffi::parse_id(catalog)?; let index = index as usize; - let max_age = std::time::Duration::from_micros(max_age_us); + let max_delay = std::time::Duration::from_micros(max_delay_us); let on_frame = unsafe { ffi::OnStatus::new(user_data, on_frame)? }; - State::lock().consume.video(catalog, index, max_age, on_frame) + State::lock().consume.video(catalog, index, max_delay, on_frame) }) } @@ -3460,7 +3460,7 @@ pub extern "C" fn moq_consume_video_cancel(track: u32) -> i32 { /// the terminal (`<= 0`) callback, `on_frame` is never called again and /// `user_data` is never touched again, so release `user_data` there. The /// terminal callback fires even after [moq_consume_audio_cancel]. -/// The `max_age_us` parameter controls how long to wait before skipping frames. +/// The `max_delay_us` parameter controls how long to wait before skipping frames. /// /// Returns a non-zero handle to the track on success, or a negative code on failure. /// @@ -3470,16 +3470,16 @@ pub extern "C" fn moq_consume_video_cancel(track: u32) -> i32 { pub unsafe extern "C" fn moq_consume_audio( catalog: u32, index: u32, - max_age_us: u64, + max_delay_us: u64, on_frame: ffi::moq_status_callback, user_data: *mut c_void, ) -> i32 { ffi::enter(move || { let catalog = ffi::parse_id(catalog)?; let index = index as usize; - let max_age = std::time::Duration::from_micros(max_age_us); + let max_delay = std::time::Duration::from_micros(max_delay_us); let on_frame = unsafe { ffi::OnStatus::new(user_data, on_frame)? }; - State::lock().consume.audio(catalog, index, max_age, on_frame) + State::lock().consume.audio(catalog, index, max_delay, on_frame) }) } diff --git a/rs/moq-c/src/audio.rs b/rs/moq-c/src/audio.rs index 21d3b1c2257..f13b3991ba0 100644 --- a/rs/moq-c/src/audio.rs +++ b/rs/moq-c/src/audio.rs @@ -108,12 +108,12 @@ pub struct moq_audio_decoder_output { pub channels: u32, /// Upper bound on buffering before skipping a stalled group, in /// microseconds. Same congestion-control knob as - /// `moq_consume_audio`'s `max_age_us`. 0 = skip + /// `moq_consume_audio`'s `max_delay_us`. 0 = skip /// aggressively (the moq-mux default); set to your playout /// buffer (tens to a few hundred ms) for a softer skip. Named /// `_max` to leave room for a future `min_buffer_us`, a /// jitter-buffer floor rather than a staleness bound. - pub max_age_us: u64, + pub max_delay_us: u64, } /// One audio frame: payload bytes plus a presentation timestamp. @@ -515,7 +515,7 @@ pub unsafe extern "C" fn moq_decode_audio( config.output.layout = zeroable(raw.channels) .map(moq_audio::Layout::from_channels) .transpose()?; - config.max_age = Duration::from_micros(raw.max_age_us); + config.max_delay = Duration::from_micros(raw.max_delay_us); let on_frame = unsafe { OnStatus::new(user_data, on_frame)? }; diff --git a/rs/moq-c/src/consume.rs b/rs/moq-c/src/consume.rs index 01167c9c799..fe6473e7a35 100644 --- a/rs/moq-c/src/consume.rs +++ b/rs/moq-c/src/consume.rs @@ -402,7 +402,7 @@ impl Consume { &mut self, catalog: Id, index: usize, - max_age: std::time::Duration, + max_delay: std::time::Duration, on_frame: OnStatus, ) -> Result { let consume = self.catalog.get(catalog).ok_or(Error::CatalogNotFound)?; @@ -440,7 +440,7 @@ impl Consume { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.video) - .with_max_age(max_age), + .with_max_delay(max_delay), ) .await?; let track = moq_mux::container::Consumer::new(track, container); @@ -463,7 +463,7 @@ impl Consume { &mut self, catalog: Id, index: usize, - max_age: std::time::Duration, + max_delay: std::time::Duration, on_frame: OnStatus, ) -> Result { let consume = self.catalog.get(catalog).ok_or(Error::CatalogNotFound)?; @@ -496,7 +496,7 @@ impl Consume { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.audio) - .with_max_age(max_age), + .with_max_delay(max_delay), ) .await?; let track = moq_mux::container::Consumer::new(track, container); diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 66a75439b33..111f32785e2 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -1402,7 +1402,7 @@ fn publish_track_invalid_broadcast() { let subscription = moq_subscription { priority: 1, - max_age_us: 0, + max_delay_us: 0, group_start: 0, group_start_present: false, group_end: 0, @@ -1452,7 +1452,7 @@ fn raw_track_publish_consume() { // finish draining if the second becomes visible while the callback runs. let subscription = moq_subscription { priority: 0, - max_age_us: 1_000_000, + max_delay_us: 1_000_000, group_start: 0, group_start_present: false, group_end: 0, @@ -1654,7 +1654,7 @@ fn raw_track_subscription_options_and_update() { let frame_cb = Callback::new(); let subscription = moq_subscription { priority: 5, - max_age_us: 25_000, + max_delay_us: 25_000, group_start: 1, group_start_present: true, group_end: 2, @@ -3307,7 +3307,7 @@ fn video_raw_publish_consume() { let catalog_id = id(catalog_cb.recv()); let decoder = moq_video_decoder_output { - max_age_us: 10_000_000, + max_delay_us: 10_000_000, format: moq_video_pixel_format::MOQ_VIDEO_PIXEL_FORMAT_I420 as u32, width: 0, height: 0, @@ -3379,7 +3379,7 @@ fn video_raw_decode_output_rejected() { use crate::ffi::ReturnCode; let bad_format = moq_video_decoder_output { - max_age_us: 0, + max_delay_us: 0, format: 999, width: 0, height: 0, @@ -3391,7 +3391,7 @@ fn video_raw_decode_output_rejected() { for (width, height) in [(320, 0), (0, 240), (321, 240), (320, 241), (u32::MAX - 1, u32::MAX - 1)] { let bad_size = moq_video_decoder_output { - max_age_us: 0, + max_delay_us: 0, format: moq_video_pixel_format::MOQ_VIDEO_PIXEL_FORMAT_I420 as u32, width, height, @@ -3409,7 +3409,7 @@ fn video_raw_decode_output_rejected() { ); let valid = moq_video_decoder_output { - max_age_us: 0, + max_delay_us: 0, format: moq_video_pixel_format::MOQ_VIDEO_PIXEL_FORMAT_RGBA as u32, width: 160, height: 120, @@ -3512,7 +3512,7 @@ fn decode_first_frame(output: &moq_video_decoder_output) -> (u32, u32, usize) { #[test] fn video_raw_decode_rgba() { let output = moq_video_decoder_output { - max_age_us: 10_000_000, + max_delay_us: 10_000_000, format: moq_video_pixel_format::MOQ_VIDEO_PIXEL_FORMAT_RGBA as u32, width: 0, height: 0, @@ -3525,7 +3525,7 @@ fn video_raw_decode_rgba() { #[test] fn video_raw_decode_resize() { let output = moq_video_decoder_output { - max_age_us: 10_000_000, + max_delay_us: 10_000_000, format: moq_video_pixel_format::MOQ_VIDEO_PIXEL_FORMAT_I420 as u32, width: 160, height: 120, @@ -3853,7 +3853,7 @@ fn video_raw_decode() { // Subscribe + decode before publishing frames so the keyframe group is delivered. let output = moq_video_decoder_output { - max_age_us: 10_000_000, + max_delay_us: 10_000_000, format: moq_video_pixel_format::MOQ_VIDEO_PIXEL_FORMAT_I420 as u32, width: 0, height: 0, @@ -4850,7 +4850,7 @@ fn read_raw_frames(consume: u32, name: &[u8], count: usize) -> Vec> { let frame_cb = Callback::new(); let subscription = moq_subscription { priority: 0, - max_age_us: 1_000_000, + max_delay_us: 1_000_000, group_start: 0, group_start_present: false, group_end: 0, diff --git a/rs/moq-c/src/video.rs b/rs/moq-c/src/video.rs index f37df0d75c9..bccaf89b9f1 100644 --- a/rs/moq-c/src/video.rs +++ b/rs/moq-c/src/video.rs @@ -139,9 +139,9 @@ pub struct moq_video_encoder_frame { pub struct moq_video_decoder_output { /// Upper bound on buffering before skipping a stalled group, in /// microseconds. Same congestion-control knob as - /// `moq_consume_video`'s `max_age_us`. 0 = skip aggressively + /// `moq_consume_video`'s `max_delay_us`. 0 = skip aggressively /// (the moq-mux default); set to your playout buffer for a softer skip. - pub max_age_us: u64, + pub max_delay_us: u64, /// `moq_video_pixel_format` discriminant. Unknown values fail /// [`moq_decode_video`] rather than decoding into an assumed layout. pub format: u32, @@ -913,7 +913,7 @@ pub unsafe extern "C" fn moq_decode_video( let mut options = moq_video::decode::Options::new(); options.start = moq_video::decode::Start::Latest; - options.max_age = Duration::from_micros(raw.max_age_us); + options.max_delay = Duration::from_micros(raw.max_delay_us); // The C caller takes packed pixels, so let a backend that can decode // straight to the CPU do that rather than downloading afterwards. options.decoder.output = moq_video::Output::Cpu; diff --git a/rs/moq-cli/src/args.rs b/rs/moq-cli/src/args.rs index a32033417dc..f010234f5a7 100644 --- a/rs/moq-cli/src/args.rs +++ b/rs/moq-cli/src/args.rs @@ -840,12 +840,10 @@ impl Export { } match &self.sink { ExportSink::Fmp4(args) | ExportSink::Mkv(args) => found.extend(args.container.deprecated()), - ExportSink::Ts(args) => found.extend(args.container.deprecated()), + ExportSink::Ts(args) => found.extend(args.deprecated()), ExportSink::Flv(args) | ExportSink::H264(args) | ExportSink::H265(args) => found.extend(args.deprecated()), ExportSink::Hls(hls) => found.extend(hls.tls.deprecated()), - ExportSink::Rtmp(rtmp) if rtmp.latency_max.is_some() => { - found.flag("--latency-max", None, "--max-age"); - } + ExportSink::Rtmp(rtmp) => found.extend(rtmp.deprecated()), _ => {} } found @@ -904,7 +902,7 @@ impl ExportSink { pub fn stdout(&self) -> Option { let container = |format, container: &Container| Stdout { format, - max_age: container.max_age.into_std(), + max_delay: container.max_delay.into_std(), linger: container.linger.into_std(), fragment_duration: None, mux_rate: None, @@ -919,8 +917,11 @@ impl ExportSink { ..container(SubscribeFormat::Mkv, &args.container) }, Self::Ts(args) => Stdout { + format: SubscribeFormat::Ts, + max_delay: args.max_age.into_std(), + linger: args.linger.into_std(), + fragment_duration: None, mux_rate: args.mux_rate, - ..container(SubscribeFormat::Ts, &args.container) }, Self::Flv(args) => container(SubscribeFormat::Flv, args), Self::H264(args) => container(SubscribeFormat::H264, args), @@ -933,26 +934,30 @@ impl ExportSink { /// A stdout sink's format and the options that apply to it. pub struct Stdout { pub format: SubscribeFormat, - pub max_age: Duration, + pub max_delay: Duration, pub linger: Duration, pub fragment_duration: Option, pub mux_rate: Option, } -/// Options shared by every stdout container sink. +/// Options shared by the stdout container sinks other than `ts`. #[derive(usage::Args, Clone)] #[usage(unknown_flags = "error", args_override_self = false)] pub struct Container { - /// How stale a group may get before it is skipped (e.g. `500ms`, `1s`). + /// How far a group may fall behind the live edge before it is skipped (e.g. `500ms`, `1s`). #[usage(long, default = "500ms")] - pub max_age: crate::duration::Duration, + pub max_delay: crate::duration::Duration, - /// How long to wait for the broadcast to come back once it ends (e.g. `10s`). - /// `ts` only; the output stops while it is gone and resumes flagged as a break. - #[usage(long, default = "0s")] + /// Accepted only to refuse a nonzero value with a pointer to `ts`, the one format + /// that can mark where a returned broadcast restarts. + #[usage(long, default = "0s", hide = true)] pub linger: crate::duration::Duration, - /// The released spelling of [`Self::max_age`]. + /// The released spelling of [`Self::max_delay`]. + #[usage(long = "max-age", hide = true)] + max_age: Option, + + /// The released spelling of [`Self::max_delay`], before `--max-age`. #[usage(long = "latency-max", hide = true)] latency_max: Option, } @@ -960,25 +965,50 @@ pub struct Container { impl Container { fn deprecated(&self) -> moq_tokio::cli::Deprecated { let mut found = moq_tokio::cli::Deprecated::default(); + if self.max_age.is_some() { + found.flag("--max-age", None, "--max-delay"); + } if self.latency_max.is_some() { - found.flag("--latency-max", None, "--max-age"); + found.flag("--latency-max", None, "--max-delay"); } found } } -/// The MPEG-TS stdout container: [`Container`] plus null padding. +/// The MPEG-TS stdout container. +// It keeps `--max-age` rather than `Container`'s `--max-delay`: TS export is moving to a +// fixed release delay that subsumes the staleness budget under its own flag. #[derive(usage::Args, Clone)] #[usage(unknown_flags = "error", args_override_self = false)] pub struct Transport { - #[usage(flatten)] - pub container: Container, + /// How stale a group may get before it is skipped (e.g. `500ms`, `1s`). + #[usage(long, default = "500ms")] + pub max_age: crate::duration::Duration, + + /// How long to wait for the broadcast to come back once it ends (e.g. `10s`). + /// The output stops while it is gone and resumes flagged as a break. + #[usage(long, default = "0s")] + pub linger: crate::duration::Duration, /// Pad the output with null packets to this constant rate, in bits per second. /// Defaults to the multiplex rate the catalog recorded from a constant-rate /// source (`mpegts.muxRate`); without either the output is unpadded. #[usage(long)] pub mux_rate: Option, + + /// The released spelling of [`Self::max_age`]. + #[usage(long = "latency-max", hide = true)] + latency_max: Option, +} + +impl Transport { + fn deprecated(&self) -> moq_tokio::cli::Deprecated { + let mut found = moq_tokio::cli::Deprecated::default(); + if self.latency_max.is_some() { + found.flag("--latency-max", None, "--max-age"); + } + found + } } /// The fmp4 / mkv stdout containers: [`Container`] plus a fragment cap. @@ -1636,6 +1666,65 @@ mod tests { panic!("--latency-max must not start a run"); }; assert!(err.to_string().contains("--latency-max -> --max-age"), "{}", err); + + let Err(err) = Invocation::try_parse_from(["moq", "export", "--broadcast", "b", "mkv", "--latency-max", "1s"]) + else { + panic!("--latency-max must not start a run"); + }; + assert!(err.to_string().contains("--latency-max -> --max-delay"), "{}", err); + } + + /// A publisher's retention is `--max-age` on `import`; a subscriber's staleness budget is + /// `--max-delay` on `export`, except `export ts`, which still spells it `--max-age`. + #[test] + fn export_staleness_is_max_delay_and_import_retention_is_max_age() { + let export = |args: &[&str]| { + let mut argv = vec!["moq", "export", "--broadcast", "b"]; + argv.extend_from_slice(args); + Invocation::try_parse_from(argv) + }; + let stdout = |args: &[&str]| { + let cli = export(args).unwrap(); + let Command::Export(export) = &cli.stages[0] else { + panic!("expected export") + }; + export.sink.stdout().unwrap().max_delay + }; + + for format in ["fmp4", "mkv", "flv", "h264", "h265"] { + assert_eq!(stdout(&[format]), Duration::from_millis(500), "{format}"); + assert_eq!( + stdout(&[format, "--max-delay", "2s"]), + Duration::from_secs(2), + "{format}" + ); + let Err(err) = export(&[format, "--max-age", "2s"]) else { + panic!("{format}: --max-age must not start a run"); + }; + assert!(err.to_string().contains("--max-age -> --max-delay"), "{format}: {err}"); + } + + assert_eq!(stdout(&["ts", "--max-age", "2s"]), Duration::from_secs(2)); + assert!(export(&["ts", "--max-delay", "2s"]).is_err(), "ts keeps --max-age"); + + let rtmp = |flag: &str| export(&["rtmp", "--connect", "rtmp://example.com/live/key", flag, "2s"]); + let cli = rtmp("--max-delay").unwrap(); + let Command::Export(export_rtmp) = &cli.stages[0] else { + panic!("expected export") + }; + let ExportSink::Rtmp(args) = &export_rtmp.sink else { + panic!("expected rtmp") + }; + assert_eq!(args.max_delay.into_std(), Duration::from_secs(2)); + let Err(err) = rtmp("--max-age") else { + panic!("rtmp: --max-age must not start a run"); + }; + assert!(err.to_string().contains("--max-age -> --max-delay"), "rtmp: {err}"); + + assert!( + Invocation::try_parse_from(["moq", "import", "--max-delay", "5s", "ts"]).is_err(), + "import has no subscriber budget" + ); } #[test] diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index c57dc984dd4..4d4fddbeb95 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -728,7 +728,7 @@ fn spawn_export( if let Some(stdout) = export.sink.stdout() { let args = SubscribeArgs { format: stdout.format, - max_age: stdout.max_age, + max_delay: stdout.max_delay, linger: stdout.linger, fragment_duration: stdout.fragment_duration, mux_rate: stdout.mux_rate, @@ -744,12 +744,12 @@ fn spawn_export( tasks.spawn(hls::export(origin.consume(), args, name)); } ExportSink::Rtmp(rtmp) => { - let max_age = rtmp.max_age.into_std(); + let max_delay = rtmp.max_delay.into_std(); if let Some(addr) = rtmp.endpoint.listen { let name = require_broadcast(name, "export rtmp --listen")?; - tasks.spawn(rtmp::listen_export(origin.consume(), addr, name, max_age)); + tasks.spawn(rtmp::listen_export(origin.consume(), addr, name, max_delay)); } else if let Some(url) = rtmp.endpoint.connect { - tasks.spawn(rtmp::connect_export(origin.consume(), url, name, max_age)); + tasks.spawn(rtmp::connect_export(origin.consume(), url, name, max_delay)); } } ExportSink::Srt(srt) => { diff --git a/rs/moq-cli/src/play/args.rs b/rs/moq-cli/src/play/args.rs index 7dadb6fe753..6a5d914994d 100644 --- a/rs/moq-cli/src/play/args.rs +++ b/rs/moq-cli/src/play/args.rs @@ -21,7 +21,7 @@ const DELAY_MAX: Duration = Duration::from_secs(10); /// never handed over, so a budget under the estimate's ceiling would cap the /// target at the budget it was cut to. Two seconds is that ceiling, the most /// lateness the estimate can represent. -const AUTO_MAX_AGE: Duration = Duration::from_secs(2); +const AUTO_MAX_DELAY: Duration = Duration::from_secs(2); /// How far video alone trails the live edge under `auto`. The estimate is /// audio's; video follows the speaker whenever there is one. @@ -98,8 +98,8 @@ impl Args { } /// How long a stalled group is waited on before it is skipped. - pub(super) fn max_age(&self) -> Duration { - self.fixed_delay().unwrap_or(AUTO_MAX_AGE) + pub(super) fn max_delay(&self) -> Duration { + self.fixed_delay().unwrap_or(AUTO_MAX_DELAY) } /// How far video trails the live edge while no speaker is setting the pace. @@ -187,7 +187,7 @@ mod tests { fn a_fixed_delay_sets_the_staleness_budget() { let args = parse(&["--delay", "500ms"]); assert_eq!(args.fixed_delay(), Some(Duration::from_millis(500))); - assert_eq!(args.max_age(), Duration::from_millis(500)); + assert_eq!(args.max_delay(), Duration::from_millis(500)); assert_eq!(args.video_delay(), Duration::from_millis(500)); } @@ -198,7 +198,7 @@ mod tests { let args = parse(&[]); assert_eq!(args.delay, Delay::Auto); assert_eq!(args.fixed_delay(), None); - assert_eq!(args.max_age(), AUTO_MAX_AGE); + assert_eq!(args.max_delay(), AUTO_MAX_DELAY); assert_eq!(parse(&["--delay", "auto"]).delay, Delay::Auto); assert_eq!(Delay::Auto.to_string(), "auto"); assert_eq!(Delay::Fixed(Duration::from_millis(250)).to_string(), "250ms"); diff --git a/rs/moq-cli/src/play/buffer.rs b/rs/moq-cli/src/play/buffer.rs index 9055bb2eb54..d03bf3590c4 100644 --- a/rs/moq-cli/src/play/buffer.rs +++ b/rs/moq-cli/src/play/buffer.rs @@ -44,7 +44,7 @@ impl Buffer { Some(frame) } - pub fn push(&mut self, frame: Frame, max_age: Duration) { + pub fn push(&mut self, frame: Frame, max_delay: Duration) { let edge = *self.edge.get_or_insert(frame.timestamp); self.edge = Some(edge.max(frame.timestamp)); if frame.keyframe { @@ -64,7 +64,7 @@ impl Buffer { self.frames.push_back(frame); let edge = self.edge.unwrap(); let stale = - |oldest: &moq_net::Timestamp| edge.as_micros().saturating_sub(oldest.as_micros()) > max_age.as_micros(); + |oldest: &moq_net::Timestamp| edge.as_micros().saturating_sub(oldest.as_micros()) > max_delay.as_micros(); if self.oldest.front().is_some_and(stale) { // Dropping a reference picture invalidates the rest of its GOP. Resume // only at a retained keyframe, never feed a broken chain to the codec. diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index 31a3c943bc1..62b70aa946a 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -173,10 +173,10 @@ impl Media { // doubles as the staleness budget on the wire. With no speaker to // follow, the playhead is video's own, so waiting on the audio // estimate's budget would only freeze the picture. - let max_age = if snapshot.audio.renditions.is_empty() { + let max_delay = if snapshot.audio.renditions.is_empty() { self.args.video_delay() } else { - self.args.max_age() + self.args.max_delay() }; let opened = async { let decoder = moq_video::decode::Sink::open(&config, &Default::default()).await?; @@ -185,7 +185,7 @@ impl Media { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.video) - .with_max_age(max_age), + .with_max_delay(max_delay), ) .await?; // Start at the local live edge without asking the shared publisher @@ -205,7 +205,7 @@ impl Media { frames: self.video.clone(), changed: self.drained.clone(), output: self.output.clone(), - max_age, + max_delay, }; tasks.spawn(async move { (Kind::Video, video.run(track, decoder).await.map(|()| None)) }); playback.started(Kind::Video); @@ -236,7 +236,7 @@ impl Media { // asked for, so a smaller budget would skip a group the playhead could // still have reached, and would size the hole fill below to a playhead // that does not exist. - decode.max_age = self.args.max_age().max(AUDIO_BUFFER_MIN); + decode.max_delay = self.args.max_delay().max(AUDIO_BUFFER_MIN); decode.delay = self.args.fixed_delay(); // The sink and the frame-duration math below both assume f32, // so ask for it rather than inheriting the decoder default. @@ -333,7 +333,7 @@ async fn play_audio( // decoder's latency budget says: anything longer is what that budget chose to // skip, so playing it as silence would hand back the delay the skip avoided. // Past it the sink skips the hole and the clock re-anchors, as it does today. - let fill_max = samples(consumer.max_age()); + let fill_max = samples(consumer.max_delay()); let mut timeline = AudioTimeline::default(); @@ -386,7 +386,7 @@ async fn play_audio( // so a deeper target could never fill. The advertised floor needs the cap, // being a number the publisher declared about itself, unbounded. The budget // is also what the sink's ring was sized to hold. - let target = samples(consumer.delay().min(consumer.max_age()).max(AUDIO_BUFFER_MIN)); + let target = samples(consumer.delay().min(consumer.max_delay()).max(AUDIO_BUFFER_MIN)); let fit = fit(dry, buffered, target, slack, timing.silence + length as u64); dry = false; @@ -619,13 +619,13 @@ mod tests { }); let mut options = moq_video::decode::Options::new(); options.decoder.kind = moq_video::decode::Kind::Software; - options.max_age = delay; + options.max_delay = delay; let decoder = moq_video::decode::Sink::open(&catalog, &options.decoder).await.unwrap(); let subscriber = broadcast .consume() .track("video") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(delay)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(delay)) .await .unwrap(); let track = moq_mux::container::Consumer::new(subscriber, Container::try_from(&catalog).unwrap()); @@ -639,7 +639,7 @@ mod tests { frames: media.video.clone(), changed: media.drained.clone(), output: recorder.clone(), - max_age: delay, + max_delay: delay, } .run(track, decoder), ); diff --git a/rs/moq-cli/src/play/video.rs b/rs/moq-cli/src/play/video.rs index 79092ec3870..e80f837b795 100644 --- a/rs/moq-cli/src/play/video.rs +++ b/rs/moq-cli/src/play/video.rs @@ -50,7 +50,7 @@ pub(super) struct Video { pub frames: Arc>>, pub changed: Arc, pub output: O, - pub max_age: Duration, + pub max_delay: Duration, } /// The production sink and the deterministic buffered decoder used by tests. @@ -93,7 +93,7 @@ impl Video { { self.output.send(Event::Wake); } - buffer.push(frame, self.max_age); + buffer.push(frame, self.max_delay); } else { buffer.ended = true; } @@ -291,13 +291,13 @@ mod tests { } } - fn playback(media: &Media, max_age: Duration) -> Video { + fn playback(media: &Media, max_delay: Duration) -> Video { Video { presentation: media.presentation.clone(), frames: media.video.clone(), changed: media.drained.clone(), output: media.output.clone(), - max_age, + max_delay, } } @@ -317,7 +317,7 @@ mod tests { .unwrap(); let subscriber = track .consume() - .subscribe(moq_net::track::Subscription::default().with_max_age(delay)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(delay)) .await .unwrap(); let format = moq_mux::catalog::hang::Container::Legacy(moq_mux::container::Kind::Data); @@ -436,7 +436,7 @@ mod tests { .unwrap(); let subscriber = track .consume() - .subscribe(moq_net::track::Subscription::default().with_max_age(delay)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(delay)) .await .unwrap(); let mut producer = moq_mux::container::Producer::new( diff --git a/rs/moq-cli/src/rtmp.rs b/rs/moq-cli/src/rtmp.rs index 0cdc0416c75..7879c622e0a 100644 --- a/rs/moq-cli/src/rtmp.rs +++ b/rs/moq-cli/src/rtmp.rs @@ -37,14 +37,31 @@ pub struct ExportArgs { #[usage(flatten)] pub endpoint: Args, - /// How stale a group may get before it is skipped. RTMP is unpaced, so this - /// bounds buffering, not the wire rate. + /// How far a group may fall behind the live edge before it is skipped. RTMP is + /// unpaced, so this bounds buffering, not the wire rate. #[usage(long, default = "500ms")] - pub max_age: crate::duration::Duration, + pub max_delay: crate::duration::Duration, - /// The released spelling of [`Self::max_age`]. + /// The released spelling of [`Self::max_delay`]. + #[usage(long = "max-age", hide = true)] + max_age: Option, + + /// The released spelling of [`Self::max_delay`], before `--max-age`. #[usage(long = "latency-max", hide = true)] - pub(crate) latency_max: Option, + latency_max: Option, +} + +impl ExportArgs { + pub(crate) fn deprecated(&self) -> moq_tokio::cli::Deprecated { + let mut found = moq_tokio::cli::Deprecated::default(); + if self.max_age.is_some() { + found.flag("--max-age", None, "--max-delay"); + } + if self.latency_max.is_some() { + found.flag("--latency-max", None, "--max-delay"); + } + found + } } /// Accept incoming RTMP publishes into the Origin as `target.name`; reject plays (import). @@ -93,7 +110,7 @@ pub async fn listen_export( origin: moq_net::origin::Consumer, addr: SocketAddr, name: String, - max_age: Duration, + max_delay: Duration, ) -> anyhow::Result<()> { let mut server = Server::bind(addr).await?; tracing::info!(%addr, %name, "RTMP listening (export)"); @@ -105,7 +122,7 @@ pub async fn listen_export( let origin = origin.clone(); let name = name.clone(); tokio::spawn(async move { - if let Err(err) = play.with_max_age(max_age).accept(&origin, &name).await { + if let Err(err) = play.with_max_delay(max_delay).accept(&origin, &name).await { tracing::warn!(%name, %err, "RTMP play ended with error"); } }); @@ -144,7 +161,7 @@ pub async fn connect_export( origin: moq_net::origin::Consumer, url: Url, name: String, - max_age: Duration, + max_delay: Duration, ) -> anyhow::Result<()> { let (addr, app, key) = parse_url(&url).await?; // Confirm the broadcast is reachable (and wait for it to be announced) before dialing; @@ -158,7 +175,7 @@ pub async fn connect_export( tracing::info!(%addr, %app, %name, "RTMP client pushing"); notify_ready(); - let client = Client::connect(addr, &app).await?.with_export_max_age(max_age); + let client = Client::connect(addr, &app).await?.with_export_max_delay(max_delay); Ok(client.publish(&key, origin, &name).await?) } diff --git a/rs/moq-cli/src/subscribe.rs b/rs/moq-cli/src/subscribe.rs index a7e0d110794..398058342f7 100644 --- a/rs/moq-cli/src/subscribe.rs +++ b/rs/moq-cli/src/subscribe.rs @@ -176,7 +176,7 @@ pub struct SubscribeArgs { pub format: SubscribeFormat, /// How far playback may drift from the live edge before skipping groups. - pub max_age: Duration, + pub max_delay: Duration, /// How long to wait for the broadcast to come back after it ends (TS only). pub linger: Duration, @@ -276,7 +276,7 @@ impl Subscribe { // yields moof+mdat fragments in timestamp order across tracks. let stream = self.stream().await?; let mut fmp4 = moq_mux::container::fmp4::Export::new(self.source, stream) - .with_max_age(self.args.max_age) + .with_max_delay(self.args.max_delay) .with_fragment_duration(self.args.fragment_duration); while let Some(chunk) = fmp4.next().await? { @@ -295,7 +295,7 @@ impl Subscribe { // shape internally (synthesizing avcC/hvcC from inline parameter sets). let stream = self.stream().await?; let mut mkv = moq_mux::container::mkv::Export::new(self.source, stream) - .with_max_age(self.args.max_age) + .with_max_delay(self.args.max_delay) .with_fragment_duration(self.args.fragment_duration); while let Some(chunk) = mkv.next().await? { @@ -310,7 +310,7 @@ impl Subscribe { let mut stdout = tokio::io::stdout(); let stream = self.stream().await?; - let mut h264 = moq_mux::codec::h264::Export::new(self.source, stream).with_max_age(self.args.max_age); + let mut h264 = moq_mux::codec::h264::Export::new(self.source, stream).with_max_delay(self.args.max_delay); while let Some(chunk) = h264.next().await? { stdout.write_all(&chunk).await?; @@ -324,7 +324,7 @@ impl Subscribe { let mut stdout = tokio::io::stdout(); let stream = self.stream().await?; - let mut h265 = moq_mux::codec::h265::Export::new(self.source, stream).with_max_age(self.args.max_age); + let mut h265 = moq_mux::codec::h265::Export::new(self.source, stream).with_max_delay(self.args.max_delay); while let Some(chunk) = h265.next().await? { stdout.write_all(&chunk).await?; @@ -346,7 +346,7 @@ impl Subscribe { let mut broadcast = source.broadcast().await?; let mut ts = moq_mux::container::ts::Export::with_ts(self.source, self.catalog) .await? - .with_max_age(self.args.max_age); + .with_max_age(self.args.max_delay); if let Some(mux_rate) = self.args.mux_rate { ts = ts.with_mux_rate(mux_rate); } @@ -359,7 +359,7 @@ impl Subscribe { // repair (#2984). See [`Delivery`] for how the pacing stays // bounded; it needs to know whether each frame was waited for, hence the // hand-rolled poll instead of `ts.next()`. - let mut delivery = Delivery::new(self.args.max_age); + let mut delivery = Delivery::new(self.args.max_delay); let linger = self.args.linger; // Reports a track that stops reaching the output while the rest keeps flowing, // the way `publish` reports one that stops arriving. @@ -419,7 +419,7 @@ impl Subscribe { let select = self.args.selection()?; let mut flv = moq_mux::container::flv::Export::with_catalog_format(self.source, self.catalog) .await? - .with_max_age(self.args.max_age) + .with_max_delay(self.args.max_delay) .with_select(select); while let Some(chunk) = flv.next().await? { diff --git a/rs/moq-e2ee/src/tests.rs b/rs/moq-e2ee/src/tests.rs index 5b54a144131..a430a50cfe8 100644 --- a/rs/moq-e2ee/src/tests.rs +++ b/rs/moq-e2ee/src/tests.rs @@ -278,7 +278,7 @@ fn test_generation() -> Generation { } fn subscribe_all() -> moq_net::track::Subscription { - moq_net::track::Subscription::default().with_max_age(Duration::from_secs(60)) + moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(60)) } fn net_track(name: &Name) -> moq_net::track::Producer { diff --git a/rs/moq-e2ee/tests/transport.rs b/rs/moq-e2ee/tests/transport.rs index f2a6b58fb9a..f5a4ba4f402 100644 --- a/rs/moq-e2ee/tests/transport.rs +++ b/rs/moq-e2ee/tests/transport.rs @@ -68,7 +68,7 @@ async fn connect_protected(version: Version, track: &str) -> Fixture { .track(name.as_str()) .unwrap() .subscribe(Some( - moq_net::track::Subscription::default().with_max_age(Duration::from_secs(60)), + moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(60)), )) .await .unwrap(); diff --git a/rs/moq-ffi/src/audio.rs b/rs/moq-ffi/src/audio.rs index 22c3ba47428..88ed3e866f4 100644 --- a/rs/moq-ffi/src/audio.rs +++ b/rs/moq-ffi/src/audio.rs @@ -125,7 +125,7 @@ pub struct MoqAudioDecoderOutput { pub channels: Option, /// Upper bound on buffering before skipping a stalled group, in /// microseconds. Same congestion-control knob as - /// [`MoqSubscription::max_age_us`](crate::consumer::MoqSubscription::max_age_us): + /// [`MoqSubscription::max_delay_us`](crate::consumer::MoqSubscription::max_delay_us): /// when a group stalls and a newer group is more than this far ahead, /// the consumer skips. `None` keeps the moq-mux default of zero (skip /// aggressively). Named `_max` to leave room for a future @@ -133,7 +133,7 @@ pub struct MoqAudioDecoderOutput { /// one bounds how stale a group may be, that one how much to hold before /// presenting. #[uniffi(default = None)] - pub max_age_us: Option, + pub max_delay_us: Option, } /// One audio frame: payload bytes plus a presentation timestamp. @@ -412,7 +412,7 @@ impl MoqBroadcastConsumer { config.output.format = output.format.into(); config.output.sample_rate = output.sample_rate; config.output.layout = output.channels.map(moq_audio::Layout::from_channels).transpose()?; - config.max_age = output.max_age_us.map(Duration::from_micros).unwrap_or_default(); + config.max_delay = output.max_delay_us.map(Duration::from_micros).unwrap_or_default(); let consumer = moq_audio::decode::Consumer::new(&broadcast, &cfg, name, config).await?; diff --git a/rs/moq-ffi/src/consumer.rs b/rs/moq-ffi/src/consumer.rs index 14e441e3209..7d4e13a12fe 100644 --- a/rs/moq-ffi/src/consumer.rs +++ b/rs/moq-ffi/src/consumer.rs @@ -54,9 +54,9 @@ pub struct MoqSubscription { /// Enforced both by the publisher's cache (sent on the wire) and by any local /// buffering, such as `subscribe_media`'s jitter buffer. #[uniffi(default = 0)] - pub max_age_us: u64, + pub max_delay_us: u64, /// The lowest group to deliver (a floor), or null for none. A floor is not a - /// request: `max_age_us` is what asks for data, and delivery starts at the oldest + /// request: `max_delay_us` is what asks for data, and delivery starts at the oldest /// group at or above the floor within that budget (the latest group at the default /// budget of 0). #[uniffi(default = None)] @@ -85,7 +85,7 @@ impl From for moq_net::track::Subscription { fn from(s: MoqSubscription) -> Self { moq_net::track::Subscription::default() .with_priority(s.priority) - .with_max_age(std::time::Duration::from_micros(s.max_age_us)) + .with_max_delay(std::time::Duration::from_micros(s.max_delay_us)) .with_start(s.group_start.map(moq_net::track::Position::group)) .with_end(s.group_end.map(moq_net::track::Position::group)) } @@ -280,7 +280,7 @@ impl MoqBroadcastConsumer { /// `container` is the track container from the catalog. /// `subscription` tunes delivery priority, group range, and staleness; omit for defaults. /// - /// [`MoqSubscription::max_age_us`] bounds the local jitter buffer as well as + /// [`MoqSubscription::max_delay_us`] bounds the local jitter buffer as well as /// the publisher's cache, so both ends skip a stalled group on the same budget. pub async fn subscribe_media( &self, diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index 59de359329b..aa4aa7d667f 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -20,7 +20,7 @@ pub struct MoqTrackInfo { pub priority: u8, /// Maximum age of a non-latest group before the publisher evicts it, in /// microseconds. Null imposes no publisher age limit. This is the publisher-side half of - /// [`MoqSubscription::max_age_us`](crate::consumer::MoqSubscription::max_age_us). + /// [`MoqSubscription::max_delay_us`](crate::consumer::MoqSubscription::max_delay_us). #[uniffi(default = None)] pub max_age_us: Option, /// Per-frame timescale in ticks per second. Null uses microseconds. diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 6f6b1a751f9..52646ff12f6 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -232,7 +232,7 @@ fn audio_output() -> crate::audio::MoqAudioDecoderOutput { format: MoqAudioSampleFormat::F32, sample_rate: None, channels: None, - max_age_us: None, + max_delay_us: None, } } @@ -644,7 +644,7 @@ async fn raw_track_update_does_not_wait_for_pending_read() { consumer.update(MoqSubscription { priority: 10, - max_age_us: 25_000, + max_delay_us: 25_000, group_start: Some(0), group_end: None, }); @@ -2888,7 +2888,7 @@ async fn raw_track_update_during_pending_group_still_reads_datagram() { consumer.update(MoqSubscription { priority: 10, - max_age_us: 25_000, + max_delay_us: 25_000, group_start: Some(0), group_end: None, }); diff --git a/rs/moq-ffi/src/video.rs b/rs/moq-ffi/src/video.rs index 8399af5144d..5aef0c6c9c5 100644 --- a/rs/moq-ffi/src/video.rs +++ b/rs/moq-ffi/src/video.rs @@ -580,10 +580,10 @@ pub struct MoqVideoDecoderOutput { pub resize: Option, /// Upper bound on buffering before skipping a stalled group, in /// microseconds. Same knob as - /// [`MoqAudioDecoderOutput::max_age_us`](crate::audio::MoqAudioDecoderOutput::max_age_us). + /// [`MoqAudioDecoderOutput::max_delay_us`](crate::audio::MoqAudioDecoderOutput::max_delay_us). /// `None` keeps the moq-mux default of zero (skip aggressively). #[uniffi(default = None)] - pub max_age_us: Option, + pub max_delay_us: Option, /// Keep each frame in the surface its decoder produced, for /// [`MoqVideoDecodedFrame::surface`]. `false`, the default, downloads every /// frame to CPU memory as it is decoded, so @@ -777,8 +777,8 @@ impl MoqBroadcastConsumer { let broadcast = self.resolve_inner(reference.as_deref()).await?; options.decoder.scale_hint = output.resize.map(|size| moq_video::Size::new(size.width, size.height)); - options.max_age = output - .max_age_us + options.max_delay = output + .max_delay_us .map(std::time::Duration::from_micros) .unwrap_or_default(); diff --git a/rs/moq-flate/src/stream/mod.rs b/rs/moq-flate/src/stream/mod.rs index 0327947c6c8..3c3323327e7 100644 --- a/rs/moq-flate/src/stream/mod.rs +++ b/rs/moq-flate/src/stream/mod.rs @@ -280,7 +280,7 @@ mod test { /// backlog. The default budget is [`Duration::ZERO`], which abandons any group a newer one has /// already superseded. fn replaying() -> moq_net::track::Subscription { - moq_net::track::Subscription::default().with_max_age(std::time::Duration::from_secs(30)) + moq_net::track::Subscription::default().with_max_delay(std::time::Duration::from_secs(30)) } /// The track ends with the group, so nothing opens a second one and splits the log. diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index b606283142b..28802637752 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -1155,7 +1155,7 @@ mod tests { .consume() .track("audiolevels") .expect("the opaque track is published") - .subscribe(moq_net::track::Subscription::default().with_max_age(std::time::Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(std::time::Duration::from_secs(1))) .await .expect("subscribe to the opaque track") .ordered(); diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index d3095676418..fff1b9c75f1 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -764,7 +764,7 @@ impl Pump { // rendition. let subscriber = tokio::select! { _ = cancel.changed() => return, - subscriber = track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) => match subscriber { + subscriber = track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) => match subscriber { Ok(subscriber) => subscriber, Err(err) => { gst::warning!(CAT, "track {name} failed to subscribe: {err:?}"); diff --git a/rs/moq-json/src/stream/mod.rs b/rs/moq-json/src/stream/mod.rs index 5c2e217fa3a..2244f2def54 100644 --- a/rs/moq-json/src/stream/mod.rs +++ b/rs/moq-json/src/stream/mod.rs @@ -313,8 +313,8 @@ mod test { .unwrap(); // Ask for a replay window, so the first group is delivered rather than skipped by the - // subscriber's default max-age budget once a newer group exists. - let subscription = moq_net::track::Subscription::default().with_max_age(std::time::Duration::from_secs(30)); + // subscriber's default max delay budget once a newer group exists. + let subscription = moq_net::track::Subscription::default().with_max_delay(std::time::Duration::from_secs(30)); let subscriber = track.subscribe(subscription); // Both groups stay open, the way a publisher writing to two at once leaves them. diff --git a/rs/moq-json/src/window/mod.rs b/rs/moq-json/src/window/mod.rs index 51d22b18c28..86783d18944 100644 --- a/rs/moq-json/src/window/mod.rs +++ b/rs/moq-json/src/window/mod.rs @@ -658,7 +658,7 @@ mod test { .produce() .create_track("test", None) .unwrap(); - let replay = moq_net::track::Subscription::default().with_max_age(std::time::Duration::from_secs(30)); + let replay = moq_net::track::Subscription::default().with_max_delay(std::time::Duration::from_secs(30)); let mut groups = track.subscribe(replay); let mut producer = Producer::::new(track, ProducerConfig::default()); diff --git a/rs/moq-mux/src/codec/h264/export.rs b/rs/moq-mux/src/codec/h264/export.rs index a9f31c01785..569858f8c3c 100644 --- a/rs/moq-mux/src/codec/h264/export.rs +++ b/rs/moq-mux/src/codec/h264/export.rs @@ -26,7 +26,7 @@ use crate::container::ExportSource; pub struct Export { source: crate::Source, catalog: Option, - max_age: std::time::Duration, + max_delay: std::time::Duration, track: Option, } @@ -60,18 +60,18 @@ impl Export { Self { source, catalog: Some(catalog), - max_age: std::time::Duration::ZERO, + max_delay: std::time::Duration::ZERO, track: None, } } - /// Set the max age for the per-track source. + /// Set the max delay for the per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) (skip aggressively). - pub fn with_max_age(mut self, max_age: std::time::Duration) -> Self { - self.max_age = max_age; + pub fn with_max_delay(mut self, max_delay: std::time::Duration) -> Self { + self.max_delay = max_delay; self } @@ -153,7 +153,7 @@ impl Export { return Ok(()); } - let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.max_age)? else { + let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.max_delay)? else { unreachable!("invalid broadcast references were removed above"); }; let convert = match config.description.as_ref().filter(|d| !d.is_empty()) { @@ -294,7 +294,7 @@ mod tests { // The whole track is written before the exporter runs, so it needs a budget // wide enough to read it: the default skips everything but the live edge. let mut export = Export::new(crate::source::announced(&consumer), Once(Some(catalog))) - .with_max_age(std::time::Duration::from_secs(30)); + .with_max_delay(std::time::Duration::from_secs(30)); let frame0 = export.next().await.unwrap().expect("first frame"); let frame1 = export.next().await.unwrap().expect("second frame"); diff --git a/rs/moq-mux/src/codec/h265/export.rs b/rs/moq-mux/src/codec/h265/export.rs index 4cae036a87f..86e548fa36b 100644 --- a/rs/moq-mux/src/codec/h265/export.rs +++ b/rs/moq-mux/src/codec/h265/export.rs @@ -19,7 +19,7 @@ use crate::container::ExportSource; pub struct Export { source: crate::Source, catalog: Option, - max_age: std::time::Duration, + max_delay: std::time::Duration, track: Option, } @@ -52,18 +52,18 @@ impl Export { Self { source, catalog: Some(catalog), - max_age: std::time::Duration::ZERO, + max_delay: std::time::Duration::ZERO, track: None, } } - /// Set the max age for the per-track source. + /// Set the max delay for the per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) (skip aggressively). - pub fn with_max_age(mut self, max_age: std::time::Duration) -> Self { - self.max_age = max_age; + pub fn with_max_delay(mut self, max_delay: std::time::Duration) -> Self { + self.max_delay = max_delay; self } @@ -145,7 +145,7 @@ impl Export { return Ok(()); } - let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.max_age)? else { + let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.max_delay)? else { unreachable!("invalid broadcast references were removed above"); }; let convert = match config.description.as_ref().filter(|d| !d.is_empty()) { @@ -280,7 +280,7 @@ mod tests { // The whole track is written before the exporter runs, so it needs a budget // wide enough to read it: the default skips everything but the live edge. let mut export = Export::new(crate::source::announced(&consumer), Once(Some(catalog))) - .with_max_age(std::time::Duration::from_secs(30)); + .with_max_delay(std::time::Duration::from_secs(30)); let frame0 = export.next().await.unwrap().expect("first frame"); let frame1 = export.next().await.unwrap().expect("second frame"); diff --git a/rs/moq-mux/src/container/consumer.rs b/rs/moq-mux/src/container/consumer.rs index 580a1446c2a..a83edffb103 100644 --- a/rs/moq-mux/src/container/consumer.rs +++ b/rs/moq-mux/src/container/consumer.rs @@ -26,9 +26,9 @@ pub(crate) enum Event { /// a group in arrival order, but across groups it advances by sequence number, skipping /// a stalled or missing group once everything it could still present (bounded by where /// the next group begins) falls a full budget behind the newest content, the same reach -/// [`moq_net::track::Subscription::max_age`] measures. With the default max age of zero, +/// [`moq_net::track::Subscription::max_delay`] measures. With the default max delay of zero, /// the consumer skips aggressively: any group that has a newer alternative is dropped. -/// With a non-zero max age, slow groups are tolerated up to that budget before being +/// With a non-zero max delay, slow groups are tolerated up to that budget before being /// skipped. A missing sequence gets the same tolerance: there is no way to tell a stream /// that lost the delivery race from one the cache evicted. /// @@ -39,15 +39,15 @@ pub(crate) enum Event { /// history the publisher no longer serves expires like any other gap, since its reach /// sits a full budget behind the newest content. /// -/// A stalled group is also skipped early, regardless of the max age budget, once it has +/// A stalled group is also skipped early, regardless of the max delay budget, once it has /// presented up to where the next group begins. CMAF frames carry a per-sample duration, /// so a group whose most recent frame ends (timestamp + duration) at or past the next /// group's first timestamp has nothing left worth waiting for. Containers without a -/// duration report zero, which disables this check and falls back to the max age budget. +/// duration report zero, which disables this check and falls back to the max delay budget. /// -/// Put the initial max age on the [`moq_net::track::Subscription`] before +/// Put the initial max delay on the [`moq_net::track::Subscription`] before /// subscribing. [`new`](Self::new) inherits that budget, and -/// [`set_max_age`](Self::set_max_age) changes it mid-stream. +/// [`set_max_delay`](Self::set_max_delay) changes it mid-stream. /// /// ## Timeline discontinuities /// @@ -73,7 +73,7 @@ pub struct Consumer { startup: bool, // How far we may drift from the live edge before skipping a group. - max_age: std::time::Duration, + max_delay: std::time::Duration, // The live edge of playback: the largest timestamp delivered so far and the group that // carried it. `None` until the first frame is delivered. @@ -112,7 +112,7 @@ fn pts_contiguous(end: Option, next_start: std::time::Durat impl Consumer { /// Create a Consumer wrapping the given moq-lite consumer, decoding `format`. /// - /// The ordering window inherits the subscriber's current max age budget, clamped + /// The ordering window inherits the subscriber's current max delay budget, clamped /// to the track's retention window. Put that budget on the /// [`moq_net::track::Subscription`] before awaiting the subscription, so the /// publisher preserves the same replay window. @@ -125,8 +125,8 @@ impl Consumer { // since history the publisher no longer keeps can't be waited for and would // otherwise stall the catch-up by the excess. let start = subscription.start.map(|position| position.group); - let max_age = subscription - .max_age + let max_delay = subscription + .max_delay .min(track.info().max_age.unwrap_or(std::time::Duration::MAX)); Self { track, @@ -134,7 +134,7 @@ impl Consumer { current: start.unwrap_or(0), pending: VecDeque::new(), startup: start.is_none(), - max_age, + max_delay, live_edge: None, start: None, floor: None, @@ -162,7 +162,7 @@ impl Consumer { /// /// This method handles timestamp decoding, group ordering, and age management /// automatically. It will skip groups that are too far behind to maintain the - /// configured max age. + /// configured max delay. /// /// Returns `None` when the track has ended. pub async fn read(&mut self) -> Result, F::Error> { @@ -359,7 +359,7 @@ impl Consumer { if let Some(front_sequence) = self.pending.front().map(|g| g.sequence) && front_sequence > self.current && let Some((_, next_start)) = next_group - && (finished || max_timestamp.saturating_sub(next_start) >= self.max_age) + && (finished || max_timestamp.saturating_sub(next_start) >= self.max_delay) { if !pts_contiguous(current_end.or(self.presented_end), next_start) { self.bump_playhead(); @@ -378,7 +378,7 @@ impl Consumer { // once it has presented up to where the next group begins (duration // coverage), since nothing is left worth waiting for. let should_skip = next_group.is_some_and(|(_, next_start)| { - max_timestamp.saturating_sub(next_start) >= self.max_age + max_timestamp.saturating_sub(next_start) >= self.max_delay || current_end.is_some_and(|end| end >= next_start) }); @@ -494,15 +494,15 @@ impl Consumer { Ok(()) } - /// Set the max age mid-stream, clamped to the track's retention window like + /// Set the max delay mid-stream, clamped to the track's retention window like /// [`new`](Self::new). The subscription keeps the requested value verbatim, - /// matching [`moq_net::track::Subscription::max_age`]. - pub fn set_max_age(&mut self, max_age: std::time::Duration) { - self.max_age = max_age.min(self.track.info().max_age.unwrap_or(std::time::Duration::MAX)); + /// matching [`moq_net::track::Subscription::max_delay`]. + pub fn set_max_delay(&mut self, max_delay: std::time::Duration) { + self.max_delay = max_delay.min(self.track.info().max_age.unwrap_or(std::time::Duration::MAX)); // The transport enforces the same budget on the subscription itself, so a // tolerance set here has to reach it: otherwise moq-net skips the very groups // this consumer was told to wait for, before they ever get here. - let subscription = self.track.subscription().with_max_age(max_age); + let subscription = self.track.subscription().with_max_delay(max_delay); let _ = self.track.update(subscription); } } @@ -827,12 +827,15 @@ mod tests { /// Both layers enforce the same budget, and normally should: the transport skipping /// a group the consumer was going to skip anyway just saves the bandwidth. These /// tests are the exception, since they are about the consumer's half of it. - fn container_max_age_only(track: moq_net::track::Subscriber, max_age: std::time::Duration) -> Consumer { + fn container_max_delay_only( + track: moq_net::track::Subscriber, + max_delay: std::time::Duration, + ) -> Consumer { let control = track.control(); let mut consumer = Consumer::new(track, Container::Legacy(crate::container::Kind::Data)); - consumer.set_max_age(max_age); + consumer.set_max_delay(max_delay); control - .update(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(30))) + .update(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(30))) .unwrap(); consumer } @@ -842,20 +845,20 @@ mod tests { #[test] fn new_inherits_the_initial_subscription_latency() { let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); - let max_age = Duration::from_millis(250); - let subscriber = track.subscribe(moq_net::track::Subscription::default().with_max_age(max_age)); + let max_delay = Duration::from_millis(250); + let subscriber = track.subscribe(moq_net::track::Subscription::default().with_max_delay(max_delay)); let consumer = Consumer::new(subscriber, Container::Legacy(crate::container::Kind::Data)); - assert_eq!(consumer.max_age, max_age); - assert_eq!(consumer.track.subscription().max_age, max_age); + assert_eq!(consumer.max_delay, max_delay); + assert_eq!(consumer.track.subscription().max_delay, max_delay); } #[tokio::test] async fn read_single_group() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0)]); @@ -890,7 +893,7 @@ mod tests { async fn empty_group_declares_a_discontinuity() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(2))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(2))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Audio)); write_group(&mut track, 0, &[ts(0)]); @@ -908,7 +911,7 @@ mod tests { async fn empty_groups_mean_nothing() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(2))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(2))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Audio)); write_group(&mut track, 0, &[ts(0)]); @@ -929,10 +932,10 @@ mod tests { async fn latency_skip_preserves_empty_group_discontinuity() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(2))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(2))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Audio)); // Keep transport filtering out of this test so it isolates the mux skip logic. - consumer.max_age = Duration::ZERO; + consumer.max_delay = Duration::ZERO; write_group(&mut track, 0, &[ts(0)]); write_group(&mut track, 3, &[ts(1_000_000)]); @@ -952,7 +955,7 @@ mod tests { async fn read_multiple_frames_single_group() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0), ts(33_000), ts(66_000)]); @@ -971,10 +974,10 @@ mod tests { async fn read_multiple_groups_within_latency() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); - // 5 groups, 20ms spacing. Total span = 80ms, well within the 500ms max age. + // 5 groups, 20ms spacing. Total span = 80ms, well within the 500ms max delay. for i in 0..5u64 { write_group(&mut track, i, &[ts(i * 20_000)]); } @@ -991,7 +994,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Group 0: 5 frames, NOT finished (blocks consumer) @@ -1034,7 +1037,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = track.subscribe(None); - let mut consumer = container_max_age_only(consumer_track, Duration::ZERO); + let mut consumer = container_max_delay_only(consumer_track, Duration::ZERO); // Group 0 at ts 0 keeps timestamps monotonic with sequence (groups 1-9 follow at // g*50 ms), so the test exercises age skipping and not rewind detection. @@ -1073,7 +1076,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = track.subscribe(None); - let mut consumer = container_max_age_only(consumer_track, Duration::from_millis(100)); + let mut consumer = container_max_delay_only(consumer_track, Duration::from_millis(100)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); Container::Legacy(crate::container::Kind::Data) @@ -1117,7 +1120,7 @@ mod tests { fn a_long_group_blocked_behind_a_newer_one_is_not_cut_short() { let waiter = kio::Waiter::noop(); let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); - let mut consumer = container_max_age_only(track.subscribe(None), Duration::from_secs(2)); + let mut consumer = container_max_delay_only(track.subscribe(None), Duration::from_secs(2)); let write = |group: &mut moq_net::group::Producer, timestamp: Timestamp| { let frame = Frame { timestamp, @@ -1252,7 +1255,7 @@ mod tests { async fn a_marker_group_and_forward_jump_bumps_playhead_once() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio)); let mut consumer = Consumer::new( - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(2))), + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(2))), Container::Legacy(crate::container::Kind::Audio), ); write_group(&mut track, 0, &[ts(0)]); @@ -1269,7 +1272,7 @@ mod tests { async fn a_zero_budget_idle_resume_jumps_the_playhead_after_a_shed_marker() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio)); let mut consumer = Consumer::new(track.subscribe(None), Container::Legacy(crate::container::Kind::Audio)); - consumer.max_age = Duration::ZERO; + consumer.max_delay = Duration::ZERO; write_group(&mut track, 0, &[ts(0)]); assert_eq!(consumer.read().await.unwrap().unwrap().timestamp, ts(0)); write_marker_group(&mut track, 1, ts(0)); @@ -1287,7 +1290,7 @@ mod tests { async fn a_zero_budget_skip_keeps_a_contiguous_marker() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.audio)); let mut consumer = Consumer::new(track.subscribe(None), Container::Legacy(crate::container::Kind::Audio)); - consumer.max_age = Duration::ZERO; + consumer.max_delay = Duration::ZERO; let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); Container::Legacy(crate::container::Kind::Audio) @@ -1359,7 +1362,7 @@ mod tests { async fn empty_payload_is_skipped() { let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Video)); let mut group = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1390,7 +1393,7 @@ mod tests { async fn leading_marker_preserves_the_first_media_keyframe() { let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Video)); let mut group = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1421,7 +1424,7 @@ mod tests { async fn consecutive_markers_do_not_stall() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Video)); let mut group = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1453,7 +1456,7 @@ mod tests { async fn loc_empty_payload_is_skipped() { let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Loc(crate::container::Kind::Video)); let mut group = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1492,7 +1495,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1529,7 +1532,7 @@ mod tests { async fn adjacent_group_flushed_immediately() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0)]); @@ -1548,7 +1551,7 @@ mod tests { async fn bframes_within_group() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0), ts(66_000), ts(33_000)]); @@ -1568,7 +1571,7 @@ mod tests { tokio::time::pause(); let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); track.finish().unwrap(); @@ -1587,7 +1590,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0)]); @@ -1611,7 +1614,7 @@ mod tests { async fn gap_in_group_sequence_recovery() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0), ts(20_000)]); @@ -1630,7 +1633,7 @@ mod tests { async fn gap_at_start_of_sequence() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(80))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(80))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 5, &[ts(0), ts(20_000)]); @@ -1667,7 +1670,7 @@ mod tests { let track = broadcast .track("video") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(2))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(2))) .await .unwrap(); let format = Container::Legacy(crate::container::Kind::Data); @@ -1749,7 +1752,7 @@ mod tests { async fn evicted_group_with_gap_skips_to_live() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Group 0: a frame the consumer reads, positioning it there. @@ -1795,7 +1798,7 @@ mod tests { async fn missing_sequence_skips_on_live_track() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Group 0, then group 2 -- sequence 1 is missing (evicted) and never arrives. @@ -1823,11 +1826,11 @@ mod tests { /// it instead of writing it off, and delivers it when its stream loses the race but /// still arrives (#3258). #[tokio::test] - async fn gap_keeps_late_arriving_group_within_max_age() { + async fn gap_keeps_late_arriving_group_within_max_delay() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Group 2's stream beats group 1's, which hasn't arrived at all yet. @@ -1859,13 +1862,13 @@ mod tests { /// wins the arrival race, the consumer waits for the requested head under the age /// budget instead of dropping it on arrival (#3258). #[tokio::test] - async fn startup_keeps_late_arriving_head_group_within_max_age() { + async fn startup_keeps_late_arriving_head_group_within_max_delay() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = track.subscribe( moq_net::track::Subscription::default() .with_start(moq_net::track::Position::group(0)) - .with_max_age(Duration::from_millis(500)), + .with_max_delay(Duration::from_millis(500)), ); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); @@ -1890,11 +1893,11 @@ mod tests { /// A group whose frames lost the race to a newer group's stream is still read once /// they land: the cursor starts at group 0 and waits under the budget (#3258). #[tokio::test] - async fn startup_keeps_slow_earlier_stream_within_max_age() { + async fn startup_keeps_slow_earlier_stream_within_max_delay() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Group 0's stream opens first but carries no frames yet; group 1's frame wins. @@ -2007,7 +2010,7 @@ mod tests { async fn frame_timestamp_and_index_decoding() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0), ts(33_333), ts(66_666)]); @@ -2028,7 +2031,7 @@ mod tests { async fn frame_payload_preserved() { let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let payload_bytes = vec![0x01, 0x02, 0x03, 0x04, 0x05]; @@ -2067,7 +2070,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2114,7 +2117,7 @@ mod tests { async fn large_timestamps() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(3700))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(3700))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let one_hour = 3_600_000_000u64; @@ -2128,10 +2131,10 @@ mod tests { } #[tokio::test] - async fn set_max_age_changes_behavior() { + async fn set_max_delay_changes_behavior() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0)]); @@ -2140,7 +2143,7 @@ mod tests { let frame = consumer.read().await.unwrap().unwrap(); assert_eq!(frame.timestamp, ts(0)); - consumer.set_max_age(Duration::from_millis(100)); + consumer.set_max_delay(Duration::from_millis(100)); assert!(consumer.read().await.unwrap().is_none()); } @@ -2150,8 +2153,8 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(110))); - // max age must exceed (group1_max - group0_min) = 100ms - 0ms = 100ms + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(110))); + // max delay must exceed (group1_max - group0_min) = 100ms - 0ms = 100ms // to avoid the age skip and test B-frame timestamp tracking. let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); @@ -2203,7 +2206,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 3, &[ts(0)]); @@ -2260,7 +2263,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let _group5 = track.create_group(moq_net::group::Info { sequence: 5 }).unwrap(); @@ -2292,7 +2295,7 @@ mod tests { tokio::time::pause(); let track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Sequence 0 never arrives; sequence 1's stream opens but never carries a frame. @@ -2323,7 +2326,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Group 0's stream is open but its frames lose the race; the track boundary @@ -2362,7 +2365,7 @@ mod tests { async fn startup_single_group_mid_stream() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 100, &[ts(3_000_000)]); @@ -2380,7 +2383,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // The track is far along and stays live (never finished); only the current @@ -2400,7 +2403,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(50))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(50))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2437,7 +2440,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2468,7 +2471,7 @@ mod tests { } /// Regression: a single stalled group with one newer group should trigger - /// an age skip when the timestamp difference exceeds the max age. + /// a delay skip when the timestamp difference exceeds the max delay. /// Previously, the span was computed across newer groups only (zero for one /// group), so the skip never fired. #[tokio::test] @@ -2476,7 +2479,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = track.subscribe(None); - let mut consumer = container_max_age_only(consumer_track, Duration::from_millis(100)); + let mut consumer = container_max_delay_only(consumer_track, Duration::from_millis(100)); // Group 0: stalled at ts=0, NOT finished let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2492,7 +2495,7 @@ mod tests { ) .unwrap(); - // Group 1: finished, 200ms ahead (well beyond the 100ms max age) + // Group 1: finished, 200ms ahead (well beyond the 100ms max delay) write_group(&mut track, 1, &[ts(200_000)]); track.finish().unwrap(); @@ -2514,7 +2517,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = track.subscribe(None); - let mut consumer = container_max_age_only(consumer_track, Duration::from_millis(100)); + let mut consumer = container_max_delay_only(consumer_track, Duration::from_millis(100)); // Group 0: finished normally write_group(&mut track, 0, &[ts(0), ts(20_000)]); @@ -2530,7 +2533,7 @@ mod tests { async fn group_error_skips_to_next() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2551,7 +2554,7 @@ mod tests { async fn finished_group_aborted_mid_read_drains_then_continues() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2589,7 +2592,7 @@ mod tests { async fn oversized_group_skips_to_next() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2632,7 +2635,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); write_group(&mut track, 0, &[ts(0)]); @@ -2662,7 +2665,7 @@ mod tests { async fn empty_group_advances() { let mut track = track_producer("test", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); let group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -2683,7 +2686,7 @@ mod tests { let track = track_producer("video", hang::container::track_info(hang::catalog::PRIORITY.video)); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy(crate::container::Kind::Data)); // Write frames using Container::Legacy(crate::container::Kind::Data) encoding @@ -2719,7 +2722,7 @@ mod tests { // ---- Duration Skipping ---- /// A stalled group whose frame covers up to the next group's start is skipped - /// immediately, even with a max age budget far larger than the gap. Without + /// immediately, even with a max delay budget far larger than the gap. Without /// duration support the consumer would block on the unfinished group forever. #[tokio::test] async fn duration_skip_advances_to_next_group() { @@ -2728,8 +2731,8 @@ mod tests { // timestamps; leave the track untimed so model-layer validation matches. let track = track_producer("test", None); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); - // The max age dwarfs the gap, so only duration coverage can trigger the skip. + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(10))); + // The max delay dwarfs the gap, so only duration coverage can trigger the skip. let mut consumer = Consumer::new(consumer_track, DurationWire); // Group 0: one frame at ts=0 lasting 33ms, never finished. @@ -2766,7 +2769,7 @@ mod tests { async fn a_nonsequential_contiguous_jump_does_not_bump_playhead() { let track = track_producer("test", None); let mut consumer = Consumer::new( - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))), + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(10))), DurationWire, ); let mut group0 = track @@ -2797,7 +2800,7 @@ mod tests { // DurationWire is untimed at the moq_net frame layer. let track = track_producer("test", None); let consumer_track = - track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, DurationWire); // Group 0: frame at ts=0 lasting only 10ms, far short of group 1 at 33ms. diff --git a/rs/moq-mux/src/container/flv/export.rs b/rs/moq-mux/src/container/flv/export.rs index 04f362726cd..86a69c27055 100644 --- a/rs/moq-mux/src/container/flv/export.rs +++ b/rs/moq-mux/src/container/flv/export.rs @@ -105,7 +105,7 @@ impl Flavor { pub struct Export { source: crate::Source, catalog: Option, - max_age: std::time::Duration, + max_delay: std::time::Duration, /// Emit every rendition as an enhanced-RTMP multitrack track, rather than only /// the best video + first audio rendition. multitrack: bool, @@ -183,7 +183,7 @@ impl Export { Ok(Self { source, catalog: Some(catalog), - max_age: std::time::Duration::ZERO, + max_delay: std::time::Duration::ZERO, multitrack: false, select: None, video: Vec::new(), @@ -192,13 +192,13 @@ impl Export { }) } - /// Set the max age for each per-track source. + /// Set the max delay for each per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) (skip aggressively). - pub fn with_max_age(mut self, max_age: std::time::Duration) -> Self { - self.max_age = max_age; + pub fn with_max_delay(mut self, max_delay: std::time::Duration) -> Self { + self.max_delay = max_delay; self } @@ -385,7 +385,7 @@ impl Export { (VideoCodec::AV1(av1), None) => Some(Bytes::copy_from_slice(&av1c_bytes(av1))), _ => None, }; - let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_age)? else { + let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_delay)? else { continue; }; let track_id = u8::try_from(self.video.len()).context("too many FLV video tracks")?; @@ -415,7 +415,7 @@ impl Export { } let flavor = audio_flavor(config)?; ensure_legacy(&config.container, "audio", name)?; - let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_age)? else { + let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_delay)? else { continue; }; let track_id = u8::try_from(self.audio.len()).context("too many FLV audio tracks")?; diff --git a/rs/moq-mux/src/container/flv/export_test.rs b/rs/moq-mux/src/container/flv/export_test.rs index 1c1679db135..18529e3dc41 100644 --- a/rs/moq-mux/src/container/flv/export_test.rs +++ b/rs/moq-mux/src/container/flv/export_test.rs @@ -17,7 +17,7 @@ use super::{Export, Import}; /// and only then export it, which the /// exporter's default [`Duration::ZERO`] collapses to the /// live edge: completeness has to be asked for, exactly as a real recorder does. -const RECORDING_MAX_AGE: Duration = Duration::from_secs(30); +const RECORDING_MAX_DELAY: Duration = Duration::from_secs(30); /// A minimal `AVCDecoderConfigurationRecord` (profile 0x42, level 0x1f, one SPS + PPS). fn avcc() -> Vec { @@ -180,7 +180,7 @@ async fn export_emits_sequence_headers_and_frames() { let exporter = Export::new(crate::source::announced(&consumer)) .await .unwrap() - .with_max_age(RECORDING_MAX_AGE); + .with_max_delay(RECORDING_MAX_DELAY); let exported = drain_export(exporter, importer).await; let tags = parse_tags(&exported); @@ -1057,7 +1057,7 @@ async fn a_track_leaving_the_catalog_is_read_to_its_end() { let mut exporter = Export::new(crate::source::announced(&consumer)) .await .unwrap() - .with_max_age(RECORDING_MAX_AGE); + .with_max_delay(RECORDING_MAX_DELAY); let mut exported = Vec::new(); assert!(drain_until_idle(&mut exporter, &mut exported).await.is_none()); diff --git a/rs/moq-mux/src/container/flv/import_test.rs b/rs/moq-mux/src/container/flv/import_test.rs index a2fefd9a1fd..c3c3da49559 100644 --- a/rs/moq-mux/src/container/flv/import_test.rs +++ b/rs/moq-mux/src/container/flv/import_test.rs @@ -174,7 +174,7 @@ async fn import_emits_frames() { let track = consumer .track(&video_name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new( @@ -497,7 +497,7 @@ async fn import_enhanced_av1() { let track = consumer .track(name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new( @@ -607,7 +607,7 @@ async fn import_reports_negative_pts_and_can_resume() { let track = consumer .track(name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new( @@ -647,7 +647,7 @@ async fn import_enhanced_hvc1_applies_composition_time() { let track = consumer .track(name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new( diff --git a/rs/moq-mux/src/container/fmp4/export.rs b/rs/moq-mux/src/container/fmp4/export.rs index 4f5e2b3d58b..7d9784e8533 100644 --- a/rs/moq-mux/src/container/fmp4/export.rs +++ b/rs/moq-mux/src/container/fmp4/export.rs @@ -19,7 +19,7 @@ use moq_net::Timestamp; /// The init segment declares every track, so it waits until each one can be described; a /// track that needs its bitstream for that (an Annex-B H.264 or H.265 source, or video /// whose catalog leaves out its dimensions) holds it until a keyframe arrives. The other -/// tracks keep reading meanwhile, so they don't fall behind the subscription's max age, +/// tracks keep reading meanwhile, so they don't fall behind the subscription's max delay, /// and their fragments are written right after the init. A source that never delivers a /// keyframe would otherwise queue forever. const INIT_QUEUE: Duration = Duration::from_secs(30); @@ -55,7 +55,7 @@ const INIT_QUEUE: Duration = Duration::from_secs(30); pub struct Export { source: crate::Source, catalog: Option, - max_age: Duration, + max_delay: Duration, fragment_duration: Option, /// Every track by rendition name. Before the init a rendition that leaves the catalog @@ -152,10 +152,10 @@ enum Rendition { } impl Rendition { - fn subscribe(&self, source: &crate::Source, name: &str, max_age: Duration) -> Result> { + fn subscribe(&self, source: &crate::Source, name: &str, max_delay: Duration) -> Result> { match self { - Rendition::Video(config) => ExportSource::for_video(source, name, config, max_age), - Rendition::Audio(config) => ExportSource::for_audio(source, name, config, max_age), + Rendition::Video(config) => ExportSource::for_video(source, name, config, max_delay), + Rendition::Audio(config) => ExportSource::for_audio(source, name, config, max_delay), } } @@ -441,7 +441,7 @@ impl Export { Self { source, catalog: Some(catalog), - max_age: Duration::ZERO, + max_delay: Duration::ZERO, fragment_duration: None, tracks: HashMap::new(), queued: VecDeque::new(), @@ -451,13 +451,13 @@ impl Export { } } - /// Set the max age for each per-track source. + /// Set the max delay for each per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to /// [`Duration::ZERO`] (skip aggressively). - pub fn with_max_age(mut self, max_age: Duration) -> Self { - self.max_age = max_age; + pub fn with_max_delay(mut self, max_delay: Duration) -> Self { + self.max_delay = max_delay; self } @@ -791,7 +791,7 @@ impl Export { match self.tracks.get_mut(&name) { Some(track) if track.source.is_some() => track.reconfigure(&name, config)?, Some(track) => { - let Some(source) = config.subscribe(&self.source, &name, self.max_age)? else { + let Some(source) = config.subscribe(&self.source, &name, self.max_delay)? else { continue; }; track.rejoin(&name, config, source)?; @@ -799,7 +799,7 @@ impl Export { None => { // Subscribe via ExportSource, which applies any per-codec transform // (Annex-B → length-prefixed) at pull time. - let Some(source) = config.subscribe(&self.source, &name, self.max_age)? else { + let Some(source) = config.subscribe(&self.source, &name, self.max_delay)? else { continue; }; if self.init_emitted { diff --git a/rs/moq-mux/src/container/fmp4/export_test.rs b/rs/moq-mux/src/container/fmp4/export_test.rs index 34b91435b52..dbefeb16f26 100644 --- a/rs/moq-mux/src/container/fmp4/export_test.rs +++ b/rs/moq-mux/src/container/fmp4/export_test.rs @@ -12,7 +12,7 @@ use crate::container::test_util::{Live, PPS, SPS, raw_frame, video_frame}; /// and only then export it, which the /// exporter's default [`std::time::Duration::ZERO`](std::time::Duration::ZERO) collapses to the /// live edge: completeness has to be asked for, exactly as a real recorder does. -const RECORDING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30); /// Avc3-shape source (catalog `Container::Legacy`, `H264 { inline: true }`, /// `description: None`) → fMP4 / CMAF export must synthesize a valid init @@ -477,7 +477,7 @@ async fn single_track_export_init_matches_fragment_track_id() { .expect("catalog consumer"); let selected = catalog_stream.select(crate::select::Broadcast::default().audio(crate::select::Audio::default())); let mut exporter = crate::container::fmp4::Export::new(crate::source::announced(&consumer), selected) - .with_max_age(RECORDING_MAX_AGE); + .with_max_delay(RECORDING_MAX_DELAY); let init = tokio::time::timeout(std::time::Duration::from_secs(1), exporter.next()) .await @@ -540,7 +540,7 @@ async fn next_chunk_reports_segment_metadata() { // Sub-GOP cap so GOP 0 splits into two parts (the trailing part non-independent). let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) .with_fragment_duration(std::time::Duration::from_millis(20)) - .with_max_age(RECORDING_MAX_AGE); + .with_max_delay(RECORDING_MAX_DELAY); // First emit is the init segment, which carries no segmenting metadata to assert on. chunk_now(&mut exporter) @@ -709,8 +709,8 @@ async fn one_packet_audio_group_is_timed_by_the_catalog() { .write(raw_frame(500_000, &[0x01, 0x02, 0x03, 0x04], true)) .unwrap(); - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); chunk_now(&mut exporter) .await .init() @@ -741,8 +741,8 @@ async fn audio_fragment_is_the_publisher_group() { .unwrap(); } - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); chunk_now(&mut exporter) .await .init() @@ -758,7 +758,7 @@ async fn audio_fragment_is_the_publisher_group() { ); // The one-frame-per-fragment mode is the explicit way back to per-packet output. let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) - .with_max_age(RECORDING_MAX_AGE) + .with_max_delay(RECORDING_MAX_DELAY) .with_fragment_duration(std::time::Duration::ZERO); chunk_now(&mut exporter).await.init().expect("init"); let fragment = chunk_now(&mut exporter).await.fragment().expect("a media fragment"); @@ -773,8 +773,8 @@ async fn closed_audio_group_flushes_without_a_successor() { let mut live = Live::audio(AudioConfig::new(AudioCodec::Opus, 48_000, 2)); live.track.write(raw_frame(0, &[0x08, 0xaa], true)).unwrap(); live.track.write(raw_frame(20_000, &[0x08, 0xbb], false)).unwrap(); - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); chunk_now(&mut exporter).await.init().expect("init"); assert!( drain_now(&mut exporter).await.is_empty(), @@ -806,8 +806,8 @@ async fn uncut_audio_waits_for_the_explicit_cap() { .unwrap(); } - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); chunk_now(&mut exporter).await.init().expect("init"); assert!( drain_now(&mut exporter).await.is_empty(), @@ -815,7 +815,7 @@ async fn uncut_audio_waits_for_the_explicit_cap() { ); let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) - .with_max_age(RECORDING_MAX_AGE) + .with_max_delay(RECORDING_MAX_DELAY) .with_fragment_duration(std::time::Duration::from_millis(200)); chunk_now(&mut exporter).await.init().expect("init"); let fragments = drain_now(&mut exporter).await; @@ -839,8 +839,8 @@ async fn opus_frame_duration_from_toc() { .write(raw_frame(20_000, &[0x08, 0xaa, 0xbb, 0xcc], true)) .unwrap(); - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); chunk_now(&mut exporter) .await .init() @@ -979,7 +979,7 @@ fn a_long_gop_does_not_cost_a_stack_frame_per_sample() { live.track.write(video_frame(600 * 16_666, true)).unwrap(); let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) - .with_max_age(RECORDING_MAX_AGE); + .with_max_delay(RECORDING_MAX_DELAY); assert!( chunk_now(&mut exporter).await.init().is_some(), "first chunk must be the init segment" @@ -1037,8 +1037,8 @@ async fn export_av(group: u64) -> (Vec<(u32, usize)>, (u32, u32)) { live.track.finish().unwrap(); audio.finish().unwrap(); - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); let init = chunk_now(&mut exporter).await.init().expect("init"); let ids = track_ids(&init); @@ -1104,8 +1104,8 @@ async fn video_that_ends_first_writes_its_tail_in_order() { .unwrap(); } - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); let init = chunk_now(&mut exporter).await.init().expect("init"); let (video_id, audio_id) = track_ids(&init); @@ -1280,8 +1280,8 @@ async fn video_cut_preserves_the_exact_duration_without_a_successor() { let mut live = Live::avc3(); live.track.write(video_frame(0, true)).unwrap(); live.track.write(video_frame(10_000, false)).unwrap(); - let mut exporter = - crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await).with_max_age(RECORDING_MAX_AGE); + let mut exporter = crate::container::fmp4::Export::new(live.source(), live.catalog_stream().await) + .with_max_delay(RECORDING_MAX_DELAY); chunk_now(&mut exporter).await.init().expect("init"); assert!(drain_now(&mut exporter).await.is_empty()); live.track @@ -1330,14 +1330,14 @@ async fn error_now(exporter: &mut crate::container::fmp4::Export moq_net::track::Subscription { - moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE) + moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_DELAY) } /// Drain every group currently buffered on the consumer without waiting for new ones. diff --git a/rs/moq-mux/src/container/group.rs b/rs/moq-mux/src/container/group.rs index d8a08cf75ee..c7888e09c63 100644 --- a/rs/moq-mux/src/container/group.rs +++ b/rs/moq-mux/src/container/group.rs @@ -9,7 +9,7 @@ use super::{Container, Frame}; /// subscribes to a track and juggles group ordering, age skipping, and rewinds, this one /// reads exactly the group it was handed, in arrival order, and ends. That is what a caller /// wants after a FETCH: a group already chosen by sequence, with no live subscription and no -/// max age budget that could skip the very group being asked for. +/// max delay budget that could skip the very group being asked for. /// /// A batch of frames decoded from one wire frame (a CMAF fragment carrying several samples) is /// handed back one frame at a time. diff --git a/rs/moq-mux/src/container/mkv/export.rs b/rs/moq-mux/src/container/mkv/export.rs index ae365df55e6..1327f379697 100644 --- a/rs/moq-mux/src/container/mkv/export.rs +++ b/rs/moq-mux/src/container/mkv/export.rs @@ -47,7 +47,7 @@ const TIMESTAMP_SCALE_NS: u64 = 1_000_000; pub struct Export { source: crate::Source, catalog: Option, - max_age: Duration, + max_delay: Duration, fragment_duration: Option, tracks: HashMap, @@ -162,7 +162,7 @@ impl Export { Self { source, catalog: Some(catalog), - max_age: Duration::ZERO, + max_delay: Duration::ZERO, fragment_duration: None, tracks: HashMap::new(), catalog_snapshot: None, @@ -171,13 +171,13 @@ impl Export { } } - /// Set the max age for each per-track source. + /// Set the max delay for each per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to /// [`Duration::ZERO`] (skip aggressively). - pub fn with_max_age(mut self, max_age: Duration) -> Self { - self.max_age = max_age; + pub fn with_max_delay(mut self, max_delay: Duration) -> Self { + self.max_delay = max_delay; self } @@ -340,7 +340,7 @@ impl Export { continue; } ensure_legacy(&config.container, "video", name)?; - let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_age)? else { + let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_delay)? else { continue; }; self.tracks.insert( @@ -361,7 +361,7 @@ impl Export { continue; } ensure_legacy(&config.container, "audio", name)?; - let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_age)? else { + let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_delay)? else { continue; }; self.tracks.insert( diff --git a/rs/moq-mux/src/container/mkv/export_test.rs b/rs/moq-mux/src/container/mkv/export_test.rs index 95a7fe72c3d..e0b9d5d1057 100644 --- a/rs/moq-mux/src/container/mkv/export_test.rs +++ b/rs/moq-mux/src/container/mkv/export_test.rs @@ -20,7 +20,7 @@ use crate::container::test_util::{IDR, Live, PPS, SPS, raw_frame, video_frame}; /// export it, which the exporter's default /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) collapses to the live edge: /// completeness has to be asked for, exactly as a real recorder does. -const RECORDING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30); #[tokio::test(start_paused = true)] async fn export_header_roundtrip_vp9_opus() { @@ -377,7 +377,7 @@ async fn export_emits_blocks_for_each_frame() { // Use per-frame clustering so each frame is observable as its own // Cluster chunk; batching is exercised in a dedicated test below. .with_fragment_duration(std::time::Duration::ZERO) - .with_max_age(RECORDING_MAX_AGE); + .with_max_delay(RECORDING_MAX_DELAY); let mut exported: Vec = Vec::new(); let mut importer = Some(importer); @@ -616,7 +616,7 @@ async fn export_fragment_duration_batches_blocks() { .expect("catalog consumer"); let mut exporter = crate::container::mkv::Export::new(crate::source::announced(&consumer), catalog_stream) .with_fragment_duration(std::time::Duration::from_secs(2)) - .with_max_age(RECORDING_MAX_AGE); + .with_max_delay(RECORDING_MAX_DELAY); let mut exported: Vec = Vec::new(); let mut importer = Some(importer); diff --git a/rs/moq-mux/src/container/mod.rs b/rs/moq-mux/src/container/mod.rs index ace07333298..0cc44b14c75 100644 --- a/rs/moq-mux/src/container/mod.rs +++ b/rs/moq-mux/src/container/mod.rs @@ -68,7 +68,7 @@ pub struct Frame { /// muxers receive the later endpoint separately, so media stays immediately available. /// The [`Consumer`] adds it to `timestamp` to learn how far a group has /// presented, so it can advance to a newer group as soon as the gap is - /// covered instead of waiting out the max age budget. + /// covered instead of waiting out the max delay budget. pub duration: Option, /// Encoded codec payload. diff --git a/rs/moq-mux/src/container/producer.rs b/rs/moq-mux/src/container/producer.rs index 13ae3383065..a197c9cc4ce 100644 --- a/rs/moq-mux/src/container/producer.rs +++ b/rs/moq-mux/src/container/producer.rs @@ -343,7 +343,7 @@ where /// it, or a keyframe arrives, packing multiple samples into one container frame (e.g. a CMAF /// moof+mdat). Zero (the default) flushes each frame immediately. /// - /// This is the publisher-side counterpart to the consumer's max age, and the one + /// This is the publisher-side counterpart to the consumer's max delay, and the one /// knob here that genuinely *adds* delay. pub fn with_buffer(mut self, duration: std::time::Duration) -> Self { self.buffer_duration = duration; @@ -782,12 +782,12 @@ mod tests { /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) budget collapses to the live /// edge: history has to be asked for. fn replay() -> moq_net::track::Subscription { - moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE) + moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_DELAY) } /// The media track's full retention window, so readers started after publishing /// can still consume every retained group. - const RECORDING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(30); + const RECORDING_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30); fn frame(timestamp_us: u64, keyframe: bool) -> Frame { Frame { @@ -1058,7 +1058,7 @@ mod tests { let discontinuity_max_age = std::time::Duration::from_secs(41 * 60); let info = hang::container::track_info(hang::catalog::PRIORITY.audio).with_max_age(discontinuity_max_age); let track = track_producer("test", info); - let consumer = track.subscribe(moq_net::track::Subscription::default().with_max_age(discontinuity_max_age)); + let consumer = track.subscribe(moq_net::track::Subscription::default().with_max_delay(discontinuity_max_age)); let mut producer = Producer::new(track, Container::Legacy(crate::container::Kind::Audio)); producer.write(frame(0, true)).unwrap(); diff --git a/rs/moq-mux/src/container/source.rs b/rs/moq-mux/src/container/source.rs index 07a7ba13e4f..b3f4c9a879d 100644 --- a/rs/moq-mux/src/container/source.rs +++ b/rs/moq-mux/src/container/source.rs @@ -65,7 +65,7 @@ pub(crate) struct ExportSource { state: SourceState, /// Wire format, consumed when the subscription resolves into a consumer. media: Option, - max_age: std::time::Duration, + max_delay: std::time::Duration, transform: Option, /// Resolved codec configuration record (avcC / hvcC / AudioSpecificConfig / /// OpusHead). Some once the codec config is available — from the catalog @@ -88,9 +88,9 @@ impl ExportSource { source: &crate::Source, name: &str, config: &VideoConfig, - max_age: std::time::Duration, + max_delay: std::time::Duration, ) -> Result, crate::Error> { - Self::video(source, name, config, max_age, build_video_transform(config)) + Self::video(source, name, config, max_delay, build_video_transform(config)) } /// Subscribe to a video rendition without attaching any codec-shape @@ -103,16 +103,16 @@ impl ExportSource { source: &crate::Source, name: &str, config: &VideoConfig, - max_age: std::time::Duration, + max_delay: std::time::Duration, ) -> Result, crate::Error> { - Self::video(source, name, config, max_age, None) + Self::video(source, name, config, max_delay, None) } fn video( source: &crate::Source, name: &str, config: &VideoConfig, - max_age: std::time::Duration, + max_delay: std::time::Duration, transform: Option, ) -> Result, crate::Error> { let media: HangContainer = config.try_into()?; @@ -124,7 +124,7 @@ impl ExportSource { let mut source = Self { state: SourceState::Requesting(request, name.to_string()), media: Some(media), - max_age, + max_delay, transform, description, video_codec: Some(config.codec.clone()), @@ -142,7 +142,7 @@ impl ExportSource { source: &crate::Source, name: &str, config: &AudioConfig, - max_age: std::time::Duration, + max_delay: std::time::Duration, ) -> Result, crate::Error> { let media: HangContainer = config.try_into()?; let description = config.description.as_ref().filter(|b| !b.is_empty()).cloned(); @@ -153,7 +153,7 @@ impl ExportSource { Ok(Some(Self { state: SourceState::Requesting(request, name.to_string()), media: Some(media), - max_age, + max_delay, transform: None, description, video_codec: None, @@ -167,11 +167,15 @@ impl ExportSource { /// /// Such a rendition has no catalog `broadcast` field, so it always lives on the /// catalog broadcast and can never carry an escaping reference. - pub fn for_stream(source: &crate::Source, name: &str, max_age: std::time::Duration) -> Result { + pub fn for_stream( + source: &crate::Source, + name: &str, + max_delay: std::time::Duration, + ) -> Result { Ok(Self { state: SourceState::Requesting(source.request_catalog(), name.to_string()), media: Some(HangContainer::Legacy(crate::container::Kind::Data)), - max_age, + max_delay, transform: None, description: None, video_codec: None, @@ -250,7 +254,7 @@ impl ExportSource { }; (ready!(pending.poll_ok(waiter))?, name.clone()) }; - let subscription = moq_net::track::Subscription::default().with_max_age(self.max_age); + let subscription = moq_net::track::Subscription::default().with_max_delay(self.max_delay); self.state = SourceState::Subscribing(broadcast.track(&name)?.subscribe(subscription)); } @@ -412,7 +416,7 @@ mod tests { async fn escaping_reference_skips_the_rendition() { let live = Live::avc3(); let source = live.source(); - let max_age = std::time::Duration::ZERO; + let max_delay = std::time::Duration::ZERO; let escaping = |result: Result, crate::Error>, what: &str| match result { Ok(None) => {} @@ -424,13 +428,13 @@ mod tests { // single-segment path, so its parent is the root and any `..` walks above it. for reference in ["..", "../source", "../../elsewhere"] { let config = video(Some(reference)); - escaping(ExportSource::for_video(&source, "video", &config, max_age), reference); + escaping(ExportSource::for_video(&source, "video", &config, max_delay), reference); escaping( - ExportSource::for_video_raw(&source, "video", &config, max_age), + ExportSource::for_video_raw(&source, "video", &config, max_delay), reference, ); escaping( - ExportSource::for_audio(&source, "audio", &audio(Some(reference)), max_age), + ExportSource::for_audio(&source, "audio", &audio(Some(reference)), max_delay), reference, ); } @@ -442,13 +446,13 @@ mod tests { async fn legal_reference_keeps_the_rendition() { let live = Live::avc3(); let source = live.source(); - let max_age = std::time::Duration::ZERO; + let max_delay = std::time::Duration::ZERO; for reference in [None, Some(""), Some("./source"), Some("sub"), Some(".")] { - ExportSource::for_video(&source, "video", &video(reference), max_age) + ExportSource::for_video(&source, "video", &video(reference), max_delay) .unwrap_or_else(|err| panic!("{reference:?} should keep the rendition: {err:?}")) .unwrap_or_else(|| panic!("{reference:?} should keep the rendition")); - ExportSource::for_audio(&source, "audio", &audio(reference), max_age) + ExportSource::for_audio(&source, "audio", &audio(reference), max_delay) .unwrap_or_else(|err| panic!("{reference:?} should keep the rendition: {err:?}")) .unwrap_or_else(|| panic!("{reference:?} should keep the rendition")); } @@ -459,20 +463,20 @@ mod tests { #[tokio::test] async fn latency_is_sent_with_the_initial_subscription() { let live = Live::avc3(); - let max_age = std::time::Duration::from_secs(10); - let mut export = ExportSource::for_video(&live.source(), live.track.name(), &video(None), max_age) + let max_delay = std::time::Duration::from_secs(10); + let mut export = ExportSource::for_video(&live.source(), live.track.name(), &video(None), max_delay) .unwrap() .expect("fixture should produce a video rendition"); let observed = kio::wait(|waiter| { let _ = export.poll_read(waiter); match live.track.subscription() { - Some(subscription) => Poll::Ready(subscription.max_age), + Some(subscription) => Poll::Ready(subscription.max_delay), None => Poll::Pending, } }) .await; - assert_eq!(observed, max_age); + assert_eq!(observed, max_delay); } } diff --git a/rs/moq-mux/src/container/test_util.rs b/rs/moq-mux/src/container/test_util.rs index d73a3c7e3cd..f577875ed45 100644 --- a/rs/moq-mux/src/container/test_util.rs +++ b/rs/moq-mux/src/container/test_util.rs @@ -147,7 +147,7 @@ pub(crate) async fn published( let mut out = std::collections::BTreeMap::new(); for (name, container) in containers { - let replay = moq_net::track::Subscription::default().with_max_age(std::time::Duration::from_secs(3600)); + let replay = moq_net::track::Subscription::default().with_max_delay(std::time::Duration::from_secs(3600)); let track = consumer.track(&name).unwrap().subscribe(replay).await.unwrap(); let mut reader = crate::container::Consumer::new(track, container); let mut timestamps = Vec::new(); diff --git a/rs/moq-mux/src/container/ts/export.rs b/rs/moq-mux/src/container/ts/export.rs index b44d282a188..50fa3979d38 100644 --- a/rs/moq-mux/src/container/ts/export.rs +++ b/rs/moq-mux/src/container/ts/export.rs @@ -592,7 +592,7 @@ impl SiTrack { self.state = match resolved { Ok((broadcast, name)) => match broadcast.track(&name) { Ok(track) => SiState::Subscribing( - track.subscribe(moq_net::track::Subscription::default().with_max_age(self.max_age)), + track.subscribe(moq_net::track::Subscription::default().with_max_delay(self.max_age)), ), Err(err) => { tracing::warn!(%err, track = %name, "SI track unavailable; carrying the last snapshot"); diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index 852fda03482..5f1dd5bfe65 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -1084,7 +1084,7 @@ async fn export_scte35_roundtrip() { let track = consumer2 .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut scte_reader = crate::container::Consumer::new(track, HangContainer::Legacy(crate::container::Kind::Data)); @@ -1197,7 +1197,7 @@ async fn export_pes_verbatim_roundtrip() { let track = consumer2 .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy(crate::container::Kind::Data)); @@ -1272,7 +1272,7 @@ async fn read_frames(consumer: &moq_net::broadcast::Consumer, name: &str, kind: let track = consumer .track(name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy(kind)); @@ -1738,7 +1738,7 @@ async fn read_cues(consumer: &moq_net::broadcast::Consumer, name: &str) -> Vec<( let track = consumer .track(name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy(crate::container::Kind::Data)); @@ -1920,7 +1920,7 @@ async fn read_si_groups(consumer: &moq_net::broadcast::Consumer, name: &str) -> .subscribe( moq_net::track::Subscription::default() .with_start(moq_net::track::Position::group(0)) - .with_max_age(Duration::from_secs(5)), + .with_max_delay(Duration::from_secs(5)), ) .await .unwrap(); diff --git a/rs/moq-mux/src/container/ts/import.rs b/rs/moq-mux/src/container/ts/import.rs index 3e59672d5e4..3f574b52032 100644 --- a/rs/moq-mux/src/container/ts/import.rs +++ b/rs/moq-mux/src/container/ts/import.rs @@ -3420,7 +3420,7 @@ pub(super) mod test { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy(crate::container::Kind::Data)); @@ -3906,7 +3906,7 @@ pub(super) mod test { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new( @@ -4785,7 +4785,7 @@ pub(super) mod test { let track = consumer .track(hang::catalog::Catalog::DEFAULT_NAME) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new( @@ -5052,7 +5052,7 @@ pub(super) mod test { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy(crate::container::Kind::Data)); @@ -5238,7 +5238,7 @@ pub(super) mod test { let track = consumer .track(name.as_str()) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy(crate::container::Kind::Data)); @@ -5325,10 +5325,10 @@ pub(super) mod test { /// Read every retained frame of `name`, with the count of timeline breaks the consumer /// crossed reading them. async fn read_breaks(consumer: &moq_net::broadcast::Consumer, name: &str) -> (Vec, u64) { - // A generous max age: the default of zero would shed every non-latest group, the + // A generous max delay: the default of zero would shed every non-latest group, the // declared breaks among them, and the subscribe start is resolved from it too, so // it has to reach back past a 30 s leap to the first frame. - let subscription = moq_net::track::Subscription::default().with_max_age(std::time::Duration::from_secs(3600)); + let subscription = moq_net::track::Subscription::default().with_max_delay(std::time::Duration::from_secs(3600)); let track = consumer.track(name).unwrap().subscribe(subscription).await.unwrap(); let mut reader = crate::container::Consumer::new( track, @@ -5937,7 +5937,7 @@ pub(super) mod test { name: &str, kind: crate::container::Kind, ) -> Vec { - let subscription = moq_net::track::Subscription::default().with_max_age(Duration::from_secs(3600)); + let subscription = moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(3600)); let track = consumer.track(name).unwrap().subscribe(subscription).await.unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy(kind)); let mut frames = Vec::new(); @@ -6350,7 +6350,7 @@ pub(super) mod test { // Each group as published, its empty end marker included. let name = catalog.snapshot().video.renditions.keys().next().unwrap().clone(); - let subscription = moq_net::track::Subscription::default().with_max_age(Duration::from_secs(3600)); + let subscription = moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(3600)); let mut track = consumer.track(&name).unwrap().subscribe(subscription).await.unwrap(); let mut groups = Vec::new(); while let Some(mut group) = track.recv_group().await.unwrap() { diff --git a/rs/moq-mux/src/container/ts/import_test.rs b/rs/moq-mux/src/container/ts/import_test.rs index 07454dab93d..e9009b4e929 100644 --- a/rs/moq-mux/src/container/ts/import_test.rs +++ b/rs/moq-mux/src/container/ts/import_test.rs @@ -248,7 +248,7 @@ async fn import_opus_frames() { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new( @@ -526,7 +526,7 @@ async fn survives_midstream_join() { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new( @@ -580,7 +580,7 @@ async fn kyrion_dirtystart_extracts_real_cues() { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new( diff --git a/rs/moq-mux/src/import/track.rs b/rs/moq-mux/src/import/track.rs index a245680ca63..49971acc583 100644 --- a/rs/moq-mux/src/import/track.rs +++ b/rs/moq-mux/src/import/track.rs @@ -1038,7 +1038,8 @@ mod tests { .unwrap(); // Every group is written before anything reads, which the default // REAL_TIME budget would collapse to the live edge. - let subscriber = track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(30))); + let subscriber = + track.subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(30))); let config = crate::codec::opus::Config::new(48_000, 2); let import = crate::codec::opus::Import::new(track, catalog.reserve(), config.into()).unwrap(); (import, subscriber) diff --git a/rs/moq-net/benches/group.rs b/rs/moq-net/benches/group.rs index 19520bf2059..ef03691d70c 100644 --- a/rs/moq-net/benches/group.rs +++ b/rs/moq-net/benches/group.rs @@ -213,7 +213,7 @@ fn filled_track(n: usize, payload: &Bytes) -> TrackCtx { /// Request the full cache window instead of the default live edge. fn replay() -> track::Subscription { track::Subscription::default() - .with_max_age(Duration::MAX) + .with_max_delay(Duration::MAX) .with_start(track::Position::group(0)) } diff --git a/rs/moq-net/benches/track.rs b/rs/moq-net/benches/track.rs index 908227f2214..6a52f734e2b 100644 --- a/rs/moq-net/benches/track.rs +++ b/rs/moq-net/benches/track.rs @@ -408,7 +408,8 @@ fn bench_parked_read(c: &mut Criterion) { let mut held: Vec<_> = waiters .iter() .map(|waiter| { - let mut sub = track.subscribe(track::Subscription::default().with_max_age(Duration::from_secs(1))); + let mut sub = + track.subscribe(track::Subscription::default().with_max_delay(Duration::from_secs(1))); let Poll::Ready(Ok(Some(mut head))) = sub.poll_recv_group(waiter) else { panic!("head is cached"); }; diff --git a/rs/moq-net/src/fuzz.rs b/rs/moq-net/src/fuzz.rs index e2a75b59dd5..c4275c592ec 100644 --- a/rs/moq-net/src/fuzz.rs +++ b/rs/moq-net/src/fuzz.rs @@ -331,7 +331,7 @@ impl LiteSample { broadcast: Path::new("room/alice"), track: "video".into(), priority: 2, - max_age: std::time::Duration::from_secs(10), + max_delay: std::time::Duration::from_secs(10), start_group: None, end_group: None, start_frame: 0, @@ -515,7 +515,7 @@ impl Default for Messages { broadcast: Path::new("room/alice"), track: "video".into(), priority: 3, - max_age: Duration::from_millis(500), + max_delay: Duration::from_millis(500), start_group: Some(1_000), end_group: None, start_frame: 0, @@ -523,7 +523,7 @@ impl Default for Messages { }, lite_update: lite::SubscribeUpdate { priority: 4, - max_age: Duration::from_millis(500), + max_delay: Duration::from_millis(500), start_group: Some(1_000), end_group: Some(2_000), start_frame: 0, diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 54bf615531a..43f885b8aed 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -23,16 +23,16 @@ use crate::{ use super::{Message, Version, cluster, error::request, peer}; /// Largest millisecond duration every implementation can carry losslessly. -const MAX_SAFE_AGE_MS: u64 = (1_u64 << 53) - 1; +const MAX_SAFE_DELAY_MS: u64 = (1_u64 << 53) - 1; /// Build the serving-side subscription for a peer whose wire protocol carries no -/// max age preference. The receiver applies its own budget after the transfer. +/// max delay preference. The receiver applies its own budget after the transfer. fn serving_subscription(subscriber_priority: u8) -> Subscription { Subscription { priority: super::priority::from_wire(subscriber_priority), // Demand can cross a Lite hop before the producer's retention bound is // known, so use the largest duration that remains wire-encodable. - max_age: Duration::from_millis(MAX_SAFE_AGE_MS), + max_delay: Duration::from_millis(MAX_SAFE_DELAY_MS), ..Default::default() } } @@ -4984,7 +4984,7 @@ mod tests { slot } - /// moq-transport cannot carry the receiver's max age budget, so the serving + /// moq-transport cannot carry the receiver's max delay budget, so the serving /// subscription must preserve everything the producer still retains. #[test] fn serving_subscription_keeps_retained_backlog() { @@ -4998,7 +4998,7 @@ mod tests { } let subscription = serving_subscription(128); - assert_eq!(subscription.max_age.as_millis(), MAX_SAFE_AGE_MS as u128); + assert_eq!(subscription.max_delay.as_millis(), MAX_SAFE_DELAY_MS as u128); let mut subscriber = producer.subscribe(subscription); for sequence in [0, 1] { let group = subscriber diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index ceb5bd8f5cd..56d7720cf92 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -7856,11 +7856,11 @@ mod stitch_tests { ], ) .with_joining(JoiningFetch::Absolute { group_id: START }, FETCH, largest); - // Keep every fetched group: the default max-age of zero would drop each one as + // Keep every fetched group: the default max delay of zero would drop each one as // its successor arrives, and the stitch would hang waiting on a group already skipped. let mut consumer = h .track - .subscribe(track::Subscription::default().with_max_age(Duration::from_secs(60))); + .subscribe(track::Subscription::default().with_max_delay(Duration::from_secs(60))); let mut fill = h.stream().await; let mut tail = h.stream().await; diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 68005b99aca..e28fc3dc9ee 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -67,7 +67,7 @@ struct Shared { } /// Largest millisecond duration every implementation can carry losslessly. -const MAX_SAFE_AGE_MS: u64 = (1_u64 << 53) - 1; +const MAX_SAFE_DELAY_MS: u64 = (1_u64 << 53) - 1; /// The budget to serve a peer with, given what its wire could tell us. /// @@ -76,23 +76,23 @@ const MAX_SAFE_AGE_MS: u64 = (1_u64 << 53) - 1; /// as real time would discard backlog a legacy subscriber never declined, so fall /// back to a window wide enough not to drop and leave enforcement to the receiver, /// exactly as the IETF path does for the same reason. -fn serving_max_age(version: Version, requested: Duration) -> Duration { - match version.carries_max_age() { +fn serving_max_delay(version: Version, requested: Duration) -> Duration { + match version.carries_max_delay() { true => requested, - false => Duration::from_millis(MAX_SAFE_AGE_MS), + false => Duration::from_millis(MAX_SAFE_DELAY_MS), } } /// Position a subscription's read cursor for the wire serving it. /// /// On lite-06 there is nothing to do: `Consumer::subscribe` resolves the cursor from the -/// subscription itself, at the oldest group its own Max Age still considers fresh, floored +/// subscription itself, at the oldest group its own max delay still considers fresh, floored /// at the group it named. /// /// Pre-06 wires are the exception: their drafts define an absent `Group Start` as the /// latest group, so say so explicitly rather than letting the budget reach back. Lite03-05 -/// carry a Max Age, but there it is a staleness tolerance only; Lite01/02 additionally get -/// an unbounded budget so nothing is dropped under them (see [`serving_max_age`]), which +/// carry a `Subscriber Max Age`, but there it is a staleness tolerance only; Lite01/02 additionally get +/// an unbounded budget so nothing is dropped under them (see [`serving_max_delay`]), which /// must not read as a request to replay the whole cache on join. /// /// `latest` is the newest group when the SUBSCRIBE arrived, not once the subscription @@ -1250,7 +1250,7 @@ impl Request for SubscribeServe { fn start(shared: &Shared, msg: Self::Message, broadcast: crate::broadcast::Consumer) -> Result { let subscription = crate::track::Subscription { priority: msg.priority, - max_age: serving_max_age(shared.version, msg.max_age), + max_delay: serving_max_delay(shared.version, msg.max_delay), ..Bounds::from(&msg).positions() }; @@ -1317,7 +1317,7 @@ impl Request for SubscribeServe { if !shared.version.has_track_stream() { let info = lite::SubscribeOk { priority: msg.priority, - max_age: Duration::ZERO, + max_delay: Duration::ZERO, start_group: None, end_group: None, }; @@ -1560,7 +1560,7 @@ mod test { // What run_subscribe hands the model for a peer that sent no budget at all. let served = |version| { producer.subscribe( - track::Subscription::default().with_max_age(serving_max_age(version, std::time::Duration::ZERO)), + track::Subscription::default().with_max_delay(serving_max_delay(version, std::time::Duration::ZERO)), ) }; let drain = |subscriber: &mut track::Subscriber| { @@ -1585,13 +1585,13 @@ mod test { // Lite03-05 declare a budget, but their drafts define it as a staleness tolerance // and an absent start as the latest group, so they are pinned all the same. let mut tolerant = - producer.subscribe(track::Subscription::default().with_max_age(std::time::Duration::from_secs(5))); + producer.subscribe(track::Subscription::default().with_max_delay(std::time::Duration::from_secs(5))); position_cursor(&mut tolerant, Version::Lite05, None, producer.latest()); assert_eq!(drain(&mut tolerant), vec![2]); // On lite-06 the declared budget is what resolves the start, so it stands. let mut declared = - producer.subscribe(track::Subscription::default().with_max_age(std::time::Duration::from_secs(5))); + producer.subscribe(track::Subscription::default().with_max_delay(std::time::Duration::from_secs(5))); position_cursor(&mut declared, Version::Lite06, None, producer.latest()); assert_eq!(drain(&mut declared), vec![0, 1, 2]); } @@ -1698,7 +1698,7 @@ mod test { use futures::FutureExt; let mut producer = track_producer("test"); - let mut subscriber = producer.subscribe(track::Subscription::default().with_max_age(Duration::from_secs(5))); + let mut subscriber = producer.subscribe(track::Subscription::default().with_max_delay(Duration::from_secs(5))); producer.create_group(group::Info { sequence: 2 }).unwrap(); match recv_next(&mut subscriber, false, false).await.unwrap() { @@ -1714,7 +1714,7 @@ mod test { None => panic!("the late-arriving group was skipped"), } - // Staleness is the max age window's job, not arrival order's: the track + // Staleness is the max delay window's job, not arrival order's: the track // still finishes normally afterward. producer.finish_at(3).unwrap(); match recv_next(&mut subscriber, false, false).await.unwrap() { @@ -2394,7 +2394,7 @@ impl TrackRun { let bounds = Bounds::from(&upd); let _ = self.track.update(crate::track::Subscription { priority: upd.priority, - max_age: serving_max_age(self.ctx.version, upd.max_age), + max_delay: serving_max_delay(self.ctx.version, upd.max_delay), ..bounds.positions() }); if let Some(start_group) = upd.start_group { @@ -3041,7 +3041,7 @@ mod serve_group_test { assert_eq!(log.resets(), vec![crate::StreamError::Old.to_code()]); } - /// A subscription group keeps checking the max age while a transport write is + /// A subscription group keeps checking the max delay while a transport write is /// flow-control blocked, so a stalled send cannot pin the stream indefinitely. #[moq_net_sim::test] async fn blocked_transport_write_expires_with_the_group() { @@ -3146,7 +3146,7 @@ mod serve_group_test { assert_eq!(log.resets(), vec![crate::StreamError::Old.to_code()]); } - /// A subscription group keeps checking the max age while transport stream credit is + /// A subscription group keeps checking the max delay while transport stream credit is /// exhausted, so returning credit is reserved for content that is still live. #[moq_net_sim::test] async fn blocked_transport_open_expires_with_the_group() { @@ -3188,7 +3188,7 @@ mod serve_group_test { assert!(matches!(serve.await, Err(Error::Old))); } - /// Lite01/02 have no max age field, so a SUBSCRIBE from one decodes as + /// Lite01/02 have no max delay field, so a SUBSCRIBE from one decodes as /// `Duration::ZERO`. Serving that as a real-time budget would hold every legacy /// peer to the live edge and discard backlog it never declined, so those versions /// get a non-dropping window and leave enforcement to the receiver. @@ -3198,17 +3198,17 @@ mod serve_group_test { #[test] fn a_version_without_the_field_serves_a_non_dropping_budget() { for version in [Version::Lite01, Version::Lite02] { - let max_age = serving_max_age(version, Duration::ZERO); + let max_delay = serving_max_delay(version, Duration::ZERO); assert!( - max_age >= Duration::from_secs(86_400), - "{version:?} must not be served as real time: {max_age:?}" + max_delay >= Duration::from_secs(86_400), + "{version:?} must not be served as real time: {max_delay:?}" ); } // A version that does carry it is taken at its word, zero included. - assert_eq!(serving_max_age(Version::Lite05, Duration::ZERO), Duration::ZERO); + assert_eq!(serving_max_delay(Version::Lite05, Duration::ZERO), Duration::ZERO); assert_eq!( - serving_max_age(Version::Lite05, Duration::from_secs(3)), + serving_max_delay(Version::Lite05, Duration::from_secs(3)), Duration::from_secs(3) ); } @@ -3412,7 +3412,7 @@ mod serve_group_test { track.request_start(Some(0)).unwrap(); let subscription = track::Subscription::default() .with_start(track::Position::group(start_group)) - .with_max_age(Duration::from_secs(30)); + .with_max_delay(Duration::from_secs(30)); let subscriber = track.subscribe(subscription); let session = ScriptedSession::new(Vec::new()); @@ -3480,7 +3480,7 @@ mod serve_group_test { // The subscriber moves its start past the held group before the source resolves. let update = lite::SubscribeUpdate { priority: 0, - max_age: Duration::ZERO, + max_delay: Duration::ZERO, start_group: Some(7), end_group: None, start_frame: 0, @@ -4047,7 +4047,7 @@ mod tests { broadcast: broadcast.clone(), track: "video".into(), priority: 0, - max_age: Duration::ZERO, + max_delay: Duration::ZERO, start_group: None, end_group: None, start_frame: 0, @@ -4100,7 +4100,7 @@ mod tests { broadcast: crate::Path::new("room"), track: "video".into(), priority: 1, - max_age: Duration::ZERO, + max_delay: Duration::ZERO, start_group: None, end_group: None, start_frame: 0, @@ -4123,7 +4123,7 @@ mod tests { let update = lite::SubscribeUpdate { priority: 7, - max_age: Duration::ZERO, + max_delay: Duration::ZERO, start_group: None, end_group: None, start_frame: 0, diff --git a/rs/moq-net/src/lite/subscribe.rs b/rs/moq-net/src/lite/subscribe.rs index b81cc2c4ea3..2dc96c40470 100644 --- a/rs/moq-net/src/lite/subscribe.rs +++ b/rs/moq-net/src/lite/subscribe.rs @@ -19,10 +19,10 @@ pub struct Subscribe<'a> { pub epoch: Option, pub track: Cow<'a, str>, pub priority: u8, - pub max_age: std::time::Duration, + pub max_delay: std::time::Duration, /// The minimum group to deliver (a floor). On lite-06 the wire carries the raw /// sequence and `None` is interchangeable with `Some(0)`: a floor of 0 constrains - /// nothing, and the start resolves from `max_age`. Pre-06 wires encode the + /// nothing, and the start resolves from `max_delay`. Pre-06 wires encode the /// sequence + 1 and an absent start means the latest group. pub start_group: Option, pub end_group: Option, @@ -36,12 +36,12 @@ pub struct Subscribe<'a> { } impl Version { - /// Whether this version's SUBSCRIBE carries the subscriber's max age preference. + /// Whether this version's SUBSCRIBE carries the subscriber's max delay preference. /// /// Lite01/02 have no field for it, so a decoded `std::time::Duration::ZERO` there means /// "not stated", not "real time". Callers that act on the budget must tell the /// two apart or they will hold every legacy peer to the live edge. - pub(crate) fn carries_max_age(self) -> bool { + pub(crate) fn carries_max_delay(self) -> bool { !matches!(self, Version::Lite01 | Version::Lite02) } } @@ -54,14 +54,14 @@ impl Message for Subscribe<'_> { let track = Cow::Owned(r.string()?); let priority = r.u8()?; - let (max_age, start_group, end_group) = match version { + let (max_delay, start_group, end_group) = match version { Version::Lite01 | Version::Lite02 => (std::time::Duration::ZERO, None, None), _ => { skip_group_order(r, version)?; - let max_age = std::time::Duration::from_millis(r.varint()?); + let max_delay = std::time::Duration::from_millis(r.varint()?); let start_group = decode_start_group(r, version)?; let end_group = r.varint_opt()?; - (max_age, start_group, end_group) + (max_delay, start_group, end_group) } }; @@ -74,7 +74,7 @@ impl Message for Subscribe<'_> { epoch, track, priority, - max_age, + max_delay, start_group, end_group, start_frame, @@ -93,7 +93,7 @@ impl Message for Subscribe<'_> { Version::Lite01 | Version::Lite02 => {} _ => { pad_group_order(w, version)?; - w.varint(u64::try_from(self.max_age.as_millis()).map_err(|_| EncodeError::BoundsExceeded)?)?; + w.varint(u64::try_from(self.max_delay.as_millis()).map_err(|_| EncodeError::BoundsExceeded)?)?; encode_start_group(w, version, self.start_group)?; w.varint_opt(self.end_group)?; } @@ -228,7 +228,7 @@ fn encode_frame_bounds( #[derive(Clone, Debug)] pub struct SubscribeOk { pub priority: u8, - pub max_age: std::time::Duration, + pub max_delay: std::time::Duration, pub start_group: Option, pub end_group: Option, } @@ -245,7 +245,7 @@ impl Message for SubscribeOk { _ => { w.u8(self.priority); pad_group_order(w, version)?; - w.varint(u64::try_from(self.max_age.as_millis()).map_err(|_| EncodeError::BoundsExceeded)?)?; + w.varint(u64::try_from(self.max_delay.as_millis()).map_err(|_| EncodeError::BoundsExceeded)?)?; w.varint_opt(self.start_group)?; w.varint_opt(self.end_group)?; } @@ -258,26 +258,26 @@ impl Message for SubscribeOk { match version { Version::Lite01 => Ok(Self { priority: r.u8()?, - max_age: std::time::Duration::ZERO, + max_delay: std::time::Duration::ZERO, start_group: None, end_group: None, }), Version::Lite02 => Ok(Self { priority: 0, - max_age: std::time::Duration::ZERO, + max_delay: std::time::Duration::ZERO, start_group: None, end_group: None, }), _ => { let priority = r.u8()?; skip_group_order(r, version)?; - let max_age = std::time::Duration::from_millis(r.varint()?); + let max_delay = std::time::Duration::from_millis(r.varint()?); let start_group = r.varint_opt()?; let end_group = r.varint_opt()?; Ok(Self { priority, - max_age, + max_delay, start_group, end_group, }) @@ -381,7 +381,7 @@ impl Message for SubscribeEnd { #[derive(Clone, Debug)] pub struct SubscribeUpdate { pub priority: u8, - pub max_age: std::time::Duration, + pub max_delay: std::time::Duration, pub start_group: Option, pub end_group: Option, /// See [`Subscribe::start_frame`]. @@ -401,7 +401,7 @@ impl Message for SubscribeUpdate { let priority = r.u8()?; skip_group_order(r, version)?; - let max_age = std::time::Duration::from_millis(r.varint()?); + let max_delay = std::time::Duration::from_millis(r.varint()?); let start_group = decode_start_group(r, version)?; let end_group = match r.varint()? { 0 => None, @@ -413,7 +413,7 @@ impl Message for SubscribeUpdate { Ok(Self { priority, - max_age, + max_delay, start_group, end_group, start_frame, @@ -431,7 +431,7 @@ impl Message for SubscribeUpdate { w.u8(self.priority); pad_group_order(w, version)?; - w.varint(u64::try_from(self.max_age.as_millis()).map_err(|_| EncodeError::BoundsExceeded)?)?; + w.varint(u64::try_from(self.max_delay.as_millis()).map_err(|_| EncodeError::BoundsExceeded)?)?; encode_start_group(w, version, self.start_group)?; @@ -717,7 +717,7 @@ mod test { broadcast: Path::new("room").to_owned(), track: Cow::Borrowed("video"), priority: 3, - max_age: std::time::Duration::from_millis(250), + max_delay: std::time::Duration::from_millis(250), start_group: Some(7), end_group: Some(9), start_frame: 4, @@ -871,7 +871,7 @@ mod test { fn subscribe_ok_rejected_on_lite05() { let resp = SubscribeResponse::Ok(SubscribeOk { priority: 1, - max_age: std::time::Duration::ZERO, + max_delay: std::time::Duration::ZERO, start_group: None, end_group: None, }); diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 97241c143be..389aa9ebcf3 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -1496,7 +1496,7 @@ mod tests { let mut sub = SubStream { stream, id: 0, - max_age: Duration::ZERO, + max_delay: Duration::ZERO, start: Some(Position::group(2)), priority: 0, requested: Some(Position::group(2)), @@ -3221,7 +3221,7 @@ struct SubStream { id: u64, /// Original SUBSCRIBE params, echoed in every SUBSCRIBE_UPDATE; refreshed as the /// downstream aggregate changes. - max_age: Duration, + max_delay: Duration, start: Option, priority: u8, /// The start the SUBSCRIBE itself carried, fixed for the stream's life. A @@ -3553,9 +3553,9 @@ impl TrackServe { // SUBSCRIBE_UPDATE (Lite03+ only; older peers can't carry one). let start_moved = active.start != subscription.start; active.priority = subscription.priority; - active.max_age = subscription.max_age; + active.max_delay = subscription.max_delay; if let Ok(mut tail) = active.tail.write() { - tail.set_grace(tail::grace(subscription.max_age)); + tail.set_grace(tail::grace(subscription.max_delay)); // A lowered floor owes groups nobody asked for until now. if let Some(start) = subscription.start { let floor = active.start.map(|start| start.group).or(active.served); @@ -3632,7 +3632,7 @@ impl TrackServe { tracing::info!(id, broadcast = %self.subscriber.log_path(&self.path), track = %self.name, "subscribe started"); - let tail = kio::Producer::new(Tail::new(tail::grace(subscription.max_age))); + let tail = kio::Producer::new(Tail::new(tail::grace(subscription.max_delay))); self.subscriber.subscribes.lock().insert( id, TrackEntry { @@ -3731,7 +3731,7 @@ fn buffer_update( let bounds = WireBounds::new(active.start, end); active.stream.writer.buffer(&lite::SubscribeUpdate { priority: active.priority, - max_age: active.max_age, + max_delay: active.max_delay, start_group: bounds.start_group, end_group: bounds.end_group, start_frame: bounds.start_frame, @@ -3787,7 +3787,7 @@ impl Establish { broadcast: self.serve.path.as_path(), track: self.serve.name.as_str().into(), priority: self.subscription.priority, - max_age: self.subscription.max_age, + max_delay: self.subscription.max_delay, start_group: bounds.start_group, end_group: bounds.end_group, start_frame: bounds.start_frame, @@ -3831,7 +3831,7 @@ impl Establish { SubStream { stream, id: self.id, - max_age: self.subscription.max_age, + max_delay: self.subscription.max_delay, start: self.subscription.start, priority: self.subscription.priority, requested: self.subscription.start, @@ -4355,12 +4355,12 @@ impl ServeLoop { 0 => end.group, _ => end.group.saturating_add(1), }); - // The effective max age is the stopgap grace: the wrong clock + // The effective max delay is the stopgap grace: the wrong clock // (it bounds presentation-time drift), but it is how long the // subscriber was willing to wait for a late group anyway. if let Ok(mut tail) = active.tail.write() { tail.set_grace(tail::grace( - subscription.map(|sub| sub.max_age).unwrap_or_default(), + subscription.map(|sub| sub.max_delay).unwrap_or_default(), )); tail.expire(serve.subscriber.runtime.now()); } diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index e6c5a15ed27..6995cea38c8 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -1200,7 +1200,7 @@ pub(crate) trait Expiry: Send + Sync + std::panic::UnwindSafe + std::panic::RefU /// Return whether the group is stale, registering `waiter` for anything that /// could change the answer while the group remains live. /// A logical reader supplies its current budget after the original copy is gone. - fn is_expired(&self, max_age: Option, waiter: &kio::Waiter) -> bool; + fn is_expired(&self, max_delay: Option, waiter: &kio::Waiter) -> bool; /// Keep the reader's budget and cap while following a replacement track's edge. fn for_track(&self, track: &track::Consumer) -> Arc; @@ -1405,7 +1405,7 @@ impl Consumer { self.cursor.expiry_pending() } - /// Whether this cursor failed because its subscription max age budget expired. + /// Whether this cursor failed because its subscription max delay budget expired. #[cfg(test)] pub(crate) fn latency_expired(&self) -> bool { self.expired diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index dc720f2a6e4..63b04025431 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -7292,7 +7292,7 @@ mod tests { queued(&server).await.accept(&source); let resolved = pending.await.expect("resolves"); - let budget = track::Subscription::default().with_max_age(Duration::from_secs(3600)); + let budget = track::Subscription::default().with_max_delay(Duration::from_secs(3600)); for name in ["a", "b"] { let mut subscription = resolved .track(name) @@ -8265,7 +8265,7 @@ mod tests { let mut again = resolved .track("video") .unwrap() - .subscribe(track::Subscription::default().with_max_age(Duration::from_secs(3600))) + .subscribe(track::Subscription::default().with_max_delay(Duration::from_secs(3600))) .await .expect("resubscribe"); let mut group = moq_net_sim::timeout(Duration::from_secs(1), again.recv_group()) @@ -8412,7 +8412,7 @@ mod tests { let mut subscription = edge_resolved .track("video") .unwrap() - .subscribe(track::Subscription::default().with_max_age(Duration::from_secs(3600))) + .subscribe(track::Subscription::default().with_max_delay(Duration::from_secs(3600))) .await .expect("resubscribe"); moq_net_sim::timeout(Duration::from_secs(5), track.demand().used()) diff --git a/rs/moq-net/src/model/resume.rs b/rs/moq-net/src/model/resume.rs index dc342792ef2..5bc17537f0a 100644 --- a/rs/moq-net/src/model/resume.rs +++ b/rs/moq-net/src/model/resume.rs @@ -960,7 +960,7 @@ impl Recover { // A held group or frame may be the only thing being polled. Mirror and watch // preferences here too, before judging its budget against the live edge. reader.sync(waiter); - Some(reader.mirrored.max_age) + Some(reader.mirrored.max_delay) } /// Commit the replacement only once the caller has acquired its cursor or frame. @@ -1074,8 +1074,8 @@ mod test { .accept(None) } - fn subscribe(logical: &track::Producer, max_age: Duration) -> track::Subscriber { - let subscription = Subscription::default().with_max_age(max_age); + fn subscribe(logical: &track::Producer, max_delay: Duration) -> track::Subscriber { + let subscription = Subscription::default().with_max_delay(max_delay); logical .consume() .subscribe(subscription) @@ -1743,7 +1743,7 @@ mod test { .update( Subscription::default() .with_priority(7) - .with_max_age(Duration::from_secs(if widen { 10 } else { 2 })), + .with_max_delay(Duration::from_secs(if widen { 10 } else { 2 })), ) .unwrap(); assert!( @@ -1780,7 +1780,7 @@ mod test { .update( Subscription::default() .with_priority(8) - .with_max_age(Duration::from_secs(10)), + .with_max_delay(Duration::from_secs(10)), ) .unwrap(); assert!( @@ -1872,7 +1872,7 @@ mod test { .update( Subscription::default() .with_priority(7) - .with_max_age(Duration::from_secs(2)), + .with_max_delay(Duration::from_secs(2)), ) .unwrap(), Event::Cancel => { @@ -1898,7 +1898,7 @@ mod test { ); let demand = copies[0].subscription().expect("surviving reader"); assert_eq!(demand.priority, 7, "{events:?}"); - assert_eq!(demand.max_age, Duration::from_secs(2), "{events:?}"); + assert_eq!(demand.max_delay, Duration::from_secs(2), "{events:?}"); drop(groups); drop(subscriptions); drop(control); diff --git a/rs/moq-net/src/model/subscription.rs b/rs/moq-net/src/model/subscription.rs index cec094b20e8..40423a2d258 100644 --- a/rs/moq-net/src/model/subscription.rs +++ b/rs/moq-net/src/model/subscription.rs @@ -15,7 +15,7 @@ use std::{ pub struct Subscription { /// Delivery priority. Higher values preempt lower ones when bandwidth is constrained. pub priority: u8, - /// How old a group may get before this subscriber gives up on it. + /// How far a group may fall behind the live edge before this subscriber gives up on it. /// /// [`Duration::ZERO`] (the default) skips immediately: group 8 arriving means group 7 /// is abandoned. A larger budget tolerates that much reordering before giving up. @@ -41,7 +41,7 @@ pub struct Subscription { /// [`track::Consumer::fetch_group`](crate::track::Consumer::fetch_group) is exempt: /// it names one old group explicitly, so there is no live edge to be late against. /// - /// # How age is measured + /// # How delay is measured /// /// In presentation time only. A group is measured by its *reach*, where its immediate /// successor begins, against the newest frame of the latest group: it cannot present @@ -55,10 +55,10 @@ pub struct Subscription { /// the measure burst-blind on the receiving side: thirty seconds of backlog delivered /// in three reads as three. The publisher's copy is stamped as it produces, so the /// gate there still holds; it is just the coarser of the two. - pub max_age: Duration, + pub max_delay: Duration, /// The lowest [`Position`] the publisher may deliver, or `None` for no floor. /// - /// A floor, not a request: only [`Self::max_age`] asks for data, and the floor bounds + /// A floor, not a request: only [`Self::max_delay`] asks for data, and the floor bounds /// how far back it may reach. `None` and a floor of group 0 mean the same thing, since /// nothing sits below group 0. Delivery starts at the oldest group at or above the /// floor that the budget still considers fresh, so a floor above the live edge simply @@ -92,7 +92,7 @@ impl Default for Subscription { fn default() -> Self { Self { priority: 0, - max_age: Duration::ZERO, + max_delay: Duration::ZERO, start: None, end: None, } @@ -106,16 +106,17 @@ impl Subscription { self } - /// Set how old a group may get before it is skipped, returning `self` for chaining. - pub fn with_max_age(mut self, max_age: Duration) -> Self { - self.max_age = max_age; + /// Set how far a group may fall behind the live edge before it is skipped, returning + /// `self` for chaining. + pub fn with_max_delay(mut self, max_delay: Duration) -> Self { + self.max_delay = max_delay; self } /// Floor delivery at `start`, or leave it unfloored when `None`. Returns `self` for /// chaining. /// - /// A floor bounds how far back [`Self::max_age`] may reach; it does not request data + /// A floor bounds how far back [`Self::max_delay`] may reach; it does not request data /// on its own. [`Position::group`] is the whole-group form. pub fn with_start(mut self, start: impl Into>) -> Self { self.start = start.into(); @@ -158,7 +159,7 @@ impl Subscription { let merged = Subscription { priority: self.priority.max(combined.priority), // Sequence-first prioritization is enabled only when every subscriber wants it. - max_age: self.max_age.max(combined.max_age), + max_delay: self.max_delay.max(combined.max_delay), // Bounds fold as whole positions. Two subscribers starting in the same group // are separated only by their frame, so folding group and frame independently // would invent a bound neither asked for. diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 899bd96164e..7b7b8bb8638 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -100,7 +100,7 @@ pub struct Info { /// is stale. The newest group is always retained. /// /// A retention bound rather than a delivery one, the inverse of an HTTP - /// `Cache-Control: max-age`. [`Subscription::max_age`] is clamped to this, since a + /// `Cache-Control: max-age`. [`Subscription::max_delay`] is clamped to this, since a /// group can't be waited for longer than it's kept around. Reported in TRACK_INFO so /// relays re-serve with the same window. `None` (the default) sets no limit; /// the origin cache ceiling and pool still apply. `Some(Duration::ZERO)` keeps the live edge. @@ -111,7 +111,7 @@ pub struct Info { /// [`expiry`](crate::cache::Pool::expiry) window, not to this budget. /// /// This is the `Publisher Max Age` on the wire, the publisher-side half of the - /// budget [`Subscription::max_age`] sets for a subscriber. + /// budget [`Subscription::max_delay`] sets for a subscriber. /// /// Encoded as milliseconds in a QUIC varint, so a duration of `2^62` milliseconds /// or more cannot be put on lite-07 or IETF wires. Lite05/06 map values at or above @@ -1846,7 +1846,7 @@ impl Producer { /// SUBSCRIBE_OK round trip). Pass `None` for [`Subscription::default`]. /// /// The read cursor starts at the group the subscription named (its floor), or 0. - /// [`Subscription::max_age`] is what asks for data: delivery skips everything above + /// [`Subscription::max_delay`] is what asks for data: delivery skips everything above /// the floor that the budget convicts, so the default budget of zero delivers only /// the latest group and a larger one reaches back over what it can still use. pub fn subscribe(&self, subscription: impl Into>) -> Subscriber { @@ -1887,7 +1887,7 @@ impl Producer { /// when there are no live subscribers. Unlike [`Self::subscription`], this /// doesn't wait for a change or advance the change cursor. /// - /// The aggregate's [`Subscription::max_age`] is clamped to this track's + /// The aggregate's [`Subscription::max_delay`] is clamped to this track's /// [`Info::max_age`]: no subscriber can wait for a late group longer than the /// publisher keeps it. pub fn subscription(&self) -> Option { @@ -2241,7 +2241,7 @@ fn snapshot_subscription(subs: &kio::Shared, bound: Option u64 { /// budget when it decides a group is stale ([`TrackState::is_stale`]). Those agree because /// `min` distributes over the `max` that combines them. `bound` is `None` on a track whose /// info isn't known yet (an unaccepted [`Request`]), which imposes no window. -fn clamp_max_age(mut max_age: Duration, bound: Option) -> Duration { +fn clamp_max_delay(mut max_delay: Duration, bound: Option) -> Duration { if let Some(bound) = bound { - max_age = max_age.min(bound); + max_delay = max_delay.min(bound); } - max_age + max_delay } -/// Clamp the aggregate's max age budget to the publisher's window; see [`clamp_max_age`]. +/// Clamp the aggregate's max delay budget to the publisher's window; see [`clamp_max_delay`]. fn clamp_combined(combined: Option, bound: Option) -> Option { let mut combined = combined?; - combined.max_age = clamp_max_age(combined.max_age, bound); + combined.max_delay = clamp_max_delay(combined.max_delay, bound); Some(combined) } @@ -2573,7 +2573,7 @@ impl Consumer { /// [`Error::Dropped`]) if it is already closed. /// /// The read cursor starts at the group the subscription named (its floor), or 0. - /// [`Subscription::max_age`] is what asks for data: delivery skips everything above + /// [`Subscription::max_delay`] is what asks for data: delivery skips everything above /// the floor that the budget convicts, so the default budget of zero delivers only /// the latest group and a larger one reaches back over what it can still use. pub fn subscribe(&self, subscription: impl Into>) -> kio::Pending { @@ -3225,7 +3225,7 @@ impl kio::Task for Fetching { /// /// The one place they meet is where the cursor comes from. A new subscriber's cursor is /// floored at the group its own subscription named (or 0), and its -/// [`Subscription::max_age`] decides what above the floor is worth delivering. Every later +/// [`Subscription::max_delay`] decides what above the floor is worth delivering. Every later /// move is the caller's. pub struct Subscriber { name: Arc, @@ -3293,14 +3293,14 @@ impl group::Expiry for GroupExpiry { }) } - fn is_expired(&self, max_age: Option, waiter: &kio::Waiter) -> bool { - let max_age = max_age.unwrap_or_else(|| { - let mut max_age = Duration::default(); + fn is_expired(&self, max_delay: Option, waiter: &kio::Waiter) -> bool { + let max_delay = max_delay.unwrap_or_else(|| { + let mut max_delay = Duration::default(); let _ = self.subscription.poll(waiter, |subscription| { - max_age = subscription.max_age; + max_delay = subscription.max_delay; Poll::<()>::Pending }); - max_age + max_delay }); let mut cap = None; @@ -3311,7 +3311,7 @@ impl group::Expiry for GroupExpiry { let mut expired = false; let _ = self.state.poll(waiter, |state| { - let budget = clamp_max_age(max_age, state.max_age_bound()); + let budget = clamp_max_delay(max_delay, state.max_age_bound()); loop { // An abort can change reach even after the successor is stamped. // Register before judging, so a racing abort is observed or wakes us. @@ -3506,14 +3506,14 @@ impl Cursor { /// [`Poll::Ready`]; the track ending surfaces as the error the caller was going to /// get anyway. fn poll_drift(&self, cap: Option, waiter: &kio::Waiter) -> Poll> { - let mut max_age = Duration::default(); + let mut max_delay = Duration::default(); let _ = self.subscription.poll(waiter, |subscription| { - max_age = subscription.max_age; + max_delay = subscription.max_delay; Poll::<()>::Pending }); self.poll(waiter, |state| { Poll::Ready(Ok(Drift { - budget: clamp_max_age(max_age, state.max_age_bound()), + budget: clamp_max_delay(max_delay, state.max_age_bound()), edge: state.drift_edge(cap), })) }) @@ -3688,7 +3688,7 @@ impl Cursor { /// A cloneable handle to a subscriber's delivery preferences. /// /// This updates the same subscription as the owning [`Subscriber`] without -/// borrowing its read cursor, so callers can change delivery priority, the max age +/// borrowing its read cursor, so callers can change delivery priority, the max delay /// budget, or group bounds while another task is waiting for groups. #[derive(Clone)] pub struct Control { @@ -3766,7 +3766,7 @@ impl Subscriber { /// [`Self::ordered`] if you only want groups whose sequence number is higher than any /// previously returned. /// - /// Groups are semi-reliable, and the [`Subscription::max_age`] budget is the other + /// Groups are semi-reliable, and the [`Subscription::max_delay`] budget is the other /// thing (alongside eviction and a moving start) that decides which of them arrive: /// one that has drifted further behind the live edge than the budget tolerates is /// skipped rather than handed over, so a single poll walks off a whole backlog. The @@ -4051,7 +4051,7 @@ impl Subscriber { /// /// # Age and skipping /// -/// [`Subscription::max_age`] applies as this cursor reads, exactly as it does on the +/// [`Subscription::max_delay`] applies as this cursor reads, exactly as it does on the /// arrival cursor: a group is skipped once its *reach*, where its immediate successor /// begins, is that far behind the newest frame on the track. Nothing weaker convicts it, /// because the reach is the only proof that *every* frame it could still hold is past the @@ -4445,7 +4445,7 @@ mod test { /// A bounded replay window for tests whose subject requires every buffered group. fn replay() -> Subscription { - Subscription::default().with_max_age(Duration::from_secs(30)) + Subscription::default().with_max_delay(Duration::from_secs(30)) } /// Helper: count live cached groups in state. @@ -5358,26 +5358,26 @@ mod test { } #[test] - fn max_age_clamped_to_cache() { + fn max_delay_clamped_to_cache() { let producer = track_producer("test", Info::default().with_max_age(Duration::from_secs(2))); - // A max age budget beyond the cache is capped in the aggregate; a group can't be + // A max delay budget beyond the cache is capped in the aggregate; a group can't be // waited for longer than the publisher keeps it. The subscriber's own preference // is stored verbatim, so what it asked for stays readable. - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(10))); - assert_eq!(subscriber.subscription().max_age, Duration::from_secs(10)); - assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(10))); + assert_eq!(subscriber.subscription().max_delay, Duration::from_secs(10)); + assert_eq!(producer.subscription().unwrap().max_delay, Duration::from_secs(2)); // A budget within the cache is left alone, and ZERO (skip immediately) stays ZERO. subscriber - .update(Subscription::default().with_max_age(Duration::from_millis(500))) + .update(Subscription::default().with_max_delay(Duration::from_millis(500))) .unwrap(); - assert_eq!(producer.subscription().unwrap().max_age, Duration::from_millis(500)); + assert_eq!(producer.subscription().unwrap().max_delay, Duration::from_millis(500)); subscriber - .update(Subscription::default().with_max_age(Duration::ZERO)) + .update(Subscription::default().with_max_delay(Duration::ZERO)) .unwrap(); - assert_eq!(producer.subscription().unwrap().max_age, Duration::ZERO); + assert_eq!(producer.subscription().unwrap().max_delay, Duration::ZERO); } /// Mint a track under an origin whose retention ceiling is `cap`, so the @@ -5447,32 +5447,32 @@ mod test { } #[test] - fn max_age_clamped_via_every_update_path() { + fn max_delay_clamped_via_every_update_path() { let producer = track_producer("test", Info::default().with_max_age(Duration::from_secs(2))); - let over = Subscription::default().with_max_age(Duration::from_secs(10)); + let over = Subscription::default().with_max_delay(Duration::from_secs(10)); // The clamp lives in the aggregation, so it applies no matter which entry point // wrote the raw preference. Previously only `Subscriber::update` clamped. let mut subscriber = producer.subscribe(over.clone()); - assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_delay, Duration::from_secs(2)); subscriber.control().update(over.clone()).unwrap(); - assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_delay, Duration::from_secs(2)); subscriber.update(over).unwrap(); - assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_delay, Duration::from_secs(2)); } #[test] - fn max_age_aggregate_clamps_across_subscribers() { + fn max_delay_aggregate_clamps_across_subscribers() { let producer = track_producer("test", Info::default().with_max_age(Duration::from_secs(2))); // The aggregate takes the max, then clamps once. Equivalent to clamping each // subscriber first, since `min` distributes over `max`. - let _a = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(500))); - let _b = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(10))); + let _a = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(500))); + let _b = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(10))); - assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_delay, Duration::from_secs(2)); } #[test] @@ -5572,7 +5572,7 @@ mod test { for second in 0..5 { append_at(&mut producer, second * 1000); } - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(1))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(1))); assert_eq!( subscriber .recv_group() @@ -5600,7 +5600,7 @@ mod test { edge.write_frame(Timestamp::from_millis(2000).unwrap(), bytes::Bytes::from_static(b"a")) .unwrap(); - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(2))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(2))); assert_eq!( subscriber .recv_group() @@ -5630,7 +5630,7 @@ mod test { // edge (2s, 3s, 4s) and drops the two below it. Group 1 reaches exactly 2s behind // the edge, and the reach bound is exclusive, so every frame it could hold is // already past the budget. - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(2))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(2))); assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); } @@ -5650,7 +5650,7 @@ mod test { // edge, so the same join is handed the head of what it can still use. One bound // decides both what is sent and what is expired, so a subscriber is never sent // history it would discard on arrival. - let budget = Subscription::default().with_max_age(Duration::from_secs(2)); + let budget = Subscription::default().with_max_delay(Duration::from_secs(2)); let mut subscriber = producer.subscribe(budget); assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); } @@ -5672,14 +5672,14 @@ mod test { // A budget reaching further back than the floor is cut off at it. let floored = Subscription::default() .with_start(Position::group(3)) - .with_max_age(Duration::from_secs(10)); + .with_max_delay(Duration::from_secs(10)); let mut subscriber = producer.subscribe(floored); assert_eq!(drain(&mut subscriber), vec![3, 4]); // A floor below what the budget admits changes nothing. let slack = Subscription::default() .with_start(Position::group(1)) - .with_max_age(Duration::from_secs(2)); + .with_max_delay(Duration::from_secs(2)); let mut subscriber = producer.subscribe(slack); assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); } @@ -5695,7 +5695,7 @@ mod test { // cursor sits at the floor rather than sliding back to what is cached. let resumed = Subscription::default() .with_start(Position::group(7)) - .with_max_age(Duration::from_secs(10)); + .with_max_delay(Duration::from_secs(10)); let mut subscriber = producer.subscribe(resumed); assert_eq!(drain(&mut subscriber), Vec::::new()); append_at(&mut producer, 3000); // sequence 3: still below the floor @@ -5717,7 +5717,7 @@ mod test { group.finish().unwrap(); } - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(5))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(5))); assert_eq!(drain(&mut subscriber), vec![5, 6, 7]); // Arriving below everything already delivered is not what makes content stale: @@ -5740,7 +5740,7 @@ mod test { append_at(&mut producer, second * 1000); } - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(1500))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(1500))); assert_eq!(drain(&mut subscriber), vec![1, 2, 3]); } @@ -5821,7 +5821,7 @@ mod test { #[moq_net_sim::test] async fn a_handed_out_group_wakes_when_a_newer_group_gets_its_first_timestamp() { let mut producer = track_producer("test", None); - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(500))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(500))); let mut old = producer.append_group().unwrap(); old.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"old")) .unwrap(); @@ -5858,7 +5858,7 @@ mod test { #[test] fn a_parked_read_ignores_first_frames_between_its_successor_and_the_edge() { let mut producer = track_producer("test", None); - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(10))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(10))); let mut head = producer.append_group().unwrap(); head.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"head")) .unwrap(); @@ -5904,7 +5904,7 @@ mod test { #[test] fn a_parked_read_watches_the_replacement_for_an_aborted_successor() { let mut producer = track_producer("test", None); - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(500))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(500))); let mut head = producer.append_group().unwrap(); head.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"head")) .unwrap(); @@ -6036,7 +6036,7 @@ mod test { #[moq_net_sim::test] async fn a_budget_is_measured_from_the_readers_position() { let producer = track_producer("test", None); - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(1))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(1))); let mut open = producer.append_group().unwrap(); open.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"key")) @@ -6167,7 +6167,7 @@ mod test { // Group 0 reaches 1s, a full second behind the 2s edge, so the clamped 500ms // budget drops it. An unclamped ten seconds would have kept it. - let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(10))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_delay(Duration::from_secs(10))); assert_eq!(drain(&mut subscriber), vec![1, 2]); } @@ -6187,7 +6187,7 @@ mod test { let mut patient = producer.subscribe( Subscription::default() .with_start(Position::group(0)) - .with_max_age(Duration::from_secs(10)), + .with_max_delay(Duration::from_secs(10)), ); patient.start_at(0); assert_eq!(drain(&mut patient), vec![0, 1, 2, 3]); @@ -6210,7 +6210,7 @@ mod test { append_at(&mut producer, 2000); // A budget far shorter than the group's own span still keeps it. - let mut sub = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(500))); + let mut sub = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(500))); assert_eq!(drain(&mut sub), vec![0, 1]); } @@ -6234,7 +6234,7 @@ mod test { append_at(&mut producer, 3000); append_at(&mut producer, 4000); - let mut sub = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(500))); + let mut sub = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(500))); assert_eq!(drain(&mut sub), vec![1, 2]); } @@ -6274,7 +6274,7 @@ mod test { // Group 0 reaches 10s, so nothing here proves it is past a 500ms budget: it could // hold frames through nearly 10s. A minimum over later groups would put its reach // at 1s and drop it. - let mut sub = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(500))); + let mut sub = producer.subscribe(Subscription::default().with_max_delay(Duration::from_millis(500))); assert!( drain(&mut sub).contains(&0), "group 0 is bounded by its successor at 10s, not by a later rewind" @@ -6351,7 +6351,7 @@ mod test { // Group 0 reaches 1s, a full 2s behind the 3s edge, so it is gone. Group 1 // reaches 2s and could still present up to it: inside a 1.5s budget. let mut subscriber = producer - .subscribe(Subscription::default().with_max_age(Duration::from_millis(1500))) + .subscribe(Subscription::default().with_max_delay(Duration::from_millis(1500))) .ordered(); assert_eq!(drain_ordered(&mut subscriber), vec![1, 2, 3]); diff --git a/rs/moq-net/src/stats.rs b/rs/moq-net/src/stats.rs index d6cf90368e0..92095b2972e 100644 --- a/rs/moq-net/src/stats.rs +++ b/rs/moq-net/src/stats.rs @@ -325,8 +325,8 @@ pub struct Traffic { /// A subset of `groups`: each one also counts there and its payload in /// `frames` / `bytes`. pub datagrams: u64, - /// Content skipped because it aged past a subscriber's - /// [`max_age`](crate::track::Subscription::max_age) budget. Disjoint from the top-level payload + /// Content skipped because it fell behind a subscriber's + /// [`max_delay`](crate::track::Subscription::max_delay) budget. Disjoint from the top-level payload /// counters: skipped content is never handed over. A steady rate here means /// subscribers are consistently behind the live edge. pub stale: Content, diff --git a/rs/moq-net/src/tail.rs b/rs/moq-net/src/tail.rs index 042a2b4fc91..63e9e16598e 100644 --- a/rs/moq-net/src/tail.rs +++ b/rs/moq-net/src/tail.rs @@ -17,16 +17,16 @@ use crate::time::{Deadline, Instant}; /// How long a subscriber waits for a group stream it cannot account for once the /// publisher has ended the subscription. /// -/// Bounds the wait on IETF, and on moq-lite when the subscription has no max age to bound +/// Bounds the wait on IETF, and on moq-lite when the subscription has no max delay to bound /// it with. Matches `@moq/net`, so a reader cannot tell which side it is talking to. pub(crate) const GRACE: Duration = Duration::from_secs(1); -/// The grace for a subscription with `max_age`: how long the subscriber was willing to +/// The grace for a subscription with `max_delay`: how long the subscriber was willing to /// wait for a late group anyway, or [`GRACE`] without one. -pub(crate) fn grace(max_age: Duration) -> Duration { - match max_age.is_zero() { +pub(crate) fn grace(max_delay: Duration) -> Duration { + match max_delay.is_zero() { true => GRACE, - false => max_age, + false => max_delay, } } @@ -72,7 +72,7 @@ impl Tail { } } - /// Change the grace, for a subscription whose max age changed. + /// Change the grace, for a subscription whose max delay changed. pub fn set_grace(&mut self, grace: Duration) { self.grace = grace; } diff --git a/rs/moq-net/tests/history_groups.rs b/rs/moq-net/tests/history_groups.rs index 62db30709fc..70680e7426d 100644 --- a/rs/moq-net/tests/history_groups.rs +++ b/rs/moq-net/tests/history_groups.rs @@ -78,7 +78,7 @@ async fn round(version: &str, relay: bool, newest_first: bool) -> Vec<(u64, usiz let reader = moq_net_sim::spawn(async move { let subscription = Subscription::default() - .with_max_age(FOREVER) + .with_max_delay(FOREVER) .with_start(Position::group(0)); let mut sub = remote .track("history") @@ -219,7 +219,7 @@ async fn a_late_subscriber_receives_the_relays_cached_history() { consumer.routed("bcast").await.unwrap(); let remote = consumer.request_broadcast("bcast").await.unwrap(); let subscription = Subscription::default() - .with_max_age(FOREVER) + .with_max_delay(FOREVER) .with_start(Position::group(0)); let first_subscription = subscription.clone(); let first_reader = moq_net_sim::spawn(async move { diff --git a/rs/moq-net/tests/rejoin.rs b/rs/moq-net/tests/rejoin.rs index f8621f9cd67..6718a4c2f41 100644 --- a/rs/moq-net/tests/rejoin.rs +++ b/rs/moq-net/tests/rejoin.rs @@ -52,7 +52,7 @@ async fn rejoin_recovers_the_group_reset_on_leave() { let remote = consumer.request_broadcast("bench").await.unwrap(); let ts = |ms| Timestamp::from_millis(ms).unwrap(); - let prefs = || track::Subscription::default().with_max_age(Duration::from_secs(10)); + let prefs = || track::Subscription::default().with_max_delay(Duration::from_secs(10)); let mut group = track.append_group().unwrap(); group.write_frame(ts(0), b"a0".as_ref()).unwrap(); diff --git a/rs/moq-net/tests/route_change.rs b/rs/moq-net/tests/route_change.rs index f52ecdf8500..8171dadabfa 100644 --- a/rs/moq-net/tests/route_change.rs +++ b/rs/moq-net/tests/route_change.rs @@ -102,7 +102,7 @@ impl Topology { let consumer = subscriber.consume(); consumer.routed("live").await.unwrap(); let remote = consumer.request_broadcast("live").await.unwrap(); - let prefs = track::Subscription::default().with_max_age(Duration::from_secs(60)); + let prefs = track::Subscription::default().with_max_delay(Duration::from_secs(60)); let sub = remote.track("video").unwrap().subscribe(prefs).await.unwrap(); let topology = Self { @@ -429,7 +429,7 @@ async fn lagging_route_dies(version: Version) -> mpsc::UnboundedReceiver<(u64, m let consumer = origin.consume(); consumer.routed("live").await.unwrap(); let remote = consumer.request_broadcast("live").await.unwrap(); - let preferences = track::Subscription::default().with_max_age(Duration::from_secs(60)); + let preferences = track::Subscription::default().with_max_delay(Duration::from_secs(60)); remote.track("video").unwrap().subscribe(preferences).await.unwrap() } fn write(group: &mut moq_net::group::Producer, sequence: u64, frame: u64) { diff --git a/rs/moq-net/tests/settled_end_survives_abort.rs b/rs/moq-net/tests/settled_end_survives_abort.rs index 1a3270e7b34..e737c31fd25 100644 --- a/rs/moq-net/tests/settled_end_survives_abort.rs +++ b/rs/moq-net/tests/settled_end_survives_abort.rs @@ -26,7 +26,7 @@ async fn round(abort: bool, ordered: bool) -> (Vec, Option) { // not the live edge. let subscription = moq_net::track::Subscription::default() .with_start(moq_net::track::Position::group(0)) - .with_max_age(std::time::Duration::from_secs(30)); + .with_max_delay(std::time::Duration::from_secs(30)); let mut consumer = track.subscribe(subscription); for _ in 0..GROUPS { diff --git a/rs/moq-net/tests/track_tail.rs b/rs/moq-net/tests/track_tail.rs index 01c25c25951..03ab5b0a492 100644 --- a/rs/moq-net/tests/track_tail.rs +++ b/rs/moq-net/tests/track_tail.rs @@ -19,7 +19,7 @@ use support::harness::{MockConnectOptions, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); const PAYLOAD: &[u8] = b"frame"; -/// How long a subscriber waits for a group it cannot account for, with no max age set. +/// How long a subscriber waits for a group it cannot account for, with no max delay set. const GRACE: Duration = Duration::from_secs(1); /// moq-lite drafts with and without SUBSCRIBE_END, and IETF drafts over the control stream diff --git a/rs/moq-relay/tests/cluster_unknown.rs b/rs/moq-relay/tests/cluster_unknown.rs index 96f33fc0ad2..72492b264c0 100644 --- a/rs/moq-relay/tests/cluster_unknown.rs +++ b/rs/moq-relay/tests/cluster_unknown.rs @@ -137,7 +137,7 @@ async fn read_first_frame(port: u16) -> Result, String> { // This verifies route propagation rather than real-time backlog skipping. Give // every hop enough tolerance for the next 100ms group to arrive while the // selected group's frame is still crossing the redundant mesh. - let subscription = moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1)); + let subscription = moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1)); let mut track = tokio::time::timeout( TIMEOUT, broadcast.track("video").expect("track handle").subscribe(subscription), diff --git a/rs/moq-relay/tests/goaway_cluster.rs b/rs/moq-relay/tests/goaway_cluster.rs index 2cfc7f8640b..9433b3de8d1 100644 --- a/rs/moq-relay/tests/goaway_cluster.rs +++ b/rs/moq-relay/tests/goaway_cluster.rs @@ -559,7 +559,7 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { "subscribe to the video track", bc.track("video") .expect("track handle") - .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(60))), + .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(60))), ) .await .expect("subscribe"); diff --git a/rs/moq-relay/tests/upstream_links.rs b/rs/moq-relay/tests/upstream_links.rs index 3d4d37d8628..695762f42ad 100644 --- a/rs/moq-relay/tests/upstream_links.rs +++ b/rs/moq-relay/tests/upstream_links.rs @@ -171,7 +171,7 @@ async fn read_frame(origin: &origin::Producer, path: &str) { let broadcast = within(&format!("route to {path}"), consumer.routed_broadcast(path)) .await .unwrap_or_else(|err| panic!("{path} unroutable: {err}")); - let subscription = moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1)); + let subscription = moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1)); let mut track = within( &format!("subscribe to {path}"), broadcast.track("video").expect("track handle").subscribe(subscription), diff --git a/rs/moq-rtmp/src/dial.rs b/rs/moq-rtmp/src/dial.rs index 1a0572b5adf..d02708fde3d 100644 --- a/rs/moq-rtmp/src/dial.rs +++ b/rs/moq-rtmp/src/dial.rs @@ -68,8 +68,8 @@ pub struct Client { /// The `` this client connected to, logged in place of the stream key. app: String, /// How long [`publish`](Self::publish)'s FLV muxer waits for a stalled group - /// before skipping. Defaults to [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE). - export_max_age: Duration, + /// before skipping. Defaults to [`DEFAULT_MAX_DELAY`](crate::DEFAULT_MAX_DELAY). + export_max_delay: Duration, /// Retention declared on the media tracks [`pull`](Self::pull) publishes, or `None` /// for hang's own default. import_max_age: Option, @@ -153,7 +153,7 @@ impl Client { session, work, app: app.to_string(), - export_max_age: crate::DEFAULT_MAX_AGE, + export_max_delay: crate::DEFAULT_MAX_DELAY, import_max_age: None, import_bandwidth: moq_net::bandwidth::Allocator::unlimited(), }) @@ -161,10 +161,10 @@ impl Client { /// Set how long [`publish`](Self::publish)'s FLV muxer waits for a stalled group /// before skipping to a newer one (the moq-level frame-drop latency). Defaults - /// to [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE); pass + /// to [`DEFAULT_MAX_DELAY`](crate::DEFAULT_MAX_DELAY); pass /// [`Duration::ZERO`] to drop stale groups aggressively. - pub fn with_export_max_age(mut self, max_age: Duration) -> Self { - self.export_max_age = max_age; + pub fn with_export_max_delay(mut self, max_delay: Duration) -> Self { + self.export_max_delay = max_delay; self } @@ -178,7 +178,7 @@ impl Client { /// and the memory matters. /// /// The pull (ingest) direction only; [`publish`](Self::publish) reads a broadcast - /// someone else declared, and takes [`with_export_max_age`](Self::with_export_max_age) instead. + /// someone else declared, and takes [`with_export_max_delay`](Self::with_export_max_delay) instead. pub fn with_import_max_age(mut self, max_age: impl Into>) -> Self { self.import_max_age = max_age.into(); self @@ -230,7 +230,7 @@ impl Client { let mut export = FlvExport::new(moq_mux::Source::new(origin, path)) .await .map_err(|e| anyhow::anyhow!("init FLV export: {e}"))? - .with_max_age(self.export_max_age); + .with_max_delay(self.export_max_delay); let mut tags = flv::TagReader::new(); let mut buffer = [0u8; READ_BUFFER]; diff --git a/rs/moq-rtmp/src/lib.rs b/rs/moq-rtmp/src/lib.rs index 1dac15e4cae..5bd0cf24c29 100644 --- a/rs/moq-rtmp/src/lib.rs +++ b/rs/moq-rtmp/src/lib.rs @@ -85,9 +85,9 @@ mod server; /// bounds buffering rather than the wire rate. Zero would drop stale groups the /// instant a newer one arrives, which is too aggressive for RTMP's typical jitter, /// so the default holds a couple of seconds. Override per request with -/// [`Play::with_max_age`] / [`Client::with_export_max_age`] or via -/// [`Config::export_max_age`]. -pub const DEFAULT_MAX_AGE: Duration = Duration::from_secs(2); +/// [`Play::with_max_delay`] / [`Client::with_export_max_delay`] or via +/// [`Config::export_max_delay`]. +pub const DEFAULT_MAX_DELAY: Duration = Duration::from_secs(2); pub use dial::Client; pub use error::{Error, Result}; diff --git a/rs/moq-rtmp/src/listen.rs b/rs/moq-rtmp/src/listen.rs index 30474e85bff..4f614db8e4e 100644 --- a/rs/moq-rtmp/src/listen.rs +++ b/rs/moq-rtmp/src/listen.rs @@ -47,9 +47,9 @@ pub struct Config { /// How long a play's FLV muxer waits for a stalled group before skipping to a /// newer one (the moq-level frame-drop latency). Defaults to - /// [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE); set [`Duration::ZERO`] + /// [`DEFAULT_MAX_DELAY`](crate::DEFAULT_MAX_DELAY); set [`Duration::ZERO`] /// to drop stale groups aggressively. Only affects egress (plays); ingest ignores it. - pub export_max_age: Duration, + pub export_max_delay: Duration, /// How long relays keep a non-latest group of an ingested media track fetchable, or /// `None` for hang's own default. @@ -89,7 +89,7 @@ impl Default for Config { Self { listen: None, prefix: Path::empty().to_owned(), - export_max_age: crate::DEFAULT_MAX_AGE, + export_max_delay: crate::DEFAULT_MAX_DELAY, import_max_age: None, #[cfg(feature = "tls")] tls: None, @@ -147,7 +147,7 @@ pub async fn run(origin: origin::Producer, config: Config) -> Result<()> { // listeners share the same claim table. let active = config.active.clone(); let prefix = config.prefix; - let export_max_age = config.export_max_age; + let export_max_delay = config.export_max_delay; let import_max_age = config.import_max_age; // Players are served out of the same origin the publishers write into. let consumer = origin.consume(); @@ -191,7 +191,7 @@ pub async fn run(origin: origin::Producer, config: Config) -> Result<()> { let _ = play.reject("missing broadcast path (RTMP app/key)").await; return; }; - if let Err(err) = play.with_max_age(export_max_age).accept(&consumer, &path).await { + if let Err(err) = play.with_max_delay(export_max_delay).accept(&consumer, &path).await { tracing::warn!(%peer, %path, %err, "RTMP play ended with error"); } }); diff --git a/rs/moq-rtmp/src/server.rs b/rs/moq-rtmp/src/server.rs index 12b003db56c..334d0b225e0 100644 --- a/rs/moq-rtmp/src/server.rs +++ b/rs/moq-rtmp/src/server.rs @@ -714,8 +714,8 @@ pub struct Play { tc_url: Option, peer: SocketAddr, /// How long the FLV muxer waits for a stalled group before skipping to a newer - /// one. Defaults to [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE); override with - /// [`with_max_age`](Self::with_max_age). + /// one. Defaults to [`DEFAULT_MAX_DELAY`](crate::DEFAULT_MAX_DELAY); override with + /// [`with_max_delay`](Self::with_max_delay). latency: Duration, /// Enhanced-RTMP capabilities advertised by the player in its connect object. capabilities: ClientCapabilities, @@ -748,11 +748,11 @@ impl Play { /// Set how long the FLV muxer waits for a stalled group before skipping to a /// newer one (the moq-level frame-drop latency). Defaults to - /// [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE). RTMP is unpaced (tags go out as + /// [`DEFAULT_MAX_DELAY`](crate::DEFAULT_MAX_DELAY). RTMP is unpaced (tags go out as /// fast as the socket accepts them), so this bounds buffering, not the wire /// rate. Pass [`Duration::ZERO`] to drop stale groups /// aggressively. - pub fn with_max_age(mut self, latency: Duration) -> Self { + pub fn with_max_delay(mut self, latency: Duration) -> Self { self.latency = latency; self } @@ -831,7 +831,7 @@ impl Play { let mut export = FlvExport::new(moq_mux::Source::new(origin.consume(), path.as_str())) .await .map_err(|e| anyhow::anyhow!("init FLV export: {e}"))? - .with_max_age(self.latency) + .with_max_delay(self.latency) .with_multitrack(self.capabilities.multitrack) .with_select(select); @@ -1103,7 +1103,7 @@ async fn accept_until_request(mut stream: S, peer: SocketAddr) -> any stream_key, tc_url, peer, - latency: crate::DEFAULT_MAX_AGE, + latency: crate::DEFAULT_MAX_DELAY, capabilities: client_capabilities.clone(), }))); } diff --git a/rs/moq-tokio/tests/broadcast.rs b/rs/moq-tokio/tests/broadcast.rs index 9141fca8b18..2a66e0abf0e 100644 --- a/rs/moq-tokio/tests/broadcast.rs +++ b/rs/moq-tokio/tests/broadcast.rs @@ -1120,7 +1120,7 @@ async fn broadcast_route_migration() { // Resolve and subscribe: the cheaper route (A) serves the track. let subscription = moq_net::track::Subscription::default() .with_start(moq_net::track::Position::group(1)) - .with_max_age(Duration::from_secs(10)); + .with_max_delay(Duration::from_secs(10)); let broadcast = tokio::time::timeout(TIMEOUT, sub_consumer.request_broadcast("test")) .await .expect("request timeout") @@ -1247,7 +1247,7 @@ async fn rejoin_skips_a_stale_warm_cache(version: &str) { .await .expect("request timeout") .expect("broadcast resolves"); - let budget = moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100)); + let budget = moq_net::track::Subscription::default().with_max_delay(Duration::from_millis(100)); async fn recv(sub: &mut moq_net::track::Subscriber, version: &str) -> u64 { tokio::time::timeout(TIMEOUT, sub.recv_group()) .await diff --git a/rs/moq-video/README.md b/rs/moq-video/README.md index 42c763de3b6..ed82678b8e4 100644 --- a/rs/moq-video/README.md +++ b/rs/moq-video/README.md @@ -242,7 +242,7 @@ decoded straight to system memory where the backend can and downloaded where it cannot. `decode::Config::scale_hint` asks a decoder with a hardware scaler (NVDEC) to emit that size; it is a hint, so check `Frame::size` and use `Frame::resize` for the exact size. `decode::Consumer` takes `decode::Options`, -which pairs that config with the subscription's `start` and `max_age`. +which pairs that config with the subscription's `start` and `max_delay`. Common feature sets: diff --git a/rs/moq-video/src/decode/consumer.rs b/rs/moq-video/src/decode/consumer.rs index 8566d3d759a..7704dd365b7 100644 --- a/rs/moq-video/src/decode/consumer.rs +++ b/rs/moq-video/src/decode/consumer.rs @@ -56,7 +56,7 @@ pub struct Options { /// (skip aggressively); set it to your playout buffer for a softer skip. /// Applied to the transport subscription and inherited by /// [`moq_mux::container::Consumer`]. - pub max_age: std::time::Duration, + pub max_delay: std::time::Duration, } impl Options { @@ -106,7 +106,7 @@ impl Consumer { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.video) - .with_max_age(options.max_age), + .with_max_delay(options.max_delay), ) .await?; // A decoder often opens on a track that is already cached: a replacement @@ -264,7 +264,7 @@ mod tests { // the second `next()` would then block forever waiting for a group that was // skipped. let mut export = - moq_mux::container::fmp4::Export::new(source, catalog).with_max_age(std::time::Duration::from_secs(30)); + moq_mux::container::fmp4::Export::new(source, catalog).with_max_delay(std::time::Duration::from_secs(30)); let init = export.next().await.unwrap().expect("CMAF init"); let fragment = export.next().await.unwrap().expect("CMAF fragment"); @@ -349,7 +349,7 @@ mod tests { // Wide enough to keep every group fresh: the age budget on its own // delivers only the live edge, which would pass this test without // `Start::Latest` doing anything. - max_age: std::time::Duration::from_secs(10), + max_delay: std::time::Duration::from_secs(10), ..Options::new() }, ) @@ -430,7 +430,7 @@ mod tests { }, // A budget that keeps every group fresh, so the start policy is the // only thing deciding what is read. - max_age: std::time::Duration::from_secs(10), + max_delay: std::time::Duration::from_secs(10), ..Options::new() }, ) @@ -459,7 +459,7 @@ mod tests { /// Driven by `pollster` rather than tokio: the probe's guard is a plain /// mutex, and holding one across an `.await` is what clippy rightly flags. #[test] - fn max_age_reaches_the_subscription_and_not_the_decoder() { + fn max_delay_reaches_the_subscription_and_not_the_decoder() { let _probe = probe::native_exclusive(); let broadcast = moq_net::broadcast::Info::new().produce(); let track = broadcast @@ -492,14 +492,14 @@ mod tests { output: crate::Output::Cpu, scale_hint: Some(crate::Size::new(160, 120)), }; - let max_age = std::time::Duration::from_secs(10); + let max_delay = std::time::Duration::from_secs(10); let mut consumer = pollster::block_on(Consumer::new( &subscriber, &catalog, "video", Options { decoder: decoder.clone(), - max_age, + max_delay, ..Options::new() }, )) @@ -507,7 +507,7 @@ mod tests { let subscription = published.subscription().expect("the consumer subscribed"); assert_eq!( - subscription.max_age, max_age, + subscription.max_delay, max_delay, "the age budget did not reach the publisher" ); @@ -626,7 +626,7 @@ mod tests { kind: Kind::Named(probe::BUFFERED_NAME.into()), ..Config::new() }, - max_age: std::time::Duration::from_secs(10), + max_delay: std::time::Duration::from_secs(10), ..Options::new() }, ) diff --git a/rs/moq-video/src/encode/producer.rs b/rs/moq-video/src/encode/producer.rs index c3d702c733f..d6fe58ad7bb 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -920,7 +920,7 @@ mod tests { catalog.track_info(hang::catalog::PRIORITY.video).with_max_age(replay), ) .unwrap(); - let consumer = track.subscribe(moq_net::track::Subscription::default().with_max_age(replay)); + let consumer = track.subscribe(moq_net::track::Subscription::default().with_max_delay(replay)); let mut config = Config::new(320, 240, crate::Rate::new(30, 1).unwrap()); config.kind = encoder::Kind::Software; @@ -1204,7 +1204,7 @@ mod tests { .consumer .track(name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_max_age(RETAIN)) + .subscribe(moq_net::track::Subscription::default().with_max_delay(RETAIN)) .await .unwrap(); moq_mux::container::Consumer::new(track, container) diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index 8c63ccf75fc..6189bf6c549 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -42,13 +42,13 @@ public typealias AudioEncoderInput = MoqFFI.MoqAudioEncoderInput /// The encoder-side config for a published audio track: codec, rate, channels, /// bitrate, and frame duration. public typealias AudioEncoderOutput = MoqFFI.MoqAudioEncoderOutput -/// What a `VideoConsumer` decodes to: an optional resize, a max age, and +/// What a `VideoConsumer` decodes to: an optional resize, a max delay, and /// whether frames keep the decoder's native surface. public typealias VideoDecoderOutput = MoqVideoDecoderOutput /// One decoded video frame, owning the decoder's surface until released; /// `pixels(format:)` converts it to packed CPU pixels. public typealias VideoDecodedFrame = MoqVideoDecodedFrame -/// The PCM layout an `AudioConsumer` decodes to, plus its max age. +/// The PCM layout an `AudioConsumer` decodes to, plus its max delay. public typealias AudioDecoderOutput = MoqFFI.MoqAudioDecoderOutput /// A raw PCM sample format, mirroring WebCodecs `AudioData.format`. public typealias AudioSampleFormat = MoqFFI.MoqAudioSampleFormat diff --git a/swift/Sources/Moq/AsyncStream.swift b/swift/Sources/Moq/AsyncStream.swift index 1728b70a265..d38fc19180d 100644 --- a/swift/Sources/Moq/AsyncStream.swift +++ b/swift/Sources/Moq/AsyncStream.swift @@ -5,7 +5,7 @@ import MoqFFI /// /// Pull-per-demand: `next` is called only when the consumer asks for the next /// element, never ahead of it. This is what preserves the FFI jitter buffer's -/// fall-behind skipping (`maxAgeUs` GoP-skipping): draining eagerly would +/// fall-behind skipping (`maxDelayUs` GoP-skipping): draining eagerly would /// move the backlog into an unbounded Swift buffer, so a slow consumer would /// grow memory and receive stale groups instead of skipping forward. /// diff --git a/swift/Sources/Moq/Broadcast.swift b/swift/Sources/Moq/Broadcast.swift index b171e6c3481..8c65cbcc21d 100644 --- a/swift/Sources/Moq/Broadcast.swift +++ b/swift/Sources/Moq/Broadcast.swift @@ -50,8 +50,8 @@ public final class BroadcastConsumer: Sendable { /// Subscribe to a media track, delivering frames in decode order. `container` /// comes from the catalog. `subscription` tunes delivery priority, group ordering - /// priority, group range, and the max age; omit for defaults. Raise - /// `Subscription.maxAgeUs` to buffer instead of skipping a stalled group. + /// priority, group range, and the max delay; omit for defaults. Raise + /// `Subscription.maxDelayUs` to buffer instead of skipping a stalled group. public func subscribeMedia( name: String, container: Container, diff --git a/test/audio-quality/README.md b/test/audio-quality/README.md index d9f0164e81a..b0ed6bdd79a 100644 --- a/test/audio-quality/README.md +++ b/test/audio-quality/README.md @@ -114,7 +114,7 @@ on the delay, so the replay decides those again. `replay.ts` plays a trace through the player's own `Container.Consumer` and rings on a simulated clock ([`js/watch/src/audio/replay.ts`](../../js/watch/src/audio/replay.ts)), at the "auto" delay a real `Sync` resolves from the playout target that consumer measures, and reads each quantum through -the tap's classifier. The consumer makes the player's group ordering, max age skips, and +the tap's classifier. The consumer makes the player's group ordering, max delay skips, and discontinuity resets again at that delay, and the ring follows the delay as it moves; a group's stream is taken to finish with its last recorded frame. Every frame is the trace's median spacing long, so a frame that never arrived stays missing audio, and rendering runs to the end of the observation, so an outage after the last arrival is heard. It diff --git a/test/audio-quality/clients/js/src/capture.test.ts b/test/audio-quality/clients/js/src/capture.test.ts index b674de62685..af642abe828 100644 --- a/test/audio-quality/clients/js/src/capture.test.ts +++ b/test/audio-quality/clients/js/src/capture.test.ts @@ -76,15 +76,15 @@ test("the observer shares playback demand and closes without ending playback", a numberOfChannels: 1, container: { kind: "legacy" }, } as Catalog.AudioConfig), - maxAge: new Signal(Time.Milli(250)), + maxDelay: new Signal(Time.Milli(250)), }); try { while (!track.subscription.peek()) await track.subscription.changed(); - expect(track.subscription.peek()).toMatchObject({ priority: Catalog.PRIORITY.audio, maxAge: 250 }); + expect(track.subscription.peek()).toMatchObject({ priority: Catalog.PRIORITY.audio, maxDelay: 250 }); const player = published .consume() .track("audio") - .subscribe({ priority: Catalog.PRIORITY.audio, maxAge: Time.Milli(250) }); + .subscribe({ priority: Catalog.PRIORITY.audio, maxDelay: Time.Milli(250) }); await capture.close(); expect(player.closed.peek()).toBeUndefined(); player.close(); @@ -113,7 +113,7 @@ async function captureGroupEnd(end: (group: Group.Producer) => void): Promise; track: Getter; config: Getter; - maxAge: Getter; + maxDelay: Getter; }; /** Record frames on the player's connection with its subscription settings. */ @@ -34,14 +34,14 @@ export class Capture { if (!active) return; const track = active .track(name) - .subscribe({ priority: Catalog.PRIORITY.audio, maxAge: input.maxAge.peek() }); + .subscribe({ priority: Catalog.PRIORITY.audio, maxDelay: input.maxDelay.peek() }); const groups = new Set(); effect.cleanup(() => { track.close(); for (const group of groups) group.close(); }); effect.run((inner) => - track.update({ priority: Catalog.PRIORITY.audio, maxAge: inner.get(input.maxAge) }), + track.update({ priority: Catalog.PRIORITY.audio, maxDelay: inner.get(input.maxDelay) }), ); effect.spawn(async () => { try { diff --git a/test/audio-quality/clients/js/src/probe.ts b/test/audio-quality/clients/js/src/probe.ts index f128432baf0..090ad0952e7 100644 --- a/test/audio-quality/clients/js/src/probe.ts +++ b/test/audio-quality/clients/js/src/probe.ts @@ -54,7 +54,7 @@ export function probe(watch: MoqWatch, capture = false): Probe { broadcast: audio.source.in.broadcast, track: audio.source.out.track, config: audio.source.out.config, - maxAge: sync.out.maxAge, + maxDelay: sync.out.maxDelay, }) : undefined; diff --git a/test/audio-quality/clients/js/src/recorder.ts b/test/audio-quality/clients/js/src/recorder.ts index ba53238c807..a9d46b36753 100644 --- a/test/audio-quality/clients/js/src/recorder.ts +++ b/test/audio-quality/clients/js/src/recorder.ts @@ -21,7 +21,7 @@ import { format, arrivals as readArrivals } from "./capture.ts"; import type { Arrival } from "./schema.ts"; /** How far back the relay may serve a group. Long, so a late group is recorded rather than dropped. */ -const MAX_AGE = Moq.Time.Milli(10_000); +const MAX_DELAY = Moq.Time.Milli(10_000); /** What the recorder has, until the driver drains it. */ export type Recorder = { @@ -86,7 +86,7 @@ async function record(): Promise { if (!name || !config) throw new Error("the catalog ended without an audio rendition"); const decoder = format(config); - const track = broadcast.track(name).subscribe({ priority: Catalog.PRIORITY.audio, maxAge: MAX_AGE }); + const track = broadcast.track(name).subscribe({ priority: Catalog.PRIORITY.audio, maxDelay: MAX_DELAY }); info = { transport: connection.transport, get rtt() { diff --git a/test/drain/drain.ts b/test/drain/drain.ts index 59716364ebc..e69302b8577 100644 --- a/test/drain/drain.ts +++ b/test/drain/drain.ts @@ -52,7 +52,7 @@ const HANDOVER = Moq.Time.Milli(2000); // drops its pull; the budget is what lets that resubscribe reach back to a group that was in // flight across the swap instead of starting at the next one. With none, a group boundary // landing inside the swap drops that group. -const MAX_AGE = Moq.Time.Milli(1000); +const MAX_DELAY = Moq.Time.Milli(1000); const path = Moq.Path.from("drain"); const trackName = "seq"; @@ -167,7 +167,7 @@ const follow = (active: Moq.Broadcast.Consumer | undefined) => { if (!active || active === current?.broadcast) return; generation++; log(`watching generation ${generation}`); - const sub = active.track(trackName).subscribe({ maxAge: MAX_AGE }); + const sub = active.track(trackName).subscribe({ maxDelay: MAX_DELAY }); void read(sub, generation); current?.sub.close(); current = { broadcast: active, sub }; diff --git a/test/interop/clients/go/main.go b/test/interop/clients/go/main.go index e99e482112b..4095102d92a 100644 --- a/test/interop/clients/go/main.go +++ b/test/interop/clients/go/main.go @@ -28,8 +28,8 @@ import ( const readChunk = 64 * 1024 -// SubscribeMedia max age: how much reordering the jitter buffer tolerates. -const maxAgeUs = 1_000_000 +// SubscribeMedia max delay: how much reordering the jitter buffer tolerates. +const maxDelayUs = 1_000_000 // Synthetic audio: a 48 kHz mono tone, encoded as Opus. const ( @@ -201,7 +201,7 @@ func subscribe(ctx context.Context, url, broadcast string, timeout time.Duration break } - media, err := consumer.SubscribeMedia(ctx, name, video.Container, &moq.Subscription{MaxAgeUs: maxAgeUs}) + media, err := consumer.SubscribeMedia(ctx, name, video.Container, &moq.Subscription{MaxDelayUs: maxDelayUs}) if err != nil { return err } diff --git a/test/interop/clients/js-native/subscribe.ts b/test/interop/clients/js-native/subscribe.ts index 59ec48610aa..f9c882a9190 100644 --- a/test/interop/clients/js-native/subscribe.ts +++ b/test/interop/clients/js-native/subscribe.ts @@ -28,7 +28,7 @@ install(); // subscribers. A relay drops a superseded group (RESET_STREAM Old) rather than // finish sending it, e.g. a cached group a fresh one lands right behind, so a // subscriber has to move on to the next group instead of failing. -const MAX_AGE = Moq.Time.Milli(1000); +const MAX_DELAY = Moq.Time.Milli(1000); const { positionals, values } = parseArgs({ allowPositionals: true, @@ -83,8 +83,8 @@ async function run(): Promise { throw new Error(`unsupported video container: ${JSON.stringify(config.container)}`); } - const sub = bc.track(name).subscribe({ priority: 0, maxAge: MAX_AGE }); - const consumer = new Container.Consumer(sub, { format, maxAge: MAX_AGE }); + const sub = bc.track(name).subscribe({ priority: 0, maxDelay: MAX_DELAY }); + const consumer = new Container.Consumer(sub, { format, maxDelay: MAX_DELAY }); try { for (;;) { const next = await consumer.next(); diff --git a/test/interop/clients/python/interop.py b/test/interop/clients/python/interop.py index ef4b7134c47..edf2a05e018 100644 --- a/test/interop/clients/python/interop.py +++ b/test/interop/clients/python/interop.py @@ -21,7 +21,7 @@ import moq READ_CHUNK = 64 * 1024 -MAX_AGE_US = 1_000_000 # subscribe_media congestion-control / lookahead window +MAX_DELAY_US = 1_000_000 # subscribe_media congestion-control / lookahead window # Synthetic audio: a 48 kHz mono tone, encoded as Opus. AUDIO_TRACK = "tone" @@ -105,7 +105,7 @@ async def subscribe(url: str, broadcast: str, timeout: float) -> None: video = catalog.video[track_name] media = await consumer.subscribe_media( - track_name, video.container, moq.Subscription(max_age_us=MAX_AGE_US) + track_name, video.container, moq.Subscription(max_delay_us=MAX_DELAY_US) ) total = 0