diff --git a/doc/concept/hang.md b/doc/concept/hang.md index 57bbb1bbcd9..0790ea6d0b9 100644 --- a/doc/concept/hang.md +++ b/doc/concept/hang.md @@ -63,6 +63,7 @@ A few things the catalog can express beyond decoder config: - **Labels.** Any rendition may carry a human-readable `label` for a track picker. The map key stays the rendition's ID, so labels need not be unique and renaming one doesn't rename the track. - **Renditions in another broadcast.** A rendition may point at a relative broadcast path, so a transcoder can publish a ladder that adds low rungs and references the source's original rendition without re-publishing its bytes. The path resolves against where the consumer found the catalog, so a reference that escapes above the root names nothing and the catalog is rejected. `@moq/watch` and `moqsrc` follow a referenced path's announcements like their own, restarting the rendition on each instance that serves it; every other reader, such as `moq play`, the exporters, and the bindings, waits for the first one announced and keeps it, and an exporter ends the rendition with it. An optional `epoch` beside the path names the [publisher instance](/concept/moq-lite#publisher-epochs) it expects: a route proving another instance ends the rendition instead of falling back to it, while a route without an epoch (an older version) cannot prove one, so there it is best effort. Omit `epoch` for a broadcast produced on demand, which has no instance until a worker answers; see [identity and recovery](/concept/identity). +- **Whole contributions.** A root `contributions` map names whole broadcasts, such as each guest feed in a composed room, by the same relative path and optional `epoch` as a rendition's reference. Listing one opens nothing, so a contribution produced on demand starts only once a viewer selects it, which `@moq/watch` does with `broadcast.contribution(effect, id)`. Its rendition IDs stay its own. - **Track names.** The map key is a rendition's ID and, by default, its track name. A rendition sets `track` only when the two must differ, such as two renditions of same-named tracks in different broadcasts, or a rendition whose media changed and so needs a new name; readers subscribe to `track` when present. An ID can't name both a video and an audio rendition. - **Jitter.** A rendition can say how much media it writes behind a frame's timestamp, in whole milliseconds rounded up: the reorder delay of B-frames and the span of a fragment or batch written together. It is measured from media timestamps alone, never the time a frame was written, so neither a constant encoder delay nor a capture clock counts. It describes the publisher, never the network, only grows over the life of a stream, and a player sizes its buffer to at least this much. A `0` is read as absent. - **Delay.** A rendition can also say how far its frames' timestamps trail those another rendition already wrote, so a video encoder running 200 ms behind audio advertises `delay: 200` on video. A rendition alone measures none. It follows the same rules as jitter. A player holds the largest `delay + jitter` among the renditions it subscribes to, and never subtracts one rendition's `delay` from another's. diff --git a/drafts/draft-lcurley-moq-hang.md b/drafts/draft-lcurley-moq-hang.md index e1ca9e40476..52a1d75e579 100644 --- a/drafts/draft-lcurley-moq-hang.md +++ b/drafts/draft-lcurley-moq-hang.md @@ -164,6 +164,10 @@ type Catalog = { "text": TextSchema | undefined, "json": JsonTracks | undefined, "binary": BinaryTracks | undefined, + "contributions": Record | undefined, // ... any custom fields ... } ~~~ @@ -176,7 +180,7 @@ For example, a chat entry should name a chat track, not carry individual chat me This way catalog updates are rare and a client MAY choose to not subscribe. The `json` and `binary` sections ({{data}}) are how a track like that is listed. -This specification defines audio, video, and text media tracks, with optional HLS records ({{hls}}) on video and audio, an optional root `clock` entry ({{clock}}) mapping content time to wall time, the root `version` ({{catalog-version}}), the application data tracks in {{data}}, and optional publisher statistics and solicited viewer feedback ({{media-stats}}). +This specification defines audio, video, and text media tracks, with optional HLS records ({{hls}}) on video and audio, an optional root `clock` entry ({{clock}}) mapping content time to wall time, the root `version` ({{catalog-version}}), the application data tracks in {{data}}, optional publisher statistics and solicited viewer feedback ({{media-stats}}), and whole broadcasts listed as `contributions` ({{contributions}}). ## Version {#catalog-version} The root `version` field is the oldest draft of this specification that reads the catalog correctly, by draft number: `4` needs a consumer of moq-hang-04 or later. @@ -192,7 +196,7 @@ This draft needs `version` 4 for: - a `track` ({{field-track}}) other than the entry's ID, which an older consumer subscribes to instead; - a video `warmup` ({{field-warmup}}) above zero, since an older consumer starts decoding a group at a picture that is not a keyframe. -Every other catalog change in this draft is safe to ignore: `enabled` ({{field-enabled}}) leaves an older consumer selecting a disabled rendition, which plays nothing; `hls` ({{hls-catalog}}) is ignored when undecodable; `stats` and `echo` ({{media-stats}}) only offer optional tracks; video `reorder` leaves an older consumer inferring decode times from timestamps; `jitter`, `delay`, audio `warmup`, and the data track estimates are hints. +Every other catalog change in this draft is safe to ignore: `enabled` ({{field-enabled}}) leaves an older consumer selecting a disabled rendition, which plays nothing; `hls` ({{hls-catalog}}) is ignored when undecodable; `stats` and `echo` ({{media-stats}}) only offer optional tracks; `contributions` ({{contributions}}) only offer broadcasts to open on selection; video `reorder` leaves an older consumer inferring decode times from timestamps; `jitter`, `delay`, audio `warmup`, and the data track estimates are hints. ## Clock {#clock} The catalog's root `clock` field is the broadcast's one continuous clock: @@ -214,6 +218,20 @@ A zero `timescale` is invalid, as is a `wall` outside the JSON-safe integer rang The mapping is fixed for the broadcast. A discontinuity marker is a delivery event, not a new epoch, and a system-clock adjustment never retimes the mapping. +## Contributions {#contributions} +The optional root `contributions` map names whole broadcasts, such as each guest feed in a composed room, whose own catalogs describe their renditions. +Each key is a contribution ID. +Each entry MUST contain a string `broadcast`, resolved against the catalog's broadcast as in {{field-broadcast}}, and MAY contain an `epoch` as in {{field-epoch}}. +A consumer MUST reject a catalog with a malformed entry or a reference that escapes above the root. + +Listing an entry MUST NOT subscribe to the contribution: a consumer opens its catalog only when it selects the contribution or one of its renditions, so a contribution produced on demand starts only for a viewer that wants it. +A selected contribution resolves like a rendition's reference, under the same rules for `epoch` and restarts ({{field-epoch}}). +A contribution produced on demand has no instance until it resolves, so a publisher omits its `epoch` until then. + +A contribution's rendition IDs belong to its own catalog and MUST NOT replace IDs in the listing catalog, so the same ID MAY name a contribution, a rendition in the listing catalog, and a rendition in the contribution. +An unavailable contribution does not invalidate the listing catalog. +A consumer does not expand a contribution's own `contributions`: each needs a selection of its own. + ## Track Identity {#identity} A track name always means the same content, so a catalog update never redefines an audio or video track. A track's identity is the fields a consumer cannot change without reinitializing its decoder or demuxer: `codec`, `description`, and `container`, plus `displayAspectWidth`, `displayAspectHeight`, and `interlaced` for video and `sampleRate` and `numberOfChannels` for audio. @@ -1125,7 +1143,7 @@ the broadcast path, not the payload. This track is distinct from an application' `hang/chat.json` snapshot extension. # Security Considerations -A rendition's `broadcast` reference ({{field-broadcast}}) resolves against the consumer's root, which is the subtree it is authorized for. +A rendition's `broadcast` reference ({{field-broadcast}}), like a contribution's ({{contributions}}), resolves against the consumer's root, which is the subtree it is authorized for. Clamping a reference that escapes above that root would silently redirect the subscription to an unrelated broadcast, so a consumer rejects the catalog instead. TODO Security @@ -1155,6 +1173,7 @@ This document has no IANA actions. - Added the optional video `preference` field: a consumer selects automatically among the highest preference it can decode. - Added the optional video `reorder` field: the most frames that can precede one in decode order and follow it in presentation, fixed for the track once declared. A consumer that authors decode times derives them from it and the current group alone, refusing deeper reordering; without it, a consumer infers them from timestamps. - Added an optional `epoch` beside every rendition and data track `broadcast` reference ({{field-epoch}}). A consumer reads each referenced path from the first broadcast it resolves for a catalog instance; a present `epoch` fails a rendition proven to resolve another instance, and is best effort over a route without an Epoch. +- Added the optional root `contributions` map ({{contributions}}): whole broadcasts named by a relative `broadcast` and an optional `epoch`, opened only on selection, whose rendition IDs stay their own. - Added optional `stats` and `echo` catalog sections, publisher/viewer snapshots keyed by rendition ID, and the `.echo` feedback broadcast convention. - An Opus frame timestamp counts the OpusHead pre-skip: a consumer presents each decoded sample the pre-skip earlier than its frame timestamp places it. diff --git a/js/hang/api/catalog.api.md b/js/hang/api/catalog.api.md index 34e78b06887..a6d7c980d78 100644 --- a/js/hang/api/catalog.api.md +++ b/js/hang/api/catalog.api.md @@ -181,6 +181,13 @@ export const ContainerSchema: ZodMiniDefault>]>>; +export type Contribution = infer; + +export const ContributionSchema: ZodMiniObject<{ + broadcast: ZodMiniType>; + epoch: ZodMiniOptional>>; +}, $strip>; + export const DEFAULT_FORMAT: Format; export class DuplicateRendition extends Error { @@ -331,6 +338,10 @@ export const RootSchema: ZodMiniObject<{ timescale: ZodMiniDefault>; wall: $ZodBranded, "u53", "out">; }, $strip>>; + contributions: ZodMiniOptional, ZodMiniObject<{ + broadcast: ZodMiniType>; + epoch: ZodMiniOptional>>; + }, $strip>>>; echo: ZodMiniOptional>; }, $strip>, ZodMiniPipe, ZodMiniTransform>]>>; diff --git a/js/hang/src/catalog/consumer.test.ts b/js/hang/src/catalog/consumer.test.ts index e889f694ee8..905ce6bc177 100644 --- a/js/hang/src/catalog/consumer.test.ts +++ b/js/hang/src/catalog/consumer.test.ts @@ -45,6 +45,12 @@ test("the shared containment check covers every section carrying a broadcast ref expect(() => checkResolvable(reference("../../x"), base)).toThrow(EscapingBroadcast); expect(checkResolvable(reference("../x"), base)).toBeDefined(); } + + // A contribution is a whole broadcast, keyed directly under its section. + const contribution = (broadcast: string) => + ({ contributions: { entry: { broadcast: Moq.Path.normalizeRelative(broadcast) } } }) as Root; + expect(() => checkResolvable(contribution("../../x"), base)).toThrow(EscapingBroadcast); + expect(checkResolvable(contribution("../x"), base)).toBeDefined(); }); test("watch yields a catalog with many renditions", async () => { diff --git a/js/hang/src/catalog/contribution.ts b/js/hang/src/catalog/contribution.ts new file mode 100644 index 00000000000..2670e494c13 --- /dev/null +++ b/js/hang/src/catalog/contribution.ts @@ -0,0 +1,20 @@ +import * as z from "@zod/mini"; +import { EpochSchema, RelativeBroadcastSchema } from "./path"; + +/** + * A whole broadcast whose own catalog describes its renditions, listed without opening it. + * + * Listing one subscribes to nothing: a consumer opens the contribution's catalog only when it + * selects one of its renditions. Its rendition IDs belong to that broadcast, never the listing + * catalog. + */ +export const ContributionSchema = z.object({ + // The contribution's broadcast, relative to the broadcast serving this catalog. + broadcast: RelativeBroadcastSchema, + // The publisher instance the reference names, with a rendition `epoch`'s meaning. A composer + // leaves it out until the contribution resolves. + epoch: z.optional(EpochSchema), +}); + +/** A whole broadcast listed for explicit, lazy selection. */ +export type Contribution = z.infer; diff --git a/js/hang/src/catalog/index.ts b/js/hang/src/catalog/index.ts index 69e18434008..eb563595357 100644 --- a/js/hang/src/catalog/index.ts +++ b/js/hang/src/catalog/index.ts @@ -1,7 +1,8 @@ /** * JSON catalog schema and types describing a broadcast's tracks: audio/video decoder configs for * WebCodecs, container format, rendition layout and HLS records, the root `clock`, - * plus the `json` and `binary` data sections and optional `stats` and `echo` discovery. + * plus the `json` and `binary` data sections, optional `stats` and `echo` discovery, and whole + * `contributions` listed without opening them. * * @module */ @@ -23,6 +24,7 @@ export { AudioConfigSchema, AudioSchema } from "./audio"; export * from "./binary"; export * from "./clock"; export * from "./container"; +export * from "./contribution"; export * from "./echo"; export * from "./format"; export * from "./hex"; diff --git a/js/hang/src/catalog/root.test.ts b/js/hang/src/catalog/root.test.ts index ccb48366eee..68a690b5d0c 100644 --- a/js/hang/src/catalog/root.test.ts +++ b/js/hang/src/catalog/root.test.ts @@ -54,6 +54,7 @@ test("rendition broadcast reference is parsed and normalized", () => { test("every reference-bearing section carries an optional epoch", () => { const EPOCH = "01890a5d-ac96-774b-bcce-b302099a8057" as ReferenceEpoch; const catalog = (epoch: string) => ({ + contributions: { c: { broadcast: "./a", epoch } }, video: { renditions: { v: { broadcast: "./a", epoch, codec: "avc1.64001f", container: { kind: "legacy" } }, @@ -84,6 +85,7 @@ test("every reference-bearing section carries an optional epoch", () => { expect(parsed.text?.renditions.t?.epoch).toBe(EPOCH); expect(parsed.json?.tracks.j?.epoch).toBe(EPOCH); expect(parsed.binary?.tracks.b?.epoch).toBe(EPOCH); + expect(parsed.contributions?.c?.epoch).toBe(EPOCH); // A malformed or noncanonical epoch refuses the catalog, as in Rust. for (const bad of ["not-a-uuid", EPOCH.toUpperCase(), "01890a5d-ac96-474b-bcce-b302099a8057"]) { @@ -91,6 +93,29 @@ test("every reference-bearing section carries an optional epoch", () => { } }); +// Mirrors Rust's `contributions_roundtrip_and_refuse_malformed_entries`. +test("a contribution parses beside a same-ID rendition and a malformed one is refused", () => { + const video = { alice: { codec: "avc1.64001f", container: { kind: "legacy" } } }; + const parsed = RootSchema.parse({ + contributions: { alice: { broadcast: "./alice.hang" } }, + video: { renditions: video }, + }); + expect(parsed.contributions?.alice).toEqual({ broadcast: "alice.hang" as RelativeBroadcast }); + // Contribution IDs are their own namespace, so one may share a rendition's ID. + expect(() => checkRenditions(parsed)).not.toThrow(); + expect(encode(parsed).version).toBeUndefined(); + + for (const contributions of [ + [], + { alice: null }, + { alice: {} }, + { alice: { broadcast: 42 } }, + { alice: { broadcast: "./alice.hang", epoch: "not-an-epoch" } }, + ]) { + expect(RootSchema.safeParse({ contributions }).success).toBe(false); + } +}); + test("rendition parent broadcast reference stays distinct from empty", () => { const catalog = { video: { diff --git a/js/hang/src/catalog/root.ts b/js/hang/src/catalog/root.ts index 263cd4526f8..91ed950d076 100644 --- a/js/hang/src/catalog/root.ts +++ b/js/hang/src/catalog/root.ts @@ -5,6 +5,7 @@ import * as z from "@zod/mini"; import { AudioSchema } from "./audio"; import { BinarySchema } from "./binary"; import { ClockSchema } from "./clock"; +import { ContributionSchema } from "./contribution"; import { EchoSchema } from "./echo"; import { TRACK } from "./format"; import { JsonSchema } from "./json"; @@ -48,8 +49,9 @@ const VersionSchema = z.number().check( * The media sections are `video`, `audio`, and `text`, alongside the broadcast's `clock` (the * one wall-clock mapping); * `json` and `binary` list application data tracks that aren't media. A section is omitted - * when it holds no tracks. `stats` names the publisher's media snapshot track, and `echo` - * solicits viewer feedback under a relative broadcast prefix. + * when it holds no tracks. `stats` names the publisher's media snapshot track, `echo` + * solicits viewer feedback under a relative broadcast prefix, and `contributions` lists whole + * broadcasts without opening them. * * This is a *loose* object: unknown root sections pass through validation untouched, so an * application can add its own sections (e.g. `scte35`) without modifying hang. A base consumer @@ -79,6 +81,8 @@ export const RootSchema = z.looseObject({ text: section(TextSchema, "renditions"), json: section(JsonSchema, "tracks"), binary: section(BinarySchema, "tracks"), + // A new key, so a malformed entry fails the catalog, the same as Rust. + contributions: z.optional(z.record(z.string(), ContributionSchema)), }); /** The root catalog object: the media sections, the clock, the data track sections, plus any app extensions. */ @@ -163,6 +167,7 @@ export function checkResolvable(root: Root, base: Moq.Path.Valid): Root { root.text?.renditions, root.json?.tracks, root.binary?.tracks, + root.contributions, ]; for (const section of sections) { for (const { broadcast } of Object.values(section ?? {})) { diff --git a/js/watch/api/index.api.md b/js/watch/api/index.api.md index 1683a82b913..4e444f96155 100644 --- a/js/watch/api/index.api.md +++ b/js/watch/api/index.api.md @@ -96,6 +96,7 @@ export namespace Audio { export class Broadcast { constructor(props?: Signals.Inputs); close(): void; + contribution(effect: Signals.Effect, id: string): Broadcast; readonly in: Signals.Readonlys; readonly out: Signals.Readonlys; } diff --git a/js/watch/src/broadcast.ts b/js/watch/src/broadcast.ts index 5f630169488..af29ac561be 100644 --- a/js/watch/src/broadcast.ts +++ b/js/watch/src/broadcast.ts @@ -4,6 +4,7 @@ import * as Msf from "@moq/msf"; import type * as Moq from "@moq/net"; import { Error as NetError, Path, StreamCode, Track } from "@moq/net"; import { + Derived, Effect, type Getter, type GetterType, @@ -180,6 +181,10 @@ export class Broadcast { // strands the filtered copy on the previous contents. readonly #raw = new Signal(undefined); + // Set only on a contribution: its broadcast resolves through the parent catalog's references, + // so the two never resolve one path independently. + readonly #resolve = new Signal<((effect: Effect) => Moq.Broadcast.Consumer | undefined) | undefined>(undefined); + #signals: Effect; constructor(props?: Inputs) { @@ -276,6 +281,20 @@ export class Broadcast { const enabled = effect.get(this.in.enabled); if (!enabled) return; + const resolve = effect.get(this.#resolve); + if (resolve) { + // Like the origin request below, a path outside the origin's scope throws. + let active: Moq.Broadcast.Consumer | undefined; + try { + active = resolve(effect); + } catch (err) { + effect.set(this.#out.error, err instanceof Error ? err : new Error(String(err)), undefined); + return; + } + effect.set(this.#out.active, active, undefined); + return; + } + const origin = effect.get(this.in.origin); if (!origin) return; @@ -491,6 +510,53 @@ export class Broadcast { return this.#requestBroadcast(effect, origin, target.path); } + /** + * Select a whole contribution, opening its catalog only while the caller owns this effect. + * + * Listing a contribution in the catalog opens nothing; this is the demand. The child tracks + * the catalog entry and resolves through this broadcast's `relativeBroadcast`, sharing + * its request: while following announcements it follows the contribution's restarts, and + * otherwise it requests the first instance once. With an `epoch` it is offline while its + * broadcast proves another instance. An absent entry leaves the child disabled, and an + * unavailable contribution reads as offline. Its rendition IDs stay local to the child, so + * they never shadow this catalog's IDs. + * + * ```ts + * effects.run((effect) => { + * const child = broadcast.contribution(effect, "alice"); + * const source = new Video.Source({ broadcast: child, supported: Video.Decoder.supported }); + * effect.cleanup(() => source.close()); + * // Feed source into a decoder as with any broadcast. + * }); + * ``` + */ + contribution(effect: Effect, id: string): Broadcast { + // Each computed notifies only on a real change, so an update that leaves the child's path + // alone (such as a new `epoch`) never restarts its catalog. + const entry = effect.computed((run) => { + const contributions = run.get(this.out.catalog)?.contributions; + return contributions && Object.hasOwn(contributions, id) ? contributions[id] : undefined; + }); + const name = effect.computed((run) => { + // An empty reference is present: it names the catalog's own broadcast. + const selected = run.get(entry); + return selected && Path.tryResolve(run.get(this.in.name), selected.broadcast); + }); + const enabled = effect.computed((run) => run.get(entry) !== undefined); + const child = new Broadcast({ + origin: this.in.origin, + name: new Derived([name], (name) => name ?? Path.empty()), + enabled: new Derived([enabled], (enabled) => enabled === true), + follow: this.in.follow, + }); + child.#resolve.set((run) => { + const selected = run.get(entry); + return selected && this.relativeBroadcast(run, selected.broadcast, selected.epoch); + }); + effect.cleanup(() => child.close()); + return child; + } + /** Stop and release everything this holds. */ close() { this.#signals.close(); diff --git a/js/watch/src/contribution.test.ts b/js/watch/src/contribution.test.ts new file mode 100644 index 00000000000..21314b0b832 --- /dev/null +++ b/js/watch/src/contribution.test.ts @@ -0,0 +1,400 @@ +import { expect, it } from "bun:test"; +import { yieldNow } from "@moq/clock"; +import * as Catalog from "@moq/hang/catalog"; +import * as Json from "@moq/json"; +import { Epoch, Origin, Path, type Track } from "@moq/net"; +import { Effect, Signal } from "@moq/signals"; +import { Broadcast } from "./broadcast"; +import { Source } from "./video/source"; + +function publish(origin: Origin.Producer, path: string, epoch?: Epoch.Valid) { + const publication = origin.createBroadcast(Path.from(path)); + publication.announce({ epoch }); + return publication.broadcast; +} + +const settle = async (): Promise => { + for (let i = 0; i < 5; i++) await yieldNow(); +}; + +async function quietly(fn: () => Promise): Promise { + const warn = console.warn; + console.warn = () => {}; + try { + return await fn(); + } finally { + console.warn = warn; + } +} + +// Resolves once nobody subscribes to the track. +async function unwanted(track: Track.Producer): Promise { + const { wanted } = track.demand(); + while (wanted.peek() !== undefined) await wanted.changed(); +} + +const video = (codec: string) => ({ codec, container: { kind: "legacy" as const } }); + +it("opens a listed contribution only on selection, keeping its rendition IDs its own", async () => { + const origin = new Origin.Producer(); + const parent = publish(origin, "room/main.hang"); + const contribution = publish(origin, "room/extra.hang"); + const contributionCatalog = contribution.createTrack(Catalog.TRACK); + const catalog = new Json.Snapshot.Producer({ track: contributionCatalog, deltas: false }); + parent.createTrack("video").writeFrame({ payload: new TextEncoder().encode("source frames") }); + const contributionVideo = contribution.createTrack("video"); + contributionVideo.writeFrame({ payload: new TextEncoder().encode("contribution frames") }); + + // The contribution and a source rendition share the ID "video". + const root = Catalog.RootSchema.parse({ + video: { renditions: { video: video("avc1.42001f") } }, + contributions: { video: { broadcast: "./extra.hang" } }, + }); + const source = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog: root, + }); + const selection = new Effect(); + try { + await settle(); + expect(source.out.catalog.peek()?.contributions).toEqual(root.contributions); + // Listing the entry does not subscribe to its catalog. + expect(contributionCatalog.demand().wanted.peek()).toBeUndefined(); + + const child = source.contribution(selection, "video"); + catalog.update({ value: { video: { renditions: { video: video("vp8") } } } }); + await settle(); + expect(contributionCatalog.demand().wanted.peek()).toBeDefined(); + expect(child.out.catalog.peek()?.video?.renditions.video?.codec).toBe("vp8"); + expect(source.out.catalog.peek()?.video?.renditions.video?.codec).toBe("avc1.42001f"); + + const media = new Source({ broadcast: child, target: { name: "video" }, supported: async () => true }); + selection.cleanup(() => media.close()); + await settle(); + expect(media.out.track.peek()).toBe("video"); + const frames = child + .relativeBroadcast(selection, media.out.config.peek()?.broadcast) + ?.track("video") + .subscribe() + .ordered(); + const original = source.relativeBroadcast(selection, undefined)?.track("video").subscribe().ordered(); + try { + expect(await frames?.readString()).toBe("contribution frames"); + expect(await original?.readString()).toBe("source frames"); + } finally { + frames?.close(); + original?.close(); + } + + // An unlisted ID leaves the child disabled. + expect(source.contribution(selection, "unknown").in.enabled.peek()).toBe(false); + + selection.close(); + await unwanted(contributionCatalog); + await unwanted(contributionVideo); + } finally { + selection.close(); + source.close(); + origin.close(); + } +}); + +it("reads an unavailable contribution as offline without touching the parent", async () => { + const origin = new Origin.Producer(); + publish(origin, "room/main.hang"); + const claim = origin.requests(Path.from("room/absent.hang")); + const requests = claim.requested(); + const source = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog: Catalog.RootSchema.parse({ + video: { renditions: { hd: video("avc1.42001f") } }, + contributions: { missing: { broadcast: "./absent.hang" } }, + }), + follow: false, + }); + const selection = new Effect(); + try { + await settle(); + const missing = source.contribution(selection, "missing"); + const { value: request } = await requests.next(); + expect(request?.path).toBe(Path.from("room/absent.hang")); + request?.reject(new Error("contribution unavailable")); + await settle(); + // Like a rendition's reference, an unavailable contribution is offline, not an error. + expect(missing.out.active.peek()).toBeUndefined(); + expect(missing.out.error.peek()).toBeUndefined(); + expect(missing.out.status.peek()).toBe("offline"); + expect(source.out.status.peek()).toBe("live"); + expect(Object.keys(source.out.catalog.peek()?.video?.renditions ?? {})).toEqual(["hd"]); + } finally { + selection.close(); + source.close(); + claim.close(); + origin.close(); + } +}); + +it("reports a contribution outside the origin's scope as an error, leaving the parent live", async () => { + const origin = new Origin.Producer(); + const scoped = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/*")])); + publish(scoped, "room/main.hang"); + const parent = new Broadcast({ + origin: scoped, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog: Catalog.RootSchema.parse({ contributions: { outside: { broadcast: "../other/extra.hang" } } }), + follow: false, + }); + const owner = new Effect(); + try { + const child = parent.contribution(owner, "outside"); + await settle(); + expect(child.out.active.peek()).toBeUndefined(); + expect(child.out.error.peek()?.message).toContain("outside the origin scope"); + expect(parent.out.status.peek()).toBe("live"); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); + +it("tracks the contribution entry without reopening it on unrelated catalog updates", async () => { + const origin = new Origin.Producer(); + publish(origin, "room/main.hang"); + const firstCatalog = publish(origin, "room/first.hang").createTrack(Catalog.TRACK); + publish(origin, "room/second.hang"); + const catalog = new Signal(Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./first.hang" } } })); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog, + follow: false, + }); + const owner = new Effect(); + try { + const child = parent.contribution(owner, "extra"); + await settle(); + const active = child.out.active.peek(); + expect(active?.path).toBe(Path.from("room/first.hang")); + + // An update that leaves the entry alone keeps the same request. + expect(firstCatalog.demand().wanted.peek()).toBeDefined(); + let withdrawals = 0; + owner.cleanup( + firstCatalog.demand().wanted.subscribe((wanted) => { + if (wanted === undefined) withdrawals += 1; + }), + ); + catalog.set( + Catalog.RootSchema.parse({ + contributions: { extra: { broadcast: "./first.hang" }, other: { broadcast: "./other.hang" } }, + metadata: "changed", + }), + ); + await settle(); + expect(child.out.active.peek()).toBe(active); + expect(withdrawals).toBe(0); + + // A changed path is a different reference, so the child follows it. + catalog.set(Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./second.hang" } } })); + await settle(); + expect(child.out.active.peek()?.path).toBe(Path.from("room/second.hang")); + + // Removing the entry disables the child. + catalog.set(Catalog.RootSchema.parse({})); + await settle(); + expect(child.in.enabled.peek()).toBe(false); + expect(child.out.active.peek()).toBeUndefined(); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); + +it("follows a restarted contributor only for an entry that names no epoch", async () => { + const origin = new Origin.Producer(); + publish(origin, "room/main.hang"); + const [oldEpoch, newEpoch] = [Epoch.mint(), Epoch.mint()]; + const old = publish(origin, "room/extra.hang", oldEpoch); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog: Catalog.RootSchema.parse({ + contributions: { + following: { broadcast: "./extra.hang" }, + pinned: { broadcast: "./extra.hang", epoch: oldEpoch }, + }, + }), + }); + const owner = new Effect(); + try { + const following = parent.contribution(owner, "following"); + const pinned = parent.contribution(owner, "pinned"); + await settle(); + expect(following.out.active.peek()?.epoch).toBe(oldEpoch); + expect(pinned.out.active.peek()?.epoch).toBe(oldEpoch); + + // The announcement is the online signal: the plain entry follows the restart, while the + // one naming the old instance goes offline rather than reading the new one. + const replacement = publish(origin, "room/extra.hang", newEpoch); + await quietly(settle); + expect(following.out.active.peek()?.epoch).toBe(newEpoch); + expect(pinned.out.active.peek()).toBeUndefined(); + expect(pinned.out.status.peek()).toBe("offline"); + replacement.close(); + } finally { + owner.close(); + parent.close(); + old.close(); + origin.close(); + } +}); + +it("pins the first instance of a contribution when not following announcements", async () => { + const origin = new Origin.Producer(); + publish(origin, "room/main.hang"); + const first = publish(origin, "room/extra.hang", Epoch.mint()); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog: Catalog.RootSchema.parse({ contributions: { extra: { broadcast: "./extra.hang" } } }), + follow: false, + }); + const owner = new Effect(); + try { + const child = parent.contribution(owner, "extra"); + await settle(); + const pinned = child.out.active.peek(); + expect(pinned?.path).toBe(Path.from("room/extra.hang")); + + // A restart ends the pinned instance without moving the child to the new one. + const second = publish(origin, "room/extra.hang", Epoch.mint()); + await settle(); + expect(child.out.active.peek()).toBeUndefined(); + expect(child.out.error.peek()).toBeUndefined(); + second.close(); + } finally { + owner.close(); + parent.close(); + first.close(); + origin.close(); + } +}); + +it("never reads a contribution proven to be another epoch, but reads an epochless route", async () => { + const origin = new Origin.Producer(); + publish(origin, "room/main.hang"); + const served = Epoch.mint(); + const proven = publish(origin, "room/proven.hang", served); + const track = proven.createTrack(Catalog.TRACK); + publish(origin, "room/plain.hang"); + const named = Epoch.mint(); + const contributions = (epoch: Epoch.Valid) => + Catalog.RootSchema.parse({ + contributions: { + proven: { broadcast: "./proven.hang", epoch }, + plain: { broadcast: "./plain.hang", epoch: named }, + }, + }); + const catalog = new Signal(contributions(named)); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog, + follow: false, + }); + const owner = new Effect(); + try { + const refused = parent.contribution(owner, "proven"); + const accepted = parent.contribution(owner, "plain"); + await quietly(settle); + expect(refused.out.active.peek()).toBeUndefined(); + expect(refused.out.error.peek()).toBeUndefined(); + expect(track.closed.peek()).toBeUndefined(); + expect(track.demand().wanted.peek()).toBeUndefined(); + // An epochless route cannot prove its instance, so the epoch cannot refuse it. + expect(accepted.out.active.peek()?.path).toBe(Path.from("room/plain.hang")); + + // A catalog update naming the served epoch admits the instance the request already holds. + catalog.set(contributions(served)); + await settle(); + expect(refused.out.active.peek()?.epoch).toBe(served); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); + +it("shares the parent's resolution, so a new epoch checks the held handle", async () => { + const origin = new Origin.Producer(); + const [served, other] = [Epoch.mint(), Epoch.mint()]; + publish(origin, "room/main.hang", served); + const extraCatalog = publish(origin, "room/extra.hang", served).createTrack(Catalog.TRACK); + const entries = (epoch?: Epoch.Valid) => + Catalog.RootSchema.parse({ + contributions: { + sibling: { broadcast: "./extra.hang", epoch }, + self: { broadcast: "./main.hang", epoch }, + empty: { broadcast: "", epoch }, + }, + }); + const catalog = new Signal(entries()); + const parent = new Broadcast({ + origin, + name: Path.from("room/main.hang"), + catalogFormat: "manual", + catalog, + follow: false, + }); + const owner = new Effect(); + try { + const sibling = parent.contribution(owner, "sibling"); + const self = parent.contribution(owner, "self"); + await settle(); + const held = sibling.out.active.peek(); + expect(held?.epoch).toBe(served); + // A self-reference is the parent's own handle, not a request of its own. An empty one is + // too, and is named like the parent, so its own references resolve against the same base. + expect(self.out.active.peek()).toBe(parent.out.active.peek()); + const empty = parent.contribution(owner, "empty"); + await settle(); + expect(empty.in.name.peek()).toBe(Path.from("room/main.hang")); + expect(empty.in.enabled.peek()).toBe(true); + + expect(extraCatalog.demand().wanted.peek()).toBeDefined(); + let withdrawals = 0; + owner.cleanup( + extraCatalog.demand().wanted.subscribe((wanted) => { + if (wanted === undefined) withdrawals += 1; + }), + ); + + // Naming the held instance keeps the same handle rather than resolving the path again. + catalog.set(entries(served)); + await settle(); + expect(sibling.out.active.peek()).toBe(held); + expect(self.out.active.peek()).toBe(parent.out.active.peek()); + expect(withdrawals).toBe(0); + + // Naming another instance fails the held one. + catalog.set(entries(other)); + await quietly(settle); + expect(sibling.out.active.peek()).toBeUndefined(); + expect(self.out.active.peek()).toBeUndefined(); + } finally { + owner.close(); + parent.close(); + origin.close(); + } +}); diff --git a/quest/m2/README.md b/quest/m2/README.md index b29a01bf978..c077e4a13a1 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -129,7 +129,6 @@ lite-07; bitrate enforcement is not part of this release. - [moq-rtc pacing](/quest/m2/rtc-pacing.md) - a capped WHEP viewer never receives more than its cap plus burst, NACK resends included - [SRT rate handle](/quest/m2/srt-rate-handle.md) - a per-connection cap paces SRT pulls, retransmits included, and closes SRT publishers past it - [One port on the io_uring workers](/quest/m2/uring-demux.md) - `moq-uring`'s workers host the UDP demux, so a ring relay keeps WebRTC media and SRT on its QUIC port -- [Hang contribution references](/quest/m2/contribution-ref.md) - a catalog names a whole contribution broadcast that a player opens only when selected, backing moq.pro's composed rooms - [Synced data playback](/quest/m2/watch-data-sync.md) - js/watch releases JSON and binary payloads on the media playhead, and a slow data track holds media back - [Watch decode gate](/quest/m2/watch-decode-gate.md) - video lookahead stays encoded until it is near presentation, like audio - [One support probe for watch audio and video](/quest/m2/watch-support-probe.md) - one probe helper with video's cache, and audio reports unsupported renditions diff --git a/quest/m2/contribution-ref.md b/quest/m2/contribution-ref.md deleted file mode 100644 index 1a5b4b26785..00000000000 --- a/quest/m2/contribution-ref.md +++ /dev/null @@ -1,51 +0,0 @@ -# [M] Hang contribution references - -## Goal - -A Hang root catalog can name a whole contribution broadcast, relative to its -own path, without opening it: each guest feed in a composed room, for -example. Rust and JavaScript catalogs carry the entry, and `@moq/watch` -resolves one only when a consumer selects one of its renditions. This backs -moq.pro's overlay contribution reference, -whose composer never reads a contribution's catalog because subscribing is -the demand that starts the encoder. - -## Plan - -Decided 2026-10-20 (maintainer): an upstream quest backs this work, because -#5722 and #5298 closed unmerged for lack of one. Only the catalog-level -reference: the processor media contract that once carried it (#4946) stays -deleted. - -Salvage `refs/pull/5722/head` ("feat(hang): add whole contribution -references") and its decision notes rather than starting over: - -- A root `contributions` map, `{ [id]: { broadcast, epoch? } }`. `broadcast` - is a relative reference with the usual escape check, like the - per-rendition `broadcast` reference in `rs/hang/src/catalog/video/mod.rs` - and its audio, text, JSON, and binary counterparts. -- Listing an entry subscribes to nothing. `@moq/watch` opens one only - through `Broadcast.contribution(effect, id)`, a child broadcast scoped to - the caller's effect, resolved through the parent's `relativeBroadcast`. - The child's rendition IDs stay its own, so a contribution's rendition - never shadows a source rendition with the same ID. -- `epoch` follows the reference epochs that landed in - [#5699](https://github.com/moq-dev/moq/pull/5699): the same validation, known-mismatch refusal, and epochless best effort. A - lazy contribution has no anticipated epoch, so a composer leaves it out - until the contribution resolves. A reader that follows announcements - follows the contribution's Start, End, and Restart; one that follows none - pins the first resolution for its parent catalog instance. Reuse - `moq_mux::Source`'s pinning and `Source::follow`; do not add a second - one. -- #5722 was stacked on #5699's reference `epoch`, which has landed; rebuild - it on `main`. - -Per cross-package sync, land `rs/hang`, `js/hang`, `js/watch`, and -`drafts/draft-lcurley-moq-hang.md` in one PR. Cover lazy resolution (listing -the entry opens nothing), a missing contribution, a malformed entry refused, -a relative path that escapes, an ID collision with a source rendition, and a -contributor restart. - -Public API: a catalog `contributions` section in `hang` and `@moq/hang`, and -`Broadcast.contribution` in `@moq/watch`. Wire: a new optional catalog -field. diff --git a/quest/m3/studio/README.md b/quest/m3/studio/README.md index 79c0f793cd0..c17041a5fb9 100644 --- a/quest/m3/studio/README.md +++ b/quest/m3/studio/README.md @@ -97,6 +97,5 @@ surface and zero-copy texture import, land before the cut. ## Related - [OBS native codecs](/quest/m2/obs-moq-video/README.md) - the OBS plugin stays the path for creators who stay on OBS -- [Hang contribution references](/quest/m2/contribution-ref.md) - composed rooms naming each guest feed - [Linux capture](/quest/m2/capture-linux.md) - Wayland window, system audio, and app capture the studio's sources inherit - [Windows capture](/quest/m2/capture-windows.md) - app capture and system audio the studio's sources inherit diff --git a/quest/m3/studio/compose/README.md b/quest/m3/studio/compose/README.md index f3a87bb5a4f..a07b24b58ec 100644 --- a/quest/m3/studio/compose/README.md +++ b/quest/m3/studio/compose/README.md @@ -29,8 +29,8 @@ Decided 2026-10-26 (maintainer), the studio's flagship and first in its epic: into its source's own track before publishing rather than living in the layout. - **Wire layout:** local sources are tracks in the studio's one broadcast. - Guests stay their own broadcasts, named through - [contribution references](/quest/m2/contribution-ref.md). + Guests stay their own broadcasts, named through the hang catalog's + `contributions` references. - **Layout:** the live scene state (items, transforms, transitions, and each element's priority and toggleable flag) as a hang JSON track on the media clock, so any host composites the same frame the studio shows. @@ -47,4 +47,3 @@ Decided 2026-10-26 (maintainer), the studio's flagship and first in its epic: - [Browser composition](/quest/m3/studio/compose/browser.md) - `@moq/watch` composes a broadcast with a layout track through moq-scene's browser build - [Server composition](/quest/m3/studio/compose/server.md) - `moq compose` renders the program from sources and layout, headless - [Viewer controls](/quest/m3/studio/compose/controls.md) - viewers toggle elements and the layout's priorities steer what they fetch -- [Hang contribution references](/quest/m2/contribution-ref.md) - guests composed by reference diff --git a/quest/m3/studio/guests.md b/quest/m3/studio/guests.md index 32c91b8832e..eb5495a0e35 100644 --- a/quest/m3/studio/guests.md +++ b/quest/m3/studio/guests.md @@ -25,7 +25,3 @@ remove a participant from the scene. - **Relay required:** guests join through a relay. Peer-to-peer WHIP ingress inside the studio was considered and dropped, because it brings NAT traversal and TURN for no capability the relay lacks. - -## Related - -- [Hang contribution references](/quest/m2/contribution-ref.md) - a composed broadcast naming each guest feed diff --git a/rs/hang/src/catalog/consumer.rs b/rs/hang/src/catalog/consumer.rs index db3e7c85d0d..67c9c722cc5 100644 --- a/rs/hang/src/catalog/consumer.rs +++ b/rs/hang/src/catalog/consumer.rs @@ -29,7 +29,7 @@ impl Consumer { /// Poll for the next catalog update. /// /// Fails with [`Error::EscapingBroadcast`](crate::Error::EscapingBroadcast) if any rendition's - /// `broadcast` reference or echo prefix walks above the root. Such a reference names no broadcast, and the + /// `broadcast` reference, contribution, or echo prefix walks above the root. Such a reference names no broadcast, and the /// root is the consumer's authorized subtree, so it is an attempt to reference content the /// consumer cannot name. The whole catalog is rejected rather than the one rendition: a /// publisher that emits one has a bug (or is hostile), and silently serving the rest hides @@ -60,7 +60,7 @@ impl Consumer { } } -/// Reject the catalog if a track reference or echo prefix walks above the root. +/// Reject the catalog if a track reference, contribution, or echo prefix walks above the root. /// /// Every section carrying a relative broadcast path must be included here; a section left out /// silently exempts its paths from the containment check. @@ -78,6 +78,7 @@ fn check_resolvable(base: &Path, catalog: &Catalog) -> Result<()> { .chain(json.map(|(_, config)| config.broadcast.as_ref())) .chain(binary.map(|(_, config)| config.broadcast.as_ref())) .flatten() + .chain(catalog.contributions.values().map(|entry| &entry.broadcast)) { if !rel.is_empty() && base.try_resolve(rel).is_none() { return Err(crate::Error::EscapingBroadcast(rel.to_string())); @@ -112,6 +113,20 @@ mod test { )); } + #[test] + fn contributions_cannot_escape_the_root() { + let base = moq_net::Path::from_static("room/main.hang"); + for (reference, accepted) in [("./alice.hang", true), ("../alice.hang", true), ("../../escape", false)] { + let json = serde_json::json!({ "contributions": { "alice": { "broadcast": reference } } }).to_string(); + let catalog = Catalog::<()>::from_str(&json).unwrap(); + match check_resolvable(&base, &catalog) { + Ok(()) => assert!(accepted, "{reference} must be refused"), + Err(crate::Error::EscapingBroadcast(_)) => assert!(!accepted, "{reference} must be accepted"), + Err(err) => panic!("unexpected error: {err}"), + } + } + } + #[tokio::test] async fn subscribe_validates_echo_prefix_before_yielding() { for (reference, accepted) in [("viewers", true), ("../../viewers", false)] { diff --git a/rs/hang/src/catalog/contribution.rs b/rs/hang/src/catalog/contribution.rs new file mode 100644 index 00000000000..ca362ed1dc0 --- /dev/null +++ b/rs/hang/src/catalog/contribution.rs @@ -0,0 +1,37 @@ +use serde::{Deserialize, Serialize}; + +/// A whole broadcast whose own catalog describes its renditions, listed without opening it. +/// +/// Listing one subscribes to nothing: a consumer opens the contribution's catalog only when it +/// selects one of its renditions. Its rendition IDs belong to that broadcast, never the listing +/// catalog. +/// +/// Marked `#[non_exhaustive]` so optional fields can be added later. External callers build one +/// with [`Contribution::new`]. +#[serde_with::serde_as] +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Contribution { + /// The contribution's broadcast, relative to the broadcast serving this catalog. + /// + /// Resolve it with [`Path::try_resolve`](moq_net::Path::try_resolve): a reference that walks + /// above the root names no broadcast, so the catalog is rejected. + pub broadcast: moq_net::path::Relative, + + /// The publisher instance the reference names, with a rendition `epoch`'s meaning: a route + /// proving another instance refuses it, and on an epochless route it is best effort. A + /// composer leaves it out until the contribution resolves. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde_as(as = "Option")] + pub epoch: Option, +} + +impl Contribution { + /// A contribution at `broadcast`, accepting whichever instance resolves. + pub fn new(broadcast: impl Into) -> Self { + Self { + broadcast: broadcast.into(), + epoch: None, + } + } +} diff --git a/rs/hang/src/catalog/mod.rs b/rs/hang/src/catalog/mod.rs index 8ab1e1570aa..0ee961229fe 100644 --- a/rs/hang/src/catalog/mod.rs +++ b/rs/hang/src/catalog/mod.rs @@ -10,6 +10,7 @@ mod binary; mod clock; mod consumer; mod container; +mod contribution; mod echo; mod hex; mod hls; @@ -29,6 +30,7 @@ pub use binary::*; pub use clock::*; pub use consumer::*; pub use container::*; +pub use contribution::*; pub use echo::*; pub use hls::*; pub use json::*; diff --git a/rs/hang/src/catalog/root.rs b/rs/hang/src/catalog/root.rs index cb0264ef81d..690bafc5c7b 100644 --- a/rs/hang/src/catalog/root.rs +++ b/rs/hang/src/catalog/root.rs @@ -12,7 +12,8 @@ use serde::{Deserialize, Serialize}; /// (the broadcast's one wall-clock mapping), the data sections /// (`json`, `binary`) for application tracks that aren't media, and the optional `m2ts` (a /// transport stream carried whole), plus `stats` naming the publisher's media snapshot track and -/// `echo` soliciting viewer feedback under a relative broadcast prefix. +/// `echo` soliciting viewer feedback under a relative broadcast prefix, and `contributions` naming +/// whole broadcasts for explicit selection. /// Applications extend it with their own root sections (e.g. `scte35`) through `E`. The catalog /// does not deny unknown fields, so a base consumer ignores the extra sections and an extended /// catalog stays wire-compatible. See the `extension_roundtrip` test. @@ -86,6 +87,12 @@ pub struct Catalog { /// An `echo` value without a string `path` decodes as absent, the same as [`stats`](Self::stats). pub echo: Option, + /// Whole broadcasts listed for explicit, lazy selection, keyed by contribution ID. + /// + /// Listing one subscribes to nothing; see [`Contribution`](crate::catalog::Contribution). + /// Omitted from the wire when empty. A malformed entry refuses the catalog. + pub contributions: std::collections::BTreeMap, + /// Application-defined root sections, flattened alongside the base catalog sections. /// /// The root `version` is reserved: serializing computes it from the base sections, and fails if @@ -156,6 +163,9 @@ struct Wire { #[serde(default, deserialize_with = "crate::catalog::deserialize_echo")] echo: Option, + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + contributions: std::collections::BTreeMap, + #[serde(flatten, serialize_with = "serialize_ext")] ext: E, } @@ -190,6 +200,7 @@ impl From> for Catalog { m2ts, stats, echo, + contributions, ext, } = wire; Self { @@ -202,6 +213,7 @@ impl From> for Catalog { m2ts, stats, echo, + contributions, ext, } } @@ -503,6 +515,33 @@ mod test { assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog); } + /// A contribution round-trips, stays off the wire when none is listed, and a malformed entry + /// refuses the catalog rather than being dropped. + #[test] + fn contributions_roundtrip_and_refuse_malformed_entries() { + let json = r#"{"contributions":{"alice":{"broadcast":"./alice.hang"}},"video":{"renditions":{"alice":{"codec":"avc1.64001f","container":{"kind":"legacy"}}}}}"#; + let catalog = Catalog::<()>::from_str(json).unwrap(); + assert_eq!( + catalog.contributions["alice"], + crate::catalog::Contribution::new(moq_net::path::Relative::new("./alice.hang").unwrap()) + ); + // Contribution IDs are their own namespace, so one may share a rendition's ID. + assert!(catalog.check_renditions().is_ok()); + assert!(catalog.video.renditions.contains_key("alice")); + assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog); + assert!(!Catalog::<()>::default().to_json().unwrap().contains("contributions")); + + for bad in [ + r#"{"contributions":[]}"#, + r#"{"contributions":{"alice":null}}"#, + r#"{"contributions":{"alice":{}}}"#, + r#"{"contributions":{"alice":{"broadcast":42}}}"#, + r#"{"contributions":{"alice":{"broadcast":"./alice.hang","epoch":"not-an-epoch"}}}"#, + ] { + assert!(Catalog::<()>::from_str(bad).is_err(), "{bad} must be refused"); + } + } + /// Every reference-bearing section carries an optional epoch beside its `broadcast`. #[test] fn reference_epochs_roundtrip_in_every_section() { @@ -511,6 +550,7 @@ mod test { const EPOCH: &str = "01890a5d-ac96-774b-bcce-b302099a8057"; let encoded = format!( r#"{{ + "contributions": {{"c": {{"broadcast": "./a", "epoch": "{EPOCH}"}}}}, "video": {{"renditions": {{"v": {{"broadcast": "./a", "epoch": "{EPOCH}", "codec": "avc1.64001f", "container": {{"kind": "legacy"}}}}}}}}, "audio": {{"renditions": {{"a": {{"broadcast": "./a", "epoch": "{EPOCH}", "codec": "opus", "sampleRate": 48000, "numberOfChannels": 2, "container": {{"kind": "legacy"}}}}}}}}, "text": {{"renditions": {{"t": {{"broadcast": "./a", "epoch": "{EPOCH}", "format": "vtt"}}}}}}, @@ -530,6 +570,7 @@ mod test { for reference in references { assert_eq!(reference.epoch(), Some(&epoch)); } + assert_eq!(catalog.contributions["c"].epoch.as_ref(), Some(&epoch)); assert_eq!(Catalog::<()>::from_str(&catalog.to_json().unwrap()).unwrap(), catalog); // Omitted stays omitted, and a malformed or noncanonical epoch refuses the catalog.