From 4790edfd7eb049e5f3fbfcf56c3bd6af28613bcc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 20 Aug 2026 01:28:14 -0700 Subject: [PATCH 1/4] refactor(net)!: replace the Latency type with a plain `max_age` duration `Latency` (added in #2688) wrapped a single `Duration` field. 125 of its 164 uses were `Latency::max(..)`, a wrapper applied at the call site and unwrapped at the comparison sites, and `merge` had exactly one caller. Its remaining justification was room for a future `min`, but a minimum belongs at presentation, where there is a render clock to hold data against. A delivery layer has no instant to enforce it at, and holding arrived bytes back there only adds delay while blinding the receiver's own buffer. So the type collapses to the duration it always was, and the name follows what the field measures. `latency` promised an end-to-end budget the field cannot carry: a subscriber's total is the publisher's emission cadence plus this value, so `latency: 300ms` against a 2s-cadence stream is 2.3s. `max_age` claims nothing about the total, and the implementation already reached for the name on its own (`evict_expired(max_age)`). - `Subscription::latency: Latency` -> `max_age: Duration` - `track::Info::latency_max` -> `max_age`, `DEFAULT_LATENCY_MAX` -> `DEFAULT_MAX_AGE` - `origin::Info::latency_default` -> `default_max_age` (`cache_duration` keeps its name: it pairs with `pool` as the origin's two cache budgets) - `Latency::REAL_TIME` -> `Duration::ZERO`, `Latency::merge` -> `Duration::max` - moq-lite `Subscriber/Publisher Max Latency` -> `Max Age` in the draft, wire bytes unchanged; mirrored in js/net The type's docs move onto `Subscription::max_age`, which is where a reader looking for them now lands. The moq-rtmp gateway configs carried both fields under one name once renamed, so they split into `import_max_age` (retention on tracks the gateway mints) and `export_max_age` (the FLV muxer's skip threshold). `import`/`export` rather than `play`/`publish` because those invert between the server and the dialing client. CLI flags are untouched: the two `#[arg(long)]` fields that derived their spelling from the field name now pin `long = "latency-max"` explicitly. Co-Authored-By: Claude Opus 5 --- demo/web/src/publish.ts | 2 +- doc/concept/layer/moq-lite.md | 6 +- drafts/draft-lcurley-moq-lite.md | 29 +-- js/hang/src/container/track.ts | 10 +- js/net/src/broadcast.test.ts | 12 +- js/net/src/integration.test.ts | 8 +- js/net/src/lite/publisher.test.ts | 2 +- js/net/src/lite/publisher.ts | 10 +- js/net/src/lite/subscribe.test.ts | 10 +- js/net/src/lite/subscribe.ts | 40 +-- js/net/src/lite/subscriber.ts | 14 +- js/net/src/lite/track.test.ts | 4 +- js/net/src/lite/track.ts | 16 +- js/net/src/track.test.ts | 14 +- js/net/src/track.ts | 22 +- js/publish/src/broadcast.ts | 6 +- rs/hang/examples/subscribe.rs | 4 +- rs/hang/src/container/frame.rs | 18 +- rs/libmoq/src/api.rs | 10 +- rs/libmoq/src/audio.rs | 2 +- rs/libmoq/src/consume.rs | 8 +- rs/libmoq/src/video.rs | 2 +- rs/moq-audio/src/decode/consumer.rs | 8 +- rs/moq-audio/src/decode/decoder.rs | 6 +- rs/moq-audio/tests/roundtrip.rs | 4 +- rs/moq-bench/src/connection.rs | 2 +- rs/moq-cli/src/args.rs | 37 ++- rs/moq-cli/src/hls.rs | 4 +- rs/moq-cli/src/main.rs | 22 +- rs/moq-cli/src/moq.rs | 2 +- rs/moq-cli/src/play.rs | 8 +- rs/moq-cli/src/publish.rs | 16 +- rs/moq-cli/src/rtc.rs | 4 +- rs/moq-cli/src/rtmp.rs | 29 +-- rs/moq-cli/src/srt.rs | 10 +- rs/moq-cli/src/subscribe.rs | 14 +- rs/moq-ffi/src/audio.rs | 5 +- rs/moq-ffi/src/consumer.rs | 4 +- rs/moq-ffi/src/producer.rs | 8 +- rs/moq-ffi/src/video.rs | 4 +- rs/moq-gst/src/source/imp.rs | 4 +- rs/moq-mux/src/catalog/producer.rs | 44 ++-- rs/moq-mux/src/codec/h264/export.rs | 16 +- rs/moq-mux/src/codec/h265/export.rs | 16 +- rs/moq-mux/src/container/consumer.rs | 241 +++++++++---------- rs/moq-mux/src/container/flv/export.rs | 16 +- rs/moq-mux/src/container/flv/export_test.rs | 6 +- rs/moq-mux/src/container/flv/import_test.rs | 18 +- rs/moq-mux/src/container/fmp4/export.rs | 16 +- rs/moq-mux/src/container/fmp4/export_test.rs | 6 +- rs/moq-mux/src/container/fmp4/import_test.rs | 6 +- rs/moq-mux/src/container/group.rs | 4 +- rs/moq-mux/src/container/mkv/export.rs | 16 +- rs/moq-mux/src/container/mkv/export_test.rs | 8 +- rs/moq-mux/src/container/mod.rs | 2 +- rs/moq-mux/src/container/producer.rs | 18 +- rs/moq-mux/src/container/source.rs | 46 ++-- rs/moq-mux/src/container/ts/export.rs | 30 +-- rs/moq-mux/src/container/ts/export_test.rs | 34 +-- rs/moq-mux/src/container/ts/import.rs | 38 ++- rs/moq-mux/src/container/ts/import_test.rs | 12 +- rs/moq-mux/src/import/track.rs | 5 +- rs/moq-mux/src/lib.rs | 4 +- rs/moq-net/src/ietf/publisher.rs | 34 +-- rs/moq-net/src/ietf/subscriber.rs | 48 ++-- rs/moq-net/src/latency.rs | 77 ------ rs/moq-net/src/lib.rs | 2 - rs/moq-net/src/lite/publisher.rs | 49 ++-- rs/moq-net/src/lite/subscribe.rs | 42 ++-- rs/moq-net/src/lite/subscriber.rs | 22 +- rs/moq-net/src/lite/track.rs | 16 +- rs/moq-net/src/model/broadcast.rs | 4 +- rs/moq-net/src/model/group.rs | 6 +- rs/moq-net/src/model/origin.rs | 52 ++-- rs/moq-net/src/model/resume.rs | 52 ++-- rs/moq-net/src/model/subscription.rs | 60 +++-- rs/moq-net/src/model/track.rs | 217 ++++++++--------- rs/moq-net/src/stats.rs | 4 +- rs/moq-relay/tests/cluster_unknown.rs | 5 +- rs/moq-relay/tests/goaway_cluster.rs | 2 +- rs/moq-rtc/src/client/mod.rs | 4 +- rs/moq-rtc/src/client/whep.rs | 2 +- rs/moq-rtc/src/ingest.rs | 6 +- rs/moq-rtc/src/server/mod.rs | 4 +- rs/moq-rtc/src/server/whip.rs | 2 +- rs/moq-rtmp/src/dial.rs | 32 +-- rs/moq-rtmp/src/lib.rs | 5 +- rs/moq-rtmp/src/listen.rs | 18 +- rs/moq-rtmp/src/server.rs | 34 +-- rs/moq-srt/src/dial.rs | 6 +- rs/moq-srt/src/listen.rs | 8 +- rs/moq-srt/src/server.rs | 16 +- rs/moq-srt/src/ts.rs | 12 +- rs/moq-tokio/tests/broadcast.rs | 53 ++-- rs/moq-video/src/decode/consumer.rs | 6 +- rs/moq-video/src/decode/decoder.rs | 6 +- 96 files changed, 918 insertions(+), 1030 deletions(-) delete mode 100644 rs/moq-net/src/latency.rs diff --git a/demo/web/src/publish.ts b/demo/web/src/publish.ts index 26f23e8f3ee..1659e9d1e88 100644 --- a/demo/web/src/publish.ts +++ b/demo/web/src/publish.ts @@ -404,7 +404,7 @@ meta.run((effect) => { if (!net) return; // A day-long cache so a viewer joining long after the last edit still replays the value. - const track = net.createTrack(META_TRACK, { latencyMax: 86_400_000 }); + const track = net.createTrack(META_TRACK, { maxAge: 86_400_000 }); effect.cleanup(() => track.close()); const producer = new Json.Snapshot.Producer({ track }); diff --git a/doc/concept/layer/moq-lite.md b/doc/concept/layer/moq-lite.md index 974a6788e68..cba62ca586c 100644 --- a/doc/concept/layer/moq-lite.md +++ b/doc/concept/layer/moq-lite.md @@ -114,7 +114,7 @@ Each Subscription consists of a few properties: - **Track Priority**: A value between 0 and 255. Tracks with higher priority will be delivered first. - **Group Order**: The order in which groups are delivered. Defaults to descending; higher IDs are delivered first. -- **Subscriber Max Latency**: The maximum age of a non-latest group before it is skipped. Defaults to zero, so stale groups are skipped immediately. +- **Subscriber Max Age**: How old a non-latest group may get before it is skipped. Defaults to zero, so stale groups are skipped immediately. That age is measured both on the media timeline (a group's first timestamp against the newest stamped one) and by wall-clock arrival time, and either limit can expire the group. The media timeline keeps a backlog delivered as a burst old, while wall-clock time backstops stalled or empty groups that have no timestamp. @@ -122,8 +122,8 @@ Both ends apply it: the publisher skips a group rather than sending it, and the The publisher only ever sees the most tolerant budget across its subscribers, which is why the subscriber applies it too. Asking for old groups with `Group Start` does not exempt them: a start bounds what you are sent, and a subscriber that wants history has to raise its budget to match. -The publisher also keeps old groups around for a best-effort **Publisher Max Latency** cache window so relays and late subscribers can still fetch them. This defaults to 5 seconds. -The subscriber's maximum latency is bounded by this window: a group can't be waited for longer than it's actually kept around. +The publisher also keeps old groups around for a best-effort **Publisher Max Age** cache window so relays and late subscribers can still fetch them. This defaults to 5 seconds. +The subscriber's max age is bounded by this window: a group can't be waited for longer than it's actually kept around. It is declared per track, so a publisher raises it on the tracks that are read as history rather than followed at the live edge. hang media tracks ask for 30 seconds on that basis: a segmented egress (HLS/DASH) may only advertise segments a fetch can still reach, and a standard player starts several segments behind the live edge. diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index b8146cf2547..f43aec0dca2 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -132,7 +132,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. - `Ordered` indicates if the Groups within a Track should be transmitted in order. -- `Subscriber Max Latency` indicates the maximum age before a non-latest Group is dropped from live delivery; `Publisher Max Latency` indicates the maximum age before a non-latest Group is dropped from the publisher's cache. +- `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. The combination of these preferences enables the most important content to arrive during network degradation while still respecting encoding dependencies. @@ -496,20 +496,20 @@ An application SHOULD use `ordered` when it wants to provide a VOD-like experien An application SHOULD NOT use `ordered` when it wants to provide a live experience, preferring to skip old groups rather than buffer them. Note that [expiration](#expiration) is not affected by `ordered`. -An old group may still be cancelled/skipped if it exceeds the `Subscriber Max Latency`. +An old group may still be cancelled/skipped if it exceeds the `Subscriber Max Age`. An application MUST support gaps and out-of-order delivery even when `ordered` is true. ## Expiration Expiration governs when an older group is dropped. -The publisher SHOULD reset Group Streams for non-latest groups whose age relative to the latest group exceeds `Subscriber Max Latency` (see [SUBSCRIBE](#subscribe)); the subscriber MAY also locally drop such groups. -Expiration only removes the group from live delivery; the publisher MAY still retain it for FETCH or new subscriptions until its age exceeds `Publisher Max Latency` (see [TRACK_INFO](#track-info)). +The publisher SHOULD reset Group Streams for non-latest groups whose age relative to the latest group exceeds `Subscriber Max Age` (see [SUBSCRIBE](#subscribe)); the subscriber MAY also locally drop such groups. +Expiration only removes the group from live delivery; the publisher MAY still retain it for FETCH or new subscriptions until its age exceeds `Publisher Max Age` (see [TRACK_INFO](#track-info)). It is not crucial to aggressively expire groups thanks to [prioritization](#prioritization), but a lower priority group still consumes RAM, bandwidth, and potentially flow control. It is RECOMMENDED that an application set conservative limits and only resort to expiration when data is absolutely no longer needed. A group is never expired until at least the next group (by sequence number) has been received or queued. -Once a newer group exists, the group's age is measured two ways, and it is expired once **either** measure exceeds the relevant `Max Latency`: +Once a newer group exists, the group's age is measured two ways, and it is expired once **either** measure exceeds the relevant `Max Age`: - **Timestamp age**: the difference between this group's first frame timestamp and the first frame timestamp of the latest group that has at least one frame. This measure is consistent across relays and unaffected by buffering or jitter. - **Wall-clock age**: the difference between when this group's first byte arrived (subscriber) or was queued (publisher) and the same instant for the latest group. @@ -922,7 +922,7 @@ SUBSCRIBE Message { Epoch (i) Subscriber Priority (8) Subscriber Ordered (8) - Subscriber Max Latency (i) + Subscriber Max Age (i) Group Start (i) Group End (i) Frame Start (i) @@ -948,12 +948,12 @@ A single byte representing whether groups are transmitted in ascending (0x1) or The publisher SHOULD transmit *older* groups first during congestion if true. See the [Prioritization](#prioritization) section for more information. -**Subscriber Max Latency**: +**Subscriber Max Age**: The subscriber's preference, in milliseconds, for how long a non-latest group may remain in flight before being considered stale and dropped from live delivery. The publisher SHOULD reset (at the QUIC level) Group Streams for groups whose age relative to the latest group exceeds this duration. Applies only to non-latest groups; the latest group is never dropped on staleness grounds. A value of `0` means the subscriber wants only the latest group in live delivery (older groups are immediately stale once a newer group arrives). -This is a delivery-time preference, not a retention rule: the publisher MAY still hold these groups for FETCH or future subscriptions (see `Publisher Max Latency` in [TRACK_INFO](#track-info)). +This is a delivery-time preference, not a retention rule: the publisher MAY still hold these groups for FETCH or future subscriptions (see `Publisher Max Age` in [TRACK_INFO](#track-info)). See the [Expiration](#expiration) section for more information. **Group Start**: @@ -991,7 +991,7 @@ SUBSCRIBE_UPDATE Message { Message Length (i) Subscriber Priority (8) Subscriber Ordered (8) - Subscriber Max Latency (i) + Subscriber Max Age (i) Group Start (i) Group End (i) Frame Start (i) @@ -1035,7 +1035,7 @@ TRACK_INFO Message { Epoch (i) Publisher Priority (8) Publisher Ordered (8) - Publisher Max Latency (i) + Publisher Max Age (i) Timescale (i) } ~~~ @@ -1056,16 +1056,16 @@ See the [Prioritization](#prioritization) section for more information. The publisher's group ordering preference (ascending `0x1` or descending `0x0`), used only to resolve ties. See the [Prioritization](#prioritization) section for more information. -**Publisher Max Latency**: +**Publisher Max Age**: The maximum age, in milliseconds, that the publisher caches a non-latest group past the arrival of a newer group. Applies only to non-latest groups; the latest group is always retained. It is an upper bound on retention, the inverse of an HTTP `Cache-Control: max-age` guarantee: -- A subscriber MAY issue a SUBSCRIBE or FETCH with an older `Group Start`, but the publisher MAY have already dropped any group whose age exceeds `Publisher Max Latency`. -- The publisher MAY drop groups sooner than `Publisher Max Latency` under resource pressure; subscribers MUST NOT assume older groups within the bound are still available. +- A subscriber MAY issue a SUBSCRIBE or FETCH with an older `Group Start`, but the publisher MAY have already dropped any group whose age exceeds `Publisher Max Age`. +- The publisher MAY drop groups sooner than `Publisher Max Age` under resource pressure; subscribers MUST NOT assume older groups within the bound are still available. A value of `0` means the publisher caches only the latest group (older groups MAY be dropped as soon as a newer group arrives). -The unit is milliseconds, matching `Subscriber Max Latency`. +The unit is milliseconds, matching `Subscriber Max Age`. See the [Expiration](#expiration) section for more information. **Timescale**: @@ -1336,6 +1336,7 @@ The `Message Length` describes the payload size on the wire. - Restricted the GOAWAY New Session URI to servers, specified a duplicate GOAWAY as a protocol violation, and recommended scheme continuity and sticky redirects. - Exempted a ceiling-cost serving path from the actively-carrying cost discount: a relay whose serving path costs the saturation ceiling (primarily a session that received a GOAWAY) advertises the ceiling instead of 0, so the drain propagates downstream instead of being re-masked by each carrying hop. Keyed on the value, not the reason, which does not travel on the wire. - Added the Error Codes section, defining separate session and stream code spaces and listing the codes moq-lite uses, reused unchanged from moq-transport. Codes 64+ are the application's; 32-63 are reserved and MUST NOT be interpreted, pending a future revision. Previously the codes were unspecified, so an endpoint could neither send one a peer would understand nor safely interpret one it received. Note this renumbers every code an existing implementation sent, and that a stream reset of 0x0 is now INTERNAL_ERROR rather than a cancellation (CANCELLED is 0x1). +- Renamed `Subscriber Max Latency` to `Subscriber Max Age` and `Publisher Max Latency` to `Publisher Max Age`. Both already measured a group's age, and neither bounds end-to-end latency: a subscriber's total is the publisher's emission cadence plus this budget, so the old name promised something the field does not carry. ## moq-lite-05 - Renamed ANNOUNCE_INTEREST to ANNOUNCE_REQUEST and ANNOUNCE to ANNOUNCE_BROADCAST. diff --git a/js/hang/src/container/track.ts b/js/hang/src/container/track.ts index 48f5e804541..ca0ac9fe75c 100644 --- a/js/hang/src/container/track.ts +++ b/js/hang/src/container/track.ts @@ -9,9 +9,9 @@ import { Time, type Track } from "@moq/net"; // How long a media track asks its publisher (and, through TRACK_INFO, every relay) to keep a -// non-latest group fetchable. Must match `hang::container::LATENCY_MAX` in +// non-latest group fetchable. Must match `hang::container::MAX_AGE` in // rs/hang/src/container/frame.rs. -const LATENCY_MAX_MS = 30_000; +const MAX_AGE_MS = 30_000; /** * Track properties for a track carrying media frames, for `Request.accept`. @@ -24,10 +24,10 @@ const LATENCY_MAX_MS = 30_000; * read at the live edge, which is retained unconditionally, so neither pays for history it never * serves. * - * Options override that retention; see {@link TrackInfoOptions.latencyMax}. + * Options override that retention; see {@link TrackInfoOptions.maxAge}. */ export function trackInfo(options?: TrackInfoOptions): Partial { - return { timescale: Time.Timescale.MICRO, latencyMax: options?.latencyMax ?? LATENCY_MAX_MS }; + return { timescale: Time.Timescale.MICRO, maxAge: options?.maxAge ?? MAX_AGE_MS }; } /** Overrides for {@link trackInfo}. */ @@ -39,5 +39,5 @@ export type TrackInfoOptions = { * A RETENTION budget, not a delivery one, so it never makes anyone play further behind live * and lowering it does not reduce latency: it only shortens how far back a fetch can reach. */ - latencyMax?: number; + maxAge?: number; }; diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index ea40cbcf277..3fdb808e2cc 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -54,14 +54,14 @@ test("consumer dedupes repeat subscriptions onto one upstream request", async () test("a request exposes the aggregate subscription options", async () => { const consumer = new TestConsumer(); - consumer.subscribe("video", { priority: 3, ordered: true, latencyMax: 100, startGroup: 10, endGroup: 20 }); - consumer.subscribe("video", { priority: 7, ordered: true, latencyMax: 250, startGroup: 0, endGroup: 30 }); + consumer.subscribe("video", { priority: 3, ordered: true, maxAge: 100, startGroup: 10, endGroup: 20 }); + consumer.subscribe("video", { priority: 7, ordered: true, maxAge: 250, startGroup: 0, endGroup: 30 }); const request = await pendingRequest(consumer); expect(request?.subscription).toEqual({ priority: 7, ordered: true, - latencyMax: 250, + maxAge: 250, startGroup: 0, endGroup: 30, }); @@ -213,7 +213,7 @@ test("a stalled consumer does not pin evicted groups", async () => { setSystemTime(new Date(10_000)); const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { latencyMax: 1000 }); + const producer = broadcast.createTrack("video", { maxAge: 1000 }); // A subscriber that never reads. Its sink must not grow without bound. const stalled = broadcast.track("video").subscribe(); @@ -242,11 +242,11 @@ test("a stalled consumer does not pin evicted groups", async () => { test("createTrack commits info up front", async () => { const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { latencyMax: 2000, priority: 3 }); + const producer = broadcast.createTrack("video", { maxAge: 2000, priority: 3 }); expect(producer.name).toBe("video"); const info = await broadcast.track("video").info(); - expect(info.latencyMax).toBe(2000); + expect(info.maxAge).toBe(2000); expect(info.priority).toBe(3); }); diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index eb18664f4f0..f3580a76375 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -140,7 +140,7 @@ test("integration: lite subscription options and updates reach the publisher", a const subscriber = remote.track("video").subscribe({ priority: 3, ordered: true, - latencyMax: 250, + maxAge: 250, startGroup: 0, endGroup: 9, }); @@ -148,17 +148,17 @@ test("integration: lite subscription options and updates reach the publisher", a expect(producer.subscription.peek()).toEqual({ priority: 3, ordered: true, - latencyMax: 250, + maxAge: 250, startGroup: 0, endGroup: 9, }); const updated = producer.subscription.changed(); - subscriber.update({ priority: 8, ordered: false, latencyMax: 500, startGroup: 2, endGroup: 12 }); + subscriber.update({ priority: 8, ordered: false, maxAge: 500, startGroup: 2, endGroup: 12 }); expect(await updated).toEqual({ priority: 8, ordered: false, - latencyMax: 500, + maxAge: 500, startGroup: 2, endGroup: 12, }); diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index ebce2145a97..f741f19f78b 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -802,7 +802,7 @@ test("lite draft-06: scheduling updates apply while SUBSCRIBE_START is blocked", expect(sub.track.subscription.peek()).toEqual({ priority: 9, ordered: true, - latencyMax: 0, + maxAge: 0, startGroup: undefined, endGroup: 5, }); diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index 064f0c385cd..bcaf54a7205 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -453,7 +453,7 @@ export class Publisher { const track = broadcast.subscribe(msg.track, { priority: msg.priority, ordered: msg.ordered, - latencyMax: msg.latencyMax, + maxAge: msg.maxAge, startGroup: msg.startGroup, endGroup: msg.endGroup, }); @@ -487,7 +487,7 @@ export class Publisher { const ok = new SubscribeOk({ priority: msg.priority, ordered: msg.ordered, - latencyMax: msg.latencyMax, + maxAge: msg.maxAge, startGroup: msg.startGroup, endGroup: msg.endGroup, }); @@ -510,7 +510,7 @@ export class Publisher { track.update({ priority: update.priority, ordered: update.ordered, - latencyMax: update.latencyMax, + maxAge: update.maxAge, startGroup: update.startGroup, endGroup: update.endGroup, }); @@ -769,9 +769,9 @@ export class Publisher { return new TrackInfoMessage({ priority: info.priority, ordered: info.ordered, - // Publisher Max Latency: the publisher's retention bound, advertised so + // Publisher Max Age: the publisher's retention bound, advertised so // relays re-serve with the same window. - latencyMax: info.latencyMax, + maxAge: info.maxAge, // Lite05 mandates per-frame timestamps. Advertise the track's timescale; // `#runGroup` emits each frame converted to it. timescale: info.timescale, diff --git a/js/net/src/lite/subscribe.test.ts b/js/net/src/lite/subscribe.test.ts index c473025d40a..6aa2ebf165a 100644 --- a/js/net/src/lite/subscribe.test.ts +++ b/js/net/src/lite/subscribe.test.ts @@ -66,7 +66,7 @@ async function encodeMessage( test("SubscribeOk round-trips priority/ordered/groups on draft-04", async () => { const got = await responseRoundtrip(Version.DRAFT_04, { - ok: new SubscribeOk({ priority: 7, ordered: true, latencyMax: 250, startGroup: 3 }), + ok: new SubscribeOk({ priority: 7, ordered: true, maxAge: 250, startGroup: 3 }), }); expect("ok" in got).toBe(true); if (!("ok" in got)) throw new Error("expected ok"); @@ -82,7 +82,7 @@ test("Subscribe round-trips every option including startGroup 0", async () => { track: "video", priority: 7, ordered: true, - latencyMax: 250, + maxAge: 250, startGroup: 0, endGroup: 9, }); @@ -92,7 +92,7 @@ test("Subscribe round-trips every option including startGroup 0", async () => { ); expect(got.priority).toBe(7); expect(got.ordered).toBe(true); - expect(got.latencyMax).toBe(250); + expect(got.maxAge).toBe(250); expect(got.startGroup).toBe(0); expect(got.endGroup).toBe(9); }); @@ -101,7 +101,7 @@ test("SubscribeUpdate round-trips every option including startGroup 0", async () const message = new SubscribeUpdate({ priority: 8, ordered: true, - latencyMax: 500, + maxAge: 500, startGroup: 0, endGroup: 12, }); @@ -111,7 +111,7 @@ test("SubscribeUpdate round-trips every option including startGroup 0", async () ); expect(got.priority).toBe(8); expect(got.ordered).toBe(true); - expect(got.latencyMax).toBe(500); + expect(got.maxAge).toBe(500); expect(got.startGroup).toBe(0); expect(got.endGroup).toBe(12); }); diff --git a/js/net/src/lite/subscribe.ts b/js/net/src/lite/subscribe.ts index 304aeec72a2..4a2be25a3fe 100644 --- a/js/net/src/lite/subscribe.ts +++ b/js/net/src/lite/subscribe.ts @@ -63,7 +63,7 @@ export class SubscribeUpdate { priority: number; ordered: boolean; /** Subscriber max latency in milliseconds; zero skips once a newer group is available. */ - latencyMax: number; + maxAge: number; startGroup?: number; endGroup?: number; /** See {@link Subscribe.startFrame}. */ @@ -74,7 +74,7 @@ export class SubscribeUpdate { constructor(props: { priority: number; ordered?: boolean; - latencyMax?: number; + maxAge?: number; startGroup?: number; endGroup?: number; startFrame?: number; @@ -82,7 +82,7 @@ export class SubscribeUpdate { }) { this.priority = props.priority; this.ordered = props.ordered ?? false; - this.latencyMax = props.latencyMax ?? 0; + this.maxAge = props.maxAge ?? 0; this.startGroup = props.startGroup; this.endGroup = props.endGroup; this.startFrame = props.startFrame ?? 0; @@ -98,7 +98,7 @@ export class SubscribeUpdate { default: await w.u8(this.priority); await w.bool(this.ordered); - await w.u53(this.latencyMax); + await w.u53(this.maxAge); await w.u53(this.startGroup !== undefined ? this.startGroup + 1 : 0); await w.u53(this.endGroup !== undefined ? this.endGroup + 1 : 0); await encodeFrameBounds(w, version, this); @@ -114,7 +114,7 @@ export class SubscribeUpdate { default: { const priority = await r.u8(); const ordered = await r.bool(); - const latencyMax = await r.u53(); + const maxAge = await r.u53(); const startGroup = (await r.u53()) || undefined; const endGroup = (await r.u53()) || undefined; const frames = await decodeFrameBounds( @@ -126,7 +126,7 @@ export class SubscribeUpdate { return new SubscribeUpdate({ priority, ordered, - latencyMax, + maxAge, startGroup: startGroup !== undefined ? startGroup - 1 : undefined, endGroup: endGroup !== undefined ? endGroup - 1 : undefined, ...frames, @@ -155,7 +155,7 @@ export class Subscribe { priority: number; ordered: boolean; /** Subscriber max latency in milliseconds; zero skips once a newer group is available. */ - latencyMax: number; + maxAge: number; startGroup?: number; endGroup?: number; @@ -178,7 +178,7 @@ export class Subscribe { track: string; priority: number; ordered?: boolean; - latencyMax?: number; + maxAge?: number; startGroup?: number; endGroup?: number; startFrame?: number; @@ -189,7 +189,7 @@ export class Subscribe { this.track = props.track; this.priority = props.priority; this.ordered = props.ordered ?? false; - this.latencyMax = props.latencyMax ?? 0; + this.maxAge = props.maxAge ?? 0; this.startGroup = props.startGroup; this.endGroup = props.endGroup; this.startFrame = props.startFrame ?? 0; @@ -208,7 +208,7 @@ export class Subscribe { break; default: await w.bool(this.ordered); - await w.u53(this.latencyMax); + await w.u53(this.maxAge); await w.u53(this.startGroup !== undefined ? this.startGroup + 1 : 0); await w.u53(this.endGroup !== undefined ? this.endGroup + 1 : 0); await encodeFrameBounds(w, version, this); @@ -228,7 +228,7 @@ export class Subscribe { return new Subscribe({ id, broadcast, track, priority }); default: { const ordered = await r.bool(); - const latencyMax = await r.u53(); + const maxAge = await r.u53(); const startGroup = (await r.u53()) || undefined; const endGroup = (await r.u53()) || undefined; const start = startGroup !== undefined ? startGroup - 1 : undefined; @@ -240,7 +240,7 @@ export class Subscribe { track, priority, ordered, - latencyMax, + maxAge, startGroup: start, endGroup: end, ...frames, @@ -268,26 +268,26 @@ export class SubscribeOk { priority: number; ordered: boolean; /** Accepted subscriber max latency in milliseconds. */ - latencyMax: number; + maxAge: number; startGroup?: number; endGroup?: number; constructor({ priority = 0, ordered = false, - latencyMax = 0, + maxAge = 0, startGroup = undefined, endGroup = undefined, }: { priority?: number; ordered?: boolean; - latencyMax?: number; + maxAge?: number; startGroup?: number; endGroup?: number; }) { this.priority = priority; this.ordered = ordered; - this.latencyMax = latencyMax; + this.maxAge = maxAge; this.startGroup = startGroup; this.endGroup = endGroup; } @@ -305,7 +305,7 @@ export class SubscribeOk { default: await w.u8(this.priority); await w.bool(this.ordered); - await w.u53(this.latencyMax); + await w.u53(this.maxAge); await w.u53(this.startGroup !== undefined ? this.startGroup + 1 : 0); await w.u53(this.endGroup !== undefined ? this.endGroup + 1 : 0); break; @@ -315,7 +315,7 @@ export class SubscribeOk { static async #decode(version: Version, r: Reader): Promise { let priority: number | undefined; let ordered: boolean | undefined; - let latencyMax: number | undefined; + let maxAge: number | undefined; let startGroup: number | undefined; let endGroup: number | undefined; @@ -329,7 +329,7 @@ export class SubscribeOk { default: priority = await r.u8(); ordered = await r.bool(); - latencyMax = await r.u53(); + maxAge = await r.u53(); startGroup = await r.u53(); endGroup = await r.u53(); break; @@ -338,7 +338,7 @@ export class SubscribeOk { return new SubscribeOk({ priority, ordered, - latencyMax, + maxAge, 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 4cf41f0ebae..fdda1396fe1 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -372,7 +372,7 @@ export class Subscriber { track: request.name, priority: subscription.priority ?? 0, ordered: subscription.ordered, - latencyMax: subscription.latencyMax, + maxAge: subscription.maxAge, startGroup: subscription.startGroup, endGroup: subscription.endGroup, }); @@ -518,9 +518,9 @@ export class Subscriber { #toModelInfo(info: TrackInfo): track.Info { return { timescale: Time.Timescale(info.timescale), - // Publisher Max Latency rides on the wire, so the local retention window + // Publisher Max Age rides on the wire, so the local retention window // matches what the upstream advertises (relays re-serve with the same bound). - latencyMax: info.latencyMax, + maxAge: info.maxAge, priority: info.priority, ordered: info.ordered, }; @@ -680,7 +680,7 @@ export class Subscriber { let lastSent: track.Subscription = { priority: msg.priority, ordered: msg.ordered, - latencyMax: msg.latencyMax, + maxAge: msg.maxAge, startGroup: msg.startGroup, endGroup: msg.endGroup, }; @@ -695,11 +695,11 @@ export class Subscriber { } // Round-trip the other Subscribe parameters so the publisher doesn't - // interpret SUBSCRIBE_UPDATE as a reset of ordered/latencyMax/etc. + // interpret SUBSCRIBE_UPDATE as a reset of ordered/maxAge/etc. const update = new SubscribeUpdate({ priority: current.priority ?? 0, ordered: current.ordered, - latencyMax: current.latencyMax, + maxAge: current.maxAge, startGroup: current.startGroup, endGroup: current.endGroup, }); @@ -713,7 +713,7 @@ export class Subscriber { return ( (a.priority ?? 0) === (b.priority ?? 0) && (a.ordered ?? false) === (b.ordered ?? false) && - (a.latencyMax ?? 0) === (b.latencyMax ?? 0) && + (a.maxAge ?? 0) === (b.maxAge ?? 0) && a.startGroup === b.startGroup && a.endGroup === b.endGroup ); diff --git a/js/net/src/lite/track.test.ts b/js/net/src/lite/track.test.ts index 62f51a99d61..f794cf42180 100644 --- a/js/net/src/lite/track.test.ts +++ b/js/net/src/lite/track.test.ts @@ -31,14 +31,14 @@ test("TrackInfo round-trips on draft-05", async () => { const info = new TrackInfo({ priority: 7, ordered: false, - latencyMax: 2000, + maxAge: 2000, timescale: 90000, }); const reader = new Reader(undefined, await bytes((w) => info.encode(w, Version.DRAFT_05))); const got = await TrackInfo.decode(reader, Version.DRAFT_05); expect(got.priority).toBe(7); expect(got.ordered).toBe(false); - expect(got.latencyMax).toBe(2000); + expect(got.maxAge).toBe(2000); expect(got.timescale).toBe(90000); }); diff --git a/js/net/src/lite/track.ts b/js/net/src/lite/track.ts index 916a83f28ee..9a6d0e589b6 100644 --- a/js/net/src/lite/track.ts +++ b/js/net/src/lite/track.ts @@ -65,10 +65,10 @@ export class TrackInfo { */ ordered: boolean; /** - * Publisher Max Latency: an upper bound (milliseconds) on how long the publisher + * Publisher Max Age: an upper bound (milliseconds) on how long the publisher * caches a non-latest group past the arrival of a newer one. */ - latencyMax: number; + maxAge: number; /** * Per-frame timestamp scale (units per second). Mandatory on Lite05: a real * (non-zero) scale, and every frame on the wire is prefixed with a zigzag-delta @@ -79,36 +79,36 @@ export class TrackInfo { constructor({ priority = 0, ordered = false, - latencyMax = 0, + maxAge = 0, timescale = 0, }: { priority?: number; ordered?: boolean; - latencyMax?: number; + maxAge?: number; timescale?: number; }) { this.priority = priority; this.ordered = ordered; - this.latencyMax = latencyMax; + this.maxAge = maxAge; this.timescale = timescale; } async #encode(w: Writer) { await w.u8(this.priority); await w.bool(this.ordered); - await w.u53(this.latencyMax); + await w.u53(this.maxAge); await w.u53(this.timescale); } static async #decode(r: Reader): Promise { const priority = await r.u8(); const ordered = await r.bool(); - const latencyMax = await r.u53(); + const maxAge = await r.u53(); const timescale = await r.u53(); // Mandatory on Lite05: a zero scale is invalid (mirrors Rust's Timescale::new rejection), // and would otherwise throw later when wrapped in Timescale(). if (timescale === 0) throw new Error("track timescale must be non-zero"); - return new TrackInfo({ priority, ordered, latencyMax, timescale }); + return new TrackInfo({ priority, ordered, maxAge, timescale }); } async encode(w: Writer, version: Version): Promise { diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index f80d5976ef0..630a1678cd9 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -130,26 +130,26 @@ test("subscriber options and updates are forwarded to the producer's aggregate", expect(producer.subscription.peek()).toEqual({ priority: 0, ordered: false, - latencyMax: 0, + maxAge: 0, startGroup: 0, endGroup: undefined, }); // The wire layer watches the producer's signal to emit SUBSCRIBE_UPDATE. const next = producer.subscription.changed(); - track.update({ priority: 7, ordered: true, latencyMax: 250, startGroup: 2, endGroup: 9 }); - expect(await next).toEqual({ priority: 7, ordered: true, latencyMax: 250, startGroup: 2, endGroup: 9 }); + track.update({ priority: 7, ordered: true, maxAge: 250, startGroup: 2, endGroup: 9 }); + expect(await next).toEqual({ priority: 7, ordered: true, maxAge: 250, startGroup: 2, endGroup: 9 }); }); test("multiple subscriber options aggregate like Rust", async () => { const producer = new TrackProducer("test"); - const bounded = producer.subscribe({ priority: 2, ordered: true, latencyMax: 100, startGroup: 10, endGroup: 20 }); - const live = producer.subscribe({ priority: 7, ordered: false, latencyMax: 250, startGroup: 5 }); + const bounded = producer.subscribe({ priority: 2, ordered: true, maxAge: 100, startGroup: 10, endGroup: 20 }); + const live = producer.subscribe({ priority: 7, ordered: false, maxAge: 250, startGroup: 5 }); expect(producer.subscription.peek()).toEqual({ priority: 7, ordered: false, - latencyMax: 250, + maxAge: 250, startGroup: 5, endGroup: undefined, }); @@ -159,7 +159,7 @@ test("multiple subscriber options aggregate like Rust", async () => { expect(await narrowed).toEqual({ priority: 2, ordered: true, - latencyMax: 100, + maxAge: 100, startGroup: 10, endGroup: 20, }); diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 7632a360142..d2defbb4ecf 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -11,8 +11,8 @@ import { Timescale, type Timestamp } from "./time.ts"; export type { Datagram } from "./datagram.ts"; -/** Default {@link Info.latencyMax} window (milliseconds) when the publisher does not set one. */ -export const DEFAULT_LATENCY_MAX_MS = 5000; +/** Default {@link Info.maxAge} window (milliseconds) when the publisher does not set one. */ +export const DEFAULT_MAX_AGE_MS = 5000; /** * How long (milliseconds) a datagram stays in the per-subscriber buffer before it is dropped. @@ -48,11 +48,11 @@ export interface Info { */ timescale: Timescale; /** - * Publisher Max Latency: the maximum age (milliseconds) of a non-latest group before + * Publisher Max Age: the maximum age (milliseconds) of a non-latest group before * the publisher evicts it. Reported in TRACK_INFO (Lite05+) so relays re-serve with the * same bound. The publisher-side half of the budget a subscriber sets for itself. */ - latencyMax: number; + maxAge: number; /** Tie-break priority between subscriptions of equal subscriber priority. */ priority: number; /** @@ -66,7 +66,7 @@ export interface Info { export function infoDefaults(info: Partial = {}): Info { return { timescale: info.timescale ?? Timescale.MILLI, - latencyMax: info.latencyMax ?? DEFAULT_LATENCY_MAX_MS, + maxAge: info.maxAge ?? DEFAULT_MAX_AGE_MS, priority: info.priority ?? 0, ordered: info.ordered ?? false, }; @@ -82,7 +82,7 @@ export interface Subscription { /** Whether groups are prioritized in sequence order. Defaults to `false` (newest-first). */ ordered?: boolean; /** Maximum age (milliseconds) of a non-latest group before it is skipped. Defaults to `0`. */ - latencyMax?: number; + maxAge?: number; /** First group the publisher should deliver, or omit to start at the latest group. */ startGroup?: number; /** Last group the publisher should deliver (inclusive), or omit for no end. */ @@ -95,7 +95,7 @@ function subscriptionDefaults(subscription: Subscription = {}): Subscription { return { priority: subscription.priority ?? 0, ordered: subscription.ordered ?? false, - latencyMax: subscription.latencyMax ?? 0, + maxAge: subscription.maxAge ?? 0, startGroup: subscription.startGroup, endGroup: subscription.endGroup, }; @@ -114,7 +114,7 @@ function combineSubscriptions(states: Iterable): Subscription | unde combined.priority = Math.max(combined.priority ?? 0, subscription.priority ?? 0); combined.ordered = (combined.ordered ?? false) && (subscription.ordered ?? false); - combined.latencyMax = Math.max(combined.latencyMax ?? 0, subscription.latencyMax ?? 0); + combined.maxAge = Math.max(combined.maxAge ?? 0, subscription.maxAge ?? 0); if (subscription.startGroup !== undefined) { combined.startGroup = @@ -295,7 +295,7 @@ let makeSubscriber: (name: string, state: TrackState) => Subscriber; * subscription the publisher serves from it) gets an independent * {@link Subscriber} that receives a full copy of the groups, each with its own * read cursor. Groups are mirrored into every live subscriber and retained for the - * track's `latencyMax` window so a late subscriber replays the recent groups. + * track's `maxAge` window so a late subscriber replays the recent groups. * * Obtained from {@link Request.accept} (the wire asks the application for a track to * serve) or constructed directly for an in-process track. @@ -470,8 +470,8 @@ export class Producer { // Evict cached groups that are closed and older than the cache window. #prune(): void { - const latencyMaxMs = this.#state.info.peek()?.latencyMax ?? DEFAULT_LATENCY_MAX_MS; - const cutoff = Date.now() - latencyMaxMs; + const maxAgeMs = this.#state.info.peek()?.maxAge ?? DEFAULT_MAX_AGE_MS; + const cutoff = Date.now() - maxAgeMs; const retained: CachedGroup[] = []; for (const entry of this.#cache) { diff --git a/js/publish/src/broadcast.ts b/js/publish/src/broadcast.ts index a8807cac920..74b46a403be 100644 --- a/js/publish/src/broadcast.ts +++ b/js/publish/src/broadcast.ts @@ -34,7 +34,7 @@ export type BroadcastInput = { * A retention budget, not a delivery one, so lowering it does not reduce latency: it only * shortens how far back a fetch can reach. */ - latencyMax: Getter; + maxAge: Getter; }; /** @@ -83,7 +83,7 @@ export class Broadcast { name: getter(props?.name ?? Moq.Path.empty()), display: getter(props?.display), flip: getter(props?.flip ?? false), - latencyMax: getter(props?.latencyMax), + maxAge: getter(props?.maxAge), }; this.#signals.run(this.#runCatalog.bind(this)); @@ -259,7 +259,7 @@ export class Broadcast { // Media, so declare the retention a FETCH-based consumer needs (the catalog above // keeps the bare defaults: it is read at the live edge, which is always retained). // Matches what a Rust publisher declares via `hang::container::track_info`. - const track = request.accept(Container.trackInfo({ latencyMax: this.in.latencyMax.peek() })); + const track = request.accept(Container.trackInfo({ maxAge: this.in.maxAge.peek() })); // A second subscription for the same name supersedes the first: close the old producer. signal.peek()?.close(); diff --git a/rs/hang/examples/subscribe.rs b/rs/hang/examples/subscribe.rs index 194efa71626..8a2b6b82b58 100644 --- a/rs/hang/examples/subscribe.rs +++ b/rs/hang/examples/subscribe.rs @@ -74,13 +74,13 @@ async fn run_subscribe(consumer: moq_net::origin::Consumer) -> anyhow::Result<() ); // Subscribe to the video track. - let latency = moq_mux::Latency::max(Duration::from_millis(500)); + let latency = Duration::from_millis(500); let track_consumer = broadcast .track(name)? .subscribe( moq_net::track::Subscription::default() .with_priority(1) - .with_latency(latency), + .with_max_age(latency), ) .await?; let mut ordered = moq_mux::container::Consumer::new(track_consumer, moq_mux::catalog::hang::Container::Legacy); diff --git a/rs/hang/src/container/frame.rs b/rs/hang/src/container/frame.rs index d8049a61aa4..f91d207a88d 100644 --- a/rs/hang/src/container/frame.rs +++ b/rs/hang/src/container/frame.rs @@ -24,7 +24,7 @@ pub const TIMESCALE: Timescale = Timescale::MICRO; /// Declared per track rather than by raising that default, so the tracks that do NOT index history /// keep the cheap default: the catalog is snapshot mode and the timeline is a single never-rolled /// group, and in both the useful value is the live edge, which is retained unconditionally. -const LATENCY_MAX: std::time::Duration = std::time::Duration::from_secs(30); +const MAX_AGE: std::time::Duration = std::time::Duration::from_secs(30); /// Track properties for creating a track that carries [`Frame`]s, via /// [`create_track`](moq_net::broadcast::Producer::create_track) or @@ -40,12 +40,12 @@ const LATENCY_MAX: std::time::Duration = std::time::Duration::from_secs(30); /// 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::latency`](moq_net::track::Subscription::latency) defaults to -/// [`Latency::REAL_TIME`](moq_net::Latency::REAL_TIME) (skip the moment a newer group arrives). +/// [`Subscription::max_age`](moq_net::track::Subscription::max_age) defaults to +/// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) (skip the moment a newer group arrives). pub fn track_info() -> moq_net::track::Info { moq_net::track::Info::default() .with_timescale(TIMESCALE) - .with_latency_max(LATENCY_MAX) + .with_max_age(MAX_AGE) } /// A media frame with a timestamp and codec-specific payload. @@ -174,14 +174,14 @@ mod test { fn media_tracks_declare_their_retention() { // A media track is read as history (a segmented egress FETCHes segments a playlist // advertised), so it declares a retention rather than inheriting the live-edge default. - assert_eq!(track_info().latency_max, LATENCY_MAX); - assert!(LATENCY_MAX > moq_net::track::DEFAULT_LATENCY_MAX); + assert_eq!(track_info().max_age, MAX_AGE); + assert!(MAX_AGE > moq_net::track::DEFAULT_MAX_AGE); // Retimescaling for a container that carries the source's own scale keeps it, since that // is the shape that would otherwise reach for `Info::default()` and lose the retention. let at = track_info().with_timescale(Timescale::MILLI); assert_eq!(at.timescale, Timescale::MILLI); - assert_eq!(at.latency_max, LATENCY_MAX); + assert_eq!(at.max_age, MAX_AGE); } #[test] @@ -190,8 +190,8 @@ mod test { // the useful value is the live edge, which is retained unconditionally, so neither pays // for history it never serves. assert_eq!( - crate::Catalog::default_track_info().latency_max, - moq_net::track::DEFAULT_LATENCY_MAX + crate::Catalog::default_track_info().max_age, + moq_net::track::DEFAULT_MAX_AGE ); } } diff --git a/rs/libmoq/src/api.rs b/rs/libmoq/src/api.rs index d0542bc9c61..f87429acff6 100644 --- a/rs/libmoq/src/api.rs +++ b/rs/libmoq/src/api.rs @@ -454,7 +454,7 @@ impl TryFrom<&moq_track_info> for moq_net::track::Info { .with_priority(info.priority) .with_ordered(info.ordered); if info.latency_max_valid { - out = out.with_latency_max(std::time::Duration::from_millis(info.latency_max_ms)); + out = out.with_max_age(std::time::Duration::from_millis(info.latency_max_ms)); } if info.timescale_valid { out = out.with_timescale(moq_net::Timescale::new(info.timescale)?); @@ -497,9 +497,7 @@ impl From<&moq_subscription> for moq_net::track::Subscription { let mut out = moq_net::track::Subscription::default() .with_priority(subscription.priority) .with_ordered(subscription.ordered) - .with_latency(moq_net::Latency::max(std::time::Duration::from_millis( - subscription.latency_max_ms, - ))); + .with_max_age(std::time::Duration::from_millis(subscription.latency_max_ms)); if subscription.group_start_valid { out = out.with_start(moq_net::track::Position::group(subscription.group_start)); } @@ -2290,7 +2288,7 @@ pub unsafe extern "C" fn moq_consume_video( ffi::enter(move || { let catalog = ffi::parse_id(catalog)?; let index = index as usize; - let latency = moq_mux::Latency::max(std::time::Duration::from_millis(latency_max_ms)); + let latency = std::time::Duration::from_millis(latency_max_ms); let on_frame = unsafe { ffi::OnStatus::new(user_data, on_frame) }; State::lock().consume.video(catalog, index, latency, on_frame) }) @@ -2334,7 +2332,7 @@ pub unsafe extern "C" fn moq_consume_audio( ffi::enter(move || { let catalog = ffi::parse_id(catalog)?; let index = index as usize; - let latency = moq_mux::Latency::max(std::time::Duration::from_millis(latency_max_ms)); + let latency = std::time::Duration::from_millis(latency_max_ms); let on_frame = unsafe { ffi::OnStatus::new(user_data, on_frame) }; State::lock().consume.audio(catalog, index, latency, on_frame) }) diff --git a/rs/libmoq/src/audio.rs b/rs/libmoq/src/audio.rs index fa17da0e145..59b2d7736cc 100644 --- a/rs/libmoq/src/audio.rs +++ b/rs/libmoq/src/audio.rs @@ -400,7 +400,7 @@ pub unsafe extern "C" fn moq_decode_audio( config.format = audio_format_from_u32(raw.format)?; config.sample_rate = zeroable(raw.sample_rate); config.channels = zeroable(raw.channels); - config.latency = moq_mux::Latency::max(Duration::from_millis(raw.latency_max_ms)); + config.max_age = Duration::from_millis(raw.latency_max_ms); let on_frame = unsafe { OnStatus::new(user_data, on_frame) }; diff --git a/rs/libmoq/src/consume.rs b/rs/libmoq/src/consume.rs index d6beaefe6a5..6b0e0aa1718 100644 --- a/rs/libmoq/src/consume.rs +++ b/rs/libmoq/src/consume.rs @@ -395,7 +395,7 @@ impl Consume { &mut self, catalog: Id, index: usize, - latency: moq_mux::Latency, + max_age: std::time::Duration, on_frame: OnStatus, ) -> Result { let consume = self.catalog.get(catalog).ok_or(Error::CatalogNotFound)?; @@ -433,7 +433,7 @@ impl Consume { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.video) - .with_latency(latency), + .with_max_age(max_age), ) .await?; let track = moq_mux::container::Consumer::new(track, container); @@ -456,7 +456,7 @@ impl Consume { &mut self, catalog: Id, index: usize, - latency: moq_mux::Latency, + max_age: std::time::Duration, on_frame: OnStatus, ) -> Result { let consume = self.catalog.get(catalog).ok_or(Error::CatalogNotFound)?; @@ -489,7 +489,7 @@ impl Consume { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.audio) - .with_latency(latency), + .with_max_age(max_age), ) .await?; let track = moq_mux::container::Consumer::new(track, container); diff --git a/rs/libmoq/src/video.rs b/rs/libmoq/src/video.rs index 6d894a51a7d..ce21ac94a49 100644 --- a/rs/libmoq/src/video.rs +++ b/rs/libmoq/src/video.rs @@ -627,7 +627,7 @@ pub unsafe extern "C" fn moq_decode_video( let raw = unsafe { output.as_ref() }.ok_or(Error::InvalidPointer)?; let mut config = moq_video::decode::Config::new(); - config.latency = moq_mux::Latency::max(Duration::from_millis(raw.latency_max_ms)); + config.max_age = Duration::from_millis(raw.latency_max_ms); let on_frame = unsafe { OnStatus::new(user_data, on_frame) }; let mut state = State::lock(); diff --git a/rs/moq-audio/src/decode/consumer.rs b/rs/moq-audio/src/decode/consumer.rs index e67af9a6cbd..168a29779b3 100644 --- a/rs/moq-audio/src/decode/consumer.rs +++ b/rs/moq-audio/src/decode/consumer.rs @@ -53,7 +53,7 @@ impl Consumer { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.audio) - .with_latency(config.latency), + .with_max_age(config.max_age), ) .await?; // The catalog says how the track is framed, and it is not always the legacy @@ -181,20 +181,20 @@ mod tests { catalog.container = hang::catalog::Container::Loc; let mut producer = moq_mux::container::Producer::new(track, moq_mux::catalog::hang::Container::Loc); - let latency = moq_mux::Latency::max(std::time::Duration::from_millis(250)); + let max_age = std::time::Duration::from_millis(250); let mut consumer = Consumer::new( &subscriber, &catalog, "audio", Config { format: Format::F32, - latency, + max_age, ..Config::new() }, ) .await .unwrap(); - assert_eq!(observed.subscription().unwrap().latency, latency); + assert_eq!(observed.subscription().unwrap().max_age, max_age); 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/decode/decoder.rs b/rs/moq-audio/src/decode/decoder.rs index c2474235aef..5c3609d4f68 100644 --- a/rs/moq-audio/src/decode/decoder.rs +++ b/rs/moq-audio/src/decode/decoder.rs @@ -35,11 +35,11 @@ pub struct Config { /// /// Applied to the initial transport subscription and inherited by /// [`moq_mux::container::Consumer`]. Defaults to - /// [`Latency::REAL_TIME`](moq_mux::Latency::REAL_TIME), which skips aggressively. - /// Set [`Latency::max`](moq_mux::Latency::max) to the playout buffer you can + /// [`std::time::Duration::ZERO`](std::time::Duration::ZERO), which skips aggressively. + /// Set [`max_age`](Self::max_age) to the playout buffer you can /// tolerate (typically tens to a few hundred ms) for the best /// congestion-vs-quality trade-off. - pub latency: moq_mux::Latency, + pub max_age: std::time::Duration, } impl Config { diff --git a/rs/moq-audio/tests/roundtrip.rs b/rs/moq-audio/tests/roundtrip.rs index 312ac0ccbb1..e023df7f903 100644 --- a/rs/moq-audio/tests/roundtrip.rs +++ b/rs/moq-audio/tests/roundtrip.rs @@ -68,7 +68,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. - config.latency = moq_mux::Latency::max(Duration::from_secs(30)); + config.max_age = Duration::from_secs(30); let mut consumer = decode::Consumer::new(&broadcast_consumer, cfg, "audio", config) .await .unwrap(); @@ -145,7 +145,7 @@ async fn opus_round_trip_44100_s16_resampled() { config.format = Format::S16; config.sample_rate = Some(44_100); config.channels = Some(1); - config.latency = moq_mux::Latency::max(Duration::from_millis(500)); + config.max_age = 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 70b7e1767e6..47b2480faa8 100644 --- a/rs/moq-bench/src/connection.rs +++ b/rs/moq-bench/src/connection.rs @@ -498,7 +498,7 @@ mod tests { } fn replay() -> track::Subscription { - track::Subscription::default().with_latency(moq_net::Latency::max(Duration::from_secs(30))) + track::Subscription::default().with_max_age(Duration::from_secs(30)) } /// A produced group must start with the JSON keyframe describing the rolled diff --git a/rs/moq-cli/src/args.rs b/rs/moq-cli/src/args.rs index d7502eae528..de495a3679c 100644 --- a/rs/moq-cli/src/args.rs +++ b/rs/moq-cli/src/args.rs @@ -462,8 +462,8 @@ pub struct Import { /// advertise segments that are still fetchable; lower it when nothing reads history and the /// memory matters. Media tracks only -- the catalog and timeline are read at the live edge, /// which is retained unconditionally. - #[arg(long, value_parser = humantime::parse_duration)] - pub latency_max: Option, + #[arg(long = "latency-max", value_parser = humantime::parse_duration)] + pub max_age: Option, /// The single source feeding the Origin. #[command(subcommand)] @@ -576,14 +576,14 @@ impl ExportSink { /// The stdout container format plus its latency and fragment cap, when this /// sink writes to stdout (the container formats). The fragment cap is /// fmp4/mkv-only. - pub fn stdout(&self) -> Option<(SubscribeFormat, moq_mux::Latency, Option)> { + pub fn stdout(&self) -> Option<(SubscribeFormat, std::time::Duration, Option)> { Some(match self { - Self::Fmp4(args) => (SubscribeFormat::Fmp4, args.container.latency(), args.fragment_duration), - Self::Mkv(args) => (SubscribeFormat::Mkv, args.container.latency(), args.fragment_duration), - Self::Ts(args) => (SubscribeFormat::Ts, args.latency(), None), - Self::Flv(args) => (SubscribeFormat::Flv, args.latency(), None), - Self::H264(args) => (SubscribeFormat::H264, args.latency(), None), - Self::H265(args) => (SubscribeFormat::H265, args.latency(), None), + Self::Fmp4(args) => (SubscribeFormat::Fmp4, args.container.max_age, args.fragment_duration), + Self::Mkv(args) => (SubscribeFormat::Mkv, args.container.max_age, args.fragment_duration), + Self::Ts(args) => (SubscribeFormat::Ts, args.max_age, None), + Self::Flv(args) => (SubscribeFormat::Flv, args.max_age, None), + Self::H264(args) => (SubscribeFormat::H264, args.max_age, None), + Self::H265(args) => (SubscribeFormat::H265, args.max_age, None), _ => return None, }) } @@ -594,14 +594,7 @@ impl ExportSink { pub struct Container { /// Maximum latency before skipping a stalled group (e.g. `500ms`, `1s`). #[arg(long = "latency-max", default_value = "500ms", value_parser = humantime::parse_duration)] - pub latency_max: Duration, -} - -impl Container { - /// The configured latency tolerance. - pub fn latency(&self) -> moq_mux::Latency { - moq_mux::Latency::max(self.latency_max) - } + pub max_age: Duration, } /// The fmp4 / mkv stdout containers: [`Container`] plus a fragment cap. @@ -1036,7 +1029,7 @@ mod tests { } #[test] - fn latency_max_is_unset_unless_asked_for() { + fn max_age_is_unset_unless_asked_for() { // Unset rather than defaulted to hang's constant, so the publisher's own default is // what every source falls back to. A `default_value` here would put the number in the // CLI as well, and the two would drift. @@ -1044,14 +1037,14 @@ mod tests { let Command::Import(import) = &cli.stages[0] else { panic!("expected import") }; - assert_eq!(import.latency_max, None); + assert_eq!(import.max_age, None); // It sits on the parent `import`, so it parses ahead of any source, gateway or not. let cli = Invocation::try_parse_from(["moq", "import", "--latency-max", "5s", "ts"]).unwrap(); let Command::Import(import) = &cli.stages[0] else { panic!("expected import") }; - assert_eq!(import.latency_max, Some(std::time::Duration::from_secs(5))); + assert_eq!(import.max_age, Some(Duration::from_secs(5))); let cli = Invocation::try_parse_from([ "moq", @@ -1066,7 +1059,7 @@ mod tests { let Command::Import(import) = &cli.stages[0] else { panic!("expected import") }; - assert_eq!(import.latency_max, Some(std::time::Duration::from_secs(5))); + assert_eq!(import.max_age, Some(Duration::from_secs(5))); } #[test] @@ -1250,7 +1243,7 @@ mod tests { let Command::Play(play) = &cli.stages[0] else { panic!("expected play") }; - assert_eq!(play.latency_max, Duration::from_millis(500)); + assert_eq!(play.max_age, Duration::from_millis(500)); assert_eq!(play.select.video_name.as_deref(), Some("hd")); assert!(cli.moq.validate().is_ok()); assert!(play.validate().is_ok()); diff --git a/rs/moq-cli/src/hls.rs b/rs/moq-cli/src/hls.rs index 4bb8c06deeb..29b6918a01d 100644 --- a/rs/moq-cli/src/hls.rs +++ b/rs/moq-cli/src/hls.rs @@ -44,7 +44,7 @@ pub async fn import( origin: &moq_net::origin::Producer, name: String, playlist: String, - latency_max: Option, + max_age: Option, ) -> anyhow::Result<()> { let mut producer = origin .create_broadcast(&name, moq_net::broadcast::Route::new().with_announce(true)) @@ -52,7 +52,7 @@ pub async fn import( // Create catalog tracks before the broadcast becomes visible so a subscriber // can consume the catalog as soon as it observes the announcement. - let config = moq_mux::catalog::Config::default().with_latency_max(latency_max); + let config = moq_mux::catalog::Config::default().with_max_age(max_age); let catalog = moq_mux::catalog::Producer::with_config(&mut producer, config)?; let mut importer = moq_hls::import::Import::new(producer, catalog, moq_hls::import::Config::new(playlist))?; diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index d89e54db7e2..f8e93fc0760 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -445,13 +445,13 @@ fn spawn_import( reject_listener_cors(&rtc.cors, "import rtc")?; } - let latency_max = import.latency_max; + let max_age = import.max_age; // The MoQ side every gateway publishes into, minted per source since each takes it // by value onto its own task. let target = |name: String| crate::moq::ImportTarget { origin: origin.clone(), name, - latency_max, + max_age, }; let mut local = None; @@ -461,14 +461,14 @@ fn spawn_import( let broadcast = origin .create_broadcast(&name, moq_net::broadcast::Route::new().with_announce(true)) .context("failed to create broadcast")?; - local = Some(Publish::new(broadcast, &format, import.latency_max)?); + local = Some(Publish::new(broadcast, &format, import.max_age)?); } else { match import.source { ImportSource::Hls(hls) => { warn_if_missing_format(&name); let origin = origin.clone(); - let latency_max = import.latency_max; - tasks.spawn(async move { hls::import(&origin, name, hls.playlist, latency_max).await }); + let max_age = import.max_age; + tasks.spawn(async move { hls::import(&origin, name, hls.playlist, max_age).await }); } ImportSource::Rtmp(rtmp) => { if let Some(addr) = rtmp.listen { @@ -508,7 +508,7 @@ fn spawn_import( let broadcast = origin .create_broadcast(&name, moq_net::broadcast::Route::new().with_announce(true)) .context("failed to create broadcast")?; - local = Some(Publish::capture(broadcast, &capture, bandwidth, import.latency_max)?); + local = Some(Publish::capture(broadcast, &capture, bandwidth, import.max_age)?); } _ => unreachable!("container formats are handled by stdin_format above"), } @@ -530,10 +530,10 @@ fn spawn_export( reject_listener_cors(&rtc.cors, "export rtc")?; } - if let Some((format, latency, fragment_duration)) = export.sink.stdout() { + if let Some((format, max_age, fragment_duration)) = export.sink.stdout() { let args = SubscribeArgs { format, - latency, + max_age, fragment_duration, catalog: export.catalog_format, select: export.select, @@ -547,12 +547,12 @@ fn spawn_export( tasks.spawn(hls::export(origin.consume(), args, name)); } ExportSink::Rtmp(rtmp) => { - let latency = rtmp.latency(); + let max_age = rtmp.max_age; if let Some(addr) = rtmp.endpoint.listen { let name = require_broadcast(name, "export rtmp --listen")?; - tasks.spawn(rtmp::listen_export(origin.consume(), addr, name, latency)); + tasks.spawn(rtmp::listen_export(origin.consume(), addr, name, max_age)); } else if let Some(url) = rtmp.endpoint.connect { - tasks.spawn(rtmp::connect_export(origin.consume(), url, name, latency)); + tasks.spawn(rtmp::connect_export(origin.consume(), url, name, max_age)); } } ExportSink::Srt(srt) => { diff --git a/rs/moq-cli/src/moq.rs b/rs/moq-cli/src/moq.rs index 26344e30fbb..ca6dad06110 100644 --- a/rs/moq-cli/src/moq.rs +++ b/rs/moq-cli/src/moq.rs @@ -21,7 +21,7 @@ pub struct ImportTarget { /// How long relays keep a non-latest group of the published media tracks fetchable /// (`--latency-max`), or `None` for the publisher's own default. - pub latency_max: Option, + pub max_age: Option, } /// Notify systemd (if any) that the endpoint is up. diff --git a/rs/moq-cli/src/play.rs b/rs/moq-cli/src/play.rs index 0bef9e21c28..ef7fc71b8c6 100644 --- a/rs/moq-cli/src/play.rs +++ b/rs/moq-cli/src/play.rs @@ -52,8 +52,8 @@ pub struct Args { pub catalog_format: Option, /// Maximum media buffering before skipping a stalled group. - #[arg(long, default_value = "500ms", value_parser = humantime::parse_duration)] - pub latency_max: Duration, + #[arg(long = "latency-max", default_value = "500ms", value_parser = humantime::parse_duration)] + pub max_age: Duration, /// Rendition selection by track name or codec. #[command(flatten)] @@ -276,7 +276,7 @@ impl Media { } }; let mut decode = moq_video::decode::Config::new(); - decode.latency = moq_mux::Latency::max(self.args.latency_max); + decode.max_age = self.args.max_age; match moq_video::decode::Consumer::new(&rendition, &config, &name, decode).await { Ok(consumer) => { tracing::info!(track = name, decoder = consumer.name(), "playing video rendition"); @@ -308,7 +308,7 @@ impl Media { } }; let mut decode = moq_audio::decode::Config::new(); - decode.latency = moq_mux::Latency::max(self.args.latency_max); + decode.max_age = self.args.max_age; // The sink and the frame-duration math below both assume f32, // so ask for it rather than inheriting the decoder default. decode.format = moq_audio::Format::F32; diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index 856da08b088..52bec3f0d81 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -220,13 +220,13 @@ impl Publish { pub fn new( mut broadcast: moq_net::broadcast::Producer, format: &PublishFormat, - latency_max: Option, + max_age: Option, ) -> anyhow::Result { // TS carries undecoded elementary streams (SCTE-35, teletext, DVB AC-3, ...) // verbatim, so it uses the `mpegts` catalog extension rather than the media-only // `()`. The catalog producer owns the broadcast's catalog tracks, so each broadcast // gets exactly one; TS builds its `Ext` catalog here instead of the shared `()` below. - let config = moq_mux::catalog::Config::default().with_latency_max(latency_max); + let config = moq_mux::catalog::Config::default().with_max_age(max_age); if let PublishFormat::Ts = format { let config = config.with_catalog(moq_mux::catalog::hang::Catalog::::default()); @@ -274,9 +274,9 @@ impl Publish { mut broadcast: moq_net::broadcast::Producer, args: &CaptureArgs, bandwidth: Option, - latency_max: Option, + max_age: Option, ) -> anyhow::Result { - let config = moq_mux::catalog::Config::default().with_latency_max(latency_max); + let config = moq_mux::catalog::Config::default().with_max_age(max_age); let catalog = moq_mux::catalog::Producer::with_config(&mut broadcast, config)?; let video = (!args.no_video).then(|| (args.video_config(), args.video_encode(bandwidth))); @@ -560,7 +560,7 @@ mod tests { Export::with_ts(moq_mux::Source::new(origin.consume(), "cli"), CatalogFormat::Hang) .await .unwrap() - .with_latency(moq_mux::Latency::max(RECORDING_LATENCY)), + .with_max_age(RECORDING_MAX_AGE), ) .await } @@ -568,9 +568,9 @@ mod tests { /// The media track's full retention window, so an exporter started after publishing /// can still read every retained group. These tests publish a whole feed before /// exporting it, which the default - /// [`Latency::REAL_TIME`](moq_mux::Latency::REAL_TIME) collapses to the live edge: + /// [`Duration::ZERO`] collapses to the live edge: /// completeness has to be asked for, exactly as a real recorder does. - const RECORDING_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); + const RECORDING_MAX_AGE: std::time::Duration = Duration::from_secs(30); /// Full CLI round-trip: a TS feed with undecoded streams goes through `Publish` /// (which selects the `mpegts` catalog) and the subscribe-side `Export::with_ts`, @@ -604,7 +604,7 @@ mod tests { Export::with_ts(moq_mux::Source::new(origin.consume(), "cli"), CatalogFormat::Hang) .await .unwrap() - .with_latency(moq_mux::Latency::max(RECORDING_LATENCY)), + .with_max_age(RECORDING_MAX_AGE), ) .await; diff --git a/rs/moq-cli/src/rtc.rs b/rs/moq-cli/src/rtc.rs index bd22a0da9b8..7e2c858a370 100644 --- a/rs/moq-cli/src/rtc.rs +++ b/rs/moq-cli/src/rtc.rs @@ -58,7 +58,7 @@ pub struct Listen { pub async fn listen_import(target: ImportTarget, listen: Listen) -> anyhow::Result<()> { let publisher = scope_producer(&target.origin, &target.name)?; let mut config = server_config(&listen); - config.latency_max = target.latency_max; + config.max_age = target.max_age; let server = moq_rtc::Server::new(config, publisher, target.origin.consume()); serve(server.publish_router(), "WHIP", listen).await } @@ -94,7 +94,7 @@ pub async fn connect_import(target: ImportTarget, url: Url) -> anyhow::Result<() notify_ready(); let mut config = moq_rtc::client::Config::default(); - config.latency_max = target.latency_max; + config.max_age = target.max_age; let client = moq_rtc::Client::new(config); Ok(client.subscribe(url, producer).await?) } diff --git a/rs/moq-cli/src/rtmp.rs b/rs/moq-cli/src/rtmp.rs index b927d6d1871..8d00a343464 100644 --- a/rs/moq-cli/src/rtmp.rs +++ b/rs/moq-cli/src/rtmp.rs @@ -35,26 +35,15 @@ pub struct ExportArgs { #[command(flatten)] pub endpoint: Args, - /// Maximum latency before skipping a stalled group. RTMP is unpaced, so this + /// Maximum age before skipping a stalled group. RTMP is unpaced, so this /// bounds buffering, not the wire rate. #[arg(long = "latency-max", default_value = "500ms", value_parser = humantime::parse_duration)] - pub latency_max: Duration, -} - -impl ExportArgs { - /// The configured latency tolerance. - pub fn latency(&self) -> moq_mux::Latency { - moq_mux::Latency::max(self.latency_max) - } + pub max_age: Duration, } /// Accept incoming RTMP publishes into the Origin as `target.name`; reject plays (import). pub async fn listen_import(target: ImportTarget, addr: SocketAddr) -> anyhow::Result<()> { - let ImportTarget { - origin, - name, - latency_max, - } = target; + let ImportTarget { origin, name, max_age } = target; let mut server = Server::bind(addr).await?; tracing::info!(%addr, %name, "RTMP listening (import)"); notify_ready(); @@ -65,7 +54,7 @@ pub async fn listen_import(target: ImportTarget, addr: SocketAddr) -> anyhow::Re let origin = origin.clone(); let name = name.clone(); tokio::spawn(async move { - if let Err(err) = publish.with_latency_max(latency_max).accept(&origin, &name).await { + if let Err(err) = publish.with_max_age(max_age).accept(&origin, &name).await { tracing::warn!(%name, %err, "RTMP ingest ended with error"); } }); @@ -87,7 +76,7 @@ pub async fn listen_export( origin: moq_net::origin::Consumer, addr: SocketAddr, name: String, - latency: moq_mux::Latency, + max_age: Duration, ) -> anyhow::Result<()> { let mut server = Server::bind(addr).await?; tracing::info!(%addr, %name, "RTMP listening (export)"); @@ -99,7 +88,7 @@ pub async fn listen_export( let origin = origin.clone(); let name = name.clone(); tokio::spawn(async move { - if let Err(err) = play.with_latency(latency).accept(&origin, &name).await { + if let Err(err) = play.with_max_age(max_age).accept(&origin, &name).await { tracing::warn!(%name, %err, "RTMP play ended with error"); } }); @@ -125,7 +114,7 @@ pub async fn connect_import(target: ImportTarget, url: Url) -> anyhow::Result<() tracing::info!(%url, %name, "RTMP client pulling"); notify_ready(); - let client = Client::connect(addr, &app).await?.with_latency_max(target.latency_max); + let client = Client::connect(addr, &app).await?.with_import_max_age(target.max_age); Ok(client.pull(&key, &target.origin, name).await?) } @@ -134,7 +123,7 @@ pub async fn connect_export( origin: moq_net::origin::Consumer, url: Url, name: String, - latency: moq_mux::Latency, + max_age: 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; @@ -147,7 +136,7 @@ pub async fn connect_export( tracing::info!(%url, %name, "RTMP client pushing"); notify_ready(); - let client = Client::connect(addr, &app).await?.with_latency(latency); + let client = Client::connect(addr, &app).await?.with_export_max_age(max_age); Ok(client.publish(&key, origin, &name).await?) } diff --git a/rs/moq-cli/src/srt.rs b/rs/moq-cli/src/srt.rs index e46633c1881..03b38ebb1cc 100644 --- a/rs/moq-cli/src/srt.rs +++ b/rs/moq-cli/src/srt.rs @@ -31,11 +31,7 @@ pub struct Args { /// Accept incoming SRT publishes into the Origin as `target.name`; reject requests (import). pub async fn listen_import(target: ImportTarget, addr: SocketAddr, latency: Duration) -> anyhow::Result<()> { - let ImportTarget { - origin, - name, - latency_max, - } = target; + let ImportTarget { origin, name, max_age } = target; let mut server = Server::bind(addr, latency).await?; tracing::info!(%addr, %name, "SRT listening (import)"); notify_ready(); @@ -46,7 +42,7 @@ pub async fn listen_import(target: ImportTarget, addr: SocketAddr, latency: Dura let origin = origin.clone(); let name = name.clone(); tokio::spawn(async move { - if let Err(err) = publish.with_latency_max(latency_max).accept(&origin, &name).await { + if let Err(err) = publish.with_max_age(max_age).accept(&origin, &name).await { tracing::warn!(%name, %err, "SRT ingest ended with error"); } }); @@ -106,7 +102,7 @@ pub async fn connect_import(target: ImportTarget, url: Url, latency: Duration) - let mut config = moq_srt::dial::Config::new(addr, resource); config.latency = latency; - config.latency_max = target.latency_max; + config.max_age = target.max_age; Ok(moq_srt::dial::pull(&config, &target.origin, name).await?) } diff --git a/rs/moq-cli/src/subscribe.rs b/rs/moq-cli/src/subscribe.rs index b1ea4d4f235..7943d1ceb1e 100644 --- a/rs/moq-cli/src/subscribe.rs +++ b/rs/moq-cli/src/subscribe.rs @@ -137,7 +137,7 @@ pub struct SubscribeArgs { pub format: SubscribeFormat, /// How far playback may drift from the live edge before skipping groups. - pub latency: moq_mux::Latency, + pub max_age: Duration, /// Cap the output fragment duration (default: one GOP). Applies to fmp4 / mkv. pub fragment_duration: Option, @@ -230,7 +230,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_latency(self.args.latency) + .with_max_age(self.args.max_age) .with_fragment_duration(self.args.fragment_duration); while let Some(chunk) = fmp4.next().await? { @@ -249,7 +249,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_latency(self.args.latency) + .with_max_age(self.args.max_age) .with_fragment_duration(self.args.fragment_duration); while let Some(chunk) = mkv.next().await? { @@ -264,7 +264,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_latency(self.args.latency); + let mut h264 = moq_mux::codec::h264::Export::new(self.source, stream).with_max_age(self.args.max_age); while let Some(chunk) = h264.next().await? { stdout.write_all(&chunk).await?; @@ -278,7 +278,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_latency(self.args.latency); + let mut h265 = moq_mux::codec::h265::Export::new(self.source, stream).with_max_age(self.args.max_age); while let Some(chunk) = h265.next().await? { stdout.write_all(&chunk).await?; @@ -298,7 +298,7 @@ impl Subscribe { // (SCTE-35, teletext, DVB AC-3, ...) are re-emitted verbatim on their PIDs. let mut ts = moq_mux::container::ts::Export::with_ts(self.source, self.catalog) .await? - .with_latency(self.args.latency); + .with_max_age(self.args.max_age); while let Some(frame) = ts.next().await? { stdout.write_all(&frame.payload).await?; @@ -317,7 +317,7 @@ impl Subscribe { // and AAC audio are supported; `fragment_duration` does not apply to FLV. let mut flv = moq_mux::container::flv::Export::with_catalog_format(self.source, self.catalog) .await? - .with_latency(self.args.latency); + .with_max_age(self.args.max_age); while let Some(chunk) = flv.next().await? { stdout.write_all(&chunk).await?; diff --git a/rs/moq-ffi/src/audio.rs b/rs/moq-ffi/src/audio.rs index acdf0c12c84..a5104231b73 100644 --- a/rs/moq-ffi/src/audio.rs +++ b/rs/moq-ffi/src/audio.rs @@ -278,10 +278,7 @@ impl MoqBroadcastConsumer { config.format = output.format.into(); config.sample_rate = output.sample_rate; config.channels = output.channels; - config.latency = output - .latency_max_ms - .map(|ms| moq_mux::Latency::max(Duration::from_millis(ms))) - .unwrap_or_default(); + config.max_age = output.latency_max_ms.map(Duration::from_millis).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 b9b467af9b9..a2b49ed1eb8 100644 --- a/rs/moq-ffi/src/consumer.rs +++ b/rs/moq-ffi/src/consumer.rs @@ -89,9 +89,7 @@ impl From for moq_net::track::Subscription { moq_net::track::Subscription::default() .with_priority(s.priority) .with_ordered(s.ordered) - .with_latency(moq_net::Latency::max(std::time::Duration::from_millis( - s.latency_max_ms, - ))) + .with_max_age(std::time::Duration::from_millis(s.latency_max_ms)) .with_start(s.group_start.map(moq_net::track::Position::group)) .with_end(s.group_end.and_then(moq_net::track::Position::after_group)) } diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index 62c4cc0783d..c398c543a92 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -40,7 +40,7 @@ impl TryFrom for moq_net::track::Info { .with_priority(info.priority) .with_ordered(info.ordered); if let Some(ms) = info.latency_max_ms { - out = out.with_latency_max(std::time::Duration::from_millis(ms)); + out = out.with_max_age(std::time::Duration::from_millis(ms)); } if let Some(ticks) = info.timescale { let scale = @@ -61,8 +61,8 @@ impl TryFrom<&moq_net::track::Info> for MoqTrackInfo { type Error = MoqError; fn try_from(info: &moq_net::track::Info) -> Result { - let latency_max_ms = u64::try_from(info.latency_max.as_millis()) - .map_err(|_| MoqError::Codec("track latency_max duration overflow".into()))?; + let latency_max_ms = u64::try_from(info.max_age.as_millis()) + .map_err(|_| MoqError::Codec("track max_age duration overflow".into()))?; Ok(Self { priority: info.priority, ordered: info.ordered, @@ -452,7 +452,7 @@ impl MoqBroadcastProducer { /// /// Same pattern as moq-boy's `status` and `command` tracks: raw UTF-8/JSON /// bytes written directly to moq-lite groups with no media framing. `info` sets - /// track properties (priority, latency_max, timescale); omit for defaults. + /// track properties (priority, max age, timescale); omit for defaults. pub fn publish_track(&self, name: String, info: Option) -> Result, MoqError> { let _guard = crate::ffi::enter(); let guard = self.state.lock().unwrap(); diff --git a/rs/moq-ffi/src/video.rs b/rs/moq-ffi/src/video.rs index cf97cf27c1c..d2c2f661e74 100644 --- a/rs/moq-ffi/src/video.rs +++ b/rs/moq-ffi/src/video.rs @@ -466,9 +466,9 @@ impl MoqBroadcastConsumer { let mut config = moq_video::decode::Config::default(); config.resize = output.resize.map(|size| moq_video::Size::new(size.width, size.height)); - config.latency = output + config.max_age = output .latency_max_ms - .map(|ms| moq_mux::Latency::max(std::time::Duration::from_millis(ms))) + .map(std::time::Duration::from_millis) .unwrap_or_default(); let consumer = moq_video::decode::Consumer::new(&broadcast, &cfg, name, config).await?; diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index d0e7ab6ac1d..3269b7fb5d1 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -442,8 +442,8 @@ async fn reconcile( } .fetch_add(1, Ordering::Relaxed); - let latency = moq_mux::Latency::max(Duration::from_secs(1)); - let subscription = moq_net::track::Subscription::default().with_latency(latency); + let latency = Duration::from_secs(1); + let subscription = moq_net::track::Subscription::default().with_max_age(latency); let track_subscriber = broadcast.track(&name)?.subscribe(subscription).await?; let track = moq_mux::container::Consumer::new(track_subscriber, container); diff --git a/rs/moq-mux/src/catalog/producer.rs b/rs/moq-mux/src/catalog/producer.rs index 3a7ec472243..be9e59ab1b7 100644 --- a/rs/moq-mux/src/catalog/producer.rs +++ b/rs/moq-mux/src/catalog/producer.rs @@ -93,8 +93,8 @@ pub struct Producer { /// Retention override for the media tracks minted under this catalog, or `None` to keep /// hang's default. Fixed at construction, so every clone and every /// [`Reserved`](super::Reserved) mints tracks under one policy. See - /// [`Config::with_latency_max`]. - latency_max: Option, + /// [`Config::with_max_age`]. + max_age: Option, } // Manual Clone so a producer is cheaply clonable regardless of whether `E` is. @@ -107,7 +107,7 @@ impl Clone for Producer { current: self.current.clone(), clock: self.clock, timeline: self.timeline.clone(), - latency_max: self.latency_max, + max_age: self.max_age, } } } @@ -122,14 +122,14 @@ impl Clone for Producer { #[derive(Clone)] pub struct Config { catalog: Catalog, - latency_max: Option, + max_age: Option, } impl Default for Config<()> { fn default() -> Self { Self { catalog: Catalog::default(), - latency_max: None, + max_age: None, } } } @@ -141,7 +141,7 @@ impl Config { pub fn with_catalog(self, catalog: Catalog) -> Config { Config { catalog, - latency_max: self.latency_max, + max_age: self.max_age, } } @@ -156,8 +156,8 @@ impl Config { /// /// Applies to the media tracks the catalog mints. The catalog and timeline tracks keep /// moq-net's default: both are read at the live edge, which is retained unconditionally. - pub fn with_latency_max(mut self, latency_max: impl Into>) -> Self { - self.latency_max = latency_max.into(); + pub fn with_max_age(mut self, max_age: impl Into>) -> Self { + self.max_age = max_age.into(); self } } @@ -216,19 +216,19 @@ impl Producer { })), clock: crate::Clock::new(), timeline: crate::timeline::Producer::new(broadcast, crate::timeline::Config::default()), - latency_max: config.latency_max, + max_age: config.max_age, }) } /// Track properties for a media track under this catalog: hang's media defaults, plus any - /// [`Config::with_latency_max`] override. + /// [`Config::with_max_age`] override. /// /// Chain [`with_timescale`](moq_net::track::Info::with_timescale) for a container that /// carries the source's own scale (CMAF and Matroska both do). pub fn track_info(&self) -> moq_net::track::Info { let info = hang::container::track_info(); - match self.latency_max { - Some(latency_max) => info.with_latency_max(latency_max), + match self.max_age { + Some(max_age) => info.with_max_age(max_age), None => info, } } @@ -644,36 +644,30 @@ mod test { // Unset, a catalog mints hang's media defaults, sized so a segmented egress can serve a // full playlist window rather than moq-net's live-edge default. let catalog = Producer::new(&mut broadcast).unwrap(); - assert_eq!( - catalog.track_info().latency_max, - hang::container::track_info().latency_max - ); - assert!(catalog.track_info().latency_max > moq_net::track::DEFAULT_LATENCY_MAX); + assert_eq!(catalog.track_info().max_age, hang::container::track_info().max_age); + assert!(catalog.track_info().max_age > moq_net::track::DEFAULT_MAX_AGE); // An override reaches every media track this catalog mints, and does NOT disturb the // timescale hang pins (or survive a retimescale for a source-scale container). let mut broadcast = moq_net::broadcast::Info::new().produce(); - let config = Config::default().with_latency_max(std::time::Duration::from_secs(3)); + let config = Config::default().with_max_age(std::time::Duration::from_secs(3)); let catalog = Producer::with_config(&mut broadcast, config).unwrap(); let info = catalog.track_info(); - assert_eq!(info.latency_max, std::time::Duration::from_secs(3)); + assert_eq!(info.max_age, std::time::Duration::from_secs(3)); assert_eq!(info.timescale, hang::container::TIMESCALE); let at = info.with_timescale(moq_net::Timescale::MILLI); - assert_eq!(at.latency_max, std::time::Duration::from_secs(3)); + assert_eq!(at.max_age, std::time::Duration::from_secs(3)); assert_eq!(at.timescale, moq_net::Timescale::MILLI); // Every handle mints under the same policy, whatever order it was taken in: the codec // paths hold a reservation and the container paths hold a clone. assert_eq!( - catalog.reserve().track_info().latency_max, - std::time::Duration::from_secs(3) - ); - assert_eq!( - catalog.clone().track_info().latency_max, + catalog.reserve().track_info().max_age, std::time::Duration::from_secs(3) ); + assert_eq!(catalog.clone().track_info().max_age, std::time::Duration::from_secs(3)); } #[test] diff --git a/rs/moq-mux/src/codec/h264/export.rs b/rs/moq-mux/src/codec/h264/export.rs index 9d77642cd38..1c7c6e96686 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, - latency: crate::Latency, + max_age: std::time::Duration, track: Option, } @@ -60,18 +60,18 @@ impl Export { Self { source, catalog: Some(catalog), - latency: crate::Latency::REAL_TIME, + max_age: std::time::Duration::ZERO, track: None, } } - /// Set the latency tolerance for the per-track source. + /// Set the max age for the per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) (skip aggressively). - pub fn with_latency(mut self, latency: crate::Latency) -> Self { - self.latency = latency; + /// [`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; self } @@ -155,7 +155,7 @@ impl Export { return Ok(()); } - let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.max_age)? else { unreachable!("invalid broadcast references were removed above"); }; let convert = match config.description.as_ref().filter(|d| !d.is_empty()) { @@ -296,7 +296,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_latency(crate::Latency::max(std::time::Duration::from_secs(30))); + .with_max_age(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 3b0f849bfbe..1a89c9cc1ee 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, - latency: crate::Latency, + max_age: std::time::Duration, track: Option, } @@ -52,18 +52,18 @@ impl Export { Self { source, catalog: Some(catalog), - latency: crate::Latency::REAL_TIME, + max_age: std::time::Duration::ZERO, track: None, } } - /// Set the latency tolerance for the per-track source. + /// Set the max age for the per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) (skip aggressively). - pub fn with_latency(mut self, latency: crate::Latency) -> Self { - self.latency = latency; + /// [`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; self } @@ -147,7 +147,7 @@ impl Export { return Ok(()); } - let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_video_raw(&self.source, name, config, self.max_age)? else { unreachable!("invalid broadcast references were removed above"); }; let convert = match config.description.as_ref().filter(|d| !d.is_empty()) { @@ -282,7 +282,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_latency(crate::Latency::max(std::time::Duration::from_secs(30))); + .with_max_age(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 66cb8dabdff..95665d03667 100644 --- a/rs/moq-mux/src/container/consumer.rs +++ b/rs/moq-mux/src/container/consumer.rs @@ -5,7 +5,7 @@ use moq_net::Timestamp; use super::{Container, Frame}; -/// Decode a moq-lite track into a stream of media [`Frame`]s in latency-bounded +/// Decode a moq-lite track into a stream of media [`Frame`]s in age-bounded /// presentation order. /// /// `Consumer` wraps a [`moq_net::track::Subscriber`] and a [`Container`] @@ -13,25 +13,25 @@ use super::{Container, Frame}; /// [`catalog::hang::Container`](crate::catalog::hang::Container). Yields /// decoded frames via [`read`](Self::read). /// -/// ## Ordering & latency skipping +/// ## Ordering & age skipping /// /// Groups can arrive on the wire out of order. The consumer always reads frames *within* /// a group in arrival order, but across groups it advances by sequence number, skipping /// stalled or missing groups when the difference between the oldest pending timestamp -/// and the newest available timestamp exceeds the configured latency. With the default -/// latency of zero, the consumer skips aggressively. Any group that has a newer -/// alternative is dropped. With a non-zero latency, slow groups are tolerated up to that +/// and the newest available timestamp exceeds the configured max age. With the default +/// max age 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 skipped. /// -/// A stalled group is also skipped early, regardless of the latency budget, once it has +/// A stalled group is also skipped early, regardless of the max age 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 latency budget. +/// duration report zero, which disables this check and falls back to the max age budget. /// -/// Put the initial latency on the [`moq_net::track::Subscription`] before +/// Put the initial max age on the [`moq_net::track::Subscription`] before /// subscribing. [`new`](Self::new) inherits that budget, and -/// [`set_latency`](Self::set_latency) changes it mid-stream. +/// [`set_max_age`](Self::set_max_age) changes it mid-stream. /// /// ## Timeline rewinds /// @@ -56,7 +56,7 @@ pub struct Consumer { startup: bool, // How far we may drift from the live edge before skipping a group. - latency: crate::Latency, + max_age: std::time::Duration, // Timeline-rewind tracking: the live edge, the active boundary, and the discontinuity count. rewind: Rewind, @@ -129,18 +129,18 @@ impl Reset { impl Consumer { /// Create a Consumer wrapping the given moq-lite consumer, decoding `format`. /// - /// The ordering window inherits the subscriber's current latency budget. Put + /// The ordering window inherits the subscriber's current max age budget. Put /// that budget on the [`moq_net::track::Subscription`] before awaiting the /// subscription, so the publisher preserves the same replay window. pub fn new(track: moq_net::track::Subscriber, format: F) -> Self { - let latency = track.subscription().latency; + let max_age = track.subscription().max_age; Self { track, format, current: 0, pending: VecDeque::new(), startup: true, - latency, + max_age, rewind: Rewind::default(), } } @@ -159,9 +159,9 @@ impl Consumer { /// Read the next frame from the track. /// - /// This method handles timestamp decoding, group ordering, and latency management + /// This method handles timestamp decoding, group ordering, and age management /// automatically. It will skip groups that are too far behind to maintain the - /// configured latency target. + /// configured max age. /// /// Returns `None` when the track has ended. pub async fn read(&mut self) -> Result, F::Error> { @@ -249,7 +249,7 @@ impl Consumer { } } - // Get the current group's min timestamp (the reference for latency + // Get the current group's min timestamp (the reference for age // comparison) and its furthest presentation point (timestamp + duration). let (oldest_timestamp, current_end) = if let Some(current) = self.pending.front_mut() && current.sequence <= self.current @@ -291,12 +291,12 @@ impl Consumer { let should_skip = if let Some((_, next_start)) = next_group { if let Some(oldest) = oldest_timestamp { // Current group is blocking. Skip if newer groups have pulled past - // the latency budget, or if the current group has already presented + // the max age budget, or if the current group has already presented // up to where the next group begins (duration coverage) so there's // nothing left worth waiting for. - let over_latency = max_timestamp.saturating_sub(oldest) >= self.latency.max; + let over_max_age = max_timestamp.saturating_sub(oldest) >= self.max_age; let covered = current_end.is_some_and(|end| end >= next_start); - over_latency || covered + over_max_age || covered } else { // The current group can't produce a timestamp: either it's missing // entirely -- a lower sequence the cache evicted, so `front` is already @@ -470,13 +470,13 @@ impl Consumer { Ok(()) } - /// Set the latency tolerance mid-stream. - pub fn set_latency(&mut self, latency: crate::Latency) { - self.latency = latency; + /// Set the max age mid-stream. + pub fn set_max_age(&mut self, max_age: std::time::Duration) { + self.max_age = max_age; // 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_latency(latency); + let subscription = self.track.subscription().with_max_age(max_age); let _ = self.track.update(subscription); } } @@ -484,7 +484,7 @@ impl Consumer { /// Internal reader for a group of frames. /// /// Handles two-phase frame reading (get FrameConsumer, then read all data), -/// timestamp parsing, and min/max timestamp tracking for latency decisions. +/// timestamp parsing, and min/max timestamp tracking for age decisions. struct GroupBuffer { group: moq_net::group::Consumer, @@ -648,7 +648,6 @@ impl std::ops::Deref for GroupBuffer { mod tests { use super::Container as ContainerTrait; use super::*; - use crate::Latency; use crate::catalog::hang::Container; use std::time::Duration; @@ -759,19 +758,19 @@ mod tests { Ok(frames) } - /// Wrap `track` so only the container consumer performs latency skips. The + /// Wrap `track` so only the container consumer performs age skips. The /// transport gets the media track's full retention window and hands over every /// retained group; what the container does with them is what the test measures. /// /// 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_latency_only(track: moq_net::track::Subscriber, latency: Latency) -> Consumer { + fn container_max_age_only(track: moq_net::track::Subscriber, max_age: std::time::Duration) -> Consumer { let control = track.control(); let mut consumer = Consumer::new(track, Container::Legacy); - consumer.set_latency(latency); + consumer.set_max_age(max_age); control - .update(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(30)))) + .update(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(30))) .unwrap(); consumer } @@ -781,20 +780,20 @@ mod tests { #[test] fn new_inherits_the_initial_subscription_latency() { let track = track_producer("test", hang::container::track_info()); - let latency = Latency::max(Duration::from_millis(250)); - let subscriber = track.subscribe(moq_net::track::Subscription::default().with_latency(latency)); + let max_age = Duration::from_millis(250); + let subscriber = track.subscribe(moq_net::track::Subscription::default().with_max_age(max_age)); let consumer = Consumer::new(subscriber, Container::Legacy); - assert_eq!(consumer.latency, latency); - assert_eq!(consumer.track.subscription().latency, latency); + assert_eq!(consumer.max_age, max_age); + assert_eq!(consumer.track.subscription().max_age, max_age); } #[tokio::test] async fn read_single_group() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0)]); @@ -812,8 +811,8 @@ mod tests { #[tokio::test] async fn read_multiple_frames_single_group() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0), ts(33_000), ts(66_000)]); @@ -831,11 +830,11 @@ mod tests { #[tokio::test] async fn read_multiple_groups_within_latency() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); - // 5 groups, 20ms spacing. Total span = 80ms, well within 500ms latency. + // 5 groups, 20ms spacing. Total span = 80ms, well within the 500ms max age. for i in 0..5u64 { write_group(&mut track, i, &[ts(i * 20_000)]); } @@ -845,14 +844,14 @@ mod tests { assert_eq!(frames.len(), 5); } - // ---- Latency Skipping ---- + // ---- Age Skipping ---- #[tokio::test] async fn latency_skip_delivers_recent_groups() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(100)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); // Group 0: 5 frames, NOT finished (blocks consumer) @@ -885,7 +884,7 @@ mod tests { }); let frames = read_all(&mut consumer).await.unwrap(); - // Group 0's 5 frames + some later groups (earlier ones skipped by latency) + // Group 0's 5 frames + some later groups (earlier ones skipped by age) assert!(frames.len() >= 25, "Expected >= 25 frames, got {}", frames.len()); finisher.await.expect("finisher task panicked"); } @@ -895,10 +894,10 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); let consumer_track = track.subscribe(None); - let mut consumer = container_latency_only(consumer_track, Latency::REAL_TIME); + let mut consumer = container_max_age_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 latency skipping and not rewind detection. + // g*50 ms), so the test exercises age skipping and not rewind detection. let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); Container::Legacy .write( @@ -934,7 +933,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); let consumer_track = track.subscribe(None); - let mut consumer = container_latency_only(consumer_track, Latency::max(Duration::from_millis(100))); + let mut consumer = container_max_age_only(consumer_track, Duration::from_millis(100)); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); Container::Legacy @@ -1002,8 +1001,8 @@ mod tests { async fn reset_keeps_out_of_order_new_group() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); // Old epoch, played forward until the live edge passes the rewind point. @@ -1042,8 +1041,8 @@ mod tests { async fn reset_detected_behind_forward_newest_group() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); // Old timeline, played to a live edge of 200 ms. @@ -1078,9 +1077,9 @@ mod tests { async fn backwards_timestamp_resets_buffer() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); - // Large latency so the slow-group skip never fires; isolate the rewind path. + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); + // Large max age so the slow-group skip never fires; isolate the rewind path. let mut consumer = Consumer::new(consumer_track, Container::Legacy); // Publisher runs ahead: groups 0-4 at 0, 100, 200, 300, 400 ms. @@ -1105,8 +1104,8 @@ mod tests { #[tokio::test] async fn backwards_timestamp_always_resets() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0)]); @@ -1141,8 +1140,8 @@ mod tests { #[tokio::test] async fn empty_payload_is_skipped() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1171,8 +1170,8 @@ mod tests { #[tokio::test] async fn consecutive_markers_do_not_stall() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1205,8 +1204,8 @@ mod tests { async fn groups_delivered_in_sequence_order() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1242,8 +1241,8 @@ mod tests { #[tokio::test] async fn adjacent_group_flushed_immediately() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0)]); @@ -1261,8 +1260,8 @@ mod tests { #[tokio::test] async fn bframes_within_group() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0), ts(66_000), ts(33_000)]); @@ -1281,8 +1280,8 @@ mod tests { async fn empty_track_returns_none() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); track.finish().unwrap(); @@ -1300,8 +1299,8 @@ mod tests { async fn track_closed_with_error() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0)]); @@ -1324,8 +1323,8 @@ mod tests { #[tokio::test] async fn gap_in_group_sequence_recovery() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(100)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0), ts(20_000)]); @@ -1343,8 +1342,8 @@ mod tests { #[tokio::test] async fn gap_at_start_of_sequence() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(80)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(80))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 5, &[ts(0), ts(20_000)]); @@ -1367,8 +1366,8 @@ mod tests { #[tokio::test] async fn evicted_group_with_gap_skips_to_live() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(100)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); // Group 0: a frame the consumer reads, positioning it there. @@ -1411,8 +1410,8 @@ mod tests { #[tokio::test] async fn missing_sequence_skips_on_live_track() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(100)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); // Group 0, then group 2 -- sequence 1 is missing (evicted) and never arrives. @@ -1511,8 +1510,8 @@ mod tests { #[tokio::test] async fn frame_timestamp_and_index_decoding() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0), ts(33_333), ts(66_666)]); @@ -1532,8 +1531,8 @@ mod tests { #[tokio::test] async fn frame_payload_preserved() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let payload_bytes = vec![0x01, 0x02, 0x03, 0x04, 0x05]; @@ -1571,8 +1570,8 @@ mod tests { async fn no_infinite_loop_with_buffered_frames() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1618,8 +1617,8 @@ mod tests { #[tokio::test] async fn large_timestamps() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(3700)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(3700))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let one_hour = 3_600_000_000u64; @@ -1635,8 +1634,8 @@ mod tests { #[tokio::test] async fn set_latency_changes_behavior() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0)]); @@ -1645,7 +1644,7 @@ mod tests { let frame = consumer.read().await.unwrap().unwrap(); assert_eq!(frame.timestamp, ts(0)); - consumer.set_latency(Latency::max(Duration::from_millis(100))); + consumer.set_max_age(Duration::from_millis(100)); assert!(consumer.read().await.unwrap().is_none()); } @@ -1654,10 +1653,10 @@ mod tests { async fn max_timestamp_tracks_through_bframes() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(110)))); - // latency must exceed (group1_max - group0_min) = 100ms - 0ms = 100ms - // to avoid the latency skip and test B-frame timestamp tracking. + 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 + // to avoid the age skip and test B-frame timestamp tracking. let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1707,8 +1706,8 @@ mod tests { async fn startup_selects_earliest_group() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(100)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 3, &[ts(0)]); @@ -1761,8 +1760,8 @@ mod tests { async fn startup_skips_groups_without_data() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let _group5 = track.create_group(moq_net::group::Info { sequence: 5 }).unwrap(); @@ -1785,8 +1784,8 @@ mod tests { #[tokio::test] async fn startup_single_group_mid_stream() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 100, &[ts(3_000_000)]); @@ -1800,8 +1799,8 @@ mod tests { async fn multiple_sequential_latency_skips() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(50)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(50))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1837,8 +1836,8 @@ mod tests { async fn latency_skip_boundary_exact() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(100)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(100))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1869,7 +1868,7 @@ mod tests { } /// Regression: a single stalled group with one newer group should trigger - /// a latency skip when the timestamp difference exceeds latency. + /// an age skip when the timestamp difference exceeds the max age. /// Previously, the span was computed across newer groups only (zero for one /// group), so the skip never fired. #[tokio::test] @@ -1877,7 +1876,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); let consumer_track = track.subscribe(None); - let mut consumer = container_latency_only(consumer_track, Latency::max(Duration::from_millis(100))); + let mut consumer = container_max_age_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(); @@ -1893,7 +1892,7 @@ mod tests { ) .unwrap(); - // Group 1: finished, 200ms ahead (well beyond 100ms latency) + // Group 1: finished, 200ms ahead (well beyond the 100ms max age) write_group(&mut track, 1, &[ts(200_000)]); track.finish().unwrap(); @@ -1915,7 +1914,7 @@ mod tests { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); let consumer_track = track.subscribe(None); - let mut consumer = container_latency_only(consumer_track, Latency::max(Duration::from_millis(100))); + let mut consumer = container_max_age_only(consumer_track, Duration::from_millis(100)); // Group 0: finished normally write_group(&mut track, 0, &[ts(0), ts(20_000)]); @@ -1930,8 +1929,8 @@ mod tests { #[tokio::test] async fn group_error_skips_to_next() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1948,8 +1947,8 @@ mod tests { async fn track_finishes_while_reading() { tokio::time::pause(); let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); write_group(&mut track, 0, &[ts(0)]); @@ -1978,8 +1977,8 @@ mod tests { #[tokio::test] async fn empty_group_advances() { let mut track = track_producer("test", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); let mut group0 = track.create_group(moq_net::group::Info { sequence: 0 }).unwrap(); @@ -1999,8 +1998,8 @@ mod tests { tokio::time::pause(); let mut track = track_producer("video", hang::container::track_info()); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_millis(500)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_millis(500))); let mut consumer = Consumer::new(consumer_track, Container::Legacy); // Write frames using Container::Legacy encoding @@ -2034,7 +2033,7 @@ mod tests { // ---- Duration Skipping ---- /// A stalled group whose frame covers up to the next group's start is skipped - /// immediately, even with a latency budget far larger than the gap. Without + /// immediately, even with a max age 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() { @@ -2042,9 +2041,9 @@ mod tests { // DurationWire is a test-only container that doesn't stamp moq_net frame // timestamps; leave the track untimed so model-layer validation matches. let mut track = track_producer("test", None); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); - // Latency dwarfs the gap, so only duration coverage can trigger the skip. + 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. let mut consumer = Consumer::new(consumer_track, DurationWire); // Group 0: one frame at ts=0 lasting 33ms, never finished. @@ -2084,8 +2083,8 @@ mod tests { tokio::time::pause(); // DurationWire is untimed at the moq_net frame layer. let mut track = track_producer("test", None); - let consumer_track = track - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(Duration::from_secs(10)))); + let consumer_track = + track.subscribe(moq_net::track::Subscription::default().with_max_age(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 47f483e0f78..6737ed671f3 100644 --- a/rs/moq-mux/src/container/flv/export.rs +++ b/rs/moq-mux/src/container/flv/export.rs @@ -103,7 +103,7 @@ impl Flavor { pub struct Export { source: crate::Source, catalog: Option, - latency: crate::Latency, + max_age: std::time::Duration, /// Emit every rendition as an enhanced-RTMP multitrack track, rather than only /// the first video + first audio rendition. multitrack: bool, @@ -179,7 +179,7 @@ impl Export { Ok(Self { source, catalog: Some(catalog), - latency: crate::Latency::REAL_TIME, + max_age: std::time::Duration::ZERO, multitrack: false, video: Vec::new(), audio: Vec::new(), @@ -187,13 +187,13 @@ impl Export { }) } - /// Set the latency tolerance for each per-track source. + /// Set the max age for each per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) (skip aggressively). - pub fn with_latency(mut self, latency: crate::Latency) -> Self { - self.latency = latency; + /// [`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; self } @@ -353,7 +353,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.latency)? else { + let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_age)? else { continue; }; let track_id = u8::try_from(self.video.len()).context("too many FLV video tracks")?; @@ -383,7 +383,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.latency)? else { + let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_age)? 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 732ae46af1a..a81ed79b946 100644 --- a/rs/moq-mux/src/container/flv/export_test.rs +++ b/rs/moq-mux/src/container/flv/export_test.rs @@ -15,9 +15,9 @@ use super::{Export, Import}; /// The media track's full retention window, so an exporter started after publishing /// can still read every retained group. These tests write or import a whole broadcast /// and only then export it, which the -/// exporter's default [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) collapses to 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_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_AGE: Duration = Duration::from_secs(30); /// A minimal `AVCDecoderConfigurationRecord` (profile 0x42, level 0x1f, one SPS + PPS). fn avcc() -> Vec { @@ -181,7 +181,7 @@ async fn export_emits_sequence_headers_and_frames() { let exporter = Export::new(crate::source::announced(&consumer)) .await .unwrap() - .with_latency(crate::Latency::max(RECORDING_LATENCY)); + .with_max_age(RECORDING_MAX_AGE); let exported = drain_export(exporter, importer).await; let tags = parse_tags(&exported); diff --git a/rs/moq-mux/src/container/flv/import_test.rs b/rs/moq-mux/src/container/flv/import_test.rs index 5c9ce8bd9d9..5151de3cc56 100644 --- a/rs/moq-mux/src/container/flv/import_test.rs +++ b/rs/moq-mux/src/container/flv/import_test.rs @@ -3,7 +3,7 @@ use hang::catalog::{AudioCodec, VideoCodec}; use super::Import; -use crate::Latency; +use std::time::Duration; /// A minimal `AVCDecoderConfigurationRecord`: AVC-LC baseline (profile 0x42, /// level 0x1f) with one SPS and one PPS. @@ -130,9 +130,7 @@ async fn import_emits_frames() { let track = consumer .track(&video_name) .unwrap() - .subscribe( - moq_net::track::Subscription::default().with_latency(Latency::max(std::time::Duration::from_secs(1))), - ) + .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); @@ -423,9 +421,7 @@ async fn import_enhanced_av1() { let track = consumer .track(name) .unwrap() - .subscribe( - moq_net::track::Subscription::default().with_latency(Latency::max(std::time::Duration::from_secs(1))), - ) + .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); @@ -532,9 +528,7 @@ async fn import_reports_negative_pts_and_can_resume() { let track = consumer .track(name) .unwrap() - .subscribe( - moq_net::track::Subscription::default().with_latency(Latency::max(std::time::Duration::from_secs(1))), - ) + .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); @@ -571,9 +565,7 @@ async fn import_enhanced_hvc1_applies_composition_time() { let track = consumer .track(name) .unwrap() - .subscribe( - moq_net::track::Subscription::default().with_latency(Latency::max(std::time::Duration::from_secs(1))), - ) + .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(1))) .await .unwrap(); let mut decoder = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); diff --git a/rs/moq-mux/src/container/fmp4/export.rs b/rs/moq-mux/src/container/fmp4/export.rs index 9a7eef94113..3b3296545a4 100644 --- a/rs/moq-mux/src/container/fmp4/export.rs +++ b/rs/moq-mux/src/container/fmp4/export.rs @@ -37,7 +37,7 @@ use moq_net::Timestamp; pub struct Export { source: crate::Source, catalog: Option, - latency: crate::Latency, + max_age: Duration, fragment_duration: Option, tracks: HashMap, @@ -157,7 +157,7 @@ impl Export { Self { source, catalog: Some(catalog), - latency: crate::Latency::REAL_TIME, + max_age: Duration::ZERO, fragment_duration: None, tracks: HashMap::new(), catalog_snapshot: None, @@ -165,13 +165,13 @@ impl Export { } } - /// Set the latency tolerance for each per-track source. + /// Set the max age for each per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) (skip aggressively). - pub fn with_latency(mut self, latency: crate::Latency) -> Self { - self.latency = latency; + /// [`Duration::ZERO`] (skip aggressively). + pub fn with_max_age(mut self, max_age: Duration) -> Self { + self.max_age = max_age; self } @@ -401,7 +401,7 @@ impl Export { if self.tracks.contains_key(name) { continue; } - let Some(source) = ExportSource::for_video(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_age)? else { continue; }; let timescale = catalog_timescale_video(config)?; @@ -429,7 +429,7 @@ impl Export { if self.tracks.contains_key(name) { continue; } - let Some(source) = ExportSource::for_audio(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_age)? else { continue; }; let timescale = catalog_timescale_audio(config)?; diff --git a/rs/moq-mux/src/container/fmp4/export_test.rs b/rs/moq-mux/src/container/fmp4/export_test.rs index c5085fafed2..3a2f73b042c 100644 --- a/rs/moq-mux/src/container/fmp4/export_test.rs +++ b/rs/moq-mux/src/container/fmp4/export_test.rs @@ -10,9 +10,9 @@ use crate::container::test_util::{Live, PPS, SPS, raw_frame, video_frame}; /// The media track's full retention window, so an exporter started after publishing /// can still read every retained group. These tests write or import a whole broadcast /// and only then export it, which the -/// exporter's default [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) collapses to 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_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_AGE: 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 @@ -538,7 +538,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_latency(crate::Latency::max(RECORDING_LATENCY)); + .with_max_age(RECORDING_MAX_AGE); // First emit is the init segment, which carries no segmenting metadata to assert on. chunk_now(&mut exporter) diff --git a/rs/moq-mux/src/container/fmp4/import_test.rs b/rs/moq-mux/src/container/fmp4/import_test.rs index 9d22f7eaa28..76e7c427f4b 100644 --- a/rs/moq-mux/src/container/fmp4/import_test.rs +++ b/rs/moq-mux/src/container/fmp4/import_test.rs @@ -6,13 +6,13 @@ use mp4_atom::{Decode, Encode}; /// /// The media track's full retention window, so a reader started after publishing can /// still read every retained group. These tests write every group up front, which the -/// default [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) budget collapses to the live +/// default [`std::time::Duration::ZERO`](std::time::Duration::ZERO) budget collapses to the live /// edge: completeness has to be asked for. -const RECORDING_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(30); /// A replay window with that budget, for a test asserting every group is delivered. fn replay() -> moq_net::track::Subscription { - moq_net::track::Subscription::default().with_latency(moq_net::Latency::max(RECORDING_LATENCY)) + moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE) } /// 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 9f479bdc5b5..3afffe86b97 100644 --- a/rs/moq-mux/src/container/group.rs +++ b/rs/moq-mux/src/container/group.rs @@ -6,10 +6,10 @@ use super::{Container, Frame}; /// Decode a single [`moq_net::group::Consumer`] into a finite stream of media [`Frame`]s. /// /// This is the group-scoped counterpart to [`Consumer`](super::Consumer). Where that one -/// subscribes to a track and juggles group ordering, latency skipping, and rewinds, this one +/// 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 -/// latency budget that could skip the very group being asked for. +/// max age 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 59df461e756..88621cb9ef1 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, - latency: crate::Latency, + max_age: Duration, fragment_duration: Option, tracks: HashMap, @@ -162,7 +162,7 @@ impl Export { Self { source, catalog: Some(catalog), - latency: crate::Latency::REAL_TIME, + max_age: Duration::ZERO, fragment_duration: None, tracks: HashMap::new(), catalog_snapshot: None, @@ -171,13 +171,13 @@ impl Export { } } - /// Set the latency tolerance for each per-track source. + /// Set the max age for each per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) (skip aggressively). - pub fn with_latency(mut self, latency: crate::Latency) -> Self { - self.latency = latency; + /// [`Duration::ZERO`] (skip aggressively). + pub fn with_max_age(mut self, max_age: Duration) -> Self { + self.max_age = max_age; self } @@ -341,7 +341,7 @@ impl Export { continue; } ensure_legacy(&config.container, "video", name)?; - let Some(source) = ExportSource::for_video(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_age)? else { continue; }; self.tracks.insert( @@ -362,7 +362,7 @@ impl Export { continue; } ensure_legacy(&config.container, "audio", name)?; - let Some(source) = ExportSource::for_audio(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_age)? 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 39935745d24..a876914ed31 100644 --- a/rs/moq-mux/src/container/mkv/export_test.rs +++ b/rs/moq-mux/src/container/mkv/export_test.rs @@ -18,9 +18,9 @@ use crate::container::test_util::{IDR, Live, PPS, SPS, raw_frame, video_frame}; /// The media track's full retention window, so an exporter started after publishing /// can still read every retained group. These tests import a whole file and only then /// export it, which the exporter's default -/// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) collapses to the live edge: +/// [`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_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_AGE: 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_latency(crate::Latency::max(RECORDING_LATENCY)); + .with_max_age(RECORDING_MAX_AGE); 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_latency(crate::Latency::max(RECORDING_LATENCY)); + .with_max_age(RECORDING_MAX_AGE); 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 8e880fe6c38..5403ccad255 100644 --- a/rs/moq-mux/src/container/mod.rs +++ b/rs/moq-mux/src/container/mod.rs @@ -56,7 +56,7 @@ pub struct Frame { /// that don't (Legacy, LOC) leave this `None`. 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 - /// latency budget. + /// max age 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 8e7de9a752c..52c5fbe2612 100644 --- a/rs/moq-mux/src/container/producer.rs +++ b/rs/moq-mux/src/container/producer.rs @@ -113,8 +113,8 @@ impl Producer { /// 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 - /// [`Latency`](crate::Latency), and the one knob here that genuinely *adds* delay. + /// This is the publisher-side counterpart to the consumer's max age, and the one + /// knob here that genuinely *adds* delay. pub fn with_buffer(mut self, duration: std::time::Duration) -> Self { self.buffer_duration = duration; self @@ -401,15 +401,15 @@ mod tests { /// A replay window wide enough to read a whole batch back. /// /// These tests write every group up front and only then read, which the default - /// [`Latency::REAL_TIME`](moq_net::Latency::REAL_TIME) budget collapses to the live + /// [`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_latency(moq_net::Latency::max(RECORDING_LATENCY)) + moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE) } /// The media track's full retention window, so readers started after publishing /// can still consume every retained group. - const RECORDING_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); + const RECORDING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(30); fn frame(timestamp_us: u64, keyframe: bool) -> Frame { Frame { @@ -559,12 +559,10 @@ mod tests { async fn discontinuity_publishes_an_empty_group() { // The resumed clock jumps forty minutes, so both the retention window and the // drift budget have to cover it or the pre-discontinuity group reads as ancient. - let discontinuity_latency = std::time::Duration::from_secs(41 * 60); - let info = hang::container::track_info().with_latency_max(discontinuity_latency); + let discontinuity_max_age = std::time::Duration::from_secs(41 * 60); + let info = hang::container::track_info().with_max_age(discontinuity_max_age); let track = track_producer("test", info); - let consumer = track.subscribe( - moq_net::track::Subscription::default().with_latency(moq_net::Latency::max(discontinuity_latency)), - ); + let consumer = track.subscribe(moq_net::track::Subscription::default().with_max_age(discontinuity_max_age)); let mut producer = Producer::new(track, Container::Legacy); 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 6273aded154..0d4128f52e8 100644 --- a/rs/moq-mux/src/container/source.rs +++ b/rs/moq-mux/src/container/source.rs @@ -64,7 +64,7 @@ pub(crate) struct ExportSource { state: SourceState, /// Wire format, consumed when the subscription resolves into a consumer. media: Option, - latency: crate::Latency, + max_age: std::time::Duration, transform: Option, /// Resolved codec configuration record (avcC / hvcC / AudioSpecificConfig / /// OpusHead). Some once the codec config is available — from the catalog @@ -87,9 +87,9 @@ impl ExportSource { source: &crate::Source, name: &str, config: &VideoConfig, - latency: crate::Latency, + max_age: std::time::Duration, ) -> Result, crate::Error> { - Self::video(source, name, config, latency, build_video_transform(config)) + Self::video(source, name, config, max_age, build_video_transform(config)) } /// Subscribe to a video rendition without attaching any codec-shape @@ -102,16 +102,16 @@ impl ExportSource { source: &crate::Source, name: &str, config: &VideoConfig, - latency: crate::Latency, + max_age: std::time::Duration, ) -> Result, crate::Error> { - Self::video(source, name, config, latency, None) + Self::video(source, name, config, max_age, None) } fn video( source: &crate::Source, name: &str, config: &VideoConfig, - latency: crate::Latency, + max_age: std::time::Duration, transform: Option, ) -> Result, crate::Error> { let media: HangContainer = (&config.container).try_into()?; @@ -123,7 +123,7 @@ impl ExportSource { let mut source = Self { state: SourceState::Requesting(request, name.to_string()), media: Some(media), - latency, + max_age, transform, description, video_codec: Some(config.codec.clone()), @@ -141,7 +141,7 @@ impl ExportSource { source: &crate::Source, name: &str, config: &AudioConfig, - latency: crate::Latency, + max_age: std::time::Duration, ) -> Result, crate::Error> { let media: HangContainer = (&config.container).try_into()?; let description = config.description.as_ref().filter(|b| !b.is_empty()).cloned(); @@ -152,7 +152,7 @@ impl ExportSource { Ok(Some(Self { state: SourceState::Requesting(request, name.to_string()), media: Some(media), - latency, + max_age, transform: None, description, video_codec: None, @@ -166,11 +166,11 @@ 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, latency: crate::Latency) -> Result { + pub fn for_stream(source: &crate::Source, name: &str, max_age: std::time::Duration) -> Result { Ok(Self { state: SourceState::Requesting(source.request_catalog(), name.to_string()), media: Some(HangContainer::Legacy), - latency, + max_age, transform: None, description: None, video_codec: None, @@ -228,7 +228,7 @@ impl ExportSource { Poll::Pending => return Poll::Pending, } }; - let subscription = moq_net::track::Subscription::default().with_latency(self.latency); + let subscription = moq_net::track::Subscription::default().with_max_age(self.max_age); self.state = SourceState::Subscribing(broadcast.track(&name)?.subscribe(subscription)); } @@ -396,7 +396,7 @@ mod tests { async fn escaping_reference_skips_the_rendition() { let live = Live::avc3(); let source = live.source(); - let latency = crate::Latency::REAL_TIME; + let max_age = std::time::Duration::ZERO; let escaping = |result: Result, crate::Error>, what: &str| match result { Ok(None) => {} @@ -408,13 +408,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, latency), reference); + escaping(ExportSource::for_video(&source, "video", &config, max_age), reference); escaping( - ExportSource::for_video_raw(&source, "video", &config, latency), + ExportSource::for_video_raw(&source, "video", &config, max_age), reference, ); escaping( - ExportSource::for_audio(&source, "audio", &audio(Some(reference)), latency), + ExportSource::for_audio(&source, "audio", &audio(Some(reference)), max_age), reference, ); } @@ -426,13 +426,13 @@ mod tests { async fn legal_reference_keeps_the_rendition() { let live = Live::avc3(); let source = live.source(); - let latency = crate::Latency::REAL_TIME; + let max_age = std::time::Duration::ZERO; for reference in [None, Some(""), Some("./source"), Some("sub"), Some(".")] { - ExportSource::for_video(&source, "video", &video(reference), latency) + ExportSource::for_video(&source, "video", &video(reference), max_age) .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), latency) + ExportSource::for_audio(&source, "audio", &audio(reference), max_age) .unwrap_or_else(|err| panic!("{reference:?} should keep the rendition: {err:?}")) .unwrap_or_else(|| panic!("{reference:?} should keep the rendition")); } @@ -443,20 +443,20 @@ mod tests { #[tokio::test] async fn latency_is_sent_with_the_initial_subscription() { let live = Live::avc3(); - let latency = crate::Latency::max(std::time::Duration::from_secs(10)); - let mut export = ExportSource::for_video(&live.source(), live.track.name(), &video(None), latency) + let max_age = std::time::Duration::from_secs(10); + let mut export = ExportSource::for_video(&live.source(), live.track.name(), &video(None), max_age) .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.latency), + Some(subscription) => Poll::Ready(subscription.max_age), None => Poll::Pending, } }) .await; - assert_eq!(observed, latency); + assert_eq!(observed, max_age); } } diff --git a/rs/moq-mux/src/container/ts/export.rs b/rs/moq-mux/src/container/ts/export.rs index 494c2a972aa..17d80f0c2a8 100644 --- a/rs/moq-mux/src/container/ts/export.rs +++ b/rs/moq-mux/src/container/ts/export.rs @@ -56,7 +56,7 @@ const PSI_INTERVAL: Duration = Duration::from_millis(500); pub struct Export { source: crate::Source, catalog: Option>, - latency: crate::Latency, + max_age: Duration, tracks: HashMap, /// Continuity counter per PID (PAT, PMT, and each elementary stream). @@ -189,7 +189,7 @@ struct SiTrack { /// rate, so the real-time default would take only the newest group and drop /// the revisions between: an SI track needs the export's replay window as much /// as the media it describes. - latency: crate::Latency, + max_age: Duration, } /// The SI subscription's lifecycle, mirroring `ExportSource`'s but reading raw @@ -208,7 +208,7 @@ enum SiState { } impl SiTrack { - fn new(source: &crate::Source, track: &str, interval: Option, latency: crate::Latency) -> Self { + fn new(source: &crate::Source, track: &str, interval: Option, max_age: Duration) -> Self { Self { track: track.to_string(), interval, @@ -216,7 +216,7 @@ impl SiTrack { active: Default::default(), pending: None, last_emit: None, - latency, + max_age, } } @@ -239,7 +239,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_latency(self.latency)), + track.subscribe(moq_net::track::Subscription::default().with_max_age(self.max_age)), ), Err(err) => { tracing::warn!(%err, track = %name, "SI track unavailable; carrying the last snapshot"); @@ -358,7 +358,7 @@ impl Export { Ok(Self { source, catalog: Some(catalog), - latency: crate::Latency::REAL_TIME, + max_age: Duration::ZERO, tracks: HashMap::new(), counters: HashMap::new(), program_descriptors: Vec::new(), @@ -372,13 +372,13 @@ impl Export { }) } - /// Set the latency tolerance for each per-track source. + /// Set the max age for each per-track source. /// /// See [`Consumer`](crate::container::Consumer) for the per-track skip behavior. /// Defaults to - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) (skip aggressively). - pub fn with_latency(mut self, latency: crate::Latency) -> Self { - self.latency = latency; + /// [`Duration::ZERO`] (skip aggressively). + pub fn with_max_age(mut self, max_age: Duration) -> Self { + self.max_age = max_age; self } @@ -583,7 +583,7 @@ impl Export { // staying attached would repeat its stale sections forever. The last // snapshot carries across so emission never goes dark mid-swap. Some(existing) if existing.track != entry.track => { - let mut replacement = SiTrack::new(&self.source, &entry.track, entry.interval, self.latency); + let mut replacement = SiTrack::new(&self.source, &entry.track, entry.interval, self.max_age); replacement.active = std::mem::take(&mut existing.active); replacement.last_emit = existing.last_emit; *existing = replacement; @@ -592,7 +592,7 @@ impl Export { None => { self.si.insert( (*pid, *table_id), - SiTrack::new(&self.source, &entry.track, entry.interval, self.latency), + SiTrack::new(&self.source, &entry.track, entry.interval, self.max_age), ); } } @@ -675,7 +675,7 @@ impl Export { self.tracks.insert(name.clone(), track); } None => { - let Some(source) = ExportSource::for_video(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_video(&self.source, name, config, self.max_age)? else { continue; }; self.insert_track(name, source, pid, kind, descriptors, reserve); @@ -694,7 +694,7 @@ impl Export { self.tracks.insert(name.clone(), track); } None => { - let Some(source) = ExportSource::for_audio(&self.source, name, config, self.latency)? else { + let Some(source) = ExportSource::for_audio(&self.source, name, config, self.max_age)? else { continue; }; self.insert_track(name, source, pid, kind, descriptors, DEFAULT_DTS_RESERVE); @@ -720,7 +720,7 @@ impl Export { self.tracks.insert(name.clone(), existing); } None => { - let source = ExportSource::for_stream(&self.source, name, self.latency)?; + let source = ExportSource::for_stream(&self.source, name, self.max_age)?; self.insert_track(name, source, pid, kind, descriptors, DEFAULT_DTS_RESERVE); } } diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index 784c20812fb..6222e1b272e 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -65,9 +65,9 @@ fn length_prefixed(nals: &[&[u8]]) -> Bytes { /// The media track's full retention window, so an exporter started after publishing /// can still read every retained group. These tests write a whole broadcast up front /// and only then export it, which the -/// exporter's default [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) collapses to 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_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_AGE: Duration = Duration::from_secs(30); async fn drain(consumer: moq_net::broadcast::Consumer) -> BytesMut { drain_with(Export::new(crate::source::announced(&consumer)).await.unwrap()).await @@ -75,10 +75,10 @@ async fn drain(consumer: moq_net::broadcast::Consumer) -> BytesMut { /// `drain` for an exporter built with an explicit catalog extension. async fn drain_with(exporter: Export) -> BytesMut { - let mut exporter = exporter.with_latency(crate::Latency::max(RECORDING_LATENCY)); + let mut exporter = exporter.with_max_age(RECORDING_MAX_AGE); let mut out = BytesMut::new(); // `while let Ok` stops on the first timeout (`Pending`: no more output). - while let Ok(res) = tokio::time::timeout(std::time::Duration::from_secs(1), exporter.next()).await { + while let Ok(res) = tokio::time::timeout(Duration::from_secs(1), exporter.next()).await { let Some(frame) = res.expect("exporter error") else { break; }; @@ -651,7 +651,7 @@ async fn export_scte35_roundtrip() { let track = consumer2 .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(crate::Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut scte_reader = crate::container::Consumer::new(track, HangContainer::Legacy); @@ -751,7 +751,7 @@ async fn export_pes_verbatim_roundtrip() { let track = consumer2 .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(crate::Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy); @@ -806,7 +806,7 @@ async fn scte35_without_video_export_is_rejected() { .await .unwrap(); let err = loop { - match tokio::time::timeout(std::time::Duration::from_secs(1), exporter.next()).await { + match tokio::time::timeout(Duration::from_secs(1), exporter.next()).await { Ok(Ok(Some(_))) => continue, Ok(Ok(None)) => panic!("export completed; a cue program without video must be rejected"), Ok(Err(e)) => break e, @@ -824,12 +824,12 @@ async fn read_frames(consumer: &moq_net::broadcast::Consumer, name: &str) -> Vec let track = consumer .track(name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(crate::Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy); let mut frames = Vec::new(); - while let Ok(res) = tokio::time::timeout(std::time::Duration::from_millis(50), reader.read()).await { + while let Ok(res) = tokio::time::timeout(Duration::from_millis(50), reader.read()).await { let Some(frame) = res.unwrap() else { break }; frames.push(frame.payload.to_vec()); } @@ -1145,12 +1145,12 @@ 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_latency(crate::Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, HangContainer::Legacy); let mut cues = Vec::new(); - while let Ok(res) = tokio::time::timeout(std::time::Duration::from_millis(50), reader.read()).await { + while let Ok(res) = tokio::time::timeout(Duration::from_millis(50), reader.read()).await { let Some(frame) = res.unwrap() else { break }; cues.push((frame.payload.to_vec(), frame.timestamp)); } @@ -1315,7 +1315,7 @@ fn make_long_section(table_id: u8, ext: u16, version: u8, number: u8, last: u8, /// Read an SI snapshot track from the start: every group, as its frames' payloads. /// /// Starting at group 0 only asks the publisher to send from there; the default -/// [`moq_net::Latency::REAL_TIME`] budget then skips every group the live edge has +/// [`Duration::ZERO`] budget then skips every group the live edge has /// already passed, which is all of them once the importer has finished. A budget /// wider than the test's wall-clock span (every cut lands within microseconds) is /// what actually delivers the history, so a count of groups counts cuts. @@ -1326,7 +1326,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_latency(moq_net::Latency::max(moq_net::track::DEFAULT_LATENCY_MAX)), + .with_max_age(moq_net::track::DEFAULT_MAX_AGE), ) .await .unwrap(); @@ -1472,7 +1472,7 @@ async fn service_layer_survives_roundtrip() { let sdt_entry = entry(0x0011, 0x42); assert_eq!( sdt_entry.interval, - Some(std::time::Duration::from_secs(2)), + Some(Duration::from_secs(2)), "the DVB SDT interval was filled in" ); let sdt_sections = read_si_sections(&consumer, &sdt_entry.track).await; @@ -1488,7 +1488,7 @@ async fn service_layer_survives_roundtrip() { let nit_entry = entry(0x0010, 0x40); assert_eq!( nit_entry.interval, - Some(std::time::Duration::from_secs(10)), + Some(Duration::from_secs(10)), "the DVB NIT interval was filled in" ); let nit_groups = read_si_groups(&consumer, &nit_entry.track).await; @@ -2479,7 +2479,7 @@ async fn repointed_si_entry_resubscribes() { let mut exporter = Export::with_ts(crate::source::announced(&consumer), crate::catalog::CatalogFormat::Hang) .await .unwrap() - .with_latency(crate::Latency::max(RECORDING_LATENCY)); + .with_max_age(RECORDING_MAX_AGE); let mut before = BytesMut::new(); write_key(&mut producer, 0); write_key(&mut producer, 1); @@ -2703,7 +2703,7 @@ async fn debounce_opens_without_a_media_clock() { assert_eq!(track.latest(), Some(0), "a revision inside the window is held"); // ...and publishes once the window passes in *real* time, no finish, no PTS. - std::thread::sleep(std::time::Duration::from_millis(1200)); + std::thread::sleep(Duration::from_millis(1200)); rig.import .decode(&BytesMut::from(&si_packet_cc(0x0011, &sdt(1, 0xbb), 3)[..])) .unwrap(); diff --git a/rs/moq-mux/src/container/ts/import.rs b/rs/moq-mux/src/container/ts/import.rs index 317fcfb6ab0..bce41f295ac 100644 --- a/rs/moq-mux/src/container/ts/import.rs +++ b/rs/moq-mux/src/container/ts/import.rs @@ -2335,14 +2335,14 @@ mod test { /// /// The media track's full retention window, so a reader started after importing can /// still read every retained group. These tests import a whole file first, which the default - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) budget collapses to the live + /// [`Duration::ZERO`] budget collapses to the live /// edge: completeness has to be asked for. - const RECORDING_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); + const RECORDING_MAX_AGE: std::time::Duration = Duration::from_secs(30); use mpeg2ts::es::StreamType; use super::{Continuation, Continuity, SectionReassembler}; - use crate::Latency; use moq_net::Timestamp; + use std::time::Duration; // libklvanc public-sample cue: table_id 0xFC, section_length 0x1b (27), 30 bytes total. const CUE: [u8; 30] = [ @@ -2632,7 +2632,7 @@ mod test { // SCTE detection takes no lock here (video/audio would still publish later): the old // discarding ScteStream took the lock and republished an empty catalog on this path. assert!( - tokio::time::timeout(std::time::Duration::from_millis(10), updates.next()) + tokio::time::timeout(Duration::from_millis(10), updates.next()) .await .is_err(), "SCTE detection must not publish the base catalog" @@ -2691,11 +2691,11 @@ mod test { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy); - let frame = tokio::time::timeout(std::time::Duration::from_secs(1), reader.read()) + let frame = tokio::time::timeout(Duration::from_secs(1), reader.read()) .await .expect("cue read timed out") .unwrap() @@ -2907,7 +2907,7 @@ mod test { // Anchored on its own PES: one 1024-sample frame at 48 kHz (~21 ms). // Anchored on the MP2 PES it would be ~2 s. assert!( - jitter <= std::time::Duration::from_millis(100), + jitter <= Duration::from_millis(100), "AAC jitter anchored on a foreign PID: {jitter:?}" ); } @@ -2928,13 +2928,12 @@ mod test { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = tokio::time::timeout(std::time::Duration::from_millis(50), reader.read()).await - { + while let Ok(Ok(Some(frame))) = tokio::time::timeout(Duration::from_millis(50), reader.read()).await { frames.push(frame); } frames @@ -3007,8 +3006,7 @@ mod test { let track = consumer.track(&name).unwrap().subscribe(None).await.unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); let mut frames = Vec::new(); - while let Ok(Ok(Some(frame))) = tokio::time::timeout(std::time::Duration::from_millis(50), reader.read()).await - { + while let Ok(Ok(Some(frame))) = tokio::time::timeout(Duration::from_millis(50), reader.read()).await { frames.push(frame); } frames @@ -3738,11 +3736,11 @@ mod test { let track = consumer .track(hang::catalog::Catalog::DEFAULT_NAME) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); - let published = tokio::time::timeout(std::time::Duration::from_millis(50), reader.read()).await; + let published = tokio::time::timeout(Duration::from_millis(50), reader.read()).await; assert!( matches!(published, Ok(Ok(Some(_)))), "a PID that never published held the catalog shut: {published:?}" @@ -3998,11 +3996,11 @@ mod test { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy); - let frame = tokio::time::timeout(std::time::Duration::from_secs(1), reader.read()) + let frame = tokio::time::timeout(Duration::from_secs(1), reader.read()) .await .expect("cue read timed out") .unwrap() @@ -4013,8 +4011,8 @@ mod test { // The legacy container normalizes the wire timestamp to microseconds, so compare the // instant (not the raw scale) against the 90 kHz media clock the cue was stamped with. assert_eq!( - std::time::Duration::from(frame.timestamp), - std::time::Duration::from(clock), + Duration::from(frame.timestamp), + Duration::from(clock), "cue stamped with the video media clock" ); } @@ -4172,11 +4170,11 @@ mod test { let track = consumer .track(name.as_str()) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = Consumer::new(track, Container::Legacy); - let frame = tokio::time::timeout(std::time::Duration::from_secs(1), reader.read()) + let frame = tokio::time::timeout(Duration::from_secs(1), reader.read()) .await .expect("verbatim read timed out") .unwrap() diff --git a/rs/moq-mux/src/container/ts/import_test.rs b/rs/moq-mux/src/container/ts/import_test.rs index efe35341274..8e9132349cd 100644 --- a/rs/moq-mux/src/container/ts/import_test.rs +++ b/rs/moq-mux/src/container/ts/import_test.rs @@ -9,9 +9,9 @@ use bytes::BytesMut; /// /// The media track's full retention window, so a reader started after importing can /// still read every retained group. These tests import a whole file first, which the default -/// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) budget collapses to the live edge: +/// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) budget collapses to the live edge: /// completeness has to be asked for. -const RECORDING_LATENCY: std::time::Duration = std::time::Duration::from_secs(30); +const RECORDING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(30); /// Decode a whole TS buffer into a fresh broadcast and return the catalog. fn import_ts(data: &[u8]) -> crate::catalog::hang::Catalog { @@ -153,7 +153,7 @@ async fn import_opus_frames() { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(crate::Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); @@ -298,7 +298,7 @@ async fn import_export_import_roundtrip() { let mut exporter = crate::container::ts::Export::new(crate::source::announced(&consumer)) .await .unwrap() - .with_latency(crate::Latency::max(RECORDING_LATENCY)); + .with_max_age(RECORDING_MAX_AGE); let mut out = BytesMut::new(); while let Ok(res) = tokio::time::timeout(std::time::Duration::from_secs(1), exporter.next()).await { match res.expect("exporter error") { @@ -353,7 +353,7 @@ async fn survives_midstream_join() { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(crate::Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); @@ -402,7 +402,7 @@ async fn kyrion_dirtystart_extracts_real_cues() { let track = consumer .track(&name) .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(crate::Latency::max(RECORDING_LATENCY))) + .subscribe(moq_net::track::Subscription::default().with_max_age(RECORDING_MAX_AGE)) .await .unwrap(); let mut reader = crate::container::Consumer::new(track, crate::catalog::hang::Container::Legacy); diff --git a/rs/moq-mux/src/import/track.rs b/rs/moq-mux/src/import/track.rs index 44d7d292563..7c12d34489e 100644 --- a/rs/moq-mux/src/import/track.rs +++ b/rs/moq-mux/src/import/track.rs @@ -912,10 +912,7 @@ mod tests { let track = broadcast.create_track("audio", hang::container::track_info()).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_latency(moq_net::Latency::max(std::time::Duration::from_secs(30))), - ); + let subscriber = track.subscribe(moq_net::track::Subscription::default().with_max_age(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-mux/src/lib.rs b/rs/moq-mux/src/lib.rs index d9740ffb9fa..45b99e03339 100644 --- a/rs/moq-mux/src/lib.rs +++ b/rs/moq-mux/src/lib.rs @@ -33,6 +33,6 @@ pub mod timeline; pub use clock::Clock; pub use error::*; -/// Re-export of [`moq_net::Latency`], the drift budget every consumer-side knob here takes. -pub use moq_net::Latency; pub use source::Source; +/// Re-export of [`std::time::Duration`], the drift budget every consumer-side knob here takes. +pub use std::time::Duration; diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 47afe36ad96..14621c45eb4 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -1,4 +1,4 @@ -use crate::{Latency, frame, group, origin, track}; +use crate::{frame, group, origin, track}; use std::{ collections::HashMap, task::{Poll, ready}, @@ -18,16 +18,16 @@ use crate::{ use super::{Message, Version, cluster, peer}; /// Largest millisecond duration every implementation can carry losslessly. -const MAX_SAFE_LATENCY_MS: u64 = (1_u64 << 53) - 1; +const MAX_SAFE_AGE_MS: u64 = (1_u64 << 53) - 1; /// Build the serving-side subscription for a peer whose wire protocol carries no -/// latency preference. The receiver applies its own budget after the transfer. +/// max age 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. - latency: Latency::max(Duration::from_millis(MAX_SAFE_LATENCY_MS)), + max_age: Duration::from_millis(MAX_SAFE_AGE_MS), ..Default::default() } } @@ -169,18 +169,18 @@ enum Watch { /// Only reached when the peer has granted no more, which on this path means it is holding /// every advertisement we already sent. Long enough that a merely slow peer is not given /// up on, short enough that the loop resumes and can retire something. -const ADVERTISE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); +const ADVERTISE_TIMEOUT: Duration = Duration::from_secs(5); /// First wait before re-offering a namespace we could not get up. -const RETRY_BASE: std::time::Duration = std::time::Duration::from_millis(100); +const RETRY_BASE: Duration = Duration::from_millis(100); /// Ceiling on that wait. The loop retries for the life of the session, so it must settle /// into a slow poll rather than a spin. -const RETRY_MAX: std::time::Duration = std::time::Duration::from_secs(5); +const RETRY_MAX: Duration = Duration::from_secs(5); /// Spread a retry over half its window, so every namespace on a busy relay does not come /// back at the same instant. -fn jitter(delay: std::time::Duration) -> std::time::Duration { +fn jitter(delay: Duration) -> Duration { use rand::RngExt; delay.mul_f64(0.5 + rand::rng().random::() / 2.0) } @@ -553,7 +553,7 @@ impl Publisher { } }; - // moq-transport has no subscriber latency parameter. Keep everything the + // moq-transport has no subscriber max age parameter. Keep everything the // producer retained and let the receiving subscriber enforce its own budget. let subscription = serving_subscription(msg.subscriber_priority); @@ -1033,7 +1033,7 @@ impl Publisher { match (self.version, retry_interval) { (Version::Draft14 | Version::Draft15, _) => Refused::No, (_, 0) => Refused::Never, - (_, ms) => Refused::Until(web_async::time::Instant::now() + std::time::Duration::from_millis(ms)), + (_, ms) => Refused::Until(web_async::time::Instant::now() + Duration::from_millis(ms)), } } @@ -1769,7 +1769,7 @@ mod group_priority_test { "stream credit is exhausted" ); - tokio::time::advance(std::time::Duration::from_secs(1)).await; + tokio::time::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(crate::Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -1830,7 +1830,7 @@ mod group_priority_test { "the final byte is transport-blocked" ); - tokio::time::advance(std::time::Duration::from_secs(1)).await; + tokio::time::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(crate::Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -1881,7 +1881,7 @@ mod tests { use futures::FutureExt; async fn settle() { - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; } fn occurrences(log: &crate::lite::test_transport::Log, needle: &[u8]) -> usize { @@ -1900,7 +1900,7 @@ mod tests { slot } - /// moq-transport cannot carry the receiver's latency budget, so the serving + /// moq-transport cannot carry the receiver's max age budget, so the serving /// subscription must preserve everything the producer still retains. #[test] fn serving_subscription_keeps_retained_backlog() { @@ -1914,7 +1914,7 @@ mod tests { } let subscription = serving_subscription(128); - assert_eq!(subscription.latency.max.as_millis(), MAX_SAFE_LATENCY_MS as u128); + assert_eq!(subscription.max_age.as_millis(), MAX_SAFE_AGE_MS as u128); let mut subscriber = producer.subscribe(subscription); for sequence in [0, 1] { let group = subscriber @@ -1976,7 +1976,7 @@ mod tests { .unwrap(); // Broadcast visibility is deferred until the executor ticks. - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let peer = cluster::Peer::default(); @@ -2782,7 +2782,7 @@ mod tests { /// Advance far enough that a parked open gives up and its retry comes due, without /// making the test wait: time is paused, so this only moves the clock the loop reads. async fn tick() { - tokio::time::advance(std::time::Duration::from_millis(200)).await; + tokio::time::advance(Duration::from_millis(200)).await; } fn set_gate(gate: &kio::Producer, open: bool) { diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 5ec653aa458..5fbbddd27e5 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -1100,11 +1100,11 @@ impl Subscriber { // Accepting at milliseconds (the default) would truncate microsecond precision. // // moq-transport carries no publisher retention property, so the window comes - // from the accepting side (see `origin::Info::latency_default`) rather than + // from the accepting side (see `origin::Info::default_max_age`) rather than // from the peer. let info = track::Info::default() .with_timescale(crate::Timescale::MICRO) - .with_latency_max(self.origin.latency_default()); + .with_max_age(self.origin.default_max_age()); let mut track = request.accept(info); // A peer that sent GOAWAY told us to stop opening streams on this session. @@ -1513,7 +1513,7 @@ mod tests { } async fn settle() { - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; } fn occurrences(log: &crate::lite::test_transport::Log, needle: &[u8]) -> usize { @@ -1754,7 +1754,7 @@ mod tests { .unwrap(); // Broadcast visibility is deferred until the executor ticks. - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let broadcast = consumer.get_broadcast("room/host").unwrap(); let hops: Vec<_> = broadcast.routes()[0].hops.iter().copied().collect(); @@ -1792,7 +1792,7 @@ mod tests { .with_announce(true), ) .unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; announced.assert_next_some("room/host"); // Held for as long as the path is advertised, exactly as the publisher holds // it in its `Watched` entry. The exclusion lives on this handle. @@ -1817,7 +1817,7 @@ mod tests { let _reflected = subscriber .start_announce(crate::Path::new("room/host").to_owned(), advert) .unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; // No announce churn, and the path still resolves to the upstream route, which // is the one the publish direction can advertise back to the peer. @@ -1865,12 +1865,12 @@ mod tests { }; let _first = connect(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; announced.assert_next_some("room/host"); // The peer reconnects before the old session is retired. let _second = connect(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; // It joined: no announce churn, and both routes are in the table so the front // can fail over the moment the stale one dies. @@ -1945,7 +1945,7 @@ mod tests { subscriber .start_announce(crate::Path::new("room/host").to_owned(), advertised) .unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let broadcast = consumer.get_broadcast("room/host").unwrap(); let hops: Vec<_> = broadcast.routes()[0].hops.iter().map(|h| h.id()).collect(); @@ -2260,7 +2260,7 @@ mod tests { publisher: Some(crate::Origin::new(7).unwrap()), }; subscriber.start_announce(path.clone(), first).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let original = consumer.get_broadcast("room/host").unwrap(); // Same publisher (hop 7), new path and cost: the route updates in place. @@ -2273,7 +2273,7 @@ mod tests { publisher: Some(crate::Origin::new(7).unwrap()), }; subscriber.update_announce(path.clone(), rerouted).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let broadcast = consumer.get_broadcast("room/host").unwrap(); let hops: Vec<_> = broadcast.routes()[0].hops.iter().map(|h| h.id()).collect(); @@ -2284,7 +2284,7 @@ mod tests { // One advertisement, so one unannounce detaches it. If the update had bumped the // refcount, this would leave the source stranded. subscriber.stop_announce(path, Detach::Graceful).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/host").is_none()); } @@ -2305,7 +2305,7 @@ mod tests { publisher: Some(crate::Origin::new(7).unwrap()), }; subscriber.start_announce(path.clone(), first).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let original = consumer.get_broadcast("room/host").unwrap(); let taken_over = crate::broadcast::Route::new() @@ -2316,7 +2316,7 @@ mod tests { publisher: Some(crate::Origin::new(8).unwrap()), }; subscriber.update_announce(path.clone(), taken_over).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(original.is_closed(), "the old source was detached"); let broadcast = consumer.get_broadcast("room/host").unwrap(); @@ -2325,7 +2325,7 @@ mod tests { // Still one advertisement, so one unannounce is all it takes. subscriber.stop_announce(path, Detach::Graceful).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/host").is_none()); } @@ -2443,23 +2443,23 @@ mod tests { let first = subscriber.route(None, &peer).expect("route"); assert_eq!(first.publisher, None, "no path means no identity to compare"); subscriber.start_announce(path.clone(), first).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let original = consumer.get_broadcast("room/host").unwrap(); // The NAMESPACE for the same namespace arrives second. let second = subscriber.route(None, &peer).expect("route"); subscriber.start_announce(path.clone(), second).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(!original.is_closed(), "the source survived the second advertisement"); assert!(consumer.get_broadcast("room/host").is_some()); // Two advertisements, so it takes two unannounces to detach. subscriber.stop_announce(path.clone(), Detach::Graceful).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/host").is_some()); subscriber.stop_announce(path, Detach::Graceful).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/host").is_none()); } @@ -2483,7 +2483,7 @@ mod tests { }; let advert = subscriber.route(Some(&clean), &peer).expect("route"); subscriber.start_announce(path.clone(), advert).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/host").is_some()); // The peer re-advertises the namespace over a path that now flows through us. @@ -2498,7 +2498,7 @@ mod tests { // That supersedes the advertisement it repeats, so the old route is retired. subscriber.stop_announce(path, Detach::Graceful).unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!( consumer.get_broadcast("room/host").is_none(), "the superseded route must not stay attached" @@ -2707,7 +2707,7 @@ mod tests { subscriber.start_announce(path.clone(), advert).unwrap(); live.insert(path); } - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/a").is_some()); assert!(consumer.get_broadcast("room/b").is_some()); @@ -2715,7 +2715,7 @@ mod tests { for path in live { subscriber.stop_announce(path, Detach::Graceful).unwrap(); } - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!(consumer.get_broadcast("room/a").is_none(), "room/a leaked a refcount"); assert!(consumer.get_broadcast("room/b").is_none(), "room/b leaked a refcount"); @@ -2760,7 +2760,7 @@ mod tests { // Errors are surfaced to the peer on the stream, not raised as a session error. subscriber.run_publish_stream(stream, msg).await.unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; assert!( consumer.get_broadcast("room/host").is_none(), diff --git a/rs/moq-net/src/latency.rs b/rs/moq-net/src/latency.rs deleted file mode 100644 index 636078b6b75..00000000000 --- a/rs/moq-net/src/latency.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! How far a subscriber may drift from the live edge. - -use std::time::Duration; - -/// How far a subscriber may drift behind the live edge before a group is skipped. -/// -/// Only a ceiling today: a stalled group is skipped once newer data is [`max`](Self::max) -/// ahead of it. [`Latency::REAL_TIME`] (the default) skips aggressively, so any group with -/// a newer alternative is dropped. -/// -/// This never *adds* latency. The bound is reached only when newer data is already that far -/// ahead, so raising it buys a stalled group more time to arrive rather than padding a -/// buffer. -/// -/// # Where it is enforced -/// -/// At both ends of a subscription, and neither alone is enough. A publisher skips a group -/// that has drifted past the budget instead of putting it on the wire, which is what bounds -/// a backlog before it costs bandwidth. But what reaches a publisher is the aggregate -/// across every subscriber, which [`merge`](Self::merge) resolves in favor of the most -/// tolerant one, so that gate is only ever as tight as the most patient viewer. The -/// subscriber applies the same budget again as it reads, where its own budget is the only -/// one in play and the semantics are exact. -/// -/// This bounds a *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 drift is measured -/// -/// By both presentation time and wall-clock arrival time, with either age able to expire -/// the group. Presentation time compares a group's first timestamp against the newest one -/// above it, so a backlog delivered as a burst still reads as its true age. Wall-clock time -/// compares when each group entered this hop, which backstops an empty or stalled group that -/// has not supplied a first-frame timestamp. -/// -/// Protocols whose wire can't carry a timestamp (pre-Lite05 moq-lite, moq-transport without -/// the Timestamp property) have their frames stamped on receipt instead, which makes 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. -/// -/// # Not a retention window -/// -/// Distinct from [`track::Info::latency_max`](crate::track::Info::latency_max), which is a -/// *retention* bound (how long the publisher keeps a group, the inverse of an HTTP -/// `Cache-Control: max-age`) rather than a drift budget. A budget is clamped to it, since -/// waiting for a group longer than it is kept around cannot produce it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -#[non_exhaustive] -pub struct Latency { - /// Ceiling: a group is skipped once newer data is this far ahead of it. - /// - /// Zero (the default) skips aggressively. - pub max: Duration, -} - -impl Latency { - /// Minimize latency: any group with a newer alternative is dropped. - pub const REAL_TIME: Self = Self { max: Duration::ZERO }; - - /// Tolerate a stalled group until newer data is `max` ahead of it. - /// - /// Set it to the playout buffer you can absorb (typically tens to a few hundred - /// milliseconds) for the best congestion-vs-quality trade-off. - pub const fn max(max: Duration) -> Self { - Self { max } - } - - /// The budget that satisfies both: the more tolerant of the two. - /// - /// How subscriptions to one track combine, since a group may only be skipped once - /// every subscriber has given up on it. - pub fn merge(self, other: Self) -> Self { - Self::max(self.max.max(other.max)) - } -} diff --git a/rs/moq-net/src/lib.rs b/rs/moq-net/src/lib.rs index 3f21a058592..198b55a167f 100644 --- a/rs/moq-net/src/lib.rs +++ b/rs/moq-net/src/lib.rs @@ -86,7 +86,6 @@ mod coding; mod error; pub mod goaway; mod ietf; -mod latency; mod lite; mod model; mod path; @@ -102,7 +101,6 @@ pub mod transport; pub use client::*; pub use coding::{BoundsExceeded, DecodeError, EncodeError, VarInt}; pub use error::*; -pub use latency::Latency; /// The session direction a client advertises in its SETUP (moq-lite-05+). pub use lite::Role; pub use model::*; diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 5f621027eab..fca27a43a69 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -90,7 +90,7 @@ struct Shared { } /// Largest millisecond duration every implementation can carry losslessly. -const MAX_SAFE_LATENCY_MS: u64 = (1_u64 << 53) - 1; +const MAX_SAFE_AGE_MS: u64 = (1_u64 << 53) - 1; /// The budget to serve a peer with, given what its wire could tell us. /// @@ -99,10 +99,10 @@ const MAX_SAFE_LATENCY_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_latency(version: Version, requested: Duration) -> crate::Latency { - match version.carries_latency() { - true => crate::Latency::max(requested), - false => crate::Latency::max(Duration::from_millis(MAX_SAFE_LATENCY_MS)), +fn serving_max_age(version: Version, requested: Duration) -> Duration { + match version.carries_max_age() { + true => requested, + false => Duration::from_millis(MAX_SAFE_AGE_MS), } } @@ -1171,7 +1171,7 @@ impl TrackInfoServe { stream.writer.buffer(&lite::TrackInfo { priority: info.priority, ordered: info.ordered, - latency_max: info.latency_max, + max_age: info.max_age, timescale: info.timescale, })?; self.state = TrackInfoState::Finish { finished: false }; @@ -1310,7 +1310,7 @@ impl SubscribeServe { let subscription = crate::track::Subscription { priority: msg.priority, ordered: msg.ordered, - latency: serving_latency(self.shared.version, msg.latency_max), + max_age: serving_max_age(self.shared.version, msg.max_age), ..Bounds::from(&msg).positions() }; @@ -1350,7 +1350,7 @@ impl SubscribeServe { let info = lite::SubscribeOk { priority: msg.priority, ordered: false, - latency_max: std::time::Duration::ZERO, + max_age: Duration::ZERO, start_group: None, end_group: None, }; @@ -1736,8 +1736,7 @@ mod test { use futures::FutureExt; let mut producer = track_producer("test"); - let mut subscriber = producer - .subscribe(track::Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(5)))); + let mut subscriber = producer.subscribe(track::Subscription::default().with_max_age(Duration::from_secs(5))); producer.create_group(group::Info { sequence: 2 }).unwrap(); match recv_next(&mut subscriber, false, false).await.unwrap() { @@ -1753,7 +1752,7 @@ mod test { None => panic!("the late-arriving group was skipped"), } - // Staleness is the latency window's job, not arrival order's: the track + // Staleness is the max age 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() { @@ -2457,7 +2456,7 @@ enum Recv { /// Groups are served in arrival order (`poll_recv_group`), not sequence order: on a relay, a /// burst can be ingested micro-reordered by the upstream leg, and a sequence cursor would then /// permanently skip the older group even though it is cached and in demand. Staleness is -/// governed by the latency window (cache expiry), not arrival raciness. +/// governed by the max age window (cache expiry), not arrival raciness. /// /// When `emit_boundary` is set, a declared-but-not-yet-reached final sequence surfaces as /// [`Recv::Boundary`] in an idle moment (after groups and datagrams), so the caller can send @@ -2787,7 +2786,7 @@ impl TrackRun { let _ = self.track.update(crate::track::Subscription { priority: upd.priority, ordered: upd.ordered, - latency: serving_latency(self.ctx.version, upd.latency_max), + max_age: serving_max_age(self.ctx.version, upd.max_age), ..bounds.positions() }); if let Some(start_group) = upd.start_group { @@ -3250,7 +3249,7 @@ mod serve_group_test { assert_eq!(log.resets(), vec![crate::StreamError::Old.to_code()]); } - /// A subscription group keeps checking latency while a transport write is + /// A subscription group keeps checking the max age while a transport write is /// flow-control blocked, so a stalled send cannot pin the stream indefinitely. #[tokio::test] async fn blocked_transport_write_expires_with_the_group() { @@ -3286,7 +3285,7 @@ mod serve_group_test { "transport write is blocked" ); - tokio::time::advance(std::time::Duration::from_secs(1)).await; + tokio::time::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -3349,7 +3348,7 @@ mod serve_group_test { "the final byte is transport-blocked" ); - tokio::time::advance(std::time::Duration::from_secs(1)).await; + tokio::time::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -3359,7 +3358,7 @@ mod serve_group_test { assert_eq!(log.resets(), vec![crate::StreamError::Old.to_code()]); } - /// A subscription group keeps checking latency while transport stream credit is + /// A subscription group keeps checking the max age while transport stream credit is /// exhausted, so returning credit is reserved for content that is still live. #[tokio::test] async fn blocked_transport_open_expires_with_the_group() { @@ -3394,7 +3393,7 @@ mod serve_group_test { "stream credit is exhausted" ); - tokio::time::advance(std::time::Duration::from_secs(1)).await; + tokio::time::advance(Duration::from_secs(1)).await; let mut edge = track.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), b"edge".as_slice()) .unwrap(); @@ -3403,7 +3402,7 @@ mod serve_group_test { assert!(matches!(serve.await, Err(Error::Old))); } - /// Lite01/02 have no latency field, so a SUBSCRIBE from one decodes as + /// Lite01/02 have no max age 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. @@ -3413,17 +3412,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 latency = serving_latency(version, Duration::ZERO); + let max_age = serving_max_age(version, Duration::ZERO); assert!( - latency.max >= Duration::from_secs(86_400), - "{version:?} must not be served as real time: {latency:?}" + max_age >= Duration::from_secs(86_400), + "{version:?} must not be served as real time: {max_age:?}" ); } // A version that does carry it is taken at its word, zero included. - assert_eq!(serving_latency(Version::Lite05, Duration::ZERO).max, Duration::ZERO); + assert_eq!(serving_max_age(Version::Lite05, Duration::ZERO), Duration::ZERO); assert_eq!( - serving_latency(Version::Lite05, Duration::from_secs(3)).max, + serving_max_age(Version::Lite05, Duration::from_secs(3)), Duration::from_secs(3) ); } @@ -3512,7 +3511,7 @@ mod tests { .unwrap(); // Broadcast visibility is deferred until the executor ticks. - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let gate = kio::Producer::new(true); let session = SinkSession::gated_bi(gate.consume()); diff --git a/rs/moq-net/src/lite/subscribe.rs b/rs/moq-net/src/lite/subscribe.rs index 7c5829b3a55..c012ed14809 100644 --- a/rs/moq-net/src/lite/subscribe.rs +++ b/rs/moq-net/src/lite/subscribe.rs @@ -17,7 +17,7 @@ pub struct Subscribe<'a> { pub track: Cow<'a, str>, pub priority: u8, pub ordered: bool, - pub latency_max: std::time::Duration, + pub max_age: std::time::Duration, pub start_group: Option, pub end_group: Option, /// First frame to deliver within `start_group`'s group; 0 is the whole group. @@ -29,12 +29,12 @@ pub struct Subscribe<'a> { } impl Version { - /// Whether this version's SUBSCRIBE carries the subscriber's latency preference. + /// Whether this version's SUBSCRIBE carries the subscriber's max age preference. /// - /// Lite01/02 have no field for it, so a decoded `Duration::ZERO` there means + /// 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_latency(self) -> bool { + pub(crate) fn carries_max_age(self) -> bool { !matches!(self, Version::Lite01 | Version::Lite02) } } @@ -46,14 +46,14 @@ impl Message for Subscribe<'_> { let track = Cow::::decode(r, version)?; let priority = u8::decode(r, version)?; - let (ordered, latency_max, start_group, end_group) = match version { + let (ordered, max_age, start_group, end_group) = match version { Version::Lite01 | Version::Lite02 => (false, std::time::Duration::ZERO, None, None), _ => { let ordered = u8::decode(r, version)? != 0; - let latency_max = std::time::Duration::decode(r, version)?; + let max_age = std::time::Duration::decode(r, version)?; let start_group = Option::::decode(r, version)?; let end_group = Option::::decode(r, version)?; - (ordered, latency_max, start_group, end_group) + (ordered, max_age, start_group, end_group) } }; @@ -65,7 +65,7 @@ impl Message for Subscribe<'_> { track, priority, ordered, - latency_max, + max_age, start_group, end_group, start_frame, @@ -83,7 +83,7 @@ impl Message for Subscribe<'_> { Version::Lite01 | Version::Lite02 => {} _ => { (self.ordered as u8).encode(w, version)?; - self.latency_max.encode(w, version)?; + self.max_age.encode(w, version)?; self.start_group.encode(w, version)?; self.end_group.encode(w, version)?; } @@ -163,7 +163,7 @@ fn encode_frame_bounds( pub struct SubscribeOk { pub priority: u8, pub ordered: bool, - pub latency_max: std::time::Duration, + pub max_age: std::time::Duration, pub start_group: Option, pub end_group: Option, } @@ -180,7 +180,7 @@ impl Message for SubscribeOk { _ => { self.priority.encode(w, version)?; (self.ordered as u8).encode(w, version)?; - self.latency_max.encode(w, version)?; + self.max_age.encode(w, version)?; self.start_group.encode(w, version)?; self.end_group.encode(w, version)?; } @@ -194,28 +194,28 @@ impl Message for SubscribeOk { Version::Lite01 => Ok(Self { priority: u8::decode(r, version)?, ordered: false, - latency_max: std::time::Duration::ZERO, + max_age: std::time::Duration::ZERO, start_group: None, end_group: None, }), Version::Lite02 => Ok(Self { priority: 0, ordered: false, - latency_max: std::time::Duration::ZERO, + max_age: std::time::Duration::ZERO, start_group: None, end_group: None, }), _ => { let priority = u8::decode(r, version)?; let ordered = u8::decode(r, version)? != 0; - let latency_max = std::time::Duration::decode(r, version)?; + let max_age = std::time::Duration::decode(r, version)?; let start_group = Option::::decode(r, version)?; let end_group = Option::::decode(r, version)?; Ok(Self { priority, ordered, - latency_max, + max_age, start_group, end_group, }) @@ -290,7 +290,7 @@ impl Message for SubscribeEnd { pub struct SubscribeUpdate { pub priority: u8, pub ordered: bool, - pub latency_max: std::time::Duration, + pub max_age: std::time::Duration, pub start_group: Option, pub end_group: Option, /// See [`Subscribe::start_frame`]. @@ -310,7 +310,7 @@ impl Message for SubscribeUpdate { let priority = u8::decode(r, version)?; let ordered = u8::decode(r, version)? != 0; - let latency_max = std::time::Duration::decode(r, version)?; + let max_age = std::time::Duration::decode(r, version)?; let start_group = match u64::decode(r, version)? { 0 => None, group => Some(group - 1), @@ -325,7 +325,7 @@ impl Message for SubscribeUpdate { Ok(Self { priority, ordered, - latency_max, + max_age, start_group, end_group, start_frame, @@ -343,7 +343,7 @@ impl Message for SubscribeUpdate { self.priority.encode(w, version)?; (self.ordered as u8).encode(w, version)?; - self.latency_max.encode(w, version)?; + self.max_age.encode(w, version)?; match self.start_group { Some(start_group) => start_group @@ -575,7 +575,7 @@ mod test { track: Cow::Borrowed("video"), priority: 3, ordered: true, - latency_max: std::time::Duration::from_millis(250), + max_age: std::time::Duration::from_millis(250), start_group: Some(7), end_group: Some(9), start_frame: 4, @@ -650,7 +650,7 @@ mod test { let resp = SubscribeResponse::Ok(SubscribeOk { priority: 1, ordered: true, - latency_max: std::time::Duration::ZERO, + max_age: 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 57e42433e21..937d2e13f0f 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -1857,7 +1857,7 @@ mod tests { assert!(accepted); // Broadcast visibility is deferred until the executor ticks. - tokio::time::sleep(std::time::Duration::from_millis(1)).await; + tokio::time::sleep(Duration::from_millis(1)).await; let broadcast = consumer.get_broadcast("room/host").unwrap(); let hops: Vec<_> = broadcast.routes()[0].hops.iter().copied().collect(); @@ -2092,7 +2092,7 @@ struct SubStream { /// Original SUBSCRIBE params, echoed in every SUBSCRIBE_UPDATE; refreshed as the /// downstream aggregate changes. ordered: bool, - latency_max: Duration, + max_age: Duration, start: Option, priority: u8, /// The start the SUBSCRIBE itself carried, fixed for the stream's life. A @@ -2228,7 +2228,7 @@ impl TrackServe { let start_moved = active.start != subscription.start; active.priority = subscription.priority; active.ordered = subscription.ordered; - active.latency_max = subscription.latency.max; + active.max_age = subscription.max_age; active.start = subscription.start; if supports_update { // The floor follows the requested start, in both directions: @@ -2393,7 +2393,7 @@ fn buffer_update( active.stream.writer.buffer(&lite::SubscribeUpdate { priority: active.priority, ordered: active.ordered, - latency_max: active.latency_max, + max_age: active.max_age, start_group: bounds.start_group, end_group: bounds.end_group, start_frame: bounds.start_frame, @@ -2448,7 +2448,7 @@ impl Establish { track: self.serve.name.as_str().into(), priority: self.subscription.priority, ordered: self.subscription.ordered, - latency_max: self.subscription.latency.max, + max_age: self.subscription.max_age, start_group: bounds.start_group, end_group: bounds.end_group, start_frame: bounds.start_frame, @@ -2493,7 +2493,7 @@ impl Establish { stream, id: self.id, ordered: self.subscription.ordered, - latency_max: self.subscription.latency.max, + max_age: self.subscription.max_age, start: self.subscription.start, priority: self.subscription.priority, requested: self.subscription.start, @@ -2532,8 +2532,8 @@ impl TrackServeRun { } } else { // No TRACK stream, so the publisher's retention window never reaches us: - // the accepting side picks it (see `origin::Info::latency_default`). - let info = track::Info::default().with_latency_max(serve.subscriber.origin.latency_default()); + // the accepting side picks it (see `origin::Info::default_max_age`). + let info = track::Info::default().with_max_age(serve.subscriber.origin.default_max_age()); TrackRunState::Serve(ServeLoop::new(&serve, request, info, None)) }; Self { serve, state } @@ -2660,13 +2660,13 @@ impl TrackInfoFetch { // stream drop. let _ = stream.writer.finish(); - // Publisher Max Latency rides on the wire, so the local retention + // Publisher Max Age rides on the wire, so the local retention // window matches what the upstream advertises (relays re-serve with // the same bound). `broadcast` is left at its default here; // `track::Request::accept` stamps the track's real broadcast. let model = track::Info::default() .with_timescale(info.timescale) - .with_latency_max(info.latency_max) + .with_max_age(info.max_age) .with_priority(info.priority) .with_ordered(info.ordered); return Poll::Ready(Ok(model)); @@ -3036,7 +3036,7 @@ impl FetchServeRun { // panicking. let group_info = track::Info::default() .with_timescale(self.timescale.unwrap_or_default()) - .with_latency_max(self.serve.subscriber.origin.latency_default()); + .with_max_age(self.serve.subscriber.origin.default_max_age()); let mut producer = match request.accept(group_info) { Ok(producer) => producer, Err(err) => { diff --git a/rs/moq-net/src/lite/track.rs b/rs/moq-net/src/lite/track.rs index ae65b5f3a6c..9dfa62ef427 100644 --- a/rs/moq-net/src/lite/track.rs +++ b/rs/moq-net/src/lite/track.rs @@ -52,9 +52,9 @@ pub struct TrackInfo { /// Whether groups are prioritized in sequence order. Groups may always arrive /// out-of-order (or not at all) over the network. pub ordered: bool, - /// Publisher Max Latency: an upper bound on how long the publisher caches a + /// Publisher Max Age: an upper bound on how long the publisher caches a /// non-latest group past the arrival of a newer one. Encoded as milliseconds. - pub latency_max: Duration, + pub max_age: Duration, /// Per-frame timestamp scale (units per second). Mandatory on Lite05+: every track /// is timed, so this is always a real scale on the wire (never zero). pub timescale: Timescale, @@ -68,13 +68,13 @@ impl Message for TrackInfo { let priority = u8::decode(r, version)?; let ordered = u8::decode(r, version)? != 0; - let latency_max = Duration::decode(r, version)?; + let max_age = Duration::decode(r, version)?; let timescale = Timescale::new(u64::decode(r, version)?).map_err(|_| DecodeError::InvalidValue)?; Ok(Self { priority, ordered, - latency_max, + max_age, timescale, }) } @@ -86,7 +86,7 @@ impl Message for TrackInfo { self.priority.encode(w, version)?; (self.ordered as u8).encode(w, version)?; - self.latency_max.encode(w, version)?; + self.max_age.encode(w, version)?; u64::from(self.timescale).encode(w, version)?; Ok(()) } @@ -100,7 +100,7 @@ mod test { TrackInfo { priority: 7, ordered: false, - latency_max: Duration::from_millis(2000), + max_age: Duration::from_millis(2000), timescale: Timescale::MICRO, } } @@ -117,7 +117,7 @@ mod test { let got = info_roundtrip(Version::Lite05, &info_sample()); assert_eq!(got.priority, 7); assert!(!got.ordered); - assert_eq!(got.latency_max, Duration::from_millis(2000)); + assert_eq!(got.max_age, Duration::from_millis(2000)); assert_eq!(got.timescale, Timescale::MICRO); } @@ -134,7 +134,7 @@ mod test { let info = TrackInfo { priority: info.priority, ordered: info.ordered, - latency_max: info.latency_max, + max_age: info.max_age, timescale: info.timescale, }; let mut buf = Vec::new(); diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index 261e793d00f..c1f609da031 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -508,7 +508,7 @@ impl Producer { /// /// Returns a fresh name like `0{suffix}`, `1{suffix}`, etc. Use this when /// you need to set non-default Track properties (e.g. `with_timescale`, - /// `with_latency_max`) before handing the Track to [`Self::create_track`]. + /// `with_max_age`) before handing the Track to [`Self::create_track`]. pub fn unique_name(&self, suffix: &str) -> String { let state = self.state.read(); (0u16..) @@ -1346,7 +1346,7 @@ mod test { /// Await with a timeout so a missed demand wake fails the test instead of /// hanging it (time is paused, so the timeout fires instantly when idle). async fn expect(fut: impl Future) -> T { - tokio::time::timeout(std::time::Duration::from_secs(1), fut) + tokio::time::timeout(Duration::from_secs(1), fut) .await .expect("timed out waiting for a demand edge") } diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index d858895f50d..93da4aecd19 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -221,7 +221,7 @@ impl GroupState { /// Resolve the group's terminal state for a reader positioned at `index`. /// /// A finished group is still aborted once its frames are released to free memory - /// (aged out of the track's latency window, or evicted by the cache pool). A reader + /// (aged out of the track's max age window, or evicted by the cache pool). A reader /// that already consumed every frame is missing nothing, so it gets the clean end of /// group; one that fell short sees the abort rather than a silently truncated stream. fn poll_terminal(&self, index: usize) -> Poll> { @@ -1120,7 +1120,7 @@ impl Consumer { } } - /// Whether this cursor failed because its subscription latency budget expired. + /// Whether this cursor failed because its subscription max age budget expired. pub(crate) fn latency_expired(&self) -> bool { self.expired } @@ -1839,7 +1839,7 @@ mod test { } /// A finished group is still aborted once its frames are released to free memory (the - /// track's latency window, or the cache pool). A reader that already drained every frame + /// track's max age window, or the cache pool). A reader that already drained every frame /// is missing nothing, so it must see the clean end of group rather than the abort. #[test] fn abort_after_finish_keeps_the_clean_end_for_a_drained_reader() { diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 582ad5154bd..ad215112a91 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -105,7 +105,7 @@ pub struct Info { pub pool: cache::Pool, /// Ceiling on how long any non-latest group under this origin is retained. Each - /// track's own [`latency_max`](track::Info::latency_max) window is clamped down to + /// track's own [`max_age`](track::Info::max_age) window is clamped down to /// this when the track binds, so a group is never held longer than this regardless /// of what a publisher advertises. The age budget alongside [`Self::pool`]'s byte /// budget: a relay bounds memory by both. [`Duration::MAX`] (the default) imposes no @@ -114,14 +114,14 @@ pub struct Info { /// The retention window given to a track whose publisher advertises none. /// - /// moq-lite 05+ carries [`latency_max`](track::Info::latency_max) in TRACK_INFO, so a + /// moq-lite 05+ carries [`max_age`](track::Info::max_age) in TRACK_INFO, so a /// track relayed over it keeps the window its publisher chose. Every moq-transport /// draft and moq-lite 01-04 have no such wire property, so a track arriving over one /// of them lands here instead. Raise it on a relay fronting a segmented egress /// (HLS/DASH), which needs a playlist window's worth of history rather than the live - /// edge. Defaults to [`track::DEFAULT_LATENCY_MAX`], and [`Self::cache_duration`] + /// edge. Defaults to [`track::DEFAULT_MAX_AGE`], and [`Self::cache_duration`] /// still caps it. - pub latency_default: Duration, + pub default_max_age: Duration, } impl Default for Info { @@ -132,7 +132,7 @@ impl Default for Info { id: Origin::UNKNOWN, pool: cache::Pool::default(), cache_duration: Duration::MAX, - latency_default: track::DEFAULT_LATENCY_MAX, + default_max_age: track::DEFAULT_MAX_AGE, } } } @@ -156,10 +156,10 @@ impl Info { self } - /// Set the retention window (see [`Self::latency_default`]) used for tracks whose + /// Set the retention window (see [`Self::default_max_age`]) used for tracks whose /// publisher advertises none, returning `self` for chaining. - pub fn with_latency_default(mut self, latency_default: Duration) -> Self { - self.latency_default = latency_default; + pub fn with_default_max_age(mut self, default_max_age: Duration) -> Self { + self.default_max_age = default_max_age; self } } @@ -935,8 +935,8 @@ pub struct Producer { cache_duration: Duration, // Retention window for a track whose publisher advertises none (see - // [`Info::latency_default`]). - latency_default: Duration, + // [`Info::default_max_age`]). + default_max_age: Duration, // Ingress stats context. Broadcasts created through this producer are attributed // to it (writes counted on the subscriber/ingress side). Empty (no-op) unless a @@ -976,7 +976,7 @@ impl Producer { dynamic: dynamic.clone(), pool: info.pool, cache_duration: info.cache_duration, - latency_default: info.latency_default, + default_max_age: info.default_max_age, stats: stats::Session::default(), tasks, }; @@ -1007,14 +1007,14 @@ impl Producer { id: self.info, pool: self.pool.clone(), cache_duration: self.cache_duration, - latency_default: self.latency_default, + default_max_age: self.default_max_age, } } // The retention window for a track whose publisher advertises none (see - // [`Info::latency_default`]). Cheaper than `info()`, which clones the pool. - pub(crate) fn latency_default(&self) -> Duration { - self.latency_default + // [`Info::default_max_age`]). Cheaper than `info()`, which clones the pool. + pub(crate) fn default_max_age(&self) -> Duration { + self.default_max_age } /// A producer with *no* allowed prefixes: it can't publish anything and @@ -1032,7 +1032,7 @@ impl Producer { dynamic: kio::Shared::default(), pool: cache::Pool::default(), cache_duration: Duration::MAX, - latency_default: track::DEFAULT_LATENCY_MAX, + default_max_age: track::DEFAULT_MAX_AGE, stats: stats::Session::default(), tasks, } @@ -1187,7 +1187,7 @@ impl Producer { dynamic: self.dynamic.clone(), pool: self.pool.clone(), cache_duration: self.cache_duration, - latency_default: self.latency_default, + default_max_age: self.default_max_age, stats: self.stats.clone(), tasks: self.tasks.clone(), }) @@ -1244,7 +1244,7 @@ impl Producer { dynamic: self.dynamic.clone(), pool: self.pool.clone(), cache_duration: self.cache_duration, - latency_default: self.latency_default, + default_max_age: self.default_max_age, stats: self.stats.clone(), tasks: self.tasks.clone(), }) @@ -3717,7 +3717,7 @@ mod tests { /// Serve one requested track from a source like a session would: wait for the /// origin to dispatch it, then accept with default info. async fn accept_track(dynamic: &mut broadcast::Dynamic, name: &str) -> track::Producer { - let request = tokio::time::timeout(std::time::Duration::from_secs(1), dynamic.requested_track()) + let request = tokio::time::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .expect("timed out waiting for a track request") .expect("source closed"); @@ -3731,7 +3731,7 @@ mod tests { async fn accept_tracks(dynamic: &mut broadcast::Dynamic, count: usize) -> HashMap { let mut accepted = HashMap::new(); for _ in 0..count { - let request = tokio::time::timeout(std::time::Duration::from_secs(1), dynamic.requested_track()) + let request = tokio::time::timeout(Duration::from_secs(1), dynamic.requested_track()) .await .expect("timed out waiting for a track request") .expect("source closed"); @@ -4069,7 +4069,7 @@ mod tests { tokio::task::yield_now().await; assert!(!pending.is_finished(), "the partial frame should still be pending"); - tokio::time::advance(std::time::Duration::from_secs(1)).await; + tokio::time::advance(Duration::from_secs(1)).await; let mut edge = producer.append_group().unwrap(); edge.write_frame(Timestamp::from_millis(1000).unwrap(), Bytes::from_static(b"edge")) .unwrap(); @@ -4486,7 +4486,7 @@ mod tests { let subscribing = broadcast .track("video") .unwrap() - .subscribe(track::Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(5)))); + .subscribe(track::Subscription::default().with_max_age(Duration::from_secs(5))); let mut producer = accept_track(&mut dynamic_a, "video").await; settle().await; dynamic_b.assert_no_request(); @@ -4872,7 +4872,7 @@ mod tests { let subscribing = broadcast .track("video") .unwrap() - .subscribe(track::Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(5)))); + .subscribe(track::Subscription::default().with_max_age(Duration::from_secs(5))); let mut producer_a = accept_track(&mut dynamic_a, "video").await; settle().await; let mut sub = subscribing.await.unwrap(); @@ -5773,7 +5773,7 @@ mod tests { let mut producer_local = None; for _ in 0..2 { - let request = tokio::time::timeout(std::time::Duration::from_secs(1), dynamic_local.requested_track()) + let request = tokio::time::timeout(Duration::from_secs(1), dynamic_local.requested_track()) .await .expect("timed out waiting for a track request") .expect("source closed"); @@ -7819,7 +7819,7 @@ mod tests { rt.block_on(scenario); let _ = done_tx.send(()); }); - match done_rx.recv_timeout(std::time::Duration::from_secs(secs)) { + match done_rx.recv_timeout(Duration::from_secs(secs)) { Ok(()) => { let _ = handle.join(); } @@ -8015,7 +8015,7 @@ mod tests { // Drain: resolve pending subscriptions and read groups. _ => { for sub in pending_subs.drain(..) { - match ::tokio::time::timeout(std::time::Duration::from_millis(5), sub).await { + match ::tokio::time::timeout(Duration::from_millis(5), sub).await { Ok(Ok(sub)) => subs.push(sub), Ok(Err(_)) => {} // Still pending: dropping unsubscribes. diff --git a/rs/moq-net/src/model/resume.rs b/rs/moq-net/src/model/resume.rs index 340353c8b00..c539dce6e4f 100644 --- a/rs/moq-net/src/model/resume.rs +++ b/rs/moq-net/src/model/resume.rs @@ -90,10 +90,10 @@ fn slice(prefs: &Subscription, start: Option, end: Option) - /// A takeover boundary therefore becomes demand even for a live-edge subscriber, so the /// replacement resumes exactly where the dead route stopped and the splice loses nothing. /// The catch-up that buys is bounded by how far the boundary trails the replacement's live -/// edge, which is failover latency: a broadcast closes with its last source (there is no +/// edge, which is failover max_age: a broadcast closes with its last source (there is no /// linger), so a takeover only happens between overlapping routes. A consumer that would -/// rather skip even that much drops it downstream on its own latency budget, which is what -/// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) means. +/// rather skip even that much drops it downstream on its own max age budget, which is what +/// [`std::time::Duration::ZERO`](std::time::Duration::ZERO) means. fn max_unbounded_start(prefs: Option, segment: Option) -> Option { match (prefs, segment) { (Some(a), Some(b)) => Some(a.max(b)), @@ -686,7 +686,7 @@ fn last_group(end: Option) -> Option { /// replacement can arrive. pub(crate) struct Group { state: kio::Consumer, - /// The logical subscription's live latency budget. + /// The logical subscription's live max age budget. subscription: kio::Consumer, /// The logical reader's group cap, used only to bound each route's drift anchor. cap: kio::Consumer>, @@ -1122,7 +1122,7 @@ struct SegmentSub { end: Option, sub: SubState, /// A completed segment's cursor, retained while parked groups may need their - /// latency budget re-evaluated after the outer cap rises. + /// max age budget re-evaluated after the outer cap rises. terminal: Option, /// The producer dropped this segment (pruned, or replaced before producing). /// The cursor drains what it already holds, then retires; see @@ -1894,7 +1894,7 @@ impl Subscriber { #[cfg(test)] mod test { use super::*; - use crate::{Latency, Timestamp, broadcast}; + use crate::{Timestamp, broadcast}; use futures::FutureExt; use std::sync::Arc; use std::time::Duration; @@ -1915,7 +1915,7 @@ mod test { /// A bounded replay window for tests whose subject requires every buffered group. fn replay() -> Subscription { - Subscription::default().with_latency(Latency::max(Duration::from_secs(30))) + Subscription::default().with_max_age(std::time::Duration::from_secs(30)) } fn write_group(producer: &mut track::Producer, sequence: u64, payload: &str) { @@ -2100,7 +2100,7 @@ mod test { async fn a_takeover_backlog_is_bounded_by_the_budget() { // Both routes retain a minute, so the budget is the only thing bounding the // backlog (a budget past the publisher's window is clamped to it). - let retain = track::Info::default().with_latency_max(Duration::from_secs(60)); + let retain = track::Info::default().with_max_age(std::time::Duration::from_secs(60)); let (mut track_a, consumer_a) = track_pair_with("a", retain.clone()); let (mut track_b, consumer_b) = track_pair_with("b", retain); @@ -2109,9 +2109,9 @@ mod test { let mut live = producer.consume().subscribe(None); let mut patient = producer .consume() - .subscribe(Subscription::default().with_latency(Latency::max(Duration::from_secs(60)))); + .subscribe(Subscription::default().with_max_age(std::time::Duration::from_secs(60))); - write_group_at(&mut track_a, 0, "a0", Duration::ZERO); + write_group_at(&mut track_a, 0, "a0", std::time::Duration::ZERO); assert_eq!(recv(&mut live), 0); assert_eq!(recv(&mut patient), 0); @@ -2121,7 +2121,7 @@ mod test { producer.takeover(&consumer_b).unwrap(); recv_pending(&mut live); for second in 1..=30 { - write_group_at(&mut track_b, second, "b", Duration::from_secs(second)); + write_group_at(&mut track_b, second, "b", std::time::Duration::from_secs(second)); } // The live subscriber takes the edge and writes the backlog off; the patient @@ -2142,7 +2142,7 @@ mod test { /// still wants read as ancient. #[tokio::test] async fn a_capped_spliced_subscriber_measures_drift_against_its_cap() { - let retain = track::Info::default().with_latency_max(Duration::from_secs(60)); + let retain = track::Info::default().with_max_age(std::time::Duration::from_secs(60)); let (mut track_a, consumer_a) = track_pair_with("a", retain); let mut producer = Producer::new(); @@ -2150,8 +2150,8 @@ mod test { let mut sub = producer.consume().subscribe(None); sub.end_at(0); - write_group_at(&mut track_a, 0, "a0", Duration::ZERO); - write_group_at(&mut track_a, 1, "a1", Duration::from_secs(30)); + write_group_at(&mut track_a, 0, "a0", std::time::Duration::ZERO); + write_group_at(&mut track_a, 1, "a1", std::time::Duration::from_secs(30)); // Group 1 is past the cap, so it is not a live edge this reader can jump to. assert_eq!(recv(&mut sub), 0); @@ -2162,7 +2162,7 @@ mod test { /// budget has already given up on. #[tokio::test] async fn a_raised_cap_rechecks_parked_groups() { - let retain = track::Info::default().with_latency_max(Duration::from_secs(60)); + let retain = track::Info::default().with_max_age(std::time::Duration::from_secs(60)); let (mut track_a, consumer_a) = track_pair_with("a", retain); let mut producer = Producer::new(); @@ -2170,13 +2170,13 @@ mod test { let mut sub = producer.consume().subscribe(None); sub.end_at(0); - write_group_at(&mut track_a, 0, "a0", Duration::ZERO); + write_group_at(&mut track_a, 0, "a0", std::time::Duration::ZERO); assert_eq!(recv(&mut sub), 0); // Group 1 parks above the cap; group 2 lands half a minute further on. - write_group_at(&mut track_a, 1, "a1", Duration::from_secs(1)); + write_group_at(&mut track_a, 1, "a1", std::time::Duration::from_secs(1)); recv_pending(&mut sub); - write_group_at(&mut track_a, 2, "a2", Duration::from_secs(30)); + write_group_at(&mut track_a, 2, "a2", std::time::Duration::from_secs(30)); // Raising the cap owes the reader group 1 again, but by now it is a backlog. sub.end_at(None); @@ -2188,7 +2188,7 @@ mod test { /// groups. A later cap increase still uses the terminal track's live edge. #[tokio::test] async fn a_raised_cap_rechecks_parked_groups_after_segment_finish() { - let retain = track::Info::default().with_latency_max(Duration::from_secs(60)); + let retain = track::Info::default().with_max_age(std::time::Duration::from_secs(60)); let (mut track_a, consumer_a) = track_pair_with("a", retain); let mut producer = Producer::new(); @@ -2196,11 +2196,11 @@ mod test { let mut sub = producer.consume().subscribe(None); sub.end_at(0); - write_group_at(&mut track_a, 0, "a0", Duration::ZERO); + write_group_at(&mut track_a, 0, "a0", std::time::Duration::ZERO); assert_eq!(recv(&mut sub), 0); - write_group_at(&mut track_a, 1, "a1", Duration::from_secs(1)); - write_group_at(&mut track_a, 2, "a2", Duration::from_secs(30)); + write_group_at(&mut track_a, 1, "a1", std::time::Duration::from_secs(1)); + write_group_at(&mut track_a, 2, "a2", std::time::Duration::from_secs(30)); track_a.finish().unwrap(); // Drive the inner cursor through its clean end while both newer groups are // parked above the cap. @@ -2616,8 +2616,8 @@ mod test { "the replacement group is still the live edge" ); - tokio::time::advance(Duration::from_secs(1)).await; - write_group_at(&mut track_b, 1, "edge", Duration::from_secs(1)); + tokio::time::advance(std::time::Duration::from_secs(1)).await; + write_group_at(&mut track_b, 1, "edge", std::time::Duration::from_secs(1)); let result = reading .read_frame() @@ -3030,7 +3030,7 @@ mod test { // A live-edge subscriber resumes at the boundary rather than at B's own live // edge, so the splice loses nothing. What that can replay is bounded by how // far the boundary trails B, which is failover latency; a consumer that wants - // none of it skips on its own latency budget downstream. + // none of it skips on its own max age budget downstream. assert_eq!(track_b.subscription().unwrap().start, Some(Position::group(2))); // The segment range still filters a group below the boundary, so a replacement @@ -3055,7 +3055,7 @@ mod test { let mut sub = producer.consume().subscribe( Subscription::default() .with_start(Position::group(0)) - .with_latency(Latency::max(Duration::from_secs(60))), + .with_max_age(std::time::Duration::from_secs(60)), ); recv_pending(&mut sub); assert_eq!(track_a.subscription().unwrap().start, Some(Position::group(0))); diff --git a/rs/moq-net/src/model/subscription.rs b/rs/moq-net/src/model/subscription.rs index 2a1a5993a4d..4670f089812 100644 --- a/rs/moq-net/src/model/subscription.rs +++ b/rs/moq-net/src/model/subscription.rs @@ -1,4 +1,4 @@ -use std::task::Poll; +use std::{task::Poll, time::Duration}; /// Subscriber-side preferences for receiving a track. /// @@ -15,17 +15,44 @@ pub struct Subscription { /// out-of-order (or not at all) over the network. Defaults to `false`; the /// aggregate is ordered only when every live subscriber asks for it. pub ordered: bool, - /// How far this subscriber may drift from the live edge before a group is skipped. - /// [`Latency::REAL_TIME`](crate::Latency::REAL_TIME) skips immediately (e.g. group 8 arriving means group 7 is - /// skipped); a larger ceiling tolerates that much reordering before giving up on the - /// older group. + /// How old a group may get before this subscriber gives up on it. /// - /// This is the `Subscriber Max Latency` on the wire. It is enforced at both ends: - /// the publisher skips a group rather than sending it, and this subscriber skips it - /// again as it reads. Clamped to the publisher's - /// [`Info::latency_max`](crate::track::Info::latency_max) retention window; stored - /// here verbatim, so what was asked for stays readable. - pub latency: crate::Latency, + /// [`Duration::ZERO`] (the default) skips immediately: group 8 arriving means group 7 + /// is abandoned. A larger budget tolerates that much reordering before giving up. + /// This never *adds* delay, since the bound is only reached once newer data is + /// already that far ahead. + /// + /// This is the `Subscriber Max Age` on the wire, and it is stored here verbatim so + /// what was asked for stays readable. Clamped to the publisher's + /// [`Info::max_age`](crate::track::Info::max_age), since waiting for a group longer + /// than it is kept around cannot produce it. + /// + /// # Where it is enforced + /// + /// At both ends, and neither alone is enough. The publisher skips a group that has + /// aged out instead of putting it on the wire, which bounds a backlog before it + /// costs bandwidth. But what reaches the publisher is the aggregate across every + /// subscriber, resolved in favor of the most tolerant one, so that gate is only ever + /// as tight as the most patient viewer. The subscriber applies the same budget again + /// as it reads, where its own is the only one in play. + /// + /// This bounds a *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 + /// + /// By both presentation time and wall-clock arrival, with either able to expire the + /// group. Presentation time compares a group's first timestamp against the newest + /// one above it, so a backlog delivered as a burst still reads as its true age. + /// Wall-clock backstops an empty or stalled group that has supplied no timestamp. + /// + /// Protocols whose wire can't carry a timestamp (pre-Lite05 moq-lite, moq-transport + /// without the Timestamp property) have their frames stamped on receipt, which makes + /// 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, /// First [`Position`] the publisher should deliver, or `None` to start at the latest /// group. /// @@ -57,7 +84,7 @@ impl Default for Subscription { Self { priority: 0, ordered: false, - latency: crate::Latency::REAL_TIME, + max_age: Duration::ZERO, start: None, end: None, } @@ -78,10 +105,9 @@ impl Subscription { self } - /// Set how far this subscriber may drift from the live edge before a group is - /// skipped, returning `self` for chaining. - pub fn with_latency(mut self, latency: crate::Latency) -> Self { - self.latency = latency; + /// 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; self } @@ -117,7 +143,7 @@ impl Subscription { priority: self.priority.max(combined.priority), // Sequence-first prioritization is enabled only when every subscriber wants it. ordered: self.ordered && combined.ordered, - latency: self.latency.merge(combined.latency), + max_age: self.max_age.max(combined.max_age), // 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 bc72c4a41b9..db082d5b944 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -13,7 +13,7 @@ //! //! The track is closed with [Error] when all writers or readers are dropped. -use crate::{Error, Latency, Result, Timescale, Timestamp, coding}; +use crate::{Error, Result, Timescale, Timestamp, coding}; use crate::{broadcast, cache, frame, group, stats}; use super::{Datagram, Requests}; @@ -29,8 +29,8 @@ use std::{ time::Duration, }; -/// Default [`Info::latency_max`] age when the publisher doesn't set one. -pub const DEFAULT_LATENCY_MAX: Duration = Duration::from_secs(5); +/// Default [`Info::max_age`] when the publisher doesn't set one. +pub const DEFAULT_MAX_AGE: Duration = Duration::from_secs(5); /// How long a datagram stays in the per-track buffer before it is dropped. /// @@ -68,15 +68,17 @@ pub struct Info { /// timestamps at this scale on the wire. Protocols whose wire can't carry it /// (pre-Lite05 moq-lite, IETF moq-transport) fall back to local monotonic milliseconds. pub timescale: Timescale, - /// The maximum age of a non-latest group before the publisher evicts it (the - /// newest group is always retained). A subscriber's - /// [`Subscription::latency`] window 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. Defaults to [`DEFAULT_LATENCY_MAX`]. + /// How old a non-latest group may get before the publisher evicts it. The newest + /// group is always retained. /// - /// This is the `Publisher Max Latency` on the wire, the publisher-side half of - /// the same budget [`Subscription::latency`] sets for a subscriber. - pub latency_max: Duration, + /// 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 + /// group can't be waited for longer than it's kept around. Reported in TRACK_INFO so + /// relays re-serve with the same window. Defaults to [`DEFAULT_MAX_AGE`]. + /// + /// This is the `Publisher Max Age` on the wire, the publisher-side half of the + /// budget [`Subscription::max_age`] sets for a subscriber. + pub max_age: Duration, /// The publisher's priority for this track, used only to break ties between /// subscriptions of equal subscriber priority. Reported in TRACK_INFO (Lite05+). pub priority: u8, @@ -90,7 +92,7 @@ impl Default for Info { fn default() -> Self { Self { timescale: Timescale::default(), - latency_max: DEFAULT_LATENCY_MAX, + max_age: DEFAULT_MAX_AGE, priority: 0, ordered: false, } @@ -107,9 +109,9 @@ impl Info { self } - /// Set the maximum age of a non-latest group before eviction, returning `self` for chaining. - pub fn with_latency_max(mut self, latency_max: Duration) -> Self { - self.latency_max = latency_max; + /// Set how old a non-latest group may get before eviction, returning `self` for chaining. + pub fn with_max_age(mut self, max_age: Duration) -> Self { + self.max_age = max_age; self } @@ -135,7 +137,7 @@ pub(crate) struct TrackState { info: Option, // The broadcast this track belongs to. Supplies the cache pool its groups charge - // into and the `cache_duration` ceiling clamping `Info::latency_max`. + // into and the `cache_duration` ceiling clamping `Info::max_age`. broadcast: Arc, // This track's account against the shared cache pool, shared with every group it @@ -525,10 +527,10 @@ impl TrackState { Some(&slot.group) } - /// The publisher's latency window, or `None` while the info is unknown (an + /// The publisher's max age window, or `None` while the info is unknown (an /// unaccepted [`Request`]). Bounds the aggregate subscription; see [`clamp_combined`]. - fn latency_bound(&self) -> Option { - self.info.as_ref().map(|info| info.latency_max) + fn max_age_bound(&self) -> Option { + self.info.as_ref().map(|info| info.max_age) } /// The live edges a subscription bounded at `cap` measures drift against: the @@ -739,7 +741,7 @@ impl TrackState { /// info to a track funnels through here, covering local publishers and relayed /// (lite / IETF) tracks alike. fn install(&mut self, mut info: Info) { - info.latency_max = info.latency_max.min(self.broadcast.origin.cache_duration); + info.max_age = info.max_age.min(self.broadcast.origin.cache_duration); self.info = Some(info); } @@ -825,10 +827,10 @@ impl TrackState { /// Admit a freshly-created group: settle eviction debt first (so the newcomer /// can never be a victim of the very write that created it), insert it, then /// expire by age. - fn commit_group(&mut self, group: &group::Producer, visible: bool, latency_max: Duration) { + fn commit_group(&mut self, group: &group::Producer, visible: bool, max_age: Duration) { self.charge_debt(); self.insert_group(group, visible); - self.evict_expired(latency_max); + self.evict_expired(max_age); } /// Accrue and pay eviction debt for everything written since the last charge: @@ -1053,14 +1055,14 @@ impl TrackState { // An evicted sequence can be re-fetched; a live one is a duplicate. self.claim_sequence(sequence, frame_start)?; - let latency_max = info.latency_max; + let max_age = info.max_age; let group = group::Producer::new(group::Info { sequence }, info, self.cache.clone()); // A backfill exists because someone is fetching it right now: stamp that // access so the eviction walk can't kill it before the fetch resolves. // It is also invisible to arrival-order subscribers: fetched on demand, // not produced live by the publisher. group.cache_refresh(); - self.commit_group(&group, false, latency_max); + self.commit_group(&group, false, max_age); Ok(group) } } @@ -1142,13 +1144,13 @@ impl Producer { return Err(Error::Closed); } let track = state.info.clone().unwrap(); - let latency_max = track.latency_max; + let max_age = track.max_age; // An evicted sequence can be re-created; a live one is a duplicate. state.claim_sequence(group.sequence, 0)?; let group = group::Producer::new(group, track, state.cache.clone()).with_meter(self.stats.meter()); - state.commit_group(&group, true, latency_max); + state.commit_group(&group, true, max_age); Ok(group) } @@ -1167,11 +1169,11 @@ impl Producer { } let track = state.info.clone().unwrap(); - let latency_max = track.latency_max; + let max_age = track.max_age; let group = group::Producer::new(group::Info { sequence }, track, state.cache.clone()).with_meter(self.stats.meter()); - state.commit_group(&group, true, latency_max); + state.commit_group(&group, true, max_age); Ok(group) } @@ -1463,12 +1465,12 @@ 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::latency`] is clamped to this track's - /// [`Info::latency_max`]: no subscriber can wait for a late group longer than the + /// The aggregate's [`Subscription::max_age`] 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 { let state = self.state.read(); - let (subs, bound) = (state.subscriptions.clone(), state.latency_bound()); + let (subs, bound) = (state.subscriptions.clone(), state.max_age_bound()); drop(state); snapshot_subscription(&subs, bound) } @@ -1486,7 +1488,7 @@ impl Producer { // Read the bound before locking `subs`, so the aggregation never nests the two locks. let state = self.state.read(); - let (subs, bound) = (state.subscriptions.clone(), state.latency_bound()); + let (subs, bound) = (state.subscriptions.clone(), state.max_age_bound()); drop(state); let prev = &self.prev_subscription; @@ -1810,17 +1812,17 @@ fn servable_cap(cursor: Option, outer: Option) -> Option { /// 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_latency(mut latency: crate::Latency, bound: Option) -> crate::Latency { +fn clamp_max_age(mut max_age: Duration, bound: Option) -> Duration { if let Some(bound) = bound { - latency.max = latency.max.min(bound); + max_age = max_age.min(bound); } - latency + max_age } -/// Clamp the aggregate's latency budget to the publisher's window; see [`clamp_latency`]. +/// Clamp the aggregate's max age budget to the publisher's window; see [`clamp_max_age`]. fn clamp_combined(combined: Option, bound: Option) -> Option { let mut combined = combined?; - combined.latency = clamp_latency(combined.latency, bound); + combined.max_age = clamp_max_age(combined.max_age, bound); Some(combined) } @@ -2332,7 +2334,7 @@ impl Subscribing { })) } SubscribingKind::Spliced(resume) => { - // Resolved from the first segment's track. The publisher's latency + // Resolved from the first segment's track. The publisher's max age // window is applied to each per-session aggregate, not here. let info = ready!(resume.poll_info(waiter))?; @@ -2651,9 +2653,9 @@ struct GroupExpiry { impl group::Expiry for GroupExpiry { fn is_expired(&self, waiter: &kio::Waiter, at: group::Position) -> bool { - let mut latency = Latency::default(); + let mut max_age = Duration::default(); let _ = self.subscription.poll(waiter, |subscription| { - latency = subscription.latency; + max_age = subscription.max_age; Poll::<()>::Pending }); @@ -2666,7 +2668,7 @@ impl group::Expiry for GroupExpiry { let mut expired = false; let _ = self.state.poll(waiter, |state| { - let budget = clamp_latency(latency, state.latency_bound()).max; + let budget = clamp_max_age(max_age, state.max_age_bound()); loop { let edge = state.live_edge(cap); expired = state.is_stale(self.sequence, Some(at), edge, budget); @@ -2823,15 +2825,15 @@ impl PlainSubscriber { /// [`Poll::Ready`]; the track ending surfaces as the error the caller was going to /// get anyway. fn poll_drift(&self, waiter: &kio::Waiter) -> Poll> { - let mut latency = Latency::default(); + let mut max_age = Duration::default(); let _ = self.subscription.poll(waiter, |subscription| { - latency = subscription.latency; + max_age = subscription.max_age; Poll::<()>::Pending }); let cap = servable_cap(self.end_sequence, self.stale_cap); self.poll(waiter, move |state| { Poll::Ready(Ok(Drift { - budget: clamp_latency(latency, state.latency_bound()).max, + budget: clamp_max_age(max_age, state.max_age_bound()), edge: state.live_edge(cap), })) }) @@ -3091,11 +3093,11 @@ impl Subscriber { /// [`Self::poll_next_group`] if you only want groups whose sequence number is higher /// than any previously returned. /// - /// Groups are semi-reliable, and the [`Subscription::latency`] budget is the other + /// Groups are semi-reliable, and the [`Subscription::max_age`] 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 - /// default is [`Latency::REAL_TIME`](crate::Latency::REAL_TIME), which takes the live + /// default is [`Duration::ZERO`], which takes the live /// edge and writes the rest off; raise it to read history. [`Self::start_at`] and /// [`Subscription::start`] are filters, not exemptions: backfill needs a budget that /// covers it. [`Consumer::fetch_group`] is the way to ask for one old group outright. @@ -3172,7 +3174,7 @@ impl Subscriber { /// produces a monotonically increasing sequence at the cost of dropping out-of-order /// groups. Use [`Self::poll_recv_group`] to see every group in arrival order instead. /// - /// The [`Subscription::latency`] budget applies here too, on the same terms; see + /// The [`Subscription::max_age`] budget applies here too, on the same terms; see /// [`Self::poll_recv_group`]. /// /// Honors the cap set by [`Self::end_at`]: groups with sequence past the cap are left @@ -3297,7 +3299,7 @@ impl Subscriber { /// Replace this subscriber's delivery preferences. /// - /// Stored verbatim; the publisher's latency window is applied to the aggregate, not + /// Stored verbatim; the publisher's max age window is applied to the aggregate, not /// here (see [`Producer::subscription`]). Returns [`Error::Closed`] if the track /// already ended; the update is meaningless at that point and can usually be ignored. pub fn update(&mut self, subscription: Subscription) -> Result<()> { @@ -3438,7 +3440,7 @@ impl Request { /// or `None` if nobody is waiting. Useful for sizing the track before accepting. pub fn subscription(&self) -> Option { let state = self.state.read(); - let (subs, bound) = (state.subscriptions.clone(), state.latency_bound()); + let (subs, bound) = (state.subscriptions.clone(), state.max_age_bound()); drop(state); snapshot_subscription(&subs, bound) } @@ -3452,7 +3454,7 @@ impl Request { /// Poll counterpart to [`subscription_changed`](Self::subscription_changed). pub fn poll_subscription_changed(&mut self, waiter: &kio::Waiter) -> Poll> { let state = self.state.read(); - let (subs, bound) = (state.subscriptions.clone(), state.latency_bound()); + let (subs, bound) = (state.subscriptions.clone(), state.max_age_bound()); drop(state); let prev = &self.prev_subscription; @@ -3530,8 +3532,8 @@ impl Subscriber { #[cfg(test)] mod test { use super::*; - use crate::Latency; use crate::model::test_tracing::count_drop_warnings; + use std::time::Duration; /// Mint a track for tests with a default parent broadcast, since tracks are /// normally born from a [`broadcast::Producer`]. @@ -3541,7 +3543,7 @@ mod test { /// A bounded replay window for tests whose subject requires every buffered group. fn replay() -> Subscription { - Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(30))) + Subscription::default().with_max_age(Duration::from_secs(30)) } /// Helper: count live cached groups in state. @@ -3864,7 +3866,7 @@ mod test { } // Advance time past the eviction threshold. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; // Append a new group to trigger eviction. producer.append_group().unwrap(); // seq 3 @@ -3884,7 +3886,7 @@ mod test { } } - /// A group whose frames outlive `latency_max` is aged out when the next group starts, but + /// A group whose frames outlive `max_age` is aged out when the next group starts, but /// a subscriber that already drained it must still see the clean end of group. Otherwise a /// track with long groups (a per-minute rollup, say) fails its readers at every boundary. #[tokio::test] @@ -3900,8 +3902,8 @@ mod test { .unwrap(); assert_eq!(consumer.next_frame().await.unwrap().unwrap().size, 5); - // The group stays open well past latency_max, then the next period starts. - tokio::time::advance(DEFAULT_LATENCY_MAX * 12).await; + // The group stays open well past the max age, then the next period starts. + tokio::time::advance(DEFAULT_MAX_AGE * 12).await; group.finish().unwrap(); let _next = producer.create_group(group::Info { sequence: 1 }).unwrap(); @@ -3916,7 +3918,7 @@ mod test { producer.append_group().unwrap(); // seq 0 // Advance time past threshold. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; // Append another group; seq 0 is expired and evicted. producer.append_group().unwrap(); // seq 1 @@ -3954,7 +3956,7 @@ mod test { let mut consumer = producer.subscribe(None); - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; producer.append_group().unwrap(); // seq 1 // Group 0 was evicted. Consumer should get group 1. @@ -3967,10 +3969,10 @@ mod test { tokio::time::pause(); // A shorter cache evicts sooner than the default. - let mut producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(1))); + let mut producer = track_producer("test", Info::default().with_max_age(Duration::from_secs(1))); producer.append_group().unwrap(); // seq 0 - // Past the custom budget but well within DEFAULT_LATENCY_MAX. + // Past the custom budget but well within DEFAULT_MAX_AGE. tokio::time::advance(Duration::from_secs(2)).await; producer.append_group().unwrap(); // seq 1 @@ -3981,27 +3983,26 @@ mod test { } #[test] - fn latency_max_clamped_to_cache() { - let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2))); + fn max_age_clamped_to_cache() { + let producer = track_producer("test", Info::default().with_max_age(Duration::from_secs(2))); - // A latency budget beyond the cache is capped in the aggregate; a group can't be + // A max age 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_latency(crate::Latency::max(Duration::from_secs(10)))); - assert_eq!(subscriber.subscription().latency.max, Duration::from_secs(10)); - assert_eq!(producer.subscription().unwrap().latency.max, Duration::from_secs(2)); + 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)); // A budget within the cache is left alone, and ZERO (skip immediately) stays ZERO. subscriber - .update(Subscription::default().with_latency(crate::Latency::max(Duration::from_millis(500)))) + .update(Subscription::default().with_max_age(Duration::from_millis(500))) .unwrap(); - assert_eq!(producer.subscription().unwrap().latency.max, Duration::from_millis(500)); + assert_eq!(producer.subscription().unwrap().max_age, Duration::from_millis(500)); subscriber - .update(Subscription::default().with_latency(Latency::REAL_TIME)) + .update(Subscription::default().with_max_age(Duration::ZERO)) .unwrap(); - assert_eq!(producer.subscription().unwrap().latency.max, Duration::ZERO); + assert_eq!(producer.subscription().unwrap().max_age, Duration::ZERO); } /// Mint a track under an origin whose retention ceiling is `cap`, so the @@ -4019,22 +4020,22 @@ mod test { } #[test] - fn origin_cache_duration_clamps_latency_max() { + fn origin_cache_duration_clamps_max_age() { // A publisher asking to keep groups for a minute is capped to the origin's 1s // ceiling; a publisher already below the ceiling is left alone (it's a min). let capped = track_producer_capped( "test", - Info::default().with_latency_max(Duration::from_secs(60)), + Info::default().with_max_age(Duration::from_secs(60)), Duration::from_secs(1), ); - assert_eq!(capped.state.read().latency_bound(), Some(Duration::from_secs(1))); + assert_eq!(capped.state.read().max_age_bound(), Some(Duration::from_secs(1))); let under = track_producer_capped( "test", - Info::default().with_latency_max(Duration::from_millis(500)), + Info::default().with_max_age(Duration::from_millis(500)), Duration::from_secs(1), ); - assert_eq!(under.state.read().latency_bound(), Some(Duration::from_millis(500))); + assert_eq!(under.state.read().max_age_bound(), Some(Duration::from_millis(500))); } #[tokio::test] @@ -4044,7 +4045,7 @@ mod test { // The publisher wants a 60s window, but the origin caps retention at 1s. let mut producer = track_producer_capped( "test", - Info::default().with_latency_max(Duration::from_secs(60)), + Info::default().with_max_age(Duration::from_secs(60)), Duration::from_secs(1), ); producer.append_group().unwrap(); // seq 0 @@ -4060,33 +4061,32 @@ mod test { } #[test] - fn latency_max_clamped_via_every_update_path() { - let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2))); - let over = Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(10))); + fn max_age_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)); // 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().latency.max, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); subscriber.control().update(over.clone()).unwrap(); - assert_eq!(producer.subscription().unwrap().latency.max, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); subscriber.update(over).unwrap(); - assert_eq!(producer.subscription().unwrap().latency.max, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); } #[test] - fn latency_max_aggregate_clamps_the_max_across_subscribers() { - let producer = track_producer("test", Info::default().with_latency_max(Duration::from_secs(2))); + fn max_age_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_latency(crate::Latency::max(Duration::from_millis(500)))); - let _b = producer.subscribe(Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(10)))); + 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))); - assert_eq!(producer.subscription().unwrap().latency.max, Duration::from_secs(2)); + assert_eq!(producer.subscription().unwrap().max_age, Duration::from_secs(2)); } /// Append a finished group presenting at `millis`, so the track carries a media @@ -4136,8 +4136,7 @@ mod test { // Two seconds of tolerance keeps the groups presenting within 2s of the live // edge (2s, 3s, 4s) and drops the two below it. - let mut subscriber = - producer.subscribe(Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(2)))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(2))); assert_eq!(drain(&mut subscriber), vec![2, 3, 4]); } @@ -4151,8 +4150,7 @@ mod test { append_at(&mut producer, second * 1000); } - let mut subscriber = - producer.subscribe(Subscription::default().with_latency(crate::Latency::max(Duration::from_millis(1500)))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(1500))); assert_eq!(drain(&mut subscriber), vec![2, 3]); } @@ -4201,8 +4199,7 @@ mod test { #[tokio::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_latency(crate::Latency::max(Duration::from_millis(500)))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_millis(500))); let mut old = producer.append_group().unwrap(); old.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"old")) .unwrap(); @@ -4314,8 +4311,7 @@ mod test { #[tokio::test] async fn a_budget_is_measured_from_the_readers_position() { let mut producer = track_producer("test", None); - let mut subscriber = - producer.subscribe(Subscription::default().with_latency(Latency::max(Duration::from_secs(1)))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(1))); let mut open = producer.append_group().unwrap(); open.write_frame(Timestamp::ZERO, bytes::Bytes::from_static(b"key")) @@ -4453,7 +4449,7 @@ mod test { assert!(!pending.is_finished(), "the real-time budget skips the old frame"); control - .update(Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(2)))) + .update(Subscription::default().with_max_age(Duration::from_secs(2))) .unwrap(); let frame = pending @@ -4465,16 +4461,15 @@ mod test { } #[test] - fn latency_max_bounds_the_budget() { + fn max_age_bounds_the_budget() { // The publisher only keeps a group around for 500ms, so a subscriber asking to // wait ten seconds for one still gives up at 500ms: the same clamp the aggregate // applies, on the subscriber's own side of it. - let mut producer = track_producer("test", Info::default().with_latency_max(Duration::from_millis(500))); + let mut producer = track_producer("test", Info::default().with_max_age(Duration::from_millis(500))); append_at(&mut producer, 0); append_at(&mut producer, 1000); - let mut subscriber = - producer.subscribe(Subscription::default().with_latency(crate::Latency::max(Duration::from_secs(10)))); + let mut subscriber = producer.subscribe(Subscription::default().with_max_age(Duration::from_secs(10))); assert_eq!(drain(&mut subscriber), vec![1]); } @@ -4494,7 +4489,7 @@ mod test { let mut patient = producer.subscribe( Subscription::default() .with_start(Position::group(0)) - .with_latency(crate::Latency::max(Duration::from_secs(10))), + .with_max_age(Duration::from_secs(10)), ); patient.start_at(0); assert_eq!(drain(&mut patient), vec![0, 1, 2, 3]); @@ -4841,7 +4836,7 @@ mod test { } // Expire all three groups. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; // Append seq 6 (becomes new max_sequence). producer.append_group().unwrap(); // seq 6 @@ -4868,7 +4863,7 @@ mod test { // Arrive: seq 5, then seq 3. producer.create_group(group::Info { sequence: 5 }).unwrap(); - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; // Seq 3 arrives late; max_sequence is still 5 (at front). producer.create_group(group::Info { sequence: 3 }).unwrap(); @@ -4882,7 +4877,7 @@ mod test { } // Expire seq 3 as well. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; // Seq 2 arrives late, triggering eviction. producer.create_group(group::Info { sequence: 2 }).unwrap(); @@ -6470,7 +6465,7 @@ mod test { producer.append_group().unwrap().finish().unwrap(); // seq 1 demotes seq 0 // Idle past the window, then the straggler receives a late frame. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; straggler .write_frame(Timestamp::ZERO, bytes::Bytes::from(vec![0u8; 100])) .unwrap(); @@ -6480,7 +6475,7 @@ mod test { assert!(consumer.peek_group(0).is_some(), "the write restarted the clock"); // Once the writes stop, the group ages out normally. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; producer.append_group().unwrap().finish().unwrap(); // seq 3 runs expiry assert!(consumer.peek_group(0).is_none(), "idle content still expires"); } @@ -6513,7 +6508,7 @@ mod test { // Age everything out, then refresh the first four backfills so they sit // fresh at the front of the eviction order, hiding the expired fifth. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; for sequence in 1..=4u64 { consumer.fetch_group(sequence, None).await.unwrap(); } @@ -6694,7 +6689,7 @@ mod test { // Keep seq 2 fresh while seq 3 (behind it in eviction order) expires. tokio::time::advance(Duration::from_secs(4)).await; consumer.fetch_group(2, None).await.unwrap(); - tokio::time::advance(DEFAULT_LATENCY_MAX - Duration::from_secs(2)).await; + tokio::time::advance(DEFAULT_MAX_AGE - Duration::from_secs(2)).await; producer.create_group(6u64.into()).unwrap().finish().unwrap(); let consumer = producer.consume(); @@ -6866,7 +6861,7 @@ mod test { let used = pool.used(); // Age past the track window; the next write reclaims the backfill. - tokio::time::advance(DEFAULT_LATENCY_MAX + Duration::from_secs(1)).await; + tokio::time::advance(DEFAULT_MAX_AGE + Duration::from_secs(1)).await; producer.create_group(6u64.into()).unwrap().finish().unwrap(); assert!(consumer.peek_group(2).is_none(), "expired backfill is reclaimed"); diff --git a/rs/moq-net/src/stats.rs b/rs/moq-net/src/stats.rs index 9403aab5144..cb2ded9fa44 100644 --- a/rs/moq-net/src/stats.rs +++ b/rs/moq-net/src/stats.rs @@ -318,8 +318,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 drifted past a subscriber's - /// [`Latency`](crate::Latency) budget. Disjoint from the top-level payload + /// Content skipped because it aged past a subscriber's + /// [`max_age`](crate::track::Subscription::max_age) 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-relay/tests/cluster_unknown.rs b/rs/moq-relay/tests/cluster_unknown.rs index e20c5ef7fe4..7f653ee08b0 100644 --- a/rs/moq-relay/tests/cluster_unknown.rs +++ b/rs/moq-relay/tests/cluster_unknown.rs @@ -59,7 +59,7 @@ async fn spawn_relay( fn client(version: Option) -> moq_tokio::Client { let mut config = moq_tokio::connect::Config::default(); config.tls.insecure = Some(true); - config.websocket.delay = Some(std::time::Duration::ZERO); + config.websocket.delay = Some(Duration::ZERO); config.bind = Some("127.0.0.1:0".parse().expect("parse bind")); config.version.extend(version); config.init(Default::default()).expect("client init") @@ -151,8 +151,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_latency(moq_net::Latency::max(Duration::from_secs(1))); + let subscription = moq_net::track::Subscription::default().with_max_age(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 3196b6a197b..93ffc8f2035 100644 --- a/rs/moq-relay/tests/goaway_cluster.rs +++ b/rs/moq-relay/tests/goaway_cluster.rs @@ -463,7 +463,7 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { bc.track("video").expect("track handle").subscribe( moq_net::track::Subscription::default() .with_ordered(true) - .with_latency(moq_net::Latency::max(Duration::from_secs(60))), + .with_max_age(Duration::from_secs(60)), ), ) .await diff --git a/rs/moq-rtc/src/client/mod.rs b/rs/moq-rtc/src/client/mod.rs index ffcdc20bfe2..d5c0ca661f6 100644 --- a/rs/moq-rtc/src/client/mod.rs +++ b/rs/moq-rtc/src/client/mod.rs @@ -22,12 +22,12 @@ pub struct Config { pub ice_candidates: Vec, /// How long relays keep a non-latest group of an ingested media track fetchable. - /// Same semantics as [`crate::server::Config::latency_max`]. + /// Same semantics as [`crate::server::Config::max_age`]. /// /// Ingest only ([`subscribe`](Client::subscribe) / WHEP): a WHIP /// [`publish`](Client::publish) reads a broadcast someone else declared, so it /// ignores this. - pub latency_max: Option, + pub max_age: Option, } /// Outbound WHIP/WHEP dialer. diff --git a/rs/moq-rtc/src/client/whep.rs b/rs/moq-rtc/src/client/whep.rs index f66ed69b63d..3e4d4dfa11d 100644 --- a/rs/moq-rtc/src/client/whep.rs +++ b/rs/moq-rtc/src/client/whep.rs @@ -18,7 +18,7 @@ use url::Url; use crate::{Error, Result, client::Client, ingest::IngestSink, session}; pub(crate) async fn dial(client: &Client, url: Url, broadcast: moq_net::broadcast::Producer) -> Result<()> { - let sink = Box::new(IngestSink::new(broadcast, client.config().latency_max)?); + let sink = Box::new(IngestSink::new(broadcast, client.config().max_age)?); let (socket, candidates) = session::bind_udp(&client.config().ice_candidates).await?; let mut rtc = Rtc::new(Instant::now()); diff --git a/rs/moq-rtc/src/ingest.rs b/rs/moq-rtc/src/ingest.rs index d67a1cec47f..2e42592ab0b 100644 --- a/rs/moq-rtc/src/ingest.rs +++ b/rs/moq-rtc/src/ingest.rs @@ -15,8 +15,8 @@ pub struct IngestSink { } impl IngestSink { - pub fn new(mut broadcast: moq_net::broadcast::Producer, latency_max: Option) -> Result { - let config = moq_mux::catalog::Config::default().with_latency_max(latency_max); + pub fn new(mut broadcast: moq_net::broadcast::Producer, max_age: Option) -> Result { + let config = moq_mux::catalog::Config::default().with_max_age(max_age); let catalog = moq_mux::catalog::Producer::with_config(&mut broadcast, config)?; Ok(Self { broadcast, @@ -97,6 +97,6 @@ mod tests { .unwrap(); let info = broadcast.consume().track("0.avc3").unwrap().info().await.unwrap(); - assert_eq!(info.latency_max, Duration::from_secs(3)); + assert_eq!(info.max_age, Duration::from_secs(3)); } } diff --git a/rs/moq-rtc/src/server/mod.rs b/rs/moq-rtc/src/server/mod.rs index ce08504aabc..fcc12d4fdac 100644 --- a/rs/moq-rtc/src/server/mod.rs +++ b/rs/moq-rtc/src/server/mod.rs @@ -157,7 +157,7 @@ pub struct Config { /// /// Ingest only (`server publish` / WHIP): WHEP egress reads a broadcast someone else /// declared, so it ignores this. - pub latency_max: Option, + pub max_age: Option, } impl Default for Config { @@ -165,7 +165,7 @@ impl Default for Config { Self { ice_candidates: Vec::new(), udp_bind: SocketAddr::from(([0, 0, 0, 0], 0)), - latency_max: None, + max_age: None, } } } diff --git a/rs/moq-rtc/src/server/whip.rs b/rs/moq-rtc/src/server/whip.rs index 7f23be69eff..420d4c98fef 100644 --- a/rs/moq-rtc/src/server/whip.rs +++ b/rs/moq-rtc/src/server/whip.rs @@ -103,7 +103,7 @@ pub async fn accept( .map_err(|err| Error::Other(anyhow::anyhow!("failed to create broadcast: {err}")))?; let handle = producer.clone(); - let sink = Box::new(IngestSink::new(producer, server.config().latency_max)?); + let sink = Box::new(IngestSink::new(producer, server.config().max_age)?); // Register a session on the shared media mux: known ICE credentials (so the // demux routes this peer's STUN by ufrag), an inbox to read datagrams from, diff --git a/rs/moq-rtmp/src/dial.rs b/rs/moq-rtmp/src/dial.rs index 19cdec3ce01..3f4d5bf5647 100644 --- a/rs/moq-rtmp/src/dial.rs +++ b/rs/moq-rtmp/src/dial.rs @@ -66,11 +66,11 @@ pub struct Client { /// Session results queued during connect, drained by the first publish/pull. work: VecDeque, /// How long [`publish`](Self::publish)'s FLV muxer waits for a stalled group - /// before skipping. Defaults to [`DEFAULT_LATENCY`](crate::DEFAULT_LATENCY). - latency: moq_mux::Latency, + /// before skipping. Defaults to [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE). + export_max_age: Duration, /// Retention declared on the media tracks [`pull`](Self::pull) publishes, or `None` /// for hang's own default. - latency_max: Option, + import_max_age: Option, } impl Client { @@ -148,17 +148,17 @@ impl Client { stream, session, work, - latency: crate::DEFAULT_LATENCY, - latency_max: None, + export_max_age: crate::DEFAULT_MAX_AGE, + import_max_age: None, }) } /// 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_LATENCY`](crate::DEFAULT_LATENCY); pass - /// [`Latency::REAL_TIME`](moq_mux::Latency::REAL_TIME) to drop stale groups aggressively. - pub fn with_latency(mut self, latency: moq_mux::Latency) -> Self { - self.latency = latency; + /// to [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE); 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; self } @@ -172,9 +172,9 @@ impl Client { /// and the memory matters. /// /// The pull (ingest) direction only; [`publish`](Self::publish) reads a broadcast - /// someone else declared, and takes [`with_latency`](Self::with_latency) instead. - pub fn with_latency_max(mut self, latency_max: impl Into>) -> Self { - self.latency_max = latency_max.into(); + /// someone else declared, and takes [`with_export_max_age`](Self::with_export_max_age) instead. + pub fn with_import_max_age(mut self, max_age: impl Into>) -> Self { + self.import_max_age = max_age.into(); self } @@ -208,7 +208,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_latency(self.latency); + .with_max_age(self.export_max_age); let mut tags = flv::TagReader::new(); let mut buffer = [0u8; READ_BUFFER]; @@ -270,7 +270,7 @@ impl Client { tracing::info!(%stream_key, %path, "rtmp play accepted by remote"); - let mut publisher = Publisher::new(origin, path.as_str(), self.latency_max)?; + let mut publisher = Publisher::new(origin, path.as_str(), self.import_max_age)?; let result = self.pull_media(&mut publisher).await; match &result { @@ -467,11 +467,11 @@ struct Publisher { } impl Publisher { - fn new(origin: &origin::Producer, path: &str, latency_max: Option) -> anyhow::Result { + fn new(origin: &origin::Producer, path: &str, max_age: Option) -> anyhow::Result { let mut broadcast = origin .create_broadcast(path, broadcast::Route::new().with_announce(true)) .map_err(|err| anyhow::anyhow!("broadcast '{path}' could not be published: {err}"))?; - let config = moq_mux::catalog::Config::default().with_latency_max(latency_max); + let config = moq_mux::catalog::Config::default().with_max_age(max_age); let catalog = moq_mux::catalog::Producer::with_config(&mut broadcast, config)?; let handle = broadcast.clone(); let mut importer = FlvImport::new(broadcast, catalog.reserve()); diff --git a/rs/moq-rtmp/src/lib.rs b/rs/moq-rtmp/src/lib.rs index 50db0d824fe..1563adc85c5 100644 --- a/rs/moq-rtmp/src/lib.rs +++ b/rs/moq-rtmp/src/lib.rs @@ -80,8 +80,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_latency`] / [`Client::with_latency`] or via [`Config::latency`]. -pub const DEFAULT_LATENCY: moq_mux::Latency = moq_mux::Latency::max(Duration::from_secs(2)); +/// [`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); 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 4c7a374511d..52f0edc394a 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_LATENCY`](crate::DEFAULT_LATENCY); set [`Latency::REAL_TIME`](moq_mux::Latency::REAL_TIME) + /// [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE); set [`Duration::ZERO`] /// to drop stale groups aggressively. Only affects egress (plays); ingest ignores it. - pub latency: moq_mux::Latency, + pub export_max_age: Duration, /// How long relays keep a non-latest group of an ingested media track fetchable, or /// `None` for hang's own default. @@ -59,7 +59,7 @@ pub struct Config { /// segmented egress (HLS/DASH) reading the broadcast downstream, which may only /// advertise segments that are still fetchable. Lower it when nothing reads history /// and the memory matters. Only affects ingest (publishes); egress ignores it. - pub latency_max: Option, + pub import_max_age: Option, /// TLS configuration for RTMPS (RTMP over TLS). When set, the /// [`listen`](Self::listen) address speaks RTMPS instead of plaintext RTMP, @@ -80,8 +80,8 @@ impl Default for Config { Self { listen: None, prefix: String::new(), - latency: crate::DEFAULT_LATENCY, - latency_max: None, + export_max_age: crate::DEFAULT_MAX_AGE, + import_max_age: None, #[cfg(feature = "tls")] tls: None, active: ActivePaths::default(), @@ -131,8 +131,8 @@ pub async fn run(origin: origin::Producer, config: Config) -> Result<()> { // listeners share the same claim table. let active = config.active.clone(); let prefix = Arc::new(config.prefix); - let latency = config.latency; - let latency_max = config.latency_max; + let export_max_age = config.export_max_age; + let import_max_age = config.import_max_age; // Players are served out of the same origin the publishers write into. let consumer = origin.consume(); @@ -159,7 +159,7 @@ pub async fn run(origin: origin::Producer, config: Config) -> Result<()> { let _ = publish.reject("path already being published").await; return; }; - if let Err(err) = publish.with_latency_max(latency_max).accept(&origin, &path).await { + if let Err(err) = publish.with_max_age(import_max_age).accept(&origin, &path).await { tracing::warn!(%peer, %path, %err, "RTMP ingest ended with error"); } }); @@ -175,7 +175,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_latency(latency).accept(&consumer, &path).await { + if let Err(err) = play.with_max_age(export_max_age).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 88b514297b3..32280961907 100644 --- a/rs/moq-rtmp/src/server.rs +++ b/rs/moq-rtmp/src/server.rs @@ -484,8 +484,8 @@ pub struct Publish { stream_key: String, peer: SocketAddr, /// Retention declared on the media tracks this publish mints, or `None` for hang's - /// own default. Override with [`with_latency_max`](Self::with_latency_max). - latency_max: Option, + /// own default. Override with [`with_max_age`](Self::with_max_age). + max_age: Option, } impl Publish { @@ -515,8 +515,8 @@ impl Publish { /// segmented egress (HLS/DASH) reading the broadcast downstream, which may only /// advertise segments that are still fetchable. Lower it when nothing reads history /// and the memory matters. - pub fn with_latency_max(mut self, latency_max: impl Into>) -> Self { - self.latency_max = latency_max.into(); + pub fn with_max_age(mut self, max_age: impl Into>) -> Self { + self.max_age = max_age.into(); self } @@ -532,7 +532,7 @@ impl Publish { // Reserve the broadcast path before telling the client the publish succeeded: // if the origin refuses `path`, reject cleanly instead of accepting and then // dropping the connection a moment later. - let mut publisher = match Publisher::new(origin, path.as_str(), self.latency_max) { + let mut publisher = match Publisher::new(origin, path.as_str(), self.max_age) { Ok(publisher) => publisher, Err(err) => { tracing::warn!(peer = %self.peer, %path, %err, "rejecting RTMP publish: broadcast unavailable"); @@ -622,9 +622,9 @@ pub struct Play { stream_key: String, peer: SocketAddr, /// How long the FLV muxer waits for a stalled group before skipping to a newer - /// one. Defaults to [`DEFAULT_LATENCY`](crate::DEFAULT_LATENCY); override with - /// [`with_latency`](Self::with_latency). - latency: moq_mux::Latency, + /// one. Defaults to [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE); override with + /// [`with_max_age`](Self::with_max_age). + latency: Duration, /// Enhanced-RTMP capabilities advertised by the player in its connect object. capabilities: ClientCapabilities, } @@ -650,11 +650,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_LATENCY`](crate::DEFAULT_LATENCY). RTMP is unpaced (tags go out as + /// [`DEFAULT_MAX_AGE`](crate::DEFAULT_MAX_AGE). RTMP is unpaced (tags go out as /// fast as the socket accepts them), so this bounds buffering, not the wire - /// rate. Pass [`Latency::REAL_TIME`](moq_mux::Latency::REAL_TIME) to drop stale groups + /// rate. Pass [`Duration::ZERO`] to drop stale groups /// aggressively. - pub fn with_latency(mut self, latency: moq_mux::Latency) -> Self { + pub fn with_max_age(mut self, latency: Duration) -> Self { self.latency = latency; self } @@ -730,7 +730,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_latency(self.latency) + .with_max_age(self.latency) .with_multitrack(self.capabilities.multitrack); // Resolve the catalog and codec headers before Play.Start, too. Otherwise a @@ -940,7 +940,7 @@ async fn accept_until_request(mut stream: S, peer: SocketAddr) -> any app: app_name, stream_key, peer, - latency_max: None, + max_age: None, }))); } // The client wants to play: hand control back to the caller. @@ -960,7 +960,7 @@ async fn accept_until_request(mut stream: S, peer: SocketAddr) -> any app: app_name, stream_key, peer, - latency: crate::DEFAULT_LATENCY, + latency: crate::DEFAULT_MAX_AGE, capabilities: client_capabilities.clone(), }))); } @@ -1249,9 +1249,9 @@ struct Publisher { impl Publisher { /// Open a broadcast at `path` and prime the importer with the FLV file /// header, so subsequent tags decode against an initialized demuxer. - fn new(origin: &origin::Producer, path: &str, latency_max: Option) -> anyhow::Result { + fn new(origin: &origin::Producer, path: &str, max_age: Option) -> anyhow::Result { let mut broadcast = origin.create_broadcast(path, broadcast::Route::new().with_announce(true))?; - let config = moq_mux::catalog::Config::default().with_latency_max(latency_max); + let config = moq_mux::catalog::Config::default().with_max_age(max_age); let catalog = moq_mux::catalog::Producer::with_config(&mut broadcast, config)?; let handle = broadcast.clone(); let mut importer = FlvImport::new(broadcast, catalog.reserve()); @@ -1592,7 +1592,7 @@ mod tests { let broadcast = origin.consume().announced_broadcast("live/cam0").await.unwrap(); let info = broadcast.track("0.flv-v").unwrap().info().await.unwrap(); - assert_eq!(info.latency_max, Duration::from_secs(3)); + assert_eq!(info.max_age, Duration::from_secs(3)); } /// End-to-end play: publish a real broadcast into an origin (via the FLV importer, so it diff --git a/rs/moq-srt/src/dial.rs b/rs/moq-srt/src/dial.rs index 9ce059ca88b..97e7a6e482d 100644 --- a/rs/moq-srt/src/dial.rs +++ b/rs/moq-srt/src/dial.rs @@ -53,7 +53,7 @@ pub struct Config { /// advertise segments that are still fetchable. Lower it when nothing reads history /// and the memory matters. [`pull`] only; [`publish`] reads a broadcast someone else /// declared. - pub latency_max: Option, + pub max_age: Option, } impl Config { @@ -64,7 +64,7 @@ impl Config { addr, resource: resource.into(), latency: DEFAULT_LATENCY, - latency_max: None, + max_age: None, } } } @@ -90,7 +90,7 @@ pub async fn publish(config: &Config, origin: &origin::Consumer, path: impl moq_ pub async fn pull(config: &Config, origin: &origin::Producer, path: impl moq_net::AsPath) -> Result<()> { let path = path.as_path(); let socket = call(config, Mode::Request).await?; - serve_publish(origin, path.as_str(), socket, config.latency_max).await + serve_publish(origin, path.as_str(), socket, config.max_age).await } /// Dial as an SRT caller, sending the standard `#!::r=,m=` stream id diff --git a/rs/moq-srt/src/listen.rs b/rs/moq-srt/src/listen.rs index 2d9978eef18..d0651b93db5 100644 --- a/rs/moq-srt/src/listen.rs +++ b/rs/moq-srt/src/listen.rs @@ -63,7 +63,7 @@ pub struct Config { /// segmented egress (HLS/DASH) reading the broadcast downstream, which may only /// advertise segments that are still fetchable. Lower it when nothing reads history /// and the memory matters. Only affects ingest (`m=publish`); egress ignores it. - pub latency_max: Option, + pub max_age: Option, } impl Default for Config { @@ -72,7 +72,7 @@ impl Default for Config { listen: None, prefix: String::new(), latency: crate::server::DEFAULT_LATENCY, - latency_max: None, + max_age: None, } } } @@ -109,7 +109,7 @@ pub async fn run(origin: origin::Producer, config: Config) -> Result<()> { // take over the path when the first publisher drops. let active = ActivePaths::default(); let prefix = Arc::new(config.prefix); - let latency_max = config.latency_max; + let max_age = config.max_age; while let Some(request) = server.accept().await { let prefix = prefix.clone(); @@ -130,7 +130,7 @@ pub async fn run(origin: origin::Producer, config: Config) -> Result<()> { let _ = publish.reject().await; return; }; - if let Err(err) = publish.with_latency_max(latency_max).accept(&origin, &path).await { + if let Err(err) = publish.with_max_age(max_age).accept(&origin, &path).await { tracing::warn!(%peer, %path, %err, "SRT ingest ended with error"); } else { tracing::info!(%peer, %path, "SRT ingest ended"); diff --git a/rs/moq-srt/src/server.rs b/rs/moq-srt/src/server.rs index bb9c163eada..8134e0ee842 100644 --- a/rs/moq-srt/src/server.rs +++ b/rs/moq-srt/src/server.rs @@ -107,7 +107,7 @@ impl Server { stream_id, peer, latency: self.latency, - latency_max: None, + max_age: None, }; // `m=request` reads a broadcast out; everything else publishes one in. @@ -135,8 +135,8 @@ struct Pending { /// The SRT receive latency, reused as the egress skip threshold on a subscribe. latency: Duration, /// Retention declared on the media tracks an ingest mints, or `None` for hang's own - /// default. Override with [`Publish::with_latency_max`]. - latency_max: Option, + /// default. Override with [`Publish::with_max_age`]. + max_age: Option, } /// What an accepted SRT connection wants: to contribute media ([`Publish`]) or to @@ -220,8 +220,8 @@ impl Publish { /// /// Unrelated to the SRT receive latency [`Server::bind`] negotiates, which is a /// transport buffer on this hop. - pub fn with_latency_max(mut self, latency_max: impl Into>) -> Self { - self.0.latency_max = latency_max.into(); + pub fn with_max_age(mut self, max_age: impl Into>) -> Self { + self.0.max_age = max_age.into(); self } @@ -236,7 +236,7 @@ impl Publish { let path = path.as_path(); let socket = self.0.request.accept(None).await?; tracing::info!(peer = %self.0.peer, %path, "SRT publish accepted"); - serve_publish(origin, path.as_str(), socket, self.0.latency_max).await + serve_publish(origin, path.as_str(), socket, self.0.max_age).await } /// Reject the publish, sending the client a `Forbidden` rejection. @@ -313,11 +313,11 @@ pub(crate) async fn serve_publish( origin: &origin::Producer, path: &str, mut socket: SrtSocket, - latency_max: Option, + max_age: Option, ) -> Result<()> { use futures::TryStreamExt; - let mut publisher = crate::ts::Publisher::new(origin, path, latency_max)?; + let mut publisher = crate::ts::Publisher::new(origin, path, max_age)?; // Run the read/feed loop so an error surfaces here instead of unwinding past // the publisher, which would drop it (and its tracks) with a bare Error::Dropped. diff --git a/rs/moq-srt/src/ts.rs b/rs/moq-srt/src/ts.rs index cff2e05397f..6a0ac477201 100644 --- a/rs/moq-srt/src/ts.rs +++ b/rs/moq-srt/src/ts.rs @@ -33,11 +33,11 @@ impl Publisher { /// Create the broadcast on `origin` at `path` and wire up the TS importer + /// catalog. /// - /// `latency_max` is the retention declared on the media tracks the importer mints: how + /// `max_age` is the retention declared on the media tracks the importer mints: how /// long relays keep a non-latest group fetchable, or `None` for hang's own default. - pub fn new(origin: &origin::Producer, path: &str, latency_max: Option) -> Result { + pub fn new(origin: &origin::Producer, path: &str, max_age: Option) -> Result { let mut broadcast = origin.create_broadcast(path, broadcast::Route::new().with_announce(true))?; - let config = moq_mux::catalog::Config::default().with_latency_max(latency_max); + let config = moq_mux::catalog::Config::default().with_max_age(max_age); let catalog = moq_mux::catalog::Producer::with_config(&mut broadcast, config)?; let handle = broadcast.clone(); let importer = ts::Import::new(broadcast, catalog.reserve()); @@ -107,9 +107,7 @@ impl Subscriber { } let source = moq_mux::Source::new(origin.consume(), path); - let export = ts::Export::new(source) - .await? - .with_latency(moq_mux::Latency::max(latency)); + let export = ts::Export::new(source).await?.with_max_age(latency); Ok(Some(Self { export })) } @@ -194,6 +192,6 @@ mod tests { let broadcast = origin.consume().announced_broadcast("live/cam0").await.unwrap(); let info = broadcast.track("0.avc3").unwrap().info().await.unwrap(); - assert_eq!(info.latency_max, Duration::from_secs(3)); + assert_eq!(info.max_age, Duration::from_secs(3)); } } diff --git a/rs/moq-tokio/tests/broadcast.rs b/rs/moq-tokio/tests/broadcast.rs index f5e02e2000d..37898f7aaf1 100644 --- a/rs/moq-tokio/tests/broadcast.rs +++ b/rs/moq-tokio/tests/broadcast.rs @@ -834,8 +834,7 @@ async fn broadcast_route_migration() { // Subscribe once, with a generous stale window so the continuation B already holds // is served rather than aged out. - let subscription = - moq_net::track::Subscription::default().with_latency(moq_net::Latency::max(Duration::from_secs(10))); + let subscription = moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10)); let mut sub = broadcast .track("video") .unwrap() @@ -1092,7 +1091,7 @@ async fn route_replaced_test(version: Option<&str>) { let mut sub = broadcast .track("video") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(moq_net::Latency::max(Duration::from_secs(10)))) + .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))) .await .expect("subscribe failed"); assert_eq!(read_payloads(&mut sub, 1).await, ["g0"]); @@ -1116,7 +1115,7 @@ async fn route_replaced_test(version: Option<&str>) { let mut sub = replacement .track("video") .unwrap() - .subscribe(moq_net::track::Subscription::default().with_latency(moq_net::Latency::max(Duration::from_secs(10)))) + .subscribe(moq_net::track::Subscription::default().with_max_age(Duration::from_secs(10))) .await .expect("subscribe to the replacement failed"); assert_eq!(read_payloads(&mut sub, 1).await, ["g0"]); @@ -1313,21 +1312,21 @@ async fn broadcast_negotiate_client_all_server_transport_19() { broadcast_test("moqt", None, Some("moq-transport-19")).await; } -// ── Retention window (track::Info::latency_max) ───────────────────── +// ── Retention window (track::Info::max_age) ───────────────────── /// The window the publisher advertises, distinct from both the model default and -/// the accepting side's [`LATENCY_DEFAULT`] so the assertions can tell them apart. -const LATENCY_PUBLISHED: Duration = Duration::from_secs(2); +/// the accepting side's [`MAX_AGE_DEFAULT`] so the assertions can tell them apart. +const MAX_AGE_PUBLISHED: Duration = Duration::from_secs(2); /// The window the subscribing origin assigns to a track whose publisher advertises /// none. Deliberately longer than the publisher's, like a relay fronting a /// segmented egress that serves a playlist window's worth of history. -const LATENCY_DEFAULT: Duration = Duration::from_secs(30); +const MAX_AGE_DEFAULT: Duration = Duration::from_secs(30); -/// Publish a track advertising [`LATENCY_PUBLISHED`], subscribe to it through an -/// origin configured with [`LATENCY_DEFAULT`], and return the window the subscriber +/// Publish a track advertising [`MAX_AGE_PUBLISHED`], subscribe to it through an +/// origin configured with [`MAX_AGE_DEFAULT`], and return the window the subscriber /// ends up with. -async fn latency_max_test(version: &str) -> Duration { +async fn max_age_test(version: &str) -> Duration { let version: moq_net::Version = version.parse().expect("invalid version"); // ── publisher (server) ────────────────────────────────────────── @@ -1335,7 +1334,7 @@ async fn latency_max_test(version: &str) -> Duration { let mut broadcast = pub_origin .create_broadcast("test", moq_net::broadcast::Route::new().with_announce(true)) .expect("create broadcast"); - let info = moq_net::track::Info::default().with_latency_max(LATENCY_PUBLISHED); + let info = moq_net::track::Info::default().with_max_age(MAX_AGE_PUBLISHED); let track = broadcast.create_track("video", info).expect("create track"); let mut server_config = moq_tokio::listen::Config::default(); @@ -1359,7 +1358,7 @@ async fn latency_max_test(version: &str) -> Duration { // The origin the session writes remote broadcasts into decides the window for // tracks whose protocol can't carry the publisher's. let sub_origin = - moq_tokio::origin::spawn(moq_net::origin::Info::new(Origin::random()).with_latency_default(LATENCY_DEFAULT)); + moq_tokio::origin::spawn(moq_net::origin::Info::new(Origin::random()).with_default_max_age(MAX_AGE_DEFAULT)); let mut announcements = sub_origin.consume().announced(); let mut client_config = moq_tokio::connect::Config::default(); @@ -1391,29 +1390,29 @@ async fn latency_max_test(version: &str) -> Duration { .subscribe(None) .await .expect("subscribe failed"); - let latency_max = sub.info().latency_max; + let max_age = sub.info().max_age; drop(sub); drop(session); handle.await.expect("server panicked").expect("server failed"); - latency_max + max_age } /// moq-lite-05 carries the publisher's window in TRACK_INFO, so it wins over the /// subscribing origin's default. #[tracing_test::traced_test] #[tokio::test] -async fn broadcast_latency_max_lite_05() { - assert_eq!(latency_max_test("moq-lite-05").await, LATENCY_PUBLISHED); +async fn broadcast_max_age_lite_05() { + assert_eq!(max_age_test("moq-lite-05").await, MAX_AGE_PUBLISHED); } /// moq-lite-01 has no TRACK stream, so the publisher's window never reaches us and /// the subscribing origin's default applies. #[tracing_test::traced_test] #[tokio::test] -async fn broadcast_latency_max_lite_01() { - assert_eq!(latency_max_test("moq-lite-01").await, LATENCY_DEFAULT); +async fn broadcast_max_age_lite_01() { + assert_eq!(max_age_test("moq-lite-01").await, MAX_AGE_DEFAULT); } /// moq-transport carries no publisher retention property at all, so an IETF-relayed @@ -1421,8 +1420,8 @@ async fn broadcast_latency_max_lite_01() { /// configured (issue #2645). #[tracing_test::traced_test] #[tokio::test] -async fn broadcast_latency_max_transport_18() { - assert_eq!(latency_max_test("moq-transport-18").await, LATENCY_DEFAULT); +async fn broadcast_max_age_transport_18() { + assert_eq!(max_age_test("moq-transport-18").await, MAX_AGE_DEFAULT); } // ── WebTransport (https://) – same version on both sides ──────────── @@ -1646,7 +1645,7 @@ async fn broadcast_websocket() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Disable WebSocket delay so client connects immediately via ws:// - client_config.websocket.delay = Some(std::time::Duration::ZERO); + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://localhost:{}", ws_addr.port()).parse().unwrap(); @@ -1758,7 +1757,7 @@ async fn broadcast_websocket_fallback() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // No delay. Race QUIC and WebSocket simultaneously. - client_config.websocket.delay = Some(std::time::Duration::ZERO); + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); @@ -1875,7 +1874,7 @@ async fn broadcast_websocket_uses_newest_version() { let sub_origin = moq_tokio::origin::spawn(Origin::random()); let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); - client_config.websocket.delay = Some(std::time::Duration::ZERO); + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://localhost:{}", ws_addr.port()).parse().unwrap(); @@ -1950,7 +1949,7 @@ async fn broadcast_race_quic_wins() { let mut client_config = moq_tokio::connect::Config::default(); client_config.tls.insecure = Some(true); // Zero head start: QUIC has to win on its own merit, not by penalising WS. - client_config.websocket.delay = Some(std::time::Duration::ZERO); + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("https://localhost:{port}").parse().unwrap(); @@ -2244,7 +2243,7 @@ async fn websocket_unauthorized_handshake_is_explicit() { }); let mut client_config = moq_tokio::connect::Config::default(); - client_config.websocket.delay = Some(std::time::Duration::ZERO); + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://{addr}").parse().unwrap(); @@ -2281,7 +2280,7 @@ async fn reconnect_stops_on_websocket_unauthorized() { }); let mut client_config = moq_tokio::connect::Config::default(); - client_config.websocket.delay = Some(std::time::Duration::ZERO); + client_config.websocket.delay = Some(Duration::ZERO); let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://{addr}").parse().unwrap(); diff --git a/rs/moq-video/src/decode/consumer.rs b/rs/moq-video/src/decode/consumer.rs index a1ff93a6da6..7eda29e3dae 100644 --- a/rs/moq-video/src/decode/consumer.rs +++ b/rs/moq-video/src/decode/consumer.rs @@ -43,7 +43,7 @@ impl Consumer { .subscribe( moq_net::track::Subscription::default() .with_priority(hang::catalog::PRIORITY.video) - .with_latency(config.latency), + .with_max_age(config.max_age), ) .await?; // The catalog says how the track is framed, and it is not always the legacy @@ -139,8 +139,8 @@ mod tests { // wide enough to read them: its REAL_TIME default keeps only the live edge, and // 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_latency(moq_mux::Latency::max(std::time::Duration::from_secs(30))); + let mut export = + moq_mux::container::fmp4::Export::new(source, catalog).with_max_age(std::time::Duration::from_secs(30)); let init = export.next().await.unwrap().expect("CMAF init"); let fragment = export.next().await.unwrap().expect("CMAF fragment"); diff --git a/rs/moq-video/src/decode/decoder.rs b/rs/moq-video/src/decode/decoder.rs index 9b38cf6af0a..8311ca74016 100644 --- a/rs/moq-video/src/decode/decoder.rs +++ b/rs/moq-video/src/decode/decoder.rs @@ -43,11 +43,11 @@ pub struct Config { /// Which backend to use. pub kind: Kind, /// How far playback may drift from the live edge before a stalled group is - /// skipped. Defaults to [`Latency::REAL_TIME`](moq_mux::Latency::REAL_TIME) - /// (skip aggressively); set [`Latency::max`](moq_mux::Latency::max) to your + /// skipped. Defaults to [`std::time::Duration::ZERO`](std::time::Duration::ZERO) + /// (skip aggressively); set [`max_age`](Self::max_age) to your /// playout buffer for a softer skip. Applied to the initial transport /// subscription and inherited by [`moq_mux::container::Consumer`]. - pub latency: moq_mux::Latency, + pub max_age: std::time::Duration, /// Ask the decoder to emit frames at this size (both dimensions even) instead /// of the stream's native one. Best effort: a hardware decoder with a /// built-in scaler (NVDEC) honors it for free, other backends ignore it. From d6535cb59a5a490c32c3c8473fbacf544fd51d2f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 20 Aug 2026 11:21:05 -0700 Subject: [PATCH 2/4] refactor(ffi)!: follow the max_age rename through the FFI and C surfaces The parent commit renamed `latency_max` to `max_age` in moq-net, but stopped at the binding boundary: `moq-ffi` and `libmoq` kept calling the same value `latency_max_ms`. That left the FFI naming a field after a budget it does not carry, and disagreeing with the crate it wraps. - `MoqTrackInfo`, `MoqSubscription`, `MoqAudioDecoderOutput`, `MoqVideoDecoderOutput`: `latency_max_ms` -> `max_age_ms` - `moq_track_info`: `latency_max_ms`/`latency_max_valid` -> `max_age_ms`/`max_age_valid` - `moq_subscription`, `moq_video_decoder_output`, `moq_audio_decoder_output`: `latency_max_ms` -> `max_age_ms` - `moq_consume_video` / `moq_consume_audio` take `max_age_ms` The Python, Swift, Kotlin, and Go bindings are generated and gitignored, so they pick the rename up on the next build. The hand-written wrappers on top of them are not, so `py/moq-rs`, `go/wrapper`, and `swift/Sources/Moq` are updated here, along with `doc/lib/c` and the smoke client. Two doc comments promised a future `latency_min_ms` to justify the `_max` suffix. A minimum here is a jitter-buffer floor, not a staleness bound, so they now name it `min_buffer_ms` and say why the two differ. This is a source-breaking change for C consumers: the struct layouts are unchanged, but the field names move. Co-Authored-By: Claude Opus 5 --- doc/lib/c/index.md | 6 +++--- go/wrapper/subscribe.go | 2 +- go/wrapper/types.go | 6 +++--- py/moq-rs/moq/subscribe.py | 6 +++--- py/moq-rs/tests/test_local.py | 14 ++++++------- rs/libmoq/README.md | 4 ++-- rs/libmoq/src/api.rs | 32 ++++++++++++++--------------- rs/libmoq/src/audio.rs | 10 ++++----- rs/libmoq/src/test.rs | 28 ++++++++++++------------- rs/libmoq/src/video.rs | 6 +++--- rs/moq-ffi/src/audio.rs | 10 +++++---- rs/moq-ffi/src/consumer.rs | 8 ++++---- rs/moq-ffi/src/producer.rs | 12 +++++------ rs/moq-ffi/src/test.rs | 10 ++++----- rs/moq-ffi/src/video.rs | 6 +++--- swift/Sources/Moq/Aliases.swift | 6 +++--- swift/Sources/Moq/AsyncStream.swift | 2 +- swift/Sources/Moq/Broadcast.swift | 4 ++-- test/smoke/clients/python/smoke.py | 4 ++-- 19 files changed, 89 insertions(+), 87 deletions(-) diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index 1d292bbee3b..54f4ba4a970 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -350,8 +350,8 @@ network. struct moq_track_info info = {0}; info.priority = 3; info.ordered = true; -info.latency_max_ms = 1000; -info.latency_max_valid = true; +info.max_age_ms = 1000; +info.max_age_valid = true; info.timescale = 1000000; info.timescale_valid = true; @@ -370,7 +370,7 @@ Fields ending in `_valid` decide whether the matching optional value is present: struct moq_subscription sub = {0}; sub.priority = 5; sub.ordered = true; -sub.latency_max_ms = 25; +sub.max_age_ms = 25; sub.group_start = 10; sub.group_start_valid = true; diff --git a/go/wrapper/subscribe.go b/go/wrapper/subscribe.go index 90d1d9b58a7..a2ff7c23160 100644 --- a/go/wrapper/subscribe.go +++ b/go/wrapper/subscribe.go @@ -82,7 +82,7 @@ func (b *BroadcastConsumer) FetchMediaGroup(name string, sequence uint64, contai // SubscribeMedia subscribes to a media track, decoded with the given container. // subscription tunes delivery priority, group ordering priority, group range, and -// the latency budget; pass nil for defaults. Raise Subscription.LatencyMaxMs to +// the max age; pass nil for defaults. Raise Subscription.MaxAgeMs to // buffer instead of skipping a stalled group. func (b *BroadcastConsumer) SubscribeMedia(name string, container Container, subscription *Subscription) (*MediaConsumer, error) { inner, err := b.inner.SubscribeMedia(name, container, subscription) diff --git a/go/wrapper/types.go b/go/wrapper/types.go index 6d584f8d2b0..4c0086b1617 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -40,16 +40,16 @@ type ( OriginOptions = ffi.MoqOriginOptions // Route is the hop chain a broadcast takes to reach an origin, its cost, and whether it's announced. Route = ffi.MoqRoute - // Subscription holds subscriber-side delivery preferences: priority, ordering, latency budget, and group range. + // Subscription holds subscriber-side delivery preferences: priority, ordering, max age, and group range. Subscription = ffi.MoqSubscription - // TrackInfo holds publisher-side track properties: priority, ordering, latency budget, and timescale. + // TrackInfo holds publisher-side track properties: priority, ordering, max age, and timescale. TrackInfo = ffi.MoqTrackInfo // Video describes one catalog rendition, including whether the publisher recommends temporarily avoiding it. Video = ffi.MoqVideo // VideoHint supplies catalog fields a video stream can't reveal itself, such as bitrate, filling only the gaps. // VideoDecodedFrame is one decoded video frame: packed I420, its dimensions, and a timestamp in microseconds. VideoDecodedFrame = ffi.MoqVideoDecodedFrame - // VideoDecoderOutput configures what DecodeVideo delivers: an optional resize plus a latency budget. + // VideoDecoderOutput configures what DecodeVideo delivers: an optional resize plus a max age. VideoDecoderOutput = ffi.MoqVideoDecoderOutput VideoHint = ffi.MoqVideoHint // AudioFormat is a single audio codec an importer can parse. diff --git a/py/moq-rs/moq/subscribe.py b/py/moq-rs/moq/subscribe.py index 2549170197d..34c014b3317 100644 --- a/py/moq-rs/moq/subscribe.py +++ b/py/moq-rs/moq/subscribe.py @@ -475,8 +475,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 ordering priority, group - range, and the latency budget; omit for defaults. Raise - :attr:`Subscription.latency_max_ms` to buffer instead of skipping a + range, and the max age; omit for defaults. Raise + :attr:`Subscription.max_age_ms` to buffer instead of skipping a stalled group. """ container = track if isinstance(track, Container) else track.container @@ -511,7 +511,7 @@ async def decode_audio( ``catalog_audio`` comes from the catalog (e.g. ``await broadcast.catalog()`` followed by ``catalog.audio[name]``). Only Opus tracks are currently supported. - Use ``output.latency_max_ms`` to + Use ``output.max_age_ms`` to control how aggressively stalled groups get skipped. That's the congestion-control knob. (Named ``_max`` to leave room for a future ``latency_min_ms`` jitter-buffer floor.) diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index c7f5f37160f..f134bbcaf1b 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -270,7 +270,7 @@ def test_publish_lifecycle(): async def test_publish_track_info_and_subscription(): """Raw track published with explicit TrackInfo, consumed with a Subscription.""" broadcast = moq.BroadcastProducer() - info = moq.TrackInfo(priority=5, latency_max_ms=2_000) + info = moq.TrackInfo(priority=5, max_age_ms=2_000) track = broadcast.publish_track("status", info) consumer = track.consume(moq.Subscription(priority=3)) @@ -623,7 +623,7 @@ async def test_raw_multiple_frames(): consumer = origin.consume() async for announcement in consumer.announced(): - raw_consumer = await announcement.broadcast.subscribe_track("commands", moq.Subscription(latency_max_ms=1_000)) + raw_consumer = await announcement.broadcast.subscribe_track("commands", moq.Subscription(max_age_ms=1_000)) messages = [ b'{"cmd": "led", "arm": "left", "led": "THUMB", "state": 1}', @@ -648,7 +648,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(latency_max_ms=1_000)) + consumer = track.consume(moq.Subscription(max_age_ms=1_000)) track.write_frame(b"hello", 0) track.write_frame(b"world", 0) @@ -704,7 +704,7 @@ async def test_raw_group_sequence(): consumer = origin.consume() async for announcement in consumer.announced(): - raw_consumer = await announcement.broadcast.subscribe_track("seq", moq.Subscription(latency_max_ms=1_000)) + raw_consumer = await announcement.broadcast.subscribe_track("seq", moq.Subscription(max_age_ms=1_000)) sent_sequences = [] for i in range(3): @@ -735,7 +735,7 @@ async def test_default_iteration_is_sequence_order(): broadcast = origin.create_broadcast("track/ordering") raw = broadcast.publish_track("ordering") - subscription = moq.Subscription(latency_max_ms=1_000) + subscription = moq.Subscription(max_age_ms=1_000) seq_consumer = raw.consume(subscription) arr_consumer = raw.consume(subscription) @@ -790,7 +790,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(latency_max_ms=1_000)) + consumer = track.consume(moq.Subscription(max_age_ms=1_000)) track.write_frame(b"ready", 0) track.write_frame(b"running", 0) @@ -834,7 +834,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(latency_max_ms=1_000)) + consumer = track.consume(moq.Subscription(max_age_ms=1_000)) group = track.append_group() group.write_frame(b"first", 0) diff --git a/rs/libmoq/README.md b/rs/libmoq/README.md index c2888c20db1..c2a1f7b6185 100644 --- a/rs/libmoq/README.md +++ b/rs/libmoq/README.md @@ -71,11 +71,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 latency_max_ms, void (*on_frame)(void *user_data, int32_t frame), void *user_data); +int32_t moq_consume_video(uint32_t catalog, uint32_t index, uint64_t max_age_ms, void (*on_frame)(void *user_data, int32_t frame), void *user_data); int32_t moq_consume_video_close(uint32_t track); // Consuming: Audio -int32_t moq_consume_audio(uint32_t catalog, uint32_t index, uint64_t latency_max_ms, void (*on_frame)(void *user_data, int32_t frame), void *user_data); +int32_t moq_consume_audio(uint32_t catalog, uint32_t index, uint64_t max_age_ms, void (*on_frame)(void *user_data, int32_t frame), void *user_data); int32_t moq_consume_audio_close(uint32_t track); // Consuming: Frames diff --git a/rs/libmoq/src/api.rs b/rs/libmoq/src/api.rs index f87429acff6..37e50f16839 100644 --- a/rs/libmoq/src/api.rs +++ b/rs/libmoq/src/api.rs @@ -431,10 +431,10 @@ pub struct moq_track_info { pub ordered: bool, /// Maximum age of a non-latest group before the publisher evicts it, in milliseconds. - /// The publisher-side half of `moq_subscription.latency_max_ms`. - pub latency_max_ms: u64, - /// Whether `latency_max_ms` should override the default. - pub latency_max_valid: bool, + /// The publisher-side half of `moq_subscription.max_age_ms`. + pub max_age_ms: u64, + /// Whether `max_age_ms` should override the default. + pub max_age_valid: bool, /// Per-frame timescale in ticks per second. pub timescale: u64, @@ -453,8 +453,8 @@ impl TryFrom<&moq_track_info> for moq_net::track::Info { .with_timescale(moq_net::Timescale::MICRO) .with_priority(info.priority) .with_ordered(info.ordered); - if info.latency_max_valid { - out = out.with_max_age(std::time::Duration::from_millis(info.latency_max_ms)); + if info.max_age_valid { + out = out.with_max_age(std::time::Duration::from_millis(info.max_age_ms)); } if info.timescale_valid { out = out.with_timescale(moq_net::Timescale::new(info.timescale)?); @@ -479,7 +479,7 @@ pub struct moq_subscription { /// Maximum age of a non-latest group before it is skipped, in milliseconds. /// Zero skips immediately. Enforced by the publisher's cache and by any local buffering. - pub latency_max_ms: u64, + pub max_age_ms: u64, /// First group to deliver. pub group_start: u64, @@ -497,7 +497,7 @@ impl From<&moq_subscription> for moq_net::track::Subscription { let mut out = moq_net::track::Subscription::default() .with_priority(subscription.priority) .with_ordered(subscription.ordered) - .with_max_age(std::time::Duration::from_millis(subscription.latency_max_ms)); + .with_max_age(std::time::Duration::from_millis(subscription.max_age_ms)); if subscription.group_start_valid { out = out.with_start(moq_net::track::Position::group(subscription.group_start)); } @@ -2266,7 +2266,7 @@ pub unsafe extern "C" fn moq_consume_catalog_section( /// Consume a video track from a broadcast, delivering frames in order. /// -/// - `latency_max_ms` controls the maximum amount of buffering allowed before skipping a GoP. +/// - `max_age_ms` 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 @@ -2281,16 +2281,16 @@ pub unsafe extern "C" fn moq_consume_catalog_section( pub unsafe extern "C" fn moq_consume_video( catalog: u32, index: u32, - latency_max_ms: u64, + max_age_ms: u64, on_frame: Option, user_data: *mut c_void, ) -> i32 { ffi::enter(move || { let catalog = ffi::parse_id(catalog)?; let index = index as usize; - let latency = std::time::Duration::from_millis(latency_max_ms); + let max_age = std::time::Duration::from_millis(max_age_ms); let on_frame = unsafe { ffi::OnStatus::new(user_data, on_frame) }; - State::lock().consume.video(catalog, index, latency, on_frame) + State::lock().consume.video(catalog, index, max_age, on_frame) }) } @@ -2315,7 +2315,7 @@ pub extern "C" fn moq_consume_video_close(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_close]. -/// The `latency_max_ms` parameter controls how long to wait before skipping frames. +/// The `max_age_ms` 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. /// @@ -2325,16 +2325,16 @@ pub extern "C" fn moq_consume_video_close(track: u32) -> i32 { pub unsafe extern "C" fn moq_consume_audio( catalog: u32, index: u32, - latency_max_ms: u64, + max_age_ms: u64, on_frame: Option, user_data: *mut c_void, ) -> i32 { ffi::enter(move || { let catalog = ffi::parse_id(catalog)?; let index = index as usize; - let latency = std::time::Duration::from_millis(latency_max_ms); + let max_age = std::time::Duration::from_millis(max_age_ms); let on_frame = unsafe { ffi::OnStatus::new(user_data, on_frame) }; - State::lock().consume.audio(catalog, index, latency, on_frame) + State::lock().consume.audio(catalog, index, max_age, on_frame) }) } diff --git a/rs/libmoq/src/audio.rs b/rs/libmoq/src/audio.rs index 59b2d7736cc..985b8bf78c7 100644 --- a/rs/libmoq/src/audio.rs +++ b/rs/libmoq/src/audio.rs @@ -101,12 +101,12 @@ pub struct moq_audio_decoder_output { pub channels: u32, /// Upper bound on buffering before skipping a stalled group, in /// milliseconds. Same congestion-control knob as - /// `moq_consume_audio`'s `latency_max_ms`. 0 = skip + /// `moq_consume_audio`'s `max_age_ms`. 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 `latency_min_ms` - /// (jitter-buffer floor). - pub latency_max_ms: u64, + /// `_max` to leave room for a future `min_buffer_ms`, a + /// jitter-buffer floor rather than a staleness bound. + pub max_age_ms: u64, } /// One audio frame: payload bytes plus a presentation timestamp. @@ -400,7 +400,7 @@ pub unsafe extern "C" fn moq_decode_audio( config.format = audio_format_from_u32(raw.format)?; config.sample_rate = zeroable(raw.sample_rate); config.channels = zeroable(raw.channels); - config.max_age = Duration::from_millis(raw.latency_max_ms); + config.max_age = Duration::from_millis(raw.max_age_ms); let on_frame = unsafe { OnStatus::new(user_data, on_frame) }; diff --git a/rs/libmoq/src/test.rs b/rs/libmoq/src/test.rs index 8c9aa0b951b..2f8e01ab0c2 100644 --- a/rs/libmoq/src/test.rs +++ b/rs/libmoq/src/test.rs @@ -1207,8 +1207,8 @@ fn publish_track_invalid_broadcast() { let info = moq_track_info { priority: 1, ordered: true, - latency_max_ms: 0, - latency_max_valid: false, + max_age_ms: 0, + max_age_valid: false, timescale: 0, timescale_valid: false, }; @@ -1222,7 +1222,7 @@ fn publish_track_invalid_broadcast() { let subscription = moq_subscription { priority: 1, ordered: true, - latency_max_ms: 0, + max_age_ms: 0, group_start: 0, group_start_valid: false, group_end: 0, @@ -1239,8 +1239,8 @@ fn publish_track_with_info_rejects_invalid_timescale() { let info = moq_track_info { priority: 0, ordered: false, - latency_max_ms: 0, - latency_max_valid: false, + max_age_ms: 0, + max_age_valid: false, timescale: 0, timescale_valid: true, }; @@ -1254,8 +1254,8 @@ fn raw_track_options_preserve_ordering_priority() { let mut info = moq_track_info { priority: 0, ordered: false, - latency_max_ms: 0, - latency_max_valid: false, + max_age_ms: 0, + max_age_valid: false, timescale: 0, timescale_valid: false, }; @@ -1267,7 +1267,7 @@ fn raw_track_options_preserve_ordering_priority() { let mut subscription = moq_subscription { priority: 0, ordered: false, - latency_max_ms: 0, + max_age_ms: 0, group_start: 0, group_start_valid: false, group_end: 0, @@ -1304,7 +1304,7 @@ fn raw_track_publish_consume() { let subscription = moq_subscription { priority: 0, ordered: false, - latency_max_ms: 1_000, + max_age_ms: 1_000, group_start: 0, group_start_valid: false, group_end: 0, @@ -1486,8 +1486,8 @@ fn raw_track_subscription_options_and_update() { let info = moq_track_info { priority: 3, ordered: false, - latency_max_ms: 1_000, - latency_max_valid: true, + max_age_ms: 1_000, + max_age_valid: true, timescale: 1_000_000, timescale_valid: true, }; @@ -1508,7 +1508,7 @@ fn raw_track_subscription_options_and_update() { let subscription = moq_subscription { priority: 5, ordered: true, - latency_max_ms: 25, + max_age_ms: 25, group_start: 1, group_start_valid: true, group_end: 1, @@ -2396,7 +2396,7 @@ fn video_raw_publish_consume() { let catalog_task = id(unsafe { moq_consume_catalog(consume, Some(channel_callback), catalog_cb.ptr) }); let catalog_id = id(catalog_cb.recv()); - let decoder = moq_video_decoder_output { latency_max_ms: 10_000 }; + let decoder = moq_video_decoder_output { max_age_ms: 10_000 }; let frame_cb = Callback::new(); let consumer = id(unsafe { moq_decode_video(catalog_id, 0, &decoder, Some(channel_callback), frame_cb.ptr) }); @@ -2759,7 +2759,7 @@ fn video_raw_decode() { let catalog_id = id(catalog_cb.recv()); // Subscribe + decode before publishing frames so the keyframe group is delivered. - let output = moq_video_decoder_output { latency_max_ms: 10_000 }; + let output = moq_video_decoder_output { max_age_ms: 10_000 }; let frame_cb = Callback::new(); let consumer = id(unsafe { moq_decode_video(catalog_id, 0, &output, Some(channel_callback), frame_cb.ptr) }); diff --git a/rs/libmoq/src/video.rs b/rs/libmoq/src/video.rs index ce21ac94a49..18c80b54bfc 100644 --- a/rs/libmoq/src/video.rs +++ b/rs/libmoq/src/video.rs @@ -132,9 +132,9 @@ pub struct moq_video_encoder_frame { pub struct moq_video_decoder_output { /// Upper bound on buffering before skipping a stalled group, in /// milliseconds. Same congestion-control knob as - /// `moq_consume_video`'s `latency_max_ms`. 0 = skip aggressively + /// `moq_consume_video`'s `max_age_ms`. 0 = skip aggressively /// (the moq-mux default); set to your playout buffer for a softer skip. - pub latency_max_ms: u64, + pub max_age_ms: u64, } /// One decoded video frame from [`moq_decode_video`]: packed I420 plus a @@ -627,7 +627,7 @@ pub unsafe extern "C" fn moq_decode_video( let raw = unsafe { output.as_ref() }.ok_or(Error::InvalidPointer)?; let mut config = moq_video::decode::Config::new(); - config.max_age = Duration::from_millis(raw.latency_max_ms); + config.max_age = Duration::from_millis(raw.max_age_ms); let on_frame = unsafe { OnStatus::new(user_data, on_frame) }; let mut state = State::lock(); diff --git a/rs/moq-ffi/src/audio.rs b/rs/moq-ffi/src/audio.rs index a5104231b73..51f81b7a8a6 100644 --- a/rs/moq-ffi/src/audio.rs +++ b/rs/moq-ffi/src/audio.rs @@ -89,12 +89,14 @@ pub struct MoqAudioDecoderOutput { pub channels: Option, /// Upper bound on buffering before skipping a stalled group, in /// milliseconds. Same congestion-control knob as - /// [`MoqSubscription::latency_max_ms`](crate::consumer::MoqSubscription::latency_max_ms): + /// [`MoqSubscription::max_age_ms`](crate::consumer::MoqSubscription::max_age_ms): /// 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 - /// `latency_min_ms` (jitter buffer). - pub latency_max_ms: Option, + /// `min_buffer_ms` (jitter-buffer floor), which is a distinct knob: this + /// one bounds how stale a group may be, that one how much to hold before + /// presenting. + pub max_age_ms: Option, } /// One audio frame: payload bytes plus a presentation timestamp. @@ -278,7 +280,7 @@ impl MoqBroadcastConsumer { config.format = output.format.into(); config.sample_rate = output.sample_rate; config.channels = output.channels; - config.max_age = output.latency_max_ms.map(Duration::from_millis).unwrap_or_default(); + config.max_age = output.max_age_ms.map(Duration::from_millis).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 a2b49ed1eb8..280a8baf8f4 100644 --- a/rs/moq-ffi/src/consumer.rs +++ b/rs/moq-ffi/src/consumer.rs @@ -61,7 +61,7 @@ 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 latency_max_ms: u64, + pub max_age_ms: u64, /// First group to deliver, or null to start at the latest group. #[uniffi(default = None)] pub group_start: Option, @@ -89,7 +89,7 @@ impl From for moq_net::track::Subscription { moq_net::track::Subscription::default() .with_priority(s.priority) .with_ordered(s.ordered) - .with_max_age(std::time::Duration::from_millis(s.latency_max_ms)) + .with_max_age(std::time::Duration::from_millis(s.max_age_ms)) .with_start(s.group_start.map(moq_net::track::Position::group)) .with_end(s.group_end.and_then(moq_net::track::Position::after_group)) } @@ -316,7 +316,7 @@ impl MoqBroadcastConsumer { /// Fetch one group and decode its track container into media frames. /// /// Unlike [`Self::subscribe_media`], this does not create a live subscription or apply - /// latency-based group skipping. The returned consumer reads exactly the requested group + /// age-based group skipping. The returned consumer reads exactly the requested group /// until [`MoqMediaGroupConsumer::next`] returns `None`. pub async fn fetch_media_group( &self, @@ -339,7 +339,7 @@ impl MoqBroadcastConsumer { /// `container` is the track container from the catalog. /// `subscription` tunes delivery priority, group ordering priority, and group range; omit for defaults. /// - /// [`MoqSubscription::latency_max_ms`] bounds the local jitter buffer as well as + /// [`MoqSubscription::max_age_ms`] 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 c398c543a92..92b90184c22 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -11,7 +11,7 @@ use crate::origin::MoqRoute; /// Publisher-side track properties, mirroring [`moq_net::track::Info`]. /// /// Construct with the fields you care about; the rest use raw-track defaults -/// (priority 0, unordered, default latency budget, microsecond timescale). +/// (priority 0, unordered, the publisher's default max age, microsecond timescale). #[derive(Clone, uniffi::Record)] pub struct MoqTrackInfo { /// Priority, used only to break ties between subscriptions of equal subscriber priority. @@ -23,9 +23,9 @@ pub struct MoqTrackInfo { pub ordered: bool, /// Maximum age of a non-latest group before the publisher evicts it, in /// milliseconds. Null uses the default. This is the publisher-side half of - /// [`MoqSubscription::latency_max_ms`](crate::consumer::MoqSubscription::latency_max_ms). + /// [`MoqSubscription::max_age_ms`](crate::consumer::MoqSubscription::max_age_ms). #[uniffi(default = None)] - pub latency_max_ms: Option, + pub max_age_ms: Option, /// Per-frame timescale in ticks per second. Null uses microseconds. #[uniffi(default = None)] pub timescale: Option, @@ -39,7 +39,7 @@ impl TryFrom for moq_net::track::Info { .with_timescale(moq_net::Timescale::MICRO) .with_priority(info.priority) .with_ordered(info.ordered); - if let Some(ms) = info.latency_max_ms { + if let Some(ms) = info.max_age_ms { out = out.with_max_age(std::time::Duration::from_millis(ms)); } if let Some(ticks) = info.timescale { @@ -61,12 +61,12 @@ impl TryFrom<&moq_net::track::Info> for MoqTrackInfo { type Error = MoqError; fn try_from(info: &moq_net::track::Info) -> Result { - let latency_max_ms = u64::try_from(info.max_age.as_millis()) + let max_age_ms = u64::try_from(info.max_age.as_millis()) .map_err(|_| MoqError::Codec("track max_age duration overflow".into()))?; Ok(Self { priority: info.priority, ordered: info.ordered, - latency_max_ms: Some(latency_max_ms), + max_age_ms: Some(max_age_ms), timescale: Some(info.timescale.as_u64()), }) } diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index e61194f3957..bc266a328a8 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -67,7 +67,7 @@ fn audio_output() -> MoqAudioDecoderOutput { format: MoqAudioSampleFormat::F32, sample_rate: None, channels: None, - latency_max_ms: None, + max_age_ms: None, } } @@ -156,7 +156,7 @@ async fn raw_track_datagram_roundtrip() { Some(MoqTrackInfo { priority: 0, ordered: true, - latency_max_ms: None, + max_age_ms: None, timescale: Some(1_000_000), }), ) @@ -187,7 +187,7 @@ async fn raw_track_info_reports_publisher_properties() { let info = MoqTrackInfo { priority: 7, ordered: false, - latency_max_ms: Some(2_500), + max_age_ms: Some(2_500), timescale: Some(90_000), }; let track = broadcast.publish_track("status".into(), Some(info)).unwrap(); @@ -196,7 +196,7 @@ async fn raw_track_info_reports_publisher_properties() { let got = consumer.info().unwrap(); assert_eq!(got.priority, 7); assert!(!got.ordered); - assert_eq!(got.latency_max_ms, Some(2_500)); + assert_eq!(got.max_age_ms, Some(2_500)); assert_eq!(got.timescale, Some(90_000)); } @@ -223,7 +223,7 @@ async fn raw_track_update_does_not_wait_for_pending_read() { consumer.update(MoqSubscription { priority: 10, ordered: false, - latency_max_ms: 25, + max_age_ms: 25, group_start: Some(0), group_end: None, }); diff --git a/rs/moq-ffi/src/video.rs b/rs/moq-ffi/src/video.rs index d2c2f661e74..a9003a33d93 100644 --- a/rs/moq-ffi/src/video.rs +++ b/rs/moq-ffi/src/video.rs @@ -339,10 +339,10 @@ pub struct MoqVideoDecoderOutput { pub resize: Option, /// Upper bound on buffering before skipping a stalled group, in /// milliseconds. Same knob as - /// [`MoqAudioDecoderOutput::latency_max_ms`](crate::audio::MoqAudioDecoderOutput::latency_max_ms). + /// [`MoqAudioDecoderOutput::max_age_ms`](crate::audio::MoqAudioDecoderOutput::max_age_ms). /// `None` keeps the moq-mux default of zero (skip aggressively). #[uniffi(default = None)] - pub latency_max_ms: Option, + pub max_age_ms: Option, } /// One decoded video frame: packed I420 plus the size it actually decoded to. @@ -467,7 +467,7 @@ impl MoqBroadcastConsumer { let mut config = moq_video::decode::Config::default(); config.resize = output.resize.map(|size| moq_video::Size::new(size.width, size.height)); config.max_age = output - .latency_max_ms + .max_age_ms .map(std::time::Duration::from_millis) .unwrap_or_default(); diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index 0a6cf99cc43..378d4f33c9c 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -41,11 +41,11 @@ 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 plus a latency budget. +/// What a `VideoConsumer` decodes to: an optional resize plus a max age. public typealias VideoDecoderOutput = MoqVideoDecoderOutput /// One decoded video frame: packed I420, its dimensions, and a timestamp. public typealias VideoDecodedFrame = MoqVideoDecodedFrame -/// The PCM layout an `AudioConsumer` decodes to, plus its latency budget. +/// The PCM layout an `AudioConsumer` decodes to, plus its max age. public typealias AudioDecoderOutput = MoqFFI.MoqAudioDecoderOutput /// A raw PCM sample format, mirroring WebCodecs `AudioData.format`. public typealias AudioSampleFormat = MoqFFI.MoqAudioSampleFormat @@ -79,7 +79,7 @@ public typealias Route = MoqFFI.MoqRoute public typealias Subscription = MoqFFI.MoqSubscription /// Options for fetching one complete group by sequence. public typealias FetchGroupOptions = MoqFFI.MoqFetchGroupOptions -/// Publisher-side track properties: priority, group ordering, latency budget, +/// Publisher-side track properties: priority, group ordering, max age, /// and timescale. public typealias TrackInfo = MoqFFI.MoqTrackInfo diff --git a/swift/Sources/Moq/AsyncStream.swift b/swift/Sources/Moq/AsyncStream.swift index c808c44ae27..6fad6803814 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 (`latencyMaxMs` GoP-skipping): draining eagerly would +/// fall-behind skipping (`maxAgeMs` 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 05f22adfbac..8e850990223 100644 --- a/swift/Sources/Moq/Broadcast.swift +++ b/swift/Sources/Moq/Broadcast.swift @@ -62,8 +62,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 latency budget; omit for defaults. Raise - /// `Subscription.latencyMaxMs` to buffer instead of skipping a stalled group. + /// priority, group range, and the max age; omit for defaults. Raise + /// `Subscription.maxAgeMs` to buffer instead of skipping a stalled group. public func subscribeMedia( name: String, container: Container, diff --git a/test/smoke/clients/python/smoke.py b/test/smoke/clients/python/smoke.py index 0cf8304f319..1c819ba2edf 100644 --- a/test/smoke/clients/python/smoke.py +++ b/test/smoke/clients/python/smoke.py @@ -16,7 +16,7 @@ import moq READ_CHUNK = 64 * 1024 -LATENCY_MAX_MS = 1_000 # subscribe_media congestion-control / lookahead window +MAX_AGE_MS = 1_000 # subscribe_media congestion-control / lookahead window async def publish(url: str, broadcast: str) -> None: @@ -62,7 +62,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(latency_max_ms=LATENCY_MAX_MS) + track_name, video.container, moq.Subscription(max_age_ms=MAX_AGE_MS) ) total = 0 From 434e41f8ff11adc985391745b8c2c5498b59e096 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 20 Aug 2026 13:16:08 -0700 Subject: [PATCH 3/4] refactor(libmoq)!: name the optional-input flags `_present`, not `_valid` `_valid` was doing two unrelated jobs in one header. On the read-back structs it is right: `moq_connection_stats` has the library set `rtt_valid` to say the backend does not report RTT, so the value is meaningless. That is a statement about the data. On the input structs it is wrong. The caller sets `max_age_valid`, and is not claiming the value is valid; it is saying "I supplied this, use it instead of your default." Validity never enters into it, and `group_start`'s own doc comment already said "whether `group_start` is present" while the field said `_valid`. So the four caller-supplied flags become `_present` and the nine library-filled stats flags keep `_valid`, which turns an overloaded suffix into a signal for which direction a field flows: - `moq_track_info`: `max_age_valid`/`timescale_valid` -> `max_age_present`/`timescale_present` - `moq_subscription`: `group_start_valid`/`group_end_valid` -> `group_start_present`/`group_end_present` `_default` was the other candidate and is a trap: a zero-initialized struct would read `max_age_default = false`, which says "not the default" when `{0}` has to mean exactly that. Fixing it needs inverted polarity, which breaks the documented guarantee that a zeroed struct gets defaults. Source-breaking for C consumers alongside the `max_age_ms` rename in the parent commit, so the two land together and callers edit once. Co-Authored-By: Claude Opus 5 --- doc/lib/c/index.md | 18 ++++++++++-------- rs/libmoq/src/api.rs | 22 +++++++++++----------- rs/libmoq/src/test.rs | 32 ++++++++++++++++---------------- 3 files changed, 37 insertions(+), 35 deletions(-) diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index 54f4ba4a970..5556df2c312 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -157,8 +157,10 @@ the right shape for configuration, and it grows under two rules: - **New fields are appended**, never inserted, so existing field offsets never move. - **Zero always means the previous behavior.** A knob whose default is not zero gets - a `has_*` / `*_valid` companion flag rather than a sentinel, so a zeroed struct - reads as "not set" and the library keeps doing what it did before. + a `*_present` companion flag rather than a sentinel, so a zeroed struct reads as + "not set" and the library keeps doing what it did before. (`*_valid` on the + read-back structs is the mirror image: there the library sets it to say whether a + metric it reports is meaningful.) Together those make an added field invisible to code that doesn't want it: you recompile against the new header and nothing changes. Always zero a struct before @@ -325,7 +327,7 @@ Raw tracks carry arbitrary byte payloads without catalog or codec parsing. Use `moq_publish_track_frame` / `moq_publish_group_frame` to provide presentation timestamps in microseconds. libmoq creates raw tracks with a microsecond timescale by default (used when -`moq_track_info.timescale_valid` is false or no info is given), matching the C +`moq_track_info.timescale_present` is false or no info is given), matching the C ABI's timestamp units. Use `moq_publish_track_group_at` to create sparse or replayed groups at an @@ -351,9 +353,9 @@ struct moq_track_info info = {0}; info.priority = 3; info.ordered = true; info.max_age_ms = 1000; -info.max_age_valid = true; +info.max_age_present = true; info.timescale = 1000000; -info.timescale_valid = true; +info.timescale_present = true; int track = moq_publish_track( broadcast, @@ -364,7 +366,7 @@ int track = moq_publish_track( `moq_consume_track` accepts optional subscriber delivery preferences. `moq_consume_track_update` changes them while the callback task is running. -Fields ending in `_valid` decide whether the matching optional value is present: +Fields ending in `_present` decide whether the matching optional value is set: ```c struct moq_subscription sub = {0}; @@ -372,7 +374,7 @@ sub.priority = 5; sub.ordered = true; sub.max_age_ms = 25; sub.group_start = 10; -sub.group_start_valid = true; +sub.group_start_present = true; int consumer = moq_consume_track( broadcast, @@ -383,7 +385,7 @@ int consumer = moq_consume_track( user_data); sub.group_end = 20; -sub.group_end_valid = true; +sub.group_end_present = true; moq_consume_track_update(consumer, &sub); ``` diff --git a/rs/libmoq/src/api.rs b/rs/libmoq/src/api.rs index 37e50f16839..53e529e7957 100644 --- a/rs/libmoq/src/api.rs +++ b/rs/libmoq/src/api.rs @@ -433,14 +433,14 @@ pub struct moq_track_info { /// Maximum age of a non-latest group before the publisher evicts it, in milliseconds. /// The publisher-side half of `moq_subscription.max_age_ms`. pub max_age_ms: u64, - /// Whether `max_age_ms` should override the default. - pub max_age_valid: bool, + /// Whether `max_age_ms` is set. When false, the publisher's default applies. + pub max_age_present: bool, /// Per-frame timescale in ticks per second. pub timescale: u64, - /// Whether `timescale` should override the default microsecond timescale, - /// which matches the `timestamp_us` units used everywhere else in this ABI. - pub timescale_valid: bool, + /// Whether `timescale` is set. When false, the default microsecond timescale + /// applies, matching the `timestamp_us` units used everywhere else in this ABI. + pub timescale_present: bool, } impl TryFrom<&moq_track_info> for moq_net::track::Info { @@ -453,10 +453,10 @@ impl TryFrom<&moq_track_info> for moq_net::track::Info { .with_timescale(moq_net::Timescale::MICRO) .with_priority(info.priority) .with_ordered(info.ordered); - if info.max_age_valid { + if info.max_age_present { out = out.with_max_age(std::time::Duration::from_millis(info.max_age_ms)); } - if info.timescale_valid { + if info.timescale_present { out = out.with_timescale(moq_net::Timescale::new(info.timescale)?); } Ok(out) @@ -484,12 +484,12 @@ pub struct moq_subscription { /// First group to deliver. pub group_start: u64, /// Whether `group_start` is present. When false, delivery starts at the latest group. - pub group_start_valid: bool, + pub group_start_present: bool, /// Last group to deliver, inclusive. pub group_end: u64, /// Whether `group_end` is present. When false, there is no end cap. - pub group_end_valid: bool, + pub group_end_present: bool, } impl From<&moq_subscription> for moq_net::track::Subscription { @@ -498,10 +498,10 @@ impl From<&moq_subscription> for moq_net::track::Subscription { .with_priority(subscription.priority) .with_ordered(subscription.ordered) .with_max_age(std::time::Duration::from_millis(subscription.max_age_ms)); - if subscription.group_start_valid { + if subscription.group_start_present { out = out.with_start(moq_net::track::Position::group(subscription.group_start)); } - if subscription.group_end_valid { + if subscription.group_end_present { out = out.with_end(moq_net::track::Position::after_group(subscription.group_end)); } out diff --git a/rs/libmoq/src/test.rs b/rs/libmoq/src/test.rs index 2f8e01ab0c2..50378ffdf91 100644 --- a/rs/libmoq/src/test.rs +++ b/rs/libmoq/src/test.rs @@ -1208,9 +1208,9 @@ fn publish_track_invalid_broadcast() { priority: 1, ordered: true, max_age_ms: 0, - max_age_valid: false, + max_age_present: false, timescale: 0, - timescale_valid: false, + timescale_present: false, }; assert!(unsafe { moq_publish_track(0, name.as_ptr() as *const c_char, name.len(), &info) } < 0); assert!(moq_publish_track_group(9999) < 0); @@ -1224,9 +1224,9 @@ fn publish_track_invalid_broadcast() { ordered: true, max_age_ms: 0, group_start: 0, - group_start_valid: false, + group_start_present: false, group_end: 0, - group_end_valid: false, + group_end_present: false, }; assert!(unsafe { moq_consume_track_update(9999, &subscription) } < 0); } @@ -1240,9 +1240,9 @@ fn publish_track_with_info_rejects_invalid_timescale() { priority: 0, ordered: false, max_age_ms: 0, - max_age_valid: false, + max_age_present: false, timescale: 0, - timescale_valid: true, + timescale_present: true, }; assert!(unsafe { moq_publish_track(broadcast, name.as_ptr() as *const c_char, name.len(), &info) } < 0); @@ -1255,9 +1255,9 @@ fn raw_track_options_preserve_ordering_priority() { priority: 0, ordered: false, max_age_ms: 0, - max_age_valid: false, + max_age_present: false, timescale: 0, - timescale_valid: false, + timescale_present: false, }; assert!(!moq_net::track::Info::try_from(&info).unwrap().ordered); @@ -1269,9 +1269,9 @@ fn raw_track_options_preserve_ordering_priority() { ordered: false, max_age_ms: 0, group_start: 0, - group_start_valid: false, + group_start_present: false, group_end: 0, - group_end_valid: false, + group_end_present: false, }; assert!(!moq_net::track::Subscription::from(&subscription).ordered); @@ -1306,9 +1306,9 @@ fn raw_track_publish_consume() { ordered: false, max_age_ms: 1_000, group_start: 0, - group_start_valid: false, + group_start_present: false, group_end: 0, - group_end_valid: false, + group_end_present: false, }; let consumer = id(unsafe { moq_consume_track( @@ -1487,9 +1487,9 @@ fn raw_track_subscription_options_and_update() { priority: 3, ordered: false, max_age_ms: 1_000, - max_age_valid: true, + max_age_present: true, timescale: 1_000_000, - timescale_valid: true, + timescale_present: true, }; let track = id(unsafe { moq_publish_track(broadcast, track_name.as_ptr() as *const c_char, track_name.len(), &info) }); @@ -1510,9 +1510,9 @@ fn raw_track_subscription_options_and_update() { ordered: true, max_age_ms: 25, group_start: 1, - group_start_valid: true, + group_start_present: true, group_end: 1, - group_end_valid: true, + group_end_present: true, }; let consumer = id(unsafe { moq_consume_track( From d50d1ccf952471d044c134e7c7cace3dcd639d83 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 20 Aug 2026 15:03:26 -0700 Subject: [PATCH 4/4] refactor(net): address review findings on the max_age rename Three fixes from the Codex review pass on #2955: - `moq-mux` no longer re-exports `Duration`. The mechanical sweep rewrote `pub use moq_net::Latency;` into `pub use std::time::Duration;`, which added `moq_mux::Duration` as a second public spelling of a std type with no abstraction behind it. Nothing referenced it, and every affected API now takes `std::time::Duration` directly. - The Python `decode_audio` docstring still justified the `_max` suffix with a future `latency_min_ms`. The Rust FFI docs were updated to `min_buffer_ms` and this one was missed, so the two published surfaces disagreed. - The moq-lite-06 changelog bullet carried two sentences of design rationale. `drafts/CLAUDE.md` asks for what changed, not why; the reasoning lives in the commit message and PR description. Co-Authored-By: Claude Opus 5 --- drafts/draft-lcurley-moq-lite.md | 2 +- py/moq-rs/moq/subscribe.py | 4 +++- rs/moq-mux/src/lib.rs | 2 -- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index f43aec0dca2..a7a2a646f81 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -1336,7 +1336,7 @@ The `Message Length` describes the payload size on the wire. - Restricted the GOAWAY New Session URI to servers, specified a duplicate GOAWAY as a protocol violation, and recommended scheme continuity and sticky redirects. - Exempted a ceiling-cost serving path from the actively-carrying cost discount: a relay whose serving path costs the saturation ceiling (primarily a session that received a GOAWAY) advertises the ceiling instead of 0, so the drain propagates downstream instead of being re-masked by each carrying hop. Keyed on the value, not the reason, which does not travel on the wire. - Added the Error Codes section, defining separate session and stream code spaces and listing the codes moq-lite uses, reused unchanged from moq-transport. Codes 64+ are the application's; 32-63 are reserved and MUST NOT be interpreted, pending a future revision. Previously the codes were unspecified, so an endpoint could neither send one a peer would understand nor safely interpret one it received. Note this renumbers every code an existing implementation sent, and that a stream reset of 0x0 is now INTERNAL_ERROR rather than a cancellation (CANCELLED is 0x1). -- Renamed `Subscriber Max Latency` to `Subscriber Max Age` and `Publisher Max Latency` to `Publisher Max Age`. Both already measured a group's age, and neither bounds end-to-end latency: a subscriber's total is the publisher's emission cadence plus this budget, so the old name promised something the field does not carry. +- Renamed `Subscriber Max Latency` to `Subscriber Max Age` and `Publisher Max Latency` to `Publisher Max Age`. ## moq-lite-05 - Renamed ANNOUNCE_INTEREST to ANNOUNCE_REQUEST and ANNOUNCE to ANNOUNCE_BROADCAST. diff --git a/py/moq-rs/moq/subscribe.py b/py/moq-rs/moq/subscribe.py index 34c014b3317..c747b2f0c7c 100644 --- a/py/moq-rs/moq/subscribe.py +++ b/py/moq-rs/moq/subscribe.py @@ -514,7 +514,9 @@ async def decode_audio( Use ``output.max_age_ms`` to control how aggressively stalled groups get skipped. That's the congestion-control knob. (Named ``_max`` to leave room for - a future ``latency_min_ms`` jitter-buffer floor.) + a future ``min_buffer_ms`` jitter-buffer floor, which is a + distinct knob: this one bounds how stale a group may be, that + one how much to hold before presenting.) """ return AudioConsumer(await self._inner.decode_audio(name, catalog_audio, output)) diff --git a/rs/moq-mux/src/lib.rs b/rs/moq-mux/src/lib.rs index 45b99e03339..9d5a21e2201 100644 --- a/rs/moq-mux/src/lib.rs +++ b/rs/moq-mux/src/lib.rs @@ -34,5 +34,3 @@ pub mod timeline; pub use clock::Clock; pub use error::*; pub use source::Source; -/// Re-export of [`std::time::Duration`], the drift budget every consumer-side knob here takes. -pub use std::time::Duration;