@blockcast/mmt-container 0.1.0-main.c71423b8a4e4 → 0.1.0-main.ce3c8aeb7f68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/align.d.ts +6 -2
  2. package/dist/align.d.ts.map +1 -1
  3. package/dist/align.js.map +2 -2
  4. package/dist/audio-ring-buffer.js +23 -36
  5. package/dist/audio-ring-buffer.js.map +1 -1
  6. package/dist/browser-runtime.js +6865 -6485
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +3 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +21 -2
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.js +10 -0
  13. package/dist/catalog-fec-params.js.map +4 -4
  14. package/dist/cmaf-block-assembler.d.ts +42 -0
  15. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  16. package/dist/cmaf-block-assembler.js +542 -535
  17. package/dist/cmaf-block-assembler.js.map +2 -2
  18. package/dist/cmaf-group-batcher.js +27 -46
  19. package/dist/cmaf-group-batcher.js.map +2 -2
  20. package/dist/cmcd-producer.js +45 -66
  21. package/dist/cmcd-producer.js.map +1 -1
  22. package/dist/fec-manager.d.ts +13 -1
  23. package/dist/fec-manager.d.ts.map +1 -1
  24. package/dist/fec-manager.js +1151 -871
  25. package/dist/fec-manager.js.map +2 -2
  26. package/dist/fec-starvation-detector.js +25 -40
  27. package/dist/fec-starvation-detector.js.map +1 -1
  28. package/dist/fec-worker-setup.js +242 -225
  29. package/dist/fec-worker-setup.js.map +3 -3
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js.map +2 -2
  33. package/dist/iso-bmff-timing.js +63 -88
  34. package/dist/iso-bmff-timing.js.map +1 -1
  35. package/dist/loc.js +7 -4
  36. package/dist/loc.js.map +1 -1
  37. package/dist/manifest-auth-plan.js +292 -311
  38. package/dist/manifest-auth-plan.js.map +1 -1
  39. package/dist/media-router.d.ts +0 -99
  40. package/dist/media-router.d.ts.map +1 -1
  41. package/dist/media-router.js +270 -504
  42. package/dist/media-router.js.map +3 -3
  43. package/dist/mfu-reassembler.js +597 -607
  44. package/dist/mfu-reassembler.js.map +3 -3
  45. package/dist/mmtp-container-parser.d.ts +37 -0
  46. package/dist/mmtp-container-parser.d.ts.map +1 -1
  47. package/dist/mmtp-container-parser.js +1531 -1522
  48. package/dist/mmtp-container-parser.js.map +3 -3
  49. package/dist/mmtp-container-parser.no-modules.js +179 -102
  50. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  51. package/dist/mmtp-decode-pipeline.js +1641 -1651
  52. package/dist/mmtp-decode-pipeline.js.map +3 -3
  53. package/dist/mmtp-router.d.ts +34 -0
  54. package/dist/mmtp-router.d.ts.map +1 -1
  55. package/dist/mmtp-router.js +3676 -3390
  56. package/dist/mmtp-router.js.map +3 -3
  57. package/dist/mmtp-to-cmaf.d.ts +7 -1
  58. package/dist/mmtp-to-cmaf.d.ts.map +1 -1
  59. package/dist/mmtp-to-cmaf.js +109 -134
  60. package/dist/mmtp-to-cmaf.js.map +2 -2
  61. package/dist/multicast-input.d.ts +7 -35
  62. package/dist/multicast-input.d.ts.map +1 -1
  63. package/dist/multicast-input.js +21 -2
  64. package/dist/multicast-input.js.map +4 -4
  65. package/dist/multicast-manager.d.ts +10 -1
  66. package/dist/multicast-manager.d.ts.map +1 -1
  67. package/dist/multicast-manager.js +5584 -4961
  68. package/dist/multicast-manager.js.map +4 -4
  69. package/dist/multicast-transport.d.ts +7 -0
  70. package/dist/multicast-transport.d.ts.map +1 -1
  71. package/dist/multicast-transport.js +369 -421
  72. package/dist/multicast-transport.js.map +4 -4
  73. package/dist/multicast-unwrap.js +53 -30
  74. package/dist/multicast-unwrap.js.map +2 -2
  75. package/dist/no-modules.js +2096 -2097
  76. package/dist/no-modules.js.map +3 -3
  77. package/dist/sample-combiner.js +118 -139
  78. package/dist/sample-combiner.js.map +1 -1
  79. package/dist/signaling.js.map +2 -2
  80. package/dist/source-auth.js +353 -382
  81. package/dist/source-auth.js.map +1 -1
  82. package/dist/switching-set-alignment.js +14 -29
  83. package/dist/switching-set-alignment.js.map +1 -1
  84. package/dist/timestamp-codec.js +17 -11
  85. package/dist/timestamp-codec.js.map +2 -2
  86. package/dist/track-pipeline-setup.js +105 -125
  87. package/dist/track-pipeline-setup.js.map +1 -1
  88. package/dist/track-pipeline.js +107 -127
  89. package/dist/track-pipeline.js.map +1 -1
  90. package/dist/track-session.d.ts +16 -0
  91. package/dist/track-session.d.ts.map +1 -1
  92. package/dist/track-session.js +230 -243
  93. package/dist/track-session.js.map +2 -2
  94. package/dist/transport-pool.js +24 -38
  95. package/dist/transport-pool.js.map +1 -1
  96. package/dist/wasm-mfu-reassembler.d.ts +6 -1
  97. package/dist/wasm-mfu-reassembler.d.ts.map +1 -1
  98. package/dist/wasm-mfu-reassembler.js +127 -144
  99. package/dist/wasm-mfu-reassembler.js.map +2 -2
  100. package/dist/wasm-mmtp-container-parser.js +1659 -1650
  101. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  102. package/node_modules/@blockcast/fec-worker/README.md +5 -1
  103. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +8 -2
  104. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -1
  105. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +89 -16
  106. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -1
  107. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts +48 -3
  108. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts.map +1 -1
  109. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js +55 -8
  110. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js.map +2 -2
  111. package/node_modules/@blockcast/fec-worker/dist/index.d.ts +1 -1
  112. package/node_modules/@blockcast/fec-worker/dist/index.d.ts.map +1 -1
  113. package/node_modules/@blockcast/fec-worker/dist/index.js.map +1 -1
  114. package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +97 -17
  115. package/node_modules/@blockcast/fec-worker/src/fec-worker-types.ts +46 -2
  116. package/node_modules/@blockcast/fec-worker/src/fec-worker.ts +78 -10
  117. package/node_modules/@blockcast/fec-worker/src/index.ts +2 -0
  118. package/node_modules/@blockcast/mmt-base/README.md +1 -0
  119. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  120. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  121. package/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  122. package/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  123. package/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  124. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/README.md +1 -0
  125. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  126. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  127. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  128. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  129. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  130. package/package.json +7 -6
  131. package/schemas/catalog.schema.json +1 -1
  132. package/src/align.ts +6 -2
  133. package/src/carp-catalog.ts +13 -3
  134. package/src/cmaf-block-assembler.ts +90 -81
  135. package/src/fec-manager.ts +530 -146
  136. package/src/index.ts +2 -2
  137. package/src/media-router.ts +0 -397
  138. package/src/mmtp-container-parser.ts +97 -21
  139. package/src/mmtp-router.ts +302 -125
  140. package/src/mmtp-to-cmaf.ts +21 -7
  141. package/src/multicast-input.ts +23 -3
  142. package/src/multicast-manager.ts +83 -11
  143. package/src/multicast-transport.ts +56 -17
  144. package/src/track-session.ts +16 -0
  145. package/src/wasm-mfu-reassembler.ts +40 -24
  146. package/test-vectors/catalog/README.md +2 -0
  147. package/test-vectors/catalog/negative/multicast-packet-id-signaling.json +26 -0
  148. package/test-vectors/catalog-validation.json +11 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/align.ts", "../src/track-session.ts", "../src/media-router.ts"],
4
- "sourcesContent": ["/**\n * Shared group-alignment primitive for MMT over MoQ switching sets.\n *\n * Pure math \u2014 no MMT wire parsing, no CMCD, no I/O. Callers wire the output\n * into their own drift-observation plumbing (see media-router.ts for the\n * libmmt wiring).\n *\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * Contract (integer-ticks form, authoritative):\n *\n * groupId = ticks < 0 ? 0 : floor(ticks / groupDurationTicks)\n *\n * Where `ticks` is a media timestamp expressed at the catalog's `timescale`\n * (Hz), and `groupDurationTicks = groupDurationSec * timescale`.\n *\n * Integer math means there is no epsilon and no float rounding to reason\n * about. The seconds-form wrapper `groupIdFor(Seconds, seconds)` exists for\n * legacy callers but converts to ticks internally.\n *\n * Every sender/receiver that emits or consumes MoQ groups from an MMT or\n * CMAF switching set MUST derive groupId from this formula so that base,\n * delta, and repair tracks agree on the group boundary for a given media\n * timestamp across languages and processes.\n *\n * Test vectors that exercise the contract live at\n * `packages/container/test-vectors/align.json`; the Go and Rust siblings\n * load the same fixture so cross-language agreement is executable, not\n * prose. **Formula changes require updating the fixture AND all three\n * sibling implementations in the same release** \u2014 divergence between\n * sender/relay/receiver is worse than any formula change.\n *\n * Canonical implementations:\n * Go: Blockcast/multicast `cmd/caddy/sender/group_align.go`\n * (commit 104eeff) \u2014 sender-side groupId stamping on egress.\n * Rust: moqtail/moqtail `apps/relay/src/server/abr.rs`\n * (commit 39accbf; experimental branch, may be rebased \u2014 rely\n * on the SHA, not the branch name) \u2014 relay-side check.\n * TS: THIS FILE (libmmt) \u2014 consumed by moq-lib + moqtail-ts via\n * @blockcast/mmt-container.\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n */\n\n/**\n * Branded seconds type. Construct only via `secondsFromTicks(ticks, timescale)`\n * or `asSeconds(n)` (the latter exists solely for tests and bring-up). The\n * brand prevents accidentally passing a raw tick count \u2014 or a Date.now()\n * millisecond \u2014 to an API that expects a media-time in seconds.\n */\nexport type Seconds = number & { readonly __brand: 'Seconds' }\n\n/**\n * Explicit conversion constructor: ticks at `timescale` Hz \u2192 Seconds.\n *\n * Call this at the wire/catalog boundary so the brand flows with the value\n * through the rest of the system. Throws on non-finite inputs or\n * non-positive timescale (CLAUDE.md \u00A7Architectural Principles: error on\n * bad init).\n */\nexport function secondsFromTicks(ticks: number, timescale: number): Seconds {\n if (!Number.isFinite(ticks)) {\n throw new Error(`[align] secondsFromTicks: ticks must be finite, got ${ticks}`)\n }\n if (!Number.isFinite(timescale) || timescale <= 0) {\n throw new Error(\n `[align] secondsFromTicks: timescale must be positive and finite, got ${timescale}`,\n )\n }\n return (ticks / timescale) as Seconds\n}\n\n/**\n * Escape hatch for tests / bring-up code that holds a raw seconds number\n * (e.g. a catalog field that ships as float seconds). Production code\n * should prefer `secondsFromTicks` so the conversion site is explicit.\n */\nexport function asSeconds(n: number): Seconds {\n if (!Number.isFinite(n)) {\n throw new Error(`[align] asSeconds: value must be finite, got ${n}`)\n }\n return n as Seconds\n}\n\n/**\n * Deterministic groupId from integer ticks. Authoritative form of the\n * contract (see module docstring).\n *\n * @param ticks \u2014 media presentation time in ticks (integer).\n * Negative values clamp to group 0 (matches\n * the Go sibling's base-clamp).\n * @param groupDurationTicks \u2014 group duration in ticks (positive integer).\n * @returns non-negative integer groupId.\n *\n * Throws on non-integer/non-finite inputs or non-positive duration. These\n * are init-time errors, not packet-hot-path errors \u2014 callers ingesting\n * wire data should validate once at catalog load, not once per packet.\n */\nexport function groupIdForTicks(ticks: number, groupDurationTicks: number): number {\n if (!Number.isInteger(ticks)) {\n throw new Error(\n `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`,\n )\n }\n if (!Number.isInteger(groupDurationTicks) || groupDurationTicks <= 0) {\n throw new Error(\n `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`,\n )\n }\n if (ticks < 0) return 0\n return Math.floor(ticks / groupDurationTicks)\n}\n\n/**\n * Seconds-form wrapper around `groupIdForTicks`. Kept for backwards\n * compatibility with existing callers that hold `Seconds` (or a raw\n * `number` that semantically represents seconds).\n *\n * Internally converts to ticks using a synthetic 1e9 Hz timescale so the\n * integer-math contract is the single source of truth. The `| number`\n * branch of the parameter type is a migration ramp \u2014 new code should\n * pass `Seconds` explicitly (via `secondsFromTicks` or `asSeconds`).\n *\n * @param mediaTimeSec \u2014 finite number of seconds; negatives clamp to 0.\n * @param groupDurationSec \u2014 positive finite seconds.\n *\n * @deprecated Use `groupIdForTicks(ticks, groupDurationTicks)` with\n * tick-space inputs from the catalog. The seconds wrapper rounds to the\n * nearest nanosecond and throws above ~104 days of media time; the\n * integer-ticks form has no rounding and a much wider safe range.\n *\n * The rounding is not benign: when `groupDurationTicks / timescale` is not\n * ns-exact (33333@90k, 1001@30k, 1024@44.1k \u2014 all real catalog cadences)\n * the quantized duration under-counts and `expected` slips a whole group.\n * See the divergence fixture in `__tests__/align.test.ts`.\n *\n * No non-test caller remains in this package: `MediaRouter` now takes\n * `GroupBoundaryTicks` (PCL-2211). Removal is tracked by BLO-21176.\n */\nexport function groupIdFor(\n mediaTimeSec: Seconds | number,\n groupDurationSec: number,\n): number {\n if (!Number.isFinite(mediaTimeSec as number)) {\n throw new Error(\n `[align] groupIdFor: mediaTimeSec must be a finite number, got ${mediaTimeSec}`,\n )\n }\n if (!Number.isFinite(groupDurationSec) || groupDurationSec <= 0) {\n throw new Error(\n `[align] groupIdFor: groupDurationSec must be a positive finite number, got ${groupDurationSec}`,\n )\n }\n if ((mediaTimeSec as number) < 0) return 0\n // 1e9 Hz keeps both operands inside Number.MAX_SAFE_INTEGER (2^53-1)\n // for ~104 days of media time. Beyond that, Math.round returns a\n // non-safe-integer float that Number.isInteger still accepts \u2014 throw\n // explicitly so the caller picks a narrower timescale rather than\n // silently quantizing.\n const TS = 1_000_000_000\n const ticks = Math.round((mediaTimeSec as number) * TS)\n const durTicks = Math.round(groupDurationSec * TS)\n if (durTicks <= 0) {\n throw new Error(\n `[align] groupIdFor: groupDurationSec=${groupDurationSec} rounds to <1 tick at 1e9 Hz; pass groupIdForTicks directly for sub-nanosecond durations`,\n )\n }\n if (!Number.isSafeInteger(ticks)) {\n throw new Error(\n `[align] groupIdFor: mediaTimeSec=${mediaTimeSec} overflows safe-integer ticks at 1e9 Hz (>~104 days); use groupIdForTicks with a narrower timescale`,\n )\n }\n return groupIdForTicks(ticks, durTicks)\n}\n\n/**\n * Result of a drift check between expected and actual groupIds.\n *\n * Discriminated on `kind` so callers must handle both outcomes explicitly\n * (the previous `{ drifted: boolean, deltaGroups: number }` shape let a\n * drifted result slip through with a silent `if (result.drifted)` gate).\n */\nexport type DriftCheckResult =\n | { readonly kind: 'aligned'; readonly deltaGroups: 0 }\n | { readonly kind: 'drifted'; readonly deltaGroups: number }\n\n/**\n * Compare a packet-stamped groupId against the formula-derived expectation.\n *\n * Pure observer \u2014 does not throw on drift, does not mutate anything.\n * Callers decide how to react (e.g. bump a CMCD counter, log, ignore).\n *\n * @param expected \u2014 groupId as derived via `groupIdForTicks` or `groupIdFor`.\n * @param actual \u2014 groupId as stamped on the incoming packet/group.\n */\nexport function driftCheck(expected: number, actual: number): DriftCheckResult {\n if (!Number.isInteger(expected) || !Number.isInteger(actual)) {\n throw new Error(\n `[align] driftCheck: both arguments must be integer groupIds, got expected=${expected} actual=${actual}`,\n )\n }\n const deltaGroups = actual - expected\n if (deltaGroups === 0) return { kind: 'aligned', deltaGroups: 0 }\n return { kind: 'drifted', deltaGroups }\n}\n\nexport type MmtpSubgroupKeyInput =\n | { readonly kind: 'mpu-metadata' }\n | {\n readonly kind: 'timed'\n readonly movieFragmentSequenceNumber: number\n readonly sampleNumber: number\n }\n | { readonly kind: 'non-timed'; readonly itemId: number }\n\n/**\n * Canonical, domain-separated key for MMTP payloads sharing one MoQ subgroup.\n * This is a map/storage key, not the scalar MoQ subgroup ID. MPU metadata is\n * carried in subgroup 0; media identity remains explicit and collision-free.\n */\nexport function subgroupKeyFor(input: MmtpSubgroupKeyInput): string {\n if (input.kind === 'mpu-metadata') return 'metadata:0'\n\n const values =\n input.kind === 'timed'\n ? [input.movieFragmentSequenceNumber, input.sampleNumber]\n : [input.itemId]\n for (const value of values) {\n if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {\n throw new Error(`[align] subgroup key coordinates must be uint32, got ${value}`)\n }\n }\n\n return input.kind === 'timed'\n ? `timed:${input.movieFragmentSequenceNumber}:${input.sampleNumber}`\n : `non-timed:${input.itemId}`\n}\n", "/**\n * TrackSession \u2014 per-track transport state machine.\n * SessionManager \u2014 orchestrates all sessions + TransportPool.\n *\n * Implements Patent Claim 9 (draft-ramadan-moq-fec APPLICATION-1):\n * (a) subscribe unicast\n * (b) simultaneously join multicast\n * (c) render from unicast during join\n * (d) activate multicast on RAP, suppress unicast\n * (e) cross-transport FEC repair during transition\n * (f) hysteresis before switching away from multicast\n * (g) re-subscribe unicast on sustained failure\n *\n * PIM: manages transport state without inspecting packet contents.\n */\n\nimport {\n TransportPool,\n type Subscription,\n type SubscriptionMode,\n type AcquireOptions,\n type DirectSocketHealth,\n type TransportPoolOptions,\n} from './transport-pool.js'\nimport { fecBlockBudgetMs } from '@blockcast/mmt-fec'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type TrackState =\n | 'idle'\n | 'unicast'\n | 'unicast-fallback'\n | 'joining'\n | 'multicast'\n | 'amt'\n | 'failing'\n\nexport interface TrackSessionConfig {\n trackName: string\n trackType: 'video' | 'audio'\n packetId: number\n /** FEC interleave depth from catalog (ms). Used for hysteresis timer. */\n fecInterleaveMs: number\n /** Explicit catalog jitter/reorder allowance in ms. */\n fecReorderToleranceMs?: number\n /** FEC K from catalog. Used for audio worklet latency calculation. */\n fecK: number\n /** FEC repair symbols per block (P). NOT symbol size. */\n fecRepairCount: number\n /**\n * Repair symbols per block this receiver actually joined: the sum of\n * `repairSymbols` over the joined BASE layers, not a count of layers\n * (draft-ramadan-moq-fec 6.3). A keyframe overlay is a separate FEC instance\n * and is not included.\n *\n * This is runtime join state, not catalog geometry: a receiver on a clean\n * path joins layer 0 only while a lossy one adds layers, so the catalog's\n * total P is not what this receiver is receiving. Diagnostics that report P\n * (the worker snapshot, CMCD `x-bc-fec-p`) must read this.\n *\n * Absent when the caller joins no layers explicitly, in which case P_0 is\n * what was joined. That is an identity on a single-layer track, not a\n * catalog default: with one layer, P_0 is the total.\n */\n joinedRepairCount?: number\n /** FEC symbol size in bytes (T). Required for WASM decoder OTI. */\n fecSymbolSize: number\n /** MoQ repair track name from catalog FEC config. */\n repairTrackName?: string\n /** Frame samples from initData parsing (audio-init-parser.ts). */\n frameSamples?: number\n /** Audio sample rate from catalog. */\n sampleRate?: number\n /** Ordered transport preference: best first. */\n preferredTransports: SubscriptionMode[]\n /** Subscription key for multicast/AMT: \"(S,G,port)\". */\n multicastKey?: string\n /** MoQ track name for unicast subscription. */\n moqTrackName?: string\n /** AMT relay address (if AMT is in preference chain). */\n amtRelay?: string\n /** MoQ relay URL (for WebTransport subscription). */\n moqRelayUrl?: string\n}\n\n// ---------------------------------------------------------------------------\n// PIM callbacks (protocol-independent \u2014 transport state only)\n// ---------------------------------------------------------------------------\n\nexport interface SessionManagerCallbacks {\n /** Fired on every transport state transition. */\n onStateChange?(trackName: string, from: TrackState, to: TrackState): void\n /** Fired to suppress/unsuppress unicast for this track (transport arbitration). */\n onSuppress?(trackName: string, suppressed: boolean): void\n /**\n * Fired when a track sat in `joining` for SessionManager.takeoverDeadlineMs\n * without a RAP (BLO-9413/D9). The session has already returned to `unicast`\n * (nothing was suppressed, so nothing to restore) and it keeps its FEC\n * decoder armed, because the multicast socket is still joined and the router\n * still admits the stream's symbols. The host should abandon the router-side\n * attempt (e.g. MediaRouter.failbackToMoq()) so the router stops waiting for\n * a keyframe that is never coming; it must not dispose the decoder here. The\n * decoder is released on the next transport edge (unsubscribe, failbackAll,\n * or transportFailed falling back to unicast) through fec-teardown.\n */\n onTakeoverTimeout?(trackName: string): void\n}\n\n// ---------------------------------------------------------------------------\n// MMTP application-layer extension (FEC lifecycle, media resets)\n// ---------------------------------------------------------------------------\n\n/**\n * MMTP track events (discriminated union).\n * Each protocol layer defines its own event union \u2014 MMTP events cover\n * media resets, latency, and FEC lifecycle.\n */\nexport type MmtpTrackEvent =\n | { type: 'reset' }\n | { type: 'latency'; latencyMs: number }\n | { type: 'fec-setup' }\n | { type: 'fec-teardown' }\n\n/**\n * MMTP application-layer extension of SessionManagerCallbacks.\n * Single onTrackEvent dispatches all MMTP-specific events.\n * PIM consumers use the base SessionManagerCallbacks (no onTrackEvent).\n *\n * IWA can define its own subinterface with its own TrackEvent union\n * (e.g., IwaTrackEvent for socket health, AMT state) using the same pattern.\n */\nexport interface MmtpSessionCallbacks extends SessionManagerCallbacks {\n onTrackEvent?(trackName: string, event: MmtpTrackEvent, config: TrackSessionConfig): void\n}\n\n/**\n * Loss-hysteresis window covering the signaled FEC block span plus jitter.\n *\n * `fecK` no longer feeds the math; it is still validated as a catalog\n * well-formedness guard and kept in the signature for positional API compat\n * (removal is a follow-up with the next cross-repo pin bump).\n */\nexport function computeFecLossWindowMs(fecInterleaveMs: number, fecK: number, jitterBufferMs?: number): number {\n return computeFecDeliveryWindowMs({\n interleaveDepthMs: fecInterleaveMs,\n sourceSymbols: fecK,\n jitterBufferMs,\n })\n}\n\nexport interface FecDeliveryWindowConfig {\n interleaveDepthMs: number\n sourceSymbols: number\n repairSymbols?: number\n symbolSize?: number\n mediaUnitsPerSecond?: number\n bandwidthBps?: number\n /**\n * Explicit jitter/reorder allowance in ms, added once to the complete span.\n * Callers pass their signaled catalog allowance, never a local default.\n */\n jitterBufferMs?: number\n}\n\n/**\n * The catalog interleaveDepthMs is the complete FEC block span, including the\n * repair tail. K, P, cadence, and bandwidth must not expand it again. Geometry\n * fields remain accepted for existing callers, but do not feed deadline math.\n */\nexport function computeFecDeliveryWindowMs(\n config: FecDeliveryWindowConfig,\n): number {\n const fecInterleaveMs = config.interleaveDepthMs\n const fecK = config.sourceSymbols\n if (!Number.isFinite(fecInterleaveMs) || fecInterleaveMs <= 0) {\n throw new Error(\n `[TrackSession] fecInterleaveMs=${fecInterleaveMs}. ` +\n `Derive a positive FEC interleave window from the stream catalog.`\n )\n }\n if (!Number.isFinite(fecK) || fecK <= 0) {\n throw new Error(\n `[TrackSession] fecK=${fecK}. ` +\n `Derive a positive FEC source-symbol count from the stream catalog.`\n )\n }\n\n // Absence stays absent; it does not authorize a synthesized reorder budget.\n if (config.jitterBufferMs === undefined) return Math.ceil(fecInterleaveMs)\n return fecBlockBudgetMs(fecInterleaveMs, config.jitterBufferMs)\n}\n\n/** Convert the shared FEC delivery deadline into an integer media timescale. */\nexport function computeFecDeliveryWindowMediaUnits(\n config: FecDeliveryWindowConfig,\n timestampTimescale: number,\n): number {\n if (!Number.isFinite(timestampTimescale) || timestampTimescale <= 0) {\n throw new Error(\n `[TrackSession] timestampTimescale=${timestampTimescale}. ` +\n 'Derive a positive media timescale from the container.',\n )\n }\n const deliveryWindow = Math.ceil(\n computeFecDeliveryWindowMs(config) * timestampTimescale / 1000,\n )\n if (!Number.isSafeInteger(deliveryWindow)) {\n throw new Error('[TrackSession] FEC delivery window exceeds the media timestamp range.')\n }\n return deliveryWindow\n}\n\n// ---------------------------------------------------------------------------\n// TrackSession\n// ---------------------------------------------------------------------------\n\nexport class TrackSession {\n readonly config: TrackSessionConfig\n #state: TrackState = 'idle'\n #subscription: Subscription | null = null\n #hysteresisTimer: ReturnType<typeof setTimeout> | null = null\n #joinDeadlineTimer: ReturnType<typeof setTimeout> | null = null\n #previousPrimary: SubscriptionMode | null = null\n #manager: SessionManager\n // Single suppression authority flag (BLO-9413 failback coherence): every\n // suppress this session fires is recorded here, and every path that leaves\n // a suppressed state unwinds through #unsuppress(). Before this flag,\n // unsubscribe() only un-suppressed from multicast/amt \u2014 a session torn down\n // from `failing` (exactly where a starving track sits) was re-subscribed to\n // unicast with the host's media still muted: MoQ playing into a dead sink.\n #suppressFired = false\n // Single FEC authority flag: set by the fec-setup edges (joinStarted,\n // enterUnicastFallback), cleared by the fec-teardown edge in #transition.\n // Setup and teardown are paired by construction, so a takeover timeout that\n // parks the session in `unicast` keeps the decoder the still-joined\n // transport is feeding, and the later unsubscribe still tears it down.\n #fecArmed = false\n\n constructor(config: TrackSessionConfig, manager: SessionManager) {\n this.config = config\n this.#manager = manager\n }\n\n // -----------------------------------------------------------------------\n // State\n // -----------------------------------------------------------------------\n\n get state(): TrackState { return this.#state }\n get subscription(): Subscription | null { return this.#subscription }\n\n /** True while this session's onSuppress(true) is outstanding (no matching\n * onSuppress(false) yet). Test/assertion surface for failback coherence. */\n get isSuppressed(): boolean { return this.#suppressFired }\n\n /** Current active transport mode, or null if idle. */\n get transport(): SubscriptionMode | null {\n switch (this.#state) {\n case 'multicast': return 'multicast'\n case 'amt': return 'amt'\n case 'unicast': return 'moq'\n case 'unicast-fallback': return 'moq' // SSM bridge absent \u2014 MoQ unicast is the only source\n case 'joining': return 'moq' // MoQ still primary during join\n case 'failing': return this.#previousPrimary\n default: return null\n }\n }\n\n // -----------------------------------------------------------------------\n // Computed (no magic numbers)\n // -----------------------------------------------------------------------\n\n /** Audio worklet latency: max(fecInterleaveMs, frameDurationMs * fecK).\n * Returns undefined if frame duration unknown (no initData). */\n get audioLatencyMs(): number | undefined {\n const fd = this.frameDurationMs\n if (fd === undefined) {\n return this.config.fecInterleaveMs > 0 ? this.config.fecInterleaveMs : undefined\n }\n return Math.max(this.config.fecInterleaveMs, fd * this.config.fecK)\n }\n\n /** Frame duration in ms, derived from frameSamples + sampleRate. */\n get frameDurationMs(): number | undefined {\n const { frameSamples, sampleRate } = this.config\n if (!frameSamples || !sampleRate || sampleRate <= 0) return undefined\n return (frameSamples / sampleRate) * 1000\n }\n\n // -----------------------------------------------------------------------\n // Transitions (Patent Claim 9)\n // -----------------------------------------------------------------------\n\n /** idle \u2192 unicast: player subscribes to this track. */\n subscribe(): void {\n if (this.#state !== 'idle') return\n this.#transition('unicast')\n\n // Emit audio latency on first subscribe\n if (this.config.trackType === 'audio') {\n const latency = this.audioLatencyMs\n if (latency !== undefined) {\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'latency', latencyMs: latency }, this.config)\n }\n }\n }\n\n /** unicast \u2192 joining: multicast/AMT capability detected, join in progress. */\n joinStarted(): void {\n if (this.#state !== 'unicast') return\n this.#transition('joining')\n // FEC decoders must be ready before multicast data arrives (Claim 9e:\n // cross-transport repair). A session re-joining after a takeover timeout\n // still owns its decoder, so fec-setup fires once per FEC epoch.\n this.#armFec()\n }\n\n /**\n * any non-fallback state \u2192 unicast-fallback. Used when the SSM bridge is\n * absent (vanilla Chromium / no extension) and the host falls back to a\n * MoQ unicast subscription per track. Terminal-ish: activateMulticast,\n * failbackAll, and transportFailed are no-ops while in this state.\n *\n * Fires fec-setup so the per-track repair worker spins up \u2014 repair packets\n * still flow over the MoQ repair-track subscription, so FEC source+repair\n * can converge as in the multicast path.\n *\n * Audio latency is NOT re-emitted here: subscribe() already fires latency\n * once on the idle \u2192 unicast edge, and enterUnicastFallback is only ever\n * reached from a non-idle state (SessionManager skips idle sessions).\n */\n enterUnicastFallback(): void {\n if (this.#state === 'unicast-fallback') return\n this.#clearHysteresis()\n this.#transition('unicast-fallback')\n // Suppress the redundant unicast media decoder. On the no-bridge path the\n // host feeds MoQ-unicast source packets into MulticastManager (the render\n // consumer); a second base-media subscribe (the @moq/watch decoder) would\n // split the single connection's QUIC flow-control budget and stall delivery\n // (BLO-8969). Fire suppress here, on the fallback edge, so the decoder is\n // gated off before it subscribes rather than after the relay forward task\n // has already wedged.\n this.#suppress()\n this.#armFec()\n }\n\n /**\n * unicast-fallback \u2192 unicast. Called when the SSM bridge appears mid-session\n * (extension installed after fallback engaged). Host first aborts the fallback\n * drainers, then transitions sessions back to unicast so the regular\n * multicast/AMT preference chain can take over via joinStarted().\n */\n exitUnicastFallback(): void {\n if (this.#state !== 'unicast-fallback') return\n this.#transition('unicast')\n // Un-suppress the unicast decoder: the bridge appeared mid-session, so the\n // host tears down the fallback drainers and the regular preference chain\n // (joinStarted -> joining -> rapReceived) will re-suppress on multicast RAP.\n this.#unsuppress()\n }\n\n /**\n * joining \u2192 multicast or amt: RAP received on the joined transport (Claim 9d).\n * Resets audio worklet, then suppresses MoQ.\n */\n rapReceived(mode: 'multicast' | 'amt'): void {\n if (this.#state !== 'joining') return\n this.#previousPrimary = mode\n this.#transition(mode)\n if (this.config.trackType === 'audio') {\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'reset' }, this.config)\n }\n this.#suppress()\n }\n\n /** multicast/amt \u2192 failing: loss detected, start hysteresis timer (Claim 9f). */\n lossDetected(): void {\n if (this.#state !== 'multicast' && this.#state !== 'amt') return\n this.#previousPrimary = this.#state as SubscriptionMode\n this.#transition('failing')\n\n // Hysteresis timer: sustained loss before failback (Claim 9f). Use the\n // same complete span plus explicit allowance as FECManager and workers.\n const hysteresisMs = computeFecLossWindowMs(\n this.config.fecInterleaveMs,\n this.config.fecK,\n this.config.fecReorderToleranceMs,\n )\n this.#hysteresisTimer = setTimeout(() => {\n this.hysteresisExpired()\n }, hysteresisMs)\n }\n\n /** failing \u2192 previous primary: loss recovered within hysteresis window. */\n lossRecovered(): void {\n if (this.#state !== 'failing') return\n this.#clearHysteresis()\n if (this.#previousPrimary) {\n this.#transition(this.#previousPrimary as TrackState)\n }\n }\n\n /**\n * Transport failed (AMT relay down, multicast interface gone).\n * Try next transport in preference chain.\n */\n transportFailed(): void {\n this.#clearHysteresis()\n // Unicast-fallback is terminal: the host owns the subscription and\n // SessionManager transport machinery does not arbitrate it.\n if (this.#state === 'unicast-fallback') return\n const current = this.#previousPrimary ?? this.transport\n const prefs = this.config.preferredTransports\n const currentIdx = current ? prefs.indexOf(current) : -1\n const nextMode = prefs[currentIdx + 1]\n\n if (nextMode !== undefined && nextMode !== 'moq') {\n // Next is multicast or AMT: start joining. `joining` means MoQ is\n // primary again (see transport getter), so if the failed transport had\n // suppressed unicast, restore it for the join window or the viewer\n // watches black video until the next RAP (which may never come).\n // The chain position moves with the attempt: a join that times out\n // parks the session in `unicast` with this transport recorded, so the\n // next failure continues past it rather than re-trying the transport\n // that already failed and re-firing onTakeoverTimeout on every lap.\n this.#previousPrimary = nextMode\n this.#transition('joining')\n this.#unsuppress()\n return\n }\n // MoQ is next, or the chain is exhausted: unicast either way (Claim 9g).\n // For a session parked in `unicast` with its decoder retained after a\n // takeover timeout, this transition is a self-edge and fires no teardown,\n // so the release is explicit. It is the \"transportFailed falling back to\n // unicast\" release path the onTakeoverTimeout doc names, and #disarmFec is\n // idempotent, so it is a no-op when the transition already fired the\n // teardown. The audio reset is not flag-guarded, so it is tied to the edge\n // itself: a session already resting in unicast changed no transport and\n // owes the host no reset, however many pool subscriptions fail for it.\n const from = this.#state\n this.#previousPrimary = null\n this.#transition('unicast')\n this.#disarmFec()\n this.#unsuppress()\n if (from !== 'unicast' && this.config.trackType === 'audio') {\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'reset' }, this.config)\n }\n }\n\n /** Hysteresis expired \u2192 failback to next transport (Claim 9g). */\n hysteresisExpired(): void {\n if (this.#state !== 'failing') return\n this.#clearHysteresis()\n this.transportFailed()\n }\n\n /** \u2192 idle: player unsubscribes / tab close / cleanup. */\n unsubscribe(): void {\n this.#clearHysteresis()\n if (this.#state !== 'idle') {\n this.#transition('idle')\n // Unwind any outstanding suppression regardless of which state we left.\n // The old `wasActive` check (multicast/amt only) leaked suppression when\n // tearing down from `failing` or `unicast-fallback` \u2014 failbackAll()'s\n // unsubscribe\u2192subscribe cycle then re-entered unicast with the host's\n // media still muted (BLO-9413 freeze: \"failing back\" logged, video dead).\n this.#unsuppress()\n }\n }\n\n /** True when SessionManager.enterUnicastFallback put this track into the\n * host-driven unicast subscription mode. Host can iterate sessions to\n * decide whether to keep its fallback drainer alive across MediaRouter\n * arbitration events. */\n get isUnicastFallback(): boolean {\n return this.#state === 'unicast-fallback'\n }\n\n /**\n * True while this track owns a FEC decoder (fec-setup fired, fec-teardown\n * not yet). Stays true across a takeover timeout that parked the session in\n * `unicast`; SessionManager.failbackAll uses it to release such sessions.\n */\n get isFecArmed(): boolean {\n return this.#fecArmed\n }\n\n /**\n * Start the deadline a `joining` entry deferred while the join was inactive\n * (SessionManager.joinActive). The track gets the FULL deadline from here,\n * because that is when media can first arrive. No-op outside `joining` and\n * when a deadline is already running, so it never shortens or restarts one.\n *\n * The `joinActive` guard is what makes this safe to call from anywhere: a\n * track parked in `joining` with a deferred (null) timer satisfies the other\n * two, so without it a host calling this while the join is still inactive\n * would arm the exact deadline the gate exists to defer -- silently\n * reinstating BLO-34289. It is a no-op for the internal caller, which writes\n * `#joinActive = true` before iterating the sessions.\n */\n armDeferredJoinDeadline(): void {\n if (this.#state !== 'joining' || this.#joinDeadlineTimer !== null) return\n if (!this.#manager.joinActive) return\n this.#armJoinDeadline(this.#manager.takeoverDeadlineMs)\n }\n\n dispose(): void {\n this.#clearHysteresis()\n this.#clearJoinDeadline()\n this.#state = 'idle'\n this.#subscription = null\n // Release through the teardown edge, not a bare assignment: the\n // retained-FEC park makes `unicast` + isFecArmed a resting state, and\n // SessionManager.dispose() calls this directly (removeTrack() reaches it\n // via unsubscribe(), which has already disarmed). A bare assignment there\n // drops the host's decoder without a fec-teardown -- a leaked Worker.\n this.#disarmFec()\n }\n\n // -----------------------------------------------------------------------\n // Internal\n // -----------------------------------------------------------------------\n\n #transition(to: TrackState, opts?: { retainFec?: boolean }): void {\n const from = this.#state\n if (from === to) return\n // Takeover deadline (BLO-9413/D9): every entry into `joining` arms it\n // (joinStarted AND transportFailed-failover both route through here);\n // every exit cancels it. Without this, a transport that accepts the\n // subscribe but never delivers a RAP parks the session in `joining`\n // forever (observed live in the Phase-0 headless repro). The value is\n // resolved before any state write, so the one residual failure -- a\n // manager whose deadline was never set at all, which addTrack() refuses --\n // leaves the session in its previous state rather than half-transitioned.\n // Invalid values never reach here: SessionManager's setter refuses them.\n // The read is unconditional even when `joinActive` defers the arm, so a\n // manager without a deadline still fails closed on every joining edge.\n const joinDeadlineMs = to === 'joining' ? this.#manager.takeoverDeadlineMs : undefined\n this.#state = to\n if (from === 'joining') this.#clearJoinDeadline()\n if (joinDeadlineMs !== undefined && this.#manager.joinActive) {\n this.#armJoinDeadline(joinDeadlineMs)\n }\n // FEC teardown: entering a state without a FEC decoder releases the one\n // this track armed, unless the caller keeps it (takeover timeout: the\n // transport is still joined and still feeding the decoder).\n const fecActive = (s: TrackState) =>\n s === 'joining' ||\n s === 'multicast' ||\n s === 'amt' ||\n s === 'failing' ||\n s === 'unicast-fallback'\n if (!fecActive(to) && !opts?.retainFec) this.#disarmFec()\n this.#manager.callbacks?.onStateChange?.(this.config.trackName, from, to)\n }\n\n #clearHysteresis(): void {\n if (this.#hysteresisTimer !== null) {\n clearTimeout(this.#hysteresisTimer)\n this.#hysteresisTimer = null\n }\n }\n\n #armJoinDeadline(deadlineMs: number): void {\n this.#clearJoinDeadline()\n if (deadlineMs === 0) return // a declared 0 disables the deadline\n this.#joinDeadlineTimer = setTimeout(() => {\n this.#joinDeadlineTimer = null\n if (this.#state !== 'joining') return\n // No RAP within the deadline: return to unicast for arbitration only.\n // MoQ was never suppressed in `joining`, so there is nothing to restore\n // and this edge stays silent on onSuppress (asserted in tests). The\n // multicast socket is still joined and the router still admits this\n // stream's symbols, so the FEC decoder stays armed; the next transport\n // edge releases it.\n this.#transition('unicast', { retainFec: true })\n this.#manager.callbacks?.onTakeoverTimeout?.(this.config.trackName)\n }, deadlineMs)\n }\n\n #clearJoinDeadline(): void {\n if (this.#joinDeadlineTimer !== null) {\n clearTimeout(this.#joinDeadlineTimer)\n this.#joinDeadlineTimer = null\n }\n }\n\n /** Fire fec-setup exactly once per FEC epoch. */\n #armFec(): void {\n if (this.#fecArmed) return\n this.#fecArmed = true\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'fec-setup' }, this.config)\n }\n\n /** Fire fec-teardown for an armed decoder; no-op when none is armed. */\n #disarmFec(): void {\n if (!this.#fecArmed) return\n this.#fecArmed = false\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'fec-teardown' }, this.config)\n }\n\n /** Fire onSuppress(true) exactly once per suppression epoch. */\n #suppress(): void {\n if (this.#suppressFired) return\n this.#suppressFired = true\n this.#manager.callbacks?.onSuppress?.(this.config.trackName, true)\n }\n\n /** Unwind an outstanding suppression; no-op when none is outstanding. */\n #unsuppress(): void {\n if (!this.#suppressFired) return\n this.#suppressFired = false\n this.#manager.callbacks?.onSuppress?.(this.config.trackName, false)\n }\n}\n\n// ---------------------------------------------------------------------------\n// SessionManager\n// ---------------------------------------------------------------------------\n\n/**\n * Largest takeover deadline setTimeout represents faithfully. setTimeout\n * coerces its delay to a signed 32-bit int, so a larger value fires on the\n * next tick (Node also warns TimeoutOverflowWarning) instead of after the\n * window the host asked for -- silently inverting the feature. Rejecting it\n * keeps the classic units bug (seconds-as-ms, a wrong timescale) loud.\n */\nexport const MAX_TAKEOVER_DEADLINE_MS = 2_147_483_647\n\n/**\n * How long `joinActive` may stay false before the library says so. The deferral\n * is unbounded by construction -- that is the feature -- so a host that never\n * flips it back parks every track in `joining` with no timer at all: exactly the\n * forever-join the takeover deadline exists to prevent, only silent. MoQ stays\n * unsuppressed so the viewer sees video, but onTakeoverTimeout never fires, the\n * FEC decoder stays armed, and the preference chain never advances past the\n * transport that failed. It looks like a slow join. A host is one un-awaited\n * rejection between `false` and `true` away from it, so the library complains\n * rather than trusting every future host to get all of its exit paths right.\n *\n * Generous against a genuinely slow subscribe -- a bridge reconnect or AMT relay\n * handshake is seconds -- so anything still unsettled here is broken, not slow.\n */\nexport const JOIN_DEFER_WARN_MS = 30_000\n\nexport class SessionManager {\n readonly pool: TransportPool\n readonly sessions = new Map<string, TrackSession>()\n callbacks: SessionManagerCallbacks | null = null\n #takeoverDeadlineMs: number | undefined = undefined\n #joinActive = true\n #joinDeferWarnTimer: ReturnType<typeof setTimeout> | null = null\n\n /**\n * Takeover deadline (BLO-9413/D9): the time a session may sit in `joining`\n * without a RAP before returning to `unicast` and firing onTakeoverTimeout.\n * MoQ is never suppressed during `joining`, so expiry abandons the takeover\n * without a playback glitch. The host derives it from the catalog (RAP\n * cadence from groupDurationTicks/timescale plus the signaled FEC delivery\n * window or reorder tolerance) and sets it before addTrack(). There is no\n * default: an unset value fails addTrack() closed, and reading the getter\n * before assignment throws the same way, so no host ever holds a\n * `number | undefined` it could coalesce back into a default.\n * `hasTakeoverDeadline` answers whether one was admitted. A declared 0\n * disables the deadline. The value is an integer number of milliseconds:\n * setTimeout truncates fractions, so a host that divides ticks by a\n * timescale must round before assigning.\n *\n * Assignment validates, so the diagnostic lands at the host's own call site.\n * That is what bounds the blast radius: `joining` is entered from\n * joinStarted(), from the transportFailed() failover branch -- itself\n * reachable from a setTimeout via hysteresisExpired(), where no caller could\n * catch a throw -- and from the activateMulticast()/activateAmt()/pool-failure\n * loops, where a throw on one session would abandon its siblings mid-loop\n * (the split-brain those loops exist to prevent). Refusing a bad value at\n * assignment means no host mutation can make an already-admitted session\n * throw out of a transport edge.\n */\n get takeoverDeadlineMs(): number {\n return this.#requireTakeoverDeadlineMs()\n }\n\n set takeoverDeadlineMs(value: number) {\n if (!Number.isInteger(value) || value < 0 || value > MAX_TAKEOVER_DEADLINE_MS) {\n throw new Error(\n `[SessionManager] takeoverDeadlineMs must be an integer from 0 to ${MAX_TAKEOVER_DEADLINE_MS} (0 disables it, larger values overflow setTimeout); got ${String(value)}`,\n )\n }\n this.#takeoverDeadlineMs = value\n }\n\n /** True once the host has admitted a deadline; a declared 0 counts. */\n get hasTakeoverDeadline(): boolean {\n return this.#takeoverDeadlineMs !== undefined\n }\n\n /**\n * Whether the transport the joining tracks are waiting on is actually\n * subscribed. The takeover deadline is a media-arrival budget and media\n * cannot arrive before the join exists, so while this is false, entering\n * `joining` arms no deadline; flipping it true starts the FULL deadline for\n * every track already parked there.\n *\n * Default true, which is the arm-on-`joining` behaviour every host had\n * before: a host that only calls joinStarted() after its own join resolves\n * (moqtail-private's player, post-BLO-33339) is already at the right edge and\n * needs no gate. A host that arms joinStarted() up front \u2014 to have FEC\n * decoders ready before the first datagram \u2014 sets this false before addTrack()\n * and true when its subscribe settles. Charging a slow subscribe (bridge\n * reconnect, AMT relay handshake) against the media budget expired the\n * deadline before the subscription existed and abandoned the join on the\n * happy path. BLO-34289.\n *\n * The flag tracks the host's primary join, not per-track transport state. A\n * track that fails over to the next transport in its own chain while this is\n * false (transportFailed's failover branch also enters `joining`) has that\n * deadline gated on the primary join activating, not on its own transport.\n * Under the documented usage -- false once at setup, true once the subscribe\n * settles -- the two coincide.\n *\n * Leaving this false is not free: see JOIN_DEFER_WARN_MS.\n */\n get joinActive(): boolean {\n return this.#joinActive\n }\n\n set joinActive(active: boolean) {\n const wasActive = this.#joinActive\n this.#joinActive = active\n if (!active) {\n // Edge-triggered: a host re-declaring false has not restarted its\n // subscribe, and total deferral is what the warning is about.\n if (wasActive) this.#armJoinDeferWarn()\n return\n }\n this.#clearJoinDeferWarn()\n if (wasActive) return\n for (const [, session] of this.sessions) session.armDeferredJoinDeadline()\n }\n\n #armJoinDeferWarn(): void {\n this.#joinDeferWarnTimer = setTimeout(() => {\n this.#joinDeferWarnTimer = null\n const deferred = [...this.sessions.values()].filter(s => s.state === 'joining').length\n console.warn(\n `[SessionManager] joinActive has been false for ${JOIN_DEFER_WARN_MS} ms and ${deferred} track(s) sit in 'joining' with no takeover deadline. Set joinActive = true when the subscribe settles, on every exit path including failures, or these tracks never time out, never release their FEC decoders, and never advance to the next transport.`,\n )\n }, JOIN_DEFER_WARN_MS)\n }\n\n #clearJoinDeferWarn(): void {\n if (this.#joinDeferWarnTimer === null) return\n clearTimeout(this.#joinDeferWarnTimer)\n this.#joinDeferWarnTimer = null\n }\n\n /** Narrow to MMTP callbacks (onTrackEvent). Safe \u2014 optional chaining handles PIM-only consumers. */\n get mmtp(): MmtpSessionCallbacks | null {\n return this.callbacks as MmtpSessionCallbacks | null\n }\n\n constructor(poolOptions?: TransportPoolOptions) {\n this.pool = new TransportPool(poolOptions)\n\n // Wire pool failure \u2192 per-track failover\n this.pool.onSubscriptionFailed(sub => {\n for (const trackName of sub.consumers) {\n const session = this.sessions.get(trackName)\n if (session) session.transportFailed()\n }\n })\n }\n\n // -----------------------------------------------------------------------\n // Track management\n // -----------------------------------------------------------------------\n\n /**\n * The admitted takeover deadline. Throws only when the host never set one,\n * every other invalid value being refused by the setter, and returns a\n * declared 0 as 0. The getter and addTrack() both route through it, so a\n * session cannot exist without an admitted deadline, which is what makes\n * the #transition() read unable to throw on an already-admitted session.\n */\n #requireTakeoverDeadlineMs(): number {\n const value = this.#takeoverDeadlineMs\n if (value === undefined) {\n throw new Error(\n '[SessionManager] takeoverDeadlineMs is unset; set a catalog-derived takeover deadline (0 disables it) before adding tracks',\n )\n }\n return value\n }\n\n /** Add a track session from catalog config. */\n addTrack(config: TrackSessionConfig): TrackSession {\n if (this.sessions.has(config.trackName)) {\n throw new Error(`[SessionManager] Track \"${config.trackName}\" already exists`)\n }\n this.#requireTakeoverDeadlineMs()\n const session = new TrackSession(config, this)\n this.sessions.set(config.trackName, session)\n return session\n }\n\n /** Remove a track session. Releases subscription with grace period. */\n removeTrack(trackName: string): void {\n const session = this.sessions.get(trackName)\n if (!session) return\n session.unsubscribe()\n\n // Release pool subscription\n const subKey = session.config.multicastKey ?? session.config.moqTrackName\n if (subKey) this.pool.releaseSubscription(subKey, trackName)\n\n session.dispose()\n this.sessions.delete(trackName)\n }\n\n // -----------------------------------------------------------------------\n // Atomic multi-track operations\n // -----------------------------------------------------------------------\n\n /**\n * All tracks with multicast RAP \u2192 multicast state (atomic).\n * Called when MediaRouter fires onSourceSwitch('multicast').\n * Prevents split-brain between video and audio.\n *\n * A takeover deadline can return a track from `joining` to `unicast` while\n * the multicast socket keeps delivering packets and the track keeps its FEC\n * decoder armed. If a valid RAP arrives later, that late-RAP edge suppresses\n * unicast and promotes multicast without a second fec-setup.\n */\n activateMulticast(): void {\n for (const [, session] of this.sessions) {\n if (session.state === 'unicast') {\n session.joinStarted()\n }\n if (session.state === 'joining') {\n session.rapReceived('multicast')\n }\n }\n }\n\n /**\n * All tracks with AMT RAP \u2192 amt state (atomic).\n */\n activateAmt(): void {\n for (const [, session] of this.sessions) {\n if (session.state === 'unicast') {\n session.joinStarted()\n }\n if (session.state === 'joining') {\n session.rapReceived('amt')\n }\n }\n }\n\n /**\n * All tracks \u2192 unicast (failback, atomic).\n * Called when MulticastManager fires onFailback().\n * unicast-fallback sessions are skipped \u2014 the host owns those subscriptions\n * and they must drain uninterrupted across transport-state events.\n *\n * Coherence invariant (BLO-9413): after this returns, every non-fallback\n * session is `unicast` (or `idle`), unsuppressed, and without a FEC decoder.\n * unsubscribe() unwinds any outstanding suppression regardless of the state\n * it tears down from (`failing` included; see TrackSession.#suppressFired),\n * and a session that a takeover timeout parked in `unicast` with its decoder\n * still armed is cycled too, because this transport edge is what releases\n * that decoder (unsubscribe fires fec-teardown).\n */\n failbackAll(): void {\n for (const [, session] of this.sessions) {\n const parkedWithFec = session.state === 'unicast' && session.isFecArmed\n if (\n parkedWithFec ||\n (session.state !== 'idle' &&\n session.state !== 'unicast' &&\n session.state !== 'unicast-fallback')\n ) {\n session.unsubscribe()\n session.subscribe() // re-enter unicast\n }\n }\n }\n\n /**\n * All tracks \u2192 unicast-fallback (atomic).\n * Called by the host when the multicast gateway is absent and\n * the player will subscribe to source tracks over MoQ unicast and feed\n * packets via MulticastManager.feedUnicastSource() (or manager.router\n * directly). Sessions in this state stay terminal until the host calls\n * unsubscribe() / disposes the SessionManager.\n */\n enterUnicastFallback(): void {\n for (const [, session] of this.sessions) {\n if (session.state === 'idle') continue\n session.enterUnicastFallback()\n }\n }\n\n /**\n * True if any session is currently in unicast-fallback. Hosts use this to\n * gate `multicastTrack.close()` on failback events \u2014 closing the shared\n * broadcast would kill the host's fallback drainers.\n */\n hasActiveFallback(): boolean {\n for (const [, session] of this.sessions) {\n if (session.isUnicastFallback) return true\n }\n return false\n }\n\n /**\n * All fallback tracks \u2192 unicast (atomic).\n * Called when the SSM bridge appears mid-session and the host has aborted\n * the fallback drainers. The session re-enters the regular preference chain\n * via joinStarted() (issued by the host immediately after).\n */\n exitUnicastFallback(): void {\n for (const [, session] of this.sessions) {\n if (session.isUnicastFallback) session.exitUnicastFallback()\n }\n }\n\n // -----------------------------------------------------------------------\n // Cleanup lifecycle\n // -----------------------------------------------------------------------\n\n /** Tab closed \u2014 release all subscriptions for this tab (grace period). */\n tabClosed(tabId: string): void {\n // All tracks owned by this tab \u2192 idle\n for (const [trackName, session] of this.sessions) {\n session.unsubscribe()\n this.pool.releaseAllForConsumer(trackName)\n }\n }\n\n /** Bridge WebTransport connection dropped \u2014 same as tab close. */\n bridgeDisconnected(): void {\n this.tabClosed('bridge')\n }\n\n /**\n * Track selection changed (user or ABR).\n * Old track released (grace period), new track subscribed.\n */\n trackSelectionChanged(oldTrackName: string, newConfig: TrackSessionConfig): void {\n this.removeTrack(oldTrackName)\n const session = this.addTrack(newConfig)\n session.subscribe()\n }\n\n // -----------------------------------------------------------------------\n // Query\n // -----------------------------------------------------------------------\n\n /** Get a track session by name. */\n getTrack(trackName: string): TrackSession | undefined {\n return this.sessions.get(trackName)\n }\n\n // -----------------------------------------------------------------------\n // Cleanup\n // -----------------------------------------------------------------------\n\n dispose(): void {\n this.#clearJoinDeferWarn()\n for (const [, session] of this.sessions) {\n session.dispose()\n }\n this.sessions.clear()\n this.pool.dispose()\n this.callbacks = null\n }\n}\n", "/**\n * MediaRouter \u2014 source arbitration for MoQ \u2194 multicast switching.\n *\n * Both moq-lib and moqtail wire their MoQ and multicast frame outputs\n * through this router. The router decides which source reaches the decoder:\n *\n * - MoQ frames pass through while multicast is inactive.\n * - Multicast video frames are suppressed until the first keyframe.\n * - Once multicast has both a video keyframe and audio, takeover is requested.\n * - MoQ is suppressed only after the source-switch callback completes.\n * - failbackToMoq() reverses the switch immediately.\n *\n * Per-track setTrackSource() allows individual tracks to be wired to a\n * specific transport source (video=multicast, audio=moq, overlay=amt) without\n * changing the binary MoQ\u2194multicast switching for other tracks.\n *\n * notifyGroupBoundary() is an observer hook: callers report the\n * packet-stamped groupId + media time for each group, and the router\n * cross-checks against the shared `align.ts` formula. Drift is emitted via\n * onGroupDrift so the player can bump the CMCD `x-bc-switch-drift-us` /\n * `x-bc-switch-miscount` counters. Observation only \u2014 does NOT alter routing.\n */\n\nimport { groupIdForTicks, driftCheck } from './align.js'\nimport { computeFecDeliveryWindowMs } from './track-session.js'\n\nexport type FrameMeta = {\n timestamp: number\n keyframe: boolean\n packetId?: number\n packetSequenceNumber?: number\n source?: 'moq' | 'multicast' | 'repair'\n recovered?: boolean\n sourceDiscontinuity?: boolean\n /**\n * Raw MMTP header timestamp (RFC 5905 short NTP, 32 bits): the publisher's\n * send-wall clock for the packet that carried this frame. On timed media it\n * is distinct from `timestamp`, the authored media presentation time. On a\n * non-timed MFU there is no authored presentation time, so `MmtpRouter`\n * derives `timestamp` from this same clock and the two carry no latency\n * between them. Populated from `RoutedFrameMeta.mmtpTimestamp` and\n * preserved by every re-emit on this router (multicast, MoQ, and repair) so\n * players can measure network ingress on the multicast legs; absent when\n * the packet header could not be read.\n */\n mmtpTimestamp?: bigint\n}\nexport type FrameKind = 'video' | 'audio'\nexport type SourceKind = 'moq' | 'multicast'\n\n/**\n * Tick-space timing for one group boundary \u2014 the exact, authoritative form.\n *\n * These are the integers the catalog already carries (`groupDurationTicks`,\n * `timescale`) plus the packet's raw timestamp in the same units. Passing\n * them straight through keeps the whole drift check in integer math.\n *\n * Prefer this over the seconds overload: `groupDurationTicks / timescale`\n * is not exactly representable for the common non-integer-second cadences\n * (33333@90k, 1001@30k, 1024@44.1k), and the seconds path has to quantize\n * to whole nanoseconds \u2014 which shifts `expected` by a whole group from the\n * second boundary onward and reports drift on a perfectly aligned stream.\n */\nexport interface GroupBoundaryTicks {\n /** Packet media timestamp in `timescale` units. Integer; negatives clamp to 0. */\n readonly mediaTimeTicks: number\n /** Group duration in `timescale` units. Positive integer. */\n readonly groupDurationTicks: number\n /**\n * Catalog timescale in Hz. Positive integer \u2014 **validated, and a hard gate**:\n * a non-integer or non-positive value skips the drift check entirely rather\n * than reporting against it. It does not feed the groupId computation (that\n * is `mediaTimeTicks / groupDurationTicks` alone), but it does derive the\n * `mediaTimeSec` / `groupDurationSec` on every GroupDriftEvent \u2014 so letting a\n * bad value through would push NaN/Infinity into CMCD `x-bc-switch-drift-us`,\n * which is worse than skipping.\n */\n readonly timescale: number\n}\n\n/** Payload emitted by MediaRouter.onGroupDrift when a packet-stamped groupId\n * disagrees with the shared `align.ts` formula. */\nexport interface GroupDriftEvent {\n trackName: string\n expectedGroupId: number\n actualGroupId: number\n /** `actual - expected` (positive = ahead, negative = behind). */\n deltaGroups: number\n /** Seconds view, kept for CMCD consumers. Derived when the caller used ticks. */\n mediaTimeSec: number\n groupDurationSec: number\n /** Exact tick-space inputs. Present only when the caller used the ticks form. */\n timing?: GroupBoundaryTicks\n}\n\n/** Normalized output of the two notifyGroupBoundary input forms. */\ntype ResolvedBoundary = {\n readonly expected: number\n readonly mediaTimeSec: number\n readonly groupDurationSec: number\n readonly timing?: GroupBoundaryTicks\n}\n\n/**\n * Distinct failure modes on the notifyGroupBoundary drift path. Each gets its\n * own bounded warn budget (see `#skipWithWarning`), so a stream that trips one\n * cannot permanently silence the diagnostic for a genuinely different one.\n *\n * Deliberately a closed union rather than `string`: the tag is the dedup key,\n * and a typo would silently mint a second budget for an existing reason.\n */\ntype GroupAlignSkipReason =\n | 'invalid-tick-inputs'\n // Currently UNREACHABLE, kept as defence in depth \u2014 see the catch in\n // #resolveTicks. Do not write a test chasing it.\n | 'ticks-formula-threw'\n | 'invalid-seconds-inputs'\n | 'sub-nanosecond-duration'\n | 'media-time-overflow'\n | 'seconds-formula-threw'\n | 'callback-threw'\n\n/**\n * Warns allowed per `GroupAlignSkipReason` for the lifetime of a router.\n *\n * Not a single flat number (PCL-2211, #329 review). The six resolver reasons\n * are closed, deterministic conditions: once you have seen\n * `sub-nanosecond-duration` on this router, the second occurrence carries no\n * new information, so one slot is the right budget and repeated malformed\n * catalog input stays silent.\n *\n * `callback-threw` is the opposite. It wraps arbitrary downstream consumer\n * code and interpolates `err.message` *because the error varies*. Under one\n * slot, a consumer that throws at startup permanently hides an unrelated\n * exception later \u2014 including one from a *replacement* consumer registered\n * through `onGroupDrift()`, which is a public setter with no budget reset.\n * That is the same argument `#skipWithWarning` makes against a single shared\n * boolean, one level down. A small cap bounds the flood, at the cost of\n * silencing distinct errors past the cap: three throws at startup exhaust\n * `callback-threw`, and a replacement consumer's unrelated exception is then\n * silenced permanently \u2014 the same failure as the one-slot budget, moved from\n * the 1st throw to the 4th. That residual is the inherent price of a bounded\n * budget and is accepted deliberately; the alternative is an unbounded warn.\n *\n * Deliberately NOT a reset on `onGroupDrift()` re-registration: that setter is\n * public and unthrottled, so a caller re-registering per boundary would\n * refresh the budget every time and restore the exact flood this prevents.\n *\n * A total `Record` rather than a lookup with a default: the union is closed, so\n * a new reason that forgets to declare its budget is a compile error \u2014 the\n * same typo-safety rationale that makes the union closed in the first place.\n */\nconst GROUP_ALIGN_WARN_BUDGET: Record<GroupAlignSkipReason, number> = {\n 'invalid-tick-inputs': 1,\n 'ticks-formula-threw': 1,\n 'invalid-seconds-inputs': 1,\n 'sub-nanosecond-duration': 1,\n 'media-time-overflow': 1,\n 'seconds-formula-threw': 1,\n 'callback-threw': 3,\n}\n\ntype FrameCb = (data: Uint8Array, meta: FrameMeta) => void\ntype SwitchCb = (source: SourceKind) => void | Promise<void>\n\nexport interface MediaRouterOptions {\n /** Set false for video-only streams. Default: true. */\n requireAudio?: boolean\n /**\n * Audio fallback timeout (ms): force multicast activation if video keyframe\n * arrived but audio hasn't within this window. Catalog-derived via\n * computeFecDeliveryWindowMs (the single FEC recovery-window source of truth).\n * Omit to disable the independent audio-fallback timer (no magic default).\n */\n audioFallbackMs?: number\n /**\n * Number of binary-path frames to allow through during a crossfade transition.\n * Derive from FEC block size (e.g., ceil(K / groupsPerBlock)). Default: 10.\n */\n crossfadeFrames?: number\n /**\n * Max pre-boundary overlay frames to buffer before dropping.\n * Derive from FEC config (e.g., ceil(K * 1.5)). Default: 128.\n */\n maxOverlayBuffer?: number\n /**\n * Max concurrent in-flight repairs. Prevents relay SUBSCRIBE flood (T-13-01 mitigation).\n * Default: 2.\n */\n maxRepairInFlight?: number\n /**\n * Allow multicast takeover from a delta frame after the player has confirmed\n * that MoQ already seeded the same decoder timeline with a video keyframe.\n * Default false: decoder-reset paths still need multicast to provide a RAP.\n */\n allowDeltaMulticastTakeoverAfterMoqKeyframe?: boolean\n}\n\n/**\n * A per-track source that emits frames independently of the binary MoQ/multicast path.\n * Used by setTrackSource() to wire specific tracks to specific transport sources.\n */\nexport interface TrackSource {\n name: string\n /**\n * Register a frame callback. Returns an unsubscribe function.\n * MediaRouter calls unsubscribe() when clearTrackSource() is called.\n */\n onFrame(cb: (data: Uint8Array, meta: FrameMeta) => void): () => void\n /**\n * Optional error callback for when the source fails.\n * MediaRouter uses this to trigger failback to binary switching for this track.\n */\n onError?(cb: () => void): () => void\n /** Optional dispose hook called when clearTrackSource() is called. */\n dispose?(): void\n}\n\n/**\n * Thrown when setTrackSource() is called for a track that already has a source\n * without an intervening clearTrackSource(). Prevents silent concurrent-assignment\n * races (T-02-16 mitigation).\n */\nexport class TrackSourceConflictError extends Error {\n constructor(public readonly trackName: string) {\n super(`Track source already assigned for '${trackName}'; call clearTrackSource first`)\n this.name = 'TrackSourceConflictError'\n }\n}\n\n/**\n * Migration policy for setTrackSource() transport switching.\n *\n * - 'crossfade': Overlap old (binary) and new source briefly (CROSSFADE_WINDOW_FRAMES),\n * then suppress the binary path. Default for audio.\n * - 'drop': Cut to new source immediately. Binary path suppressed at once.\n * Suitable for latency-critical tracks.\n * - 'wait': Defer migration until first FEC block boundary (same as overlay=true).\n * Default for video \u2014 avoids decoder reset mid-block.\n */\nexport type MigrationPolicy = 'crossfade' | 'drop' | 'wait'\n\n/** Default crossfade window \u2014 override via MediaRouterOptions.crossfadeFrames. */\nconst DEFAULT_CROSSFADE_FRAMES = 10\n\n/** Options passed to setTrackSource(). */\nexport interface SetTrackSourceOptions {\n /**\n * If true, this source is an overlay track that must wait for the first FEC\n * block boundary signal (via notifyFecBlockBoundary()) before emitting frames.\n * Frames arriving before the first boundary are buffered up to MAX_OVERLAY_BUFFER.\n *\n * Backwards compat: equivalent to policy: 'wait'.\n */\n overlay?: boolean\n /**\n * Migration policy for the transport switch. Overrides `overlay` when provided.\n * See MigrationPolicy for semantics.\n */\n policy?: MigrationPolicy\n}\n\n/** Default overlay buffer cap \u2014 override via MediaRouterOptions.maxOverlayBuffer. */\nconst DEFAULT_MAX_OVERLAY_BUFFER = 128\n\n/** Internal per-track source record. */\ninterface TrackSourceRecord {\n source: TrackSource\n unsubscribeFrame: () => void\n unsubscribeError?: () => void\n emitCount: number\n}\n\nexport class MediaRouter {\n #active: SourceKind = 'moq'\n #multicastVideoKeyed = false\n #multicastAudioReceived = false\n #moqVideoKeyframeEmitted = false\n #requireAudio: boolean\n #suppressed = false // true after multicast confirmed \u2014 suppresses MoQ\n #audioFallbackTimer: ReturnType<typeof setTimeout> | null = null\n\n // Configurable constants (from catalog/FEC config, not magic numbers)\n readonly #audioFallbackMs: number\n readonly #crossfadeFrames: number\n readonly #maxOverlayBuffer: number\n readonly #allowDeltaMulticastTakeoverAfterMoqKeyframe: boolean\n\n // \u2500\u2500 Keyframe repair state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Groups currently being repaired \u2014 idempotent guard per Pitfall 2 (T-13-01 mitigation) */\n #repairInFlight = new Set<number>()\n /** Max concurrent repairs \u2014 prevents relay SUBSCRIBE flood (T-13-01 mitigation) */\n readonly #maxRepairInFlight: number\n /** Callback to request MoQ subscribe for a specific group (wired by player) */\n #onRepairRequest: ((expectedGroupId: number, trackName: string) => void) | null = null\n\n #onVideoFrame: FrameCb | null = null\n #onAudioFrame: FrameCb | null = null\n #onOverlayFrame: FrameCb | null = null\n #onSourceSwitch: SwitchCb | null = null\n #sourceSwitchReady: Promise<void> | null = null\n #sourceSwitchToken = 0\n #pendingMulticastToken: number | null = null\n #pendingMulticastVideo: { data: Uint8Array; meta: FrameMeta } | null = null\n #pendingMulticastAudio: { data: Uint8Array; meta: FrameMeta } | null = null\n\n // Per-track source state\n #trackSources = new Map<string, TrackSourceRecord>()\n\n // Track type registry: trackName \u2192 { type, source }.\n // Init data / inline signaling is authoritative until catalog updates.\n // Priority: 'init' > 'catalog' > 'name' (backward compat fallback).\n #trackTypes = new Map<string, { type: FrameKind; source: 'catalog' | 'init' }>()\n\n // Crossfade state: maps trackName \u2192 remaining binary-path frames allowed during window\n #crossfadeCounters = new Map<string, number>()\n\n // Overlay alignment state\n #overlayBoundaryReached = false\n #overlayBuffer: Array<{ data: Uint8Array; meta: FrameMeta }> = []\n\n // \u2500\u2500 Phase 14: deltaActive state machine (D-11..D-14) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // No timers \u2014 state transitions driven entirely by notifyDeltaBlock() callbacks.\n // All thresholds derived from catalog fields or throw at configureDelta() time.\n #deltaConfigured = false\n #deltaActive: boolean = true\n #deltaWindow: boolean[] = [] // ring buffer: true = block failed\n #deltaWindowSize: number = 0\n #deltaFailThresholdRatio: number = 0 // P/K\n #deltaRecoverThresholdRatio: number = 0 // (P/K)/2 \u2014 hysteresis (D-13)\n #deltaProbeIntervalMs: number = 0\n #lastProbeAt: number = 0\n #onDeltaFallbackCb: (() => void) | null = null\n #onDeltaRecoverCb: (() => void) | null = null\n\n constructor(options?: MediaRouterOptions) {\n this.#requireAudio = options?.requireAudio ?? true\n // Catalog-derived \u2014 the caller passes an audioFallbackMs computed from the\n // FEC recovery window (computeFecDeliveryWindowMs). No magic default: when\n // absent, the independent audio-fallback timer is disabled (0) and\n // activation waits for real audio arrival.\n this.#audioFallbackMs = options?.audioFallbackMs ?? 0\n this.#crossfadeFrames = options?.crossfadeFrames ?? DEFAULT_CROSSFADE_FRAMES\n this.#maxOverlayBuffer = options?.maxOverlayBuffer ?? DEFAULT_MAX_OVERLAY_BUFFER\n this.#maxRepairInFlight = options?.maxRepairInFlight ?? 2\n this.#allowDeltaMulticastTakeoverAfterMoqKeyframe =\n options?.allowDeltaMulticastTakeoverAfterMoqKeyframe ?? false\n }\n\n onVideoFrame(cb: FrameCb) { this.#onVideoFrame = cb }\n onAudioFrame(cb: FrameCb) { this.#onAudioFrame = cb }\n onOverlayFrame(cb: FrameCb) { this.#onOverlayFrame = cb }\n onSourceSwitch(cb: SwitchCb) { this.#onSourceSwitch = cb }\n\n // \u2500\u2500 Group-alignment observer (align.ts formula) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Observation only \u2014 does NOT alter routing. Producers are wired in\n // follow-up PRs; when they land they will call\n // CmcdProducer.incrementSwitchMiscount() + emitSwitchDrift() from the\n // onGroupDrift callback so divergence between packet-stamped groupIds\n // and the shared formula surfaces on `x-bc-switch-drift-us` /\n // `x-bc-switch-miscount`. Canonical Go impl: Blockcast/multicast\n // cmd/caddy/sender/group_align.go (commit 104eeff). Canonical Rust impl:\n // moqtail/moqtail apps/relay/src/server/abr.rs (branch\n // experimental/server-side-abr, commit 39accbf).\n #onGroupDrift: ((evt: GroupDriftEvent) => void) | null = null\n #groupAlignWarnCounts = new Map<GroupAlignSkipReason, number>()\n onGroupDrift(cb: (evt: GroupDriftEvent) => void): void {\n this.#onGroupDrift = cb\n }\n\n /**\n * Report a group boundary observed on an incoming track. Cross-checks the\n * packet-stamped groupId against the shared `align.ts` formula and fires\n * the onGroupDrift callback when they disagree.\n *\n * Two input forms:\n * - **Ticks (preferred).** `notifyGroupBoundary(track, id, { mediaTimeTicks,\n * groupDurationTicks, timescale })` \u2014 pure integer math via\n * `align.groupIdForTicks`, no rounding anywhere.\n * - **Seconds (deprecated).** The 4-argument form. Quantizes both operands\n * to whole nanoseconds, which is exact only when `groupDurationSec` is a\n * whole number of nanoseconds. It is not for 33333@90k, 1001@30k or\n * 1024@44.1k, and there `expected` diverges by a whole group from the\n * second boundary onward \u2014 a false drift event on every subsequent\n * group, and a systematically wrong CMCD `x-bc-switch-drift-us`.\n *\n * No-op when no onGroupDrift callback is registered (avoid unnecessary work\n * on hot paths).\n *\n * Hot-path robustness (does NOT throw on bad inputs \u2014 the ingest stream\n * must not be torn down by a malformed catalog or a disposed producer):\n * - Invalid duration (NaN / <=0) or non-finite media time \u2192 warn + early\n * return (same convention as audioFallbackMs).\n * - Any throw out of the align formula (e.g. the safe-integer overflow\n * guard at ~104 days of media time on the seconds path) is caught +\n * logged so an unusually long-running stream cannot tear down ingest.\n * - Callback throws are caught + logged; ingest continues.\n * - Skip warnings are coalesced **per failure mode** for the lifetime\n * of the router (never reset, including across `dispose()`), so a hot\n * path cannot flood the log while a genuinely new failure mode still\n * gets heard. Deterministic modes get one line; a throwing consumer\n * callback gets a small budget because its error varies. See\n * `#skipWithWarning` and `GROUP_ALIGN_WARN_BUDGET`.\n *\n * Init-track filter: media time === 0 with a non-zero stamped groupId is\n * treated as an init/ambient track emitting pre-PTS-zero packets and is\n * skipped (matches Go's base-clamp intent without producing spurious\n * drift).\n *\n * NOTE: do NOT call from the repair path (feedRepair). Repair frames carry\n * the groupId they are recovering for, not a freshly-stamped one.\n */\n notifyGroupBoundary(\n trackName: string,\n packetGroupId: number,\n timing: GroupBoundaryTicks,\n ): void\n /**\n * @deprecated Pass a {@link GroupBoundaryTicks} instead. The seconds form\n * rounds to whole nanoseconds and reports phantom drift on catalogs whose\n * `groupDurationTicks / timescale` is not ns-exact.\n */\n notifyGroupBoundary(\n trackName: string,\n packetGroupId: number,\n mediaTimeSec: number,\n groupDurationSec: number,\n ): void\n notifyGroupBoundary(\n trackName: string,\n packetGroupId: number,\n timingOrMediaTimeSec: GroupBoundaryTicks | number,\n groupDurationSec?: number,\n ): void {\n if (!this.#onGroupDrift) return\n\n const resolved =\n typeof timingOrMediaTimeSec === 'object' && timingOrMediaTimeSec !== null\n ? this.#resolveTicks(trackName, timingOrMediaTimeSec)\n : this.#resolveSeconds(\n trackName,\n timingOrMediaTimeSec as number,\n groupDurationSec as number,\n )\n if (!resolved) return\n\n // Init/ambient track heuristic: mediaTime=0 with stamped groupId !== 0\n // is a signaling packet pre-PTS-zero, not a real drift. Skipping here\n // avoids every stream opening with a false drift event.\n if (resolved.mediaTimeSec === 0 && packetGroupId !== 0) return\n\n const expected = resolved.expected\n const result = driftCheck(expected, packetGroupId)\n if (result.kind === 'aligned') return\n\n try {\n this.#onGroupDrift({\n trackName,\n expectedGroupId: expected,\n actualGroupId: packetGroupId,\n deltaGroups: result.deltaGroups,\n mediaTimeSec: resolved.mediaTimeSec,\n groupDurationSec: resolved.groupDurationSec,\n ...(resolved.timing ? { timing: resolved.timing } : {}),\n })\n } catch (err) {\n // A disposed CmcdProducer (or any downstream consumer) throwing here\n // must NOT tear down the MoQ ingest stream. Log and continue.\n //\n // Routed through the same per-reason budget as the resolver skips: this\n // fires once per DRIFT EVENT, so a consumer that throws on every\n // boundary would otherwise flood at boundary rate \u2014 exactly the failure\n // mode #skipWithWarning exists to prevent, and exactly the disposed-\n // producer scenario this comment already cites (#329 review).\n this.#skipWithWarning(\n 'callback-threw',\n `[MediaRouter] onGroupDrift callback threw (track=${trackName} expected=${expected} actual=${packetGroupId}); continuing: ${(err as Error)?.message ?? err}`,\n )\n }\n }\n\n /**\n * Warn at most `GROUP_ALIGN_WARN_BUDGET[reason]` times **per reason**, across\n * every skip and post-emit failure on the drift path.\n *\n * Note the two call shapes: the resolvers call this *instead of* computing a\n * groupId, and return its `null` to skip the drift check; the `onGroupDrift`\n * catch calls it after the check already ran and the event was already\n * emitted, so there only the warn is coalesced and the `null` is discarded.\n *\n * Keyed on a short stable `reason` tag, NOT on the formatted message: the\n * messages interpolate track name and operand values, so message-keying\n * would hand a malformed stream a fresh warn slot on every boundary \u2014 the\n * log flood this coalescing exists to prevent.\n *\n * Per-reason rather than one shared boolean (PCL-2211, #329 review): the\n * budget is never reset \u2014 not by `dispose()`, not on source switch \u2014 so a\n * single flag means the FIRST malformed boundary of a long-running stream\n * permanently silences every later, genuinely different failure mode. The\n * throw/overflow diagnostics carry the operand values (`ticks=`, `durTicks=`,\n * `err.message`) an incident responder actually needs, and under one shared\n * flag those are precisely the ones most likely to be already spent by an\n * unrelated NaN at catalog load.\n *\n * A closed, bounded set of reasons times a small per-reason budget is still\n * bounded, so this cannot flood. See `GROUP_ALIGN_WARN_BUDGET` for why the\n * budget is not uniform.\n */\n #skipWithWarning(reason: GroupAlignSkipReason, message: string): null {\n const seen = this.#groupAlignWarnCounts.get(reason) ?? 0\n if (seen < GROUP_ALIGN_WARN_BUDGET[reason]) {\n this.#groupAlignWarnCounts.set(reason, seen + 1)\n console.warn(message)\n }\n return null\n }\n\n /**\n * Exact path: integers straight from the catalog, no rounding. `mediaTimeSec`\n * / `groupDurationSec` are derived for reporting only and never feed the\n * groupId computation.\n */\n #resolveTicks(\n trackName: string,\n timing: GroupBoundaryTicks,\n ): ResolvedBoundary | null {\n const { mediaTimeTicks, groupDurationTicks, timescale } = timing\n if (\n !Number.isInteger(mediaTimeTicks) ||\n !Number.isInteger(groupDurationTicks) ||\n groupDurationTicks <= 0 ||\n !Number.isInteger(timescale) ||\n timescale <= 0\n ) {\n return this.#skipWithWarning(\n 'invalid-tick-inputs',\n `[MediaRouter] notifyGroupBoundary invalid tick inputs (track=${trackName} mediaTimeTicks=${mediaTimeTicks} groupDurationTicks=${groupDurationTicks} timescale=${timescale}); skipping drift check. Pre-validate at catalog load time.`,\n )\n }\n try {\n return {\n expected: groupIdForTicks(mediaTimeTicks, groupDurationTicks),\n mediaTimeSec: mediaTimeTicks / timescale,\n groupDurationSec: groupDurationTicks / timescale,\n // Snapshot, not the caller's reference: a producer that reuses one\n // scratch object per boundary would otherwise retroactively mutate\n // every GroupDriftEvent it has already emitted. Three integers.\n timing: { mediaTimeTicks, groupDurationTicks, timescale },\n }\n } catch (err) {\n // UNREACHABLE as of today, and deliberately kept. groupIdForTicks throws\n // on exactly two conditions \u2014 !Number.isInteger(ticks) and\n // !Number.isInteger(groupDurationTicks) || groupDurationTicks <= 0 \u2014 and\n // the guard above pre-rejects both; Math.floor(a / b) does not throw.\n //\n // Kept because align.ts is a separate module that can grow a new\n // precondition (a safe-integer check, say) without this file changing,\n // and the no-throw contract must hold on that day too. Nobody should\n // write a test chasing this branch \u2014 see BLO-21176 note.\n //\n // NOTE the asymmetry this implies: the seconds path is the only one that\n // can actually reach its catch, because durTicks <= 0 cannot catch\n // Infinity and Number.isSafeInteger guards only `ticks`. That is the real\n // shape of the AC#5a bug, not an oversight in this resolver.\n return this.#skipWithWarning(\n 'ticks-formula-threw',\n `[MediaRouter] notifyGroupBoundary: groupIdForTicks threw (track=${trackName} mediaTimeTicks=${mediaTimeTicks} groupDurationTicks=${groupDurationTicks}); skipping drift check: ${(err as Error)?.message ?? err}`,\n )\n }\n }\n\n /**\n * Legacy seconds path. Quantizes to a synthetic 1e9 Hz timescale \u2014 the exact\n * behaviour the deprecated `align.groupIdFor` wrapper had, reproduced here so\n * that wrapper has no non-test callers left and can be deleted (BLO-21176).\n *\n * Inherits that wrapper's ns-rounding error; see the `@deprecated` overload.\n * Delete this branch once every caller passes ticks.\n */\n #resolveSeconds(\n trackName: string,\n mediaTimeSec: number,\n groupDurationSec: number,\n ): ResolvedBoundary | null {\n if (\n !Number.isFinite(groupDurationSec) ||\n groupDurationSec <= 0 ||\n !Number.isFinite(mediaTimeSec)\n ) {\n return this.#skipWithWarning(\n 'invalid-seconds-inputs',\n `[MediaRouter] notifyGroupBoundary invalid inputs (track=${trackName} mediaTimeSec=${mediaTimeSec} groupDurationSec=${groupDurationSec}); skipping drift check. Pre-validate at catalog load time.`,\n )\n }\n // 1e9 Hz keeps both operands inside MAX_SAFE_INTEGER for ~104 days of\n // media time. Past that Math.round yields a non-safe integer that\n // Number.isInteger still accepts, so bail explicitly rather than\n // silently quantizing \u2014 ingest must survive either way.\n const TS = 1_000_000_000\n const ticks = mediaTimeSec < 0 ? 0 : Math.round(mediaTimeSec * TS)\n const durTicks = Math.round(groupDurationSec * TS)\n if (durTicks <= 0) {\n return this.#skipWithWarning(\n 'sub-nanosecond-duration',\n `[MediaRouter] notifyGroupBoundary: groupDurationSec=${groupDurationSec} rounds to <1 tick at 1e9 Hz (track=${trackName}); skipping drift check. Pass GroupBoundaryTicks for sub-nanosecond durations.`,\n )\n }\n if (!Number.isSafeInteger(ticks)) {\n return this.#skipWithWarning(\n 'media-time-overflow',\n `[MediaRouter] notifyGroupBoundary: mediaTimeSec=${mediaTimeSec} overflows safe-integer ticks at 1e9 Hz (>~104 days, track=${trackName}); skipping drift check. Pass GroupBoundaryTicks with the catalog timescale.`,\n )\n }\n // Same try as #resolveTicks: a finite groupDurationSec can still overflow\n // the * 1e9 multiply to Infinity, which clears the durTicks <= 0 bail above\n // but fails Number.isInteger inside groupIdForTicks. Without this catch the\n // throw escapes notifyGroupBoundary and breaks its documented no-throw\n // contract \u2014 the one path #resolveTicks already guards and this did not.\n try {\n return {\n expected: groupIdForTicks(ticks, durTicks),\n mediaTimeSec,\n groupDurationSec,\n }\n } catch (err) {\n return this.#skipWithWarning(\n 'seconds-formula-threw',\n `[MediaRouter] notifyGroupBoundary: groupIdForTicks threw (track=${trackName} mediaTimeSec=${mediaTimeSec} groupDurationSec=${groupDurationSec} ticks=${ticks} durTicks=${durTicks}); skipping drift check: ${(err as Error)?.message ?? err}`,\n )\n }\n }\n\n get activeSource(): SourceKind { return this.#active }\n\n // \u2500\u2500 Keyframe repair API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Register callback for keyframe repair requests. Player wires this to issue MoQ SUBSCRIBE. */\n onRepairRequest(cb: (expectedGroupId: number, trackName: string) => void): void {\n this.#onRepairRequest = cb\n }\n\n /**\n * Request repair for a lost keyframe group. Only fires when activeSource is 'multicast'.\n * Idempotent per groupId \u2014 duplicate calls for the same group are suppressed.\n * @param expectedGroupId - The group ID expected but not received\n * @param trackName - Track name for the SUBSCRIBE (e.g. 'video'). Default: 'video'.\n */\n repairLostGroup(expectedGroupId: number, trackName = 'video'): void {\n if (this.#active !== 'multicast') return // only repair on multicast path\n if (this.#repairInFlight.has(expectedGroupId)) return // idempotent\n if (this.#repairInFlight.size >= this.#maxRepairInFlight) {\n console.warn(\n `[MediaRouter] max repair in flight (${this.#maxRepairInFlight}), dropping repair for group ${expectedGroupId}`,\n )\n return\n }\n this.#repairInFlight.add(expectedGroupId)\n this.#onRepairRequest?.(expectedGroupId, trackName)\n }\n\n /**\n * Feed a recovered keyframe frame from the repair path.\n * Bypasses source arbitration entirely \u2014 goes directly to decoder callbacks.\n * Does NOT change activeSource. Does NOT trigger failbackToMoq.\n */\n feedRepair(data: Uint8Array, meta: FrameMeta, kind: FrameKind): void {\n // Repair only makes sense when multicast is active.\n // Silently drop if MoQ became active (race with failbackToMoq) to avoid\n // injecting stale-timestamp frames into the MoQ decoder path (WR-02).\n if (this.#active !== 'multicast') return\n const routedMeta = { ...meta, source: 'repair' as const, recovered: true }\n if (kind === 'video') this.#onVideoFrame?.(data, routedMeta)\n else this.#onAudioFrame?.(data, routedMeta)\n }\n\n /**\n * Clear repair-in-flight state for a group (called after repair completes or times out).\n */\n clearRepairInFlight(groupId: number): void {\n this.#repairInFlight.delete(groupId)\n }\n\n // \u2500\u2500 Phase 14: deltaActive state machine API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Configure the delta-track fallback state machine from catalog parameters.\n *\n * D-11: Thresholds derive from fec.sourceSymbols, fec.repairSymbols, framerate.\n * D-13: Probe interval derives from deltaProbeIntervalMs or interleaveDepthMs*2.\n * CLAUDE.md: error on bad init \u2014 throws if required inputs are absent.\n *\n * Calling again resets deltaActive=true and clears the window buffer (stream restart).\n */\n configureDelta(cfg: {\n framerate: number\n sourceSymbols: number\n repairSymbols: number\n deltaFailWindowBlocks?: number\n deltaProbeIntervalMs?: number\n interleaveDepthMs?: number\n }): void {\n if (typeof cfg.framerate !== 'number' || !Number.isFinite(cfg.framerate) || cfg.framerate <= 0) {\n throw new Error('[MediaRouter] configureDelta: framerate required and must be > 0')\n }\n if (typeof cfg.sourceSymbols !== 'number' || cfg.sourceSymbols <= 0) {\n throw new Error('[MediaRouter] configureDelta: sourceSymbols (K_delta) required and must be > 0')\n }\n if (typeof cfg.repairSymbols !== 'number' || cfg.repairSymbols <= 0) {\n throw new Error('[MediaRouter] configureDelta: repairSymbols (P_delta) required and must be > 0')\n }\n if (cfg.deltaProbeIntervalMs === undefined && cfg.interleaveDepthMs === undefined) {\n throw new Error(\n '[MediaRouter] configureDelta: either deltaProbeIntervalMs or interleaveDepthMs required for probe interval derivation'\n )\n }\n\n // Derivations \u2014 no magic floors, no hardcoded defaults (CLAUDE.md).\n this.#deltaWindowSize = cfg.deltaFailWindowBlocks ?? Math.ceil(cfg.framerate)\n this.#deltaFailThresholdRatio = cfg.repairSymbols / cfg.sourceSymbols\n this.#deltaRecoverThresholdRatio = this.#deltaFailThresholdRatio / 2\n // Without an explicit probe interval, use one complete signaled block span.\n this.#deltaProbeIntervalMs = cfg.deltaProbeIntervalMs ?? computeFecDeliveryWindowMs({\n interleaveDepthMs: cfg.interleaveDepthMs!,\n sourceSymbols: cfg.sourceSymbols,\n })\n\n // Reset state \u2014 useful for stream restart.\n this.#deltaActive = true\n this.#deltaWindow = []\n this.#lastProbeAt = 0\n this.#deltaConfigured = true\n }\n\n /**\n * Notify the state machine of a completed FEC block for the delta track.\n *\n * @param failed - true if the block was unrecoverable (FEC failure)\n * @param nowMs - caller-injected monotonic ms (no internal timer \u2014 D-13, CLAUDE.md)\n *\n * If configureDelta() has not been called, this is a silent no-op (pre-catalog state).\n */\n notifyDeltaBlock(failed: boolean, nowMs: number): void {\n if (!this.#deltaConfigured) return\n\n // Maintain sliding window \u2014 ring buffer semantics.\n this.#deltaWindow.push(failed)\n if (this.#deltaWindow.length > this.#deltaWindowSize) {\n this.#deltaWindow.shift()\n }\n\n // Window not yet full \u2014 insufficient data for decision.\n if (this.#deltaWindow.length < this.#deltaWindowSize) return\n\n const failedCount = this.#deltaWindow.filter(x => x).length\n const ratio = failedCount / this.#deltaWindowSize\n\n if (this.#deltaActive) {\n // Fallback transition: active \u2192 inactive (T-14-03: fires exactly once)\n if (ratio > this.#deltaFailThresholdRatio) {\n this.#deltaActive = false\n this.#lastProbeAt = nowMs\n this.#onDeltaFallbackCb?.()\n }\n } else {\n // Recovery transition: inactive \u2192 active (after probe interval + low ratio)\n if (\n (nowMs - this.#lastProbeAt) >= this.#deltaProbeIntervalMs &&\n ratio < this.#deltaRecoverThresholdRatio\n ) {\n this.#deltaActive = true\n this.#lastProbeAt = nowMs\n this.#onDeltaRecoverCb?.()\n }\n }\n }\n\n /** Register callback fired when delta track degrades past threshold (D-12). */\n onDeltaFallback(cb: () => void): void {\n this.#onDeltaFallbackCb = cb\n }\n\n /** Register callback fired when delta track recovers below recovery threshold (D-13). */\n onDeltaRecover(cb: () => void): void {\n this.#onDeltaRecoverCb = cb\n }\n\n /** Whether the delta track is currently considered healthy (true = active). */\n get deltaActive(): boolean {\n return this.#deltaActive\n }\n\n // \u2500\u2500 Test-visible accessors for threshold verification \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // These expose internal derived values for test assertions (Tests 3,4,5,6,7).\n // Prefixed with 'delta' to namespace clearly within the public API surface.\n\n /** Derived window size \u2014 exposed for test assertions (Test 3, 4). */\n get deltaWindowSize(): number { return this.#deltaWindowSize }\n /** Derived fail threshold ratio (P/K) \u2014 exposed for test assertions (Test 6). */\n get deltaFailThresholdRatio(): number { return this.#deltaFailThresholdRatio }\n /** Derived recovery threshold ratio ((P/K)/2) \u2014 exposed for test assertions (Test 7). */\n get deltaRecoverThresholdRatio(): number { return this.#deltaRecoverThresholdRatio }\n /** Derived probe interval ms \u2014 exposed for test assertions (Test 5a). */\n get deltaProbeIntervalMs(): number { return this.#deltaProbeIntervalMs }\n\n /**\n * Register a track name \u2192 type mapping from catalog.\n * Catalog is the default authority. Init data / inline signaling\n * takes precedence until the next catalog update.\n */\n registerTrackType(trackName: string, type: FrameKind): void {\n // Catalog overwrites any previous registration (including init).\n this.#trackTypes.set(trackName, { type, source: 'catalog' })\n }\n\n /**\n * Register a track name \u2192 type from init data / inline signaling (MMTP FT=0).\n * Authoritative until the next catalog update per \u00A75.3.\n * Does NOT overwrite an existing catalog registration.\n */\n registerTrackTypeFromInit(trackName: string, type: FrameKind): void {\n const existing = this.#trackTypes.get(trackName)\n if (existing?.source === 'catalog') return // catalog already set \u2014 don't downgrade\n this.#trackTypes.set(trackName, { type, source: 'init' })\n }\n\n /**\n * Assign a per-track source. Frames from this source bypass the binary\n * MoQ\u2194multicast switching for this track only.\n *\n * Throws TrackSourceConflictError if a source is already assigned for this\n * track without a clearTrackSource() in between.\n */\n setTrackSource(trackName: string, source: TrackSource, opts?: SetTrackSourceOptions): void {\n if (this.#trackSources.has(trackName)) {\n throw new TrackSourceConflictError(trackName)\n }\n\n // Resolve effective policy. opts.policy takes precedence; overlay=true is legacy 'wait'.\n const effectivePolicy: MigrationPolicy | undefined =\n opts?.policy ?? (opts?.overlay ? 'wait' : undefined)\n\n // For crossfade: open the binary-path window immediately so the first per-track frame\n // triggers the window (counter starts before the frame callback is wired).\n if (effectivePolicy === 'crossfade') {\n this.#crossfadeCounters.set(trackName, this.#crossfadeFrames)\n }\n\n const record: TrackSourceRecord = {\n source,\n unsubscribeFrame: () => {},\n emitCount: 0,\n }\n\n // Wire the frame callback\n record.unsubscribeFrame = source.onFrame((data, meta) => {\n record.emitCount++\n if (effectivePolicy === 'wait') {\n this.#handleOverlayFrame(data, meta)\n } else {\n // 'drop', 'crossfade', or undefined: emit immediately\n this.#emitForTrack(trackName, data, meta)\n }\n })\n\n // Wire the optional error callback \u2014 failback to binary switching\n if (source.onError) {\n record.unsubscribeError = source.onError(() => {\n this.clearTrackSource(trackName)\n })\n }\n\n this.#trackSources.set(trackName, record)\n }\n\n /**\n * Remove the per-track source for the given track.\n * Binary switching resumes for this track after this call.\n */\n clearTrackSource(trackName: string): void {\n const record = this.#trackSources.get(trackName)\n if (!record) return\n\n record.unsubscribeFrame()\n record.unsubscribeError?.()\n record.source.dispose?.()\n this.#trackSources.delete(trackName)\n\n // Clean up crossfade window if one was active for this track\n this.#crossfadeCounters.delete(trackName)\n\n // Reset overlay buffer if removing a non-media track (overlay/unknown)\n const reg = this.#trackTypes.get(trackName)\n const isMedia = reg?.type === 'video' || reg?.type === 'audio' ||\n (reg === undefined && (trackName === 'video' || trackName === 'audio'))\n if (!isMedia) {\n this.#overlayBoundaryReached = false\n this.#overlayBuffer = []\n }\n }\n\n /**\n * Signal that a FEC block boundary has been reached on the base track.\n * Overlay tracks waiting for alignment flush their buffered frames now.\n */\n notifyFecBlockBoundary(): void {\n if (this.#overlayBoundaryReached) return\n this.#overlayBoundaryReached = true\n\n // Flush buffered overlay frames\n const buffered = this.#overlayBuffer.splice(0)\n for (const { data, meta } of buffered) {\n this.#onOverlayFrame?.(data, meta)\n }\n }\n\n /**\n * Return the number of frames emitted from the per-track source for a given\n * track. Used in test-mode to verify per-track routing histogram.\n * Returns 0 if no per-track source is active for the track.\n */\n trackSourceEmitCount(trackName: string): number {\n return this.#trackSources.get(trackName)?.emitCount ?? 0\n }\n\n /** Feed a frame from the MoQ path. Suppressed when multicast is active OR a per-track source owns this track. */\n feedMoq(data: Uint8Array, meta: FrameMeta, kind: FrameKind) {\n // Per-track source takes precedence; allow through during crossfade window\n if (this.#trackSources.has(kind)) {\n const remaining = this.#crossfadeCounters.get(kind)\n if (remaining && remaining > 0) {\n // Decrement crossfade counter and allow this frame through\n const next = remaining - 1\n if (next === 0) {\n this.#crossfadeCounters.delete(kind)\n } else {\n this.#crossfadeCounters.set(kind, next)\n }\n // Fall through to emit below (no return)\n } else {\n return // suppressed \u2014 no crossfade window active\n }\n }\n if (this.#suppressed) return\n // Audio suppression is handled by SessionManager onSuppress callback \u2014\n // do NOT independently suppress based on multicastAudioReceived.\n // The state machine decides when to switch; the router just routes.\n const routedMeta = { ...meta, source: 'moq' as const }\n if (kind === 'video') this.#onVideoFrame?.(data, routedMeta)\n else this.#onAudioFrame?.(data, routedMeta)\n }\n\n /** Feed a frame from the multicast path. Video waits for keyframe before activating. */\n feedMulticast(data: Uint8Array, meta: FrameMeta, kind: FrameKind) {\n // Per-track source takes precedence; allow through during crossfade window\n if (this.#trackSources.has(kind)) {\n const remaining = this.#crossfadeCounters.get(kind)\n if (remaining && remaining > 0) {\n const next = remaining - 1\n if (next === 0) {\n this.#crossfadeCounters.delete(kind)\n } else {\n this.#crossfadeCounters.set(kind, next)\n }\n // Fall through to emit below (no return)\n } else {\n return // suppressed\n }\n }\n\n if (kind === 'video') {\n if (!this.#multicastVideoKeyed) {\n const moqSeededDelta =\n !meta.keyframe &&\n this.#allowDeltaMulticastTakeoverAfterMoqKeyframe &&\n this.#moqVideoKeyframeEmitted\n if (!meta.keyframe && !moqSeededDelta) return // drop until first safe decode point\n this.#multicastVideoKeyed = true\n const pendingMeta: FrameMeta = { ...meta, source: 'multicast' }\n if (!moqSeededDelta) pendingMeta.sourceDiscontinuity = true\n this.#pendingMulticastVideo = {\n data: data.slice(),\n meta: pendingMeta,\n }\n // If audio is required but hasn't arrived yet, start a fallback timer.\n // Audio FEC blocks may recover after video \u2014 don't block activation forever.\n // Only arms when a catalog-derived audioFallbackMs was supplied (>0).\n if (this.#requireAudio && this.#audioFallbackMs > 0 && !this.#multicastAudioReceived && !this.#audioFallbackTimer) {\n this.#audioFallbackTimer = setTimeout(() => {\n if (!this.#multicastAudioReceived && this.#active !== 'multicast') {\n this.#multicastAudioReceived = true // force\n // Also release the MoQ-audio-warmup gate so the fallback actually\n // activates \u2014 otherwise #tryActivateMulticast would still bail.\n this.#moqAudioWarmed = true\n this.#tryActivateMulticast()\n }\n }, this.#audioFallbackMs)\n }\n } else if (this.#active !== 'multicast') {\n // Do not feed video into the multicast decoder while the source switch\n // is still pending. Keep the newest keyframe as the post-activation\n // decoder opener and drop deltas until takeover commits.\n if (meta.keyframe) {\n this.#pendingMulticastVideo = {\n data: data.slice(),\n meta: { ...meta, source: 'multicast', sourceDiscontinuity: true },\n }\n }\n this.#tryActivateMulticast()\n return\n }\n if (this.#active === 'multicast') this.#onVideoFrame?.(data, { ...meta, source: 'multicast' })\n this.#tryActivateMulticast()\n } else {\n this.#multicastAudioReceived = true\n if (this.#audioFallbackTimer) {\n clearTimeout(this.#audioFallbackTimer)\n this.#audioFallbackTimer = null\n }\n // BLO-3035 layer 5: in a multicast-first scenario (no MoQ unicast audio\n // source) `notifyMoqAudioEmit()` is never called and the audio-fallback\n // timer's force-set is bypassed (the timer's inner `!multicastAudioReceived`\n // check returns early because audio already arrived). Without this gate\n // `#moqAudioWarmed` stays false forever and `#tryActivateMulticast` never\n // fires `onSourceSwitch('multicast')` \u2014 the player can't know to emit\n // `__MULTICAST_TAKEOVER_TIME`. Treat the arrival of multicast audio as\n // sufficient evidence to release the warmup gate. For the MoQ\u2192multicast\n // handoff case `notifyMoqAudioEmit()` will already have set this flag, so\n // the assignment is idempotent.\n if (!this.#moqAudioWarmed) this.#moqAudioWarmed = true\n // Activate BEFORE delivering the frame \u2014 the source switch callback\n // (e.g. ring buffer reset) must fire before the first multicast audio\n // frame reaches the backend. Otherwise the NTP timestamp hits the\n // MoQ-era ring buffer base \u2192 overflow \u2192 silence gap.\n this.#tryActivateMulticast()\n // Only emit multicast audio AFTER takeover succeeds. Before takeover,\n // MoQ audio is still flowing through feedMoq \u2192 #onAudioFrame; emitting\n // multicast audio too would double-feed the backend (2x audio frames,\n // pitch wobble and distortion). Post-takeover, feedMoq is suppressed\n // (#suppressed=true) so only multicast audio reaches the backend.\n if (this.#active === 'multicast') {\n this.#onAudioFrame?.(data, { ...meta, source: 'multicast' })\n } else if (this.#pendingMulticastToken !== null) {\n this.#pendingMulticastAudio = { data: data.slice(), meta: { ...meta, source: 'multicast' } }\n }\n }\n }\n\n /**\n * MoQ unicast audio warmup gate. When audio is required, multicast takeover\n * waits until the MoQ unicast audio decoder has emitted at least one frame\n * (so downstream samples-before-takeover counters observe nonzero) or until\n * the existing audio-fallback timer forces the flag true.\n */\n #moqAudioWarmed = false\n\n /** Called by the player when the MoQ unicast audio decoder emits first frame. */\n public notifyMoqAudioEmit(): void {\n if (this.#moqAudioWarmed) return\n this.#moqAudioWarmed = true\n this.#tryActivateMulticast()\n }\n\n /**\n * Called by the player after a MoQ video keyframe has reached the active\n * decoder path. Used only by MSE/MMTP continuity switching; decoder-reset\n * paths leave allowDeltaMulticastTakeoverAfterMoqKeyframe disabled.\n */\n public notifyMoqVideoKeyframeEmit(): void {\n this.#moqVideoKeyframeEmitted = true\n this.#tryActivateMulticast()\n }\n\n #tryActivateMulticast() {\n if (this.#active === 'multicast') return\n if (this.#pendingMulticastToken !== null) return\n if (!this.#multicastVideoKeyed) return\n if (this.#requireAudio && !this.#multicastAudioReceived) return\n if (this.#requireAudio && !this.#moqAudioWarmed) return\n const token = ++this.#sourceSwitchToken\n const maybeReady = this.#onSourceSwitch?.('multicast')\n if (!maybeReady || typeof (maybeReady as Promise<void>).then !== 'function') {\n this.#commitMulticastActivation(token)\n return\n }\n const ready = Promise.resolve(maybeReady)\n this.#pendingMulticastToken = token\n this.#sourceSwitchReady = ready\n void ready.then(\n () => this.#commitMulticastActivation(token),\n err => this.#rejectMulticastActivation(token, err),\n ).finally(() => {\n if (this.#sourceSwitchReady === ready) this.#sourceSwitchReady = null\n })\n }\n\n #commitMulticastActivation(token: number) {\n if (token !== this.#sourceSwitchToken) return\n this.#active = 'multicast'\n this.#suppressed = true\n this.#pendingMulticastToken = null\n const video = this.#pendingMulticastVideo\n this.#pendingMulticastVideo = null\n const audio = this.#pendingMulticastAudio\n this.#pendingMulticastAudio = null\n if (video) this.#onVideoFrame?.(video.data, video.meta)\n if (audio) this.#onAudioFrame?.(audio.data, audio.meta)\n }\n\n #rejectMulticastActivation(token: number, err: unknown) {\n if (token !== this.#sourceSwitchToken) return\n if (this.#pendingMulticastToken === token) this.#pendingMulticastToken = null\n this.#pendingMulticastVideo = null\n this.#pendingMulticastAudio = null\n console.warn('[MediaRouter] onSourceSwitch(multicast) failed', err)\n }\n\n /** Switch back to MoQ immediately (called on multicast failback). */\n failbackToMoq() {\n const hadPendingMulticast = this.#pendingMulticastToken !== null\n if (this.#active === 'moq' && !hadPendingMulticast) return // already on MoQ, no-op\n ++this.#sourceSwitchToken\n this.#active = 'moq'\n this.#suppressed = false\n this.#pendingMulticastToken = null\n this.#pendingMulticastVideo = null\n this.#pendingMulticastAudio = null\n this.#sourceSwitchReady = null\n this.#multicastVideoKeyed = false\n this.#multicastAudioReceived = false\n this.#moqVideoKeyframeEmitted = false\n // A pending audio-fallback timer belongs to the abandoned takeover attempt.\n // Left running it would force-set the audio flags against the next attempt's\n // fresh state (BLO-9413 failback coherence \u2014 every takeover-era flag/timer\n // unwinds on this edge).\n if (this.#audioFallbackTimer) {\n clearTimeout(this.#audioFallbackTimer)\n this.#audioFallbackTimer = null\n }\n this.#onSourceSwitch?.('moq')\n }\n\n /** Dispose timers and per-track sources. Call on teardown to prevent\n * stale timer callbacks firing into garbage-collected closures (WR-03). */\n dispose(): void {\n if (this.#audioFallbackTimer) {\n clearTimeout(this.#audioFallbackTimer)\n this.#audioFallbackTimer = null\n }\n for (const [name] of this.#trackSources) {\n this.clearTrackSource(name)\n }\n }\n\n // \u2500\u2500 Private helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Emit a frame on the correct per-track callback using the type registry.\n * Falls back to name match if no type registered (backward compat). */\n #emitForTrack(trackName: string, data: Uint8Array, meta: FrameMeta): void {\n // Prefer explicit type registry (catalog or init data)\n const reg = this.#trackTypes.get(trackName)\n if (reg?.type === 'video') {\n this.#onVideoFrame?.(data, meta)\n } else if (reg?.type === 'audio') {\n this.#onAudioFrame?.(data, meta)\n } else if (reg !== undefined) {\n // Registered but unknown type \u2014 overlay\n this.#onOverlayFrame?.(data, meta)\n } else {\n // Not registered \u2014 fall back to name match (backward compat for tests/legacy)\n if (trackName === 'video') this.#onVideoFrame?.(data, meta)\n else if (trackName === 'audio') this.#onAudioFrame?.(data, meta)\n else this.#onOverlayFrame?.(data, meta)\n }\n }\n\n /** Handle an overlay frame: buffer until first FEC block boundary, then pass through. */\n #handleOverlayFrame(data: Uint8Array, meta: FrameMeta): void {\n if (this.#overlayBoundaryReached) {\n this.#onOverlayFrame?.(data, meta)\n return\n }\n\n // Buffer until boundary \u2014 enforcing cap for T-02-17 DoS mitigation\n if (this.#overlayBuffer.length >= this.#maxOverlayBuffer) {\n console.warn(\n `[MediaRouter] overlay buffer full (${this.#maxOverlayBuffer} frames); dropping frame ts=${meta.timestamp}`\n )\n return\n }\n this.#overlayBuffer.push({ data, meta })\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAgGO,SAAS,gBAAgB,OAAe,oBAAoC;AACjF,MAAI,CAAC,OAAO,UAAU,KAAK,GAAG;AAC5B,UAAM,IAAI;AAAA,MACR,0DAA0D,KAAK;AAAA,IACjE;AAAA,EACF;AACA,MAAI,CAAC,OAAO,UAAU,kBAAkB,KAAK,sBAAsB,GAAG;AACpE,UAAM,IAAI;AAAA,MACR,+EAA+E,kBAAkB;AAAA,IACnG;AAAA,EACF;AACA,MAAI,QAAQ,EAAG,QAAO;AACtB,SAAO,KAAK,MAAM,QA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,MAAM,MAAM,MAAM;AAClD,MAAI,MAAO,0BAAK,mBAAL,8BAAqB,MAAM,MAAM,MAAM;AACpD;AAEA,+BAA0B,SAAC,OAAe,KAAc;AACtD,MAAI,UAAU,mBAAK,oBAAoB;AACvC,MAAI,mBAAK,4BAA2B,MAAO,oBAAK,wBAAyB;AACzE,qBAAK,wBAAyB;AAC9B,qBAAK,wBAAyB;AAC9B,UAAQ,KAAK,kDAAkD,GAAG;AACpE;AAAA;AAAA;AAAA;AA2CA,kBAAa,SAAC,WAAmB,MAAkB,MAAuB;AAroC5E;AAuoCI,QAAM,MAAM,mBAAK,aAAY,IAAI,SAAS;AAC1C,MAAI,KAAK,SAAS,SAAS;AACzB,6BAAK,mBAAL,8BAAqB,MAAM;AAAA,EAC7B,WAAW,KAAK,SAAS,SAAS;AAChC,6BAAK,mBAAL,8BAAqB,MAAM;AAAA,EAC7B,WAAW,QAAQ,QAAW;AAE5B,6BAAK,qBAAL,8BAAuB,MAAM;AAAA,EAC/B,OAAO;AAEL,QAAI,cAAc,QAAS,0BAAK,mBAAL,8BAAqB,MAAM;AAAA,aAC7C,cAAc,QAAS,0BAAK,mBAAL,8BAAqB,MAAM;AAAA,QACtD,0BAAK,qBAAL,8BAAuB,MAAM;AAAA,EACpC;AACF;AAAA;AAGA,wBAAmB,SAAC,MAAkB,MAAuB;AAxpC/D;AAypCI,MAAI,mBAAK,0BAAyB;AAChC,6BAAK,qBAAL,8BAAuB,MAAM;AAC7B;AAAA,EACF;AAGA,MAAI,mBAAK,gBAAe,UAAU,mBAAK,oBAAmB;AACxD,YAAQ;AAAA,MACN,sCAAsC,mBAAK,kBAAiB,+BAA+B,KAAK,SAAS;AAAA,IAC3G;AACA;AAAA,EACF;AACA,qBAAK,gBAAe,KAAK,EAAE,MAAM,KAAK,CAAC;AACzC;",
3
+ "sources": ["../src/track-session.ts", "../src/media-router.ts"],
4
+ "sourcesContent": ["/**\n * TrackSession \u2014 per-track transport state machine.\n * SessionManager \u2014 orchestrates all sessions + TransportPool.\n *\n * Implements Patent Claim 9 (draft-ramadan-moq-fec APPLICATION-1):\n * (a) subscribe unicast\n * (b) simultaneously join multicast\n * (c) render from unicast during join\n * (d) activate multicast on RAP, suppress unicast\n * (e) cross-transport FEC repair during transition\n * (f) hysteresis before switching away from multicast\n * (g) re-subscribe unicast on sustained failure\n *\n * PIM: manages transport state without inspecting packet contents.\n */\n\nimport {\n TransportPool,\n type Subscription,\n type SubscriptionMode,\n type AcquireOptions,\n type DirectSocketHealth,\n type TransportPoolOptions,\n} from './transport-pool.js'\nimport { fecBlockBudgetMs } from '@blockcast/mmt-fec'\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type TrackState =\n | 'idle'\n | 'unicast'\n | 'unicast-fallback'\n | 'joining'\n | 'multicast'\n | 'amt'\n | 'failing'\n\nexport interface TrackSessionConfig {\n trackName: string\n trackType: 'video' | 'audio'\n packetId: number\n /** FEC interleave depth from catalog (ms). Used for hysteresis timer. */\n fecInterleaveMs: number\n /** Explicit catalog jitter/reorder allowance in ms. */\n fecReorderToleranceMs?: number\n /** FEC K from catalog. Used for audio worklet latency calculation. */\n fecK: number\n /** FEC repair symbols per block (P). NOT symbol size. */\n fecRepairCount: number\n /**\n * Repair symbols per block this receiver actually joined: the sum of\n * `repairSymbols` over the joined BASE layers, not a count of layers\n * (draft-ramadan-moq-fec 6.3). A keyframe overlay is a separate FEC instance\n * and is not included.\n *\n * This is runtime join state, not catalog geometry: a receiver on a clean\n * path joins layer 0 only while a lossy one adds layers, so the catalog's\n * total P is not what this receiver is receiving. Diagnostics that report P\n * (the worker snapshot, CMCD `x-bc-fec-p`) must read this.\n *\n * Absent when the caller joins no layers explicitly, in which case P_0 is\n * what was joined. That is an identity on a single-layer track, not a\n * catalog default: with one layer, P_0 is the total.\n */\n joinedRepairCount?: number\n /** FEC symbol size in bytes (T). Required for WASM decoder OTI. */\n fecSymbolSize: number\n /** MoQ repair track name from catalog FEC config. */\n repairTrackName?: string\n /** Frame samples from initData parsing (audio-init-parser.ts). */\n frameSamples?: number\n /** Audio sample rate from catalog. */\n sampleRate?: number\n /** Ordered transport preference: best first. */\n preferredTransports: SubscriptionMode[]\n /** Subscription key for multicast/AMT: \"(S,G,port)\". */\n multicastKey?: string\n /** MoQ track name for unicast subscription. */\n moqTrackName?: string\n /** AMT relay address (if AMT is in preference chain). */\n amtRelay?: string\n /** MoQ relay URL (for WebTransport subscription). */\n moqRelayUrl?: string\n}\n\n// ---------------------------------------------------------------------------\n// PIM callbacks (protocol-independent \u2014 transport state only)\n// ---------------------------------------------------------------------------\n\nexport interface SessionManagerCallbacks {\n /** Fired on every transport state transition. */\n onStateChange?(trackName: string, from: TrackState, to: TrackState): void\n /** Fired to suppress/unsuppress unicast for this track (transport arbitration). */\n onSuppress?(trackName: string, suppressed: boolean): void\n /**\n * Fired when a track sat in `joining` for SessionManager.takeoverDeadlineMs\n * without a RAP (BLO-9413/D9). The session has already returned to `unicast`\n * (nothing was suppressed, so nothing to restore) and it keeps its FEC\n * decoder armed, because the multicast socket is still joined and the router\n * still admits the stream's symbols. The host should abandon the router-side\n * attempt (e.g. MediaRouter.failbackToMoq()) so the router stops waiting for\n * a keyframe that is never coming; it must not dispose the decoder here. The\n * decoder is released on the next transport edge (unsubscribe, failbackAll,\n * or transportFailed falling back to unicast) through fec-teardown.\n */\n onTakeoverTimeout?(trackName: string): void\n}\n\n// ---------------------------------------------------------------------------\n// MMTP application-layer extension (FEC lifecycle, media resets)\n// ---------------------------------------------------------------------------\n\n/**\n * MMTP track events (discriminated union).\n * Each protocol layer defines its own event union \u2014 MMTP events cover\n * media resets, latency, and FEC lifecycle.\n */\nexport type MmtpTrackEvent =\n | { type: 'reset' }\n | { type: 'latency'; latencyMs: number }\n | { type: 'fec-setup' }\n | { type: 'fec-teardown' }\n\n/**\n * MMTP application-layer extension of SessionManagerCallbacks.\n * Single onTrackEvent dispatches all MMTP-specific events.\n * PIM consumers use the base SessionManagerCallbacks (no onTrackEvent).\n *\n * IWA can define its own subinterface with its own TrackEvent union\n * (e.g., IwaTrackEvent for socket health, AMT state) using the same pattern.\n */\nexport interface MmtpSessionCallbacks extends SessionManagerCallbacks {\n onTrackEvent?(trackName: string, event: MmtpTrackEvent, config: TrackSessionConfig): void\n}\n\n/**\n * Loss-hysteresis window covering the signaled FEC block span plus jitter.\n *\n * `fecK` no longer feeds the math; it is still validated as a catalog\n * well-formedness guard and kept in the signature for positional API compat\n * (removal is a follow-up with the next cross-repo pin bump).\n */\nexport function computeFecLossWindowMs(fecInterleaveMs: number, fecK: number, jitterBufferMs?: number): number {\n return computeFecDeliveryWindowMs({\n interleaveDepthMs: fecInterleaveMs,\n sourceSymbols: fecK,\n jitterBufferMs,\n })\n}\n\nexport interface FecDeliveryWindowConfig {\n interleaveDepthMs: number\n sourceSymbols: number\n repairSymbols?: number\n symbolSize?: number\n mediaUnitsPerSecond?: number\n bandwidthBps?: number\n /**\n * Explicit jitter/reorder allowance in ms, added once to the complete span.\n * Callers pass their signaled catalog allowance, never a local default.\n */\n jitterBufferMs?: number\n}\n\n/**\n * The catalog interleaveDepthMs is the complete FEC block span, including the\n * repair tail. K, P, cadence, and bandwidth must not expand it again. Geometry\n * fields remain accepted for existing callers, but do not feed deadline math.\n */\nexport function computeFecDeliveryWindowMs(\n config: FecDeliveryWindowConfig,\n): number {\n const fecInterleaveMs = config.interleaveDepthMs\n const fecK = config.sourceSymbols\n if (!Number.isFinite(fecInterleaveMs) || fecInterleaveMs <= 0) {\n throw new Error(\n `[TrackSession] fecInterleaveMs=${fecInterleaveMs}. ` +\n `Derive a positive FEC interleave window from the stream catalog.`\n )\n }\n if (!Number.isFinite(fecK) || fecK <= 0) {\n throw new Error(\n `[TrackSession] fecK=${fecK}. ` +\n `Derive a positive FEC source-symbol count from the stream catalog.`\n )\n }\n\n // Absence stays absent; it does not authorize a synthesized reorder budget.\n if (config.jitterBufferMs === undefined) return Math.ceil(fecInterleaveMs)\n return fecBlockBudgetMs(fecInterleaveMs, config.jitterBufferMs)\n}\n\n/** Convert the shared FEC delivery deadline into an integer media timescale. */\nexport function computeFecDeliveryWindowMediaUnits(\n config: FecDeliveryWindowConfig,\n timestampTimescale: number,\n): number {\n if (!Number.isFinite(timestampTimescale) || timestampTimescale <= 0) {\n throw new Error(\n `[TrackSession] timestampTimescale=${timestampTimescale}. ` +\n 'Derive a positive media timescale from the container.',\n )\n }\n const deliveryWindow = Math.ceil(\n computeFecDeliveryWindowMs(config) * timestampTimescale / 1000,\n )\n if (!Number.isSafeInteger(deliveryWindow)) {\n throw new Error('[TrackSession] FEC delivery window exceeds the media timestamp range.')\n }\n return deliveryWindow\n}\n\n// ---------------------------------------------------------------------------\n// TrackSession\n// ---------------------------------------------------------------------------\n\nexport class TrackSession {\n readonly config: TrackSessionConfig\n #state: TrackState = 'idle'\n #subscription: Subscription | null = null\n #hysteresisTimer: ReturnType<typeof setTimeout> | null = null\n #joinDeadlineTimer: ReturnType<typeof setTimeout> | null = null\n #previousPrimary: SubscriptionMode | null = null\n #manager: SessionManager\n // Single suppression authority flag (BLO-9413 failback coherence): every\n // suppress this session fires is recorded here, and every path that leaves\n // a suppressed state unwinds through #unsuppress(). Before this flag,\n // unsubscribe() only un-suppressed from multicast/amt \u2014 a session torn down\n // from `failing` (exactly where a starving track sits) was re-subscribed to\n // unicast with the host's media still muted: MoQ playing into a dead sink.\n #suppressFired = false\n // Single FEC authority flag: set by the fec-setup edges (joinStarted,\n // enterUnicastFallback), cleared by the fec-teardown edge in #transition.\n // Setup and teardown are paired by construction, so a takeover timeout that\n // parks the session in `unicast` keeps the decoder the still-joined\n // transport is feeding, and the later unsubscribe still tears it down.\n #fecArmed = false\n\n constructor(config: TrackSessionConfig, manager: SessionManager) {\n this.config = config\n this.#manager = manager\n }\n\n // -----------------------------------------------------------------------\n // State\n // -----------------------------------------------------------------------\n\n get state(): TrackState { return this.#state }\n get subscription(): Subscription | null { return this.#subscription }\n\n /** True while this session's onSuppress(true) is outstanding (no matching\n * onSuppress(false) yet). Test/assertion surface for failback coherence. */\n get isSuppressed(): boolean { return this.#suppressFired }\n\n /** Current active transport mode, or null if idle. */\n get transport(): SubscriptionMode | null {\n switch (this.#state) {\n case 'multicast': return 'multicast'\n case 'amt': return 'amt'\n case 'unicast': return 'moq'\n case 'unicast-fallback': return 'moq' // SSM bridge absent \u2014 MoQ unicast is the only source\n case 'joining': return 'moq' // MoQ still primary during join\n case 'failing': return this.#previousPrimary\n default: return null\n }\n }\n\n // -----------------------------------------------------------------------\n // Computed (no magic numbers)\n // -----------------------------------------------------------------------\n\n /** Audio worklet latency: max(fecInterleaveMs, frameDurationMs * fecK).\n * Returns undefined if frame duration unknown (no initData). */\n get audioLatencyMs(): number | undefined {\n const fd = this.frameDurationMs\n if (fd === undefined) {\n return this.config.fecInterleaveMs > 0 ? this.config.fecInterleaveMs : undefined\n }\n return Math.max(this.config.fecInterleaveMs, fd * this.config.fecK)\n }\n\n /** Frame duration in ms, derived from frameSamples + sampleRate. */\n get frameDurationMs(): number | undefined {\n const { frameSamples, sampleRate } = this.config\n if (!frameSamples || !sampleRate || sampleRate <= 0) return undefined\n return (frameSamples / sampleRate) * 1000\n }\n\n // -----------------------------------------------------------------------\n // Transitions (Patent Claim 9)\n // -----------------------------------------------------------------------\n\n /** idle \u2192 unicast: player subscribes to this track. */\n subscribe(): void {\n if (this.#state !== 'idle') return\n this.#transition('unicast')\n\n // Emit audio latency on first subscribe\n if (this.config.trackType === 'audio') {\n const latency = this.audioLatencyMs\n if (latency !== undefined) {\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'latency', latencyMs: latency }, this.config)\n }\n }\n }\n\n /** unicast \u2192 joining: multicast/AMT capability detected, join in progress. */\n joinStarted(): void {\n if (this.#state !== 'unicast') return\n this.#transition('joining')\n // FEC decoders must be ready before multicast data arrives (Claim 9e:\n // cross-transport repair). A session re-joining after a takeover timeout\n // still owns its decoder, so fec-setup fires once per FEC epoch.\n this.#armFec()\n }\n\n /**\n * any non-fallback state \u2192 unicast-fallback. Used when the SSM bridge is\n * absent (vanilla Chromium / no extension) and the host falls back to a\n * MoQ unicast subscription per track. Terminal-ish: activateMulticast,\n * failbackAll, and transportFailed are no-ops while in this state.\n *\n * Fires fec-setup so the per-track repair worker spins up \u2014 repair packets\n * still flow over the MoQ repair-track subscription, so FEC source+repair\n * can converge as in the multicast path.\n *\n * Audio latency is NOT re-emitted here: subscribe() already fires latency\n * once on the idle \u2192 unicast edge, and enterUnicastFallback is only ever\n * reached from a non-idle state (SessionManager skips idle sessions).\n */\n enterUnicastFallback(): void {\n if (this.#state === 'unicast-fallback') return\n this.#clearHysteresis()\n this.#transition('unicast-fallback')\n // Suppress the redundant unicast media decoder. On the no-bridge path the\n // host feeds MoQ-unicast source packets into MulticastManager (the render\n // consumer); a second base-media subscribe (the @moq/watch decoder) would\n // split the single connection's QUIC flow-control budget and stall delivery\n // (BLO-8969). Fire suppress here, on the fallback edge, so the decoder is\n // gated off before it subscribes rather than after the relay forward task\n // has already wedged.\n this.#suppress()\n this.#armFec()\n }\n\n /**\n * unicast-fallback \u2192 unicast. Called when the SSM bridge appears mid-session\n * (extension installed after fallback engaged). Host first aborts the fallback\n * drainers, then transitions sessions back to unicast so the regular\n * multicast/AMT preference chain can take over via joinStarted().\n */\n exitUnicastFallback(): void {\n if (this.#state !== 'unicast-fallback') return\n this.#transition('unicast')\n // Un-suppress the unicast decoder: the bridge appeared mid-session, so the\n // host tears down the fallback drainers and the regular preference chain\n // (joinStarted -> joining -> rapReceived) will re-suppress on multicast RAP.\n this.#unsuppress()\n }\n\n /**\n * joining \u2192 multicast or amt: RAP received on the joined transport (Claim 9d).\n * Resets audio worklet, then suppresses MoQ.\n */\n rapReceived(mode: 'multicast' | 'amt'): void {\n if (this.#state !== 'joining') return\n this.#previousPrimary = mode\n this.#transition(mode)\n if (this.config.trackType === 'audio') {\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'reset' }, this.config)\n }\n this.#suppress()\n }\n\n /** multicast/amt \u2192 failing: loss detected, start hysteresis timer (Claim 9f). */\n lossDetected(): void {\n if (this.#state !== 'multicast' && this.#state !== 'amt') return\n this.#previousPrimary = this.#state as SubscriptionMode\n this.#transition('failing')\n\n // Hysteresis timer: sustained loss before failback (Claim 9f). Use the\n // same complete span plus explicit allowance as FECManager and workers.\n const hysteresisMs = computeFecLossWindowMs(\n this.config.fecInterleaveMs,\n this.config.fecK,\n this.config.fecReorderToleranceMs,\n )\n this.#hysteresisTimer = setTimeout(() => {\n this.hysteresisExpired()\n }, hysteresisMs)\n }\n\n /** failing \u2192 previous primary: loss recovered within hysteresis window. */\n lossRecovered(): void {\n if (this.#state !== 'failing') return\n this.#clearHysteresis()\n if (this.#previousPrimary) {\n this.#transition(this.#previousPrimary as TrackState)\n }\n }\n\n /**\n * Transport failed (AMT relay down, multicast interface gone).\n * Try next transport in preference chain.\n */\n transportFailed(): void {\n this.#clearHysteresis()\n // Unicast-fallback is terminal: the host owns the subscription and\n // SessionManager transport machinery does not arbitrate it.\n if (this.#state === 'unicast-fallback') return\n const current = this.#previousPrimary ?? this.transport\n const prefs = this.config.preferredTransports\n const currentIdx = current ? prefs.indexOf(current) : -1\n const nextMode = prefs[currentIdx + 1]\n\n if (nextMode !== undefined && nextMode !== 'moq') {\n // Next is multicast or AMT: start joining. `joining` means MoQ is\n // primary again (see transport getter), so if the failed transport had\n // suppressed unicast, restore it for the join window or the viewer\n // watches black video until the next RAP (which may never come).\n // The chain position moves with the attempt: a join that times out\n // parks the session in `unicast` with this transport recorded, so the\n // next failure continues past it rather than re-trying the transport\n // that already failed and re-firing onTakeoverTimeout on every lap.\n this.#previousPrimary = nextMode\n this.#transition('joining')\n this.#unsuppress()\n return\n }\n // MoQ is next, or the chain is exhausted: unicast either way (Claim 9g).\n // For a session parked in `unicast` with its decoder retained after a\n // takeover timeout, this transition is a self-edge and fires no teardown,\n // so the release is explicit. It is the \"transportFailed falling back to\n // unicast\" release path the onTakeoverTimeout doc names, and #disarmFec is\n // idempotent, so it is a no-op when the transition already fired the\n // teardown. The audio reset is not flag-guarded, so it is tied to the edge\n // itself: a session already resting in unicast changed no transport and\n // owes the host no reset, however many pool subscriptions fail for it.\n const from = this.#state\n this.#previousPrimary = null\n this.#transition('unicast')\n this.#disarmFec()\n this.#unsuppress()\n if (from !== 'unicast' && this.config.trackType === 'audio') {\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'reset' }, this.config)\n }\n }\n\n /** Hysteresis expired \u2192 failback to next transport (Claim 9g). */\n hysteresisExpired(): void {\n if (this.#state !== 'failing') return\n this.#clearHysteresis()\n this.transportFailed()\n }\n\n /** \u2192 idle: player unsubscribes / tab close / cleanup. */\n unsubscribe(): void {\n this.#clearHysteresis()\n if (this.#state !== 'idle') {\n this.#transition('idle')\n // Unwind any outstanding suppression regardless of which state we left.\n // The old `wasActive` check (multicast/amt only) leaked suppression when\n // tearing down from `failing` or `unicast-fallback` \u2014 failbackAll()'s\n // unsubscribe\u2192subscribe cycle then re-entered unicast with the host's\n // media still muted (BLO-9413 freeze: \"failing back\" logged, video dead).\n this.#unsuppress()\n }\n }\n\n /** True when SessionManager.enterUnicastFallback put this track into the\n * host-driven unicast subscription mode. Host can iterate sessions to\n * decide whether to keep its fallback drainer alive across MediaRouter\n * arbitration events. */\n get isUnicastFallback(): boolean {\n return this.#state === 'unicast-fallback'\n }\n\n /**\n * True while this track owns a FEC decoder (fec-setup fired, fec-teardown\n * not yet). Stays true across a takeover timeout that parked the session in\n * `unicast`; SessionManager.failbackAll uses it to release such sessions.\n */\n get isFecArmed(): boolean {\n return this.#fecArmed\n }\n\n /**\n * Start the deadline a `joining` entry deferred while the join was inactive\n * (SessionManager.joinActive). The track gets the FULL deadline from here,\n * because that is when media can first arrive. No-op outside `joining` and\n * when a deadline is already running, so it never shortens or restarts one.\n *\n * The `joinActive` guard is what makes this safe to call from anywhere: a\n * track parked in `joining` with a deferred (null) timer satisfies the other\n * two, so without it a host calling this while the join is still inactive\n * would arm the exact deadline the gate exists to defer -- silently\n * reinstating BLO-34289. It is a no-op for the internal caller, which writes\n * `#joinActive = true` before iterating the sessions.\n */\n armDeferredJoinDeadline(): void {\n if (this.#state !== 'joining' || this.#joinDeadlineTimer !== null) return\n if (!this.#manager.joinActive) return\n this.#armJoinDeadline(this.#manager.takeoverDeadlineMs)\n }\n\n dispose(): void {\n this.#clearHysteresis()\n this.#clearJoinDeadline()\n this.#state = 'idle'\n this.#subscription = null\n // Release through the teardown edge, not a bare assignment: the\n // retained-FEC park makes `unicast` + isFecArmed a resting state, and\n // SessionManager.dispose() calls this directly (removeTrack() reaches it\n // via unsubscribe(), which has already disarmed). A bare assignment there\n // drops the host's decoder without a fec-teardown -- a leaked Worker.\n this.#disarmFec()\n }\n\n // -----------------------------------------------------------------------\n // Internal\n // -----------------------------------------------------------------------\n\n #transition(to: TrackState, opts?: { retainFec?: boolean }): void {\n const from = this.#state\n if (from === to) return\n // Takeover deadline (BLO-9413/D9): every entry into `joining` arms it\n // (joinStarted AND transportFailed-failover both route through here);\n // every exit cancels it. Without this, a transport that accepts the\n // subscribe but never delivers a RAP parks the session in `joining`\n // forever (observed live in the Phase-0 headless repro). The value is\n // resolved before any state write, so the one residual failure -- a\n // manager whose deadline was never set at all, which addTrack() refuses --\n // leaves the session in its previous state rather than half-transitioned.\n // Invalid values never reach here: SessionManager's setter refuses them.\n // The read is unconditional even when `joinActive` defers the arm, so a\n // manager without a deadline still fails closed on every joining edge.\n const joinDeadlineMs = to === 'joining' ? this.#manager.takeoverDeadlineMs : undefined\n this.#state = to\n if (from === 'joining') this.#clearJoinDeadline()\n if (joinDeadlineMs !== undefined && this.#manager.joinActive) {\n this.#armJoinDeadline(joinDeadlineMs)\n }\n // FEC teardown: entering a state without a FEC decoder releases the one\n // this track armed, unless the caller keeps it (takeover timeout: the\n // transport is still joined and still feeding the decoder).\n const fecActive = (s: TrackState) =>\n s === 'joining' ||\n s === 'multicast' ||\n s === 'amt' ||\n s === 'failing' ||\n s === 'unicast-fallback'\n if (!fecActive(to) && !opts?.retainFec) this.#disarmFec()\n this.#manager.callbacks?.onStateChange?.(this.config.trackName, from, to)\n }\n\n #clearHysteresis(): void {\n if (this.#hysteresisTimer !== null) {\n clearTimeout(this.#hysteresisTimer)\n this.#hysteresisTimer = null\n }\n }\n\n #armJoinDeadline(deadlineMs: number): void {\n this.#clearJoinDeadline()\n if (deadlineMs === 0) return // a declared 0 disables the deadline\n this.#joinDeadlineTimer = setTimeout(() => {\n this.#joinDeadlineTimer = null\n if (this.#state !== 'joining') return\n // No RAP within the deadline: return to unicast for arbitration only.\n // MoQ was never suppressed in `joining`, so there is nothing to restore\n // and this edge stays silent on onSuppress (asserted in tests). The\n // multicast socket is still joined and the router still admits this\n // stream's symbols, so the FEC decoder stays armed; the next transport\n // edge releases it.\n this.#transition('unicast', { retainFec: true })\n this.#manager.callbacks?.onTakeoverTimeout?.(this.config.trackName)\n }, deadlineMs)\n }\n\n #clearJoinDeadline(): void {\n if (this.#joinDeadlineTimer !== null) {\n clearTimeout(this.#joinDeadlineTimer)\n this.#joinDeadlineTimer = null\n }\n }\n\n /** Fire fec-setup exactly once per FEC epoch. */\n #armFec(): void {\n if (this.#fecArmed) return\n this.#fecArmed = true\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'fec-setup' }, this.config)\n }\n\n /** Fire fec-teardown for an armed decoder; no-op when none is armed. */\n #disarmFec(): void {\n if (!this.#fecArmed) return\n this.#fecArmed = false\n this.#manager.mmtp?.onTrackEvent?.(this.config.trackName, { type: 'fec-teardown' }, this.config)\n }\n\n /** Fire onSuppress(true) exactly once per suppression epoch. */\n #suppress(): void {\n if (this.#suppressFired) return\n this.#suppressFired = true\n this.#manager.callbacks?.onSuppress?.(this.config.trackName, true)\n }\n\n /** Unwind an outstanding suppression; no-op when none is outstanding. */\n #unsuppress(): void {\n if (!this.#suppressFired) return\n this.#suppressFired = false\n this.#manager.callbacks?.onSuppress?.(this.config.trackName, false)\n }\n}\n\n// ---------------------------------------------------------------------------\n// SessionManager\n// ---------------------------------------------------------------------------\n\n/**\n * Largest takeover deadline setTimeout represents faithfully. setTimeout\n * coerces its delay to a signed 32-bit int, so a larger value fires on the\n * next tick (Node also warns TimeoutOverflowWarning) instead of after the\n * window the host asked for -- silently inverting the feature. Rejecting it\n * keeps the classic units bug (seconds-as-ms, a wrong timescale) loud.\n */\nexport const MAX_TAKEOVER_DEADLINE_MS = 2_147_483_647\n\n/**\n * How long `joinActive` may stay false before the library says so. The deferral\n * is unbounded by construction -- that is the feature -- so a host that never\n * flips it back parks every track in `joining` with no timer at all: exactly the\n * forever-join the takeover deadline exists to prevent, only silent. MoQ stays\n * unsuppressed so the viewer sees video, but onTakeoverTimeout never fires, the\n * FEC decoder stays armed, and the preference chain never advances past the\n * transport that failed. It looks like a slow join. A host is one un-awaited\n * rejection between `false` and `true` away from it, so the library complains\n * rather than trusting every future host to get all of its exit paths right.\n *\n * Generous against a genuinely slow subscribe -- a bridge reconnect or AMT relay\n * handshake is seconds -- so anything still unsettled here is broken, not slow.\n */\nexport const JOIN_DEFER_WARN_MS = 30_000\n\nexport class SessionManager {\n readonly pool: TransportPool\n readonly sessions = new Map<string, TrackSession>()\n callbacks: SessionManagerCallbacks | null = null\n #takeoverDeadlineMs: number | undefined = undefined\n #joinActive = true\n #joinDeferWarnTimer: ReturnType<typeof setTimeout> | null = null\n\n /**\n * Takeover deadline (BLO-9413/D9): the time a session may sit in `joining`\n * without a RAP before returning to `unicast` and firing onTakeoverTimeout.\n * MoQ is never suppressed during `joining`, so expiry abandons the takeover\n * without a playback glitch. The host derives it from the catalog (RAP\n * cadence from groupDurationTicks/timescale plus the signaled FEC delivery\n * window or reorder tolerance) and sets it before addTrack(). There is no\n * default: an unset value fails addTrack() closed, and reading the getter\n * before assignment throws the same way, so no host ever holds a\n * `number | undefined` it could coalesce back into a default.\n * `hasTakeoverDeadline` answers whether one was admitted. A declared 0\n * disables the deadline. The value is an integer number of milliseconds:\n * setTimeout truncates fractions, so a host that divides ticks by a\n * timescale must round before assigning.\n *\n * Assignment validates, so the diagnostic lands at the host's own call site.\n * That is what bounds the blast radius: `joining` is entered from\n * joinStarted(), from the transportFailed() failover branch -- itself\n * reachable from a setTimeout via hysteresisExpired(), where no caller could\n * catch a throw -- and from the activateMulticast()/activateAmt()/pool-failure\n * loops, where a throw on one session would abandon its siblings mid-loop\n * (the split-brain those loops exist to prevent). Refusing a bad value at\n * assignment means no host mutation can make an already-admitted session\n * throw out of a transport edge.\n */\n get takeoverDeadlineMs(): number {\n return this.#requireTakeoverDeadlineMs()\n }\n\n set takeoverDeadlineMs(value: number) {\n if (!Number.isInteger(value) || value < 0 || value > MAX_TAKEOVER_DEADLINE_MS) {\n throw new Error(\n `[SessionManager] takeoverDeadlineMs must be an integer from 0 to ${MAX_TAKEOVER_DEADLINE_MS} (0 disables it, larger values overflow setTimeout); got ${String(value)}`,\n )\n }\n this.#takeoverDeadlineMs = value\n }\n\n /** True once the host has admitted a deadline; a declared 0 counts. */\n get hasTakeoverDeadline(): boolean {\n return this.#takeoverDeadlineMs !== undefined\n }\n\n /**\n * Whether the transport the joining tracks are waiting on is actually\n * subscribed. The takeover deadline is a media-arrival budget and media\n * cannot arrive before the join exists, so while this is false, entering\n * `joining` arms no deadline; flipping it true starts the FULL deadline for\n * every track already parked there.\n *\n * Default true, which is the arm-on-`joining` behaviour every host had\n * before: a host that only calls joinStarted() after its own join resolves\n * (moqtail-private's player, post-BLO-33339) is already at the right edge and\n * needs no gate. A host that arms joinStarted() up front \u2014 to have FEC\n * decoders ready before the first datagram \u2014 sets this false before addTrack()\n * and true when its subscribe settles. Charging a slow subscribe (bridge\n * reconnect, AMT relay handshake) against the media budget expired the\n * deadline before the subscription existed and abandoned the join on the\n * happy path. BLO-34289.\n *\n * The flag tracks the host's primary join, not per-track transport state. A\n * track that fails over to the next transport in its own chain while this is\n * false (transportFailed's failover branch also enters `joining`) has that\n * deadline gated on the primary join activating, not on its own transport.\n * Under the documented usage -- false once at setup, true once the subscribe\n * settles -- the two coincide.\n *\n * The gate is on the ENTRY into `joining`, and false cannot take back a\n * deadline already running: the `true -> false` edge arms the warn below and\n * clears nothing. So set it false BEFORE the `joining` entry it is meant to\n * gate. A host that instead flipped it false after a `transportFailed()`\n * failover had already entered `joining` would leave the full deadline\n * counting against a subscribe that had not begun -- BLO-34289 again, on the\n * failover edge. Clearing running deadlines on that edge is deliberately NOT\n * done: this flag is manager-wide, so one transport's brief false would\n * cancel an unrelated track's live deadline and then re-arm it at FULL length\n * on the next activation (armDeferredJoinDeadline sees `joining` + a null\n * timer and cannot tell a cleared deadline from a deferred one). Every\n * unrelated transport blip would restart the whole budget, so under repeated\n * failover a track that should have timed out is extended indefinitely and\n * never advances. Only a false that never returns true loses the timer\n * outright, and JOIN_DEFER_WARN_MS already covers that.\n *\n * Leaving this false is not free: see JOIN_DEFER_WARN_MS.\n */\n get joinActive(): boolean {\n return this.#joinActive\n }\n\n set joinActive(active: boolean) {\n const wasActive = this.#joinActive\n this.#joinActive = active\n if (!active) {\n // Edge-triggered: a host re-declaring false has not restarted its\n // subscribe, and total deferral is what the warning is about.\n if (wasActive) this.#armJoinDeferWarn()\n return\n }\n this.#clearJoinDeferWarn()\n if (wasActive) return\n for (const [, session] of this.sessions) session.armDeferredJoinDeadline()\n }\n\n #armJoinDeferWarn(): void {\n this.#joinDeferWarnTimer = setTimeout(() => {\n this.#joinDeferWarnTimer = null\n const deferred = [...this.sessions.values()].filter(s => s.state === 'joining').length\n console.warn(\n `[SessionManager] joinActive has been false for ${JOIN_DEFER_WARN_MS} ms and ${deferred} track(s) sit in 'joining' with no takeover deadline. Set joinActive = true when the subscribe settles, on every exit path including failures, or these tracks never time out, never release their FEC decoders, and never advance to the next transport.`,\n )\n }, JOIN_DEFER_WARN_MS)\n }\n\n #clearJoinDeferWarn(): void {\n if (this.#joinDeferWarnTimer === null) return\n clearTimeout(this.#joinDeferWarnTimer)\n this.#joinDeferWarnTimer = null\n }\n\n /** Narrow to MMTP callbacks (onTrackEvent). Safe \u2014 optional chaining handles PIM-only consumers. */\n get mmtp(): MmtpSessionCallbacks | null {\n return this.callbacks as MmtpSessionCallbacks | null\n }\n\n constructor(poolOptions?: TransportPoolOptions) {\n this.pool = new TransportPool(poolOptions)\n\n // Wire pool failure \u2192 per-track failover\n this.pool.onSubscriptionFailed(sub => {\n for (const trackName of sub.consumers) {\n const session = this.sessions.get(trackName)\n if (session) session.transportFailed()\n }\n })\n }\n\n // -----------------------------------------------------------------------\n // Track management\n // -----------------------------------------------------------------------\n\n /**\n * The admitted takeover deadline. Throws only when the host never set one,\n * every other invalid value being refused by the setter, and returns a\n * declared 0 as 0. The getter and addTrack() both route through it, so a\n * session cannot exist without an admitted deadline, which is what makes\n * the #transition() read unable to throw on an already-admitted session.\n */\n #requireTakeoverDeadlineMs(): number {\n const value = this.#takeoverDeadlineMs\n if (value === undefined) {\n throw new Error(\n '[SessionManager] takeoverDeadlineMs is unset; set a catalog-derived takeover deadline (0 disables it) before adding tracks',\n )\n }\n return value\n }\n\n /** Add a track session from catalog config. */\n addTrack(config: TrackSessionConfig): TrackSession {\n if (this.sessions.has(config.trackName)) {\n throw new Error(`[SessionManager] Track \"${config.trackName}\" already exists`)\n }\n this.#requireTakeoverDeadlineMs()\n const session = new TrackSession(config, this)\n this.sessions.set(config.trackName, session)\n return session\n }\n\n /** Remove a track session. Releases subscription with grace period. */\n removeTrack(trackName: string): void {\n const session = this.sessions.get(trackName)\n if (!session) return\n session.unsubscribe()\n\n // Release pool subscription\n const subKey = session.config.multicastKey ?? session.config.moqTrackName\n if (subKey) this.pool.releaseSubscription(subKey, trackName)\n\n session.dispose()\n this.sessions.delete(trackName)\n }\n\n // -----------------------------------------------------------------------\n // Atomic multi-track operations\n // -----------------------------------------------------------------------\n\n /**\n * All tracks with multicast RAP \u2192 multicast state (atomic).\n * Called when MediaRouter fires onSourceSwitch('multicast').\n * Prevents split-brain between video and audio.\n *\n * A takeover deadline can return a track from `joining` to `unicast` while\n * the multicast socket keeps delivering packets and the track keeps its FEC\n * decoder armed. If a valid RAP arrives later, that late-RAP edge suppresses\n * unicast and promotes multicast without a second fec-setup.\n */\n activateMulticast(): void {\n for (const [, session] of this.sessions) {\n if (session.state === 'unicast') {\n session.joinStarted()\n }\n if (session.state === 'joining') {\n session.rapReceived('multicast')\n }\n }\n }\n\n /**\n * All tracks with AMT RAP \u2192 amt state (atomic).\n */\n activateAmt(): void {\n for (const [, session] of this.sessions) {\n if (session.state === 'unicast') {\n session.joinStarted()\n }\n if (session.state === 'joining') {\n session.rapReceived('amt')\n }\n }\n }\n\n /**\n * All tracks \u2192 unicast (failback, atomic).\n * Called when MulticastManager fires onFailback().\n * unicast-fallback sessions are skipped \u2014 the host owns those subscriptions\n * and they must drain uninterrupted across transport-state events.\n *\n * Coherence invariant (BLO-9413): after this returns, every non-fallback\n * session is `unicast` (or `idle`), unsuppressed, and without a FEC decoder.\n * unsubscribe() unwinds any outstanding suppression regardless of the state\n * it tears down from (`failing` included; see TrackSession.#suppressFired),\n * and a session that a takeover timeout parked in `unicast` with its decoder\n * still armed is cycled too, because this transport edge is what releases\n * that decoder (unsubscribe fires fec-teardown).\n */\n failbackAll(): void {\n for (const [, session] of this.sessions) {\n const parkedWithFec = session.state === 'unicast' && session.isFecArmed\n if (\n parkedWithFec ||\n (session.state !== 'idle' &&\n session.state !== 'unicast' &&\n session.state !== 'unicast-fallback')\n ) {\n session.unsubscribe()\n session.subscribe() // re-enter unicast\n }\n }\n }\n\n /**\n * All tracks \u2192 unicast-fallback (atomic).\n * Called by the host when the multicast gateway is absent and\n * the player will subscribe to source tracks over MoQ unicast and feed\n * packets via MulticastManager.feedUnicastSource() (or manager.router\n * directly). Sessions in this state stay terminal until the host calls\n * unsubscribe() / disposes the SessionManager.\n */\n enterUnicastFallback(): void {\n for (const [, session] of this.sessions) {\n if (session.state === 'idle') continue\n session.enterUnicastFallback()\n }\n }\n\n /**\n * True if any session is currently in unicast-fallback. Hosts use this to\n * gate `multicastTrack.close()` on failback events \u2014 closing the shared\n * broadcast would kill the host's fallback drainers.\n */\n hasActiveFallback(): boolean {\n for (const [, session] of this.sessions) {\n if (session.isUnicastFallback) return true\n }\n return false\n }\n\n /**\n * All fallback tracks \u2192 unicast (atomic).\n * Called when the SSM bridge appears mid-session and the host has aborted\n * the fallback drainers. The session re-enters the regular preference chain\n * via joinStarted() (issued by the host immediately after).\n */\n exitUnicastFallback(): void {\n for (const [, session] of this.sessions) {\n if (session.isUnicastFallback) session.exitUnicastFallback()\n }\n }\n\n // -----------------------------------------------------------------------\n // Cleanup lifecycle\n // -----------------------------------------------------------------------\n\n /** Tab closed \u2014 release all subscriptions for this tab (grace period). */\n tabClosed(tabId: string): void {\n // All tracks owned by this tab \u2192 idle\n for (const [trackName, session] of this.sessions) {\n session.unsubscribe()\n this.pool.releaseAllForConsumer(trackName)\n }\n }\n\n /** Bridge WebTransport connection dropped \u2014 same as tab close. */\n bridgeDisconnected(): void {\n this.tabClosed('bridge')\n }\n\n /**\n * Track selection changed (user or ABR).\n * Old track released (grace period), new track subscribed.\n */\n trackSelectionChanged(oldTrackName: string, newConfig: TrackSessionConfig): void {\n this.removeTrack(oldTrackName)\n const session = this.addTrack(newConfig)\n session.subscribe()\n }\n\n // -----------------------------------------------------------------------\n // Query\n // -----------------------------------------------------------------------\n\n /** Get a track session by name. */\n getTrack(trackName: string): TrackSession | undefined {\n return this.sessions.get(trackName)\n }\n\n // -----------------------------------------------------------------------\n // Cleanup\n // -----------------------------------------------------------------------\n\n dispose(): void {\n this.#clearJoinDeferWarn()\n for (const [, session] of this.sessions) {\n session.dispose()\n }\n this.sessions.clear()\n this.pool.dispose()\n this.callbacks = null\n }\n}\n", "/**\n * MediaRouter \u2014 source arbitration for MoQ \u2194 multicast switching.\n *\n * Both moq-lib and moqtail wire their MoQ and multicast frame outputs\n * through this router. The router decides which source reaches the decoder:\n *\n * - MoQ frames pass through while multicast is inactive.\n * - Multicast video frames are suppressed until the first keyframe.\n * - Once multicast has both a video keyframe and audio, takeover is requested.\n * - MoQ is suppressed only after the source-switch callback completes.\n * - failbackToMoq() reverses the switch immediately.\n *\n * Per-track setTrackSource() allows individual tracks to be wired to a\n * specific transport source (video=multicast, audio=moq, overlay=amt) without\n * changing the binary MoQ\u2194multicast switching for other tracks.\n */\n\nimport { computeFecDeliveryWindowMs } from './track-session.js'\n\nexport type FrameMeta = {\n timestamp: number\n keyframe: boolean\n packetId?: number\n packetSequenceNumber?: number\n source?: 'moq' | 'multicast' | 'repair'\n recovered?: boolean\n sourceDiscontinuity?: boolean\n /**\n * Raw MMTP header timestamp (RFC 5905 short NTP, 32 bits): the publisher's\n * send-wall clock for the packet that carried this frame. On timed media it\n * is distinct from `timestamp`, the authored media presentation time. On a\n * non-timed MFU there is no authored presentation time, so `MmtpRouter`\n * derives `timestamp` from this same clock and the two carry no latency\n * between them. Populated from `RoutedFrameMeta.mmtpTimestamp` and\n * preserved by every re-emit on this router (multicast, MoQ, and repair) so\n * players can measure network ingress on the multicast legs; absent when\n * the packet header could not be read.\n */\n mmtpTimestamp?: bigint\n}\nexport type FrameKind = 'video' | 'audio'\nexport type SourceKind = 'moq' | 'multicast'\n\ntype FrameCb = (data: Uint8Array, meta: FrameMeta) => void\ntype SwitchCb = (source: SourceKind) => void | Promise<void>\n\nexport interface MediaRouterOptions {\n /** Set false for video-only streams. Default: true. */\n requireAudio?: boolean\n /**\n * Audio fallback timeout (ms): force multicast activation if video keyframe\n * arrived but audio hasn't within this window. Catalog-derived via\n * computeFecDeliveryWindowMs (the single FEC recovery-window source of truth).\n * Omit to disable the independent audio-fallback timer (no magic default).\n */\n audioFallbackMs?: number\n /**\n * Number of binary-path frames to allow through during a crossfade transition.\n * Derive from FEC block size (e.g., ceil(K / groupsPerBlock)). Default: 10.\n */\n crossfadeFrames?: number\n /**\n * Max pre-boundary overlay frames to buffer before dropping.\n * Derive from FEC config (e.g., ceil(K * 1.5)). Default: 128.\n */\n maxOverlayBuffer?: number\n /**\n * Max concurrent in-flight repairs. Prevents relay SUBSCRIBE flood (T-13-01 mitigation).\n * Default: 2.\n */\n maxRepairInFlight?: number\n /**\n * Allow multicast takeover from a delta frame after the player has confirmed\n * that MoQ already seeded the same decoder timeline with a video keyframe.\n * Default false: decoder-reset paths still need multicast to provide a RAP.\n */\n allowDeltaMulticastTakeoverAfterMoqKeyframe?: boolean\n}\n\n/**\n * A per-track source that emits frames independently of the binary MoQ/multicast path.\n * Used by setTrackSource() to wire specific tracks to specific transport sources.\n */\nexport interface TrackSource {\n name: string\n /**\n * Register a frame callback. Returns an unsubscribe function.\n * MediaRouter calls unsubscribe() when clearTrackSource() is called.\n */\n onFrame(cb: (data: Uint8Array, meta: FrameMeta) => void): () => void\n /**\n * Optional error callback for when the source fails.\n * MediaRouter uses this to trigger failback to binary switching for this track.\n */\n onError?(cb: () => void): () => void\n /** Optional dispose hook called when clearTrackSource() is called. */\n dispose?(): void\n}\n\n/**\n * Thrown when setTrackSource() is called for a track that already has a source\n * without an intervening clearTrackSource(). Prevents silent concurrent-assignment\n * races (T-02-16 mitigation).\n */\nexport class TrackSourceConflictError extends Error {\n constructor(public readonly trackName: string) {\n super(`Track source already assigned for '${trackName}'; call clearTrackSource first`)\n this.name = 'TrackSourceConflictError'\n }\n}\n\n/**\n * Migration policy for setTrackSource() transport switching.\n *\n * - 'crossfade': Overlap old (binary) and new source briefly (CROSSFADE_WINDOW_FRAMES),\n * then suppress the binary path. Default for audio.\n * - 'drop': Cut to new source immediately. Binary path suppressed at once.\n * Suitable for latency-critical tracks.\n * - 'wait': Defer migration until first FEC block boundary (same as overlay=true).\n * Default for video \u2014 avoids decoder reset mid-block.\n */\nexport type MigrationPolicy = 'crossfade' | 'drop' | 'wait'\n\n/** Default crossfade window \u2014 override via MediaRouterOptions.crossfadeFrames. */\nconst DEFAULT_CROSSFADE_FRAMES = 10\n\n/** Options passed to setTrackSource(). */\nexport interface SetTrackSourceOptions {\n /**\n * If true, this source is an overlay track that must wait for the first FEC\n * block boundary signal (via notifyFecBlockBoundary()) before emitting frames.\n * Frames arriving before the first boundary are buffered up to MAX_OVERLAY_BUFFER.\n *\n * Backwards compat: equivalent to policy: 'wait'.\n */\n overlay?: boolean\n /**\n * Migration policy for the transport switch. Overrides `overlay` when provided.\n * See MigrationPolicy for semantics.\n */\n policy?: MigrationPolicy\n}\n\n/** Default overlay buffer cap \u2014 override via MediaRouterOptions.maxOverlayBuffer. */\nconst DEFAULT_MAX_OVERLAY_BUFFER = 128\n\n/** Internal per-track source record. */\ninterface TrackSourceRecord {\n source: TrackSource\n unsubscribeFrame: () => void\n unsubscribeError?: () => void\n emitCount: number\n}\n\nexport class MediaRouter {\n #active: SourceKind = 'moq'\n #multicastVideoKeyed = false\n #multicastAudioReceived = false\n #moqVideoKeyframeEmitted = false\n #requireAudio: boolean\n #suppressed = false // true after multicast confirmed \u2014 suppresses MoQ\n #audioFallbackTimer: ReturnType<typeof setTimeout> | null = null\n\n // Configurable constants (from catalog/FEC config, not magic numbers)\n readonly #audioFallbackMs: number\n readonly #crossfadeFrames: number\n readonly #maxOverlayBuffer: number\n readonly #allowDeltaMulticastTakeoverAfterMoqKeyframe: boolean\n\n // \u2500\u2500 Keyframe repair state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Groups currently being repaired \u2014 idempotent guard per Pitfall 2 (T-13-01 mitigation) */\n #repairInFlight = new Set<number>()\n /** Max concurrent repairs \u2014 prevents relay SUBSCRIBE flood (T-13-01 mitigation) */\n readonly #maxRepairInFlight: number\n /** Callback to request MoQ subscribe for a specific group (wired by player) */\n #onRepairRequest: ((expectedGroupId: number, trackName: string) => void) | null = null\n\n #onVideoFrame: FrameCb | null = null\n #onAudioFrame: FrameCb | null = null\n #onOverlayFrame: FrameCb | null = null\n #onSourceSwitch: SwitchCb | null = null\n #sourceSwitchReady: Promise<void> | null = null\n #sourceSwitchToken = 0\n #pendingMulticastToken: number | null = null\n #pendingMulticastVideo: { data: Uint8Array; meta: FrameMeta } | null = null\n #pendingMulticastAudio: { data: Uint8Array; meta: FrameMeta } | null = null\n\n // Per-track source state\n #trackSources = new Map<string, TrackSourceRecord>()\n\n // Track type registry: trackName \u2192 { type, source }.\n // Init data / inline signaling is authoritative until catalog updates.\n // Priority: 'init' > 'catalog' > 'name' (backward compat fallback).\n #trackTypes = new Map<string, { type: FrameKind; source: 'catalog' | 'init' }>()\n\n // Crossfade state: maps trackName \u2192 remaining binary-path frames allowed during window\n #crossfadeCounters = new Map<string, number>()\n\n // Overlay alignment state\n #overlayBoundaryReached = false\n #overlayBuffer: Array<{ data: Uint8Array; meta: FrameMeta }> = []\n\n // \u2500\u2500 Phase 14: deltaActive state machine (D-11..D-14) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // No timers \u2014 state transitions driven entirely by notifyDeltaBlock() callbacks.\n // All thresholds derived from catalog fields or throw at configureDelta() time.\n #deltaConfigured = false\n #deltaActive: boolean = true\n #deltaWindow: boolean[] = [] // ring buffer: true = block failed\n #deltaWindowSize: number = 0\n #deltaFailThresholdRatio: number = 0 // P/K\n #deltaRecoverThresholdRatio: number = 0 // (P/K)/2 \u2014 hysteresis (D-13)\n #deltaProbeIntervalMs: number = 0\n #lastProbeAt: number = 0\n #onDeltaFallbackCb: (() => void) | null = null\n #onDeltaRecoverCb: (() => void) | null = null\n\n constructor(options?: MediaRouterOptions) {\n this.#requireAudio = options?.requireAudio ?? true\n // Catalog-derived \u2014 the caller passes an audioFallbackMs computed from the\n // FEC recovery window (computeFecDeliveryWindowMs). No magic default: when\n // absent, the independent audio-fallback timer is disabled (0) and\n // activation waits for real audio arrival.\n this.#audioFallbackMs = options?.audioFallbackMs ?? 0\n this.#crossfadeFrames = options?.crossfadeFrames ?? DEFAULT_CROSSFADE_FRAMES\n this.#maxOverlayBuffer = options?.maxOverlayBuffer ?? DEFAULT_MAX_OVERLAY_BUFFER\n this.#maxRepairInFlight = options?.maxRepairInFlight ?? 2\n this.#allowDeltaMulticastTakeoverAfterMoqKeyframe =\n options?.allowDeltaMulticastTakeoverAfterMoqKeyframe ?? false\n }\n\n onVideoFrame(cb: FrameCb) { this.#onVideoFrame = cb }\n onAudioFrame(cb: FrameCb) { this.#onAudioFrame = cb }\n onOverlayFrame(cb: FrameCb) { this.#onOverlayFrame = cb }\n onSourceSwitch(cb: SwitchCb) { this.#onSourceSwitch = cb }\n\n get activeSource(): SourceKind { return this.#active }\n\n // \u2500\u2500 Keyframe repair API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Register callback for keyframe repair requests. Player wires this to issue MoQ SUBSCRIBE. */\n onRepairRequest(cb: (expectedGroupId: number, trackName: string) => void): void {\n this.#onRepairRequest = cb\n }\n\n /**\n * Request repair for a lost keyframe group. Only fires when activeSource is 'multicast'.\n * Idempotent per groupId \u2014 duplicate calls for the same group are suppressed.\n * @param expectedGroupId - The group ID expected but not received\n * @param trackName - Track name for the SUBSCRIBE (e.g. 'video'). Default: 'video'.\n */\n repairLostGroup(expectedGroupId: number, trackName = 'video'): void {\n if (this.#active !== 'multicast') return // only repair on multicast path\n if (this.#repairInFlight.has(expectedGroupId)) return // idempotent\n if (this.#repairInFlight.size >= this.#maxRepairInFlight) {\n console.warn(\n `[MediaRouter] max repair in flight (${this.#maxRepairInFlight}), dropping repair for group ${expectedGroupId}`,\n )\n return\n }\n this.#repairInFlight.add(expectedGroupId)\n this.#onRepairRequest?.(expectedGroupId, trackName)\n }\n\n /**\n * Feed a recovered keyframe frame from the repair path.\n * Bypasses source arbitration entirely \u2014 goes directly to decoder callbacks.\n * Does NOT change activeSource. Does NOT trigger failbackToMoq.\n */\n feedRepair(data: Uint8Array, meta: FrameMeta, kind: FrameKind): void {\n // Repair only makes sense when multicast is active.\n // Silently drop if MoQ became active (race with failbackToMoq) to avoid\n // injecting stale-timestamp frames into the MoQ decoder path (WR-02).\n if (this.#active !== 'multicast') return\n const routedMeta = { ...meta, source: 'repair' as const, recovered: true }\n if (kind === 'video') this.#onVideoFrame?.(data, routedMeta)\n else this.#onAudioFrame?.(data, routedMeta)\n }\n\n /**\n * Clear repair-in-flight state for a group (called after repair completes or times out).\n */\n clearRepairInFlight(groupId: number): void {\n this.#repairInFlight.delete(groupId)\n }\n\n // \u2500\u2500 Phase 14: deltaActive state machine API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Configure the delta-track fallback state machine from catalog parameters.\n *\n * D-11: Thresholds derive from fec.sourceSymbols, fec.repairSymbols, framerate.\n * D-13: Probe interval derives from deltaProbeIntervalMs or interleaveDepthMs*2.\n * CLAUDE.md: error on bad init \u2014 throws if required inputs are absent.\n *\n * Calling again resets deltaActive=true and clears the window buffer (stream restart).\n */\n configureDelta(cfg: {\n framerate: number\n sourceSymbols: number\n repairSymbols: number\n deltaFailWindowBlocks?: number\n deltaProbeIntervalMs?: number\n interleaveDepthMs?: number\n }): void {\n if (typeof cfg.framerate !== 'number' || !Number.isFinite(cfg.framerate) || cfg.framerate <= 0) {\n throw new Error('[MediaRouter] configureDelta: framerate required and must be > 0')\n }\n if (typeof cfg.sourceSymbols !== 'number' || cfg.sourceSymbols <= 0) {\n throw new Error('[MediaRouter] configureDelta: sourceSymbols (K_delta) required and must be > 0')\n }\n if (typeof cfg.repairSymbols !== 'number' || cfg.repairSymbols <= 0) {\n throw new Error('[MediaRouter] configureDelta: repairSymbols (P_delta) required and must be > 0')\n }\n if (cfg.deltaProbeIntervalMs === undefined && cfg.interleaveDepthMs === undefined) {\n throw new Error(\n '[MediaRouter] configureDelta: either deltaProbeIntervalMs or interleaveDepthMs required for probe interval derivation'\n )\n }\n\n // Derivations \u2014 no magic floors, no hardcoded defaults (CLAUDE.md).\n this.#deltaWindowSize = cfg.deltaFailWindowBlocks ?? Math.ceil(cfg.framerate)\n this.#deltaFailThresholdRatio = cfg.repairSymbols / cfg.sourceSymbols\n this.#deltaRecoverThresholdRatio = this.#deltaFailThresholdRatio / 2\n // Without an explicit probe interval, use one complete signaled block span.\n this.#deltaProbeIntervalMs = cfg.deltaProbeIntervalMs ?? computeFecDeliveryWindowMs({\n interleaveDepthMs: cfg.interleaveDepthMs!,\n sourceSymbols: cfg.sourceSymbols,\n })\n\n // Reset state \u2014 useful for stream restart.\n this.#deltaActive = true\n this.#deltaWindow = []\n this.#lastProbeAt = 0\n this.#deltaConfigured = true\n }\n\n /**\n * Notify the state machine of a completed FEC block for the delta track.\n *\n * @param failed - true if the block was unrecoverable (FEC failure)\n * @param nowMs - caller-injected monotonic ms (no internal timer \u2014 D-13, CLAUDE.md)\n *\n * If configureDelta() has not been called, this is a silent no-op (pre-catalog state).\n */\n notifyDeltaBlock(failed: boolean, nowMs: number): void {\n if (!this.#deltaConfigured) return\n\n // Maintain sliding window \u2014 ring buffer semantics.\n this.#deltaWindow.push(failed)\n if (this.#deltaWindow.length > this.#deltaWindowSize) {\n this.#deltaWindow.shift()\n }\n\n // Window not yet full \u2014 insufficient data for decision.\n if (this.#deltaWindow.length < this.#deltaWindowSize) return\n\n const failedCount = this.#deltaWindow.filter(x => x).length\n const ratio = failedCount / this.#deltaWindowSize\n\n if (this.#deltaActive) {\n // Fallback transition: active \u2192 inactive (T-14-03: fires exactly once)\n if (ratio > this.#deltaFailThresholdRatio) {\n this.#deltaActive = false\n this.#lastProbeAt = nowMs\n this.#onDeltaFallbackCb?.()\n }\n } else {\n // Recovery transition: inactive \u2192 active (after probe interval + low ratio)\n if (\n (nowMs - this.#lastProbeAt) >= this.#deltaProbeIntervalMs &&\n ratio < this.#deltaRecoverThresholdRatio\n ) {\n this.#deltaActive = true\n this.#lastProbeAt = nowMs\n this.#onDeltaRecoverCb?.()\n }\n }\n }\n\n /** Register callback fired when delta track degrades past threshold (D-12). */\n onDeltaFallback(cb: () => void): void {\n this.#onDeltaFallbackCb = cb\n }\n\n /** Register callback fired when delta track recovers below recovery threshold (D-13). */\n onDeltaRecover(cb: () => void): void {\n this.#onDeltaRecoverCb = cb\n }\n\n /** Whether the delta track is currently considered healthy (true = active). */\n get deltaActive(): boolean {\n return this.#deltaActive\n }\n\n // \u2500\u2500 Test-visible accessors for threshold verification \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // These expose internal derived values for test assertions (Tests 3,4,5,6,7).\n // Prefixed with 'delta' to namespace clearly within the public API surface.\n\n /** Derived window size \u2014 exposed for test assertions (Test 3, 4). */\n get deltaWindowSize(): number { return this.#deltaWindowSize }\n /** Derived fail threshold ratio (P/K) \u2014 exposed for test assertions (Test 6). */\n get deltaFailThresholdRatio(): number { return this.#deltaFailThresholdRatio }\n /** Derived recovery threshold ratio ((P/K)/2) \u2014 exposed for test assertions (Test 7). */\n get deltaRecoverThresholdRatio(): number { return this.#deltaRecoverThresholdRatio }\n /** Derived probe interval ms \u2014 exposed for test assertions (Test 5a). */\n get deltaProbeIntervalMs(): number { return this.#deltaProbeIntervalMs }\n\n /**\n * Register a track name \u2192 type mapping from catalog.\n * Catalog is the default authority. Init data / inline signaling\n * takes precedence until the next catalog update.\n */\n registerTrackType(trackName: string, type: FrameKind): void {\n // Catalog overwrites any previous registration (including init).\n this.#trackTypes.set(trackName, { type, source: 'catalog' })\n }\n\n /**\n * Register a track name \u2192 type from init data / inline signaling (MMTP FT=0).\n * Authoritative until the next catalog update per \u00A75.3.\n * Does NOT overwrite an existing catalog registration.\n */\n registerTrackTypeFromInit(trackName: string, type: FrameKind): void {\n const existing = this.#trackTypes.get(trackName)\n if (existing?.source === 'catalog') return // catalog already set \u2014 don't downgrade\n this.#trackTypes.set(trackName, { type, source: 'init' })\n }\n\n /**\n * Assign a per-track source. Frames from this source bypass the binary\n * MoQ\u2194multicast switching for this track only.\n *\n * Throws TrackSourceConflictError if a source is already assigned for this\n * track without a clearTrackSource() in between.\n */\n setTrackSource(trackName: string, source: TrackSource, opts?: SetTrackSourceOptions): void {\n if (this.#trackSources.has(trackName)) {\n throw new TrackSourceConflictError(trackName)\n }\n\n // Resolve effective policy. opts.policy takes precedence; overlay=true is legacy 'wait'.\n const effectivePolicy: MigrationPolicy | undefined =\n opts?.policy ?? (opts?.overlay ? 'wait' : undefined)\n\n // For crossfade: open the binary-path window immediately so the first per-track frame\n // triggers the window (counter starts before the frame callback is wired).\n if (effectivePolicy === 'crossfade') {\n this.#crossfadeCounters.set(trackName, this.#crossfadeFrames)\n }\n\n const record: TrackSourceRecord = {\n source,\n unsubscribeFrame: () => {},\n emitCount: 0,\n }\n\n // Wire the frame callback\n record.unsubscribeFrame = source.onFrame((data, meta) => {\n record.emitCount++\n if (effectivePolicy === 'wait') {\n this.#handleOverlayFrame(data, meta)\n } else {\n // 'drop', 'crossfade', or undefined: emit immediately\n this.#emitForTrack(trackName, data, meta)\n }\n })\n\n // Wire the optional error callback \u2014 failback to binary switching\n if (source.onError) {\n record.unsubscribeError = source.onError(() => {\n this.clearTrackSource(trackName)\n })\n }\n\n this.#trackSources.set(trackName, record)\n }\n\n /**\n * Remove the per-track source for the given track.\n * Binary switching resumes for this track after this call.\n */\n clearTrackSource(trackName: string): void {\n const record = this.#trackSources.get(trackName)\n if (!record) return\n\n record.unsubscribeFrame()\n record.unsubscribeError?.()\n record.source.dispose?.()\n this.#trackSources.delete(trackName)\n\n // Clean up crossfade window if one was active for this track\n this.#crossfadeCounters.delete(trackName)\n\n // Reset overlay buffer if removing a non-media track (overlay/unknown)\n const reg = this.#trackTypes.get(trackName)\n const isMedia = reg?.type === 'video' || reg?.type === 'audio' ||\n (reg === undefined && (trackName === 'video' || trackName === 'audio'))\n if (!isMedia) {\n this.#overlayBoundaryReached = false\n this.#overlayBuffer = []\n }\n }\n\n /**\n * Signal that a FEC block boundary has been reached on the base track.\n * Overlay tracks waiting for alignment flush their buffered frames now.\n */\n notifyFecBlockBoundary(): void {\n if (this.#overlayBoundaryReached) return\n this.#overlayBoundaryReached = true\n\n // Flush buffered overlay frames\n const buffered = this.#overlayBuffer.splice(0)\n for (const { data, meta } of buffered) {\n this.#onOverlayFrame?.(data, meta)\n }\n }\n\n /**\n * Return the number of frames emitted from the per-track source for a given\n * track. Used in test-mode to verify per-track routing histogram.\n * Returns 0 if no per-track source is active for the track.\n */\n trackSourceEmitCount(trackName: string): number {\n return this.#trackSources.get(trackName)?.emitCount ?? 0\n }\n\n /** Feed a frame from the MoQ path. Suppressed when multicast is active OR a per-track source owns this track. */\n feedMoq(data: Uint8Array, meta: FrameMeta, kind: FrameKind) {\n // Per-track source takes precedence; allow through during crossfade window\n if (this.#trackSources.has(kind)) {\n const remaining = this.#crossfadeCounters.get(kind)\n if (remaining && remaining > 0) {\n // Decrement crossfade counter and allow this frame through\n const next = remaining - 1\n if (next === 0) {\n this.#crossfadeCounters.delete(kind)\n } else {\n this.#crossfadeCounters.set(kind, next)\n }\n // Fall through to emit below (no return)\n } else {\n return // suppressed \u2014 no crossfade window active\n }\n }\n if (this.#suppressed) return\n // Audio suppression is handled by SessionManager onSuppress callback \u2014\n // do NOT independently suppress based on multicastAudioReceived.\n // The state machine decides when to switch; the router just routes.\n const routedMeta = { ...meta, source: 'moq' as const }\n if (kind === 'video') this.#onVideoFrame?.(data, routedMeta)\n else this.#onAudioFrame?.(data, routedMeta)\n }\n\n /** Feed a frame from the multicast path. Video waits for keyframe before activating. */\n feedMulticast(data: Uint8Array, meta: FrameMeta, kind: FrameKind) {\n // Per-track source takes precedence; allow through during crossfade window\n if (this.#trackSources.has(kind)) {\n const remaining = this.#crossfadeCounters.get(kind)\n if (remaining && remaining > 0) {\n const next = remaining - 1\n if (next === 0) {\n this.#crossfadeCounters.delete(kind)\n } else {\n this.#crossfadeCounters.set(kind, next)\n }\n // Fall through to emit below (no return)\n } else {\n return // suppressed\n }\n }\n\n if (kind === 'video') {\n if (!this.#multicastVideoKeyed) {\n const moqSeededDelta =\n !meta.keyframe &&\n this.#allowDeltaMulticastTakeoverAfterMoqKeyframe &&\n this.#moqVideoKeyframeEmitted\n if (!meta.keyframe && !moqSeededDelta) return // drop until first safe decode point\n this.#multicastVideoKeyed = true\n const pendingMeta: FrameMeta = { ...meta, source: 'multicast' }\n if (!moqSeededDelta) pendingMeta.sourceDiscontinuity = true\n this.#pendingMulticastVideo = {\n data: data.slice(),\n meta: pendingMeta,\n }\n // If audio is required but hasn't arrived yet, start a fallback timer.\n // Audio FEC blocks may recover after video \u2014 don't block activation forever.\n // Only arms when a catalog-derived audioFallbackMs was supplied (>0).\n if (this.#requireAudio && this.#audioFallbackMs > 0 && !this.#multicastAudioReceived && !this.#audioFallbackTimer) {\n this.#audioFallbackTimer = setTimeout(() => {\n if (!this.#multicastAudioReceived && this.#active !== 'multicast') {\n this.#multicastAudioReceived = true // force\n // Also release the MoQ-audio-warmup gate so the fallback actually\n // activates \u2014 otherwise #tryActivateMulticast would still bail.\n this.#moqAudioWarmed = true\n this.#tryActivateMulticast()\n }\n }, this.#audioFallbackMs)\n }\n } else if (this.#active !== 'multicast') {\n // Do not feed video into the multicast decoder while the source switch\n // is still pending. Keep the newest keyframe as the post-activation\n // decoder opener and drop deltas until takeover commits.\n if (meta.keyframe) {\n this.#pendingMulticastVideo = {\n data: data.slice(),\n meta: { ...meta, source: 'multicast', sourceDiscontinuity: true },\n }\n }\n this.#tryActivateMulticast()\n return\n }\n if (this.#active === 'multicast') this.#onVideoFrame?.(data, { ...meta, source: 'multicast' })\n this.#tryActivateMulticast()\n } else {\n this.#multicastAudioReceived = true\n if (this.#audioFallbackTimer) {\n clearTimeout(this.#audioFallbackTimer)\n this.#audioFallbackTimer = null\n }\n // BLO-3035 layer 5: in a multicast-first scenario (no MoQ unicast audio\n // source) `notifyMoqAudioEmit()` is never called and the audio-fallback\n // timer's force-set is bypassed (the timer's inner `!multicastAudioReceived`\n // check returns early because audio already arrived). Without this gate\n // `#moqAudioWarmed` stays false forever and `#tryActivateMulticast` never\n // fires `onSourceSwitch('multicast')` \u2014 the player can't know to emit\n // `__MULTICAST_TAKEOVER_TIME`. Treat the arrival of multicast audio as\n // sufficient evidence to release the warmup gate. For the MoQ\u2192multicast\n // handoff case `notifyMoqAudioEmit()` will already have set this flag, so\n // the assignment is idempotent.\n if (!this.#moqAudioWarmed) this.#moqAudioWarmed = true\n // Activate BEFORE delivering the frame \u2014 the source switch callback\n // (e.g. ring buffer reset) must fire before the first multicast audio\n // frame reaches the backend. Otherwise the NTP timestamp hits the\n // MoQ-era ring buffer base \u2192 overflow \u2192 silence gap.\n this.#tryActivateMulticast()\n // Only emit multicast audio AFTER takeover succeeds. Before takeover,\n // MoQ audio is still flowing through feedMoq \u2192 #onAudioFrame; emitting\n // multicast audio too would double-feed the backend (2x audio frames,\n // pitch wobble and distortion). Post-takeover, feedMoq is suppressed\n // (#suppressed=true) so only multicast audio reaches the backend.\n if (this.#active === 'multicast') {\n this.#onAudioFrame?.(data, { ...meta, source: 'multicast' })\n } else if (this.#pendingMulticastToken !== null) {\n this.#pendingMulticastAudio = { data: data.slice(), meta: { ...meta, source: 'multicast' } }\n }\n }\n }\n\n /**\n * MoQ unicast audio warmup gate. When audio is required, multicast takeover\n * waits until the MoQ unicast audio decoder has emitted at least one frame\n * (so downstream samples-before-takeover counters observe nonzero) or until\n * the existing audio-fallback timer forces the flag true.\n */\n #moqAudioWarmed = false\n\n /** Called by the player when the MoQ unicast audio decoder emits first frame. */\n public notifyMoqAudioEmit(): void {\n if (this.#moqAudioWarmed) return\n this.#moqAudioWarmed = true\n this.#tryActivateMulticast()\n }\n\n /**\n * Called by the player after a MoQ video keyframe has reached the active\n * decoder path. Used only by MSE/MMTP continuity switching; decoder-reset\n * paths leave allowDeltaMulticastTakeoverAfterMoqKeyframe disabled.\n */\n public notifyMoqVideoKeyframeEmit(): void {\n this.#moqVideoKeyframeEmitted = true\n this.#tryActivateMulticast()\n }\n\n #tryActivateMulticast() {\n if (this.#active === 'multicast') return\n if (this.#pendingMulticastToken !== null) return\n if (!this.#multicastVideoKeyed) return\n if (this.#requireAudio && !this.#multicastAudioReceived) return\n if (this.#requireAudio && !this.#moqAudioWarmed) return\n const token = ++this.#sourceSwitchToken\n const maybeReady = this.#onSourceSwitch?.('multicast')\n if (!maybeReady || typeof (maybeReady as Promise<void>).then !== 'function') {\n this.#commitMulticastActivation(token)\n return\n }\n const ready = Promise.resolve(maybeReady)\n this.#pendingMulticastToken = token\n this.#sourceSwitchReady = ready\n void ready.then(\n () => this.#commitMulticastActivation(token),\n err => this.#rejectMulticastActivation(token, err),\n ).finally(() => {\n if (this.#sourceSwitchReady === ready) this.#sourceSwitchReady = null\n })\n }\n\n #commitMulticastActivation(token: number) {\n if (token !== this.#sourceSwitchToken) return\n this.#active = 'multicast'\n this.#suppressed = true\n this.#pendingMulticastToken = null\n const video = this.#pendingMulticastVideo\n this.#pendingMulticastVideo = null\n const audio = this.#pendingMulticastAudio\n this.#pendingMulticastAudio = null\n if (video) this.#onVideoFrame?.(video.data, video.meta)\n if (audio) this.#onAudioFrame?.(audio.data, audio.meta)\n }\n\n #rejectMulticastActivation(token: number, err: unknown) {\n if (token !== this.#sourceSwitchToken) return\n if (this.#pendingMulticastToken === token) this.#pendingMulticastToken = null\n this.#pendingMulticastVideo = null\n this.#pendingMulticastAudio = null\n console.warn('[MediaRouter] onSourceSwitch(multicast) failed', err)\n }\n\n /** Switch back to MoQ immediately (called on multicast failback). */\n failbackToMoq() {\n const hadPendingMulticast = this.#pendingMulticastToken !== null\n if (this.#active === 'moq' && !hadPendingMulticast) return // already on MoQ, no-op\n ++this.#sourceSwitchToken\n this.#active = 'moq'\n this.#suppressed = false\n this.#pendingMulticastToken = null\n this.#pendingMulticastVideo = null\n this.#pendingMulticastAudio = null\n this.#sourceSwitchReady = null\n this.#multicastVideoKeyed = false\n this.#multicastAudioReceived = false\n this.#moqVideoKeyframeEmitted = false\n // A pending audio-fallback timer belongs to the abandoned takeover attempt.\n // Left running it would force-set the audio flags against the next attempt's\n // fresh state (BLO-9413 failback coherence \u2014 every takeover-era flag/timer\n // unwinds on this edge).\n if (this.#audioFallbackTimer) {\n clearTimeout(this.#audioFallbackTimer)\n this.#audioFallbackTimer = null\n }\n this.#onSourceSwitch?.('moq')\n }\n\n /** Dispose timers and per-track sources. Call on teardown to prevent\n * stale timer callbacks firing into garbage-collected closures (WR-03). */\n dispose(): void {\n if (this.#audioFallbackTimer) {\n clearTimeout(this.#audioFallbackTimer)\n this.#audioFallbackTimer = null\n }\n for (const [name] of this.#trackSources) {\n this.clearTrackSource(name)\n }\n }\n\n // \u2500\u2500 Private helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Emit a frame on the correct per-track callback using the type registry.\n * Falls back to name match if no type registered (backward compat). */\n #emitForTrack(trackName: string, data: Uint8Array, meta: FrameMeta): void {\n // Prefer explicit type registry (catalog or init data)\n const reg = this.#trackTypes.get(trackName)\n if (reg?.type === 'video') {\n this.#onVideoFrame?.(data, meta)\n } else if (reg?.type === 'audio') {\n this.#onAudioFrame?.(data, meta)\n } else if (reg !== undefined) {\n // Registered but unknown type \u2014 overlay\n this.#onOverlayFrame?.(data, meta)\n } else {\n // Not registered \u2014 fall back to name match (backward compat for tests/legacy)\n if (trackName === 'video') this.#onVideoFrame?.(data, meta)\n else if (trackName === 'audio') this.#onAudioFrame?.(data, meta)\n else this.#onOverlayFrame?.(data, meta)\n }\n }\n\n /** Handle an overlay frame: buffer until first FEC block boundary, then pass through. */\n #handleOverlayFrame(data: Uint8Array, meta: FrameMeta): void {\n if (this.#overlayBoundaryReached) {\n this.#onOverlayFrame?.(data, meta)\n return\n }\n\n // Buffer until boundary \u2014 enforcing cap for T-02-17 DoS mitigation\n if (this.#overlayBuffer.length >= this.#maxOverlayBuffer) {\n console.warn(\n `[MediaRouter] overlay buffer full (${this.#maxOverlayBuffer} frames); dropping frame ts=${meta.timestamp}`\n )\n return\n }\n this.#overlayBuffer.push({ data, meta })\n }\n}\n"],
5
+ "mappings": ";AAwBA,SAAS,wBAAwB;AAmJ1B,SAAS,2BACd,QACQ;AACR,QAAM,kBAAkB,OAAO;AAC/B,QAAM,OAAO,OAAO;AACpB,MAAI,CAAC,OAAO,SAAS,eAAe,KAAK,mBAAmB,GAAG;AAC7D,UAAM,IAAI;AAAA,MACR,kCAAkC,eAAe;AAAA,IAEnD;AAAA,EACF;AACA,MAAI,CAAC,OAAO,SAAS,IAAI,KAAK,QAAQ,GAAG;AACvC,UAAM,IAAI;AAAA,MACR,uBAAuB,IAAI;AAAA,IAE7B;AAAA,EACF;AAGA,MAAI,OAAO,mBAAmB,OAAW,QAAO,KAAK,KAAK,eAAe;AACzE,SAAO,iBAAiB,iBAAiB,OAAO,cAAc;AAChE;;;ACxFO,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YAA4B,WAAmB;AAC7C,UAAM,sCAAsC,SAAS,gCAAgC;AAD3D;AAE1B,SAAK,OAAO;AAAA,EACd;AACF;AAeA,IAAM,2BAA2B;AAoBjC,IAAM,6BAA6B;AAU5B,IAAM,cAAN,MAAkB;AAAA,EACvB,UAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,0BAA0B;AAAA,EAC1B,2BAA2B;AAAA,EAC3B;AAAA,EAC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