@blockcast/mmt-container 2.2.0-main.cc3fe0684403 → 2.2.0-main.d79fbb738dc0

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 (126) hide show
  1. package/README.md +125 -2
  2. package/dist/__tests__/ad-creative-signer.d.ts +11 -0
  3. package/dist/__tests__/ad-creative-signer.d.ts.map +1 -0
  4. package/dist/__tests__/test-utils.d.ts +1 -0
  5. package/dist/__tests__/test-utils.d.ts.map +1 -1
  6. package/dist/ad-creative-record.d.ts +65 -0
  7. package/dist/ad-creative-record.d.ts.map +1 -0
  8. package/dist/ad-creative-record.js +2281 -0
  9. package/dist/ad-creative-record.js.map +7 -0
  10. package/dist/ad-creative-timeline.d.ts +102 -0
  11. package/dist/ad-creative-timeline.d.ts.map +1 -0
  12. package/dist/ad-creative-timeline.js +2529 -0
  13. package/dist/ad-creative-timeline.js.map +7 -0
  14. package/dist/block-policy.d.ts +128 -14
  15. package/dist/block-policy.d.ts.map +1 -1
  16. package/dist/block-policy.js +472 -27
  17. package/dist/block-policy.js.map +2 -2
  18. package/dist/browser-runtime.js +1040 -120
  19. package/dist/browser-runtime.js.map +4 -4
  20. package/dist/carp-catalog.d.ts +1 -0
  21. package/dist/carp-catalog.d.ts.map +1 -1
  22. package/dist/carp-catalog.js +34 -0
  23. package/dist/carp-catalog.js.map +4 -4
  24. package/dist/catalog-fec-params.js.map +1 -1
  25. package/dist/catalog-network-source.d.ts +1 -17
  26. package/dist/catalog-network-source.d.ts.map +1 -1
  27. package/dist/catalog-network-source.js +25 -19
  28. package/dist/catalog-network-source.js.map +3 -3
  29. package/dist/cmaf-block-assembler.d.ts +10 -2
  30. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  31. package/dist/cmaf-block-assembler.js +30 -8
  32. package/dist/cmaf-block-assembler.js.map +3 -3
  33. package/dist/codec-utils.d.ts.map +1 -1
  34. package/dist/codec-utils.js +16 -3
  35. package/dist/codec-utils.js.map +2 -2
  36. package/dist/conceal-timeline.d.ts +24 -1
  37. package/dist/conceal-timeline.d.ts.map +1 -1
  38. package/dist/conceal-timeline.js +201 -4
  39. package/dist/conceal-timeline.js.map +3 -3
  40. package/dist/datagram-leg-deadline.d.ts +26 -2
  41. package/dist/datagram-leg-deadline.d.ts.map +1 -1
  42. package/dist/datagram-leg-deadline.js +14 -2
  43. package/dist/datagram-leg-deadline.js.map +2 -2
  44. package/dist/event-timeline-mmtp.d.ts +17 -0
  45. package/dist/event-timeline-mmtp.d.ts.map +1 -0
  46. package/dist/event-timeline-mmtp.js +3117 -0
  47. package/dist/event-timeline-mmtp.js.map +7 -0
  48. package/dist/fec-manager.d.ts +24 -3
  49. package/dist/fec-manager.d.ts.map +1 -1
  50. package/dist/fec-manager.js +531 -38
  51. package/dist/fec-manager.js.map +2 -2
  52. package/dist/feed-gate.d.ts +114 -0
  53. package/dist/feed-gate.d.ts.map +1 -0
  54. package/dist/feed-gate.js +175 -0
  55. package/dist/feed-gate.js.map +7 -0
  56. package/dist/index.d.ts +4 -3
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +16 -2
  59. package/dist/index.js.map +2 -2
  60. package/dist/iso-bmff-timing.d.ts +16 -0
  61. package/dist/iso-bmff-timing.d.ts.map +1 -1
  62. package/dist/iso-bmff-timing.js +28 -0
  63. package/dist/iso-bmff-timing.js.map +2 -2
  64. package/dist/mfu-reassembler.d.ts +2 -0
  65. package/dist/mfu-reassembler.d.ts.map +1 -1
  66. package/dist/mfu-reassembler.js +4 -2
  67. package/dist/mfu-reassembler.js.map +2 -2
  68. package/dist/mmtp-container-parser.d.ts +12 -0
  69. package/dist/mmtp-container-parser.d.ts.map +1 -1
  70. package/dist/mmtp-container-parser.js +73 -3
  71. package/dist/mmtp-container-parser.js.map +2 -2
  72. package/dist/mmtp-container-parser.no-modules.js +103 -25
  73. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  74. package/dist/mmtp-decode-pipeline.js +73 -3
  75. package/dist/mmtp-decode-pipeline.js.map +2 -2
  76. package/dist/mmtp-router.d.ts +20 -2
  77. package/dist/mmtp-router.d.ts.map +1 -1
  78. package/dist/mmtp-router.js +150 -23
  79. package/dist/mmtp-router.js.map +3 -3
  80. package/dist/multicast-auth-catalog.js.map +1 -1
  81. package/dist/multicast-input.js.map +1 -1
  82. package/dist/multicast-manager.d.ts +23 -2
  83. package/dist/multicast-manager.d.ts.map +1 -1
  84. package/dist/multicast-manager.js +737 -86
  85. package/dist/multicast-manager.js.map +3 -3
  86. package/dist/multicast-transport.js +44 -22
  87. package/dist/multicast-transport.js.map +2 -2
  88. package/dist/no-modules.js +98 -22
  89. package/dist/no-modules.js.map +4 -4
  90. package/dist/repair-fetch.d.ts +15 -7
  91. package/dist/repair-fetch.d.ts.map +1 -1
  92. package/dist/repair-fetch.js +34 -7
  93. package/dist/repair-fetch.js.map +2 -2
  94. package/dist/wasm-mfu-reassembler.js.map +2 -2
  95. package/dist/wasm-mmtp-container-parser.js +73 -3
  96. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  97. package/package.json +17 -5
  98. package/schemas/catalog.schema.json +7 -2
  99. package/src/ad-creative-record.ts +276 -0
  100. package/src/ad-creative-timeline.ts +409 -0
  101. package/src/block-policy.ts +673 -42
  102. package/src/carp-catalog.ts +9 -0
  103. package/src/catalog-network-source.ts +3 -37
  104. package/src/cmaf-block-assembler.ts +17 -0
  105. package/src/codec-utils.ts +19 -3
  106. package/src/conceal-timeline.ts +60 -5
  107. package/src/datagram-leg-deadline.ts +34 -2
  108. package/src/event-timeline-mmtp.ts +55 -0
  109. package/src/fec-manager.ts +84 -12
  110. package/src/feed-gate.ts +295 -0
  111. package/src/index.ts +22 -0
  112. package/src/iso-bmff-timing.ts +33 -0
  113. package/src/mfu-reassembler.ts +4 -0
  114. package/src/mmtp-container-parser.ts +51 -5
  115. package/src/mmtp-router.ts +116 -4
  116. package/src/multicast-manager.ts +31 -0
  117. package/src/repair-fetch.ts +70 -19
  118. package/test-vectors/catalog/README.md +1 -0
  119. package/test-vectors/catalog/negative/event-timeline-empty-event-type.json +41 -0
  120. package/test-vectors/catalog/positive/event-timeline-ad-creative.json +41 -0
  121. package/test-vectors/catalog/positive/event-timeline-wallclock-no-depends.json +38 -0
  122. package/test-vectors/catalog/positive/multicast-event-timeline.json +81 -0
  123. package/test-vectors/catalog/section-codes.json +1 -0
  124. package/test-vectors/catalog-timing.json +184 -1
  125. package/test-vectors/frame-needs-v1.json +295 -0
  126. package/test-vectors/repair-policy-v1.json +98 -18
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../mmt-base/src/mmtp.ts", "../../mmt-base/src/ntp-short.ts", "../../mmt-base/src/serial-number.ts", "../../mmt-base/src/fec-block-profile.ts", "../../mmt-base/src/fec-bindings.ts", "../../mmt-base/src/mmtp-siblings.ts", "../../mmt-base/src/datagram-leg-size.ts", "../src/repair-fetch.ts", "../src/block-policy.ts", "../src/repair-layers.ts"],
4
- "sourcesContent": ["/**\n * @mmt/container - MMTP Parser\n *\n * MMTP (MMT Protocol) packet parser based on ISO/IEC 23008-1:2023 Section 9.2\n *\n * MMTP header format (12 bytes):\n * - Byte 0: V(2) | C(1) | FEC_type(2) | r(1) | X(1) | R(1)\n * - Byte 1: reserved(2) | packet_type(6)\n * - Bytes 2-3: packet_id (big-endian)\n * - Bytes 4-7: timestamp (big-endian, 32-bit)\n * - Bytes 8-11: sequence_number (big-endian)\n *\n * FEC_type values:\n * - 0: No FEC / source packet\n * - 1: FEC mode 0 (source with FEC payload ID)\n * - 2: FEC repair packet mode 0\n * - 3: FEC repair packet mode 1\n *\n * @packageDocumentation\n */\n\nexport interface MMTPHeader {\n version: number\n /** Packet type: 0x00=MPU, 0x02=Signaling, 0x03=Repair */\n packetType: number\n packetId: number\n timestamp: bigint\n sequenceNumber: number\n payloadLength: number\n fecType: number\n /** C flag: header carries a 32-bit packet_counter. */\n packetCounterFlag: boolean\n packetCounter?: number\n /** X flag: header carries an extension header and value. */\n extensionFlag: boolean\n extension?: { type: number; data: Uint8Array }\n /** Byte offset at which the MMTP payload begins. */\n headerLength: number\n /** Random Access Point flag - indicates keyframe (ISO 23008-1, byte 0 bit 0) */\n rapFlag: boolean\n}\n\nexport interface MPUHeader {\n mpuSequenceNumber: number\n fragmentationIndicator: number // FI: 0=complete, 1=first, 2=middle, 3=last\n /** 8-bit MPU fragment_counter from byte 3. */\n fragmentCounter: number\n /** T flag: 1=timed media (14-byte MFU DU header), 0=non-timed (4-byte header) */\n timedFlag: number\n /** A flag: aggregated MPU payload. This strict profile requires A=0. */\n aggregationFlag: boolean\n /** MPU payload_length (bytes 0-1): bytes after the length field, including\n * the remaining six MPU-header bytes and all data-unit bytes. */\n payloadLength: number\n}\n\nexport interface MFUDuHeader {\n movieFragmentSequenceNumber: number\n sampleNumber: number\n offset: number\n priority: number\n dependencyCounter: number\n}\n\nexport interface MMTPPacket {\n header: MMTPHeader\n payload: Uint8Array\n}\n\nexport const MMTP_HEADER_SIZE = 12\nexport const MPU_HEADER_SIZE = 8\nexport const MFU_DU_HEADER_SIZE_TIMED = 14 // T=1: timed media (video/audio samples)\nexport const MFU_DU_HEADER_SIZE_NONTIMED = 4 // T=0: non-timed media (item_id only)\n\nconst MPU_LENGTH_FIELD_SIZE = 2\nconst MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE\nexport const SOURCE_FEC_PAYLOAD_ID_SIZE = 4\n\n// MMTP Packet Types (ISO/IEC 23008-1:2023 Section 9.2.2)\nexport const PACKET_TYPE_MPU = 0x00\nexport const PACKET_TYPE_SIGNALING = 0x02\nexport const PACKET_TYPE_REPAIR = 0x03\n\n// AL-FEC Signaling Message ID (ISO/IEC 23008-1:2023 Amendment 1:2025)\nexport const ALFEC_MESSAGE_ID = 0x0203\n\n/**\n * MMTP `packet_id` of the signaling flow, which carries PACKET_TYPE_SIGNALING\n * packets such as the AL-FEC message (ALFEC_MESSAGE_ID). The FFmpeg `moq_mmt`\n * muxer sends that message on this packet_id into the same multicast group as\n * the media, and moqcast-draft (PR #44) makes advertising it for a track a\n * MUST NOT. A track's packet_id is therefore 1..MMTP_PACKET_ID_MAX.\n */\nexport const MMTP_SIGNALING_PACKET_ID = 0\n\n/** Largest value of the 16-bit MMTP `packet_id` header field. */\nexport const MMTP_PACKET_ID_MAX = 0xffff\n\n// fec_code_id_for_repair_flow code points (ISO/IEC 23008-10 Table 1;\n// draft-ramadan-moq-mmt-01 Section 8.3).\nexport const FEC_CODE_REED_SOLOMON = 1\nexport const FEC_CODE_RAPTORQ = 3\n\n/**\n * Parse MMTP header from buffer\n */\nexport function parseMMTPHeader(buffer: Uint8Array): MMTPHeader {\n if (buffer.length < MMTP_HEADER_SIZE) {\n throw new Error(`MMTP packet too small: ${buffer.length} bytes`)\n }\n\n const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n\n const version = (buffer[0]! >> 6) & 0x03\n if (version !== 0) {\n throw new Error(`Unsupported MMTP version: ${version}`)\n }\n\n // Extract FEC type from byte 0, bits 3-4\n const fecType = (buffer[0]! >> 3) & 0x03\n const packetCounterFlag = (buffer[0]! & 0x20) !== 0\n const extensionFlag = (buffer[0]! & 0x02) !== 0\n\n // Extract RAP flag from byte 0, bit 0 (R bit - Random Access Point)\n const rapFlag = (buffer[0]! & 0x01) === 1\n\n // ISO/IEC 23008-1:2023 Figure 8 (V=0) places reserved(2) before\n // packet_type(6), so packet_type occupies the low six bits of byte 1.\n const packetType = buffer[1]! & 0x3F\n\n let offset = 2\n\n // Packet ID (2 bytes, big-endian)\n const packetId = view.getUint16(offset, false)\n offset += 2\n\n // Timestamp (4 bytes, big-endian)\n const timestamp = BigInt(view.getUint32(offset, false))\n offset += 4\n\n // Sequence number (4 bytes, big-endian)\n const sequenceNumber = view.getUint32(offset, false)\n offset += 4\n\n let packetCounter: number | undefined\n if (packetCounterFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in packet_counter')\n packetCounter = view.getUint32(offset, false)\n offset += 4\n }\n\n let extension: { type: number; data: Uint8Array } | undefined\n if (extensionFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in header extension')\n const type = view.getUint16(offset, false)\n const length = view.getUint16(offset + 2, false)\n offset += 4\n if (offset + length > buffer.length) throw new Error('MMTP packet truncated in header extension value')\n extension = { type, data: buffer.subarray(offset, offset + length) }\n offset += length\n }\n\n return {\n version,\n packetType,\n packetId,\n timestamp,\n sequenceNumber,\n payloadLength: buffer.length - offset,\n fecType,\n packetCounterFlag,\n packetCounter,\n extensionFlag,\n extension,\n headerLength: offset,\n rapFlag,\n }\n}\n\n/**\n * The MMTP `packet_id` of `buffer`, or null exactly when parseMMTPHeader would\n * throw for it (short buffer, V != 0, truncated packet_counter or header\n * extension).\n *\n * This is the per-packet filter a receiver runs before any other work, so it\n * builds no header object, DataView or BigInt timestamp (BLO-36599). Use\n * parseMMTPHeader when any other header field is needed.\n */\nexport function readMMTPPacketId(buffer: Uint8Array): number | null {\n if (buffer.length < MMTP_HEADER_SIZE) return null\n const flags = buffer[0]!\n if (((flags >> 6) & 0x03) !== 0) return null\n let offset = MMTP_HEADER_SIZE\n if ((flags & 0x20) !== 0) {\n if (offset + 4 > buffer.length) return null\n offset += 4\n }\n if ((flags & 0x02) !== 0) {\n if (offset + 4 > buffer.length) return null\n const length = (buffer[offset + 2]! << 8) | buffer[offset + 3]!\n if (offset + 4 + length > buffer.length) return null\n }\n return (buffer[2]! << 8) | buffer[3]!\n}\n\n/**\n * Unwrap MMTP packet to extract payload\n */\nexport function unwrapMMTP(buffer: Uint8Array): MMTPPacket {\n const header = parseMMTPHeader(buffer)\n const payload = buffer.subarray(header.headerLength)\n\n return { header, payload }\n}\n\n/**\n * Parse MPU header from payload\n * ISO/IEC 23008-1:2023 Section 9.2.3.3\n *\n * MPU Header format (8 bytes) as written by FFmpeg/libmmt:\n * - Bytes 0-1: payload_length (16 bits, big-endian)\n * - Byte 2: FT(4) | T(1) | FI(2) | A(1)\n * - Byte 3: fragment_counter (8 bits)\n * - Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n */\nexport function parseMPUHeader(payload: Uint8Array): MPUHeader {\n if (payload.length < MPU_HEADER_SIZE) {\n throw new Error(`Payload too small for MPU header: ${payload.length} bytes`)\n }\n\n const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength)\n\n // Bytes 0-1: payload_length (16 bits, big-endian)\n const payloadLength = view.getUint16(0, false)\n\n // Byte 2: FT(4) | T(1) | FI(2) | A(1)\n const flagsByte = payload[2]!\n const timedFlag = (flagsByte >> 3) & 0x01\n const fragmentationIndicator = (flagsByte >> 1) & 0x03\n const aggregationFlag = (flagsByte & 0x01) !== 0\n\n // Byte 3: fragment_counter (8 bits). The high bit is part of the counter in\n // the current libmmt/FFmpeg writer ABI.\n const fragmentCounter = payload[3]!\n\n // Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n const mpuSequenceNumber = view.getUint32(4, false)\n\n return {\n mpuSequenceNumber,\n fragmentationIndicator,\n fragmentCounter,\n timedFlag,\n aggregationFlag,\n payloadLength,\n }\n}\n\nexport function parseTimedMfuDuHeader(payload: Uint8Array, offset: number): MFUDuHeader | null {\n if (offset < 0 || offset + MFU_DU_HEADER_SIZE_TIMED > payload.length) return null\n const view = new DataView(payload.buffer, payload.byteOffset + offset, MFU_DU_HEADER_SIZE_TIMED)\n return {\n movieFragmentSequenceNumber: view.getUint32(0, false),\n sampleNumber: view.getUint32(4, false),\n offset: view.getUint32(8, false),\n priority: payload[offset + 12]!,\n dependencyCounter: payload[offset + 13]!,\n }\n}\n\n/**\n * Why `extractMFUPayload` refused a packet.\n *\n * These identifiers are part of the public contract: callers surface them in\n * diagnostics, so renaming one is a breaking change.\n */\nexport type MFURejectionGate =\n | 'packet-shorter-than-mmtp-plus-mpu-header'\n | 'mmtp-header-unparseable'\n | 'not-an-mpu-packet'\n | 'payload-shorter-than-mpu-header'\n | 'aggregation-flag-set'\n | 'mpu-payload-length-below-header-remainder'\n | 'mpu-declared-end-exceeds-payload'\n | 'mfu-offset-at-or-past-declared-end'\n | 'source-fec-payload-id-width-mismatch'\n | 'declared-trailers-unresolved'\n\nexport interface MFURejection {\n gate: MFURejectionGate\n /** Human-readable detail, including the byte arithmetic that decided it. */\n detail: string\n}\n\ninterface MfuPayloadLayout {\n hasMfuDuHeader: boolean\n mfuOffset: number\n dataEnd: number\n}\n\nfunction resolveMfuPayloadLayout(\n mpu: MPUHeader,\n fragmentType: number,\n payload: Uint8Array,\n): { layout: MfuPayloadLayout } | { rejection: MFURejection } {\n if (mpu.payloadLength < MPU_HEADER_REMAINDER_SIZE) {\n return {\n rejection: {\n gate: 'mpu-payload-length-below-header-remainder',\n detail: `payload_length=${mpu.payloadLength} < ${MPU_HEADER_REMAINDER_SIZE}`,\n },\n }\n }\n\n // ISO/IEC 23008-1 defines payload_length from immediately after its own\n // two-byte field. It therefore includes the remaining six MPU-header bytes.\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + mpu.payloadLength\n if (declaredEnd > payload.length) {\n return {\n rejection: {\n gate: 'mpu-declared-end-exceeds-payload',\n detail:\n `payload_length=${mpu.payloadLength} implies end=${declaredEnd}, ` +\n `payload is ${payload.length} bytes`,\n },\n }\n }\n\n const hasHeader = fragmentType === 2 && mpu.fragmentationIndicator <= 1\n const mfuHeaderSize = mpu.timedFlag ? MFU_DU_HEADER_SIZE_TIMED : MFU_DU_HEADER_SIZE_NONTIMED\n const mfuOffset = MPU_HEADER_SIZE + (hasHeader ? mfuHeaderSize : 0)\n if (mfuOffset >= declaredEnd) {\n return {\n rejection: {\n gate: 'mfu-offset-at-or-past-declared-end',\n detail: `mfuOffset=${mfuOffset} >= declaredEnd=${declaredEnd}`,\n },\n }\n }\n\n return {\n layout: {\n hasMfuDuHeader: hasHeader,\n mfuOffset,\n dataEnd: declaredEnd,\n },\n }\n}\n\n// Legacy detached per-packet authenticator suffix `[0xf0a1][len][auth]`. Its\n// producer was removed (BLO-16483) and nothing verifies it any more; provenance\n// is the signed per-group manifest. Receivers still skip an exact suffix so a\n// stale producer degrades to unauthenticated playback instead of dropped\n// packets. ponytail: hard-cut to reject once no deployed producer can emit it.\nconst LEGACY_TRAILER_EXT_TYPE = 0xf0a1\nconst LEGACY_TRAILER_HEADER_SIZE = 4\n\nfunction isEmptyOrExactLegacyTrailer(payload: Uint8Array, start: number, end: number): boolean {\n if (start === end) return true\n if (start < 0 || end > payload.length || start + LEGACY_TRAILER_HEADER_SIZE > end) {\n return false\n }\n\n const view = new DataView(\n payload.buffer,\n payload.byteOffset + start,\n end - start,\n )\n if (view.getUint16(0, false) !== LEGACY_TRAILER_EXT_TYPE) return false\n\n const authLength = view.getUint16(2, false)\n return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end\n}\n\ninterface DeclaredTrailerLayout {\n hasFecId: boolean\n}\n\n/** Options for extractMFUPayload and explainMFURejection. */\nexport interface MFUExtractOptions {\n /**\n * When true, do NOT subtract the Source FEC Payload ID from the payload\n * boundary, even if fecType >= 1. For FEC-recovered symbols whose FEC PID\n * was already stripped before WASM decoding.\n */\n skipFecId?: boolean\n}\n\nfunction resolveDeclaredTrailers(\n payload: Uint8Array,\n declaredEnd: number,\n fecType: number,\n options?: MFUExtractOptions,\n): DeclaredTrailerLayout | null {\n if (declaredEnd > payload.length) return null\n\n if (options?.skipFecId) {\n return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)\n ? { hasFecId: false }\n : null\n }\n\n if (fecType === 1) {\n const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {\n return null\n }\n return { hasFecId: true }\n }\n if (fecType !== 0) return null\n\n if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {\n return { hasFecId: false }\n }\n\n return null\n}\n\n/**\n * Extract NAL unit payload from MMTP packet\n */\nexport function extractNALUnit(mmtpPacket: Uint8Array): Uint8Array {\n const extraction = extractMFUPayload(mmtpPacket)\n if (!extraction) throw new Error('Malformed MMTP MPU payload')\n return extraction.data\n}\n\n/** Result of extracting MFU payload from an MMTP packet */\nexport interface MFUExtraction {\n /** MMTP header fields */\n header: MMTPHeader\n /** MPU header fields */\n mpu: MPUHeader\n /** Fragment type (FT field, 4 bits): 0=metadata, 2=MFU data */\n fragmentType: number\n /** MFU payload data (video/audio bytes, headers stripped, FEC ID excluded) */\n data: Uint8Array\n /** Parsed timed MFU DU header when present, otherwise null */\n mfuDuHeader: MFUDuHeader | null\n /** Non-timed MFU Item_ID when the 4-byte DU header is present. */\n itemId: number | null\n /** Source FEC Payload ID if present (`FEC_type == 1`), or null */\n fecPayloadId: { ssId: number } | null\n}\n\n/**\n * Extract MFU payload from a raw MMTP packet.\n *\n * Handles all the byte arithmetic for:\n * - MMTP header (12 bytes)\n * - MPU sub-header (8 bytes, payloadLength field)\n * - MFU DU header (14 bytes timed / 4 bytes non-timed, only for FI \u2264 1)\n * - Source FEC Payload ID (4 bytes at end, only when `FEC_type == 1`)\n *\n * `payloadLength` is the ISO length-after-field value: six remaining MPU-header\n * bytes, then the MFU DU header when present, then media. The legacy\n * authenticator suffix and the Source FEC trailer are outside that declared span and must consume the exact suffix.\n *\n * @param mmtpPacket Raw MMTP packet (from multicast or MoQ)\n * @param options.skipFecId When true, do NOT subtract the 4-byte Source FEC Payload ID\n * from the payload boundary, even if fecType >= 1 in the MMTP header. Use this for\n * FEC-recovered symbols where the FEC PID was already stripped before WASM decoding\n * but the fecType bits in byte 0 still reflect the original packet (FEC Type=1 per\n * draft-ramadan-moq-mmt-01 \u00A73.1).\n * @returns Extracted MFU data + metadata, or null if packet is too small\n */\ninterface MfuPlan {\n header: MMTPHeader\n payload: Uint8Array\n mpu: MPUHeader\n fragmentType: number\n layout: MfuPayloadLayout\n trailerLayout: DeclaredTrailerLayout\n}\n\n/**\n * Single source of truth for whether a packet yields an MFU payload.\n *\n * `extractMFUPayload` and `explainMFURejection` both delegate here, so the\n * reason reported to operators can never drift from the decision the parser\n * actually made.\n */\nfunction planMfuExtraction(\n mmtpPacket: Uint8Array,\n options?: MFUExtractOptions,\n parsedHeader?: MMTPHeader,\n): { plan: MfuPlan } | { rejection: MFURejection } {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'packet-shorter-than-mmtp-plus-mpu-header',\n detail: `${mmtpPacket.length} bytes < ${MMTP_HEADER_SIZE + MPU_HEADER_SIZE}`,\n },\n }\n }\n\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch (error) {\n return {\n rejection: {\n gate: 'mmtp-header-unparseable',\n detail: error instanceof Error ? error.message : String(error),\n },\n }\n }\n }\n if (header.packetType !== PACKET_TYPE_MPU) {\n return {\n rejection: {\n gate: 'not-an-mpu-packet',\n detail: `packetType=0x${header.packetType.toString(16).padStart(2, '0')}`,\n },\n }\n }\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'payload-shorter-than-mpu-header',\n detail: `${payload.length} bytes < ${MPU_HEADER_SIZE}`,\n },\n }\n }\n\n const mpu = parseMPUHeader(payload)\n if (mpu.aggregationFlag) {\n return {\n rejection: { gate: 'aggregation-flag-set', detail: 'strict profile requires A=0' },\n }\n }\n\n // Fragment type from byte 2 upper nibble (not returned by parseMPUHeader)\n const fragmentType = (payload[2]! >> 4) & 0x0f\n\n const layoutResult = resolveMfuPayloadLayout(mpu, fragmentType, payload)\n if ('rejection' in layoutResult) return layoutResult\n const { layout } = layoutResult\n\n const trailerLayout = resolveDeclaredTrailers(\n payload,\n layout.dataEnd,\n header.fecType,\n options,\n )\n if (!trailerLayout) {\n // The most common cause is a producer whose Source FEC Payload ID width\n // disagrees with ISO/IEC 23008-1 \u00A7C.5.2. Name that explicitly rather than\n // leaving operators to infer it from a generic trailer error.\n if (!options?.skipFecId && header.fecType === 1) {\n const observed = payload.length - layout.dataEnd\n const expected = SOURCE_FEC_PAYLOAD_ID_SIZE\n if (observed !== expected) {\n return {\n rejection: {\n gate: 'source-fec-payload-id-width-mismatch',\n detail:\n `producer wrote a ${observed}-byte Source FEC Payload ID, ` +\n `ISO/IEC 23008-1 \u00A7C.5.2 requires ${expected} ` +\n `(payload=${payload.length}, declaredEnd=${layout.dataEnd})`,\n },\n }\n }\n }\n return {\n rejection: {\n gate: 'declared-trailers-unresolved',\n detail:\n `trailer bytes [${layout.dataEnd}, ${payload.length}) are neither empty ` +\n `nor an exact legacy authenticator trailer (fecType=${header.fecType})`,\n },\n }\n }\n\n return { plan: { header, payload, mpu, fragmentType, layout, trailerLayout } }\n}\n\n/**\n * Report why `extractMFUPayload` would refuse this packet, or null if it would\n * accept it.\n *\n * `extractMFUPayload` returns bare `null` on ten distinct conditions, which\n * makes a producer/consumer framing disagreement indistinguishable from a\n * publisher that never started \u2014 both render as silence. Use this wherever\n * that distinction matters: diagnostics, contract tests, and operator-facing\n * logs.\n */\nexport function explainMFURejection(\n mmtpPacket: Uint8Array,\n options?: MFUExtractOptions,\n): MFURejection | null {\n const result = planMfuExtraction(mmtpPacket, options)\n return 'rejection' in result ? result.rejection : null\n}\n\nexport function extractMFUPayload(\n mmtpPacket: Uint8Array,\n options?: MFUExtractOptions,\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options))\n}\n\n/**\n * extractMFUPayload for a caller that already holds this packet's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet; the\n * result is then identical to `extractMFUPayload(mmtpPacket, options)`.\n */\nexport function extractMFUPayloadWithHeader(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n options?: MFUExtractOptions,\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options, header))\n}\n\nfunction extractPlannedMfu(\n mmtpPacket: Uint8Array,\n result: { plan: MfuPlan } | { rejection: MFURejection },\n): MFUExtraction | null {\n if ('rejection' in result) return null\n const { header, payload, mpu, fragmentType, layout, trailerLayout } = result.plan\n\n const mfuDuHeaderPresent = layout.hasMfuDuHeader\n const mfuOffset = layout.mfuOffset\n const dataEnd = layout.dataEnd\n\n const mfuDuHeader =\n mfuDuHeaderPresent && mpu.timedFlag === 1\n ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE)\n : null\n const itemId =\n mfuDuHeaderPresent && mpu.timedFlag === 0\n ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false)\n : null\n\n const data = payload.subarray(mfuOffset, dataEnd)\n\n const fecPayloadId = trailerLayout.hasFecId\n ? {\n ssId: new DataView(\n mmtpPacket.buffer,\n mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE,\n 4,\n ).getUint32(0, false),\n }\n : null\n\n return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId }\n}\n\n/**\n * Extract timestamp from MMTP packet\n */\nexport function extractTimestamp(mmtpPacket: Uint8Array): bigint {\n const { header } = unwrapMMTP(mmtpPacket)\n return header.timestamp\n}\n\n/**\n * Check if MMTP packet is an FEC repair packet\n * FEC_type 2 and 3 are repair packets\n */\nexport function isFecRepairPacket(mmtpPacket: Uint8Array): boolean {\n if (mmtpPacket.length < 1) return false\n const fecType = (mmtpPacket[0]! >> 3) & 0x03\n return fecType >= 2\n}\n\n/**\n * Extract Source FEC Payload ID (SS_ID) from the last 4 bytes of an MMTP\n * source packet per ISO/IEC 23008-1:2023 Section C.5.2 Figure C.10.\n *\n * SS_ID is a flat 32-bit monotonic counter (incremented by 1 per packet\n * for ssbg_mode0 and ssbg_mode1). Block membership and ESI use the\n * configured K; repair SS_Start identifies the first SS_ID of the block and\n * SSB_length records the authored source-symbol count:\n * SBN = floor(SS_ID / K), ESI = SS_ID % K\n * SS_Start = SBN * K (first SS_ID of the block)\n *\n * This matches FFmpeg moqenc_mmt.c, the drafts (draft-ramadan-moq-fec \u00A76.2),\n * and ATSC A/331 \u00A78.1.2.5 which defers to ISO 23008-1 Annex C.\n */\nexport function extractFecPayloadId(mmtpPacket: Uint8Array): { ssId: number } | null {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header ? sourceFecPayloadIdOf(mmtpPacket, header) : null\n}\n\n/**\n * Return true when FEC_type=1 and the exact suffix after the ISO-declared MPU\n * payload contains a four-byte Source FEC Payload ID.\n */\nexport function hasSourceFecPayloadId(mmtpPacket: Uint8Array): boolean {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header !== null && sourceFecPayloadIdOf(mmtpPacket, header) !== null\n}\n\nfunction parseHeaderForSourceFecId(mmtpPacket: Uint8Array): MMTPHeader | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n try {\n return parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n}\n\n/**\n * The Source FEC Payload ID of a packet whose MMTP header the caller already\n * parsed, or null when the packet carries none: present only when FEC_type=1\n * and the exact suffix after the ISO-declared MPU payload holds the four-byte\n * ID (ISO/IEC 23008-1 \u00A7C.5.2). Same answer as extractFecPayloadId, without a\n * second header parse (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet.\n */\nexport function sourceFecPayloadIdOf(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n): { ssId: number } | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n if (header.packetType !== PACKET_TYPE_MPU) return null\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) return null\n const payloadLength = (payload[0]! << 8) | payload[1]!\n if (payloadLength < MPU_HEADER_REMAINDER_SIZE) return null\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + payloadLength\n if (!resolveDeclaredTrailers(payload, declaredEnd, header.fecType)?.hasFecId) return null\n\n // Flat 4-byte SS_ID: encoder writes block_id * K + symbol_id\n const off = mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n return {\n ssId:\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0,\n }\n}\n\n/** Size of Repair FEC Payload ID per ISO/IEC 23008-1 Section C.5.3 */\nexport const REPAIR_FEC_PID_SIZE = 13\n\n/**\n * Parse the 13-byte Repair FEC Payload ID after the complete dynamic MMTP header.\n * `parsedHeader`, when given, must be `parseMMTPHeader(mmtpPacket)` of this\n * same packet; it spares the second header parse (BLO-36599).\n */\nfunction readRepairFecPayloadIdFields(mmtpPacket: Uint8Array, parsedHeader?: MMTPHeader): {\n packetId: number; ssStart: number; rsbLength: number; rsId: number; ssbLength: number; dataOffset: number\n} | null {\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n }\n if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2) return null\n\n const off = header.headerLength\n if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE) return null\n const ssStart =\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0 // 32 bits\n const rsbLength = (mmtpPacket[off + 4]! << 16) | (mmtpPacket[off + 5]! << 8) | mmtpPacket[off + 6]! // 24 bits\n const rsId = (mmtpPacket[off + 7]! << 16) | (mmtpPacket[off + 8]! << 8) | mmtpPacket[off + 9]! // 24 bits\n const ssbLength = (mmtpPacket[off + 10]! << 16) | (mmtpPacket[off + 11]! << 8) | mmtpPacket[off + 12]! // 24 bits\n return {\n packetId: header.packetId,\n ssStart,\n rsbLength,\n rsId,\n ssbLength,\n dataOffset: off + REPAIR_FEC_PID_SIZE,\n }\n}\n\n/**\n * Extract Repair FEC Payload ID from a raw-multicast MMTP repair packet.\n * Per ISO/IEC 23008-1:2023 Section C.5.3 (ssbg_mode0, one-stage, no FFSRP_TS):\n * [MMTP header][SS_Start:4][RSB_length:3][RS_ID:3][SSB_length:3][repair data]\n * OTI is delivered via AL-FEC signaling message (Table C.3), not per-packet.\n *\n * Byte 1 is reserved(2)|packet_type(6) for V=0, so repair type 0x03 is 0x03.\n * Pre-migration high-bits bytes (0x0c) are rejected \u2014 no compatibility decode.\n */\nexport function extractRepairFecPayloadId(mmtpPacket: Uint8Array): {\n ssStart: number; rsbLength: number; rsId: number; ssbLength: number\n} | null {\n const fields = readRepairFecPayloadIdFields(mmtpPacket)\n if (!fields) return null\n return {\n ssStart: fields.ssStart,\n rsbLength: fields.rsbLength,\n rsId: fields.rsId,\n ssbLength: fields.ssbLength,\n }\n}\n\n/** Parsed MoQ repair frame per ISO/IEC 23008-1 Section C.4.3 + C.5.3 */\nexport interface MoqRepairFrame {\n /** MMTP packetId (1=video, 2=audio) \u2014 for routing to correct FEC decoder */\n packetId: number\n /** SS_Start (32 bits): SS_ID of first source symbol in block */\n ssStart: number\n /** RSB_length (24 bits): number of repair symbols (P) */\n rsbLength: number\n /** RS_ID (24 bits): repair symbol index (0-based) */\n rsId: number\n /** SSB_length (24 bits): authored source-symbol count (1..=configured K) */\n ssbLength: number\n /** Repair symbol data after the dynamic MMTP header and 13-byte FEC payload ID. */\n symbolData: Uint8Array\n}\n\n/**\n * Parse a MoQ repair frame (ISO/IEC 23008-1 Annex C format).\n *\n * Wire format per ISO 23008-1 \u00A7C.4.3 + \u00A7C.5.3:\n * MMTP Header: fixed 12 bytes plus C/X optional fields\n * then SS_Start (4 bytes) \u2192 block identifier\n * then RSB_length (3 bytes) \u2192 P\n * then RS_ID (3 bytes) \u2192 ESI = K + RS_ID\n * then SSB_length (3 bytes) \u2192 authored source-symbol count (1..=K)\n * then Repair Symbol Data (T bytes)\n *\n * @param frame - Raw MoQ repair frame bytes\n * @returns Parsed frame or null if invalid\n */\nexport function parseMoqRepairFrame(frame: Uint8Array): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame))\n}\n\n/**\n * parseMoqRepairFrame for a caller that already holds this frame's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599). The router's\n * multicast repair branch uses it: one repair packet in every K + P otherwise\n * paid two header parses.\n *\n * `header` must be `parseMMTPHeader(frame)` of this same frame; the result is\n * then identical to `parseMoqRepairFrame(frame)`.\n */\nexport function parseMoqRepairFrameWithHeader(\n frame: Uint8Array,\n header: MMTPHeader,\n): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header))\n}\n\nfunction moqRepairFrameFrom(\n frame: Uint8Array,\n repairId: ReturnType<typeof readRepairFecPayloadIdFields>,\n checkRsId = true,\n): MoqRepairFrame | null {\n if (!repairId) return null\n\n const symbolData = frame.subarray(repairId.dataOffset)\n if (\n repairId.ssbLength === 0 ||\n (checkRsId && repairId.rsId >= repairId.rsbLength) ||\n symbolData.length === 0\n ) return null\n\n return {\n packetId: repairId.packetId,\n ssStart: repairId.ssStart,\n rsbLength: repairId.rsbLength,\n rsId: repairId.rsId,\n ssbLength: repairId.ssbLength,\n symbolData,\n }\n}\n\n/**\n * Why a repair object of an mmtp track is discarded on admission:\n * `repairLength` -- the object is not exactly 12 + 13 + T bytes with a\n * 12-byte MMTP header (C = 0, X = 0; draft-ramadan-moq-mmt-02 7.3, judged\n * before any Repair FEC Payload ID field is read); `repairRsId` -- RS_ID is not\n * below RSB_length, under every scheme; `repairSchemeBound` -- the object\n * breaks its scheme's bound: reed-solomon SSB_length + RSB_length > 255, which\n * also caps RS_ID at 253, or raptorq SSB_length + RSB_length - 1 > 2^24 - 1\n * (draft-ramadan-moq-fec-core-00 7.5 and 10.3, -block-codes-00 7).\n */\nexport type RepairObjectReject = 'repairLength' | 'repairRsId' | 'repairSchemeBound'\n\n/**\n * Admission of one mmtp repair object under its instance's T and scheme. The\n * caller names the instance (by the repair track it subscribed); nothing here\n * infers it from the fields. `repairRsId` and `repairSchemeBound` carry the\n * frame so the caller can first route an RSB_length below a held layer's\n * O_i + P_i to the 7.3.2 stop, which takes precedence over the discard.\n * `null`: not an iso repair packet, or SSB_length 0.\n */\nexport function admitMmtpRepairObject(\n packet: Uint8Array,\n header: MMTPHeader,\n symbolSize: number,\n algorithm: string | undefined,\n): { frame: MoqRepairFrame; reject?: Exclude<RepairObjectReject, 'repairLength'> } | { reject: 'repairLength' } | null {\n if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2) return null\n if (header.headerLength !== MMTP_HEADER_SIZE || packet.length !== MMTP_HEADER_SIZE + REPAIR_FEC_PID_SIZE + symbolSize) {\n return { reject: 'repairLength' }\n }\n const frame = moqRepairFrameFrom(packet, readRepairFecPayloadIdFields(packet, header), false)\n if (!frame) return null\n if (frame.rsId >= frame.rsbLength) return { frame, reject: 'repairRsId' }\n const blockSymbols = frame.ssbLength + frame.rsbLength\n if (algorithm === 'reed-solomon' ? blockSymbols > 255 : algorithm === 'raptorq' && blockSymbols - 1 > 0xffffff) {\n return { frame, reject: 'repairSchemeBound' }\n }\n return { frame }\n}\n\n// The signalling-message parsers (9.3.4.2 payload header, AL-FEC message,\n// PA/MPT) live in ./signalling.ts.\n", "/**\n * NTP short format (RFC 5905 \u00A76): an unsigned 32-bit, 16.16 fixed-point count\n * of seconds. The MMTP header `timestamp` field (ISO/IEC 23008-1 \u00A79.2.2)\n * carries each packet's UTC sending instant in this format, so the value wraps\n * to 0 every 2^16 s (~18.2 h).\n *\n * Plain numeric order on these values breaks at every wrap: a retained\n * `Math.max` stays at the pre-wrap value and every later instant compares as\n * older. Order send times only with {@link compareNtpShort}, which applies\n * RFC 1982 serial-number arithmetic over the field's width.\n */\n\n/** Width in bits of the MMTP `timestamp` field (NTP short). */\nexport const NTP_SHORT_BITS = 32\n\n/** Number of distinct NTP-short values; the field wraps to 0 here. */\nexport const NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS\n\n/**\n * RFC 1982 \u00A73.2's `2^(SERIAL_BITS - 1)`. Two values whose forward distance is\n * below this are ordered; exactly this far apart they are not ordered at all.\n * Two instants must be less than this far apart (2^15 s, ~9.1 h of send time)\n * for the comparison to give their true order.\n */\nexport const NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1)\n\n/**\n * Serial order of one NTP-short value relative to another.\n *\n * `'unordered'` is RFC 1982's undefined case: the values are exactly\n * {@link NTP_SHORT_HALF_RANGE} apart, so neither precedes the other. It is\n * never folded into `'before'` or `'after'`; each caller decides what an\n * unorderable pair means for it.\n */\nexport type NtpShortOrder = 'before' | 'equal' | 'after' | 'unordered'\n\n/** True when `value` is an NTP-short value: an integer in [0, NTP_SHORT_MODULUS). */\nexport function isNtpShort(value: number): boolean {\n return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS\n}\n\n/**\n * RFC 1982 serial comparison of NTP-short `a` against `b`: `'after'` when `a`\n * is the later instant, `'before'` when it is the earlier one.\n *\n * The answer is the true order only while the two instants are less than\n * {@link NTP_SHORT_HALF_RANGE} apart. Past that a 32-bit field cannot tell\n * later from earlier, and the result names whichever direction is nearer.\n * This is not a total order (it is not transitive across the whole space), so\n * it must never be used to sort.\n *\n * @throws {RangeError} if either operand is not an NTP-short value\n */\nexport function compareNtpShort(a: number, b: number): NtpShortOrder {\n if (!isNtpShort(a) || !isNtpShort(b)) {\n throw new RangeError(\n `NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS}), got ${String(a)} and ${String(b)}`,\n )\n }\n if (a === b) return 'equal'\n // Forward distance from b to a, reduced into [1, NTP_SHORT_MODULUS). Both\n // operands are below 2^32, so every step is exact in a double.\n const forward = (a - b + NTP_SHORT_MODULUS) % NTP_SHORT_MODULUS\n if (forward < NTP_SHORT_HALF_RANGE) return 'after'\n if (forward > NTP_SHORT_HALF_RANGE) return 'before'\n return 'unordered'\n}\n", "/**\n * RFC 1982 serial-number arithmetic for the 32-bit MMTP AL-FEC symbol\n * counters (ISO/IEC 23008-1:2023 C.5.2 SS_ID, C.5.3 SS_Start).\n *\n * SS_ID is a 32-bit field, so a stream that runs long enough wraps it to 0.\n * Ordering two SS_IDs (or two blocks by their first SS_ID) with `<` reads\n * every post-wrap value as older than every pre-wrap one. Serial order\n * agrees with `<` whenever the two values are less than 2^31 apart, so for\n * every stream that has not reached the wrap the result is unchanged; only\n * the order across the wrap point differs (BLO-35597 iso:5).\n */\n\n/** 2^SERIAL_BITS for SERIAL_BITS = 32. */\nexport const SERIAL32_SPAN = 0x1_0000_0000\n\n/** RFC 1982 \u00A73.2's 2^(SERIAL_BITS - 1). */\nexport const SERIAL32_HALF = 0x8000_0000\n\nfunction assertUint32(value: number, name: string): void {\n if (!Number.isInteger(value) || value < 0 || value >= SERIAL32_SPAN) {\n throw new RangeError(`${name} must be a uint32 (got ${value})`)\n }\n}\n\n/**\n * RFC 1982 \u00A73.1 addition, extended to negative `n` for the matching\n * subtraction: `(s + n) mod 2^32`. `n` must lie in (-2^31, 2^31).\n */\nexport function serial32Add(s: number, n: number): number {\n assertUint32(s, 's')\n if (!Number.isInteger(n) || n <= -SERIAL32_HALF || n >= SERIAL32_HALF) {\n throw new RangeError(`serial addend must lie in (-2^31, 2^31) (got ${n})`)\n }\n return (s + n + SERIAL32_SPAN) % SERIAL32_SPAN\n}\n\n/** Forward distance from `from` to `to`: `(to - from) mod 2^32`. */\nexport function serial32Distance(from: number, to: number): number {\n return (to - from) >>> 0\n}\n\n/**\n * RFC 1982 \u00A73.2: `a` precedes `b`. Values exactly 2^31 apart are unordered\n * (neither precedes the other).\n */\nexport function serial32Precedes(a: number, b: number): boolean {\n const distance = serial32Distance(a, b)\n return distance !== 0 && distance < SERIAL32_HALF\n}\n", "/**\n * FEC block profile (BLO-35597, ISO/IEC 23008-1 Annex C).\n *\n * Every catalog `fec` object that declares an FEC instance names its block\n * profile in `fec.blockProfile`. A receiver applies all of a profile's rules\n * or none of them, so the token is the one explicit per-stream discriminator:\n * it is never defaulted and never inferred from the wire.\n *\n * draft-ramadan-moq-fec \u00A75.1 defines exactly one value, and it is the only\n * profile this library implements:\n *\n * - `iso-ssbg1-v1`: ssbg_mode1 (C.3.3): a source symbol is\n * `u16 length || protected packet || zero padding` to T; a block is a\n * K' = SSB_length RaptorQ block (C.5.3) and repair ESI = SSB_length + RS_ID;\n * SS_ID increments by one per FEC source packet and wraps at 2^32 (C.5.2),\n * so a block is located by membership in `[SS_Start, SS_Start + SSB_length)`\n * under RFC 1982 serial arithmetic; the MoQ repair group id is the 62-bit\n * wrap-epoch-extended SS_Start. The AL-FEC coding byte for this profile is\n * 0x14 (one-stage, ssbg_mode1, fec_payload_id_mode 0, Amd 1:2025 Table C.3).\n *\n * A track whose `blockProfile` is absent or names any other token (the\n * retired Blockcast-private `k-padded-v1` included) has no FEC: a receiver\n * consumes its source without FEC and joins none of its repair tracks\n * (draft-ramadan-moq-fec \u00A75.1). `parseFecBlockProfile` throws for such a\n * token; the per-track catalog resolver turns the same rule into a typed\n * per-track \"FEC unavailable\" outcome instead of failing the session.\n */\nimport { serial32Add, serial32Distance, serial32Precedes } from './serial-number.js'\n\n/** The block profile a catalog `fec.blockProfile` may name: the one this library implements. */\nexport type FecBlockProfile = 'iso-ssbg1-v1'\n\n/** Every accepted `fec.blockProfile` token. */\nexport const FEC_BLOCK_PROFILES: readonly FecBlockProfile[] = Object.freeze([\n 'iso-ssbg1-v1',\n])\n\n/** True for a block-profile token this library implements. */\nexport function isFecBlockProfile(value: unknown): value is FecBlockProfile {\n return value === 'iso-ssbg1-v1'\n}\n\n/**\n * Read a required `fec.blockProfile`. Throws on an absent token and on any\n * token other than `iso-ssbg1-v1`: there is no default and nothing is\n * inferred from the wire (draft-ramadan-moq-fec \u00A75.1).\n *\n * @param where the catalog path of the field, for the error message.\n */\nexport function parseFecBlockProfile(value: unknown, where: string): FecBlockProfile {\n if (isFecBlockProfile(value)) return value\n if (value === undefined) {\n throw new Error(`${where} is required: name the FEC block profile (\"iso-ssbg1-v1\")`)\n }\n throw new Error(`${where} must be \"iso-ssbg1-v1\" (got ${JSON.stringify(value)})`)\n}\n\n/** ISO/IEC 23008-1 C.3.3 ssbg_mode1: the two-octet packet length field. */\nexport const SSBG1_LENGTH_FIELD_BYTES = 2\n\n/** The largest protected packet an ssbg_mode1 symbol of size T can carry. */\nexport function ssbg1MaxPacketLength(symbolSize: number): number {\n return symbolSize - SSBG1_LENGTH_FIELD_BYTES\n}\n\n/** Whether a protected packet of `packetLength` bytes fits one T-byte ssbg_mode1 symbol. */\nexport function ssbg1FitsSymbol(packetLength: number, symbolSize: number): boolean {\n return (\n Number.isSafeInteger(packetLength) &&\n packetLength >= 0 &&\n packetLength <= ssbg1MaxPacketLength(symbolSize) &&\n packetLength <= 0xffff\n )\n}\n\n/**\n * Build one ssbg_mode1 source symbol (C.3.3): the protected packet's length\n * in two octets, network byte order, then the packet, then zero octets up to\n * T. The protected packet is the MMTP packet before its Source FEC Payload ID\n * is appended (C.4.2).\n *\n * @throws when `length + 2 > T`: the packet cannot be protected under this\n * profile, and silently truncating it would corrupt every repair symbol.\n */\nexport function buildSsbg1SourceSymbol(packet: Uint8Array, symbolSize: number): Uint8Array {\n if (!Number.isSafeInteger(symbolSize) || symbolSize <= SSBG1_LENGTH_FIELD_BYTES) {\n throw new Error(`ssbg_mode1 symbol size must exceed ${SSBG1_LENGTH_FIELD_BYTES} (got ${symbolSize})`)\n }\n if (!ssbg1FitsSymbol(packet.byteLength, symbolSize)) {\n throw new Error(\n `ssbg_mode1 source symbol needs ${packet.byteLength} + ${SSBG1_LENGTH_FIELD_BYTES} bytes but T is ${symbolSize}`,\n )\n }\n const symbol = new Uint8Array(symbolSize)\n symbol[0] = (packet.byteLength >>> 8) & 0xff\n symbol[1] = packet.byteLength & 0xff\n symbol.set(packet, SSBG1_LENGTH_FIELD_BYTES)\n return symbol\n}\n\n/**\n * Recover the protected packet from one ssbg_mode1 source symbol: the bytes\n * the length field names. Returns null, never a guess, when the length field\n * points past the symbol or any padding octet is non-zero (C.3.3 padding is\n * all 00h), since either means the recovered symbol is not what was sent.\n */\nexport function trimSsbg1SourceSymbol(symbol: Uint8Array): Uint8Array | null {\n if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES) return null\n const length = (symbol[0]! << 8) | symbol[1]!\n const end = SSBG1_LENGTH_FIELD_BYTES + length\n if (end > symbol.byteLength) return null\n for (let i = end; i < symbol.byteLength; i++) {\n if (symbol[i] !== 0) return null\n }\n return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end)\n}\n\n/** The SS_ID after the last source symbol of `[ssStart, ssStart + ssbLength)`. */\nexport function isoBlockEnd(ssStart: number, ssbLength: number): number {\n return serial32Add(ssStart, ssbLength)\n}\n\n/**\n * Range membership (C.5.2, C.5.3): whether `ssId` is one of the\n * `ssbLength` consecutive SS_IDs starting at `ssStart`, modulo 2^32.\n */\nexport function isoBlockContains(ssStart: number, ssbLength: number, ssId: number): boolean {\n return serial32Distance(ssStart, ssId) < ssbLength\n}\n\n/**\n * A lower bound on how many blocks the block starting at `a` lies behind the\n * one starting at `b` (0 when `a` does not precede `b`). An iso-ssbg1-v1\n * block holds at most `kMax` source symbols (the catalog `sourceSymbols`, the\n * AL-FEC maximum_k_for_repair_flow), so `n * kMax` SS_IDs always span at least\n * `n` blocks. Every interleave horizon in the receiver (decoder retention,\n * worker retirement, ordered-relay settlement) uses this one bound, so the\n * manager's horizon can never fall inside the decoder's.\n */\nexport function isoBlocksBehindLowerBound(a: number, b: number, kMax: number): number {\n if (!Number.isSafeInteger(kMax) || kMax <= 0) {\n throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`)\n }\n return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0\n}\n", "/**\n * Runtime FEC bindings (BLO-50171): what each source track's FEC resolves to\n * for this library's receiver, read from `validateFecCatalog`'s per-instance\n * result and never re-derived.\n *\n * Every runtime reader (the container's `resolveCatalogTrackFec`,\n * `resolveRepairLayers`, `MulticastManager.configureMultiTrack`, transport's\n * `catalogRepairTracks`) goes through `resolveFecBindings`, so they cannot\n * disagree with the validator or with each other about which tracks have FEC\n * and which repair tracks belong to them.\n *\n * The draft-ramadan-moq-fec-catalog-00 array is the only shape. Both catalog\n * dialects bind through it: an MSF `tracks[]` entry directly, and a hang\n * `video`/`audio` rendition (`fec` the same array) with its `repair.renditions`\n * entries (`source` + `instanceId`), mapped onto a `tracks[]` view so the same\n * validator runs. A hang rendition is authoritative over a `tracks[]` entry of\n * the same name.\n *\n * Fail closed per instance: a source whose base instance is not `ok` resolves\n * to `unavailable` with the validator's code and path, and costs no other\n * track anything. A draft-01 object `fec` is `fec_member` at that track's\n * `fec`: the track plays without FEC.\n */\nimport {\n validateFecCatalog,\n type FecCatalogCode,\n type FecCatalogIssue,\n type FecCatalogReceiver,\n type FecCatalogReport,\n} from './fec-catalog.js'\n\n/** The receiver this runtime is: it decodes `iso-ssbg1-v1` only. */\nexport const RUNTIME_FEC_RECEIVER: FecCatalogReceiver = Object.freeze({\n schemes: Object.freeze(['raptorq', 'reed-solomon']),\n blockProfiles: Object.freeze(['iso-ssbg1-v1']),\n overlays: true,\n})\n\n/** Repair track priority when the track states none (MoQT scale, 192..255). */\nexport const DEFAULT_FEC_REPAIR_PRIORITY = 240\n\n/** One `ok` instance's geometry. */\nexport interface FecInstanceGeometry {\n readonly instanceId: number\n readonly scheme: 'raptorq' | 'reed-solomon'\n /** `iso-ssbg1-v1` under `RUNTIME_FEC_RECEIVER`. */\n readonly blockProfile: string\n /** K. */\n readonly sourceSymbols: number\n /** P_0 for a base instance; the overlay's own P for an overlay. */\n readonly repairSymbols: number\n /** T. */\n readonly symbolSize: number\n readonly interleaveDepthMs?: number\n readonly reorderToleranceMs?: number\n readonly repairTrack: string\n readonly symbolTrack?: string\n}\n\nexport interface FecLayerBinding {\n readonly layer: number\n readonly repairTrackName: string\n readonly repairSymbols: number\n /** O_i = sum(P_j, j < i). */\n readonly rsIdOffset: number\n readonly priority: number\n}\n\nexport interface FecOverlayBinding {\n readonly repairTrackName: string\n readonly scope: 'keyframe'\n readonly sourceSymbols: number\n readonly repairSymbols: number\n readonly priority: number\n readonly geometry: FecInstanceGeometry\n}\n\nexport interface FecBindingUnavailable {\n /** The validator's code, or `fec_base_instances` for a track with no base\n * instance or more than one `ok` one (the MMTP wire carries one base Source FEC Payload\n * ID, mmt-02 7.4.1). */\n readonly code: FecCatalogCode | 'fec_base_instances'\n /** JSON Pointer into the catalog (a hang path starts `/video` or `/audio`). */\n readonly path: string\n readonly outcome: 'unavailable' | 'violation'\n}\n\nexport type FecSourceBinding =\n | {\n readonly status: 'ok'\n readonly track: string\n /** JSON Pointer of the source track (`/tracks/<i>`, `/video/renditions/<name>`). */\n readonly pointer: string\n readonly base: FecInstanceGeometry\n /** Base layers in order, layer 0 first. */\n readonly layers: readonly FecLayerBinding[]\n /** Sum of P over the base layers: the wire RSB_length. */\n readonly totalBaseRepairSymbols: number\n readonly overlay?: FecOverlayBinding\n /** Why a declared overlay is not used, when one is not. */\n readonly overlayUnavailable?: FecBindingUnavailable\n }\n | {\n readonly status: 'unavailable'\n readonly track: string\n readonly pointer: string\n readonly reason: FecBindingUnavailable\n }\n\ntype Obj = Record<string, unknown>\nconst recordOf = (v: unknown): Obj | undefined =>\n typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Obj) : undefined\nconst escape = (s: string) => s.replace(/~/g, '~0').replace(/\\//g, '~1')\n\n/**\n * The `tracks[]` view of a catalog in either dialect, with each view track's\n * JSON Pointer in the original catalog.\n */\nexport function fecCatalogTracks(catalog: unknown): { tracks: unknown[]; pointers: string[] } {\n const root = recordOf(catalog) ?? {}\n const tracks: unknown[] = []\n const pointers: string[] = []\n const hangNames = new Set<string>()\n for (const role of ['video', 'audio'] as const) {\n for (const [name, r] of Object.entries(recordOf(recordOf(root[role])?.['renditions']) ?? {})) {\n const entry = recordOf(r)\n if (!entry) continue\n hangNames.add(name)\n const kind = recordOf(entry['container'])?.['kind']\n // A hang rendition carries no `packaging`; its container kind is it.\n // `mmtp-fec` is hang's kind for MMTP that carries FEC (the FFmpeg\n // publisher's `moq_publish_set_video_packaging`): MMTP packaging.\n const view: Obj = { name, packaging: kind === undefined || kind === 'mmtp-fec' ? 'mmtp' : kind }\n if (entry['fec'] !== undefined) view['fec'] = entry['fec']\n tracks.push(view)\n pointers.push(`/${role}/renditions/${escape(name)}`)\n }\n }\n const hangRenditions = tracks.length\n for (const [name, r] of Object.entries(recordOf(recordOf(root['repair'])?.['renditions']) ?? {})) {\n hangNames.add(name)\n tracks.push({ packaging: 'fec-repair', ...recordOf(r), name })\n pointers.push(`/repair/renditions/${escape(name)}`)\n }\n const raw = Array.isArray(root['tracks']) ? root['tracks'] : []\n const named = new Set(hangNames)\n raw.forEach((t, i) => {\n const name = recordOf(t)?.['name']\n if (typeof name === 'string') named.add(name)\n if (typeof name === 'string' && hangNames.has(name)) return\n tracks.push(t)\n pointers.push(`/tracks/${i}`)\n })\n // hang layer 0 needs no `repair.renditions` entry: the rendition's instance\n // names it, and a hang Root (hang's toHang) carries no repair block. Such a\n // name stands for a repair track of that instance.\n tracks.slice(0, hangRenditions).forEach((t, ti) => {\n const view = t as Obj\n if (!Array.isArray(view['fec'])) return\n view['fec'].forEach((o, ii) => {\n const repairTrack = recordOf(o)?.['repairTrack']\n if (typeof repairTrack !== 'string' || named.has(repairTrack)) return\n named.add(repairTrack)\n const instanceId = recordOf(o)?.['instanceId']\n tracks.push({ name: repairTrack, packaging: 'fec-repair', source: view['name'], ...(instanceId === undefined ? {} : { instanceId }) })\n pointers.push(`${pointers[ti]}/fec/${ii}/repairTrack`)\n })\n })\n return { tracks, pointers }\n}\n\nfunction runtimeView(catalog: unknown, receiver: FecCatalogReceiver) {\n const { tracks, pointers } = fecCatalogTracks(catalog)\n const report = validateFecCatalog({ tracks }, receiver)\n const at = (path: string) => {\n const m = /^\\/tracks\\/(\\d+)(.*)$/.exec(path)\n return m ? pointers[Number(m[1])] + m[2] : path\n }\n return { tracks, pointers, report, at }\n}\n\n/**\n * The `validateFecCatalog` report `resolveFecBindings` acts on (BLO-55242):\n * the same `tracks[]` view and the same receiver, so a host publishing it\n * cannot disagree with what the runtime does. Paths are JSON Pointers into\n * the original catalog (a hang path starts `/video`, `/audio` or `/repair`).\n * One kind does not resolve: a hang layer 0 repair track with no\n * `repair.renditions` entry stands at the `repairTrack` string that names it\n * (`.../fec/<j>/repairTrack`), so a path below that track names nothing in\n * the catalog. The track indices (`trackIndex`, `repairTrack`,\n * `boundRepairTracks`, `symbolTrack`) index `fecCatalogTracks(catalog).tracks`.\n */\nexport function runtimeFecCatalogReport(\n catalog: unknown,\n receiver: FecCatalogReceiver = RUNTIME_FEC_RECEIVER,\n): FecCatalogReport {\n const { report, at } = runtimeView(catalog, receiver)\n const issue = (i: FecCatalogIssue) => Object.freeze({ code: i.code, path: at(i.path) })\n return Object.freeze({\n instances: Object.freeze(\n report.instances.map((i) => Object.freeze({ ...i, path: at(i.path), issues: Object.freeze(i.issues.map(issue)) })),\n ),\n issues: Object.freeze(report.issues.map(issue)),\n })\n}\n\n/**\n * Every source track's runtime FEC binding, by track name. A track with no\n * `fec`, or an empty `fec` array, declares no FEC and has no entry.\n */\nexport function resolveFecBindings(\n catalog: unknown,\n receiver: FecCatalogReceiver = RUNTIME_FEC_RECEIVER,\n): ReadonlyMap<string, FecSourceBinding> {\n const { tracks, pointers, report, at } = runtimeView(catalog, receiver)\n const trackAt = (i: number) => recordOf(tracks[i]) ?? {}\n const nameAt = (i: number | null) => (i === null ? undefined : (trackAt(i)['name'] as string))\n const why = (i: { outcome: string; issues: readonly { code: FecCatalogCode; path: string }[]; path: string }) =>\n Object.freeze({\n code: i.issues[0]?.code ?? 'fec_member',\n path: at(i.issues[0]?.path ?? i.path),\n outcome: i.outcome === 'unavailable' ? ('unavailable' as const) : ('violation' as const),\n })\n\n const out = new Map<string, FecSourceBinding>()\n tracks.forEach((t, ti) => {\n const track = recordOf(t)\n const name = track?.['name']\n if (!track || typeof name !== 'string' || out.has(name)) return\n if (track['packaging'] === 'fec-repair' || track['packaging'] === 'fec-source') return\n const fec = track['fec']\n if (fec === undefined) return\n if (!Array.isArray(fec)) {\n const reason = { code: 'fec_member' as const, path: at(`/tracks/${ti}/fec`), outcome: 'violation' as const }\n out.set(name, Object.freeze({ status: 'unavailable', track: name, pointer: pointers[ti]!, reason: Object.freeze(reason) }))\n return\n }\n if (fec.length === 0) return\n const insts = report.instances.filter((i) => i.trackIndex === ti)\n const isOverlay = (i: (typeof insts)[number]) => Object.hasOwn(recordOf(fec[Number(i.path.split('/').pop())]) ?? {}, 'scope')\n const bases = insts.filter((i) => !isOverlay(i))\n const okBases = bases.filter((i) => i.outcome === 'ok')\n if (okBases.length !== 1) {\n const reason =\n // No base instance at all (overlay-only `fec`) is a count of 0, not\n // the overlay's own issue.\n okBases.length > 1 || bases.length === 0\n ? Object.freeze({ code: 'fec_base_instances' as const, path: at(`/tracks/${ti}/fec`), outcome: 'violation' as const })\n : why(bases[0] ?? insts[0]!)\n out.set(name, Object.freeze({ status: 'unavailable', track: name, pointer: pointers[ti]!, reason }))\n return\n }\n const b = okBases[0]!\n const base = geometry(recordOf(fec[Number(b.path.split('/').pop())])!, b.instanceId!, nameAt(b.symbolTrack))\n const priorityOf = (i: number | null) => {\n const p = i === null ? undefined : trackAt(i)['priority']\n return typeof p === 'number' ? p : DEFAULT_FEC_REPAIR_PRIORITY\n }\n const layers: FecLayerBinding[] = [\n { layer: 0, repairTrackName: base.repairTrack, repairSymbols: base.repairSymbols, rsIdOffset: 0, priority: priorityOf(b.repairTrack) },\n ]\n const more = b.boundRepairTracks\n .map((tj) => ({ tj, layer: trackAt(tj)['repairLayer'] as number }))\n .sort((x, y) => x.layer - y.layer)\n let offset = base.repairSymbols\n for (const { tj, layer } of more) {\n const repairSymbols = trackAt(tj)['repairSymbols'] as number\n layers.push({ layer, repairTrackName: nameAt(tj)!, repairSymbols, rsIdOffset: offset, priority: priorityOf(tj) })\n offset += repairSymbols\n }\n let overlay: FecOverlayBinding | undefined\n let overlayUnavailable: FecBindingUnavailable | undefined\n const ov = insts.find(isOverlay)\n if (ov?.outcome === 'ok') {\n const g = geometry(recordOf(fec[Number(ov.path.split('/').pop())])!, ov.instanceId!, nameAt(ov.symbolTrack))\n overlay = Object.freeze({\n repairTrackName: g.repairTrack,\n scope: 'keyframe' as const,\n sourceSymbols: g.sourceSymbols,\n repairSymbols: g.repairSymbols,\n priority: priorityOf(ov.repairTrack),\n geometry: g,\n })\n } else if (ov) overlayUnavailable = why(ov)\n out.set(\n name,\n Object.freeze({\n status: 'ok' as const,\n track: name,\n pointer: pointers[ti]!,\n base,\n layers: Object.freeze(layers.map((l) => Object.freeze(l))),\n totalBaseRepairSymbols: offset,\n ...(overlay ? { overlay } : {}),\n ...(overlayUnavailable ? { overlayUnavailable } : {}),\n }),\n )\n })\n return out\n}\n\n// The validator passed this instance for this receiver, so every member read\n// here is present and in range.\nfunction geometry(o: Obj, instanceId: number, symbolTrack: string | undefined): FecInstanceGeometry {\n return Object.freeze({\n instanceId,\n scheme: o['scheme'] as 'raptorq' | 'reed-solomon',\n blockProfile: o['blockProfile'] as string,\n sourceSymbols: o['sourceSymbols'] as number,\n repairSymbols: o['repairSymbols'] as number,\n symbolSize: o['symbolSize'] as number,\n ...(typeof o['interleaveDepthMs'] === 'number' ? { interleaveDepthMs: o['interleaveDepthMs'] } : {}),\n ...(typeof o['reorderToleranceMs'] === 'number' ? { reorderToleranceMs: o['reorderToleranceMs'] } : {}),\n repairTrack: o['repairTrack'] as string,\n ...(symbolTrack !== undefined ? { symbolTrack } : {}),\n })\n}\n", "// The mmtp track modes of draft-ramadan-moq-mmt-02 13.1 and the pairing of\n// an \"mfu-datagram\" track with the \"mfu\" track it mirrors (4.3.1).\n//\n// A publisher MUST NOT publish an \"mfu-datagram\" track without an \"mfu\" track\n// of the same namespace whose objects are identical in Group ID, Object ID\n// and payload. The catalog carries no sibling pointer, so the pair is read\n// from what the two entries state: they are siblings when their whole\n// identity set is equal, field by field or absent on both. The identity set\n// is the hard set (what the Group and Object IDs are derived from) and the\n// rendition fields of mmt-02 13.1 (one payload has one codec, size, bitrate\n// and language; the rungs of a ladder share the hard set, so nothing else\n// tells them apart). A datagram track with no sibling, or more than one, is\n// rejected and the player plays \"mfu\". The soft set is reported, never a\n// fault. Names, roles and labels are not read: fec-catalog-00 makes names\n// non-normative. Known limit: two \"mfu\" tracks with one description cannot\n// carry datagram siblings until the draft defines a pointer.\n//\n// The rule is a per-pair predicate: it answers the same over the whole\n// catalog and over any subset of it a consumer kept.\n\n/** Every mmtpMode this library accepts (mmt-02 13.1). Anything else rejects the track. */\nexport const MMTP_MODES = Object.freeze(['mfu', 'mfu-datagram'] as const)\n\nexport type MmtpMode = (typeof MMTP_MODES)[number]\n\nexport function isMmtpMode(value: unknown): value is MmtpMode {\n return typeof value === 'string' && (MMTP_MODES as readonly string[]).includes(value)\n}\n\n/**\n * Fields the Group and Object IDs of an mmtp track are derived from: two\n * tracks whose values differ cannot carry identical ids (mmt-02 4.4.2, 4.6).\n * Compared equal-or-both-absent, group duration as resolved ticks.\n */\nexport const MMTP_SIBLING_HARD_FIELDS = Object.freeze([\n 'namespace',\n 'timescale',\n 'presentationAnchorTicks',\n 'groupDuration',\n] as const)\n\n/**\n * Fields that describe the media a track carries. The pair carries one\n * payload (mmt-02 4.3.1), so it has one description: an \"mfu\" track whose\n * description differs is another rendition. The rungs of a ladder share the\n * hard set and nothing else in the catalog tells them apart. Compared\n * equal-or-both-absent, like the hard set.\n */\nexport const MMTP_SIBLING_RENDITION_FIELDS = Object.freeze([\n 'codec',\n 'width',\n 'height',\n 'framerate',\n 'bitrate',\n 'samplerate',\n 'channelConfig',\n 'lang',\n] as const)\n\n/**\n * Fields the pair SHOULD share; a mismatch is reported, not a fault. A soft\n * field is read from the entry of the track subscribed, never borrowed from\n * its sibling: a leg takes the keyframe interval its \"mfu-datagram\" entry\n * states, and none when that entry states none (mmt-02 4.4.3).\n */\nexport const MMTP_SIBLING_SOFT_FIELDS = Object.freeze([\n 'initRef',\n 'keyframeIntervalMs',\n 'keyframeIntervalTicks',\n 'isLive',\n 'altGroup',\n] as const)\n\nexport interface MmtpSiblingPair<T> {\n /** The \"mfu\" track. */\n readonly stream: T\n /** Its \"mfu-datagram\" sibling, when the catalog carries exactly one. */\n readonly datagram?: T\n /** Soft-set fields on which the two differ (empty without a datagram sibling). */\n readonly softMismatches: readonly string[]\n}\n\ntype Fields = Record<string, unknown>\n\nfunction fields(track: object): Fields {\n return track as Fields\n}\n\nfunction groupDurationTicks(track: Fields): bigint | undefined {\n const ticks = track['groupDurationTicks']\n if (Number.isSafeInteger(ticks)) return BigInt(ticks as number)\n const ms = track['groupDurationMs']\n const timescale = track['timescale']\n if (!Number.isSafeInteger(ms) || !Number.isSafeInteger(timescale)) return undefined\n return (BigInt(ms as number) * BigInt(timescale as number)) / 1000n\n}\n\nfunction identityEqual(a: Fields, b: Fields): boolean {\n return (\n a['namespace'] === b['namespace'] &&\n a['timescale'] === b['timescale'] &&\n a['presentationAnchorTicks'] === b['presentationAnchorTicks'] &&\n groupDurationTicks(a) === groupDurationTicks(b) &&\n MMTP_SIBLING_RENDITION_FIELDS.every((field) => a[field] === b[field])\n )\n}\n\nfunction isMmtpTrack(track: unknown, mode: MmtpMode): track is object {\n return (\n typeof track === 'object' && track !== null && !Array.isArray(track) &&\n fields(track)['packaging'] === 'mmtp' && fields(track)['mmtpMode'] === mode\n )\n}\n\n/**\n * The \"mfu\" tracks of `tracks` an \"mfu-datagram\" track could be the sibling\n * of: the ones whose identity set (hard set and rendition fields) equals its own. Exactly one\n * pairs it; zero or more than one rejects the datagram track (mmt-02 4.3.1).\n */\nexport function mmtpSiblingCandidates<T extends object>(tracks: readonly T[], datagram: T): T[] {\n const own = fields(datagram)\n return tracks.filter((track) => isMmtpTrack(track, 'mfu') && identityEqual(fields(track), own))\n}\n\n/**\n * Every \"mfu\" track of `tracks` by name, each with its \"mfu-datagram\" sibling\n * when exactly one matches its identity set. A datagram track that matches no\n * \"mfu\" track or more than one pairs with none, and two datagram tracks that\n * match the same \"mfu\" track pair with neither (each is rejected by\n * `mmtpTrackIssues` in the container validator, which first sets aside a\n * track it rejects for its delivery mode); the \"mfu\" tracks are listed\n * whatever happens to their siblings. Never throws.\n */\nexport function pairMmtpSiblings<T extends object>(tracks: readonly T[]): ReadonlyMap<string, MmtpSiblingPair<T>> {\n const pairs = new Map<string, MmtpSiblingPair<T>>()\n for (const track of tracks) {\n if (!isMmtpTrack(track, 'mfu')) continue\n const name = fields(track)['name']\n if (typeof name === 'string' && !pairs.has(name)) pairs.set(name, { stream: track, softMismatches: [] })\n }\n // Two datagram tracks matching one \"mfu\" track pair with neither: the\n // catalog says nothing about which mirrors it.\n const datagrams = new Map<string, T[]>()\n for (const datagram of tracks) {\n if (!isMmtpTrack(datagram, 'mfu-datagram')) continue\n const candidates = mmtpSiblingCandidates(tracks, datagram)\n if (candidates.length !== 1) continue\n const name = fields(candidates[0]!)['name']\n if (typeof name !== 'string' || pairs.get(name)?.stream !== candidates[0]) continue\n datagrams.set(name, [...(datagrams.get(name) ?? []), datagram])\n }\n for (const [name, matched] of datagrams) {\n if (matched.length !== 1) continue\n const { stream } = pairs.get(name)!\n const a = fields(stream)\n const b = fields(matched[0]!)\n const softMismatches = MMTP_SIBLING_SOFT_FIELDS.filter((field) => a[field] !== b[field])\n pairs.set(name, { stream, datagram: matched[0]!, softMismatches })\n }\n return pairs\n}\n", "// The datagram-leg size table of draft-ramadan-moq-mmt-02 4.3.1: every object\n// of an \"mfu-datagram\" track and of its repair tracks MUST fit one datagram,\n// and SHOULD fit a 1200-byte UDP payload with its QUIC and WebTransport\n// framing, its OBJECT_DATAGRAM header and room for the Object Properties a\n// relay adds. The same numbers live in FFmpeg's moqenc_mmt.h\n// (FF_MOQ_MMT_DG_*) and the dual-stack relay's conformance test; change them\n// together.\n\n/** The smallest maximum UDP payload QUIC allows (RFC 9000 14). */\nexport const DATAGRAM_LEG_UDP_FLOOR = 1200\n/** QUIC short header (1 + DCID <= 20 + PN <= 4) + AEAD tag 16, DATAGRAM frame type + length 3, WebTransport quarter-stream-id varint <= 4. */\nexport const DATAGRAM_LEG_QUIC_WT_FRAMING = 48\n/** OBJECT_DATAGRAM header, varint worst cases: type 1 + alias <= 4 + group <= 4 + object <= 2 + priority 1 + extensions length 1. */\nexport const DATAGRAM_LEG_OBJECT_HEADER = 13\n/** Room for two small varint properties a relay may add (e.g. draft-20 Prior Group/Object ID Gap). */\nexport const DATAGRAM_LEG_RELAY_ROOM = 16\n/** FEC Source Info 0x11 inside Immutable Properties 0x0B on a source object. */\nexport const DATAGRAM_LEG_SOURCE_PROPS = 8\n/** A repair packet is 12 (MMTP header) + 13 (Repair FEC Payload ID) + T bytes (mmt-02 7.3). */\nexport const DATAGRAM_LEG_REPAIR_OVERHEAD = 25\n/** The MoQ datagram budget: what reaches the MoQ layer of a 1200-byte UDP payload. */\nexport const DATAGRAM_LEG_DATAGRAM_MAX = DATAGRAM_LEG_UDP_FLOOR - DATAGRAM_LEG_QUIC_WT_FRAMING\n/** The object body budget: the datagram minus the OBJECT_DATAGRAM header and the relay room. */\nexport const DATAGRAM_LEG_BODY_MAX = DATAGRAM_LEG_DATAGRAM_MAX - DATAGRAM_LEG_OBJECT_HEADER - DATAGRAM_LEG_RELAY_ROOM\n/** The largest RaptorQ symbol size (a multiple of 8) whose repair object fits the body budget. */\nexport const DATAGRAM_LEG_SYMBOL_SIZE_MAX = 1096\n\n/**\n * The largest MoQ datagram a receiver of the leg gets at symbol size T: a\n * repair object with its OBJECT_DATAGRAM header, 13 + 25 + T. The relay's\n * property room is a publisher reserve (DATAGRAM_LEG_BODY_MAX), not a\n * receiver cost: what arrives already carries those properties. A session\n * whose `datagrams.maxDatagramSize` is below it cannot carry the track's\n * repair, so the subscriber takes the \"mfu\" track (mmt-02 4.3.1).\n */\nexport function datagramLegObjectMax(symbolSize: number): number {\n return DATAGRAM_LEG_OBJECT_HEADER + DATAGRAM_LEG_REPAIR_OVERHEAD + symbolSize\n}\n\n/** Whether a RaptorQ symbol size keeps every object of the leg inside the 1200-byte table. */\nexport function datagramLegSymbolSizeFits(symbolSize: number): boolean {\n return (\n Number.isInteger(symbolSize) && symbolSize > 0 && symbolSize % 8 === 0 &&\n symbolSize + DATAGRAM_LEG_REPAIR_OVERHEAD <= DATAGRAM_LEG_BODY_MAX\n )\n}\n", "/**\n * D-28 shared repair-fetch scheduler.\n *\n * Player-agnostic orchestration for per-block on-demand MoQ FEC repair\n * backfill. Each player (moqtail client, hang watch, Shaka MSF bridge)\n * supplies only its protocol verb via {@link RepairFetchTransport}, fetching\n * one block's repair group. Blocks are `iso-ssbg1-v1` (ISO/IEC 23008-1\n * ssbg_mode1, the only FEC block profile), so that group's MoQ id is the\n * 62-bit wrap-epoch-extended SS_Start, `extSsStart(wrapEpoch, ssStart)` from\n * `@blockcast/mmt-fec` -- never the 32-bit block key itself (see\n * `RepairFetchRequest.sbn`):\n *\n * - moqtail: standalone FETCH (FetchType.Standalone) of that one group\n * - moq-lite/hang: Subscribe with startGroup = endGroup = that group (the\n * relay propagates startGroup upstream to pull the past group from the\n * origin's producer cache)\n *\n * Everything else \u2014 registration, fire-time repair-track resolution,\n * keyframe-first admission, preemption, feeding symbols, and in-flight slot\n * release \u2014 is identical across players and lives here. The Player owns the\n * scheduler: one per `wireRepairFetch` call, and its disposer aborts\n * everything.\n *\n * Priority (from the block's class, see `repairPriorityForClass`):\n * - P0 (keyframe / unknown) dispatches as soon as it is enqueued, with no\n * cap. Each has its own fail deadline, and a cap would turn a\n * recoverable protected block into a stall; their number is already\n * bounded by the blocks one fail window can hold. A P0 block that lies\n * below a RAP the receiver already holds complete is not requested at\n * all (`moot-rap`), and a P0 FETCH still running when such a RAP\n * arrives is cancelled (`repair-stopped`, `moot`): the receiver resumes\n * from that RAP (draft-ramadan-moq-fec \u00A711.4.2). Only a repair that\n * could not land by the block's playout deadline (it relies on the\n * keyframe budget's extension) is moot: one that can stalls nothing.\n * - P1 (audio) dispatches, uncapped, while no P0 is queued or in flight;\n * P2 (delta) only while no P0/P1 is, earliest absolute fail deadline\n * first (\u00A711.4.5 item 3).\n * - Only a P0 FETCH the scheduler actually sends aborts the in-flight P1\n * and P2 FETCHes (`repair-preempted`), which return to the queue while\n * their blocks are unresolved: a keyframe request that is refused, moot\n * or otherwise never sent cancels nothing (\u00A711.4.5 item 3), and an audio\n * request never preempts. A P2 that never ran before its block resolved\n * is reported as `repair-deferred`.\n * - A hole walked over the one-Group transport (no `rangeTransport`) is\n * repair the run gets before its FEC deadline (`walkHole`). On a video\n * track it is keyframe repair (class `unknown`): P0, and no audio or\n * delta FETCH is issued while one of its Group FETCHes is outstanding\n * (fec-multicast-00 rule 3). It reaches no FEC deadline, so it preempts\n * nothing and holds back no audio or delta request: one that comes due\n * cancels the walk's Group FETCH and goes out at once, and the walk asks\n * for that Group again after it (`yieldVideoWalks`). On an audio track\n * it is audio repair: P1 at the audio wire priority, one Group per FETCH,\n * and like any audio request it waits while keyframe repair is\n * outstanding, stopping before its next Group, and is preempted by a\n * keyframe FETCH sent.\n * - A block reclassified to a higher class while its P2 fetch is in flight\n * is re-issued at once under the new class's wire priority: the running\n * FETCH is aborted (FETCH_CANCEL) and a new one sent.\n *\n * Wire priority (draft-ramadan-moq-fec \u00A711.4.5): every request carries the\n * MoQ Transport SUBSCRIBER_PRIORITY its FETCH must use, derived from the two\n * catalog priorities `ResolveRepairTarget` returns (see\n * `repairFetchSubscriberPriority`): a keyframe-bearing (or unknown) block's\n * FETCH is sent in the Source Media range at no more than the source\n * track's priority, so it is delivered ahead of every repair track and not\n * shed with repair data; a delta or audio FETCH is sent at no less than the\n * fetched repair track's priority, so it is shed first.\n *\n * Deadline and admission (BLO-35597): a repair FETCH rides the reliable path,\n * so its deadline is the block's PRESENTATION deadline, not the multicast\n * reassembly deadline. The player states how long after a block's first\n * symbol its media can still be presented (`presentationDelayMs`); from the\n * block's receiver-local anchor that gives an absolute deadline, never earlier\n * than the multicast wait and never later than the release gate's hold ceiling\n * (`terminalRetentionMsForPacket`), which bounds how long any successor frame\n * may wait behind the block. A FETCH is sent only when the measured\n * reliable-path RTT (`reliableRttMs`) is less than the time left to that\n * deadline -- a request that cannot come back in time is never sent, rather\n * than sent and cancelled -- and an admitted FETCH holds the block open to\n * that deadline, so the multicast span elapsing never aborts it.\n *\n * Keyframe late-repair budget: a block that may hold a RAP may be given a\n * longer deadline than the playout budget (`keyframeRepairBudgetMs`). Losing\n * such a block costs every frame up to the next keyframe, so holding it open\n * for a FETCH that lands within the budget trades a short hold for a GOP-long\n * freeze. At a small playout budget (a low-latency target) the presentation\n * deadline alone leaves less than one round trip by the time the multicast\n * wait gives up on the block, so every keyframe request would be refused\n * (`rtt-exceeds-budget`). Eligible (`keyframeBudgetEligible`): a `keyframe`\n * block (in-band RAP evidence), and an `unknown` block only while its\n * stream's classifier is `classifying`, where `unknown` means the window rule\n * could not exclude a RAP. Under `all-protected` every block reads `unknown`\n * whatever it holds, so there only RAP evidence earns the budget. Never\n * audio (P1) or delta (P2), and never a block its repair group cannot\n * complete (received sources + RSB_length < K'). The hold ends when its\n * FETCH ends without making the block decodable, not at the budget.\n *\n * Every deadline is capped by the release gate's hold ceiling measured the\n * way the gate measures it: from the earliest frame it holds for the stream\n * (a surviving frame of the block itself is routed before a repair symbol\n * states the block, so before its anchor), never later than from the anchor.\n * A FETCH landing after the gate forced that frame out would recover media\n * the gate then drops as stale.\n *\n * The scheduler arms no timers for block requests. A fetch ends when its\n * transport completes or throws, when it is preempted, when any later\n * scheduling event finds it past its presentation deadline, when its block\n * resolves (recovered, or failed at that deadline), on track reset, or on\n * dispose. A range request (\u00A77.5) is for a hole, not a tracked block, so no\n * FEC deadline resolves it: it arms one timer at its deadline, cleared when\n * it retires, so a hung range FETCH cannot hold the hole (and the release\n * gate behind it) past that deadline.\n */\n\nimport {\n extractRepairFecPayloadId,\n parseFecBlockProfile,\n serial32Add,\n serial32Distance,\n type FecBlockProfile,\n} from '@blockcast/mmt-base'\nimport { extendSsId, repairFetchRange, type RepairFetchRange } from '@blockcast/mmt-fec'\nimport {\n repairPriorityForClass,\n type BlockClass,\n type ClassifierMode,\n type RepairPriority,\n type TrackKind,\n} from './block-policy.js'\nimport type { ExpiredIsoHole, UndelimitedIsoLoss } from './fec-manager.js'\nimport type { RepairLifecycleObserver } from './multicast-manager.js'\nimport { REPAIR_PRIORITY_MIN } from './repair-layers.js'\n\n/** The MoQ Transport priority scale: 0..255, a lower value is delivered first. */\nconst MOQT_PRIORITY_MAX = 255\n\n/**\n * How long before the span a walked hole leaves asks for its repair (D-28)\n * the walk ends: past the deadline timer's 1 ms slack and one timer tick, so\n * the span's request timer is armed before it is due (walkDeadlineAt).\n */\nconst WALK_LEAD_MS = 3\n\n/**\n * The highest value in the Source Media priority range of\n * draft-ramadan-moq-fec \u00A710 (64..191): one below the repair range, which\n * starts at `REPAIR_PRIORITY_MIN` (192).\n */\nexport const SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1\n\n/** What `ResolveRepairTarget` returns for one repair-bearing stream. */\nexport interface RepairTarget {\n /** The repair track to FETCH (base layer 0 of the block's source). */\n readonly repairTrack: string\n /**\n * The catalog `priority` of the SOURCE track the block belongs to, on the\n * MoQ Transport scale (0..255, lower first), or null when the catalog\n * carries none. Never a player constant: a keyframe repair must not be\n * delivered behind the source it repairs, and only the catalog says what\n * that source's priority is.\n */\n readonly sourcePriority: number | null\n /**\n * The catalog priority of `repairTrack` (MoQ Transport scale). Layer 0\n * that declares none has the value draft-ramadan-moq-fec \u00A710 defines\n * (240); `resolveRepairLayers` / `catalogRepairTarget` already apply it.\n * Null only when the resolver cannot read the repair track's entry.\n */\n readonly repairPriority: number | null\n}\n\n/** Resolve a packetId to its repair track and priorities at FIRE TIME.\n *\n * Called on every repair request, never cached by the shell: ABR ladder\n * rungs can share a packetId (e.g. video/720p and video/360p both p:1), so\n * the mapping must reflect the track active when the request fires, not\n * when the shell was wired. Return null when the packetId has no\n * repair-bearing track \u2014 the request is released without a fetch.\n * `catalogRepairTarget` builds the answer from a catalog. */\nexport type ResolveRepairTarget = (\n packetId: number,\n catalogTrackName?: string,\n) => RepairTarget | null\n\n/** One on-demand repair FETCH, as the scheduler hands it to the transport. */\nexport interface RepairFetchRequest {\n /** Repair track whose block `sbn` is fetched. */\n readonly repairTrack: string\n /**\n * The block's key: its 32-bit SS_Start (ISO/IEC 23008-1 C.5.3). The field\n * keeps its historical name, but ssbg_mode1 blocks have no source block\n * number (BLO-35597 D2a). The repair group's MoQ id is the 62-bit\n * `extSsStart(wrapEpoch, sbn)`; a receiver that knows only a lost SS_ID\n * fetches `repairFetchRange(lostSsId, kMax, anchor)`, where `anchor` is\n * `{ previousBlockStart }` (the extended start of the last block delimited\n * before it) or `{ reference }` (an epoch reference). Never use it as a\n * group id directly: SS_Start wraps at 2^32, a MoQ group id never goes\n * backwards.\n */\n readonly sbn: number\n /**\n * The block profile `sbn` is keyed by: the catalog `fec.blockProfile`,\n * which is always `iso-ssbg1-v1`. Required, and validated with\n * `parseFecBlockProfile` when the request is queued, so a stream configured\n * with any other token (the retired `k-padded-v1` included) never reaches\n * the transport.\n */\n readonly blockProfile: FecBlockProfile\n /** The source packetId the block belongs to. */\n readonly packetId: number\n /**\n * Aborts when the scheduler no longer wants the group: preemption by\n * keyframe work, reprioritisation, block resolution, track reset, dispose.\n * When the scheduler stops a running request, `signal.reason` is its\n * `RepairStopReason`, the one `noteRepairStopped` reports.\n */\n readonly signal: AbortSignal\n /**\n * The SUBSCRIBER_PRIORITY parameter the FETCH MUST carry, on the MoQ\n * Transport scale (0..255, lower delivered first), as\n * draft-ramadan-moq-fec \u00A711.4.5 requires. `undefined` means OMIT the\n * parameter: the catalog carries no priority to derive it from, and the\n * publisher then uses the value draft-ietf-moq-transport-16 \u00A79.2.2.3\n * defines for an omitted parameter (128, inside the Source Media range).\n * A transport never substitutes a value of its own. A transport whose API\n * uses another scale (moq-lite's higher-wins weight, say) maps this one\n * without reordering it against the source and repair subscriptions.\n */\n readonly subscriberPriority: number | undefined\n}\n\n/** Protocol-specific fetch of one FEC block's repair group.\n *\n * Yield each repair object payload (MMTP packet bytes, ISO 23008-1 \u00A7C.5.3\n * Repair FEC Payload ID framing). Return when the group ends.\n *\n * Put `request.subscriberPriority` on the FETCH (see RepairFetchRequest).\n *\n * When `request.signal` aborts, the transport MUST cancel the FETCH ON THE\n * WIRE, not merely stop reading: send FETCH_CANCEL for its Request ID\n * (draft-ietf-moq-transport-16 \u00A79.18; STOP_SENDING on an open data stream\n * as well, \u00A75.2), and do it from the abort handler itself, before it\n * returns. A relay that is never told keeps sending the group, so a\n * preempted delta repair keeps competing with the keyframe repair that\n * preempted it. The scheduler may issue the next request for the same block\n * (reprioritisation) as soon as it aborts one, and \u00A711.4.5 allows at most\n * one repair FETCH outstanding per block and repair layer, so the cancel\n * must already be queued ahead of that request. A FETCH whose Request ID\n * is not known yet is cancelled as soon as FETCH_OK assigns it. */\nexport type RepairFetchTransport = (request: RepairFetchRequest) => AsyncIterable<Uint8Array>\n\n/**\n * One range repair FETCH for a lost SS_ID in an undelimited span\n * (draft-ramadan-moq-fec \u00A77.5): the absolute, inclusive repair-track Group\n * range `repairFetchRange` gives. The last Group returned is the block holding\n * `lostSsId`; earlier ones are other blocks, admitted like any repair object.\n */\nexport interface RepairRangeFetchRequest extends RepairFetchRange {\n readonly repairTrack: string\n /** The lost SS_ID x the range was computed for. */\n readonly lostSsId: number\n readonly blockProfile: FecBlockProfile\n readonly packetId: number\n /** Same contract as `RepairFetchRequest.signal`: cancel on the wire. */\n readonly signal: AbortSignal\n /** Same contract as `RepairFetchRequest.subscriberPriority`. */\n readonly subscriberPriority: number | undefined\n}\n\n/**\n * Protocol-specific range FETCH (e.g. MoQT LOCATION_FILTER 0x03 Group range).\n * Yield each repair object payload; return when the range ends. The abort\n * rules of {@link RepairFetchTransport} apply unchanged.\n */\nexport type RepairRangeFetchTransport = (request: RepairRangeFetchRequest) => AsyncIterable<Uint8Array>\n\n/** Why a request could not carry a catalog-derived priority. */\nexport type RepairPriorityReason =\n | 'source-priority-absent'\n | 'source-priority-invalid'\n | 'repair-priority-absent'\n | 'repair-priority-invalid'\n\n/**\n * The wire priority of one repair request (draft-ramadan-moq-fec \u00A711.4.5).\n *\n * - `carry`: send the FETCH with `subscriberPriority`.\n * - `omit`: send it without SUBSCRIBER_PRIORITY. Only a keyframe-bearing or\n * unknown block's request is ever sent this way: the publisher then uses\n * 128 (draft-ietf-moq-transport-16 \u00A79.2.2.3), which lies in the Source\n * Media range, and without a catalog source priority there is no bound\n * below it to honour.\n * - `decline`: send no FETCH. A delta or audio FETCH MUST carry a priority\n * at least its repair track's, so at least 192, and the omitted value (128)\n * would put best-effort repair ahead of every repair track. Unicast repair\n * is optional for those classes (\u00A711.4.3, \u00A711.4.4); in-band FEC and\n * concealment still apply.\n */\nexport type RepairFetchPriority =\n | { readonly kind: 'carry'; readonly subscriberPriority: number }\n | { readonly kind: 'omit'; readonly reason: RepairPriorityReason }\n | { readonly kind: 'decline'; readonly reason: RepairPriorityReason }\n\nfunction isMoqtPriority(value: number): boolean {\n return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX\n}\n\n/**\n * Derive the SUBSCRIBER_PRIORITY of a repair FETCH from the block's class and\n * the catalog priorities of its source and repair tracks\n * (draft-ramadan-moq-fec \u00A711.4.5 and the \u00A710 ranges):\n *\n * - keyframe / unknown: in the Source Media range and no greater than the\n * source track's priority, i.e. min(source, 191); omitted when the catalog\n * carries no source priority.\n * - delta / audio: no lower than the fetched repair track's priority and at\n * least 192, i.e. max(repair, 192); declined when it carries none.\n */\nexport function repairFetchSubscriberPriority(\n blockClass: BlockClass,\n target: Pick<RepairTarget, 'sourcePriority' | 'repairPriority'>,\n): RepairFetchPriority {\n if (repairPriorityForClass(blockClass) === 0) {\n const source = target.sourcePriority\n if (source === null) return { kind: 'omit', reason: 'source-priority-absent' }\n if (!isMoqtPriority(source)) return { kind: 'omit', reason: 'source-priority-invalid' }\n return { kind: 'carry', subscriberPriority: Math.min(source, SOURCE_MEDIA_PRIORITY_MAX) }\n }\n const repair = target.repairPriority\n if (repair === null) return { kind: 'decline', reason: 'repair-priority-absent' }\n if (!isMoqtPriority(repair)) return { kind: 'decline', reason: 'repair-priority-invalid' }\n return { kind: 'carry', subscriberPriority: Math.max(repair, REPAIR_PRIORITY_MIN) }\n}\n\n/** What `RepairFetchHost.fecManager.blockSymbolCounts` reports for one open block. */\nexport interface BlockSymbolCounts {\n readonly sources: number\n readonly repairs: number\n readonly authoredLength: number | undefined\n readonly repairGroupLength: number | undefined\n}\n\n/**\n * Whether a block of `blockClass` may get the keyframe late-repair budget:\n * a `keyframe` block always (in-band RAP evidence), an `unknown` block only\n * while its stream's classifier is `classifying` (the window rule could not\n * exclude a RAP). An `all-protected` stream reads `unknown` for every block,\n * delta-only ones included, so there `unknown` is no evidence of a RAP and\n * earns no hold. Audio and delta never do.\n */\nexport function keyframeBudgetEligible(\n blockClass: BlockClass,\n classifierMode: ClassifierMode | undefined,\n): boolean {\n if (blockClass === 'keyframe') return true\n return blockClass === 'unknown' && classifierMode === 'classifying'\n}\n\nexport interface WireRepairFetchOptions {\n resolveTarget: ResolveRepairTarget\n transport: RepairFetchTransport\n /**\n * Maximum transport attempts per block (required). A retry happens only\n * when the transport rejects with an error `shouldRetry` classifies as\n * retryable, before any symbol was fed, while the block's deadline remains.\n */\n attemptLimit: number\n /** Classify a transport error as a transient publisher/relay retention race. */\n shouldRetry?: (error: unknown) => boolean\n /**\n * The measured round-trip time of the reliable path the transport fetches\n * over, in ms (required). Read at every admission, so it tracks the live\n * session. A value that is not finite and positive, or a throw, means the\n * path offers no measurement: nothing can show the FETCH would come back in\n * time, so none is sent (`rtt-unmeasured`). Never a default.\n */\n reliableRttMs: () => number\n /**\n * How long after a block's first symbol arrived its media can still be\n * presented, in ms (required): the player's own playout budget for the\n * stream. Same fail-closed rule as `reliableRttMs`\n * (`presentation-delay-unavailable`).\n */\n presentationDelayMs: (packetId: number, catalogTrackName?: string) => number\n /**\n * How long after the first symbol of a block that may hold a RAP a repair\n * FETCH of it may still land, in ms (optional). Such a block\n * (`keyframeBudgetEligible`) gets the larger of this and\n * `presentationDelayMs`, still never later than the release gate's hold\n * ceiling and never earlier than the multicast wait; RTT admission is\n * unchanged. Losing a keyframe block costs the rest of its GOP, so a player\n * may hold the block (and the frames released after it) while its FETCH is\n * in flight rather than freeze to the next keyframe. Absent, throwing, or\n * not finite and positive: every block gets the presentation deadline\n * alone. Never applied to audio, delta, or an `unknown` block of an\n * `all-protected` stream.\n */\n keyframeRepairBudgetMs?: (packetId: number, catalogTrackName?: string) => number\n /**\n * Range repair for a lost SS_ID whose block no repair delimited\n * (draft-ramadan-moq-fec \u00A77.5), optional. A host that can keep such a gap as\n * a pending hole gets range repair either way, under the same admission,\n * priority and abort rules as a block request (class `unknown`, P0). Given,\n * the scheduler FETCHes `repairFetchRange(x, K, anchor)` over it, and\n * requires `repairEpochReference`. Absent, it walks the hole over\n * `transport` one Group at a time from the hole's start, whose Group is a\n * block's, each repair stating where the next block starts (BLO-52085),\n * under the class of the hole's track (see the module note).\n */\n rangeTransport?: RepairRangeFetchTransport\n /**\n * The epoch reference r of `repairTrack` on the live session\n * (`RepairEpochReferences.reference`), or undefined while none is held.\n * The \u00A77.5 anchor is ext(S_prev) extended from it when a stated block ends\n * where the hole starts, else r itself; without r no range request is sent\n * (`range-no-anchor`).\n */\n repairEpochReference?: (repairTrack: string) => bigint | undefined\n}\n\n/** Why the D-28 layer asked for a repair: the block's class at its deadline. */\nexport type RepairSubscribeCallback = (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n) => void\n\n/** Why the scheduler sent no FETCH for a block it was asked to repair. */\nexport type RepairSkipReason =\n /** The reliable path offered no RTT measurement; arrival cannot be shown. */\n | 'rtt-unmeasured'\n /** The measured RTT is not less than the time left to the deadline. */\n | 'rtt-exceeds-budget'\n /** The player gave no usable presentation delay for the block's stream. */\n | 'presentation-delay-unavailable'\n /** A lost SS_ID in an undelimited span had no \u00A77.5 anchor to extend it from. */\n | 'range-no-anchor'\n /**\n * The block lost more sources than its repair group carries symbols\n * (sources + RSB_length < K'): no FETCH of the group can complete it, and\n * when multicast already delivered the whole group the relay could serve\n * only duplicates (BLO-50082).\n */\n | 'group-cannot-complete'\n /**\n * The keyframe-bearing block lies below a RAP the receiver already holds\n * complete, so its repair would be moot (draft-ramadan-moq-fec \u00A711.4.2).\n */\n | 'moot-rap'\n\n/**\n * Which term set a FETCH's deadline (BLO-33597): the multicast wait, the\n * player's presentation delay past the block anchor, the keyframe budget past\n * the anchor (when it granted more than the presentation delay), or the\n * release gate's retention ceiling.\n */\nexport type RepairDeadlineBound = 'wait' | 'presentation' | 'keyframe' | 'retention'\n\n/** The admission inputs of a FETCH the scheduler sent (BLO-33597). */\nexport interface RepairSendMeasurement {\n /** The reliable-path RTT admission compared against `budgetMs`. */\n readonly rttMs: number\n /** Time left to the entry's deadline when the FETCH was sent. */\n readonly budgetMs: number\n /**\n * Delay past the block anchor the deadline was computed from; null when\n * the block had no anchor (its deadline is then the multicast wait).\n */\n readonly delayMs: number | null\n /** Time since the block anchor; null when the block had no anchor. */\n readonly blockAgeMs: number | null\n readonly bound: RepairDeadlineBound\n /** True for a range repair FETCH (\u00A77.5 lost SS_ID); absent for a block FETCH. */\n readonly range?: true\n}\n\n/** The subset of MulticastManager the scheduler drives. */\nexport interface RepairFetchHost {\n readonly fecManager: {\n blockProfileForPacket(packetId: number): FecBlockProfile | undefined\n repairFetchTimeoutMsForBlock(sbn: number, packetId: number, catalogTrackName?: string): number | undefined\n /** Receiver-local time of the block's first accepted symbol, if any. */\n blockAnchorAtMs(sbn: number, packetId: number, catalogTrackName?: string): number | undefined\n /** The stream's classifier mode (optional; absent reads as unknown). */\n classifierModeFor?(packetId: number, catalogTrackName?: string): { readonly mode: ClassifierMode }\n /**\n * An open block's received sources and distinct repair symbols, its K'\n * (SSB_length) and RSB_length (optional). The repair group carries\n * RSB_length symbols, so it can complete the block only when\n * sources + RSB_length >= K'; a FETCH that ended leaving fewer than K'\n * distinct symbols cannot be decoding it.\n */\n blockSymbolCounts?(\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): BlockSymbolCounts | undefined\n /** How long a terminal block stays authoritative: the release-gate hold ceiling. */\n terminalRetentionMsForPacket(packetId: number): number | undefined\n /** Keep the block open to `untilAtMs` for an admitted FETCH. */\n holdBlockForRepair(\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n untilAtMs: number,\n ): boolean\n /** The admitted FETCH ended without delivering: back to the multicast wait. */\n releaseRepairHold(sbn: number, packetId: number, catalogTrackName?: string): void\n /** Run `fn` with `receivedAtMs` as the receipt time of what it feeds (optional). */\n withReceiptTime?(receivedAtMs: number, fn: () => void): void\n /** The configured media kind of a packetId (optional; absent reads as video). */\n trackKindFor?(packetId: number): TrackKind | undefined\n /** The stream's D-28 repair deadline: how long after a block's sources it asks for repair (optional). */\n repairDeadlineMsForPacket?(packetId: number): number | undefined\n }\n onRepairSubscribe(cb: RepairSubscribeCallback): void\n /**\n * Arrival time of the earliest frame the in-order release gate holds for\n * the stream, or undefined (optional; absent, the block's anchor bounds the\n * ceiling alone). The gate releases that frame `terminalRetentionMsForPacket`\n * after it, whatever its blocks are doing.\n */\n earliestGatedFrameAtMs?(packetId: number, catalogTrackName?: string): number | undefined\n /** The keyframe budget extended a request's deadline by `extensionMs` (optional). */\n noteKeyframeBudgetGranted?(\n extensionMs: number,\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n addRepairLifecycleObserver(observer: RepairLifecycleObserver): () => void\n addTrackResetObserver(observer: (packetId: number, catalogTrackName: string) => void): () => void\n /**\n * Register for lost SS_IDs in undelimited spans (required with\n * `rangeTransport`). A host that offers it and `closeIsoHoles` keeps such a\n * gap as a pending hole for the scheduler to repair. `onExpired` is told of\n * a pending hole the stream ran past the locator's horizon; returning true,\n * the scheduler closes it (`closeIsoHoles`), otherwise the host discards it.\n */\n onUndelimitedLoss?(\n cb: (loss: UndelimitedIsoLoss) => void,\n onExpired?: (hole: ExpiredIsoHole) => boolean,\n ): void\n /** A hole's range repair ended, or none is sent: feed what was not stated. */\n closeIsoHoles?(packetId: number, catalogTrackName: string | undefined, start: number, length: number): void\n clearRepairForBlock(sbn: number, packetId: number, catalogTrackName?: string): void\n processRepairFromMoQ(packet: Uint8Array, ownerPacketId?: number, catalogTrackName?: string): void\n /** This scheduler can request unicast repair: protected flows keep pending entries for it (optional). */\n setUnicastRepair?(enabled: boolean): void\n noteRepairScheduling(\n type: 'repair-preempted' | 'repair-deferred',\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /** A request whose wire priority the catalog could not supply. */\n noteRepairPriority(\n action: 'omitted' | 'declined',\n reason: RepairPriorityReason,\n blockClass: BlockClass,\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /**\n * A request the scheduler did not send (see RepairSkipReason).\n * `measurement.priority` is the request's repair priority (0 keyframe or\n * unknown, 1 audio, 2 delta).\n */\n noteRepairSkipped(\n reason: RepairSkipReason,\n measurement: { readonly rttMs: number | null; readonly budgetMs: number; readonly priority?: RepairPriority },\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /** A running FETCH the scheduler stopped, and why (optional). */\n noteRepairStopped?(\n reason: RepairStopReason,\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /**\n * Whether a complete RAP above SS_ID `ssId` already reached the stream\n * (optional; absent, none ever has). Under the bc-provenance profile only\n * an admitted RAP counts (multicast-01 \u00A77.2.7).\n */\n rapCompleteAbove?(packetId: number, catalogTrackName: string | undefined, ssId: number): boolean\n /** Observe each complete RAP reaching a stream (optional; called synchronously). */\n addRapCompleteObserver?(\n observer: (packetId: number, catalogTrackName: string | undefined, ssId: number) => void,\n ): () => void\n /**\n * Observe each base block (`sbn`) whose RAP fragments the keyframe overlay\n * recovered with the keyframe's FT=0 and FT=1 held (optional; called\n * synchronously). Its keyframe FETCH is then stopped (fec-multicast-00 \u00A76.6).\n */\n addKeyframeOverlayRecoveredObserver?(\n observer: (packetId: number, catalogTrackName: string | undefined, sbn: number) => void,\n ): () => void\n /**\n * A FETCH the scheduler admitted and handed to the transport (optional):\n * every attempt, a retry or a reprioritised restart included.\n */\n noteRepairFetchSent?(\n priority: RepairPriority,\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n measurement: RepairSendMeasurement,\n ): void\n}\n\n/**\n * Why the scheduler ended a running FETCH (the transport cancels it on the\n * wire): preempted by a sent keyframe FETCH, reissued at a new class's\n * priority, past its deadline, its block resolved, track reset or a newer\n * request for the block, dispose, `moot` (a RAP above the block arrived\n * complete first, draft-ramadan-moq-fec \u00A711.4.2), or `overlay-recovered`\n * (the keyframe overlay recovered the block's RAP, fec-multicast-00 \u00A76.6).\n */\nexport type RepairStopReason =\n | 'preempted'\n | 'reprioritized'\n | 'expired'\n | 'resolved'\n | 'reset'\n | 'disposed'\n | 'moot'\n | 'overlay-recovered'\ntype StopReason = RepairStopReason\n\ninterface FetchRun {\n readonly controller: AbortController\n /** When this FETCH went out: it lands around `sentAt + rtt`. */\n readonly sentAt: number\n stopped: StopReason | null\n}\n\ninterface RepairEntry {\n readonly key: string\n readonly sbn: number\n readonly packetId: number\n readonly catalogTrackName?: string\n readonly repairTrack: string\n readonly target: RepairTarget\n /** The block profile `sbn` is keyed by, resolved before the entry is queued. */\n readonly blockProfile: FecBlockProfile\n priority: RepairPriority\n /** SUBSCRIBER_PRIORITY for this entry's class; undefined = omit it. */\n subscriberPriority: number | undefined\n /**\n * Absolute `performance.now()` millisecond by which a FETCH must land: the\n * block's presentation deadline (see the module note). Only ever moves\n * later: a block reclassified from delta can gain the keyframe budget.\n */\n deadlineAt: number\n /**\n * `deadlineAt` without the keyframe budget's extension: the block's playout\n * deadline. A FETCH landing by it costs no stall, so it is never moot.\n */\n playoutDeadlineAt: number\n /** Inputs `deadlineAt` was computed from; they move with it. */\n anchorAt: number | null\n delayMs: number | null\n bound: RepairDeadlineBound\n /** Monotonic enqueue order, the EDF tie-break. */\n readonly order: number\n attempts: number\n running: FetchRun | null\n /** A range request for a pending hole `[sbn, sbn + holeLength)`. */\n readonly range?: {\n readonly lostSsId: number\n readonly holeLength: number\n /** The \u00A77.7 Group range for `rangeTransport`; null walks the hole over `transport`. */\n readonly groups: RepairFetchRange | null\n /** When the hole was reported: what it states keeps the deadline a span opened then would have. */\n readonly reportedAt: number\n }\n /** A range request's deadline timer (see the module note). */\n expiry?: ReturnType<typeof setTimeout>\n /**\n * A hole walked over `transport` (walkHole): the Group its next FETCH asks\n * for, and the Group FETCH it has outstanding, if any.\n */\n walk?: {\n next: number\n group: { readonly sbn: number; readonly controller: AbortController } | null\n /** Its Group FETCH was cancelled for best-effort repair: ask for that Group again. */\n yielded: boolean\n }\n}\n\ninterface ResolvedDeadline {\n readonly deadlineAt: number\n readonly extensionMs: number\n readonly anchorAt: number | null\n readonly delayMs: number | null\n readonly bound: RepairDeadlineBound\n}\n\n/**\n * Wire the D-28 repair-fetch scheduler onto a MulticastManager.\n *\n * Call AFTER the manager has a repair-bearing FEC configuration (players gate\n * this on the first fec-setup that carries a repairTrack) \u2014 registration arms\n * the per-block repair deadlines in the FEC layer.\n *\n * Returns a dispose function that aborts outstanding fetches and stops new\n * ones from being issued.\n */\nexport function wireRepairFetch(mc: RepairFetchHost, opts: WireRepairFetchOptions): () => void {\n if (!Number.isSafeInteger(opts.attemptLimit) || opts.attemptLimit < 1) {\n throw new Error(\n `[RepairFetch] attemptLimit=${String(opts.attemptLimit)} must be a positive integer`,\n )\n }\n if (typeof opts.reliableRttMs !== 'function') {\n throw new Error('[RepairFetch] reliableRttMs is required: repair admission needs the measured reliable-path RTT')\n }\n if (typeof opts.presentationDelayMs !== 'function') {\n throw new Error('[RepairFetch] presentationDelayMs is required: a repair FETCH is due by the block\\'s presentation deadline')\n }\n if (\n opts.rangeTransport !== undefined &&\n (typeof opts.repairEpochReference !== 'function' || !mc.onUndelimitedLoss || !mc.closeIsoHoles)\n ) {\n throw new Error('[RepairFetch] rangeTransport needs repairEpochReference and a host that reports undelimited losses')\n }\n mc.setUnicastRepair?.(true)\n const entries = new Map<string, RepairEntry>()\n const warnedNoTarget = new Set<string>()\n let disposed = false\n let enqueueOrder = 0\n\n const requestKey = (sbn: number, packetId: number, catalogTrackName?: string): string =>\n JSON.stringify([packetId, catalogTrackName ?? null, sbn])\n const noTargetKey = (packetId: number, catalogTrackName?: string): string =>\n JSON.stringify([packetId, catalogTrackName ?? null])\n\n const clearRepair = (sbn: number, packetId: number, catalogTrackName?: string): void => {\n if (catalogTrackName === undefined) mc.clearRepairForBlock(sbn, packetId)\n else mc.clearRepairForBlock(sbn, packetId, catalogTrackName)\n }\n const note = (type: 'repair-preempted' | 'repair-deferred', entry: RepairEntry): void => {\n mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n /** Whatever ends an entry: a block's repair slot, or a hole's pending state. */\n const clearEntry = (entry: RepairEntry): void => {\n const { range } = entry\n if (range) {\n atReport(range, () => mc.closeIsoHoles!(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength))\n } else {\n clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n }\n\n /**\n * Run what a hole's walk states, or the rest of the hole it leaves as\n * spans, at the time the hole was reported: the blocks start their\n * deadlines from there, as the one repair-less span a host without holes\n * opened then would have, so the walk never holds a frame later than that\n * span did. A \u00A77.7 range FETCH feeds at its own receipt time, as a host\n * with `rangeTransport` always has.\n */\n const atReport = (range: NonNullable<RepairEntry['range']>, work: () => void): void => {\n const fec = mc.fecManager\n if (range.groups !== null || fec.withReceiptTime === undefined) work()\n else fec.withReceiptTime(range.reportedAt, work)\n }\n\n const releaseHold = (entry: RepairEntry): void => {\n // A hole is no tracked block: nothing holds it but the hole itself.\n if (entry.range) return\n if (entry.catalogTrackName === undefined) mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId)\n else mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n const stop = (entry: RepairEntry, reason: StopReason): void => {\n const run = entry.running\n if (!run) return\n entry.running = null\n run.stopped = reason\n run.controller.abort(reason)\n // A preempted request returns to the queue; until it runs again nothing is\n // in flight that could land, so the block goes back to its multicast wait.\n if (reason === 'preempted') releaseHold(entry)\n mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n /** The last SS_ID the entry covers, or undefined while its block is undelimited. */\n const lastSsId = (entry: RepairEntry): number | undefined => {\n if (entry.range) return entry.sbn + entry.range.holeLength - 1\n const length = symbolCounts(entry.sbn, entry.packetId, entry.catalogTrackName)?.authoredLength\n return length === undefined ? undefined : entry.sbn + length - 1\n }\n\n /**\n * A keyframe request whose whole block lies below a RAP already held\n * complete, and whose repair can only land on the keyframe budget's\n * extension. One that lands by the playout deadline stalls nothing, and\n * skipping it only throws away the block's frames (BLO-51635).\n */\n const moot = (entry: RepairEntry): boolean => {\n if (entry.priority !== 0) return false\n const rttMs = readRtt()\n // A running FETCH lands relative to when it was sent, not to now.\n const sentAt = entry.running?.sentAt ?? performance.now()\n if (rttMs !== null && sentAt + rttMs < entry.playoutDeadlineAt) return false\n const last = lastSsId(entry)\n if (last === undefined) return false\n try {\n return mc.rapCompleteAbove?.(entry.packetId, entry.catalogTrackName, last) === true\n } catch {\n return false\n }\n }\n\n /** Drop a request no FETCH will be sent for, and say why. */\n const skip = (entry: RepairEntry, reason: RepairSkipReason, rttMs: number | null, budgetMs: number): void => {\n retire(entry)\n releaseHold(entry)\n clearEntry(entry)\n mc.noteRepairSkipped(\n reason,\n { rttMs, budgetMs, priority: entry.priority },\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n )\n }\n\n /** The keyframe budget for a P0 block, or null: absent, throwing or not positive. */\n const readKeyframeBudget = (packetId: number, catalogTrackName: string | undefined): number | null => {\n const reader = opts.keyframeRepairBudgetMs\n if (reader === undefined) return null\n try {\n const budgetMs = reader(packetId, catalogTrackName)\n return Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : null\n } catch {\n return null\n }\n }\n\n const readRtt = (): number | null => {\n try {\n const rtt = opts.reliableRttMs()\n return Number.isFinite(rtt) && rtt > 0 ? rtt : null\n } catch {\n return null\n }\n }\n\n /**\n * Admission: send only a FETCH whose repair group can complete the block\n * and that the measured round trip says can land before the entry's\n * deadline. A refused entry is released, not queued: the\n * deadline only gets closer. Returns the admitting RTT, or null when refused.\n */\n const admit = (entry: RepairEntry, now: number): number | null => {\n const budgetMs = entry.deadlineAt - now\n const rttMs = readRtt()\n const reason = refusal(entry, now, rttMs)\n if (reason === null) return rttMs\n skip(entry, reason, rttMs, budgetMs)\n return null\n }\n\n /** Why admission refuses `entry` at `now` with round trip `rttMs`, or null when it admits it. */\n const refusal = (entry: RepairEntry, now: number, rttMs: number | null): RepairSkipReason | null =>\n !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName)\n ? 'group-cannot-complete'\n : rttMs === null\n ? 'rtt-unmeasured'\n : rttMs < entry.deadlineAt - now\n ? null\n : 'rtt-exceeds-budget'\n\n const retire = (entry: RepairEntry): void => {\n if (entries.get(entry.key) === entry) entries.delete(entry.key)\n if (entry.expiry !== undefined) clearTimeout(entry.expiry)\n }\n\n /**\n * Whether `entry` holds back a request of `priority`: no audio or delta\n * repair FETCH is issued while a keyframe repair FETCH is outstanding\n * (fec-multicast-00 rule 3), and no delta one while audio repair is. A\n * walk (walkHole) is repair a run gets before it reaches its FEC deadline:\n * on a video track it is keyframe repair while one of its Group FETCHes is\n * outstanding and between two Groups holds nothing back; on an audio track\n * it holds nothing back (BLO-52085). `videoWalks` false leaves video walks\n * out: they yield to a request that is no walk (`yieldVideoWalks`).\n */\n const holdsBack = (entry: RepairEntry, priority: RepairPriority, videoWalks = true): boolean => {\n if (entry.priority >= priority) return false\n const { walk } = entry\n if (walk === undefined) return true\n if (entry.priority !== 0 || !videoWalks) return false\n return entry.running === null || (walk.group !== null && !walk.group.controller.signal.aborted)\n }\n\n /** Whether any entry holds back a request of `priority` (see `holdsBack`). */\n const outstandingBelow = (priority: RepairPriority, videoWalks = true): boolean => {\n for (const entry of entries.values()) {\n if (holdsBack(entry, priority, videoWalks)) return true\n }\n return false\n }\n\n /**\n * A video walk reaches no FEC deadline, so it holds back no audio or delta\n * request that came due (one of `queued` that is no walk), that nothing\n * else holds back and that admission takes (`admit`): it cancels its outstanding Group FETCH first, so no\n * keyframe repair FETCH is outstanding when that request is issued\n * (fec-multicast-00 rule 3), and asks for that Group again after it\n * (walkHole). Audio and delta repair so goes out when it would with no\n * walk at all (BLO-52085).\n */\n const yieldVideoWalks = (queued: readonly RepairEntry[]): void => {\n const now = performance.now()\n const rttMs = readRtt()\n const due = queued.some((entry) =>\n entry.priority !== 0 && entry.walk === undefined && !outstandingBelow(entry.priority, false) &&\n refusal(entry, now, rttMs) === null)\n if (!due) return\n for (const entry of entries.values()) {\n const walk = entry.walk\n if (entry.priority !== 0 || walk === undefined || walk.group === null) continue\n if (walk.group.controller.signal.aborted) continue\n walk.yielded = true\n walk.group.controller.abort()\n }\n }\n\n /**\n * A keyframe FETCH is being sent: cancel every in-flight audio and delta\n * FETCH (\u00A711.4.5 item 3). Called only for a FETCH actually sent.\n */\n const preemptBestEffort = (): void => {\n for (const entry of entries.values()) {\n if (entry.priority === 0 || !entry.running) continue\n stop(entry, 'preempted')\n note('repair-preempted', entry)\n }\n }\n\n /**\n * The wire priority for `blockClass`, or null when no FETCH may be sent.\n * A priority the catalog cannot supply is reported once per request.\n */\n const wirePriority = (\n entry: Pick<RepairEntry, 'target' | 'sbn' | 'packetId' | 'catalogTrackName'>,\n blockClass: BlockClass,\n ): { subscriberPriority: number | undefined } | null => {\n const derived = repairFetchSubscriberPriority(blockClass, entry.target)\n if (derived.kind === 'carry') return { subscriberPriority: derived.subscriberPriority }\n mc.noteRepairPriority(\n derived.kind === 'omit' ? 'omitted' : 'declined',\n derived.reason,\n blockClass,\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n )\n return derived.kind === 'omit' ? { subscriberPriority: undefined } : null\n }\n\n /** `counted` is false for a reprioritisation restart, which is no retry. */\n const start = (entry: RepairEntry, counted = true): void => {\n const now = performance.now()\n if (moot(entry)) {\n skip(entry, 'moot-rap', readRtt(), entry.deadlineAt - now)\n return\n }\n const rttMs = admit(entry, now)\n if (rttMs === null) return\n // Before the transport sees this request, so the cancels go out first. A\n // walk reaches no FEC deadline, so it cancels nothing (rule 3).\n if (entry.priority === 0 && entry.walk === undefined) preemptBestEffort()\n // fec-multicast-00 rule 1: one FETCH per block and repair layer. A walk\n // reading this block's Group leaves it to this request.\n if (entry.range === undefined) leaveWalkedGroup(entry)\n if (counted) entry.attempts++\n mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {\n rttMs,\n budgetMs: entry.deadlineAt - now,\n delayMs: entry.delayMs,\n blockAgeMs: entry.anchorAt === null ? null : Math.max(0, now - entry.anchorAt),\n bound: entry.bound,\n ...(entry.range ? { range: true as const } : {}),\n })\n const run: FetchRun = { controller: new AbortController(), sentAt: now, stopped: null }\n entry.running = run\n // Hold the block open to the presentation deadline while this FETCH can\n // still land: the multicast span elapsing must not abort it.\n if (!entry.range) {\n mc.fecManager.holdBlockForRepair(\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n entry.deadlineAt,\n )\n }\n void execute(entry, run)\n }\n\n /** End any walk's FETCH of `block`'s Group, cancelling it, before the block's own goes out. */\n const leaveWalkedGroup = (block: RepairEntry): void => {\n for (const entry of entries.values()) {\n const group = entry.walk?.group\n if (\n group?.sbn === block.sbn &&\n entry.packetId === block.packetId &&\n entry.catalogTrackName === block.catalogTrackName\n ) {\n group.controller.abort()\n }\n }\n }\n\n const dispatch = (): void => {\n if (disposed) return\n const now = performance.now()\n const queued: RepairEntry[] = []\n for (const entry of [...entries.values()]) {\n if (entry.running) {\n // A fetch still running at its block's fail bound can no longer land\n // in time. Cancel it here rather than trust the transport or the FEC\n // layer's resolution to end it: a hung P0/P1 left running would keep\n // outstandingBelow() true and gate every P1/P2 for the session.\n if (entry.deadlineAt <= now) {\n stop(entry, 'expired')\n retire(entry)\n clearEntry(entry)\n }\n continue\n }\n if (entry.deadlineAt <= now) {\n // The block's fail bound has passed; its resolution is imminent and\n // no fetch can land in time.\n retire(entry)\n if (entry.priority === 2 && entry.attempts === 0) note('repair-deferred', entry)\n clearEntry(entry)\n continue\n }\n queued.push(entry)\n }\n for (const entry of queued) {\n if (entry.priority === 0) start(entry)\n }\n yieldVideoWalks(queued)\n if (outstandingBelow(1)) return\n for (const entry of queued) {\n if (entry.priority === 1) start(entry)\n }\n if (outstandingBelow(2)) return\n queued\n .filter((entry) => entry.priority === 2)\n .sort((a, b) => a.deadlineAt - b.deadlineAt || a.order - b.order)\n .forEach((entry) => start(entry))\n }\n\n /**\n * Whether the block may still be decoding from what it holds: false only\n * when the host shows fewer distinct symbols than its K'. A FETCH that\n * ended leaving it short delivered all it could (its group carries no more\n * symbols), so holding the block, and every frame behind it, longer buys\n * nothing: it goes back to its multicast wait. Unknown counts read as\n * decodable (the FEC layer resolves the block).\n */\n const symbolCounts = (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n ): BlockSymbolCounts | undefined => {\n try {\n return mc.fecManager.blockSymbolCounts?.(sbn, packetId, catalogTrackName)\n } catch {\n return undefined\n }\n }\n const decodable = (entry: RepairEntry): boolean => {\n const counts = symbolCounts(entry.sbn, entry.packetId, entry.catalogTrackName)\n if (counts === undefined || counts.authoredLength === undefined) return true\n return counts.sources + counts.repairs >= counts.authoredLength\n }\n /**\n * Whether the block's repair group can complete it: its received sources\n * plus every symbol the group carries reach K'. A loss of more sources than\n * the group has repair symbols (every source-only loss among them: the\n * block then already holds the whole group) gets no FETCH-length hold. True\n * while the counts are not known (no repair stated the block yet).\n */\n const groupCanComplete = (sbn: number, packetId: number, catalogTrackName: string | undefined): boolean => {\n const counts = symbolCounts(sbn, packetId, catalogTrackName)\n if (counts === undefined || counts.authoredLength === undefined || counts.repairGroupLength === undefined) {\n return true\n }\n return counts.sources + counts.repairGroupLength >= counts.authoredLength\n }\n /**\n * Whether the block a walked Group states can use none of the Group's other\n * repair symbols: the host holds as many of its symbols as its K' (complete,\n * or decoding), its group cannot complete it, or it no longer tracks it\n * (resolved). A relay may hold only part of a Group, or keep its FETCH open,\n * so the walk does not wait for the rest. False when the host reports no\n * counts: the walk then takes the whole Group.\n */\n const groupServed = (sbn: number, packetId: number, catalogTrackName: string | undefined): boolean => {\n if (mc.fecManager.blockSymbolCounts === undefined) return false\n const counts = symbolCounts(sbn, packetId, catalogTrackName)\n if (counts === undefined || counts.authoredLength === undefined) return true\n return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName)\n }\n /** Where the next block starts after the open block `sbn`, when a repair stated it. */\n const statedEnd = (sbn: number, packetId: number, catalogTrackName: string | undefined): number | undefined => {\n const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength\n return length === undefined ? undefined : serial32Add(sbn, length)\n }\n\n const finish = (entry: RepairEntry, run: FetchRun, fed: number, error: unknown): void => {\n if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {\n return\n }\n entry.running = null\n if (error === undefined) {\n retire(entry)\n // A fetch that ended without feeding anything cannot resolve the block;\n // release the slot and the hold so failure accounting is not wedged. A\n // fetch that fed symbols leaves resolution to the FEC layer.\n // A range FETCH placed whatever it stated as it arrived; the rest of\n // its hole is now known to have no repair coming.\n if (entry.range || fed === 0 || !decodable(entry)) {\n releaseHold(entry)\n clearEntry(entry)\n }\n dispatch()\n return\n }\n const retryable =\n fed === 0 &&\n entry.attempts < opts.attemptLimit &&\n entry.deadlineAt > performance.now() &&\n opts.shouldRetry?.(error) === true\n if (retryable) {\n // Back through the same admission rule: a P2 retry waits for P0/P1.\n dispatch()\n return\n }\n retire(entry)\n if (fed === 0) releaseHold(entry)\n clearEntry(entry)\n console.warn(\n `[RepairFetch] fetch failed pid=${entry.packetId} sbn=${entry.sbn} track=${entry.repairTrack}:`,\n error,\n )\n dispatch()\n }\n\n // The profile the block key is in; a stream reaching repair was configured\n // from its catalog, so an absent profile is a wiring fault, not a default.\n // Any token other than `iso-ssbg1-v1` (the retired `k-padded-v1` included)\n // is one too: `parseFecBlockProfile` refuses it, whatever an untyped host\n // returns. Resolved when the request arrives (onRepairSubscribe below),\n // never inside execute: there its throw would read as an ordinary fetch\n // failure, warned once per block while the stream silently lost unicast\n // repair.\n const blockProfileOf = (packetId: number): FecBlockProfile => {\n const profile: unknown = mc.fecManager.blockProfileForPacket(packetId)\n if (profile === undefined) {\n throw new Error(`[RepairFetch] packetId=${packetId} has no configured fec.blockProfile`)\n }\n return parseFecBlockProfile(profile, `[RepairFetch] packetId=${packetId} fec.blockProfile`)\n }\n\n const execute = async (entry: RepairEntry, run: FetchRun): Promise<void> => {\n let fed = 0\n const common = {\n repairTrack: entry.repairTrack,\n blockProfile: entry.blockProfile,\n packetId: entry.packetId,\n signal: run.controller.signal,\n subscriberPriority: entry.subscriberPriority,\n }\n const { range } = entry\n const feed = (packet: Uint8Array): void => {\n if (entry.catalogTrackName === undefined) {\n mc.processRepairFromMoQ(packet, entry.packetId)\n } else {\n mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName)\n }\n }\n try {\n const packets = range === undefined\n ? opts.transport({ ...common, sbn: entry.sbn })\n : entry.walk !== undefined\n ? walkHole(entry, entry.walk, range, common)\n : opts.rangeTransport!({\n ...common,\n startGroup: range.groups!.startGroup,\n endGroup: range.groups!.endGroup,\n lostSsId: range.lostSsId,\n })\n for await (const packet of packets) {\n if (run.stopped !== null || entry.running !== run) break\n fed++\n if (range === undefined) feed(packet)\n else atReport(range, () => feed(packet))\n }\n finish(entry, run, fed, undefined)\n } catch (error) {\n finish(entry, run, fed, error ?? new Error('repair transport rejected'))\n }\n }\n\n /**\n * The \u00A77.7 range FETCH of a hole over a transport that FETCHes one Group.\n * A hole starts where a stated block ends, so ext(hole start) is a block's\n * Group; the repair of each Group states its block, and that block's end is\n * the next block's Group. Walks to the block holding the hole's highest\n * lost SS_ID (everything after it arrived) and stops early when a Group\n * names no block and none is stated there. A Group is done when it ends,\n * when it held its RSB_length repair symbols, or once the block it states\n * can use none of the rest (`groupServed`): a relay may keep the FETCH open\n * past its last object (BLO-52085 D2 80601), or hold only part of the\n * Group. Each Group is its own FETCH with its own signal, aborted once the\n * walk leaves it, so the transport cancels it on the wire, and never one\n * the block's own FETCH reads (fec-multicast-00 rule 1: `leaveWalkedGroup`\n * takes it over). Between two Groups the walk honours rule 3 (see\n * `holdsBack`): an audio walk that finds keyframe repair outstanding goes\n * back to the queue and resumes at `walk.next`; a video walk first\n * dispatches what came due, and asks again for a Group whose FETCH it\n * cancelled for audio or delta repair (`yieldVideoWalks`). Every packet is\n * fed before the walk reads the host's counts: the consumer feeds what it\n * yields before asking for more.\n */\n async function* walkHole(\n entry: RepairEntry,\n walk: NonNullable<RepairEntry['walk']>,\n hole: NonNullable<RepairEntry['range']>,\n common: Omit<RepairFetchRequest, 'sbn'>,\n ): AsyncGenerator<Uint8Array> {\n const lostAt = serial32Distance(entry.sbn, hole.lostSsId)\n for (let first = true; !common.signal.aborted; first = false) {\n if (!first && entry.priority !== 0 && outstandingBelow(1)) {\n stop(entry, 'preempted')\n note('repair-preempted', entry)\n return\n }\n if (!first && entry.priority === 0) {\n dispatch()\n if (common.signal.aborted) return\n }\n const sbn = walk.next\n let next: number | undefined\n if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {\n const rsIds = new Set<number>()\n const group = new AbortController()\n const cancel = (): void => group.abort(common.signal.reason)\n common.signal.addEventListener('abort', cancel, { once: true })\n walk.group = { sbn, controller: group }\n try {\n for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {\n yield packet\n const id = extractRepairFecPayloadId(packet)\n if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue\n next ??= serial32Add(sbn, id.ssbLength)\n rsIds.add(id.rsId)\n // Aborted before the loop lets go of the transport, whose own\n // cleanup may stop listening for the abort.\n if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {\n group.abort()\n break\n }\n }\n } catch (error) {\n // The Group was taken over or yielded: the walk goes on.\n if (!group.signal.aborted || common.signal.aborted) throw error\n } finally {\n common.signal.removeEventListener('abort', cancel)\n walk.group = null\n }\n if (walk.yielded) {\n walk.yielded = false\n continue\n }\n }\n next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName)\n if (next === undefined) return\n // Past the highest lost SS_ID, which lies in the hole: done.\n if (serial32Distance(entry.sbn, next) > lostAt) return\n walk.next = next\n }\n }\n\n const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {\n for (const entry of [...entries.values()]) {\n if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue\n retire(entry)\n stop(entry, 'reset')\n if (entry.range) clearEntry(entry)\n }\n // A reset is when the packetId -> repair-track mapping can change, so\n // re-arm the once-per-track warn for the new epoch.\n warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName))\n dispatch()\n })\n\n const removeLifecycleObserver = mc.addRepairLifecycleObserver((event) => {\n if (disposed) return\n if (event.type === 'reclassified') {\n const entry = entries.get(\n requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? undefined),\n )\n if (!entry || entry.priority !== 2) return\n const promoted = repairPriorityForClass(event.to)\n if (promoted >= entry.priority) return\n const wire = wirePriority(entry, event.to)\n // A block leaves P2 only for P0, whose request is never declined.\n if (wire === null) return\n entry.priority = promoted\n entry.subscriberPriority = wire.subscriberPriority\n // A block that turned out to carry a keyframe gets the keyframe budget\n // its request would have had (never a shorter deadline than it had).\n const promotedDeadline = presentationDeadlineAt(\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n performance.now(),\n event.to,\n )\n if (promotedDeadline !== null && promotedDeadline.deadlineAt > entry.deadlineAt) {\n entry.deadlineAt = promotedDeadline.deadlineAt\n entry.playoutDeadlineAt = Math.max(\n entry.playoutDeadlineAt,\n promotedDeadline.deadlineAt - promotedDeadline.extensionMs,\n )\n entry.anchorAt = promotedDeadline.anchorAt\n entry.delayMs = promotedDeadline.delayMs\n entry.bound = promotedDeadline.bound\n noteBudget(entry, promotedDeadline.extensionMs)\n }\n if (entry.running) {\n // The running FETCH carries the delta priority. Cancel it and send\n // the block's repair again under its new class (\u00A711.4.5): a keyframe\n // repair must not stay queued behind source media.\n stop(entry, 'reprioritized')\n start(entry, false)\n }\n dispatch()\n return\n }\n if (event.type === 'gap') {\n // mmt-02 5.3.3: a receiver cancels a repair it stops waiting for. A\n // frame the release gate forces out at its hold ceiling (a\n // discontinuity stall over blocks that never resolved) declares the\n // loss behind it, so every FETCH of that stream past its deadline is\n // cancelled here, inside the decision, before the frame leaves the\n // gate (MulticastManager emits the decision as a lifecycle event\n // synchronously from the gate's `decide`).\n if (event.action !== 'stall' || event.reason !== 'discontinuity') return\n const now = performance.now()\n let expired = false\n for (const entry of [...entries.values()]) {\n if (entry.packetId !== event.stream.packetId) continue\n if (entry.catalogTrackName !== (event.stream.catalogTrackName ?? undefined)) continue\n if (!entry.running || entry.deadlineAt > now) continue\n stop(entry, 'expired')\n retire(entry)\n clearEntry(entry)\n expired = true\n }\n if (expired) dispatch()\n return\n }\n if (event.type !== 'recovered' && event.type !== 'failed') return\n const entry = entries.get(\n requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? undefined),\n )\n if (!entry) return\n retire(entry)\n if (entry.running) stop(entry, 'resolved')\n else if (entry.priority === 2 && entry.attempts === 0) note('repair-deferred', entry)\n dispatch()\n })\n\n /**\n * The block's presentation deadline, or null when the player gives none.\n *\n * anchor + presentationDelay, clamped below by the multicast wait (the block\n * is open that long whatever happens, so a FETCH landing inside it still\n * counts) and above by anchor + the release gate's hold ceiling (a successor\n * frame may not wait behind a block longer than that). A block no symbol\n * reached has no anchor; its deadline is the multicast wait. The ceiling is\n * measured from the earlier of the anchor and the earliest frame the gate\n * holds for the stream (see the module note). A block that may hold a RAP\n * (`keyframeBudgetEligible`) uses the larger of the presentation delay and\n * the keyframe budget; `extensionMs` is how much later that made it.\n */\n const presentationDeadlineAt = (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n now: number,\n blockClass: BlockClass,\n ): ResolvedDeadline | null => {\n // Undefined: the packetId is no longer configured (released), so it has\n // no repair budget.\n const waitMs = mc.fecManager.repairFetchTimeoutMsForBlock(sbn, packetId, catalogTrackName)\n if (waitMs === undefined) return null\n const waitDeadlineAt = now + waitMs\n const anchor = mc.fecManager.blockAnchorAtMs(sbn, packetId, catalogTrackName)\n if (anchor === undefined) {\n return { deadlineAt: waitDeadlineAt, extensionMs: 0, anchorAt: null, delayMs: null, bound: 'wait' }\n }\n let delayMs: number\n try {\n delayMs = opts.presentationDelayMs(packetId, catalogTrackName)\n } catch {\n return null\n }\n if (!(Number.isFinite(delayMs) && delayMs > 0)) return null\n const retentionMs = mc.fecManager.terminalRetentionMsForPacket(packetId)\n if (retentionMs === undefined) return null\n const ceilingAt = Math.min(anchor, earliestGatedFrameAt(packetId, catalogTrackName) ?? anchor) + retentionMs\n const at = (\n delay: number,\n delayBound: 'presentation' | 'keyframe',\n ): { readonly deadlineAt: number; readonly bound: RepairDeadlineBound } => {\n const presentAt = Math.min(anchor + delay, ceilingAt)\n if (waitDeadlineAt >= presentAt) return { deadlineAt: waitDeadlineAt, bound: 'wait' }\n return { deadlineAt: presentAt, bound: anchor + delay <= ceilingAt ? delayBound : 'retention' }\n }\n const base = at(delayMs, 'presentation')\n const budgetMs =\n keyframeBudgetEligible(blockClass, classifierMode(packetId, catalogTrackName)) &&\n groupCanComplete(sbn, packetId, catalogTrackName)\n ? readKeyframeBudget(packetId, catalogTrackName)\n : null\n if (budgetMs === null || budgetMs <= delayMs) return { ...base, extensionMs: 0, anchorAt: anchor, delayMs }\n const extended = at(budgetMs, 'keyframe')\n return {\n ...extended,\n extensionMs: extended.deadlineAt - base.deadlineAt,\n anchorAt: anchor,\n delayMs: budgetMs,\n }\n }\n\n const earliestGatedFrameAt = (packetId: number, catalogTrackName: string | undefined): number | undefined => {\n try {\n const at = mc.earliestGatedFrameAtMs?.(packetId, catalogTrackName)\n return at !== undefined && Number.isFinite(at) ? at : undefined\n } catch {\n return undefined\n }\n }\n\n const classifierMode = (packetId: number, catalogTrackName: string | undefined): ClassifierMode | undefined => {\n try {\n return mc.fecManager.classifierModeFor?.(packetId, catalogTrackName).mode\n } catch {\n return undefined\n }\n }\n\n const noteBudget = (entry: Pick<RepairEntry, 'sbn' | 'packetId' | 'catalogTrackName'>, extensionMs: number): void => {\n if (extensionMs > 0) mc.noteKeyframeBudgetGranted?.(extensionMs, entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n mc.onRepairSubscribe((sbn, packetId, catalogTrackName, blockClass) => {\n if (disposed) {\n clearRepair(sbn, packetId, catalogTrackName)\n return\n }\n // Throws on a wiring fault, here and synchronously, before anything is\n // queued (see blockProfileOf).\n const blockProfile = blockProfileOf(packetId)\n\n // Fire-time resolution \u2014 see ResolveRepairTarget.\n const target = opts.resolveTarget(packetId, catalogTrackName)\n if (!target) {\n // A starved block with no repair target can only resolve via the fail\n // bound. Say so, once per track: a null target is also the documented\n // answer for a rung that carries no repair, and the typed lifecycle\n // events already enumerate every block.\n const warnKey = noTargetKey(packetId, catalogTrackName)\n if (!warnedNoTarget.has(warnKey)) {\n warnedNoTarget.add(warnKey)\n console.warn(\n `[RepairFetch] no repair target for pid=${packetId} sbn=${sbn}` +\n `${catalogTrackName === undefined ? '' : ` track=${catalogTrackName}`}; releasing without a fetch`,\n )\n }\n clearRepair(sbn, packetId, catalogTrackName)\n return\n }\n\n const key = requestKey(sbn, packetId, catalogTrackName)\n const previous = entries.get(key)\n if (previous) {\n retire(previous)\n stop(previous, 'reset')\n }\n const identity = {\n target,\n sbn,\n packetId,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n }\n const wire = wirePriority(identity, blockClass)\n if (wire === null) {\n // No conformant FETCH exists for this block (see RepairFetchPriority).\n clearRepair(sbn, packetId, catalogTrackName)\n return\n }\n const now = performance.now()\n const priority = repairPriorityForClass(blockClass)\n const deadline = presentationDeadlineAt(sbn, packetId, catalogTrackName, now, blockClass)\n if (deadline === null) {\n clearRepair(sbn, packetId, catalogTrackName)\n mc.noteRepairSkipped(\n 'presentation-delay-unavailable',\n { rttMs: readRtt(), budgetMs: 0, priority },\n sbn,\n packetId,\n catalogTrackName,\n )\n return\n }\n const entry: RepairEntry = {\n key,\n ...identity,\n repairTrack: target.repairTrack,\n blockProfile,\n priority,\n subscriberPriority: wire.subscriberPriority,\n deadlineAt: deadline.deadlineAt,\n playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,\n anchorAt: deadline.anchorAt,\n delayMs: deadline.delayMs,\n bound: deadline.bound,\n order: enqueueOrder++,\n attempts: 0,\n running: null,\n }\n entries.set(key, entry)\n noteBudget(entry, deadline.extensionMs)\n dispatch()\n })\n\n /**\n * \u00A77.5 range for a lost SS_ID: from ext(S_prev) when a stated block ends\n * where the hole starts, else from the epoch reference r. Null when there\n * is no r, or the lost SS_ID cannot be extended from it.\n */\n const rangeFor = (loss: UndelimitedIsoLoss, repairTrack: string): RepairFetchRange | null => {\n let reference: bigint | undefined\n try {\n reference = opts.repairEpochReference!(repairTrack)\n } catch {\n return null\n }\n if (reference === undefined) return null\n try {\n const anchor = loss.previousBlockStart === undefined\n ? { reference }\n : { previousBlockStart: extendSsId(reference, loss.previousBlockStart) }\n return repairFetchRange(loss.lostSsId, loss.kMax, anchor)\n } catch (error) {\n if (error instanceof RangeError) return null\n throw error\n }\n }\n\n const trackKind = (packetId: number): TrackKind | undefined => {\n try {\n return mc.fecManager.trackKindFor?.(packetId)\n } catch {\n return undefined\n }\n }\n\n /**\n * Where a walk of a hole reported `now` ends: WALK_LEAD_MS before the span\n * it leaves asks for its repair (D-28 from the report, as the span a host\n * without holes opened then did), so that span's request is armed before\n * it is due and goes out at the same time; never later than `deadlineAt`.\n */\n const walkDeadlineAt = (packetId: number, now: number, deadlineAt: number): number => {\n let repairDeadlineMs: number | undefined\n try {\n repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId)\n } catch {\n repairDeadlineMs = undefined\n }\n if (repairDeadlineMs === undefined || !Number.isFinite(repairDeadlineMs)) return deadlineAt\n return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS)\n }\n\n /**\n * The stream ran past the locator's horizon behind a hole: no repair can\n * state its blocks any more. A walking hole's walk ends and the hole closes\n * as at its deadline, so the span it leaves fails, and is reported, as the\n * span opened at its report would have (BLO-52085); the host discards any\n * other. Called from inside the stream's packet handling, so the walk ends\n * once that returns, as for a RAP (below).\n */\n const onHoleExpired = (hole: ExpiredIsoHole): boolean => {\n if (disposed) return false\n const entry = [...entries.values()].find((candidate) =>\n candidate.walk !== undefined &&\n candidate.packetId === hole.packetId &&\n candidate.catalogTrackName === hole.catalogTrackName &&\n serial32Distance(candidate.sbn, hole.holeStart) < candidate.range!.holeLength)\n if (entry === undefined) return false\n queueMicrotask(() => {\n if (entries.get(entry.key) !== entry) return\n retire(entry)\n stop(entry, 'expired')\n clearEntry(entry)\n dispatch()\n })\n return true\n }\n\n // A host that can keep a hole gets range repair: the \u00A77.7 range over\n // `rangeTransport`, or else a walk of the hole's Groups over `transport`.\n if (mc.onUndelimitedLoss !== undefined && mc.closeIsoHoles !== undefined) {\n mc.onUndelimitedLoss((loss) => {\n const { packetId, catalogTrackName, holeStart, holeLength } = loss\n const close = (): void => mc.closeIsoHoles!(packetId, catalogTrackName, holeStart, holeLength)\n if (disposed) return close()\n const blockProfile = blockProfileOf(packetId)\n const target = opts.resolveTarget(packetId, catalogTrackName)\n if (!target) return close()\n // The run's class (fec-multicast-00 Block Classification, Audio\n // Blocks): walked, a hole on an audio track is audio repair, one Group\n // per FETCH; any other is of unknown class, so keyframe repair.\n const walked = opts.rangeTransport === undefined\n const holeClass: BlockClass = walked && trackKind(packetId) === 'audio' ? 'audio' : 'unknown'\n const priority = repairPriorityForClass(holeClass)\n const groups = walked ? null : rangeFor(loss, target.repairTrack)\n if (!walked && groups === null) {\n close()\n mc.noteRepairSkipped('range-no-anchor', { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName)\n return\n }\n const identity = {\n target,\n sbn: holeStart,\n packetId,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n }\n // `unknown` is P0, whose request is never declined (omitted at worst);\n // an audio FETCH the catalog gives no priority for is not sent.\n const wire = wirePriority(identity, holeClass)\n if (wire === null) return close()\n // The hole is no tracked block: no anchor, so this is the multicast\n // wait (`bound: 'wait'`), by intent. A hole holds the release gate, so it\n // must not wait out a presentation delay on top.\n const now = performance.now()\n const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass)\n if (deadline === null) {\n close()\n mc.noteRepairSkipped(\n 'presentation-delay-unavailable',\n { rttMs: readRtt(), budgetMs: 0, priority },\n holeStart,\n packetId,\n catalogTrackName,\n )\n return\n }\n const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt\n const entry: RepairEntry = {\n key: JSON.stringify(['range', packetId, catalogTrackName ?? null, holeStart]),\n ...identity,\n repairTrack: target.repairTrack,\n blockProfile,\n priority,\n subscriberPriority: wire.subscriberPriority,\n deadlineAt,\n playoutDeadlineAt: deadlineAt - deadline.extensionMs,\n anchorAt: deadline.anchorAt,\n delayMs: deadline.delayMs,\n bound: deadline.bound,\n order: enqueueOrder++,\n attempts: 0,\n running: null,\n range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },\n ...(walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}),\n }\n const previous = entries.get(entry.key)\n if (previous) {\n retire(previous)\n stop(previous, 'reset')\n }\n entries.set(entry.key, entry)\n entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1)\n dispatch()\n }, onHoleExpired)\n }\n\n // A RAP arrived complete: a keyframe FETCH below it is moot (\u00A711.4.2). The\n // observer runs inside the frame push, so the cancel waits for a microtask\n // rather than re-entering the FEC layer through the hold release.\n const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {\n queueMicrotask(() => {\n if (disposed) return\n for (const entry of [...entries.values()]) {\n if (entry.packetId !== packetId || !entry.running || !moot(entry)) continue\n stop(entry, 'moot')\n retire(entry)\n releaseHold(entry)\n clearEntry(entry)\n }\n dispatch()\n })\n })\n\n // fec-multicast-00 \u00A76.6: once the overlay recovered a block's RAP (its FT=0\n // and FT=1 held), the rest of the block is concealed as a non-keyframe\n // block, so its keyframe FETCH is stopped whatever its deadline. Deferred\n // as the RAP observer is: this fires from inside the recovered-block route.\n const removeOverlayObserver = mc.addKeyframeOverlayRecoveredObserver?.((packetId, catalogTrackName, sbn) => {\n queueMicrotask(() => {\n if (disposed) return\n for (const entry of [...entries.values()]) {\n if (entry.range || entry.priority !== 0 || entry.packetId !== packetId || entry.sbn !== sbn) continue\n if (catalogTrackName !== undefined && entry.catalogTrackName !== catalogTrackName) continue\n stop(entry, 'overlay-recovered')\n retire(entry)\n releaseHold(entry)\n clearEntry(entry)\n }\n dispatch()\n })\n })\n\n return () => {\n disposed = true\n mc.setUnicastRepair?.(false)\n removeResetObserver()\n removeLifecycleObserver()\n removeRapObserver?.()\n removeOverlayObserver?.()\n for (const entry of [...entries.values()]) {\n clearEntry(entry)\n if (entry.running) releaseHold(entry)\n stop(entry, 'disposed')\n if (entry.expiry !== undefined) clearTimeout(entry.expiry)\n }\n entries.clear()\n }\n}\n", "/**\n * Keyframe-protected FEC repair policy.\n *\n * Every FEC block still gets in-band FEC decode. What this module decides is\n * (1) which blocks may hold a keyframe (RAP), so a block short of K at its\n * repair deadline can be repaired over QUIC with the right priority, and\n * (2) what a sink must do with the first frame released after a gap: stall\n * until the next RAP, or conceal and keep playing.\n *\n * The two decisions are deliberately independent. Classification only sets\n * repair priority. The stall/conceal decision is made again per released gap\n * from the media that is actually missing, so a wrong classification can only\n * lower a block's repair priority; it can never make playback wrong.\n *\n * Everything here is derived from catalog-authored timing and in-band MMTP\n * evidence. There are no timers, no cadence heuristics, and no defaults: a\n * track whose geometry cannot be derived exactly runs in the defined\n * fail-closed mode `all-protected`, where every block is treated as possibly\n * keyframe-bearing.\n *\n * All three players (moqtail, hang, Shaka) consume this one implementation.\n */\n\nimport { deriveFecInterleaveDepth } from '@blockcast/mmt-fec'\n\n// \u2500\u2500\u2500 Classes and priorities \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 * Repair class of one FEC block.\n *\n * - `keyframe`: the block holds (or held) a RAP / MPU start.\n * - `delta`: the block provably holds only non-RAP video frames.\n * - `unknown`: neither could be proven; treated exactly like `keyframe`.\n * - `audio`: an audio block.\n */\nexport type BlockClass = 'keyframe' | 'delta' | 'unknown' | 'audio'\n\n/** Repair priority. Lower is more urgent. */\nexport type RepairPriority = 0 | 1 | 2\n\nexport type TrackKind = 'video' | 'audio'\n\n/** P0 = keyframe/unknown (stall-preventing), P1 = audio, P2 = delta. */\nexport function repairPriorityForClass(blockClass: BlockClass): RepairPriority {\n switch (blockClass) {\n case 'keyframe':\n case 'unknown':\n return 0\n case 'audio':\n return 1\n case 'delta':\n return 2\n }\n}\n\n// \u2500\u2500\u2500 Geometry \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\nexport type ClassifierMode = 'classifying' | 'all-protected'\n\n/** Why a track runs `all-protected`. */\nexport type ClassifierReason =\n // Geometry (catalog) reasons.\n | 'framerate-absent'\n | 'keyframe-cadence-absent'\n | 'keyframe-interval-not-integral'\n | 'block-spans-gop'\n /**\n * The catalog keyframe interval is not an exact integer number of ticks\n * in the media track's own timescale (ISO-BMFF `mdhd`), so released RAP\n * spacing cannot be verified and hold-last cannot predict the next RAP.\n * Nothing is wrong with the stream; the cadence is simply unprovable.\n */\n | 'keyframe-interval-not-media-integral'\n /**\n * Another stream on this packetId was configured with its own geometry\n * and this one was not, so no geometry provably belongs to it (ABR rungs\n * sharing a packetId).\n */\n | 'stream-geometry-absent'\n // In-band invariant violations (positive evidence only).\n | 'rap-not-mpu-start'\n | 'mpu-longer-than-gop'\n | 'block-not-contiguous'\n /**\n * MPU-start RAPs are not exactly one keyframe interval apart per MPU:\n * released RAPs in the media timescale, or, once each frame is its own\n * movie fragment, RAP fragments G fragments apart per MPU (P3).\n */\n | 'rap-spacing-mismatch'\n /**\n * An MPU of several movie fragments whose fragments hold several samples:\n * neither sample_number nor the fragment number states a frame's MPU\n * position (P3).\n */\n | 'mpu-multiple-fragments'\n | 'block-wider-than-interleave'\n\n/** Raw catalog timing for one track. Never a resolved cadence. */\nexport interface BlockClassifierGeometryInput {\n readonly trackKind: TrackKind\n /** Catalog `framerate` (frames per second). */\n readonly framerate?: number\n /** Catalog `fec.interleaveDepthMs`: the full FEC block span (\u00A75.1). */\n readonly interleaveDepthMs: number\n /** Catalog track `timescale` for `keyframeIntervalTicks`. */\n readonly timescale?: number\n /** Catalog `keyframeIntervalTicks` (preferred when the timescale is present). */\n readonly keyframeIntervalTicks?: number\n /** Catalog `keyframeIntervalMs`. */\n readonly keyframeIntervalMs?: number\n}\n\n/** Exact keyframe interval as a rational number of seconds: ticks / timescale. */\nexport interface KeyframeInterval {\n readonly ticks: number\n readonly timescale: number\n}\n\nexport type BlockClassifierGeometry =\n | { readonly trackKind: 'audio' }\n | {\n readonly trackKind: 'video'\n readonly mode: 'classifying'\n /** F: one frame's duration in milliseconds (1000 / framerate). */\n readonly frameDurationMs: number\n /** D: media units per FEC block (deriveFecInterleaveDepth). */\n readonly interleaveUnits: number\n /** G: frames per GOP. */\n readonly gopFrames: number\n readonly keyframeInterval: KeyframeInterval\n }\n | {\n readonly trackKind: 'video'\n readonly mode: 'all-protected'\n readonly reason: ClassifierReason\n /** The catalog interval when one is stated: gap decisions use it (keyframeInstantBetween). */\n readonly keyframeInterval?: KeyframeInterval\n }\n\n/**\n * Integer value of `numerator / denominator` when it is one, else null.\n *\n * Catalog framerates are JSON numbers, so an NTSC rate arrives as the double\n * nearest 30000/1001. One multiply and one divide each add at most half an\n * ulp of relative error (IEEE-754), so a quotient within two ulps of an\n * integer IS that integer; anything further is genuinely non-integral.\n */\nfunction exactInteger(numerator: number, denominator: number): number | null {\n if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator === 0) {\n return null\n }\n const quotient = numerator / denominator\n const rounded = Math.round(quotient)\n if (rounded < 1) return null\n const representationError = 2 * Number.EPSILON * Math.abs(quotient)\n return Math.abs(quotient - rounded) <= representationError ? rounded : null\n}\n\nfunction isPositiveFinite(value: number | undefined): value is number {\n return value !== undefined && Number.isFinite(value) && value > 0\n}\n\n/**\n * Derive the per-track classifier geometry from raw catalog fields.\n *\n * `all-protected` is the policy's defined fail-closed state, not a default:\n * it is returned with the exact reason. The only throw is for a value the\n * catalog validator already rejects (a non-positive block span).\n */\nexport function deriveBlockClassifierGeometry(\n input: BlockClassifierGeometryInput,\n): BlockClassifierGeometry {\n if (!isPositiveFinite(input.interleaveDepthMs)) {\n throw new Error(\n `[BlockPolicy] interleaveDepthMs=${input.interleaveDepthMs} is not a positive block span; ` +\n 'the catalog validator rejects this',\n )\n }\n if (input.trackKind === 'audio') return { trackKind: 'audio' }\n\n // Every video geometry keeps the catalog interval: gap decisions need it in\n // either mode (fec-multicast-00 Block Classification item 3).\n let keyframeInterval: KeyframeInterval | undefined\n if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {\n keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale }\n } else if (isPositiveFinite(input.keyframeIntervalMs)) {\n keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1000 }\n }\n const protect = (reason: ClassifierReason): BlockClassifierGeometry => ({\n trackKind: 'video',\n mode: 'all-protected',\n reason,\n ...(keyframeInterval === undefined ? {} : { keyframeInterval }),\n })\n\n if (!isPositiveFinite(input.framerate)) return protect('framerate-absent')\n const framerate = input.framerate\n if (keyframeInterval === undefined) return protect('keyframe-cadence-absent')\n\n const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale)\n if (gopFrames === null) return protect('keyframe-interval-not-integral')\n\n const frameDurationMs = 1000 / framerate\n const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs)\n if (interleaveUnits >= gopFrames) return protect('block-spans-gop')\n\n return {\n trackKind: 'video',\n mode: 'classifying',\n frameDurationMs,\n interleaveUnits,\n gopFrames,\n keyframeInterval,\n }\n}\n\n/**\n * The keyframe interval expressed in a media track's timescale, or null when\n * the geometry states none or the interval is not an exact integer number of\n * media ticks (fec-multicast-00 Block Classification item 3: an inexact one\n * gives no usable interval).\n */\nexport function keyframeIntervalMediaTicks(\n geometry: BlockClassifierGeometry,\n mediaTimescale: number,\n): bigint | null {\n if (geometry.trackKind !== 'video' || geometry.keyframeInterval === undefined) return null\n if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null\n const { ticks, timescale } = geometry.keyframeInterval\n if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null\n const scaled = BigInt(ticks) * BigInt(mediaTimescale)\n const divisor = BigInt(timescale)\n if (scaled % divisor !== 0n) return null\n return scaled / divisor\n}\n\n/**\n * fec-multicast-00 Block Classification item 3 for two released frames:\n * whether `(from, to]` holds `start + k * interval` for some k >= 1, `start`\n * the decode time of an MPU's first RAP, all in one media timescale. `from`\n * is exclusive: the frame at `from` is held and complete, so an instant there\n * is that frame itself (an on-cadence RAP), not a lost one. The draft's closed\n * interval is for bounding packets, which may be part of a RAP.\n */\nexport function keyframeInstantBetween(start: bigint, interval: bigint, from: bigint, to: bigint): boolean {\n const k = from >= start ? (from - start) / interval + 1n : 1n\n return start + k * interval <= to\n}\n\n// \u2500\u2500\u2500 Evidence \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 * In-band evidence from ONE first-arrival source symbol received from the\n * network. Recovered symbols and repair symbols never contribute, and the\n * MFU `priority > 0x80` hint is not evidence.\n */\nexport interface SourceSymbolEvidence {\n /** The MMTP header R (RAP) bit. */\n readonly rap: boolean\n /** MPU_sequence_number, when parsed from this packet. */\n readonly mpu?: number\n /**\n * 0-based sample position within its movie fragment: the MFU DU-header\n * `sample_number` minus one (ISO/IEC 23008-1 numbers samples from 1, and\n * the parser rejects `sample_number` 0). Present only when this packet\n * carried a DU header. It is the MPU position only while the MPU is one\n * movie fragment; BlockClassifier derives MPU positions (P3).\n */\n readonly idx?: number\n /**\n * movie_fragment_sequence_number from the DU header, when present. When\n * each frame is its own fragment, it positions the frame from its MPU's\n * RAP fragment (P3).\n */\n readonly movieFragment?: number\n /**\n * DU-header `offset`: the data unit's authored byte position within its\n * sample (0 for a whole-sample data unit, the partition boundary for a\n * subsample data unit). Present only with `idx`; absent reads as 0.\n */\n readonly offset?: number\n /**\n * The MMTP header packet_sequence_number (contiguous per packet_id). Not\n * classification evidence: FECManager uses it to bound how many blocks the\n * producer can have started between two source symbols, so an outage is\n * never mistaken for a source restart.\n */\n readonly packetSequenceNumber?: number\n}\n\nexport type ReclassificationEvidence = 'rap' | 'mpu-span' | 'window' | 'classifier-disabled'\n\nexport type ClassifierChange =\n | {\n readonly kind: 'reclassified'\n readonly sbn: number\n readonly from: BlockClass\n readonly to: BlockClass\n readonly evidence: ReclassificationEvidence\n }\n | {\n readonly kind: 'mode'\n readonly mode: 'all-protected'\n readonly reason: ClassifierReason\n }\n\ninterface BlockEvidence {\n rapSeen: boolean\n mpus: Set<number>\n /** The lowest and highest MPU positions its DU headers proved (P3). */\n positionMin?: number\n positionMax?: number\n cls: BlockClass\n}\n\n/** A data-unit start (a packet carrying a DU header) and the block it is in. */\ninterface DataUnitStart {\n readonly movieFragment: number\n readonly idx: number\n readonly offset: number\n readonly sbn: number\n}\n\n/**\n * Authored order of two data-unit starts of one MPU. Fragment numbers wrap\n * at 2^32, so they compare in RFC 1982 serial order.\n */\nfunction compareDataUnitStarts(\n a: Omit<DataUnitStart, 'sbn'>,\n b: Omit<DataUnitStart, 'sbn'>,\n): number {\n return ((a.movieFragment - b.movieFragment) | 0) || a.idx - b.idx || a.offset - b.offset\n}\n\n/**\n * How many MPUs behind the newest released RAP a stale release can be. The\n * release gate holds a frame for seconds at most, so a late copy is a few\n * MPUs back; anything further is another MPU sequence. With MPUs so short\n * that a late copy lies further back, it re-anchors there: the newest MPU's\n * gaps read rap-unknown until the next MPU's RAP, never a wrong measure.\n */\nconst LATE_RAP_MAX_MPUS_BACK = 64\n\n/** One MPU's movie fragments (P3). */\ninterface MpuLayout {\n /** Serial-earliest movie_fragment_sequence_number of its DU headers. */\n low: number\n /** The fragment of its first RAP-flagged DU header: position 0. */\n anchor?: number\n}\n\n/** What one DU header proves about its MPU (BlockClassifier `#place`). */\ninterface Placement {\n /** Its 0-based MPU position, when the wire proves it. */\n readonly position?: number\n /**\n * It shows a RAP inside an MPU, or an MPU longer than G: MPU boundaries\n * no longer bound the stream's RAPs (`rap-not-mpu-start`).\n */\n readonly rapNotMpuStart: boolean\n /** A refuted layout premise. */\n readonly violation?: ClassifierReason\n}\n\nconst UNPLACED: Placement = { rapNotMpuStart: false }\n\n/**\n * Per-stream block classifier.\n *\n * Classes only move toward more protection or narrower evidence:\n * `unknown\u2192delta` and `unknown\u2192keyframe` / `delta\u2192keyframe` on evidence, and\n * `delta\u2192unknown` when an invariant disables classification. `keyframe` is\n * terminal.\n *\n * The delta window rule rests on three premises, each guarded by an\n * invariant that fires on positive evidence only:\n *\n * - P1: the source packets of one block are one contiguous run of the\n * stream's authored order, and blocks follow each other in SBN order\n * (`block-not-contiguous`). The producer assigns SS_IDs in authored order\n * and a block is the SS_ID range [SBN*K, SBN*K + K), so this holds for a\n * block that closes at K symbols in the middle of a frame: that frame's\n * fragments then land in two ADJACENT blocks, which is still one run each.\n * A frame split across adjacent blocks is not a violation.\n * - P2: that run touches at most D media units, counting a frame continued\n * from the previous block (`block-wider-than-interleave`). The producer\n * counts a media-unit boundary only once the open block holds a symbol.\n * - P3: an MPU starts with its only RAP and holds at most G frames\n * (`rap-not-mpu-start`, `mpu-longer-than-gop`, `rap-spacing-mismatch`),\n * and its DU headers state each frame's MPU position in one of two layouts\n * (`mpu-multiple-fragments` when an MPU shows two fragments and a DU\n * header states sample_number above 1, which is neither):\n * - one movie fragment per MPU (ATSC 3.0): the position is\n * sample_number \u2212 1. This is the rule until some MPU of the sequence\n * shows two fragments.\n * - one fragment per frame, numbered one per frame (FFmpeg's MoQ MMT\n * muxer, every DU header stating sample_number 1): the position is the\n * fragment's distance from the fragment of the MPU's first RAP-flagged\n * DU header (its anchor). The RAP's own fragment is position 0. Each\n * anchor must lie exactly G fragments per MPU from the anchor received\n * before it, which is kept past the horizon, and from the anchor\n * received last (`rap-spacing-mismatch`, as after a dropped frame).\n * Once two anchors kept that spacing, fragment numbers count frames:\n * later fragments get positions, and an anchor arriving past the\n * spacing is a RAP inside its MPU or follows an MPU longer than G\n * (`rap-not-mpu-start`). An MPU whose anchor was not received has no\n * positions; its blocks stay unknown. A second RAP-flagged fragment, or\n * a DU header in a fragment before the anchor, refutes the MPU start\n * (`rap-not-mpu-start`).\n *\n * P1 and P2 are what make a block's frames contiguous and lie within\n * [positionMax \u2212 D + 1, positionMin + D \u2212 1] of its MPU. What refutes P1 is\n * a pair of source packets whose wire-stated authored order and SBN order\n * disagree: a later MPU in an earlier block, a later data unit of one MPU\n * (by movie_fragment_sequence_number, sample_number, then DU offset) in an\n * earlier block, or one data unit in two blocks. That is the signature of a\n * round-robin interleave, which scatters one run over several concurrent\n * blocks. Non-adjacency alone is not: a sample larger than K packets\n * legitimately spans blocks SBN..SBN+n.\n */\nexport class BlockClassifier {\n #geometry: BlockClassifierGeometry\n #mode: ClassifierMode\n #reason: ClassifierReason | null\n /**\n * False once the stream showed that an MPU boundary does not bound its\n * RAPs (a RAP inside an MPU, or an MPU longer than a GOP). Recorded in\n * every mode: the stall/conceal decision relies on it even when the\n * catalog geometry already runs the classifier `all-protected`.\n */\n #mpuBoundsRaps = true\n #blocks = new Map<number, BlockEvidence>()\n /**\n * P1 ledger, kept for the MPUs within the classification horizon (the\n * highest MPU seen and the one before it): the SBN span of every source\n * packet of each MPU, and each MPU's data-unit starts in authored order.\n * Valid only within one continuous SBN sequence; a source discontinuity\n * clears it (`noteSourceDiscontinuity`).\n */\n #mpuSbnSpans = new Map<number, { min: number; max: number }>()\n #dataUnitStarts = new Map<number, DataUnitStart[]>()\n #highestMpu: number | null = null\n /**\n * P3 layout, kept for the MPUs within the classification horizon and valid\n * within one continuous SBN sequence (`noteSourceDiscontinuity`).\n */\n #mpus = new Map<number, MpuLayout>()\n /** An MPU of this sequence showed two movie fragments: each frame is one. */\n #fragmentPerFrame = false\n /** A DU header of this sequence stated sample_number above 1. */\n #multiSampleFragment = false\n /**\n * The anchor received last, whether or not its MPU is still in the\n * horizon. Each new anchor, and the anchor of every DU header's MPU, is\n * checked against it.\n */\n #lastAnchor: { mpu: number; fragment: number } | null = null\n /** Two anchors were exactly G fragments per MPU apart. */\n #fragmentsProven = false\n /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */\n #lastRap: { mpu: number; presentationTime: bigint; mediaTimescale: number; decodeTime?: bigint } | null = null\n\n constructor(geometry: BlockClassifierGeometry) {\n this.#geometry = geometry\n this.#mode = 'classifying'\n this.#reason = null\n this.reset(geometry)\n }\n\n get geometry(): BlockClassifierGeometry {\n return this.#geometry\n }\n\n get mode(): ClassifierMode {\n return this.#mode\n }\n\n get reason(): ClassifierReason | null {\n return this.#reason\n }\n\n /**\n * Whether \"same MPU on both sides of a gap\" still proves the gap held no\n * RAP. It stops holding for the rest of the epoch once a RAP was received\n * inside an MPU or an MPU ran longer than a GOP.\n */\n get mpuBoundsRaps(): boolean {\n return this.#mpuBoundsRaps\n }\n\n /** Begin a fresh epoch (catalog change or track reset). */\n reset(geometry: BlockClassifierGeometry = this.#geometry): void {\n this.#geometry = geometry\n this.#blocks.clear()\n this.#clearContiguityLedger()\n this.#clearMpuLayout()\n this.#lastRap = null\n this.#mpuBoundsRaps = true\n if (geometry.trackKind === 'video' && geometry.mode === 'all-protected') {\n this.#mode = 'all-protected'\n this.#reason = geometry.reason\n } else {\n this.#mode = 'classifying'\n this.#reason = null\n }\n }\n\n /**\n * Retire this classifier (its stream moves to a new catalog epoch). Every\n * block it had classified `delta` loses the evidence behind that class and\n * reads `unknown` from now on; the returned changes say so.\n */\n retire(): ClassifierChange[] {\n const changes: ClassifierChange[] = []\n for (const [sbn, block] of this.#blocks) {\n if (block.cls !== 'delta') continue\n block.cls = 'unknown'\n changes.push({\n kind: 'reclassified',\n sbn,\n from: 'delta',\n to: 'unknown',\n evidence: 'classifier-disabled',\n })\n }\n return changes\n }\n\n /**\n * The stream's SBN sequence restarted (FECManager source discontinuity:\n * a publisher restart, or the SS_ID space wrapped). Authored order and SBN\n * order are comparable only within one continuous sequence, and a\n * restarted publisher numbers MPUs and movie fragments again, so the P1\n * ledger and the P3 layout start again.\n */\n noteSourceDiscontinuity(): void {\n this.#clearContiguityLedger()\n this.#clearMpuLayout()\n // A restarted publisher numbers MPUs again: its first RAP is no second\n // RAP of the MPU the old sequence last released one in.\n this.#lastRap = null\n }\n\n /** Register a block that exists without evidence (a vanished block). */\n touch(sbn: number): void {\n this.#blockFor(sbn)\n }\n\n /** Forget a resolved block. */\n forget(sbn: number): void {\n this.#blocks.delete(sbn)\n }\n\n classOf(sbn: number): BlockClass {\n if (this.#geometry.trackKind === 'audio') return 'audio'\n return this.#blocks.get(sbn)?.cls ?? 'unknown'\n }\n\n /** Record one first-arrival source symbol's evidence for block `sbn`. */\n observe(sbn: number, evidence: SourceSymbolEvidence): ClassifierChange[] {\n if (this.#geometry.trackKind === 'audio') return []\n const changes: ClassifierChange[] = []\n const block = this.#blockFor(sbn)\n const placement = this.#place(evidence)\n\n if (evidence.rap) block.rapSeen = true\n if (evidence.mpu !== undefined) block.mpus.add(evidence.mpu)\n const { position } = placement\n if (position !== undefined) {\n block.positionMin =\n block.positionMin === undefined ? position : Math.min(block.positionMin, position)\n block.positionMax =\n block.positionMax === undefined ? position : Math.max(block.positionMax, position)\n }\n\n // A RAP inside an MPU refutes \"an MPU boundary bounds RAPs\" whatever the\n // classifier mode, because gap decisions rely on it in every mode.\n if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false\n\n const violation = this.#checkInvariants(sbn, block, evidence, placement)\n if (violation !== null) changes.push(...this.#disable(violation))\n\n const next = this.#classify(block)\n if (next !== block.cls && this.#allowed(block.cls, next)) {\n changes.push({\n kind: 'reclassified',\n sbn,\n from: block.cls,\n to: next,\n evidence: this.#evidenceFor(block, next),\n })\n block.cls = next\n }\n return changes\n }\n\n /**\n * Record a RAP frame released in order. Released MPU-start RAPs of MPUs m\n * and m+n must be exactly n keyframe intervals apart in the media\n * timescale, compared as integers.\n *\n * Comparing only consecutive MPUs would miss exactly the case the window\n * rule cannot survive: a short MPU whose successor's RAP was lost (that\n * RAP-bearing block is the one a wrong G calls delta), because the next\n * released RAP then belongs to m+2. Every MPU is one interval long, so the\n * span to any later released RAP proves or refutes all MPUs in between.\n *\n * In every mode it keeps each MPU's first released RAP, with its decode\n * time, as the start keyframeFreeBetween measures the catalog interval\n * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`\n * when it lies off the catalog lattice (not a whole number of intervals\n * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to\n * it): with no repair, released RAPs are the only evidence of where they\n * lie. Without a usable interval, or a decode time on either, any second\n * RAP with another presentation time refutes.\n */\n noteReleasedRap(\n mpu: number,\n presentationTime: bigint,\n mediaTimescale: number,\n decodeTime?: bigint,\n ): ClassifierChange[] {\n if (this.#geometry.trackKind === 'audio') return []\n const previous = this.#lastRap\n // A further RAP inside an already-anchored MPU is not an MPU start; the\n // MPU keeps its first RAP as the spacing anchor (rap-not-mpu-start owns\n // mid-MPU RAPs). The same RAP released again is no further one.\n if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {\n if (presentationTime === previous.presentationTime) return []\n const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale)\n if (\n interval === null ||\n decodeTime === undefined ||\n previous.decodeTime === undefined ||\n (decodeTime - previous.decodeTime) % interval !== 0n\n ) {\n this.#mpuBoundsRaps = false\n }\n return []\n }\n // A late copy of an earlier MPU's RAP (the gate reports stale releases\n // too) moves no anchor back: the newest MPU's gaps are measured from its\n // own. MPU sequence numbers wrap at 2^32, so \"earlier\" is serial; it is\n // bounded, and a late copy is older in presentation time than the anchor.\n // Any other RAP behind the anchor is a restarted MPU sequence nothing\n // signalled, which re-anchors, or no same-MPU gap could ever be measured\n // again. A restart inside the bound whose presentation time went back\n // too still reads as late, and fails closed: its same-MPU gaps stay\n // rap-unknown until its MPU numbers pass the old newest, and unless it\n // repeats the old timeline the spacing checks then end the epoch\n // all-protected.\n if (previous !== null && previous.mediaTimescale === mediaTimescale) {\n const back = (previous.mpu - mpu) >>> 0\n if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return []\n }\n this.#lastRap = { mpu, presentationTime, mediaTimescale, ...(decodeTime === undefined ? {} : { decodeTime }) }\n if (this.#mode === 'all-protected') return []\n // Verification compares integers in the media timescale. When the\n // catalog interval is not an exact tick count there, spacing is\n // unprovable: fail closed, naming the cause, rather than blaming the\n // encoder with rap-spacing-mismatch on a perfectly spaced RAP.\n const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale)\n if (interval === null) return this.#disable('keyframe-interval-not-media-integral')\n if (\n previous === null ||\n mpu < previous.mpu ||\n previous.mediaTimescale !== mediaTimescale\n ) {\n return []\n }\n if (\n presentationTime - previous.presentationTime === interval * BigInt(mpu - previous.mpu)\n ) {\n return []\n }\n return this.#disable('rap-spacing-mismatch')\n }\n\n /**\n * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`\n * of the frames on either side, holds no keyframe: MPU boundaries still\n * bound RAPs, the catalog states an interval exact in this timescale, and\n * none of its instants after the MPU's first released RAP lies in\n * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything\n * unknown counts as a keyframe.\n */\n keyframeFreeBetween(mpu: number, from: bigint, to: bigint, mediaTimescale: number): boolean {\n const rap = this.#lastRap\n if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === undefined) {\n return false\n }\n const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale)\n return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to)\n }\n\n #blockFor(sbn: number): BlockEvidence {\n let block = this.#blocks.get(sbn)\n if (!block) {\n block = { rapSeen: false, mpus: new Set(), cls: 'unknown' }\n this.#blocks.set(sbn, block)\n }\n return block\n }\n\n #checkInvariants(\n sbn: number,\n block: BlockEvidence,\n evidence: SourceSymbolEvidence,\n placement: Placement,\n ): ClassifierReason | null {\n if (this.#mode === 'all-protected' || this.#geometry.trackKind !== 'video') return null\n const geometry = this.#geometry\n if (geometry.mode !== 'classifying') return null\n if (placement.rapNotMpuStart) return 'rap-not-mpu-start'\n if (placement.position !== undefined && placement.position >= geometry.gopFrames) {\n return 'mpu-longer-than-gop'\n }\n // A block closes at the latest after D media units, so the DU headers it\n // carries from one MPU lie within D consecutive positions. A wider span\n // means the producer closes blocks some other way (at K symbols, or\n // round-robin across concurrent blocks) and the window rule is void.\n if (\n block.mpus.size === 1 &&\n block.positionMin !== undefined &&\n block.positionMax !== undefined &&\n block.positionMax - block.positionMin >= geometry.interleaveUnits\n ) {\n return 'block-wider-than-interleave'\n }\n if (placement.violation !== undefined) return placement.violation\n if (evidence.mpu !== undefined && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {\n return 'block-not-contiguous'\n }\n return null\n }\n\n /**\n * The MPU position a source symbol's DU header proves (P3), and what it\n * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.\n */\n #place(evidence: SourceSymbolEvidence): Placement {\n const { mpu, idx, movieFragment: fragment } = evidence\n if (idx === undefined) return UNPLACED\n const bySample: Placement = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 }\n // Every wire DU header states both; evidence without them keeps the\n // one-fragment rule unless the sequence is fragment-per-frame.\n if (mpu === undefined || fragment === undefined) {\n return this.#fragmentPerFrame && !this.#multiSampleFragment\n ? { rapNotMpuStart: bySample.rapNotMpuStart }\n : bySample\n }\n let layout = this.#mpus.get(mpu)\n if (layout === undefined) {\n layout = { low: fragment }\n this.#mpus.set(mpu, layout)\n // One entry per MPU still inside the classification horizon.\n for (const other of this.#mpus.keys()) {\n if (other + 1 < mpu) this.#mpus.delete(other)\n }\n } else if (fragment !== layout.low) {\n this.#fragmentPerFrame = true\n if (((fragment - layout.low) | 0) < 0) layout.low = fragment\n }\n if (idx !== 0) this.#multiSampleFragment = true\n let arrival: number | undefined\n if (evidence.rap && layout.anchor === undefined) {\n layout.anchor = fragment\n arrival = this.#anchorDrift(mpu, fragment)\n // Proof takes two MPUs: an MPU's RAP header seen again proves nothing.\n if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true\n this.#lastAnchor = { mpu, fragment }\n }\n // Until an MPU shows two fragments, sample_number \u2212 1 is the position.\n // Once one has, a sample_number above 1 leaves neither layout.\n if (!this.#fragmentPerFrame) return bySample\n if (this.#multiSampleFragment) return { ...bySample, violation: 'mpu-multiple-fragments' }\n const { anchor } = layout\n if (anchor === undefined) return UNPLACED\n // A new anchor against the anchor received before it; any other DU\n // header's anchor against the anchor received last, so an anchor that\n // arrived before the layout was known is held to the spacing too.\n const drift = arrival ?? this.#anchorDrift(mpu, anchor)\n // RFC 1982 distance from the anchor: positive for a later fragment.\n const offset = (fragment - anchor) | 0\n return {\n ...(offset === 0 || (offset > 0 && this.#fragmentsProven) ? { position: offset } : {}),\n rapNotMpuStart:\n (evidence.rap && offset !== 0) ||\n ((layout.low - anchor) | 0) < 0 ||\n // Fragments count frames: an anchor arriving past the spacing is a\n // RAP inside its MPU, or an earlier MPU outran G.\n (arrival !== undefined && arrival > 0 && this.#fragmentsProven),\n ...(drift === undefined || drift === 0 ? {} : { violation: 'rap-spacing-mismatch' }),\n }\n }\n\n /**\n * How many fragments MPU m's anchor `fragment` lies past the start that\n * the anchor received last predicts for MPU m: one frame per fragment and\n * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')\n * fragments apart, modulo 2^32. Undefined without a last anchor, a\n * cadence, or this layout.\n */\n #anchorDrift(mpu: number, fragment: number): number | undefined {\n const geometry = this.#geometry\n const last = this.#lastAnchor\n if (\n last === null ||\n !this.#fragmentPerFrame ||\n this.#multiSampleFragment ||\n geometry.trackKind !== 'video' ||\n geometry.mode !== 'classifying'\n ) {\n return undefined\n }\n return (fragment - last.fragment - geometry.gopFrames * (mpu - last.mpu)) | 0\n }\n\n #clearMpuLayout(): void {\n this.#mpus.clear()\n this.#fragmentPerFrame = false\n this.#multiSampleFragment = false\n this.#lastAnchor = null\n this.#fragmentsProven = false\n }\n\n #clearContiguityLedger(): void {\n this.#mpuSbnSpans.clear()\n this.#dataUnitStarts.clear()\n this.#highestMpu = null\n }\n\n /**\n * P1 check for one source packet of MPU `mpu` in block `sbn`, then record\n * it. True when some recorded packet's authored order and SBN order\n * disagree with this one's (see the class comment). Only positions the\n * wire states are compared: MPU order for every packet, and data-unit\n * order for packets that carry a DU header. A packet of one data unit\n * that continues into the next block carries no DU header and so only\n * takes part through its MPU, which is exactly what makes an adjacent\n * straddle consistent.\n */\n #contradictsAuthoredOrder(sbn: number, mpu: number, evidence: SourceSymbolEvidence): boolean {\n // Every packet of MPU m precedes every packet of MPU m' > m.\n for (const [other, span] of this.#mpuSbnSpans) {\n if (other < mpu && span.max > sbn) return true\n if (other > mpu && span.min < sbn) return true\n }\n const inHorizon = this.#highestMpu === null || mpu + 1 >= this.#highestMpu\n let insertAt = -1\n let starts: DataUnitStart[] | undefined\n let start: DataUnitStart | undefined\n if (evidence.idx !== undefined) {\n start = {\n movieFragment: evidence.movieFragment ?? 0,\n idx: evidence.idx,\n offset: evidence.offset ?? 0,\n sbn,\n }\n starts = this.#dataUnitStarts.get(mpu)\n if (starts !== undefined) {\n let lo = 0\n let hi = starts.length\n while (lo < hi) {\n const mid = (lo + hi) >>> 1\n if (compareDataUnitStarts(starts[mid]!, start) < 0) lo = mid + 1\n else hi = mid\n }\n const at = starts[lo]\n if (at !== undefined && compareDataUnitStarts(at, start) === 0) {\n // One data unit has one first packet: seen in another block, the\n // SBN-to-authored-order map is not a function.\n if (at.sbn !== sbn) return true\n } else {\n const before = starts[lo - 1]\n if (before !== undefined && before.sbn > sbn) return true\n if (at !== undefined && at.sbn < sbn) return true\n insertAt = lo\n }\n }\n }\n if (!inHorizon) return false\n const span = this.#mpuSbnSpans.get(mpu)\n if (span === undefined) this.#mpuSbnSpans.set(mpu, { min: sbn, max: sbn })\n else {\n if (sbn < span.min) span.min = sbn\n if (sbn > span.max) span.max = sbn\n }\n if (start !== undefined) {\n if (starts === undefined) this.#dataUnitStarts.set(mpu, [start])\n else if (insertAt >= 0) starts.splice(insertAt, 0, start)\n }\n if (this.#highestMpu === null || mpu > this.#highestMpu) {\n this.#highestMpu = mpu\n for (const other of [...this.#mpuSbnSpans.keys()]) {\n if (other + 1 < mpu) {\n this.#mpuSbnSpans.delete(other)\n this.#dataUnitStarts.delete(other)\n }\n }\n }\n return false\n }\n\n #disable(reason: ClassifierReason): ClassifierChange[] {\n if (reason === 'rap-not-mpu-start' || reason === 'mpu-longer-than-gop') {\n this.#mpuBoundsRaps = false\n }\n if (this.#mode === 'all-protected') return []\n this.#mode = 'all-protected'\n this.#reason = reason\n const changes: ClassifierChange[] = [{ kind: 'mode', mode: 'all-protected', reason }]\n for (const [sbn, block] of this.#blocks) {\n if (block.cls !== 'delta') continue\n block.cls = 'unknown'\n changes.push({\n kind: 'reclassified',\n sbn,\n from: 'delta',\n to: 'unknown',\n evidence: 'classifier-disabled',\n })\n }\n return changes\n }\n\n #classify(block: BlockEvidence): BlockClass {\n if (block.rapSeen || block.mpus.size >= 2) return 'keyframe'\n if (this.#mode === 'all-protected') return 'unknown'\n const geometry = this.#geometry\n if (geometry.trackKind !== 'video' || geometry.mode !== 'classifying') return 'unknown'\n if (\n block.mpus.size === 1 &&\n block.positionMin !== undefined &&\n block.positionMax !== undefined\n ) {\n // A block closes every D media units, so its frames are contiguous and\n // lie in [positionMax \u2212 D + 1, positionMin + D \u2212 1] of MPU m. Position\n // 0 is the only RAP of an MPU and G bounds its length.\n const span = geometry.interleaveUnits - 1\n if (\n block.positionMax - span >= 1 &&\n block.positionMin + span <= geometry.gopFrames - 1\n ) {\n return 'delta'\n }\n }\n return 'unknown'\n }\n\n #allowed(from: BlockClass, to: BlockClass): boolean {\n if (from === 'keyframe') return false\n if (from === 'unknown') return to === 'delta' || to === 'keyframe'\n if (from === 'delta') return to === 'keyframe'\n return false\n }\n\n #evidenceFor(block: BlockEvidence, to: BlockClass): ReclassificationEvidence {\n if (to === 'delta') return 'window'\n return block.rapSeen ? 'rap' : 'mpu-span'\n }\n}\n\n// \u2500\u2500\u2500 Stall vs conceal \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\nexport interface GapStreamIdentity {\n readonly packetId: number\n /** Non-empty catalog identity, or null when the producer has no track name. */\n readonly catalogTrackName: string | null\n}\n\n/** What the sink knows about one side of a released gap. */\nexport interface GapFrameEvidence {\n /**\n * Codec-aware RAP check: `MmtpContainerParser.isKeyframe(data, rapFlag,\n * codec)`, bitstream-only for recovered frames. Never the priority hint.\n */\n readonly rap: boolean\n /**\n * MPU_sequence_number of the frame. Omit it once the stream showed that\n * an MPU boundary does not bound its RAPs (`BlockClassifier.mpuBoundsRaps`):\n * same-MPU then no longer proves a gap lost only deltas.\n */\n readonly mpu?: number\n /**\n * 0-based sample position within its movie fragment (sample_number \u2212 1).\n * State it on both sides only when both frames are in one movie fragment:\n * decideGap reads `after.idx \u2212 before.idx \u2212 1` as the samples missed\n * between them.\n */\n readonly idx?: number\n /** Authored presentation time in `timescale` ticks. */\n readonly pts?: bigint\n /** Authored sample duration in `timescale` ticks. */\n readonly durationTicks?: number\n /** The media timescale of `pts` and `durationTicks`. */\n readonly timescale?: number\n}\n\nexport type FrameGapAction = 'stall' | 'conceal'\n\nexport type FrameGapReason =\n | 'rap-lost'\n | 'rap-unknown'\n | 'discontinuity'\n | 'delta-lost'\n | 'rap-next'\n | 'audio-gap'\n | 'audio-discontinuity'\n\n/**\n * The decision attached to the first frame released after a gap\n * (`RoutedFrameMeta.gapBefore`). It is the same frozen object the manager\n * emits as its `gap` repair lifecycle event, so a sink that acts on the frame\n * and an observer that counts events see one fact.\n */\nexport interface FrameGapDecision {\n readonly version: 2\n readonly type: 'gap'\n readonly stream: GapStreamIdentity\n readonly trackKind: TrackKind\n readonly action: FrameGapAction\n readonly reason: FrameGapReason\n /** FEC blocks in the gap whose media was lost (failed or vanished). */\n readonly blocks: readonly number[]\n /** Missing video frames or audio access units, when exactly known. */\n readonly missingFrames: number | null\n /** Authored duration of the missing media in milliseconds, when known. */\n readonly missingMs: number | null\n /** Manager epoch of the stream when the decision was made. */\n readonly epoch: number\n}\n\nexport interface DecideGapInput {\n readonly stream: GapStreamIdentity\n readonly trackKind: TrackKind\n /** Last frame released before the gap. */\n readonly before: GapFrameEvidence\n /** First frame released after the gap. */\n readonly after: GapFrameEvidence\n /** The stream restarted (FEC SBN went backwards or the publisher reset). */\n readonly discontinuity: boolean\n readonly blocks: readonly number[]\n /**\n * The most media units the gap can hold: the FEC blocks spanned from the\n * frame before to the frame after, times D (media units per block,\n * ceil(interleaveDepthMs / unit duration), \u00A75.1). A block touches at most D\n * units whether it closes at D or at K symbols. Null when the span or D is\n * unknown. An audio PTS delta that implies more AUs than this is a clock\n * jump, not loss, and re-anchors instead of concealing every slot.\n */\n readonly maxMissingUnits: number | null\n readonly epoch: number\n}\n\nfunction durationMs(units: number, before: GapFrameEvidence): number | null {\n if (\n before.durationTicks === undefined ||\n before.timescale === undefined ||\n before.timescale <= 0\n ) {\n return null\n }\n return (units * before.durationTicks * 1000) / before.timescale\n}\n\n/**\n * Pure stall/conceal decision for the first frame released after a gap.\n *\n * Video stalls only when a RAP may be inside the gap: the frame after it is\n * not a RAP and either sits in another MPU (`rap-lost`) or the MPU cannot be\n * proven on both sides (`rap-unknown`), or the stream restarted\n * (`discontinuity`). A gap inside one MPU lost only deltas (`delta-lost`) and\n * a RAP after the gap resynchronises by itself (`rap-next`). Audio never\n * stalls: an exact gap is concealed per access unit (`audio-gap`), anything\n * else re-anchors at the next frame (`audio-discontinuity`).\n */\nexport function decideGap(input: DecideGapInput): FrameGapDecision {\n const { before, after } = input\n let action: FrameGapAction\n let reason: FrameGapReason\n let missingFrames: number | null = null\n\n if (input.trackKind === 'audio') {\n action = 'conceal'\n reason = 'audio-discontinuity'\n if (\n !input.discontinuity &&\n before.pts !== undefined &&\n after.pts !== undefined &&\n before.durationTicks !== undefined &&\n Number.isSafeInteger(before.durationTicks) &&\n before.durationTicks > 0\n ) {\n const auDuration = BigInt(before.durationTicks)\n const missingTicks = after.pts - before.pts - auDuration\n const bound = input.maxMissingUnits\n if (\n missingTicks > 0n &&\n missingTicks % auDuration === 0n &&\n bound !== null &&\n missingTicks / auDuration <= BigInt(bound)\n ) {\n reason = 'audio-gap'\n missingFrames = Number(missingTicks / auDuration)\n }\n }\n } else if (input.discontinuity) {\n action = 'stall'\n reason = 'discontinuity'\n } else if (after.rap) {\n action = 'conceal'\n reason = 'rap-next'\n } else if (before.mpu === undefined || after.mpu === undefined) {\n action = 'stall'\n reason = 'rap-unknown'\n } else if (before.mpu !== after.mpu) {\n action = 'stall'\n reason = 'rap-lost'\n } else {\n action = 'conceal'\n reason = 'delta-lost'\n if (before.idx !== undefined && after.idx !== undefined) {\n const missing = after.idx - before.idx - 1\n missingFrames = missing > 0 ? missing : null\n }\n }\n\n return Object.freeze({\n version: 2 as const,\n type: 'gap' as const,\n stream: Object.freeze({\n packetId: input.stream.packetId,\n catalogTrackName: input.stream.catalogTrackName,\n }),\n trackKind: input.trackKind,\n action,\n reason,\n blocks: Object.freeze([...input.blocks]),\n missingFrames,\n missingMs: missingFrames === null ? null : durationMs(missingFrames, before),\n epoch: input.epoch,\n })\n}\n", "// Resolved repair layer and overlay shapes (draft-ramadan-moq-fec-catalog-00,\n// fec-core-00): the output of `resolveRepairLayers`. Every base layer comes\n// from one instance's partition and differs only in P_i; layer i owns RS_IDs\n// [O_i, O_i + P_i) with O_i = sum(P_j, j < i), and ESI = K + RS_ID. A keyframe\n// overlay is a second instance with its own K, P and RS_ID space.\n//\n// Binding (which repair tracks belong to which instance) is\n// `resolveFecBindings` in mmt-base; nothing here reads a catalog.\n\n/** Lowest MoQT-scale priority a repair track may declare. */\nexport const REPAIR_PRIORITY_MIN = 192;\n/** Highest MoQT-scale priority a repair track may declare. */\nexport const REPAIR_PRIORITY_MAX = 255;\n/** Priority of a base layer 0 track that declares none. */\nexport const DEFAULT_REPAIR_PRIORITY = 240;\n/** RFC 6330 \u00A74.4.1.2: the largest number of source symbols in one RaptorQ source block. */\nexport const MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;\n/** The 24-bit RS_ID field (\u00A77.1) bounds the repair total of one FEC instance. */\nexport const MAX_REPAIR_SYMBOLS = 0xffffff;\n/** The 24-bit ESI bounds K + totalP - 1 for one FEC instance. */\nexport const MAX_ENCODING_SYMBOL_ID = 0xffffff;\n/** Reed-Solomon block bound: K + P <= 255 (draft-ramadan-moq-fec-01 4.5, 6.3.4 rule 12). */\nexport const MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;\n\n/** A resolved base repair layer with its derived RS_ID range. */\nexport type RepairLayerParams = {\n\t/** Layer index; 0 is the track named by the source's `fec.repairTrack`. */\n\tlayer: number;\n\trepairTrackName: string;\n\t/** P_i: repair symbols per block carried by this layer. */\n\trepairSymbols: number;\n\t/** O_i = sum(P_j for j < i): the first RS_ID this layer carries. ESI = K + RS_ID. */\n\trsIdOffset: number;\n\t/** MoQT-scale priority (lower first); 240 when layer 0 declares none. */\n\tpriority: number;\n};\n\n/** A resolved keyframe overlay: a separate FEC instance over RAP fragments only. */\nexport type RepairOverlayParams = {\n\trepairTrackName: string;\n\tscope: \"keyframe\";\n\t/** K_overlay: source symbols of the overlay instance. */\n\tsourceSymbols: number;\n\t/** P_overlay: repair symbols per overlay block; also the overlay's own RSB_length. */\n\trepairSymbols: number;\n\t/** MoQT-scale priority, independent of the base layer chain. */\n\tpriority: number;\n};\n\nexport type RepairLayersResolution = {\n\tsourceTrackName: string;\n\t/** Base layers in layer order, layer 0 first. Never empty. */\n\tbaseLayers: readonly RepairLayerParams[];\n\t/** Keyframe overlay instances, in catalog order. Empty when none is declared. */\n\t/** At most one entry: the wire carries one overlay trailer per RAP packet. */\n\toverlays: readonly RepairOverlayParams[];\n\t/** Sum of P over base layers: the wire RSB_length on every base layer packet. */\n\ttotalBaseRepairSymbols: number;\n};\n\n"],
5
- "mappings": ";AAqEO,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAI/B,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B,kBAAkB;AAM7C,IAAM,qBAAqB;AAyB5B,SAAU,gBAAgB,QAAkB;AAChD,MAAI,OAAO,SAAS,kBAAkB;AACpC,UAAM,IAAI,MAAM,0BAA0B,OAAO,MAAM,QAAQ;EACjE;AAEA,QAAM,OAAO,IAAI,SAAS,OAAO,QAAQ,OAAO,YAAY,OAAO,UAAU;AAE7E,QAAM,UAAW,OAAO,CAAC,KAAM,IAAK;AACpC,MAAI,YAAY,GAAG;AACjB,UAAM,IAAI,MAAM,6BAA6B,OAAO,EAAE;EACxD;AAGA,QAAM,UAAW,OAAO,CAAC,KAAM,IAAK;AACpC,QAAM,qBAAqB,OAAO,CAAC,IAAK,QAAU;AAClD,QAAM,iBAAiB,OAAO,CAAC,IAAK,OAAU;AAG9C,QAAM,WAAW,OAAO,CAAC,IAAK,OAAU;AAIxC,QAAM,aAAa,OAAO,CAAC,IAAK;AAEhC,MAAI,SAAS;AAGb,QAAM,WAAW,KAAK,UAAU,QAAQ,KAAK;AAC7C,YAAU;AAGV,QAAM,YAAY,OAAO,KAAK,UAAU,QAAQ,KAAK,CAAC;AACtD,YAAU;AAGV,QAAM,iBAAiB,KAAK,UAAU,QAAQ,KAAK;AACnD,YAAU;AAEV,MAAI;AACJ,MAAI,mBAAmB;AACrB,QAAI,SAAS,IAAI,OAAO;AAAQ,YAAM,IAAI,MAAM,yCAAyC;AACzF,oBAAgB,KAAK,UAAU,QAAQ,KAAK;AAC5C,cAAU;EACZ;AAEA,MAAI;AACJ,MAAI,eAAe;AACjB,Q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B;AACpB,4BAAwB;AACxB,eAAW,SAAS,CAAC,GAAG,QAAQ,OAAO,CAAC,GAAG;AACzC,iBAAW,KAAK;AAChB,UAAI,MAAM,QAAS,aAAY,KAAK;AACpC,WAAK,OAAO,UAAU;AACtB,UAAI,MAAM,WAAW,OAAW,cAAa,MAAM,MAAM;AAAA,IAC3D;AACA,YAAQ,MAAM;AAAA,EAChB;AACF;",
4
+ "sourcesContent": ["/**\n * @mmt/container - MMTP Parser\n *\n * MMTP (MMT Protocol) packet parser based on ISO/IEC 23008-1:2023 Section 9.2\n *\n * MMTP header format (12 bytes):\n * - Byte 0: V(2) | C(1) | FEC_type(2) | r(1) | X(1) | R(1)\n * - Byte 1: reserved(2) | packet_type(6)\n * - Bytes 2-3: packet_id (big-endian)\n * - Bytes 4-7: timestamp (big-endian, 32-bit)\n * - Bytes 8-11: sequence_number (big-endian)\n *\n * FEC_type values:\n * - 0: No FEC / source packet\n * - 1: FEC mode 0 (source with FEC payload ID)\n * - 2: FEC repair packet mode 0\n * - 3: FEC repair packet mode 1\n *\n * @packageDocumentation\n */\n\nexport interface MMTPHeader {\n version: number\n /** Packet type: 0x00=MPU, 0x02=Signaling, 0x03=Repair */\n packetType: number\n packetId: number\n timestamp: bigint\n sequenceNumber: number\n payloadLength: number\n fecType: number\n /** C flag: header carries a 32-bit packet_counter. */\n packetCounterFlag: boolean\n packetCounter?: number\n /** X flag: header carries an extension header and value. */\n extensionFlag: boolean\n extension?: { type: number; data: Uint8Array }\n /** Byte offset at which the MMTP payload begins. */\n headerLength: number\n /** Random Access Point flag - indicates keyframe (ISO 23008-1, byte 0 bit 0) */\n rapFlag: boolean\n}\n\nexport interface MPUHeader {\n mpuSequenceNumber: number\n fragmentationIndicator: number // FI: 0=complete, 1=first, 2=middle, 3=last\n /** 8-bit MPU fragment_counter from byte 3. */\n fragmentCounter: number\n /** T flag: 1=timed media (14-byte MFU DU header), 0=non-timed (4-byte header) */\n timedFlag: number\n /** A flag: aggregated MPU payload. This strict profile requires A=0. */\n aggregationFlag: boolean\n /** MPU payload_length (bytes 0-1): bytes after the length field, including\n * the remaining six MPU-header bytes and all data-unit bytes. */\n payloadLength: number\n}\n\nexport interface MFUDuHeader {\n movieFragmentSequenceNumber: number\n sampleNumber: number\n offset: number\n priority: number\n dependencyCounter: number\n}\n\nexport interface MMTPPacket {\n header: MMTPHeader\n payload: Uint8Array\n}\n\nexport const MMTP_HEADER_SIZE = 12\nexport const MPU_HEADER_SIZE = 8\nexport const MFU_DU_HEADER_SIZE_TIMED = 14 // T=1: timed media (video/audio samples)\nexport const MFU_DU_HEADER_SIZE_NONTIMED = 4 // T=0: non-timed media (item_id only)\n\nconst MPU_LENGTH_FIELD_SIZE = 2\nconst MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE\nexport const SOURCE_FEC_PAYLOAD_ID_SIZE = 4\n\n// MMTP Packet Types (ISO/IEC 23008-1:2023 Section 9.2.2)\nexport const PACKET_TYPE_MPU = 0x00\nexport const PACKET_TYPE_SIGNALING = 0x02\nexport const PACKET_TYPE_REPAIR = 0x03\n\n// AL-FEC Signaling Message ID (ISO/IEC 23008-1:2023 Amendment 1:2025)\nexport const ALFEC_MESSAGE_ID = 0x0203\n\n/**\n * MMTP `packet_id` of the signaling flow, which carries PACKET_TYPE_SIGNALING\n * packets such as the AL-FEC message (ALFEC_MESSAGE_ID). The FFmpeg `moq_mmt`\n * muxer sends that message on this packet_id into the same multicast group as\n * the media, and moqcast-draft (PR #44) makes advertising it for a track a\n * MUST NOT. A track's packet_id is therefore 1..MMTP_PACKET_ID_MAX.\n */\nexport const MMTP_SIGNALING_PACKET_ID = 0\n\n/** Largest value of the 16-bit MMTP `packet_id` header field. */\nexport const MMTP_PACKET_ID_MAX = 0xffff\n\n// fec_code_id_for_repair_flow code points (ISO/IEC 23008-10 Table 1;\n// draft-ramadan-moq-mmt-01 Section 8.3).\nexport const FEC_CODE_REED_SOLOMON = 1\nexport const FEC_CODE_RAPTORQ = 3\n\n/**\n * Parse MMTP header from buffer\n */\nexport function parseMMTPHeader(buffer: Uint8Array): MMTPHeader {\n if (buffer.length < MMTP_HEADER_SIZE) {\n throw new Error(`MMTP packet too small: ${buffer.length} bytes`)\n }\n\n const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n\n const version = (buffer[0]! >> 6) & 0x03\n if (version !== 0) {\n throw new Error(`Unsupported MMTP version: ${version}`)\n }\n\n // Extract FEC type from byte 0, bits 3-4\n const fecType = (buffer[0]! >> 3) & 0x03\n const packetCounterFlag = (buffer[0]! & 0x20) !== 0\n const extensionFlag = (buffer[0]! & 0x02) !== 0\n\n // Extract RAP flag from byte 0, bit 0 (R bit - Random Access Point)\n const rapFlag = (buffer[0]! & 0x01) === 1\n\n // ISO/IEC 23008-1:2023 Figure 8 (V=0) places reserved(2) before\n // packet_type(6), so packet_type occupies the low six bits of byte 1.\n const packetType = buffer[1]! & 0x3F\n\n let offset = 2\n\n // Packet ID (2 bytes, big-endian)\n const packetId = view.getUint16(offset, false)\n offset += 2\n\n // Timestamp (4 bytes, big-endian)\n const timestamp = BigInt(view.getUint32(offset, false))\n offset += 4\n\n // Sequence number (4 bytes, big-endian)\n const sequenceNumber = view.getUint32(offset, false)\n offset += 4\n\n let packetCounter: number | undefined\n if (packetCounterFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in packet_counter')\n packetCounter = view.getUint32(offset, false)\n offset += 4\n }\n\n let extension: { type: number; data: Uint8Array } | undefined\n if (extensionFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in header extension')\n const type = view.getUint16(offset, false)\n const length = view.getUint16(offset + 2, false)\n offset += 4\n if (offset + length > buffer.length) throw new Error('MMTP packet truncated in header extension value')\n extension = { type, data: buffer.subarray(offset, offset + length) }\n offset += length\n }\n\n return {\n version,\n packetType,\n packetId,\n timestamp,\n sequenceNumber,\n payloadLength: buffer.length - offset,\n fecType,\n packetCounterFlag,\n packetCounter,\n extensionFlag,\n extension,\n headerLength: offset,\n rapFlag,\n }\n}\n\n/**\n * The MMTP `packet_id` of `buffer`, or null exactly when parseMMTPHeader would\n * throw for it (short buffer, V != 0, truncated packet_counter or header\n * extension).\n *\n * This is the per-packet filter a receiver runs before any other work, so it\n * builds no header object, DataView or BigInt timestamp (BLO-36599). Use\n * parseMMTPHeader when any other header field is needed.\n */\nexport function readMMTPPacketId(buffer: Uint8Array): number | null {\n if (buffer.length < MMTP_HEADER_SIZE) return null\n const flags = buffer[0]!\n if (((flags >> 6) & 0x03) !== 0) return null\n let offset = MMTP_HEADER_SIZE\n if ((flags & 0x20) !== 0) {\n if (offset + 4 > buffer.length) return null\n offset += 4\n }\n if ((flags & 0x02) !== 0) {\n if (offset + 4 > buffer.length) return null\n const length = (buffer[offset + 2]! << 8) | buffer[offset + 3]!\n if (offset + 4 + length > buffer.length) return null\n }\n return (buffer[2]! << 8) | buffer[3]!\n}\n\n/**\n * Unwrap MMTP packet to extract payload\n */\nexport function unwrapMMTP(buffer: Uint8Array): MMTPPacket {\n const header = parseMMTPHeader(buffer)\n const payload = buffer.subarray(header.headerLength)\n\n return { header, payload }\n}\n\n/**\n * Parse MPU header from payload\n * ISO/IEC 23008-1:2023 Section 9.2.3.3\n *\n * MPU Header format (8 bytes) as written by FFmpeg/libmmt:\n * - Bytes 0-1: payload_length (16 bits, big-endian)\n * - Byte 2: FT(4) | T(1) | FI(2) | A(1)\n * - Byte 3: fragment_counter (8 bits)\n * - Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n */\nexport function parseMPUHeader(payload: Uint8Array): MPUHeader {\n if (payload.length < MPU_HEADER_SIZE) {\n throw new Error(`Payload too small for MPU header: ${payload.length} bytes`)\n }\n\n const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength)\n\n // Bytes 0-1: payload_length (16 bits, big-endian)\n const payloadLength = view.getUint16(0, false)\n\n // Byte 2: FT(4) | T(1) | FI(2) | A(1)\n const flagsByte = payload[2]!\n const timedFlag = (flagsByte >> 3) & 0x01\n const fragmentationIndicator = (flagsByte >> 1) & 0x03\n const aggregationFlag = (flagsByte & 0x01) !== 0\n\n // Byte 3: fragment_counter (8 bits). The high bit is part of the counter in\n // the current libmmt/FFmpeg writer ABI.\n const fragmentCounter = payload[3]!\n\n // Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n const mpuSequenceNumber = view.getUint32(4, false)\n\n return {\n mpuSequenceNumber,\n fragmentationIndicator,\n fragmentCounter,\n timedFlag,\n aggregationFlag,\n payloadLength,\n }\n}\n\nexport function parseTimedMfuDuHeader(payload: Uint8Array, offset: number): MFUDuHeader | null {\n if (offset < 0 || offset + MFU_DU_HEADER_SIZE_TIMED > payload.length) return null\n const view = new DataView(payload.buffer, payload.byteOffset + offset, MFU_DU_HEADER_SIZE_TIMED)\n return {\n movieFragmentSequenceNumber: view.getUint32(0, false),\n sampleNumber: view.getUint32(4, false),\n offset: view.getUint32(8, false),\n priority: payload[offset + 12]!,\n dependencyCounter: payload[offset + 13]!,\n }\n}\n\n/**\n * Why `extractMFUPayload` refused a packet.\n *\n * These identifiers are part of the public contract: callers surface them in\n * diagnostics, so renaming one is a breaking change.\n */\nexport type MFURejectionGate =\n | 'packet-shorter-than-mmtp-plus-mpu-header'\n | 'mmtp-header-unparseable'\n | 'not-an-mpu-packet'\n | 'payload-shorter-than-mpu-header'\n | 'aggregation-flag-set'\n | 'mpu-payload-length-below-header-remainder'\n | 'mpu-declared-end-exceeds-payload'\n | 'mfu-offset-at-or-past-declared-end'\n | 'source-fec-payload-id-width-mismatch'\n | 'declared-trailers-unresolved'\n\nexport interface MFURejection {\n gate: MFURejectionGate\n /** Human-readable detail, including the byte arithmetic that decided it. */\n detail: string\n}\n\ninterface MfuPayloadLayout {\n hasMfuDuHeader: boolean\n mfuOffset: number\n dataEnd: number\n}\n\nfunction resolveMfuPayloadLayout(\n mpu: MPUHeader,\n fragmentType: number,\n payload: Uint8Array,\n): { layout: MfuPayloadLayout } | { rejection: MFURejection } {\n if (mpu.payloadLength < MPU_HEADER_REMAINDER_SIZE) {\n return {\n rejection: {\n gate: 'mpu-payload-length-below-header-remainder',\n detail: `payload_length=${mpu.payloadLength} < ${MPU_HEADER_REMAINDER_SIZE}`,\n },\n }\n }\n\n // ISO/IEC 23008-1 defines payload_length from immediately after its own\n // two-byte field. It therefore includes the remaining six MPU-header bytes.\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + mpu.payloadLength\n if (declaredEnd > payload.length) {\n return {\n rejection: {\n gate: 'mpu-declared-end-exceeds-payload',\n detail:\n `payload_length=${mpu.payloadLength} implies end=${declaredEnd}, ` +\n `payload is ${payload.length} bytes`,\n },\n }\n }\n\n const hasHeader = fragmentType === 2 && mpu.fragmentationIndicator <= 1\n const mfuHeaderSize = mpu.timedFlag ? MFU_DU_HEADER_SIZE_TIMED : MFU_DU_HEADER_SIZE_NONTIMED\n const mfuOffset = MPU_HEADER_SIZE + (hasHeader ? mfuHeaderSize : 0)\n if (mfuOffset >= declaredEnd) {\n return {\n rejection: {\n gate: 'mfu-offset-at-or-past-declared-end',\n detail: `mfuOffset=${mfuOffset} >= declaredEnd=${declaredEnd}`,\n },\n }\n }\n\n return {\n layout: {\n hasMfuDuHeader: hasHeader,\n mfuOffset,\n dataEnd: declaredEnd,\n },\n }\n}\n\n// Legacy detached per-packet authenticator suffix `[0xf0a1][len][auth]`. Its\n// producer was removed (BLO-16483) and nothing verifies it any more; provenance\n// is the signed per-group manifest. Receivers still skip an exact suffix so a\n// stale producer degrades to unauthenticated playback instead of dropped\n// packets. ponytail: hard-cut to reject once no deployed producer can emit it.\nconst LEGACY_TRAILER_EXT_TYPE = 0xf0a1\nconst LEGACY_TRAILER_HEADER_SIZE = 4\n\nfunction isEmptyOrExactLegacyTrailer(payload: Uint8Array, start: number, end: number): boolean {\n if (start === end) return true\n if (start < 0 || end > payload.length || start + LEGACY_TRAILER_HEADER_SIZE > end) {\n return false\n }\n\n const view = new DataView(\n payload.buffer,\n payload.byteOffset + start,\n end - start,\n )\n if (view.getUint16(0, false) !== LEGACY_TRAILER_EXT_TYPE) return false\n\n const authLength = view.getUint16(2, false)\n return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end\n}\n\ninterface DeclaredTrailerLayout {\n hasFecId: boolean\n}\n\n/** Options for extractMFUPayload and explainMFURejection. */\nexport interface MFUExtractOptions {\n /**\n * When true, do NOT subtract the Source FEC Payload ID from the payload\n * boundary, even if fecType >= 1. For FEC-recovered symbols whose FEC PID\n * was already stripped before WASM decoding.\n */\n skipFecId?: boolean\n}\n\nfunction resolveDeclaredTrailers(\n payload: Uint8Array,\n declaredEnd: number,\n fecType: number,\n options?: MFUExtractOptions,\n): DeclaredTrailerLayout | null {\n if (declaredEnd > payload.length) return null\n\n if (options?.skipFecId) {\n return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)\n ? { hasFecId: false }\n : null\n }\n\n if (fecType === 1) {\n const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {\n return null\n }\n return { hasFecId: true }\n }\n if (fecType !== 0) return null\n\n if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {\n return { hasFecId: false }\n }\n\n return null\n}\n\n/**\n * Extract NAL unit payload from MMTP packet\n */\nexport function extractNALUnit(mmtpPacket: Uint8Array): Uint8Array {\n const extraction = extractMFUPayload(mmtpPacket)\n if (!extraction) throw new Error('Malformed MMTP MPU payload')\n return extraction.data\n}\n\n/** Result of extracting MFU payload from an MMTP packet */\nexport interface MFUExtraction {\n /** MMTP header fields */\n header: MMTPHeader\n /** MPU header fields */\n mpu: MPUHeader\n /** Fragment type (FT field, 4 bits): 0=metadata, 2=MFU data */\n fragmentType: number\n /** MFU payload data (video/audio bytes, headers stripped, FEC ID excluded) */\n data: Uint8Array\n /** Parsed timed MFU DU header when present, otherwise null */\n mfuDuHeader: MFUDuHeader | null\n /** Non-timed MFU Item_ID when the 4-byte DU header is present. */\n itemId: number | null\n /** Source FEC Payload ID if present (`FEC_type == 1`), or null */\n fecPayloadId: { ssId: number } | null\n}\n\n/**\n * Extract MFU payload from a raw MMTP packet.\n *\n * Handles all the byte arithmetic for:\n * - MMTP header (12 bytes)\n * - MPU sub-header (8 bytes, payloadLength field)\n * - MFU DU header (14 bytes timed / 4 bytes non-timed, only for FI \u2264 1)\n * - Source FEC Payload ID (4 bytes at end, only when `FEC_type == 1`)\n *\n * `payloadLength` is the ISO length-after-field value: six remaining MPU-header\n * bytes, then the MFU DU header when present, then media. The legacy\n * authenticator suffix and the Source FEC trailer are outside that declared span and must consume the exact suffix.\n *\n * @param mmtpPacket Raw MMTP packet (from multicast or MoQ)\n * @param options.skipFecId When true, do NOT subtract the 4-byte Source FEC Payload ID\n * from the payload boundary, even if fecType >= 1 in the MMTP header. Use this for\n * FEC-recovered symbols where the FEC PID was already stripped before WASM decoding\n * but the fecType bits in byte 0 still reflect the original packet (FEC Type=1 per\n * draft-ramadan-moq-mmt-01 \u00A73.1).\n * @returns Extracted MFU data + metadata, or null if packet is too small\n */\ninterface MfuPlan {\n header: MMTPHeader\n payload: Uint8Array\n mpu: MPUHeader\n fragmentType: number\n layout: MfuPayloadLayout\n trailerLayout: DeclaredTrailerLayout\n}\n\n/**\n * Single source of truth for whether a packet yields an MFU payload.\n *\n * `extractMFUPayload` and `explainMFURejection` both delegate here, so the\n * reason reported to operators can never drift from the decision the parser\n * actually made.\n */\nfunction planMfuExtraction(\n mmtpPacket: Uint8Array,\n options?: MFUExtractOptions,\n parsedHeader?: MMTPHeader,\n): { plan: MfuPlan } | { rejection: MFURejection } {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'packet-shorter-than-mmtp-plus-mpu-header',\n detail: `${mmtpPacket.length} bytes < ${MMTP_HEADER_SIZE + MPU_HEADER_SIZE}`,\n },\n }\n }\n\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch (error) {\n return {\n rejection: {\n gate: 'mmtp-header-unparseable',\n detail: error instanceof Error ? error.message : String(error),\n },\n }\n }\n }\n if (header.packetType !== PACKET_TYPE_MPU) {\n return {\n rejection: {\n gate: 'not-an-mpu-packet',\n detail: `packetType=0x${header.packetType.toString(16).padStart(2, '0')}`,\n },\n }\n }\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'payload-shorter-than-mpu-header',\n detail: `${payload.length} bytes < ${MPU_HEADER_SIZE}`,\n },\n }\n }\n\n const mpu = parseMPUHeader(payload)\n if (mpu.aggregationFlag) {\n return {\n rejection: { gate: 'aggregation-flag-set', detail: 'strict profile requires A=0' },\n }\n }\n\n // Fragment type from byte 2 upper nibble (not returned by parseMPUHeader)\n const fragmentType = (payload[2]! >> 4) & 0x0f\n\n const layoutResult = resolveMfuPayloadLayout(mpu, fragmentType, payload)\n if ('rejection' in layoutResult) return layoutResult\n const { layout } = layoutResult\n\n const trailerLayout = resolveDeclaredTrailers(\n payload,\n layout.dataEnd,\n header.fecType,\n options,\n )\n if (!trailerLayout) {\n // The most common cause is a producer whose Source FEC Payload ID width\n // disagrees with ISO/IEC 23008-1 \u00A7C.5.2. Name that explicitly rather than\n // leaving operators to infer it from a generic trailer error.\n if (!options?.skipFecId && header.fecType === 1) {\n const observed = payload.length - layout.dataEnd\n const expected = SOURCE_FEC_PAYLOAD_ID_SIZE\n if (observed !== expected) {\n return {\n rejection: {\n gate: 'source-fec-payload-id-width-mismatch',\n detail:\n `producer wrote a ${observed}-byte Source FEC Payload ID, ` +\n `ISO/IEC 23008-1 \u00A7C.5.2 requires ${expected} ` +\n `(payload=${payload.length}, declaredEnd=${layout.dataEnd})`,\n },\n }\n }\n }\n return {\n rejection: {\n gate: 'declared-trailers-unresolved',\n detail:\n `trailer bytes [${layout.dataEnd}, ${payload.length}) are neither empty ` +\n `nor an exact legacy authenticator trailer (fecType=${header.fecType})`,\n },\n }\n }\n\n return { plan: { header, payload, mpu, fragmentType, layout, trailerLayout } }\n}\n\n/**\n * Report why `extractMFUPayload` would refuse this packet, or null if it would\n * accept it.\n *\n * `extractMFUPayload` returns bare `null` on ten distinct conditions, which\n * makes a producer/consumer framing disagreement indistinguishable from a\n * publisher that never started \u2014 both render as silence. Use this wherever\n * that distinction matters: diagnostics, contract tests, and operator-facing\n * logs.\n */\nexport function explainMFURejection(\n mmtpPacket: Uint8Array,\n options?: MFUExtractOptions,\n): MFURejection | null {\n const result = planMfuExtraction(mmtpPacket, options)\n return 'rejection' in result ? result.rejection : null\n}\n\nexport function extractMFUPayload(\n mmtpPacket: Uint8Array,\n options?: MFUExtractOptions,\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options))\n}\n\n/**\n * extractMFUPayload for a caller that already holds this packet's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet; the\n * result is then identical to `extractMFUPayload(mmtpPacket, options)`.\n */\nexport function extractMFUPayloadWithHeader(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n options?: MFUExtractOptions,\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options, header))\n}\n\nfunction extractPlannedMfu(\n mmtpPacket: Uint8Array,\n result: { plan: MfuPlan } | { rejection: MFURejection },\n): MFUExtraction | null {\n if ('rejection' in result) return null\n const { header, payload, mpu, fragmentType, layout, trailerLayout } = result.plan\n\n const mfuDuHeaderPresent = layout.hasMfuDuHeader\n const mfuOffset = layout.mfuOffset\n const dataEnd = layout.dataEnd\n\n const mfuDuHeader =\n mfuDuHeaderPresent && mpu.timedFlag === 1\n ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE)\n : null\n const itemId =\n mfuDuHeaderPresent && mpu.timedFlag === 0\n ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false)\n : null\n\n const data = payload.subarray(mfuOffset, dataEnd)\n\n const fecPayloadId = trailerLayout.hasFecId\n ? {\n ssId: new DataView(\n mmtpPacket.buffer,\n mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE,\n 4,\n ).getUint32(0, false),\n }\n : null\n\n return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId }\n}\n\n/**\n * Extract timestamp from MMTP packet\n */\nexport function extractTimestamp(mmtpPacket: Uint8Array): bigint {\n const { header } = unwrapMMTP(mmtpPacket)\n return header.timestamp\n}\n\n/**\n * Check if MMTP packet is an FEC repair packet\n * FEC_type 2 and 3 are repair packets\n */\nexport function isFecRepairPacket(mmtpPacket: Uint8Array): boolean {\n if (mmtpPacket.length < 1) return false\n const fecType = (mmtpPacket[0]! >> 3) & 0x03\n return fecType >= 2\n}\n\n/**\n * Extract Source FEC Payload ID (SS_ID) from the last 4 bytes of an MMTP\n * source packet per ISO/IEC 23008-1:2023 Section C.5.2 Figure C.10.\n *\n * SS_ID is a flat 32-bit monotonic counter (incremented by 1 per packet\n * for ssbg_mode0 and ssbg_mode1). Block membership and ESI use the\n * configured K; repair SS_Start identifies the first SS_ID of the block and\n * SSB_length records the authored source-symbol count:\n * SBN = floor(SS_ID / K), ESI = SS_ID % K\n * SS_Start = SBN * K (first SS_ID of the block)\n *\n * This matches FFmpeg moqenc_mmt.c, the drafts (draft-ramadan-moq-fec \u00A76.2),\n * and ATSC A/331 \u00A78.1.2.5 which defers to ISO 23008-1 Annex C.\n */\nexport function extractFecPayloadId(mmtpPacket: Uint8Array): { ssId: number } | null {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header ? sourceFecPayloadIdOf(mmtpPacket, header) : null\n}\n\n/**\n * Return true when FEC_type=1 and the exact suffix after the ISO-declared MPU\n * payload contains a four-byte Source FEC Payload ID.\n */\nexport function hasSourceFecPayloadId(mmtpPacket: Uint8Array): boolean {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header !== null && sourceFecPayloadIdOf(mmtpPacket, header) !== null\n}\n\nfunction parseHeaderForSourceFecId(mmtpPacket: Uint8Array): MMTPHeader | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n try {\n return parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n}\n\n/**\n * The Source FEC Payload ID of a packet whose MMTP header the caller already\n * parsed, or null when the packet carries none: present only when FEC_type=1\n * and the exact suffix after the ISO-declared MPU payload holds the four-byte\n * ID (ISO/IEC 23008-1 \u00A7C.5.2). Same answer as extractFecPayloadId, without a\n * second header parse (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet.\n */\nexport function sourceFecPayloadIdOf(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n): { ssId: number } | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n if (header.packetType !== PACKET_TYPE_MPU) return null\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) return null\n const payloadLength = (payload[0]! << 8) | payload[1]!\n if (payloadLength < MPU_HEADER_REMAINDER_SIZE) return null\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + payloadLength\n if (!resolveDeclaredTrailers(payload, declaredEnd, header.fecType)?.hasFecId) return null\n\n // Flat 4-byte SS_ID: encoder writes block_id * K + symbol_id\n const off = mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n return {\n ssId:\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0,\n }\n}\n\n/** Size of Repair FEC Payload ID per ISO/IEC 23008-1 Section C.5.3 */\nexport const REPAIR_FEC_PID_SIZE = 13\n\n/**\n * Parse the 13-byte Repair FEC Payload ID after the complete dynamic MMTP header.\n * `parsedHeader`, when given, must be `parseMMTPHeader(mmtpPacket)` of this\n * same packet; it spares the second header parse (BLO-36599).\n */\nfunction readRepairFecPayloadIdFields(mmtpPacket: Uint8Array, parsedHeader?: MMTPHeader): {\n packetId: number; ssStart: number; rsbLength: number; rsId: number; ssbLength: number; dataOffset: number\n} | null {\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n }\n if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2) return null\n\n const off = header.headerLength\n if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE) return null\n const ssStart =\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0 // 32 bits\n const rsbLength = (mmtpPacket[off + 4]! << 16) | (mmtpPacket[off + 5]! << 8) | mmtpPacket[off + 6]! // 24 bits\n const rsId = (mmtpPacket[off + 7]! << 16) | (mmtpPacket[off + 8]! << 8) | mmtpPacket[off + 9]! // 24 bits\n const ssbLength = (mmtpPacket[off + 10]! << 16) | (mmtpPacket[off + 11]! << 8) | mmtpPacket[off + 12]! // 24 bits\n return {\n packetId: header.packetId,\n ssStart,\n rsbLength,\n rsId,\n ssbLength,\n dataOffset: off + REPAIR_FEC_PID_SIZE,\n }\n}\n\n/**\n * Extract Repair FEC Payload ID from a raw-multicast MMTP repair packet.\n * Per ISO/IEC 23008-1:2023 Section C.5.3 (ssbg_mode0, one-stage, no FFSRP_TS):\n * [MMTP header][SS_Start:4][RSB_length:3][RS_ID:3][SSB_length:3][repair data]\n * OTI is delivered via AL-FEC signaling message (Table C.3), not per-packet.\n *\n * Byte 1 is reserved(2)|packet_type(6) for V=0, so repair type 0x03 is 0x03.\n * Pre-migration high-bits bytes (0x0c) are rejected \u2014 no compatibility decode.\n */\nexport function extractRepairFecPayloadId(mmtpPacket: Uint8Array): {\n ssStart: number; rsbLength: number; rsId: number; ssbLength: number\n} | null {\n const fields = readRepairFecPayloadIdFields(mmtpPacket)\n if (!fields) return null\n return {\n ssStart: fields.ssStart,\n rsbLength: fields.rsbLength,\n rsId: fields.rsId,\n ssbLength: fields.ssbLength,\n }\n}\n\n/** Parsed MoQ repair frame per ISO/IEC 23008-1 Section C.4.3 + C.5.3 */\nexport interface MoqRepairFrame {\n /** MMTP packetId (1=video, 2=audio) \u2014 for routing to correct FEC decoder */\n packetId: number\n /** SS_Start (32 bits): SS_ID of first source symbol in block */\n ssStart: number\n /** RSB_length (24 bits): number of repair symbols (P) */\n rsbLength: number\n /** RS_ID (24 bits): repair symbol index (0-based) */\n rsId: number\n /** SSB_length (24 bits): authored source-symbol count (1..=configured K) */\n ssbLength: number\n /** Repair symbol data after the dynamic MMTP header and 13-byte FEC payload ID. */\n symbolData: Uint8Array\n}\n\n/**\n * Parse a MoQ repair frame (ISO/IEC 23008-1 Annex C format).\n *\n * Wire format per ISO 23008-1 \u00A7C.4.3 + \u00A7C.5.3:\n * MMTP Header: fixed 12 bytes plus C/X optional fields\n * then SS_Start (4 bytes) \u2192 block identifier\n * then RSB_length (3 bytes) \u2192 P\n * then RS_ID (3 bytes) \u2192 ESI = K + RS_ID\n * then SSB_length (3 bytes) \u2192 authored source-symbol count (1..=K)\n * then Repair Symbol Data (T bytes)\n *\n * @param frame - Raw MoQ repair frame bytes\n * @returns Parsed frame or null if invalid\n */\nexport function parseMoqRepairFrame(frame: Uint8Array): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame))\n}\n\n/**\n * parseMoqRepairFrame for a caller that already holds this frame's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599). The router's\n * multicast repair branch uses it: one repair packet in every K + P otherwise\n * paid two header parses.\n *\n * `header` must be `parseMMTPHeader(frame)` of this same frame; the result is\n * then identical to `parseMoqRepairFrame(frame)`.\n */\nexport function parseMoqRepairFrameWithHeader(\n frame: Uint8Array,\n header: MMTPHeader,\n): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header))\n}\n\nfunction moqRepairFrameFrom(\n frame: Uint8Array,\n repairId: ReturnType<typeof readRepairFecPayloadIdFields>,\n checkRsId = true,\n): MoqRepairFrame | null {\n if (!repairId) return null\n\n const symbolData = frame.subarray(repairId.dataOffset)\n if (\n repairId.ssbLength === 0 ||\n (checkRsId && repairId.rsId >= repairId.rsbLength) ||\n symbolData.length === 0\n ) return null\n\n return {\n packetId: repairId.packetId,\n ssStart: repairId.ssStart,\n rsbLength: repairId.rsbLength,\n rsId: repairId.rsId,\n ssbLength: repairId.ssbLength,\n symbolData,\n }\n}\n\n/**\n * Why a repair object of an mmtp track is discarded on admission:\n * `repairLength` -- the object is not exactly 12 + 13 + T bytes with a\n * 12-byte MMTP header (C = 0, X = 0; draft-ramadan-moq-mmt-02 7.3, judged\n * before any Repair FEC Payload ID field is read); `repairRsId` -- RS_ID is not\n * below RSB_length, under every scheme; `repairSchemeBound` -- the object\n * breaks its scheme's bound: reed-solomon SSB_length + RSB_length > 255, which\n * also caps RS_ID at 253, or raptorq SSB_length + RSB_length - 1 > 2^24 - 1\n * (draft-ramadan-moq-fec-core-00 7.5 and 10.3, -block-codes-00 7).\n */\nexport type RepairObjectReject = 'repairLength' | 'repairRsId' | 'repairSchemeBound'\n\n/**\n * Admission of one mmtp repair object under its instance's T and scheme. The\n * caller names the instance (by the repair track it subscribed); nothing here\n * infers it from the fields. `repairRsId` and `repairSchemeBound` carry the\n * frame so the caller can first route an RSB_length below a held layer's\n * O_i + P_i to the 7.3.2 stop, which takes precedence over the discard.\n * `null`: not an iso repair packet, or SSB_length 0.\n */\nexport function admitMmtpRepairObject(\n packet: Uint8Array,\n header: MMTPHeader,\n symbolSize: number,\n algorithm: string | undefined,\n): { frame: MoqRepairFrame; reject?: Exclude<RepairObjectReject, 'repairLength'> } | { reject: 'repairLength' } | null {\n if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2) return null\n if (header.headerLength !== MMTP_HEADER_SIZE || packet.length !== MMTP_HEADER_SIZE + REPAIR_FEC_PID_SIZE + symbolSize) {\n return { reject: 'repairLength' }\n }\n const frame = moqRepairFrameFrom(packet, readRepairFecPayloadIdFields(packet, header), false)\n if (!frame) return null\n if (frame.rsId >= frame.rsbLength) return { frame, reject: 'repairRsId' }\n const blockSymbols = frame.ssbLength + frame.rsbLength\n if (algorithm === 'reed-solomon' ? blockSymbols > 255 : algorithm === 'raptorq' && blockSymbols - 1 > 0xffffff) {\n return { frame, reject: 'repairSchemeBound' }\n }\n return { frame }\n}\n\n// The signalling-message parsers (9.3.4.2 payload header, AL-FEC message,\n// PA/MPT) live in ./signalling.ts.\n", "/**\n * NTP short format (RFC 5905 \u00A76): an unsigned 32-bit, 16.16 fixed-point count\n * of seconds. The MMTP header `timestamp` field (ISO/IEC 23008-1 \u00A79.2.2)\n * carries each packet's UTC sending instant in this format, so the value wraps\n * to 0 every 2^16 s (~18.2 h).\n *\n * Plain numeric order on these values breaks at every wrap: a retained\n * `Math.max` stays at the pre-wrap value and every later instant compares as\n * older. Order send times only with {@link compareNtpShort}, which applies\n * RFC 1982 serial-number arithmetic over the field's width.\n */\n\n/** Width in bits of the MMTP `timestamp` field (NTP short). */\nexport const NTP_SHORT_BITS = 32\n\n/** Number of distinct NTP-short values; the field wraps to 0 here. */\nexport const NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS\n\n/**\n * RFC 1982 \u00A73.2's `2^(SERIAL_BITS - 1)`. Two values whose forward distance is\n * below this are ordered; exactly this far apart they are not ordered at all.\n * Two instants must be less than this far apart (2^15 s, ~9.1 h of send time)\n * for the comparison to give their true order.\n */\nexport const NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1)\n\n/**\n * Serial order of one NTP-short value relative to another.\n *\n * `'unordered'` is RFC 1982's undefined case: the values are exactly\n * {@link NTP_SHORT_HALF_RANGE} apart, so neither precedes the other. It is\n * never folded into `'before'` or `'after'`; each caller decides what an\n * unorderable pair means for it.\n */\nexport type NtpShortOrder = 'before' | 'equal' | 'after' | 'unordered'\n\n/** True when `value` is an NTP-short value: an integer in [0, NTP_SHORT_MODULUS). */\nexport function isNtpShort(value: number): boolean {\n return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS\n}\n\n/**\n * RFC 1982 serial comparison of NTP-short `a` against `b`: `'after'` when `a`\n * is the later instant, `'before'` when it is the earlier one.\n *\n * The answer is the true order only while the two instants are less than\n * {@link NTP_SHORT_HALF_RANGE} apart. Past that a 32-bit field cannot tell\n * later from earlier, and the result names whichever direction is nearer.\n * This is not a total order (it is not transitive across the whole space), so\n * it must never be used to sort.\n *\n * @throws {RangeError} if either operand is not an NTP-short value\n */\nexport function compareNtpShort(a: number, b: number): NtpShortOrder {\n if (!isNtpShort(a) || !isNtpShort(b)) {\n throw new RangeError(\n `NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS}), got ${String(a)} and ${String(b)}`,\n )\n }\n if (a === b) return 'equal'\n // Forward distance from b to a, reduced into [1, NTP_SHORT_MODULUS). Both\n // operands are below 2^32, so every step is exact in a double.\n const forward = (a - b + NTP_SHORT_MODULUS) % NTP_SHORT_MODULUS\n if (forward < NTP_SHORT_HALF_RANGE) return 'after'\n if (forward > NTP_SHORT_HALF_RANGE) return 'before'\n return 'unordered'\n}\n", "/**\n * RFC 1982 serial-number arithmetic for the 32-bit MMTP AL-FEC symbol\n * counters (ISO/IEC 23008-1:2023 C.5.2 SS_ID, C.5.3 SS_Start).\n *\n * SS_ID is a 32-bit field, so a stream that runs long enough wraps it to 0.\n * Ordering two SS_IDs (or two blocks by their first SS_ID) with `<` reads\n * every post-wrap value as older than every pre-wrap one. Serial order\n * agrees with `<` whenever the two values are less than 2^31 apart, so for\n * every stream that has not reached the wrap the result is unchanged; only\n * the order across the wrap point differs (BLO-35597 iso:5).\n */\n\n/** 2^SERIAL_BITS for SERIAL_BITS = 32. */\nexport const SERIAL32_SPAN = 0x1_0000_0000\n\n/** RFC 1982 \u00A73.2's 2^(SERIAL_BITS - 1). */\nexport const SERIAL32_HALF = 0x8000_0000\n\nfunction assertUint32(value: number, name: string): void {\n if (!Number.isInteger(value) || value < 0 || value >= SERIAL32_SPAN) {\n throw new RangeError(`${name} must be a uint32 (got ${value})`)\n }\n}\n\n/**\n * RFC 1982 \u00A73.1 addition, extended to negative `n` for the matching\n * subtraction: `(s + n) mod 2^32`. `n` must lie in (-2^31, 2^31).\n */\nexport function serial32Add(s: number, n: number): number {\n assertUint32(s, 's')\n if (!Number.isInteger(n) || n <= -SERIAL32_HALF || n >= SERIAL32_HALF) {\n throw new RangeError(`serial addend must lie in (-2^31, 2^31) (got ${n})`)\n }\n return (s + n + SERIAL32_SPAN) % SERIAL32_SPAN\n}\n\n/** Forward distance from `from` to `to`: `(to - from) mod 2^32`. */\nexport function serial32Distance(from: number, to: number): number {\n return (to - from) >>> 0\n}\n\n/**\n * RFC 1982 \u00A73.2: `a` precedes `b`. Values exactly 2^31 apart are unordered\n * (neither precedes the other).\n */\nexport function serial32Precedes(a: number, b: number): boolean {\n const distance = serial32Distance(a, b)\n return distance !== 0 && distance < SERIAL32_HALF\n}\n", "/**\n * FEC block profile (BLO-35597, ISO/IEC 23008-1 Annex C).\n *\n * Every catalog `fec` object that declares an FEC instance names its block\n * profile in `fec.blockProfile`. A receiver applies all of a profile's rules\n * or none of them, so the token is the one explicit per-stream discriminator:\n * it is never defaulted and never inferred from the wire.\n *\n * draft-ramadan-moq-fec \u00A75.1 defines exactly one value, and it is the only\n * profile this library implements:\n *\n * - `iso-ssbg1-v1`: ssbg_mode1 (C.3.3): a source symbol is\n * `u16 length || protected packet || zero padding` to T; a block is a\n * K' = SSB_length RaptorQ block (C.5.3) and repair ESI = SSB_length + RS_ID;\n * SS_ID increments by one per FEC source packet and wraps at 2^32 (C.5.2),\n * so a block is located by membership in `[SS_Start, SS_Start + SSB_length)`\n * under RFC 1982 serial arithmetic; the MoQ repair group id is the 62-bit\n * wrap-epoch-extended SS_Start. The AL-FEC coding byte for this profile is\n * 0x14 (one-stage, ssbg_mode1, fec_payload_id_mode 0, Amd 1:2025 Table C.3).\n *\n * A track whose `blockProfile` is absent or names any other token (the\n * retired Blockcast-private `k-padded-v1` included) has no FEC: a receiver\n * consumes its source without FEC and joins none of its repair tracks\n * (draft-ramadan-moq-fec \u00A75.1). `parseFecBlockProfile` throws for such a\n * token; the per-track catalog resolver turns the same rule into a typed\n * per-track \"FEC unavailable\" outcome instead of failing the session.\n */\nimport { serial32Add, serial32Distance, serial32Precedes } from './serial-number.js'\n\n/** The block profile a catalog `fec.blockProfile` may name: the one this library implements. */\nexport type FecBlockProfile = 'iso-ssbg1-v1'\n\n/** Every accepted `fec.blockProfile` token. */\nexport const FEC_BLOCK_PROFILES: readonly FecBlockProfile[] = Object.freeze([\n 'iso-ssbg1-v1',\n])\n\n/** True for a block-profile token this library implements. */\nexport function isFecBlockProfile(value: unknown): value is FecBlockProfile {\n return value === 'iso-ssbg1-v1'\n}\n\n/**\n * Read a required `fec.blockProfile`. Throws on an absent token and on any\n * token other than `iso-ssbg1-v1`: there is no default and nothing is\n * inferred from the wire (draft-ramadan-moq-fec \u00A75.1).\n *\n * @param where the catalog path of the field, for the error message.\n */\nexport function parseFecBlockProfile(value: unknown, where: string): FecBlockProfile {\n if (isFecBlockProfile(value)) return value\n if (value === undefined) {\n throw new Error(`${where} is required: name the FEC block profile (\"iso-ssbg1-v1\")`)\n }\n throw new Error(`${where} must be \"iso-ssbg1-v1\" (got ${JSON.stringify(value)})`)\n}\n\n/** ISO/IEC 23008-1 C.3.3 ssbg_mode1: the two-octet packet length field. */\nexport const SSBG1_LENGTH_FIELD_BYTES = 2\n\n/** The largest protected packet an ssbg_mode1 symbol of size T can carry. */\nexport function ssbg1MaxPacketLength(symbolSize: number): number {\n return symbolSize - SSBG1_LENGTH_FIELD_BYTES\n}\n\n/** Whether a protected packet of `packetLength` bytes fits one T-byte ssbg_mode1 symbol. */\nexport function ssbg1FitsSymbol(packetLength: number, symbolSize: number): boolean {\n return (\n Number.isSafeInteger(packetLength) &&\n packetLength >= 0 &&\n packetLength <= ssbg1MaxPacketLength(symbolSize) &&\n packetLength <= 0xffff\n )\n}\n\n/**\n * Build one ssbg_mode1 source symbol (C.3.3): the protected packet's length\n * in two octets, network byte order, then the packet, then zero octets up to\n * T. The protected packet is the MMTP packet before its Source FEC Payload ID\n * is appended (C.4.2).\n *\n * @throws when `length + 2 > T`: the packet cannot be protected under this\n * profile, and silently truncating it would corrupt every repair symbol.\n */\nexport function buildSsbg1SourceSymbol(packet: Uint8Array, symbolSize: number): Uint8Array {\n if (!Number.isSafeInteger(symbolSize) || symbolSize <= SSBG1_LENGTH_FIELD_BYTES) {\n throw new Error(`ssbg_mode1 symbol size must exceed ${SSBG1_LENGTH_FIELD_BYTES} (got ${symbolSize})`)\n }\n if (!ssbg1FitsSymbol(packet.byteLength, symbolSize)) {\n throw new Error(\n `ssbg_mode1 source symbol needs ${packet.byteLength} + ${SSBG1_LENGTH_FIELD_BYTES} bytes but T is ${symbolSize}`,\n )\n }\n const symbol = new Uint8Array(symbolSize)\n symbol[0] = (packet.byteLength >>> 8) & 0xff\n symbol[1] = packet.byteLength & 0xff\n symbol.set(packet, SSBG1_LENGTH_FIELD_BYTES)\n return symbol\n}\n\n/**\n * Recover the protected packet from one ssbg_mode1 source symbol: the bytes\n * the length field names. Returns null, never a guess, when the length field\n * points past the symbol or any padding octet is non-zero (C.3.3 padding is\n * all 00h), since either means the recovered symbol is not what was sent.\n */\nexport function trimSsbg1SourceSymbol(symbol: Uint8Array): Uint8Array | null {\n if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES) return null\n const length = (symbol[0]! << 8) | symbol[1]!\n const end = SSBG1_LENGTH_FIELD_BYTES + length\n if (end > symbol.byteLength) return null\n for (let i = end; i < symbol.byteLength; i++) {\n if (symbol[i] !== 0) return null\n }\n return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end)\n}\n\n/** The SS_ID after the last source symbol of `[ssStart, ssStart + ssbLength)`. */\nexport function isoBlockEnd(ssStart: number, ssbLength: number): number {\n return serial32Add(ssStart, ssbLength)\n}\n\n/**\n * Range membership (C.5.2, C.5.3): whether `ssId` is one of the\n * `ssbLength` consecutive SS_IDs starting at `ssStart`, modulo 2^32.\n */\nexport function isoBlockContains(ssStart: number, ssbLength: number, ssId: number): boolean {\n return serial32Distance(ssStart, ssId) < ssbLength\n}\n\n/**\n * A lower bound on how many blocks the block starting at `a` lies behind the\n * one starting at `b` (0 when `a` does not precede `b`). An iso-ssbg1-v1\n * block holds at most `kMax` source symbols (the catalog `sourceSymbols`, the\n * AL-FEC maximum_k_for_repair_flow), so `n * kMax` SS_IDs always span at least\n * `n` blocks. Every interleave horizon in the receiver (decoder retention,\n * worker retirement, ordered-relay settlement) uses this one bound, so the\n * manager's horizon can never fall inside the decoder's.\n */\nexport function isoBlocksBehindLowerBound(a: number, b: number, kMax: number): number {\n if (!Number.isSafeInteger(kMax) || kMax <= 0) {\n throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`)\n }\n return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0\n}\n", "/**\n * Runtime FEC bindings (BLO-50171): what each source track's FEC resolves to\n * for this library's receiver, read from `validateFecCatalog`'s per-instance\n * result and never re-derived.\n *\n * Every runtime reader (the container's `resolveCatalogTrackFec`,\n * `resolveRepairLayers`, `MulticastManager.configureMultiTrack`, transport's\n * `catalogRepairTracks`) goes through `resolveFecBindings`, so they cannot\n * disagree with the validator or with each other about which tracks have FEC\n * and which repair tracks belong to them.\n *\n * The draft-ramadan-moq-fec-catalog-00 array is the only shape. Both catalog\n * dialects bind through it: an MSF `tracks[]` entry directly, and a hang\n * `video`/`audio` rendition (`fec` the same array) with its `repair.renditions`\n * entries (`source` + `instanceId`), mapped onto a `tracks[]` view so the same\n * validator runs. A hang rendition is authoritative over a `tracks[]` entry of\n * the same name.\n *\n * Fail closed per instance: a source whose base instance is not `ok` resolves\n * to `unavailable` with the validator's code and path, and costs no other\n * track anything. A draft-01 object `fec` is `fec_member` at that track's\n * `fec`: the track plays without FEC.\n */\nimport {\n validateFecCatalog,\n type FecCatalogCode,\n type FecCatalogIssue,\n type FecCatalogReceiver,\n type FecCatalogReport,\n} from './fec-catalog.js'\n\n/** The receiver this runtime is: it decodes `iso-ssbg1-v1` only. */\nexport const RUNTIME_FEC_RECEIVER: FecCatalogReceiver = Object.freeze({\n schemes: Object.freeze(['raptorq', 'reed-solomon']),\n blockProfiles: Object.freeze(['iso-ssbg1-v1']),\n overlays: true,\n})\n\n/** Repair track priority when the track states none (MoQT scale, 192..255). */\nexport const DEFAULT_FEC_REPAIR_PRIORITY = 240\n\n/** One `ok` instance's geometry. */\nexport interface FecInstanceGeometry {\n readonly instanceId: number\n readonly scheme: 'raptorq' | 'reed-solomon'\n /** `iso-ssbg1-v1` under `RUNTIME_FEC_RECEIVER`. */\n readonly blockProfile: string\n /** K. */\n readonly sourceSymbols: number\n /** P_0 for a base instance; the overlay's own P for an overlay. */\n readonly repairSymbols: number\n /** T. */\n readonly symbolSize: number\n readonly interleaveDepthMs?: number\n readonly reorderToleranceMs?: number\n readonly repairTrack: string\n readonly symbolTrack?: string\n}\n\nexport interface FecLayerBinding {\n readonly layer: number\n readonly repairTrackName: string\n readonly repairSymbols: number\n /** O_i = sum(P_j, j < i). */\n readonly rsIdOffset: number\n readonly priority: number\n}\n\nexport interface FecOverlayBinding {\n readonly repairTrackName: string\n readonly scope: 'keyframe'\n readonly sourceSymbols: number\n readonly repairSymbols: number\n readonly priority: number\n readonly geometry: FecInstanceGeometry\n}\n\nexport interface FecBindingUnavailable {\n /** The validator's code, or `fec_base_instances` for a track with no base\n * instance or more than one `ok` one (the MMTP wire carries one base Source FEC Payload\n * ID, mmt-02 7.4.1). */\n readonly code: FecCatalogCode | 'fec_base_instances'\n /** JSON Pointer into the catalog (a hang path starts `/video` or `/audio`). */\n readonly path: string\n readonly outcome: 'unavailable' | 'violation'\n}\n\nexport type FecSourceBinding =\n | {\n readonly status: 'ok'\n readonly track: string\n /** JSON Pointer of the source track (`/tracks/<i>`, `/video/renditions/<name>`). */\n readonly pointer: string\n readonly base: FecInstanceGeometry\n /** Base layers in order, layer 0 first. */\n readonly layers: readonly FecLayerBinding[]\n /** Sum of P over the base layers: the wire RSB_length. */\n readonly totalBaseRepairSymbols: number\n readonly overlay?: FecOverlayBinding\n /** Why a declared overlay is not used, when one is not. */\n readonly overlayUnavailable?: FecBindingUnavailable\n }\n | {\n readonly status: 'unavailable'\n readonly track: string\n readonly pointer: string\n readonly reason: FecBindingUnavailable\n }\n\ntype Obj = Record<string, unknown>\nconst recordOf = (v: unknown): Obj | undefined =>\n typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Obj) : undefined\nconst escape = (s: string) => s.replace(/~/g, '~0').replace(/\\//g, '~1')\n\n/**\n * The `tracks[]` view of a catalog in either dialect, with each view track's\n * JSON Pointer in the original catalog.\n */\nexport function fecCatalogTracks(catalog: unknown): { tracks: unknown[]; pointers: string[] } {\n const root = recordOf(catalog) ?? {}\n const tracks: unknown[] = []\n const pointers: string[] = []\n const hangNames = new Set<string>()\n for (const role of ['video', 'audio'] as const) {\n for (const [name, r] of Object.entries(recordOf(recordOf(root[role])?.['renditions']) ?? {})) {\n const entry = recordOf(r)\n if (!entry) continue\n hangNames.add(name)\n const kind = recordOf(entry['container'])?.['kind']\n // A hang rendition carries no `packaging`; its container kind is it.\n // `mmtp-fec` is hang's kind for MMTP that carries FEC (the FFmpeg\n // publisher's `moq_publish_set_video_packaging`): MMTP packaging.\n const view: Obj = { name, packaging: kind === undefined || kind === 'mmtp-fec' ? 'mmtp' : kind }\n if (entry['fec'] !== undefined) view['fec'] = entry['fec']\n tracks.push(view)\n pointers.push(`/${role}/renditions/${escape(name)}`)\n }\n }\n const hangRenditions = tracks.length\n for (const [name, r] of Object.entries(recordOf(recordOf(root['repair'])?.['renditions']) ?? {})) {\n hangNames.add(name)\n tracks.push({ packaging: 'fec-repair', ...recordOf(r), name })\n pointers.push(`/repair/renditions/${escape(name)}`)\n }\n const raw = Array.isArray(root['tracks']) ? root['tracks'] : []\n const named = new Set(hangNames)\n raw.forEach((t, i) => {\n const name = recordOf(t)?.['name']\n if (typeof name === 'string') named.add(name)\n if (typeof name === 'string' && hangNames.has(name)) return\n tracks.push(t)\n pointers.push(`/tracks/${i}`)\n })\n // hang layer 0 needs no `repair.renditions` entry: the rendition's instance\n // names it, and a hang Root (hang's toHang) carries no repair block. Such a\n // name stands for a repair track of that instance.\n tracks.slice(0, hangRenditions).forEach((t, ti) => {\n const view = t as Obj\n if (!Array.isArray(view['fec'])) return\n view['fec'].forEach((o, ii) => {\n const repairTrack = recordOf(o)?.['repairTrack']\n if (typeof repairTrack !== 'string' || named.has(repairTrack)) return\n named.add(repairTrack)\n const instanceId = recordOf(o)?.['instanceId']\n tracks.push({ name: repairTrack, packaging: 'fec-repair', source: view['name'], ...(instanceId === undefined ? {} : { instanceId }) })\n pointers.push(`${pointers[ti]}/fec/${ii}/repairTrack`)\n })\n })\n return { tracks, pointers }\n}\n\nfunction runtimeView(catalog: unknown, receiver: FecCatalogReceiver) {\n const { tracks, pointers } = fecCatalogTracks(catalog)\n const report = validateFecCatalog({ tracks }, receiver)\n const at = (path: string) => {\n const m = /^\\/tracks\\/(\\d+)(.*)$/.exec(path)\n return m ? pointers[Number(m[1])] + m[2] : path\n }\n return { tracks, pointers, report, at }\n}\n\n/**\n * The `validateFecCatalog` report `resolveFecBindings` acts on (BLO-55242):\n * the same `tracks[]` view and the same receiver, so a host publishing it\n * cannot disagree with what the runtime does. Paths are JSON Pointers into\n * the original catalog (a hang path starts `/video`, `/audio` or `/repair`).\n * One kind does not resolve: a hang layer 0 repair track with no\n * `repair.renditions` entry stands at the `repairTrack` string that names it\n * (`.../fec/<j>/repairTrack`), so a path below that track names nothing in\n * the catalog. The track indices (`trackIndex`, `repairTrack`,\n * `boundRepairTracks`, `symbolTrack`) index `fecCatalogTracks(catalog).tracks`.\n */\nexport function runtimeFecCatalogReport(\n catalog: unknown,\n receiver: FecCatalogReceiver = RUNTIME_FEC_RECEIVER,\n): FecCatalogReport {\n const { report, at } = runtimeView(catalog, receiver)\n const issue = (i: FecCatalogIssue) => Object.freeze({ code: i.code, path: at(i.path) })\n return Object.freeze({\n instances: Object.freeze(\n report.instances.map((i) => Object.freeze({ ...i, path: at(i.path), issues: Object.freeze(i.issues.map(issue)) })),\n ),\n issues: Object.freeze(report.issues.map(issue)),\n })\n}\n\n/**\n * Every source track's runtime FEC binding, by track name. A track with no\n * `fec`, or an empty `fec` array, declares no FEC and has no entry.\n */\nexport function resolveFecBindings(\n catalog: unknown,\n receiver: FecCatalogReceiver = RUNTIME_FEC_RECEIVER,\n): ReadonlyMap<string, FecSourceBinding> {\n const { tracks, pointers, report, at } = runtimeView(catalog, receiver)\n const trackAt = (i: number) => recordOf(tracks[i]) ?? {}\n const nameAt = (i: number | null) => (i === null ? undefined : (trackAt(i)['name'] as string))\n const why = (i: { outcome: string; issues: readonly { code: FecCatalogCode; path: string }[]; path: string }) =>\n Object.freeze({\n code: i.issues[0]?.code ?? 'fec_member',\n path: at(i.issues[0]?.path ?? i.path),\n outcome: i.outcome === 'unavailable' ? ('unavailable' as const) : ('violation' as const),\n })\n\n const out = new Map<string, FecSourceBinding>()\n tracks.forEach((t, ti) => {\n const track = recordOf(t)\n const name = track?.['name']\n if (!track || typeof name !== 'string' || out.has(name)) return\n if (track['packaging'] === 'fec-repair' || track['packaging'] === 'fec-source') return\n const fec = track['fec']\n if (fec === undefined) return\n if (!Array.isArray(fec)) {\n const reason = { code: 'fec_member' as const, path: at(`/tracks/${ti}/fec`), outcome: 'violation' as const }\n out.set(name, Object.freeze({ status: 'unavailable', track: name, pointer: pointers[ti]!, reason: Object.freeze(reason) }))\n return\n }\n if (fec.length === 0) return\n const insts = report.instances.filter((i) => i.trackIndex === ti)\n const isOverlay = (i: (typeof insts)[number]) => Object.hasOwn(recordOf(fec[Number(i.path.split('/').pop())]) ?? {}, 'scope')\n const bases = insts.filter((i) => !isOverlay(i))\n const okBases = bases.filter((i) => i.outcome === 'ok')\n if (okBases.length !== 1) {\n const reason =\n // No base instance at all (overlay-only `fec`) is a count of 0, not\n // the overlay's own issue.\n okBases.length > 1 || bases.length === 0\n ? Object.freeze({ code: 'fec_base_instances' as const, path: at(`/tracks/${ti}/fec`), outcome: 'violation' as const })\n : why(bases[0] ?? insts[0]!)\n out.set(name, Object.freeze({ status: 'unavailable', track: name, pointer: pointers[ti]!, reason }))\n return\n }\n const b = okBases[0]!\n const base = geometry(recordOf(fec[Number(b.path.split('/').pop())])!, b.instanceId!, nameAt(b.symbolTrack))\n const priorityOf = (i: number | null) => {\n const p = i === null ? undefined : trackAt(i)['priority']\n return typeof p === 'number' ? p : DEFAULT_FEC_REPAIR_PRIORITY\n }\n const layers: FecLayerBinding[] = [\n { layer: 0, repairTrackName: base.repairTrack, repairSymbols: base.repairSymbols, rsIdOffset: 0, priority: priorityOf(b.repairTrack) },\n ]\n const more = b.boundRepairTracks\n .map((tj) => ({ tj, layer: trackAt(tj)['repairLayer'] as number }))\n .sort((x, y) => x.layer - y.layer)\n let offset = base.repairSymbols\n for (const { tj, layer } of more) {\n const repairSymbols = trackAt(tj)['repairSymbols'] as number\n layers.push({ layer, repairTrackName: nameAt(tj)!, repairSymbols, rsIdOffset: offset, priority: priorityOf(tj) })\n offset += repairSymbols\n }\n let overlay: FecOverlayBinding | undefined\n let overlayUnavailable: FecBindingUnavailable | undefined\n const ov = insts.find(isOverlay)\n if (ov?.outcome === 'ok') {\n const g = geometry(recordOf(fec[Number(ov.path.split('/').pop())])!, ov.instanceId!, nameAt(ov.symbolTrack))\n overlay = Object.freeze({\n repairTrackName: g.repairTrack,\n scope: 'keyframe' as const,\n sourceSymbols: g.sourceSymbols,\n repairSymbols: g.repairSymbols,\n priority: priorityOf(ov.repairTrack),\n geometry: g,\n })\n } else if (ov) overlayUnavailable = why(ov)\n out.set(\n name,\n Object.freeze({\n status: 'ok' as const,\n track: name,\n pointer: pointers[ti]!,\n base,\n layers: Object.freeze(layers.map((l) => Object.freeze(l))),\n totalBaseRepairSymbols: offset,\n ...(overlay ? { overlay } : {}),\n ...(overlayUnavailable ? { overlayUnavailable } : {}),\n }),\n )\n })\n return out\n}\n\n// The validator passed this instance for this receiver, so every member read\n// here is present and in range.\nfunction geometry(o: Obj, instanceId: number, symbolTrack: string | undefined): FecInstanceGeometry {\n return Object.freeze({\n instanceId,\n scheme: o['scheme'] as 'raptorq' | 'reed-solomon',\n blockProfile: o['blockProfile'] as string,\n sourceSymbols: o['sourceSymbols'] as number,\n repairSymbols: o['repairSymbols'] as number,\n symbolSize: o['symbolSize'] as number,\n ...(typeof o['interleaveDepthMs'] === 'number' ? { interleaveDepthMs: o['interleaveDepthMs'] } : {}),\n ...(typeof o['reorderToleranceMs'] === 'number' ? { reorderToleranceMs: o['reorderToleranceMs'] } : {}),\n repairTrack: o['repairTrack'] as string,\n ...(symbolTrack !== undefined ? { symbolTrack } : {}),\n })\n}\n", "// The mmtp track modes of draft-ramadan-moq-mmt-02 13.1 and the pairing of\n// an \"mfu-datagram\" track with the \"mfu\" track it mirrors (4.3.1).\n//\n// A publisher MUST NOT publish an \"mfu-datagram\" track without an \"mfu\" track\n// of the same namespace whose objects are identical in Group ID, Object ID\n// and payload. The catalog carries no sibling pointer, so the pair is read\n// from what the two entries state: they are siblings when their whole\n// identity set is equal, field by field or absent on both. The identity set\n// is the hard set (what the Group and Object IDs are derived from) and the\n// rendition fields of mmt-02 13.1 (one payload has one codec, size, bitrate\n// and language; the rungs of a ladder share the hard set, so nothing else\n// tells them apart). A datagram track with no sibling, or more than one, is\n// rejected and the player plays \"mfu\". The soft set is reported, never a\n// fault. Names, roles and labels are not read: fec-catalog-00 makes names\n// non-normative. Known limit: two \"mfu\" tracks with one description cannot\n// carry datagram siblings until the draft defines a pointer.\n//\n// The rule is a per-pair predicate: it answers the same over the whole\n// catalog and over any subset of it a consumer kept.\n\n/** Every mmtpMode this library accepts (mmt-02 13.1). Anything else rejects the track. */\nexport const MMTP_MODES = Object.freeze(['mfu', 'mfu-datagram'] as const)\n\nexport type MmtpMode = (typeof MMTP_MODES)[number]\n\nexport function isMmtpMode(value: unknown): value is MmtpMode {\n return typeof value === 'string' && (MMTP_MODES as readonly string[]).includes(value)\n}\n\n/**\n * Fields the Group and Object IDs of an mmtp track are derived from: two\n * tracks whose values differ cannot carry identical ids (mmt-02 4.4.2, 4.6).\n * Compared equal-or-both-absent, group duration as resolved ticks.\n */\nexport const MMTP_SIBLING_HARD_FIELDS = Object.freeze([\n 'namespace',\n 'timescale',\n 'presentationAnchorTicks',\n 'groupDuration',\n] as const)\n\n/**\n * Fields that describe the media a track carries. The pair carries one\n * payload (mmt-02 4.3.1), so it has one description: an \"mfu\" track whose\n * description differs is another rendition. The rungs of a ladder share the\n * hard set and nothing else in the catalog tells them apart. Compared\n * equal-or-both-absent, like the hard set.\n */\nexport const MMTP_SIBLING_RENDITION_FIELDS = Object.freeze([\n 'codec',\n 'width',\n 'height',\n 'framerate',\n 'bitrate',\n 'samplerate',\n 'channelConfig',\n 'lang',\n] as const)\n\n/**\n * Fields the pair SHOULD share; a mismatch is reported, not a fault. A soft\n * field is read from the entry of the track subscribed, never borrowed from\n * its sibling: a leg takes the keyframe interval its \"mfu-datagram\" entry\n * states, and none when that entry states none (mmt-02 4.4.3).\n */\nexport const MMTP_SIBLING_SOFT_FIELDS = Object.freeze([\n 'initRef',\n 'keyframeIntervalMs',\n 'keyframeIntervalTicks',\n 'isLive',\n 'altGroup',\n] as const)\n\nexport interface MmtpSiblingPair<T> {\n /** The \"mfu\" track. */\n readonly stream: T\n /** Its \"mfu-datagram\" sibling, when the catalog carries exactly one. */\n readonly datagram?: T\n /** Soft-set fields on which the two differ (empty without a datagram sibling). */\n readonly softMismatches: readonly string[]\n}\n\ntype Fields = Record<string, unknown>\n\nfunction fields(track: object): Fields {\n return track as Fields\n}\n\nfunction groupDurationTicks(track: Fields): bigint | undefined {\n const ticks = track['groupDurationTicks']\n if (Number.isSafeInteger(ticks)) return BigInt(ticks as number)\n const ms = track['groupDurationMs']\n const timescale = track['timescale']\n if (!Number.isSafeInteger(ms) || !Number.isSafeInteger(timescale)) return undefined\n return (BigInt(ms as number) * BigInt(timescale as number)) / 1000n\n}\n\nfunction identityEqual(a: Fields, b: Fields): boolean {\n return (\n a['namespace'] === b['namespace'] &&\n a['timescale'] === b['timescale'] &&\n a['presentationAnchorTicks'] === b['presentationAnchorTicks'] &&\n groupDurationTicks(a) === groupDurationTicks(b) &&\n MMTP_SIBLING_RENDITION_FIELDS.every((field) => a[field] === b[field])\n )\n}\n\nfunction isMmtpTrack(track: unknown, mode: MmtpMode): track is object {\n return (\n typeof track === 'object' && track !== null && !Array.isArray(track) &&\n fields(track)['packaging'] === 'mmtp' && fields(track)['mmtpMode'] === mode\n )\n}\n\n/**\n * The \"mfu\" tracks of `tracks` an \"mfu-datagram\" track could be the sibling\n * of: the ones whose identity set (hard set and rendition fields) equals its own. Exactly one\n * pairs it; zero or more than one rejects the datagram track (mmt-02 4.3.1).\n */\nexport function mmtpSiblingCandidates<T extends object>(tracks: readonly T[], datagram: T): T[] {\n const own = fields(datagram)\n return tracks.filter((track) => isMmtpTrack(track, 'mfu') && identityEqual(fields(track), own))\n}\n\n/**\n * Every \"mfu\" track of `tracks` by name, each with its \"mfu-datagram\" sibling\n * when exactly one matches its identity set. A datagram track that matches no\n * \"mfu\" track or more than one pairs with none, and two datagram tracks that\n * match the same \"mfu\" track pair with neither (each is rejected by\n * `mmtpTrackIssues` in the container validator, which first sets aside a\n * track it rejects for its delivery mode); the \"mfu\" tracks are listed\n * whatever happens to their siblings. Never throws.\n */\nexport function pairMmtpSiblings<T extends object>(tracks: readonly T[]): ReadonlyMap<string, MmtpSiblingPair<T>> {\n const pairs = new Map<string, MmtpSiblingPair<T>>()\n for (const track of tracks) {\n if (!isMmtpTrack(track, 'mfu')) continue\n const name = fields(track)['name']\n if (typeof name === 'string' && !pairs.has(name)) pairs.set(name, { stream: track, softMismatches: [] })\n }\n // Two datagram tracks matching one \"mfu\" track pair with neither: the\n // catalog says nothing about which mirrors it.\n const datagrams = new Map<string, T[]>()\n for (const datagram of tracks) {\n if (!isMmtpTrack(datagram, 'mfu-datagram')) continue\n const candidates = mmtpSiblingCandidates(tracks, datagram)\n if (candidates.length !== 1) continue\n const name = fields(candidates[0]!)['name']\n if (typeof name !== 'string' || pairs.get(name)?.stream !== candidates[0]) continue\n datagrams.set(name, [...(datagrams.get(name) ?? []), datagram])\n }\n for (const [name, matched] of datagrams) {\n if (matched.length !== 1) continue\n const { stream } = pairs.get(name)!\n const a = fields(stream)\n const b = fields(matched[0]!)\n const softMismatches = MMTP_SIBLING_SOFT_FIELDS.filter((field) => a[field] !== b[field])\n pairs.set(name, { stream, datagram: matched[0]!, softMismatches })\n }\n return pairs\n}\n", "// The datagram-leg size table of draft-ramadan-moq-mmt-02 4.3.1: every object\n// of an \"mfu-datagram\" track and of its repair tracks MUST fit one datagram,\n// and SHOULD fit a 1200-byte UDP payload with its QUIC and WebTransport\n// framing, its OBJECT_DATAGRAM header and room for the Object Properties a\n// relay adds. The same numbers live in FFmpeg's moqenc_mmt.h\n// (FF_MOQ_MMT_DG_*) and the dual-stack relay's conformance test; change them\n// together.\n\n/** The smallest maximum UDP payload QUIC allows (RFC 9000 14). */\nexport const DATAGRAM_LEG_UDP_FLOOR = 1200\n/** QUIC short header (1 + DCID <= 20 + PN <= 4) + AEAD tag 16, DATAGRAM frame type + length 3, WebTransport quarter-stream-id varint <= 4. */\nexport const DATAGRAM_LEG_QUIC_WT_FRAMING = 48\n/** OBJECT_DATAGRAM header, varint worst cases: type 1 + alias <= 4 + group <= 4 + object <= 2 + priority 1 + extensions length 1. */\nexport const DATAGRAM_LEG_OBJECT_HEADER = 13\n/** Room for two small varint properties a relay may add (e.g. draft-20 Prior Group/Object ID Gap). */\nexport const DATAGRAM_LEG_RELAY_ROOM = 16\n/** FEC Source Info 0x11 inside Immutable Properties 0x0B on a source object. */\nexport const DATAGRAM_LEG_SOURCE_PROPS = 8\n/** A repair packet is 12 (MMTP header) + 13 (Repair FEC Payload ID) + T bytes (mmt-02 7.3). */\nexport const DATAGRAM_LEG_REPAIR_OVERHEAD = 25\n/** The MoQ datagram budget: what reaches the MoQ layer of a 1200-byte UDP payload. */\nexport const DATAGRAM_LEG_DATAGRAM_MAX = DATAGRAM_LEG_UDP_FLOOR - DATAGRAM_LEG_QUIC_WT_FRAMING\n/** The object body budget: the datagram minus the OBJECT_DATAGRAM header and the relay room. */\nexport const DATAGRAM_LEG_BODY_MAX = DATAGRAM_LEG_DATAGRAM_MAX - DATAGRAM_LEG_OBJECT_HEADER - DATAGRAM_LEG_RELAY_ROOM\n/** The largest RaptorQ symbol size (a multiple of 8) whose repair object fits the body budget. */\nexport const DATAGRAM_LEG_SYMBOL_SIZE_MAX = 1096\n\n/**\n * The largest MoQ datagram a receiver of the leg gets at symbol size T: a\n * repair object with its OBJECT_DATAGRAM header, 13 + 25 + T. The relay's\n * property room is a publisher reserve (DATAGRAM_LEG_BODY_MAX), not a\n * receiver cost: what arrives already carries those properties. A session\n * whose `datagrams.maxDatagramSize` is below it cannot carry the track's\n * repair, so the subscriber takes the \"mfu\" track (mmt-02 4.3.1).\n */\nexport function datagramLegObjectMax(symbolSize: number): number {\n return DATAGRAM_LEG_OBJECT_HEADER + DATAGRAM_LEG_REPAIR_OVERHEAD + symbolSize\n}\n\n/** Whether a RaptorQ symbol size keeps every object of the leg inside the 1200-byte table. */\nexport function datagramLegSymbolSizeFits(symbolSize: number): boolean {\n return (\n Number.isInteger(symbolSize) && symbolSize > 0 && symbolSize % 8 === 0 &&\n symbolSize + DATAGRAM_LEG_REPAIR_OVERHEAD <= DATAGRAM_LEG_BODY_MAX\n )\n}\n", "/**\n * D-28 shared repair-fetch scheduler.\n *\n * Player-agnostic orchestration for per-block on-demand MoQ FEC repair\n * backfill. Each player (moqtail client, hang watch, Shaka MSF bridge)\n * supplies only its protocol verb via {@link RepairFetchTransport}, fetching\n * one block's repair group. Blocks are `iso-ssbg1-v1` (ISO/IEC 23008-1\n * ssbg_mode1, the only FEC block profile), so that group's MoQ id is the\n * 62-bit wrap-epoch-extended SS_Start, `extSsStart(wrapEpoch, ssStart)` from\n * `@blockcast/mmt-fec` -- never the 32-bit block key itself (see\n * `RepairFetchRequest.sbn`):\n *\n * - moqtail: standalone FETCH (FetchType.Standalone) of that one group\n * - moq-lite/hang: Subscribe with startGroup = endGroup = that group (the\n * relay propagates startGroup upstream to pull the past group from the\n * origin's producer cache)\n *\n * Everything else \u2014 registration, fire-time repair-track resolution,\n * keyframe-first admission, preemption, feeding symbols, and in-flight slot\n * release \u2014 is identical across players and lives here. The Player owns the\n * scheduler: one per `wireRepairFetch` call, and its disposer aborts\n * everything.\n *\n * Priority (from the block's class, see `repairPriorityForClass`):\n * - P0 (keyframe / unknown) dispatches as soon as it is enqueued, with no\n * cap. Each has its own fail deadline, and a cap would turn a\n * recoverable protected block into a stall; their number is already\n * bounded by the blocks one fail window can hold. A P0 block that lies\n * below a RAP the receiver already holds complete is not requested at\n * all (`moot-rap`), and a P0 FETCH still running when such a RAP\n * arrives is cancelled (`repair-stopped`, `moot`): the receiver resumes\n * from that RAP (draft-ramadan-moq-fec-multicast-01 \u00A76.2.1). Only a\n * repair that cannot land by the block's playout deadline (it relies on\n * the keyframe budget's extension, or that deadline has passed) is\n * moot: one that can stalls nothing.\n * - P1 (audio) dispatches, uncapped, while no P0 is queued or in flight;\n * P2 (delta) only while no P0/P1 is, earliest absolute fail deadline\n * first (\u00A711.4.5 item 3).\n * - Only a P0 FETCH the scheduler actually sends aborts the in-flight P1\n * and P2 FETCHes (`repair-preempted`), which return to the queue while\n * their blocks are unresolved: a keyframe request that is refused, moot\n * or otherwise never sent cancels nothing (\u00A711.4.5 item 3), and an audio\n * request never preempts. A P2 that never ran before its block resolved\n * is reported as `repair-deferred`.\n * - A hole walked over the one-Group transport (no `rangeTransport`) is\n * repair the run gets before its FEC deadline (`walkHole`). On a video\n * track it is keyframe repair (class `unknown`): P0, and no audio or\n * delta FETCH is issued while one of its Group FETCHes is outstanding\n * (fec-multicast-00 rule 3). It reaches no FEC deadline, so it preempts\n * nothing and holds back no audio or delta request: one that comes due\n * cancels the walk's Group FETCH and goes out at once, and the walk asks\n * for that Group again after it (`yieldVideoWalks`). On an audio track\n * it is audio repair: P1 at the audio wire priority, one Group per FETCH,\n * and like any audio request it waits while keyframe repair is\n * outstanding, stopping before its next Group, and is preempted by a\n * keyframe FETCH sent.\n * - A block reclassified to a higher class while its P2 fetch is in flight\n * is re-issued at once under the new class's wire priority: the running\n * FETCH is aborted (FETCH_CANCEL) and a new one sent.\n *\n * Wire priority (draft-ramadan-moq-fec \u00A711.4.5): every request carries the\n * MoQ Transport SUBSCRIBER_PRIORITY its FETCH must use, derived from the two\n * catalog priorities `ResolveRepairTarget` returns (see\n * `repairFetchSubscriberPriority`): a keyframe-bearing (or unknown) block's\n * FETCH is sent in the Source Media range at no more than the source\n * track's priority, so it is delivered ahead of every repair track and not\n * shed with repair data; a delta or audio FETCH is sent at no less than the\n * fetched repair track's priority, so it is shed first.\n *\n * Deadline and admission (BLO-35597): a repair FETCH rides the reliable path,\n * so its deadline is the block's PRESENTATION deadline, not the multicast\n * reassembly deadline. The player states how long after a block's first\n * symbol its media can still be presented (`presentationDelayMs`); from the\n * block's receiver-local anchor that gives an absolute deadline, never earlier\n * than the multicast wait and never later than the release gate's hold ceiling\n * (`terminalRetentionMsForPacket`), which bounds how long any successor frame\n * may wait behind the block. A FETCH is sent only when the measured\n * reliable-path RTT (`reliableRttMs`) is less than the time left to that\n * deadline -- a request that cannot come back in time is never sent, rather\n * than sent and cancelled -- and an admitted FETCH holds the block open to\n * that deadline, so the multicast span elapsing never aborts it.\n *\n * Keyframe late-repair budget: a block that may hold a RAP may be given a\n * longer deadline than the playout budget (`keyframeRepairBudgetMs`). Losing\n * such a block costs every frame up to the next keyframe, so holding it open\n * for a FETCH that lands within the budget trades a short hold for a GOP-long\n * freeze. At a small playout budget (a low-latency target) the presentation\n * deadline alone leaves less than one round trip by the time the multicast\n * wait gives up on the block, so every keyframe request would be refused\n * (`rtt-exceeds-budget`). Eligible (`keyframeBudgetEligible`): a `keyframe`\n * block (in-band RAP evidence), and an `unknown` block only while its\n * stream's classifier is `classifying`, where `unknown` means the window rule\n * could not exclude a RAP. Under `all-protected` every block reads `unknown`\n * whatever it holds, so there only RAP evidence earns the budget. The mode\n * also reads `classifying` on a track where no block is classed `delta`\n * (`BlockClassifier.mpuRuleOff` names a catalog reason or a thing found):\n * every short block of it is `unknown` whatever it holds, and is eligible. Never\n * audio (P1) or delta (P2), and never a block its repair group cannot\n * complete (received sources + RSB_length < K'). The hold ends when its\n * FETCH ends without making the block decodable, not at the budget.\n *\n * Every deadline is capped by the release gate's hold ceiling measured the\n * way the gate measures it: from the earliest frame it holds for the stream\n * (a surviving frame of the block itself is routed before a repair symbol\n * states the block, so before its anchor), never later than from the anchor.\n * A FETCH landing after the gate forced that frame out would recover media\n * the gate then drops as stale.\n *\n * The scheduler arms no timers for block requests but one: a running P0\n * FETCH below a RAP held complete gets a timer at its playout deadline, when\n * it turns moot (\u00A76.2.1). A fetch ends when its\n * transport completes or throws, when it is preempted, when any later\n * scheduling event finds it past its presentation deadline, when its block\n * resolves (recovered, or failed at that deadline), on track reset, or on\n * dispose. A range request (\u00A77.5) is for a hole, not a tracked block, so no\n * FEC deadline resolves it: it arms one timer at its deadline, cleared when\n * it retires, so a hung range FETCH cannot hold the hole (and the release\n * gate behind it) past that deadline.\n */\n\nimport {\n extractRepairFecPayloadId,\n parseFecBlockProfile,\n serial32Add,\n serial32Distance,\n type FecBlockProfile,\n} from '@blockcast/mmt-base'\nimport { extendSsId, repairFetchRange, type RepairFetchRange } from '@blockcast/mmt-fec'\nimport {\n repairPriorityForClass,\n type BlockClass,\n type ClassifierMode,\n type RepairPriority,\n type TrackKind,\n} from './block-policy.js'\nimport type { ExpiredIsoHole, UndelimitedIsoLoss } from './fec-manager.js'\nimport type { RepairLifecycleObserver } from './multicast-manager.js'\nimport { REPAIR_PRIORITY_MIN } from './repair-layers.js'\n\n/** The MoQ Transport priority scale: 0..255, a lower value is delivered first. */\nconst MOQT_PRIORITY_MAX = 255\n\n/**\n * How long before the span a walked hole leaves asks for its repair (D-28)\n * the walk ends: past the deadline timer's 1 ms slack and one timer tick, so\n * the span's request timer is armed before it is due (walkDeadlineAt).\n */\nconst WALK_LEAD_MS = 3\n\n/**\n * The highest value in the Source Media priority range of\n * draft-ramadan-moq-fec \u00A710 (64..191): one below the repair range, which\n * starts at `REPAIR_PRIORITY_MIN` (192).\n */\nexport const SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1\n\n/** What `ResolveRepairTarget` returns for one repair-bearing stream. */\nexport interface RepairTarget {\n /** The repair track to FETCH (base layer 0 of the block's source). */\n readonly repairTrack: string\n /**\n * The catalog `priority` of the SOURCE track the block belongs to, on the\n * MoQ Transport scale (0..255, lower first), or null when the catalog\n * carries none. Never a player constant: a keyframe repair must not be\n * delivered behind the source it repairs, and only the catalog says what\n * that source's priority is.\n */\n readonly sourcePriority: number | null\n /**\n * The catalog priority of `repairTrack` (MoQ Transport scale). Layer 0\n * that declares none has the value draft-ramadan-moq-fec \u00A710 defines\n * (240); `resolveRepairLayers` / `catalogRepairTarget` already apply it.\n * Null only when the resolver cannot read the repair track's entry.\n */\n readonly repairPriority: number | null\n}\n\n/** Resolve a packetId to its repair track and priorities at FIRE TIME.\n *\n * Called on every repair request, never cached by the shell: ABR ladder\n * rungs can share a packetId (e.g. video/720p and video/360p both p:1), so\n * the mapping must reflect the track active when the request fires, not\n * when the shell was wired. Return null when the packetId has no\n * repair-bearing track \u2014 the request is released without a fetch.\n * `catalogRepairTarget` builds the answer from a catalog. */\nexport type ResolveRepairTarget = (\n packetId: number,\n catalogTrackName?: string,\n) => RepairTarget | null\n\n/** One on-demand repair FETCH, as the scheduler hands it to the transport. */\nexport interface RepairFetchRequest {\n /** Repair track whose block `sbn` is fetched. */\n readonly repairTrack: string\n /**\n * The block's key: its 32-bit SS_Start (ISO/IEC 23008-1 C.5.3). The field\n * keeps its historical name, but ssbg_mode1 blocks have no source block\n * number (BLO-35597 D2a). The repair group's MoQ id is the 62-bit\n * `extSsStart(wrapEpoch, sbn)`; a receiver that knows only a lost SS_ID\n * fetches `repairFetchRange(lostSsId, kMax, anchor)`, where `anchor` is\n * `{ previousBlockStart }` (the extended start of the last block delimited\n * before it) or `{ reference }` (an epoch reference). Never use it as a\n * group id directly: SS_Start wraps at 2^32, a MoQ group id never goes\n * backwards.\n */\n readonly sbn: number\n /**\n * The block profile `sbn` is keyed by: the catalog `fec.blockProfile`,\n * which is always `iso-ssbg1-v1`. Required, and validated with\n * `parseFecBlockProfile` when the request is queued, so a stream configured\n * with any other token (the retired `k-padded-v1` included) never reaches\n * the transport.\n */\n readonly blockProfile: FecBlockProfile\n /** The source packetId the block belongs to. */\n readonly packetId: number\n /**\n * Aborts when the scheduler no longer wants the group: preemption by\n * keyframe work, reprioritisation, block resolution, track reset, dispose.\n * When the scheduler stops a running request, `signal.reason` is its\n * `RepairStopReason`, the one `noteRepairStopped` reports.\n */\n readonly signal: AbortSignal\n /**\n * The SUBSCRIBER_PRIORITY parameter the FETCH MUST carry, on the MoQ\n * Transport scale (0..255, lower delivered first), as\n * draft-ramadan-moq-fec \u00A711.4.5 requires. `undefined` means OMIT the\n * parameter: the catalog carries no priority to derive it from, and the\n * publisher then uses the value draft-ietf-moq-transport-16 \u00A79.2.2.3\n * defines for an omitted parameter (128, inside the Source Media range).\n * A transport never substitutes a value of its own. A transport whose API\n * uses another scale (moq-lite's higher-wins weight, say) maps this one\n * without reordering it against the source and repair subscriptions.\n */\n readonly subscriberPriority: number | undefined\n}\n\n/** Protocol-specific fetch of one FEC block's repair group.\n *\n * Yield each repair object payload (MMTP packet bytes, ISO 23008-1 \u00A7C.5.3\n * Repair FEC Payload ID framing). Return when the group ends.\n *\n * Put `request.subscriberPriority` on the FETCH (see RepairFetchRequest).\n *\n * When `request.signal` aborts, the transport MUST cancel the FETCH ON THE\n * WIRE, not merely stop reading: send FETCH_CANCEL for its Request ID\n * (draft-ietf-moq-transport-16 \u00A79.18; STOP_SENDING on an open data stream\n * as well, \u00A75.2), and do it from the abort handler itself, before it\n * returns. A relay that is never told keeps sending the group, so a\n * preempted delta repair keeps competing with the keyframe repair that\n * preempted it. The scheduler may issue the next request for the same block\n * (reprioritisation) as soon as it aborts one, and \u00A711.4.5 allows at most\n * one repair FETCH outstanding per block and repair layer, so the cancel\n * must already be queued ahead of that request. A FETCH whose Request ID\n * is not known yet is cancelled as soon as FETCH_OK assigns it. */\nexport type RepairFetchTransport = (request: RepairFetchRequest) => AsyncIterable<Uint8Array>\n\n/**\n * One range repair FETCH for a lost SS_ID in an undelimited span\n * (draft-ramadan-moq-fec \u00A77.5): the absolute, inclusive repair-track Group\n * range `repairFetchRange` gives. The last Group returned is the block holding\n * `lostSsId`; earlier ones are other blocks, admitted like any repair object.\n */\nexport interface RepairRangeFetchRequest extends RepairFetchRange {\n readonly repairTrack: string\n /** The lost SS_ID x the range was computed for. */\n readonly lostSsId: number\n readonly blockProfile: FecBlockProfile\n readonly packetId: number\n /** Same contract as `RepairFetchRequest.signal`: cancel on the wire. */\n readonly signal: AbortSignal\n /** Same contract as `RepairFetchRequest.subscriberPriority`. */\n readonly subscriberPriority: number | undefined\n}\n\n/**\n * Protocol-specific range FETCH (e.g. MoQT LOCATION_FILTER 0x03 Group range).\n * Yield each repair object payload; return when the range ends. The abort\n * rules of {@link RepairFetchTransport} apply unchanged.\n */\nexport type RepairRangeFetchTransport = (request: RepairRangeFetchRequest) => AsyncIterable<Uint8Array>\n\n/** Why a request could not carry a catalog-derived priority. */\nexport type RepairPriorityReason =\n | 'source-priority-absent'\n | 'source-priority-invalid'\n | 'repair-priority-absent'\n | 'repair-priority-invalid'\n\n/**\n * The wire priority of one repair request (draft-ramadan-moq-fec \u00A711.4.5).\n *\n * - `carry`: send the FETCH with `subscriberPriority`.\n * - `omit`: send it without SUBSCRIBER_PRIORITY. Only a keyframe-bearing or\n * unknown block's request is ever sent this way: the publisher then uses\n * 128 (draft-ietf-moq-transport-16 \u00A79.2.2.3), which lies in the Source\n * Media range, and without a catalog source priority there is no bound\n * below it to honour.\n * - `decline`: send no FETCH. A delta or audio FETCH MUST carry a priority\n * at least its repair track's, so at least 192, and the omitted value (128)\n * would put best-effort repair ahead of every repair track. Unicast repair\n * is optional for those classes (\u00A711.4.3, \u00A711.4.4); in-band FEC and\n * concealment still apply.\n */\nexport type RepairFetchPriority =\n | { readonly kind: 'carry'; readonly subscriberPriority: number }\n | { readonly kind: 'omit'; readonly reason: RepairPriorityReason }\n | { readonly kind: 'decline'; readonly reason: RepairPriorityReason }\n\nfunction isMoqtPriority(value: number): boolean {\n return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX\n}\n\n/**\n * Derive the SUBSCRIBER_PRIORITY of a repair FETCH from the block's class and\n * the catalog priorities of its source and repair tracks\n * (draft-ramadan-moq-fec \u00A711.4.5 and the \u00A710 ranges):\n *\n * - keyframe / unknown: in the Source Media range and no greater than the\n * source track's priority, i.e. min(source, 191); omitted when the catalog\n * carries no source priority.\n * - delta / audio: no lower than the fetched repair track's priority and at\n * least 192, i.e. max(repair, 192); declined when it carries none.\n */\nexport function repairFetchSubscriberPriority(\n blockClass: BlockClass,\n target: Pick<RepairTarget, 'sourcePriority' | 'repairPriority'>,\n): RepairFetchPriority {\n if (repairPriorityForClass(blockClass) === 0) {\n const source = target.sourcePriority\n if (source === null) return { kind: 'omit', reason: 'source-priority-absent' }\n if (!isMoqtPriority(source)) return { kind: 'omit', reason: 'source-priority-invalid' }\n return { kind: 'carry', subscriberPriority: Math.min(source, SOURCE_MEDIA_PRIORITY_MAX) }\n }\n const repair = target.repairPriority\n if (repair === null) return { kind: 'decline', reason: 'repair-priority-absent' }\n if (!isMoqtPriority(repair)) return { kind: 'decline', reason: 'repair-priority-invalid' }\n return { kind: 'carry', subscriberPriority: Math.max(repair, REPAIR_PRIORITY_MIN) }\n}\n\n/** What `RepairFetchHost.fecManager.blockSymbolCounts` reports for one open block. */\nexport interface BlockSymbolCounts {\n readonly sources: number\n readonly repairs: number\n readonly authoredLength: number | undefined\n readonly repairGroupLength: number | undefined\n}\n\n/**\n * Whether a block of `blockClass` may get the keyframe late-repair budget:\n * a `keyframe` block always (in-band RAP evidence), an `unknown` block only\n * while its stream's classifier is `classifying` (the window rule could not\n * exclude a RAP). An `all-protected` stream reads `unknown` for every block,\n * delta-only ones included, so there `unknown` is no evidence of a RAP and\n * earns no hold. Audio and delta never do. The mode alone is read: a\n * `classifying` track on which `mpuRuleOff` leaves every block `unknown`\n * gets the hold for each short block.\n */\nexport function keyframeBudgetEligible(\n blockClass: BlockClass,\n classifierMode: ClassifierMode | undefined,\n): boolean {\n if (blockClass === 'keyframe') return true\n return blockClass === 'unknown' && classifierMode === 'classifying'\n}\n\nexport interface WireRepairFetchOptions {\n resolveTarget: ResolveRepairTarget\n transport: RepairFetchTransport\n /**\n * Maximum transport attempts per block (required). A retry happens only\n * when the transport rejects with an error `shouldRetry` classifies as\n * retryable, before any symbol was fed, while the block's deadline remains.\n */\n attemptLimit: number\n /** Classify a transport error as a transient publisher/relay retention race. */\n shouldRetry?: (error: unknown) => boolean\n /**\n * The measured round-trip time of the reliable path the transport fetches\n * over, in ms (required). Read at every admission, so it tracks the live\n * session. A value that is not finite and positive, or a throw, means the\n * path offers no measurement: nothing can show the FETCH would come back in\n * time, so none is sent (`rtt-unmeasured`). Never a default.\n */\n reliableRttMs: () => number\n /**\n * How long after a block's first symbol arrived its media can still be\n * presented, in ms (required): the player's own playout budget for the\n * stream. Same fail-closed rule as `reliableRttMs`\n * (`presentation-delay-unavailable`).\n */\n presentationDelayMs: (packetId: number, catalogTrackName?: string) => number\n /**\n * How long after the first symbol of a block that may hold a RAP a repair\n * FETCH of it may still land, in ms (optional). Such a block\n * (`keyframeBudgetEligible`) gets the larger of this and\n * `presentationDelayMs`, still never later than the release gate's hold\n * ceiling and never earlier than the multicast wait; RTT admission is\n * unchanged. Losing a keyframe block costs the rest of its GOP, so a player\n * may hold the block (and the frames released after it) while its FETCH is\n * in flight rather than freeze to the next keyframe. Absent, throwing, or\n * not finite and positive: every block gets the presentation deadline\n * alone. Never applied to audio, delta, or an `unknown` block of an\n * `all-protected` stream.\n */\n keyframeRepairBudgetMs?: (packetId: number, catalogTrackName?: string) => number\n /**\n * Range repair for a lost SS_ID whose block no repair delimited\n * (draft-ramadan-moq-fec \u00A77.5), optional. A host that can keep such a gap as\n * a pending hole gets range repair either way, under the same admission,\n * priority and abort rules as a block request (class `unknown`, P0). Given,\n * the scheduler FETCHes `repairFetchRange(x, K, anchor)` over it, and\n * requires `repairEpochReference`. Absent, it walks the hole over\n * `transport` one Group at a time from the hole's start, whose Group is a\n * block's, each repair stating where the next block starts (BLO-52085),\n * under the class of the hole's track (see the module note).\n */\n rangeTransport?: RepairRangeFetchTransport\n /**\n * The epoch reference r of `repairTrack` on the live session\n * (`RepairEpochReferences.reference`), or undefined while none is held.\n * The \u00A77.5 anchor is ext(S_prev) extended from it when a stated block ends\n * where the hole starts, else r itself; without r no range request is sent\n * (`range-no-anchor`).\n */\n repairEpochReference?: (repairTrack: string) => bigint | undefined\n}\n\n/** Why the D-28 layer asked for a repair: the block's class at its deadline. */\nexport type RepairSubscribeCallback = (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n) => void\n\n/** Why the scheduler sent no FETCH for a block it was asked to repair. */\nexport type RepairSkipReason =\n /** The reliable path offered no RTT measurement; arrival cannot be shown. */\n | 'rtt-unmeasured'\n /** The measured RTT is not less than the time left to the deadline. */\n | 'rtt-exceeds-budget'\n /** The player gave no usable presentation delay for the block's stream. */\n | 'presentation-delay-unavailable'\n /** A lost SS_ID in an undelimited span had no \u00A77.5 anchor to extend it from. */\n | 'range-no-anchor'\n /**\n * The block lost more sources than its repair group carries symbols\n * (sources + RSB_length < K'): no FETCH of the group can complete it, and\n * when multicast already delivered the whole group the relay could serve\n * only duplicates (BLO-50082).\n */\n | 'group-cannot-complete'\n /**\n * The keyframe-bearing block lies below a RAP the receiver already holds\n * complete, so its repair would be moot (draft-ramadan-moq-fec-multicast-01 \u00A76.2.1).\n */\n | 'moot-rap'\n\n/**\n * Which term set a FETCH's deadline (BLO-33597): the multicast wait, the\n * player's presentation delay past the block anchor, the keyframe budget past\n * the anchor (when it granted more than the presentation delay), or the\n * release gate's retention ceiling.\n */\nexport type RepairDeadlineBound = 'wait' | 'presentation' | 'keyframe' | 'retention'\n\n/** The admission inputs of a FETCH the scheduler sent (BLO-33597). */\nexport interface RepairSendMeasurement {\n /** The reliable-path RTT admission compared against `budgetMs`. */\n readonly rttMs: number\n /** Time left to the entry's deadline when the FETCH was sent. */\n readonly budgetMs: number\n /**\n * Delay past the block anchor the deadline was computed from; null when\n * the block had no anchor (its deadline is then the multicast wait).\n */\n readonly delayMs: number | null\n /** Time since the block anchor; null when the block had no anchor. */\n readonly blockAgeMs: number | null\n readonly bound: RepairDeadlineBound\n /** True for a range repair FETCH (\u00A77.5 lost SS_ID); absent for a block FETCH. */\n readonly range?: true\n}\n\n/** The subset of MulticastManager the scheduler drives. */\nexport interface RepairFetchHost {\n readonly fecManager: {\n blockProfileForPacket(packetId: number): FecBlockProfile | undefined\n repairFetchTimeoutMsForBlock(sbn: number, packetId: number, catalogTrackName?: string): number | undefined\n /** Receiver-local time of the block's first accepted symbol, if any. */\n blockAnchorAtMs(sbn: number, packetId: number, catalogTrackName?: string): number | undefined\n /** The stream's classifier mode (optional; absent reads as unknown). */\n classifierModeFor?(packetId: number, catalogTrackName?: string): { readonly mode: ClassifierMode }\n /**\n * An open block's received sources and distinct repair symbols, its K'\n * (SSB_length) and RSB_length (optional). The repair group carries\n * RSB_length symbols, so it can complete the block only when\n * sources + RSB_length >= K'; a FETCH that ended leaving fewer than K'\n * distinct symbols cannot be decoding it.\n */\n blockSymbolCounts?(\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): BlockSymbolCounts | undefined\n /** How long a terminal block stays authoritative: the release-gate hold ceiling. */\n terminalRetentionMsForPacket(packetId: number): number | undefined\n /** Keep the block open to `untilAtMs` for an admitted FETCH. */\n holdBlockForRepair(\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n untilAtMs: number,\n ): boolean\n /** The admitted FETCH ended without delivering: back to the multicast wait. */\n releaseRepairHold(sbn: number, packetId: number, catalogTrackName?: string): void\n /** Run `fn` with `receivedAtMs` as the receipt time of what it feeds (optional). */\n withReceiptTime?(receivedAtMs: number, fn: () => void): void\n /** The configured media kind of a packetId (optional; absent reads as video). */\n trackKindFor?(packetId: number): TrackKind | undefined\n /** The stream's D-28 repair deadline: how long after a block's sources it asks for repair (optional). */\n repairDeadlineMsForPacket?(packetId: number): number | undefined\n }\n onRepairSubscribe(cb: RepairSubscribeCallback): void\n /**\n * Arrival time of the earliest frame the in-order release gate holds for\n * the stream, or undefined (optional; absent, the block's anchor bounds the\n * ceiling alone). The gate releases that frame `terminalRetentionMsForPacket`\n * after it, whatever its blocks are doing.\n */\n earliestGatedFrameAtMs?(packetId: number, catalogTrackName?: string): number | undefined\n /** The keyframe budget extended a request's deadline by `extensionMs` (optional). */\n noteKeyframeBudgetGranted?(\n extensionMs: number,\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n addRepairLifecycleObserver(observer: RepairLifecycleObserver): () => void\n addTrackResetObserver(observer: (packetId: number, catalogTrackName: string) => void): () => void\n /**\n * Register for lost SS_IDs in undelimited spans (required with\n * `rangeTransport`). A host that offers it and `closeIsoHoles` keeps such a\n * gap as a pending hole for the scheduler to repair. `onExpired` is told of\n * a pending hole the stream ran past the locator's horizon; returning true,\n * the scheduler closes it (`closeIsoHoles`), otherwise the host discards it.\n */\n onUndelimitedLoss?(\n cb: (loss: UndelimitedIsoLoss) => void,\n onExpired?: (hole: ExpiredIsoHole) => boolean,\n ): void\n /** A hole's range repair ended, or none is sent: feed what was not stated. */\n closeIsoHoles?(packetId: number, catalogTrackName: string | undefined, start: number, length: number): void\n clearRepairForBlock(sbn: number, packetId: number, catalogTrackName?: string): void\n processRepairFromMoQ(packet: Uint8Array, ownerPacketId?: number, catalogTrackName?: string): void\n /** This scheduler can request unicast repair: protected flows keep pending entries for it (optional). */\n setUnicastRepair?(enabled: boolean): void\n noteRepairScheduling(\n type: 'repair-preempted' | 'repair-deferred',\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /** A request whose wire priority the catalog could not supply. */\n noteRepairPriority(\n action: 'omitted' | 'declined',\n reason: RepairPriorityReason,\n blockClass: BlockClass,\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /**\n * A request the scheduler did not send (see RepairSkipReason).\n * `measurement.priority` is the request's repair priority (0 keyframe or\n * unknown, 1 audio, 2 delta).\n */\n noteRepairSkipped(\n reason: RepairSkipReason,\n measurement: { readonly rttMs: number | null; readonly budgetMs: number; readonly priority?: RepairPriority },\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /** A running FETCH the scheduler stopped, and why (optional). */\n noteRepairStopped?(\n reason: RepairStopReason,\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): void\n /**\n * Whether a complete RAP above SS_ID `ssId` already reached the stream\n * (optional; absent, none ever has). Under the bc-provenance profile only\n * an admitted RAP counts (multicast-01 \u00A77.2.7).\n */\n rapCompleteAbove?(packetId: number, catalogTrackName: string | undefined, ssId: number): boolean\n /** Observe each complete RAP reaching a stream (optional; called synchronously). */\n addRapCompleteObserver?(\n observer: (packetId: number, catalogTrackName: string | undefined, ssId: number) => void,\n ): () => void\n /**\n * Observe each base block (`sbn`) whose RAP fragments the keyframe overlay\n * recovered with the keyframe's FT=0 and FT=1 held (optional; called\n * synchronously). Its keyframe FETCH is then stopped (fec-multicast-00 \u00A76.6).\n */\n addKeyframeOverlayRecoveredObserver?(\n observer: (packetId: number, catalogTrackName: string | undefined, sbn: number) => void,\n ): () => void\n /**\n * A FETCH the scheduler admitted and handed to the transport (optional):\n * every attempt, a retry or a reprioritised restart included.\n */\n noteRepairFetchSent?(\n priority: RepairPriority,\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n measurement: RepairSendMeasurement,\n ): void\n}\n\n/**\n * Why the scheduler ended a running FETCH (the transport cancels it on the\n * wire): preempted by a sent keyframe FETCH, reissued at a new class's\n * priority, past its deadline, its block resolved, track reset or a newer\n * request for the block, dispose, `moot` (a RAP above the block arrived\n * complete first, draft-ramadan-moq-fec \u00A711.4.2), or `overlay-recovered`\n * (the keyframe overlay recovered the block's RAP, fec-multicast-00 \u00A76.6).\n */\nexport type RepairStopReason =\n | 'preempted'\n | 'reprioritized'\n | 'expired'\n | 'resolved'\n | 'reset'\n | 'disposed'\n | 'moot'\n | 'overlay-recovered'\ntype StopReason = RepairStopReason\n\ninterface FetchRun {\n readonly controller: AbortController\n /** When this FETCH went out: it lands around `sentAt + rtt`. */\n readonly sentAt: number\n stopped: StopReason | null\n /** Set while a RAP above the block is held complete: fires at the playout deadline (mootAtPlayout). */\n mootTimer?: ReturnType<typeof setTimeout>\n}\n\ninterface RepairEntry {\n readonly key: string\n readonly sbn: number\n readonly packetId: number\n readonly catalogTrackName?: string\n readonly repairTrack: string\n readonly target: RepairTarget\n /** The block profile `sbn` is keyed by, resolved before the entry is queued. */\n readonly blockProfile: FecBlockProfile\n priority: RepairPriority\n /** SUBSCRIBER_PRIORITY for this entry's class; undefined = omit it. */\n subscriberPriority: number | undefined\n /**\n * Absolute `performance.now()` millisecond by which a FETCH must land: the\n * block's presentation deadline (see the module note). Only ever moves\n * later: a block reclassified from delta can gain the keyframe budget.\n */\n deadlineAt: number\n /**\n * `deadlineAt` without the keyframe budget's extension: the block's playout\n * deadline. A FETCH landing by it costs no stall, so it is not moot\n * while this deadline is still ahead.\n */\n playoutDeadlineAt: number\n /** Inputs `deadlineAt` was computed from; they move with it. */\n anchorAt: number | null\n delayMs: number | null\n bound: RepairDeadlineBound\n /** Monotonic enqueue order, the EDF tie-break. */\n readonly order: number\n attempts: number\n running: FetchRun | null\n /** A range request for a pending hole `[sbn, sbn + holeLength)`. */\n readonly range?: {\n readonly lostSsId: number\n readonly holeLength: number\n /** The \u00A77.7 Group range for `rangeTransport`; null walks the hole over `transport`. */\n readonly groups: RepairFetchRange | null\n /** When the hole was reported: what it states keeps the deadline a span opened then would have. */\n readonly reportedAt: number\n }\n /** A range request's deadline timer (see the module note). */\n expiry?: ReturnType<typeof setTimeout>\n /**\n * A hole walked over `transport` (walkHole): the Group its next FETCH asks\n * for, and the Group FETCH it has outstanding, if any.\n */\n walk?: {\n next: number\n group: { readonly sbn: number; readonly controller: AbortController } | null\n /** Its Group FETCH was cancelled for best-effort repair: ask for that Group again. */\n yielded: boolean\n }\n}\n\ninterface ResolvedDeadline {\n readonly deadlineAt: number\n readonly extensionMs: number\n readonly anchorAt: number | null\n readonly delayMs: number | null\n readonly bound: RepairDeadlineBound\n}\n\n/**\n * Wire the D-28 repair-fetch scheduler onto a MulticastManager.\n *\n * Call AFTER the manager has a repair-bearing FEC configuration (players gate\n * this on the first fec-setup that carries a repairTrack) \u2014 registration arms\n * the per-block repair deadlines in the FEC layer.\n *\n * Returns a dispose function that aborts outstanding fetches and stops new\n * ones from being issued.\n */\nexport function wireRepairFetch(mc: RepairFetchHost, opts: WireRepairFetchOptions): () => void {\n if (!Number.isSafeInteger(opts.attemptLimit) || opts.attemptLimit < 1) {\n throw new Error(\n `[RepairFetch] attemptLimit=${String(opts.attemptLimit)} must be a positive integer`,\n )\n }\n if (typeof opts.reliableRttMs !== 'function') {\n throw new Error('[RepairFetch] reliableRttMs is required: repair admission needs the measured reliable-path RTT')\n }\n if (typeof opts.presentationDelayMs !== 'function') {\n throw new Error('[RepairFetch] presentationDelayMs is required: a repair FETCH is due by the block\\'s presentation deadline')\n }\n if (\n opts.rangeTransport !== undefined &&\n (typeof opts.repairEpochReference !== 'function' || !mc.onUndelimitedLoss || !mc.closeIsoHoles)\n ) {\n throw new Error('[RepairFetch] rangeTransport needs repairEpochReference and a host that reports undelimited losses')\n }\n mc.setUnicastRepair?.(true)\n const entries = new Map<string, RepairEntry>()\n const warnedNoTarget = new Set<string>()\n let disposed = false\n let enqueueOrder = 0\n\n const requestKey = (sbn: number, packetId: number, catalogTrackName?: string): string =>\n JSON.stringify([packetId, catalogTrackName ?? null, sbn])\n const noTargetKey = (packetId: number, catalogTrackName?: string): string =>\n JSON.stringify([packetId, catalogTrackName ?? null])\n\n const clearRepair = (sbn: number, packetId: number, catalogTrackName?: string): void => {\n if (catalogTrackName === undefined) mc.clearRepairForBlock(sbn, packetId)\n else mc.clearRepairForBlock(sbn, packetId, catalogTrackName)\n }\n const note = (type: 'repair-preempted' | 'repair-deferred', entry: RepairEntry): void => {\n mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n /** Whatever ends an entry: a block's repair slot, or a hole's pending state. */\n const clearEntry = (entry: RepairEntry): void => {\n const { range } = entry\n if (range) {\n atReport(range, () => mc.closeIsoHoles!(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength))\n } else {\n clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n }\n\n /**\n * Run what a hole's walk states, or the rest of the hole it leaves as\n * spans, at the time the hole was reported: the blocks start their\n * deadlines from there, as the one repair-less span a host without holes\n * opened then would have, so the walk never holds a frame later than that\n * span did. A \u00A77.7 range FETCH feeds at its own receipt time, as a host\n * with `rangeTransport` always has.\n */\n const atReport = (range: NonNullable<RepairEntry['range']>, work: () => void): void => {\n const fec = mc.fecManager\n if (range.groups !== null || fec.withReceiptTime === undefined) work()\n else fec.withReceiptTime(range.reportedAt, work)\n }\n\n const releaseHold = (entry: RepairEntry): void => {\n // A hole is no tracked block: nothing holds it but the hole itself.\n if (entry.range) return\n if (entry.catalogTrackName === undefined) mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId)\n else mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n const stop = (entry: RepairEntry, reason: StopReason): void => {\n const run = entry.running\n if (!run) return\n entry.running = null\n if (run.mootTimer !== undefined) clearTimeout(run.mootTimer)\n run.stopped = reason\n run.controller.abort(reason)\n // A preempted request returns to the queue; until it runs again nothing is\n // in flight that could land, so the block goes back to its multicast wait.\n if (reason === 'preempted') releaseHold(entry)\n mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n /** The last SS_ID the entry covers, or undefined while its block is undelimited. */\n const lastSsId = (entry: RepairEntry): number | undefined => {\n if (entry.range) return entry.sbn + entry.range.holeLength - 1\n const length = symbolCounts(entry.sbn, entry.packetId, entry.catalogTrackName)?.authoredLength\n return length === undefined ? undefined : entry.sbn + length - 1\n }\n\n /**\n * A keyframe request whose whole block lies below a RAP already held\n * complete, and whose repair cannot land by the block's playout deadline\n * (draft-ramadan-moq-fec-multicast-01 \u00A76.2.1): the deadline has passed,\n * or send time + RTT is not before it, or no RTT is measured. One that\n * lands by the playout deadline stalls nothing, and skipping it only\n * throws away the block's frames (BLO-51635).\n */\n const moot = (entry: RepairEntry): boolean => {\n if (entry.priority !== 0) return false\n const rttMs = readRtt()\n const now = performance.now()\n // A running FETCH lands relative to when it was sent, not to now; once\n // the playout deadline has passed it can no longer land by it.\n const sentAt = entry.running?.sentAt ?? now\n if (rttMs !== null && now < entry.playoutDeadlineAt && sentAt + rttMs < entry.playoutDeadlineAt) return false\n const last = lastSsId(entry)\n if (last === undefined) return false\n try {\n return mc.rapCompleteAbove?.(entry.packetId, entry.catalogTrackName, last) === true\n } catch {\n return false\n }\n }\n\n /** Cancel a running FETCH that turned moot. */\n const dropMoot = (entry: RepairEntry): void => {\n stop(entry, 'moot')\n retire(entry)\n releaseHold(entry)\n clearEntry(entry)\n }\n\n /**\n * Moot is a state (\u00A76.2.1 condition 1: a RAP already admitted complete), so\n * a running keyframe FETCH kept only because it could land by playout turns\n * moot when that deadline passes, with no newer RAP: arm one timer for it\n * then. None is armed while no RAP above the block is held complete.\n */\n const mootAtPlayout = (entry: RepairEntry): void => {\n const run = entry.running\n if (run === null || run.mootTimer !== undefined || entry.priority !== 0) return\n const last = lastSsId(entry)\n if (last === undefined) return\n try {\n if (mc.rapCompleteAbove?.(entry.packetId, entry.catalogTrackName, last) !== true) return\n } catch {\n return\n }\n run.mootTimer = setTimeout(() => {\n run.mootTimer = undefined\n if (disposed || entry.running !== run) return\n // The deadline moved later (a reclassified block), or the timer ran early.\n if (performance.now() < entry.playoutDeadlineAt) return mootAtPlayout(entry)\n if (!moot(entry)) return\n dropMoot(entry)\n dispatch()\n }, Math.max(0, entry.playoutDeadlineAt - performance.now()))\n }\n\n /** Drop a request no FETCH will be sent for, and say why. */\n const skip = (entry: RepairEntry, reason: RepairSkipReason, rttMs: number | null, budgetMs: number): void => {\n retire(entry)\n releaseHold(entry)\n clearEntry(entry)\n mc.noteRepairSkipped(\n reason,\n { rttMs, budgetMs, priority: entry.priority },\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n )\n }\n\n /** The keyframe budget for a P0 block, or null: absent, throwing or not positive. */\n const readKeyframeBudget = (packetId: number, catalogTrackName: string | undefined): number | null => {\n const reader = opts.keyframeRepairBudgetMs\n if (reader === undefined) return null\n try {\n const budgetMs = reader(packetId, catalogTrackName)\n return Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : null\n } catch {\n return null\n }\n }\n\n const readRtt = (): number | null => {\n try {\n const rtt = opts.reliableRttMs()\n return Number.isFinite(rtt) && rtt > 0 ? rtt : null\n } catch {\n return null\n }\n }\n\n /**\n * Admission: send only a FETCH whose repair group can complete the block\n * and that the measured round trip says can land before the entry's\n * deadline. A refused entry is released, not queued: the\n * deadline only gets closer. Returns the admitting RTT, or null when refused.\n */\n const admit = (entry: RepairEntry, now: number): number | null => {\n const budgetMs = entry.deadlineAt - now\n const rttMs = readRtt()\n const reason = refusal(entry, now, rttMs)\n if (reason === null) return rttMs\n skip(entry, reason, rttMs, budgetMs)\n return null\n }\n\n /** Why admission refuses `entry` at `now` with round trip `rttMs`, or null when it admits it. */\n const refusal = (entry: RepairEntry, now: number, rttMs: number | null): RepairSkipReason | null =>\n !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName)\n ? 'group-cannot-complete'\n : rttMs === null\n ? 'rtt-unmeasured'\n : rttMs < entry.deadlineAt - now\n ? null\n : 'rtt-exceeds-budget'\n\n const retire = (entry: RepairEntry): void => {\n if (entries.get(entry.key) === entry) entries.delete(entry.key)\n if (entry.expiry !== undefined) clearTimeout(entry.expiry)\n }\n\n /**\n * Whether `entry` holds back a request of `priority`: no audio or delta\n * repair FETCH is issued while a keyframe repair FETCH is outstanding\n * (fec-multicast-00 rule 3), and no delta one while audio repair is. A\n * walk (walkHole) is repair a run gets before it reaches its FEC deadline:\n * on a video track it is keyframe repair while one of its Group FETCHes is\n * outstanding and between two Groups holds nothing back; on an audio track\n * it holds nothing back (BLO-52085). `videoWalks` false leaves video walks\n * out: they yield to a request that is no walk (`yieldVideoWalks`).\n */\n const holdsBack = (entry: RepairEntry, priority: RepairPriority, videoWalks = true): boolean => {\n if (entry.priority >= priority) return false\n const { walk } = entry\n if (walk === undefined) return true\n if (entry.priority !== 0 || !videoWalks) return false\n return entry.running === null || (walk.group !== null && !walk.group.controller.signal.aborted)\n }\n\n /** Whether any entry holds back a request of `priority` (see `holdsBack`). */\n const outstandingBelow = (priority: RepairPriority, videoWalks = true): boolean => {\n for (const entry of entries.values()) {\n if (holdsBack(entry, priority, videoWalks)) return true\n }\n return false\n }\n\n /**\n * A video walk reaches no FEC deadline, so it holds back no audio or delta\n * request that came due (one of `queued` that is no walk), that nothing\n * else holds back and that admission takes (`admit`): it cancels its outstanding Group FETCH first, so no\n * keyframe repair FETCH is outstanding when that request is issued\n * (fec-multicast-00 rule 3), and asks for that Group again after it\n * (walkHole). Audio and delta repair so goes out when it would with no\n * walk at all (BLO-52085).\n */\n const yieldVideoWalks = (queued: readonly RepairEntry[]): void => {\n const now = performance.now()\n const rttMs = readRtt()\n const due = queued.some((entry) =>\n entry.priority !== 0 && entry.walk === undefined && !outstandingBelow(entry.priority, false) &&\n refusal(entry, now, rttMs) === null)\n if (!due) return\n for (const entry of entries.values()) {\n const walk = entry.walk\n if (entry.priority !== 0 || walk === undefined || walk.group === null) continue\n if (walk.group.controller.signal.aborted) continue\n walk.yielded = true\n walk.group.controller.abort()\n }\n }\n\n /**\n * A keyframe FETCH is being sent: cancel every in-flight audio and delta\n * FETCH (\u00A711.4.5 item 3). Called only for a FETCH actually sent.\n */\n const preemptBestEffort = (): void => {\n for (const entry of entries.values()) {\n if (entry.priority === 0 || !entry.running) continue\n stop(entry, 'preempted')\n note('repair-preempted', entry)\n }\n }\n\n /**\n * The wire priority for `blockClass`, or null when no FETCH may be sent.\n * A priority the catalog cannot supply is reported once per request.\n */\n const wirePriority = (\n entry: Pick<RepairEntry, 'target' | 'sbn' | 'packetId' | 'catalogTrackName'>,\n blockClass: BlockClass,\n ): { subscriberPriority: number | undefined } | null => {\n const derived = repairFetchSubscriberPriority(blockClass, entry.target)\n if (derived.kind === 'carry') return { subscriberPriority: derived.subscriberPriority }\n mc.noteRepairPriority(\n derived.kind === 'omit' ? 'omitted' : 'declined',\n derived.reason,\n blockClass,\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n )\n return derived.kind === 'omit' ? { subscriberPriority: undefined } : null\n }\n\n /** `counted` is false for a reprioritisation restart, which is no retry. */\n const start = (entry: RepairEntry, counted = true): void => {\n const now = performance.now()\n if (moot(entry)) {\n skip(entry, 'moot-rap', readRtt(), entry.deadlineAt - now)\n return\n }\n const rttMs = admit(entry, now)\n if (rttMs === null) return\n // Before the transport sees this request, so the cancels go out first. A\n // walk reaches no FEC deadline, so it cancels nothing (rule 3).\n if (entry.priority === 0 && entry.walk === undefined) preemptBestEffort()\n // fec-multicast-00 rule 1: one FETCH per block and repair layer. A walk\n // reading this block's Group leaves it to this request.\n if (entry.range === undefined) leaveWalkedGroup(entry)\n if (counted) entry.attempts++\n mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {\n rttMs,\n budgetMs: entry.deadlineAt - now,\n delayMs: entry.delayMs,\n blockAgeMs: entry.anchorAt === null ? null : Math.max(0, now - entry.anchorAt),\n bound: entry.bound,\n ...(entry.range ? { range: true as const } : {}),\n })\n const run: FetchRun = { controller: new AbortController(), sentAt: now, stopped: null }\n entry.running = run\n mootAtPlayout(entry)\n // Hold the block open to the presentation deadline while this FETCH can\n // still land: the multicast span elapsing must not abort it.\n if (!entry.range) {\n mc.fecManager.holdBlockForRepair(\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n entry.deadlineAt,\n )\n }\n void execute(entry, run)\n }\n\n /** End any walk's FETCH of `block`'s Group, cancelling it, before the block's own goes out. */\n const leaveWalkedGroup = (block: RepairEntry): void => {\n for (const entry of entries.values()) {\n const group = entry.walk?.group\n if (\n group?.sbn === block.sbn &&\n entry.packetId === block.packetId &&\n entry.catalogTrackName === block.catalogTrackName\n ) {\n group.controller.abort()\n }\n }\n }\n\n const dispatch = (): void => {\n if (disposed) return\n const now = performance.now()\n const queued: RepairEntry[] = []\n for (const entry of [...entries.values()]) {\n if (entry.running) {\n // A fetch still running at its block's fail bound can no longer land\n // in time. Cancel it here rather than trust the transport or the FEC\n // layer's resolution to end it: a hung P0/P1 left running would keep\n // outstandingBelow() true and gate every P1/P2 for the session.\n if (entry.deadlineAt <= now) {\n stop(entry, 'expired')\n retire(entry)\n clearEntry(entry)\n }\n continue\n }\n if (entry.deadlineAt <= now) {\n // The block's fail bound has passed; its resolution is imminent and\n // no fetch can land in time.\n retire(entry)\n if (entry.priority === 2 && entry.attempts === 0) note('repair-deferred', entry)\n clearEntry(entry)\n continue\n }\n queued.push(entry)\n }\n for (const entry of queued) {\n if (entry.priority === 0) start(entry)\n }\n yieldVideoWalks(queued)\n if (outstandingBelow(1)) return\n for (const entry of queued) {\n if (entry.priority === 1) start(entry)\n }\n if (outstandingBelow(2)) return\n queued\n .filter((entry) => entry.priority === 2)\n .sort((a, b) => a.deadlineAt - b.deadlineAt || a.order - b.order)\n .forEach((entry) => start(entry))\n }\n\n /**\n * Whether the block may still be decoding from what it holds: false only\n * when the host shows fewer distinct symbols than its K'. A FETCH that\n * ended leaving it short delivered all it could (its group carries no more\n * symbols), so holding the block, and every frame behind it, longer buys\n * nothing: it goes back to its multicast wait. Unknown counts read as\n * decodable (the FEC layer resolves the block).\n */\n const symbolCounts = (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n ): BlockSymbolCounts | undefined => {\n try {\n return mc.fecManager.blockSymbolCounts?.(sbn, packetId, catalogTrackName)\n } catch {\n return undefined\n }\n }\n const decodable = (entry: RepairEntry): boolean => {\n const counts = symbolCounts(entry.sbn, entry.packetId, entry.catalogTrackName)\n if (counts === undefined || counts.authoredLength === undefined) return true\n return counts.sources + counts.repairs >= counts.authoredLength\n }\n /**\n * Whether the block's repair group can complete it: its received sources\n * plus every symbol the group carries reach K'. A loss of more sources than\n * the group has repair symbols (every source-only loss among them: the\n * block then already holds the whole group) gets no FETCH-length hold. True\n * while the counts are not known (no repair stated the block yet).\n */\n const groupCanComplete = (sbn: number, packetId: number, catalogTrackName: string | undefined): boolean => {\n const counts = symbolCounts(sbn, packetId, catalogTrackName)\n if (counts === undefined || counts.authoredLength === undefined || counts.repairGroupLength === undefined) {\n return true\n }\n return counts.sources + counts.repairGroupLength >= counts.authoredLength\n }\n /**\n * Whether the block a walked Group states can use none of the Group's other\n * repair symbols: the host holds as many of its symbols as its K' (complete,\n * or decoding), its group cannot complete it, or it no longer tracks it\n * (resolved). A relay may hold only part of a Group, or keep its FETCH open,\n * so the walk does not wait for the rest. False when the host reports no\n * counts: the walk then takes the whole Group.\n */\n const groupServed = (sbn: number, packetId: number, catalogTrackName: string | undefined): boolean => {\n if (mc.fecManager.blockSymbolCounts === undefined) return false\n const counts = symbolCounts(sbn, packetId, catalogTrackName)\n if (counts === undefined || counts.authoredLength === undefined) return true\n return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName)\n }\n /** Where the next block starts after the open block `sbn`, when a repair stated it. */\n const statedEnd = (sbn: number, packetId: number, catalogTrackName: string | undefined): number | undefined => {\n const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength\n return length === undefined ? undefined : serial32Add(sbn, length)\n }\n\n const finish = (entry: RepairEntry, run: FetchRun, fed: number, error: unknown): void => {\n if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {\n return\n }\n entry.running = null\n if (run.mootTimer !== undefined) clearTimeout(run.mootTimer)\n if (error === undefined) {\n retire(entry)\n // A fetch that ended without feeding anything cannot resolve the block;\n // release the slot and the hold so failure accounting is not wedged. A\n // fetch that fed symbols leaves resolution to the FEC layer.\n // A range FETCH placed whatever it stated as it arrived; the rest of\n // its hole is now known to have no repair coming.\n if (entry.range || fed === 0 || !decodable(entry)) {\n releaseHold(entry)\n clearEntry(entry)\n }\n dispatch()\n return\n }\n const retryable =\n fed === 0 &&\n entry.attempts < opts.attemptLimit &&\n entry.deadlineAt > performance.now() &&\n opts.shouldRetry?.(error) === true\n if (retryable) {\n // Back through the same admission rule: a P2 retry waits for P0/P1.\n dispatch()\n return\n }\n retire(entry)\n if (fed === 0) releaseHold(entry)\n clearEntry(entry)\n console.warn(\n `[RepairFetch] fetch failed pid=${entry.packetId} sbn=${entry.sbn} track=${entry.repairTrack}:`,\n error,\n )\n dispatch()\n }\n\n // The profile the block key is in; a stream reaching repair was configured\n // from its catalog, so an absent profile is a wiring fault, not a default.\n // Any token other than `iso-ssbg1-v1` (the retired `k-padded-v1` included)\n // is one too: `parseFecBlockProfile` refuses it, whatever an untyped host\n // returns. Resolved when the request arrives (onRepairSubscribe below),\n // never inside execute: there its throw would read as an ordinary fetch\n // failure, warned once per block while the stream silently lost unicast\n // repair.\n const blockProfileOf = (packetId: number): FecBlockProfile => {\n const profile: unknown = mc.fecManager.blockProfileForPacket(packetId)\n if (profile === undefined) {\n throw new Error(`[RepairFetch] packetId=${packetId} has no configured fec.blockProfile`)\n }\n return parseFecBlockProfile(profile, `[RepairFetch] packetId=${packetId} fec.blockProfile`)\n }\n\n const execute = async (entry: RepairEntry, run: FetchRun): Promise<void> => {\n let fed = 0\n const common = {\n repairTrack: entry.repairTrack,\n blockProfile: entry.blockProfile,\n packetId: entry.packetId,\n signal: run.controller.signal,\n subscriberPriority: entry.subscriberPriority,\n }\n const { range } = entry\n const feed = (packet: Uint8Array): void => {\n if (entry.catalogTrackName === undefined) {\n mc.processRepairFromMoQ(packet, entry.packetId)\n } else {\n mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName)\n }\n }\n try {\n const packets = range === undefined\n ? opts.transport({ ...common, sbn: entry.sbn })\n : entry.walk !== undefined\n ? walkHole(entry, entry.walk, range, common)\n : opts.rangeTransport!({\n ...common,\n startGroup: range.groups!.startGroup,\n endGroup: range.groups!.endGroup,\n lostSsId: range.lostSsId,\n })\n for await (const packet of packets) {\n if (run.stopped !== null || entry.running !== run) break\n fed++\n if (range === undefined) feed(packet)\n else atReport(range, () => feed(packet))\n }\n finish(entry, run, fed, undefined)\n } catch (error) {\n finish(entry, run, fed, error ?? new Error('repair transport rejected'))\n }\n }\n\n /**\n * The \u00A77.7 range FETCH of a hole over a transport that FETCHes one Group.\n * A hole starts where a stated block ends, so ext(hole start) is a block's\n * Group; the repair of each Group states its block, and that block's end is\n * the next block's Group. Walks to the block holding the hole's highest\n * lost SS_ID (everything after it arrived) and stops early when a Group\n * names no block and none is stated there. A Group is done when it ends,\n * when it held its RSB_length repair symbols, or once the block it states\n * can use none of the rest (`groupServed`): a relay may keep the FETCH open\n * past its last object (BLO-52085 D2 80601), or hold only part of the\n * Group. Each Group is its own FETCH with its own signal, aborted once the\n * walk leaves it, so the transport cancels it on the wire, and never one\n * the block's own FETCH reads (fec-multicast-00 rule 1: `leaveWalkedGroup`\n * takes it over). Between two Groups the walk honours rule 3 (see\n * `holdsBack`): an audio walk that finds keyframe repair outstanding goes\n * back to the queue and resumes at `walk.next`; a video walk first\n * dispatches what came due, and asks again for a Group whose FETCH it\n * cancelled for audio or delta repair (`yieldVideoWalks`). Every packet is\n * fed before the walk reads the host's counts: the consumer feeds what it\n * yields before asking for more.\n */\n async function* walkHole(\n entry: RepairEntry,\n walk: NonNullable<RepairEntry['walk']>,\n hole: NonNullable<RepairEntry['range']>,\n common: Omit<RepairFetchRequest, 'sbn'>,\n ): AsyncGenerator<Uint8Array> {\n const lostAt = serial32Distance(entry.sbn, hole.lostSsId)\n for (let first = true; !common.signal.aborted; first = false) {\n if (!first && entry.priority !== 0 && outstandingBelow(1)) {\n stop(entry, 'preempted')\n note('repair-preempted', entry)\n return\n }\n if (!first && entry.priority === 0) {\n dispatch()\n if (common.signal.aborted) return\n }\n const sbn = walk.next\n let next: number | undefined\n if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {\n const rsIds = new Set<number>()\n const group = new AbortController()\n const cancel = (): void => group.abort(common.signal.reason)\n common.signal.addEventListener('abort', cancel, { once: true })\n walk.group = { sbn, controller: group }\n try {\n for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {\n yield packet\n const id = extractRepairFecPayloadId(packet)\n if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue\n next ??= serial32Add(sbn, id.ssbLength)\n rsIds.add(id.rsId)\n // Aborted before the loop lets go of the transport, whose own\n // cleanup may stop listening for the abort.\n if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {\n group.abort()\n break\n }\n }\n } catch (error) {\n // The Group was taken over or yielded: the walk goes on.\n if (!group.signal.aborted || common.signal.aborted) throw error\n } finally {\n common.signal.removeEventListener('abort', cancel)\n walk.group = null\n }\n if (walk.yielded) {\n walk.yielded = false\n continue\n }\n }\n next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName)\n if (next === undefined) return\n // Past the highest lost SS_ID, which lies in the hole: done.\n if (serial32Distance(entry.sbn, next) > lostAt) return\n walk.next = next\n }\n }\n\n const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {\n for (const entry of [...entries.values()]) {\n if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue\n retire(entry)\n stop(entry, 'reset')\n if (entry.range) clearEntry(entry)\n }\n // A reset is when the packetId -> repair-track mapping can change, so\n // re-arm the once-per-track warn for the new epoch.\n warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName))\n dispatch()\n })\n\n const removeLifecycleObserver = mc.addRepairLifecycleObserver((event) => {\n if (disposed) return\n if (event.type === 'reclassified') {\n const entry = entries.get(\n requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? undefined),\n )\n if (!entry || entry.priority !== 2) return\n const promoted = repairPriorityForClass(event.to)\n if (promoted >= entry.priority) return\n const wire = wirePriority(entry, event.to)\n // A block leaves P2 only for P0, whose request is never declined.\n if (wire === null) return\n entry.priority = promoted\n entry.subscriberPriority = wire.subscriberPriority\n // A block that turned out to carry a keyframe gets the keyframe budget\n // its request would have had (never a shorter deadline than it had).\n const promotedDeadline = presentationDeadlineAt(\n entry.sbn,\n entry.packetId,\n entry.catalogTrackName,\n performance.now(),\n event.to,\n )\n if (promotedDeadline !== null && promotedDeadline.deadlineAt > entry.deadlineAt) {\n entry.deadlineAt = promotedDeadline.deadlineAt\n entry.playoutDeadlineAt = Math.max(\n entry.playoutDeadlineAt,\n promotedDeadline.deadlineAt - promotedDeadline.extensionMs,\n )\n entry.anchorAt = promotedDeadline.anchorAt\n entry.delayMs = promotedDeadline.delayMs\n entry.bound = promotedDeadline.bound\n noteBudget(entry, promotedDeadline.extensionMs)\n }\n if (entry.running) {\n // The running FETCH carries the delta priority. Cancel it and send\n // the block's repair again under its new class (\u00A711.4.5): a keyframe\n // repair must not stay queued behind source media.\n stop(entry, 'reprioritized')\n start(entry, false)\n }\n dispatch()\n return\n }\n if (event.type === 'gap') {\n // mmt-02 5.3.3: a receiver cancels a repair it stops waiting for. A\n // frame the release gate forces out at its hold ceiling (a\n // discontinuity stall over blocks that never resolved) declares the\n // loss behind it, so every FETCH of that stream past its deadline is\n // cancelled here, inside the decision, before the frame leaves the\n // gate (MulticastManager emits the decision as a lifecycle event\n // synchronously from the gate's `decide`).\n if (event.action !== 'stall' || event.reason !== 'discontinuity') return\n const now = performance.now()\n let expired = false\n for (const entry of [...entries.values()]) {\n if (entry.packetId !== event.stream.packetId) continue\n if (entry.catalogTrackName !== (event.stream.catalogTrackName ?? undefined)) continue\n if (!entry.running || entry.deadlineAt > now) continue\n stop(entry, 'expired')\n retire(entry)\n clearEntry(entry)\n expired = true\n }\n if (expired) dispatch()\n return\n }\n if (event.type !== 'recovered' && event.type !== 'failed') return\n const entry = entries.get(\n requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? undefined),\n )\n if (!entry) return\n retire(entry)\n if (entry.running) stop(entry, 'resolved')\n else if (entry.priority === 2 && entry.attempts === 0) note('repair-deferred', entry)\n dispatch()\n })\n\n /**\n * The block's presentation deadline, or null when the player gives none.\n *\n * anchor + presentationDelay, clamped below by the multicast wait (the block\n * is open that long whatever happens, so a FETCH landing inside it still\n * counts) and above by anchor + the release gate's hold ceiling (a successor\n * frame may not wait behind a block longer than that). A block no symbol\n * reached has no anchor; its deadline is the multicast wait. The ceiling is\n * measured from the earlier of the anchor and the earliest frame the gate\n * holds for the stream (see the module note). A block that may hold a RAP\n * (`keyframeBudgetEligible`) uses the larger of the presentation delay and\n * the keyframe budget; `extensionMs` is how much later that made it.\n */\n const presentationDeadlineAt = (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n now: number,\n blockClass: BlockClass,\n ): ResolvedDeadline | null => {\n // Undefined: the packetId is no longer configured (released), so it has\n // no repair budget.\n const waitMs = mc.fecManager.repairFetchTimeoutMsForBlock(sbn, packetId, catalogTrackName)\n if (waitMs === undefined) return null\n const waitDeadlineAt = now + waitMs\n const anchor = mc.fecManager.blockAnchorAtMs(sbn, packetId, catalogTrackName)\n if (anchor === undefined) {\n return { deadlineAt: waitDeadlineAt, extensionMs: 0, anchorAt: null, delayMs: null, bound: 'wait' }\n }\n let delayMs: number\n try {\n delayMs = opts.presentationDelayMs(packetId, catalogTrackName)\n } catch {\n return null\n }\n if (!(Number.isFinite(delayMs) && delayMs > 0)) return null\n const retentionMs = mc.fecManager.terminalRetentionMsForPacket(packetId)\n if (retentionMs === undefined) return null\n const ceilingAt = Math.min(anchor, earliestGatedFrameAt(packetId, catalogTrackName) ?? anchor) + retentionMs\n const at = (\n delay: number,\n delayBound: 'presentation' | 'keyframe',\n ): { readonly deadlineAt: number; readonly bound: RepairDeadlineBound } => {\n const presentAt = Math.min(anchor + delay, ceilingAt)\n if (waitDeadlineAt >= presentAt) return { deadlineAt: waitDeadlineAt, bound: 'wait' }\n return { deadlineAt: presentAt, bound: anchor + delay <= ceilingAt ? delayBound : 'retention' }\n }\n const base = at(delayMs, 'presentation')\n const budgetMs =\n keyframeBudgetEligible(blockClass, classifierMode(packetId, catalogTrackName)) &&\n groupCanComplete(sbn, packetId, catalogTrackName)\n ? readKeyframeBudget(packetId, catalogTrackName)\n : null\n if (budgetMs === null || budgetMs <= delayMs) return { ...base, extensionMs: 0, anchorAt: anchor, delayMs }\n const extended = at(budgetMs, 'keyframe')\n return {\n ...extended,\n extensionMs: extended.deadlineAt - base.deadlineAt,\n anchorAt: anchor,\n delayMs: budgetMs,\n }\n }\n\n const earliestGatedFrameAt = (packetId: number, catalogTrackName: string | undefined): number | undefined => {\n try {\n const at = mc.earliestGatedFrameAtMs?.(packetId, catalogTrackName)\n return at !== undefined && Number.isFinite(at) ? at : undefined\n } catch {\n return undefined\n }\n }\n\n const classifierMode = (packetId: number, catalogTrackName: string | undefined): ClassifierMode | undefined => {\n try {\n return mc.fecManager.classifierModeFor?.(packetId, catalogTrackName).mode\n } catch {\n return undefined\n }\n }\n\n const noteBudget = (entry: Pick<RepairEntry, 'sbn' | 'packetId' | 'catalogTrackName'>, extensionMs: number): void => {\n if (extensionMs > 0) mc.noteKeyframeBudgetGranted?.(extensionMs, entry.sbn, entry.packetId, entry.catalogTrackName)\n }\n\n mc.onRepairSubscribe((sbn, packetId, catalogTrackName, blockClass) => {\n if (disposed) {\n clearRepair(sbn, packetId, catalogTrackName)\n return\n }\n // Throws on a wiring fault, here and synchronously, before anything is\n // queued (see blockProfileOf).\n const blockProfile = blockProfileOf(packetId)\n\n // Fire-time resolution \u2014 see ResolveRepairTarget.\n const target = opts.resolveTarget(packetId, catalogTrackName)\n if (!target) {\n // A starved block with no repair target can only resolve via the fail\n // bound. Say so, once per track: a null target is also the documented\n // answer for a rung that carries no repair, and the typed lifecycle\n // events already enumerate every block.\n const warnKey = noTargetKey(packetId, catalogTrackName)\n if (!warnedNoTarget.has(warnKey)) {\n warnedNoTarget.add(warnKey)\n console.warn(\n `[RepairFetch] no repair target for pid=${packetId} sbn=${sbn}` +\n `${catalogTrackName === undefined ? '' : ` track=${catalogTrackName}`}; releasing without a fetch`,\n )\n }\n clearRepair(sbn, packetId, catalogTrackName)\n return\n }\n\n const key = requestKey(sbn, packetId, catalogTrackName)\n const previous = entries.get(key)\n if (previous) {\n retire(previous)\n stop(previous, 'reset')\n }\n const identity = {\n target,\n sbn,\n packetId,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n }\n const wire = wirePriority(identity, blockClass)\n if (wire === null) {\n // No conformant FETCH exists for this block (see RepairFetchPriority).\n clearRepair(sbn, packetId, catalogTrackName)\n return\n }\n const now = performance.now()\n const priority = repairPriorityForClass(blockClass)\n const deadline = presentationDeadlineAt(sbn, packetId, catalogTrackName, now, blockClass)\n if (deadline === null) {\n clearRepair(sbn, packetId, catalogTrackName)\n mc.noteRepairSkipped(\n 'presentation-delay-unavailable',\n { rttMs: readRtt(), budgetMs: 0, priority },\n sbn,\n packetId,\n catalogTrackName,\n )\n return\n }\n const entry: RepairEntry = {\n key,\n ...identity,\n repairTrack: target.repairTrack,\n blockProfile,\n priority,\n subscriberPriority: wire.subscriberPriority,\n deadlineAt: deadline.deadlineAt,\n playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,\n anchorAt: deadline.anchorAt,\n delayMs: deadline.delayMs,\n bound: deadline.bound,\n order: enqueueOrder++,\n attempts: 0,\n running: null,\n }\n entries.set(key, entry)\n noteBudget(entry, deadline.extensionMs)\n dispatch()\n })\n\n /**\n * \u00A77.5 range for a lost SS_ID: from ext(S_prev) when a stated block ends\n * where the hole starts, else from the epoch reference r. Null when there\n * is no r, or the lost SS_ID cannot be extended from it.\n */\n const rangeFor = (loss: UndelimitedIsoLoss, repairTrack: string): RepairFetchRange | null => {\n let reference: bigint | undefined\n try {\n reference = opts.repairEpochReference!(repairTrack)\n } catch {\n return null\n }\n if (reference === undefined) return null\n try {\n const anchor = loss.previousBlockStart === undefined\n ? { reference }\n : { previousBlockStart: extendSsId(reference, loss.previousBlockStart) }\n return repairFetchRange(loss.lostSsId, loss.kMax, anchor)\n } catch (error) {\n if (error instanceof RangeError) return null\n throw error\n }\n }\n\n const trackKind = (packetId: number): TrackKind | undefined => {\n try {\n return mc.fecManager.trackKindFor?.(packetId)\n } catch {\n return undefined\n }\n }\n\n /**\n * Where a walk of a hole reported `now` ends: WALK_LEAD_MS before the span\n * it leaves asks for its repair (D-28 from the report, as the span a host\n * without holes opened then did), so that span's request is armed before\n * it is due and goes out at the same time; never later than `deadlineAt`.\n */\n const walkDeadlineAt = (packetId: number, now: number, deadlineAt: number): number => {\n let repairDeadlineMs: number | undefined\n try {\n repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId)\n } catch {\n repairDeadlineMs = undefined\n }\n if (repairDeadlineMs === undefined || !Number.isFinite(repairDeadlineMs)) return deadlineAt\n return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS)\n }\n\n /**\n * The stream ran past the locator's horizon behind a hole: no repair can\n * state its blocks any more. A walking hole's walk ends and the hole closes\n * as at its deadline, so the span it leaves fails, and is reported, as the\n * span opened at its report would have (BLO-52085); the host discards any\n * other. Called from inside the stream's packet handling, so the walk ends\n * once that returns, as for a RAP (below).\n */\n const onHoleExpired = (hole: ExpiredIsoHole): boolean => {\n if (disposed) return false\n const entry = [...entries.values()].find((candidate) =>\n candidate.walk !== undefined &&\n candidate.packetId === hole.packetId &&\n candidate.catalogTrackName === hole.catalogTrackName &&\n serial32Distance(candidate.sbn, hole.holeStart) < candidate.range!.holeLength)\n if (entry === undefined) return false\n queueMicrotask(() => {\n if (entries.get(entry.key) !== entry) return\n retire(entry)\n stop(entry, 'expired')\n clearEntry(entry)\n dispatch()\n })\n return true\n }\n\n // A host that can keep a hole gets range repair: the \u00A77.7 range over\n // `rangeTransport`, or else a walk of the hole's Groups over `transport`.\n if (mc.onUndelimitedLoss !== undefined && mc.closeIsoHoles !== undefined) {\n mc.onUndelimitedLoss((loss) => {\n const { packetId, catalogTrackName, holeStart, holeLength } = loss\n const close = (): void => mc.closeIsoHoles!(packetId, catalogTrackName, holeStart, holeLength)\n if (disposed) return close()\n const blockProfile = blockProfileOf(packetId)\n const target = opts.resolveTarget(packetId, catalogTrackName)\n if (!target) return close()\n // The run's class (fec-multicast-00 Block Classification, Audio\n // Blocks): walked, a hole on an audio track is audio repair, one Group\n // per FETCH; any other is of unknown class, so keyframe repair.\n const walked = opts.rangeTransport === undefined\n const holeClass: BlockClass = walked && trackKind(packetId) === 'audio' ? 'audio' : 'unknown'\n const priority = repairPriorityForClass(holeClass)\n const groups = walked ? null : rangeFor(loss, target.repairTrack)\n if (!walked && groups === null) {\n close()\n mc.noteRepairSkipped('range-no-anchor', { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName)\n return\n }\n const identity = {\n target,\n sbn: holeStart,\n packetId,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n }\n // `unknown` is P0, whose request is never declined (omitted at worst);\n // an audio FETCH the catalog gives no priority for is not sent.\n const wire = wirePriority(identity, holeClass)\n if (wire === null) return close()\n // The hole is no tracked block: no anchor, so this is the multicast\n // wait (`bound: 'wait'`), by intent. A hole holds the release gate, so it\n // must not wait out a presentation delay on top.\n const now = performance.now()\n const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass)\n if (deadline === null) {\n close()\n mc.noteRepairSkipped(\n 'presentation-delay-unavailable',\n { rttMs: readRtt(), budgetMs: 0, priority },\n holeStart,\n packetId,\n catalogTrackName,\n )\n return\n }\n const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt\n const entry: RepairEntry = {\n key: JSON.stringify(['range', packetId, catalogTrackName ?? null, holeStart]),\n ...identity,\n repairTrack: target.repairTrack,\n blockProfile,\n priority,\n subscriberPriority: wire.subscriberPriority,\n deadlineAt,\n playoutDeadlineAt: deadlineAt - deadline.extensionMs,\n anchorAt: deadline.anchorAt,\n delayMs: deadline.delayMs,\n bound: deadline.bound,\n order: enqueueOrder++,\n attempts: 0,\n running: null,\n range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },\n ...(walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}),\n }\n const previous = entries.get(entry.key)\n if (previous) {\n retire(previous)\n stop(previous, 'reset')\n }\n entries.set(entry.key, entry)\n entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1)\n dispatch()\n }, onHoleExpired)\n }\n\n // A RAP arrived complete: a keyframe FETCH below it is moot (\u00A711.4.2). The\n // observer runs inside the frame push, so the cancel waits for a microtask\n // rather than re-entering the FEC layer through the hold release.\n const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {\n queueMicrotask(() => {\n if (disposed) return\n for (const entry of [...entries.values()]) {\n if (entry.packetId !== packetId || !entry.running) continue\n if (moot(entry)) dropMoot(entry)\n else mootAtPlayout(entry)\n }\n dispatch()\n })\n })\n\n // fec-multicast-00 \u00A76.6: once the overlay recovered a block's RAP (its FT=0\n // and FT=1 held), the rest of the block is concealed as a non-keyframe\n // block, so its keyframe FETCH is stopped whatever its deadline. Deferred\n // as the RAP observer is: this fires from inside the recovered-block route.\n const removeOverlayObserver = mc.addKeyframeOverlayRecoveredObserver?.((packetId, catalogTrackName, sbn) => {\n queueMicrotask(() => {\n if (disposed) return\n for (const entry of [...entries.values()]) {\n if (entry.range || entry.priority !== 0 || entry.packetId !== packetId || entry.sbn !== sbn) continue\n if (catalogTrackName !== undefined && entry.catalogTrackName !== catalogTrackName) continue\n stop(entry, 'overlay-recovered')\n retire(entry)\n releaseHold(entry)\n clearEntry(entry)\n }\n dispatch()\n })\n })\n\n return () => {\n disposed = true\n mc.setUnicastRepair?.(false)\n removeResetObserver()\n removeLifecycleObserver()\n removeRapObserver?.()\n removeOverlayObserver?.()\n for (const entry of [...entries.values()]) {\n clearEntry(entry)\n if (entry.running) releaseHold(entry)\n stop(entry, 'disposed')\n if (entry.expiry !== undefined) clearTimeout(entry.expiry)\n }\n entries.clear()\n }\n}\n", "/**\n * Keyframe-protected FEC repair policy.\n *\n * Every FEC block still gets in-band FEC decode. What this module decides is\n * (1) which blocks may hold a keyframe (RAP), so a block short of K at its\n * repair deadline can be repaired over QUIC with the right priority, and\n * (2) what a sink must do with the first frame released after a gap: stall\n * until the next RAP, or conceal and keep playing.\n *\n * The two decisions are deliberately independent. Classification only sets\n * repair priority. The stall/conceal decision is made again per released gap\n * from the media that is actually missing, so a wrong classification can only\n * lower a block's repair priority; it can never make playback wrong.\n *\n * Everything here is derived from catalog-authored timing and in-band MMTP\n * evidence. There are no timers, no cadence heuristics, and no defaults: a\n * track whose geometry cannot be derived exactly runs in the defined\n * fail-closed mode `all-protected`, where the window rule is off: a block is\n * treated as possibly keyframe-bearing unless the MPU numbers of the DU\n * headers held around it show otherwise (the MPU rule). That rule needs no\n * block geometry, but it classes nothing on a track whose catalog does not\n * state a keyframe interval equal to its group duration.\n *\n * All three players (moqtail, hang, Shaka) consume this one implementation.\n */\n\nimport { deriveFecInterleaveDepth } from '@blockcast/mmt-fec'\n\n// \u2500\u2500\u2500 Classes and priorities \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 * Repair class of one FEC block.\n *\n * - `keyframe`: the block holds (or held) a RAP / MPU start.\n * - `delta`: the block provably holds only non-RAP video frames.\n * - `unknown`: neither could be proven; treated exactly like `keyframe`.\n * - `audio`: an audio block.\n */\nexport type BlockClass = 'keyframe' | 'delta' | 'unknown' | 'audio'\n\n/** Repair priority. Lower is more urgent. */\nexport type RepairPriority = 0 | 1 | 2\n\nexport type TrackKind = 'video' | 'audio'\n\n/** P0 = keyframe/unknown (stall-preventing), P1 = audio, P2 = delta. */\nexport function repairPriorityForClass(blockClass: BlockClass): RepairPriority {\n switch (blockClass) {\n case 'keyframe':\n case 'unknown':\n return 0\n case 'audio':\n return 1\n case 'delta':\n return 2\n }\n}\n\n// \u2500\u2500\u2500 Geometry \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\nexport type ClassifierMode = 'classifying' | 'all-protected'\n\n/** Why a track runs `all-protected`. */\nexport type ClassifierReason =\n // Geometry (catalog) reasons.\n | 'framerate-absent'\n | 'keyframe-cadence-absent'\n | 'keyframe-interval-not-integral'\n | 'block-spans-gop'\n /**\n * The catalog keyframe interval is not an exact integer number of ticks\n * in the media track's own timescale (ISO-BMFF `mdhd`), so released RAP\n * spacing cannot be verified and hold-last cannot predict the next RAP.\n * Nothing is wrong with the stream; the cadence is simply unprovable.\n */\n | 'keyframe-interval-not-media-integral'\n /**\n * Another stream on this packetId was configured with its own geometry\n * and this one was not, so no geometry provably belongs to it (ABR rungs\n * sharing a packetId).\n */\n | 'stream-geometry-absent'\n // In-band invariant violations (positive evidence only).\n | 'rap-not-mpu-start'\n | 'mpu-longer-than-gop'\n | 'block-not-contiguous'\n /**\n * MPU-start RAPs are not exactly one keyframe interval apart per MPU:\n * released RAPs in the media timescale, or, once each frame is its own\n * movie fragment, RAP fragments G fragments apart per MPU (P3).\n */\n | 'rap-spacing-mismatch'\n /**\n * An MPU of several movie fragments whose fragments hold several samples:\n * neither sample_number nor the fragment number states a frame's MPU\n * position (P3).\n */\n | 'mpu-multiple-fragments'\n | 'block-wider-than-interleave'\n\n/** Raw catalog timing for one track. Never a resolved cadence. */\nexport interface BlockClassifierGeometryInput {\n readonly trackKind: TrackKind\n /** Catalog `framerate` (frames per second). */\n readonly framerate?: number\n /** Catalog `fec.interleaveDepthMs`: the full FEC block span (\u00A75.1). */\n readonly interleaveDepthMs: number\n /** Catalog track `timescale` for `keyframeIntervalTicks`. */\n readonly timescale?: number\n /** Catalog `keyframeIntervalTicks` (preferred when the timescale is present). */\n readonly keyframeIntervalTicks?: number\n /** Catalog `keyframeIntervalMs`. */\n readonly keyframeIntervalMs?: number\n /**\n * The track's catalog group duration in ms (`catalogGroupDurationMs`: the\n * tick form over the timescale where the catalog states it, so it may be a\n * fraction). Never a cadence. It is only compared with the keyframe\n * interval: the MPU rule classes nothing unless the two are equal.\n */\n readonly groupDurationMs?: number\n}\n\n/** Exact keyframe interval as a rational number of seconds: ticks / timescale. */\nexport interface KeyframeInterval {\n readonly ticks: number\n readonly timescale: number\n}\n\nexport type BlockClassifierGeometry =\n | { readonly trackKind: 'audio' }\n | {\n readonly trackKind: 'video'\n readonly mode: 'classifying'\n /** F: one frame's duration in milliseconds (1000 / framerate). */\n readonly frameDurationMs: number\n /** D: media units per FEC block (deriveFecInterleaveDepth). */\n readonly interleaveUnits: number\n /** G: frames per GOP. */\n readonly gopFrames: number\n readonly keyframeInterval: KeyframeInterval\n /** The catalog group duration in ms, when stated (the MPU rule's catalog test). */\n readonly groupDurationMs?: number\n }\n | {\n readonly trackKind: 'video'\n readonly mode: 'all-protected'\n readonly reason: ClassifierReason\n /** The catalog interval when one is stated: gap decisions use it (keyframeInstantBetween). */\n readonly keyframeInterval?: KeyframeInterval\n /** The catalog group duration in ms, when stated (the MPU rule's catalog test). */\n readonly groupDurationMs?: number\n }\n\n/**\n * Integer value of `numerator / denominator` when it is one, else null.\n *\n * Catalog framerates are JSON numbers, so an NTSC rate arrives as the double\n * nearest 30000/1001. One multiply and one divide each add at most half an\n * ulp of relative error (IEEE-754), so a quotient within two ulps of an\n * integer IS that integer; anything further is genuinely non-integral.\n */\nfunction exactInteger(numerator: number, denominator: number): number | null {\n if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator === 0) {\n return null\n }\n const quotient = numerator / denominator\n const rounded = Math.round(quotient)\n if (rounded < 1) return null\n const representationError = 2 * Number.EPSILON * Math.abs(quotient)\n return Math.abs(quotient - rounded) <= representationError ? rounded : null\n}\n\nfunction isPositiveFinite(value: number | undefined): value is number {\n return value !== undefined && Number.isFinite(value) && value > 0\n}\n\n/**\n * Derive the per-track classifier geometry from raw catalog fields.\n *\n * `all-protected` is the policy's defined fail-closed state, not a default:\n * it is returned with the exact reason. It turns the window rule off; the\n * MPU rule can still class a block `delta` where the catalog states a\n * keyframe interval equal to the group duration (`mpuRuleCatalogReason`).\n * A `classifying` geometry whose catalog does not state that gets no `delta`\n * either: the window rule classes only on a track the MPU rule applies to.\n * The only throw is for a value the catalog validator already rejects (a\n * non-positive block span).\n */\nexport function deriveBlockClassifierGeometry(\n input: BlockClassifierGeometryInput,\n): BlockClassifierGeometry {\n if (!isPositiveFinite(input.interleaveDepthMs)) {\n throw new Error(\n `[BlockPolicy] interleaveDepthMs=${input.interleaveDepthMs} is not a positive block span; ` +\n 'the catalog validator rejects this',\n )\n }\n if (input.trackKind === 'audio') return { trackKind: 'audio' }\n\n // Every video geometry keeps the catalog interval: gap decisions need it in\n // either mode (fec-multicast-00 Block Classification item 3).\n let keyframeInterval: KeyframeInterval | undefined\n if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {\n keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale }\n } else if (isPositiveFinite(input.keyframeIntervalMs)) {\n keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1000 }\n }\n const groupDuration = isPositiveFinite(input.groupDurationMs) ? { groupDurationMs: input.groupDurationMs } : {}\n const protect = (reason: ClassifierReason): BlockClassifierGeometry => ({\n trackKind: 'video',\n mode: 'all-protected',\n reason,\n ...(keyframeInterval === undefined ? {} : { keyframeInterval }),\n ...groupDuration,\n })\n\n if (!isPositiveFinite(input.framerate)) return protect('framerate-absent')\n const framerate = input.framerate\n if (keyframeInterval === undefined) return protect('keyframe-cadence-absent')\n\n const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale)\n if (gopFrames === null) return protect('keyframe-interval-not-integral')\n\n const frameDurationMs = 1000 / framerate\n const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs)\n if (interleaveUnits >= gopFrames) return protect('block-spans-gop')\n\n return {\n trackKind: 'video',\n mode: 'classifying',\n frameDurationMs,\n interleaveUnits,\n gopFrames,\n keyframeInterval,\n ...groupDuration,\n }\n}\n\n/**\n * Why the MPU rule classes no block on a track (`BlockClassifier.mpuRuleOff`).\n * Under every reason but the last the window rule classes none either: the\n * track gets no `delta` (fec-multicast-01 Block Classification).\n *\n * The first three are the catalog's: it does not state that the publisher\n * keeps one RAP to an MPU. It carries no usable keyframe interval (none, or\n * one that is not a whole number of its unit), no group duration, or two that\n * differ. The rest are what the stream showed. Each lasts for the epoch but\n * the last, which ends at the next source discontinuity.\n */\nexport type MpuRuleOffReason =\n | 'keyframe-interval-absent'\n | 'group-duration-absent'\n | 'keyframe-interval-not-group-duration'\n /** A DU header carried RAP_flag and was not the first sample of its movie fragment, or was held and lay in another fragment than the first header held of its MPU. */\n | 'rap-inside-mpu'\n /** An MPU held a sample one keyframe interval or more after another, by decode time. */\n | 'mpu-longer-than-keyframe-interval'\n /** `mpuBoundsRaps` went false (see `BlockClassifier.mpuBoundsRaps`). */\n | 'mpu-bounds-raps-refuted'\n /** Two DU headers lay in blocks against their authored order. */\n | 'du-headers-out-of-order'\n\nfunction isPositiveSafeInteger(value: number): boolean {\n return Number.isSafeInteger(value) && value > 0\n}\n\n/**\n * The catalog's side of the MPU rule (fec-multicast-01 Block Classification):\n * a keyframe interval equal to the group duration is the publisher's\n * statement that every MPU of the track holds one RAP, its first sample. A\n * packet does not say so, and a publisher of an earlier revision could put\n * more RAPs in an MPU. Null when the catalog states it, else what is missing.\n *\n * Integers compare exactly, as rationals: ticks / timescale against ms / 1000.\n * A group duration that the catalog states in ticks reaches here as the\n * double nearest ticks / timescale * 1000. Each side then carries at most two\n * roundings, so the two are equal when they differ by no more than\n * 2 * Number.EPSILON of the group duration (as exactInteger reads a quotient).\n */\nfunction mpuRuleCatalogReason(\n geometry: Extract<BlockClassifierGeometry, { trackKind: 'video' }>,\n): MpuRuleOffReason | null {\n const interval = geometry.keyframeInterval\n if (\n interval === undefined ||\n !isPositiveSafeInteger(interval.ticks) ||\n !isPositiveSafeInteger(interval.timescale)\n ) {\n return 'keyframe-interval-absent'\n }\n const groupMs = geometry.groupDurationMs\n if (!isPositiveFinite(groupMs)) return 'group-duration-absent'\n const { ticks, timescale } = interval\n const equal = Number.isSafeInteger(groupMs)\n ? BigInt(ticks) * 1000n === BigInt(groupMs) * BigInt(timescale)\n : Math.abs((ticks / timescale) * 1000 - groupMs) <= 2 * Number.EPSILON * groupMs\n return equal ? null : 'keyframe-interval-not-group-duration'\n}\n\n/**\n * The keyframe interval expressed in a media track's timescale, or null when\n * the geometry states none or the interval is not an exact integer number of\n * media ticks (fec-multicast-00 Block Classification item 3: an inexact one\n * gives no usable interval).\n */\nexport function keyframeIntervalMediaTicks(\n geometry: BlockClassifierGeometry,\n mediaTimescale: number,\n): bigint | null {\n if (geometry.trackKind !== 'video' || geometry.keyframeInterval === undefined) return null\n if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null\n const { ticks, timescale } = geometry.keyframeInterval\n if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null\n const scaled = BigInt(ticks) * BigInt(mediaTimescale)\n const divisor = BigInt(timescale)\n if (scaled % divisor !== 0n) return null\n return scaled / divisor\n}\n\n/**\n * fec-multicast-00 Block Classification item 3 for two released frames:\n * whether `(from, to]` holds `start + k * interval` for some k >= 1, `start`\n * the decode time of an MPU's first RAP, all in one media timescale. `from`\n * is exclusive: the frame at `from` is held and complete, so an instant there\n * is that frame itself (an on-cadence RAP), not a lost one. The draft's closed\n * interval is for bounding packets, which may be part of a RAP.\n */\nexport function keyframeInstantBetween(start: bigint, interval: bigint, from: bigint, to: bigint): boolean {\n const k = from >= start ? (from - start) / interval + 1n : 1n\n return start + k * interval <= to\n}\n\n// \u2500\u2500\u2500 Evidence \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 * In-band evidence from ONE first-arrival source symbol received from the\n * network. Repair symbols never contribute, and the MFU `priority > 0x80`\n * hint is not evidence. A recovered symbol is no evidence for its own block\n * and supports no class by the window rule; its DU header alone bounds the\n * blocks around it for the MPU rule (BlockClassifier.observeRecovered).\n */\nexport interface SourceSymbolEvidence {\n /** The MMTP header R (RAP) bit. */\n readonly rap: boolean\n /** MPU_sequence_number, when parsed from this packet. */\n readonly mpu?: number\n /**\n * 0-based sample position within its movie fragment: the MFU DU-header\n * `sample_number` minus one (ISO/IEC 23008-1 numbers samples from 1, and\n * the parser rejects `sample_number` 0). Present only when this packet\n * carried a DU header. It is the MPU position only while the MPU is one\n * movie fragment; BlockClassifier derives MPU positions (P3).\n */\n readonly idx?: number\n /**\n * movie_fragment_sequence_number from the DU header, when present. When\n * each frame is its own fragment, it positions the frame from its MPU's\n * RAP fragment (P3).\n */\n readonly movieFragment?: number\n /**\n * DU-header `offset`: the data unit's authored byte position within its\n * sample (0 for a whole-sample data unit, the partition boundary for a\n * subsample data unit). Present only with `idx`; absent reads as 0.\n */\n readonly offset?: number\n /**\n * The MMTP header packet_sequence_number (contiguous per packet_id). Not\n * classification evidence: FECManager uses it to bound how many blocks the\n * producer can have started between two source symbols, so an outage is\n * never mistaken for a source restart. A hop may write it anew on every\n * packet it forwards (cast's bridge does), so a gap in it, or none, says\n * nothing of what was lost before that hop.\n */\n readonly packetSequenceNumber?: number\n /**\n * DU-header `dep_counter` (ISO/IEC 23008-1 `dependency_counter`). Carried\n * for whoever wants to see it. Nothing here reads it: no class and no gap\n * decision changes with its value.\n */\n readonly depCounter?: number\n}\n\n/**\n * What moved a block's class. `mpu-rule`: the MPU numbers of the DU headers\n * held before and after the block show that it holds no part of a RAP.\n */\nexport type ReclassificationEvidence =\n | 'rap'\n | 'mpu-span'\n | 'window'\n | 'mpu-rule'\n /**\n * @deprecated Never emitted. It named the dependent run in `dep_counter`,\n * which no longer classes a block. The name stays so that a consumer that\n * spells it still compiles and an event recorded earlier still validates.\n */\n | 'dependent-run'\n | 'classifier-disabled'\n\nexport type ClassifierChange =\n | {\n readonly kind: 'reclassified'\n readonly sbn: number\n readonly from: BlockClass\n readonly to: BlockClass\n readonly evidence: ReclassificationEvidence\n }\n | {\n readonly kind: 'mode'\n readonly mode: 'all-protected'\n readonly reason: ClassifierReason\n }\n\ninterface BlockEvidence {\n rapSeen: boolean\n mpus: Set<number>\n /** The lowest and highest MPU positions its DU headers proved (P3). */\n positionMin?: number\n positionMax?: number\n cls: BlockClass\n}\n\n/** A data-unit start (a packet carrying a DU header) and the block it is in. */\ninterface DataUnitStart {\n readonly movieFragment: number\n readonly idx: number\n readonly offset: number\n readonly sbn: number\n}\n\n/** A held DU header as the MPU rule reads it. */\ninterface HeldHeader extends DataUnitStart {\n readonly rap: boolean\n /**\n * Its FEC source symbol id when it arrived from the network. A header that\n * FEC rebuilt has none here: it is not counted as a packet that arrived.\n */\n readonly ssId?: number\n /** Its MPU position, where the wire proved one when it arrived (P3). */\n readonly position?: number\n}\n\n/**\n * Authored order of two data-unit starts of one MPU. Fragment numbers wrap\n * at 2^32, so they compare in RFC 1982 serial order.\n */\nfunction compareDataUnitStarts(\n a: Omit<DataUnitStart, 'sbn'>,\n b: Omit<DataUnitStart, 'sbn'>,\n): number {\n return ((a.movieFragment - b.movieFragment) | 0) || a.idx - b.idx || a.offset - b.offset\n}\n\n/** The first index of an SBN-ordered list whose block is `sbn` or later. */\nfunction firstStartAtOrAfter(starts: readonly HeldHeader[], sbn: number): number {\n let lo = 0\n let hi = starts.length\n while (lo < hi) {\n const mid = (lo + hi) >>> 1\n if (starts[mid]!.sbn < sbn) lo = mid + 1\n else hi = mid\n }\n return lo\n}\n\n/**\n * What arrived of one MPU. The MPU rule asks only about an MPU's start and\n * about its last packet, so that is all that is kept however long the MPU.\n */\ninterface ArrivedPackets {\n /** Source symbol id to block, for the first ARRIVED_START_MAX packets that arrived. */\n readonly start: Map<number, number>\n /** The highest source symbol id among those that arrived. */\n last: number\n}\n\n/** More packets than an MPU's metadata and first sample take; a longer start proves nothing. */\nconst ARRIVED_START_MAX = 4096\n\n/** The first DU header after `headers[at]`, in authored order, of another sample. */\nfunction nextSampleHeader(headers: readonly HeldHeader[], at: number): HeldHeader | undefined {\n const of = headers[at]!\n for (let i = at + 1; i < headers.length; i++) {\n const header = headers[i]!\n if (header.movieFragment !== of.movieFragment || header.idx !== of.idx) return header\n }\n return undefined\n}\n\n/**\n * How many MPUs behind the newest released RAP a stale release can be. The\n * release gate holds a frame for seconds at most, so a late copy is a few\n * MPUs back; anything further is another MPU sequence. With MPUs so short\n * that a late copy lies further back, it re-anchors there: the newest MPU's\n * gaps read rap-unknown until the next MPU's RAP, never a wrong measure.\n */\nconst LATE_RAP_MAX_MPUS_BACK = 64\n\n/** One MPU's movie fragments (P3). */\ninterface MpuLayout {\n /** Serial-earliest movie_fragment_sequence_number of its DU headers. */\n low: number\n /** The fragment of its first RAP-flagged DU header: position 0. */\n anchor?: number\n}\n\n/** What one DU header proves about its MPU (BlockClassifier `#place`). */\ninterface Placement {\n /** Its 0-based MPU position, when the wire proves it. */\n readonly position?: number\n /**\n * It shows a RAP inside an MPU, or an MPU longer than G: MPU boundaries\n * no longer bound the stream's RAPs (`rap-not-mpu-start`).\n */\n readonly rapNotMpuStart: boolean\n /** A refuted layout premise. */\n readonly violation?: ClassifierReason\n}\n\nconst UNPLACED: Placement = { rapNotMpuStart: false }\n\n/**\n * Per-stream block classifier.\n *\n * Classes only move toward more protection or narrower evidence:\n * `unknown\u2192delta` and `unknown\u2192keyframe` / `delta\u2192keyframe` on evidence, and\n * `delta\u2192unknown` when an invariant disables classification. `keyframe` is\n * terminal.\n *\n * The delta window rule classes a block only on a track the MPU rule applies\n * to: one whose catalog passes that rule's test and that has shown neither a\n * RAP inside an MPU nor an MPU longer than the keyframe interval\n * (`mpuRuleOff`). It rests on three premises, each guarded by an invariant\n * that fires on positive evidence only:\n *\n * - P1: the source packets of one block are one contiguous run of the\n * stream's authored order, and blocks follow each other in SBN order\n * (`block-not-contiguous`). The producer assigns SS_IDs in authored order\n * and a block is the SS_ID range [SBN*K, SBN*K + K), so this holds for a\n * block that closes at K symbols in the middle of a frame: that frame's\n * fragments then land in two ADJACENT blocks, which is still one run each.\n * A frame split across adjacent blocks is not a violation.\n * - P2: that run touches at most D media units, counting a frame continued\n * from the previous block (`block-wider-than-interleave`). The producer\n * counts a media-unit boundary only once the open block holds a symbol.\n * - P3: an MPU starts with its only RAP and holds at most G frames\n * (`rap-not-mpu-start`, `mpu-longer-than-gop`, `rap-spacing-mismatch`),\n * and its DU headers state each frame's MPU position in one of two layouts\n * (`mpu-multiple-fragments` when an MPU shows two fragments and a DU\n * header states sample_number above 1, which is neither):\n * - one movie fragment per MPU (ATSC 3.0): the position is\n * sample_number \u2212 1. This is the rule until some MPU of the sequence\n * shows two fragments.\n * - one fragment per frame, numbered one per frame (FFmpeg's MoQ MMT\n * muxer, every DU header stating sample_number 1): the position is the\n * fragment's distance from the fragment of the MPU's first RAP-flagged\n * DU header (its anchor). The RAP's own fragment is position 0. Each\n * anchor must lie exactly G fragments per MPU from the anchor received\n * before it, which is kept past the horizon, and from the anchor\n * received last (`rap-spacing-mismatch`, as after a dropped frame).\n * Once two anchors kept that spacing, fragment numbers count frames:\n * later fragments get positions, and an anchor arriving past the\n * spacing is a RAP inside its MPU or follows an MPU longer than G\n * (`rap-not-mpu-start`). An MPU whose anchor was not received has no\n * positions; its blocks stay unknown. A second RAP-flagged fragment, or\n * a DU header in a fragment before the anchor, refutes the MPU start\n * (`rap-not-mpu-start`).\n *\n * P1 and P2 are what make a block's frames contiguous and lie within\n * [positionMax \u2212 D + 1, positionMin + D \u2212 1] of its MPU. What refutes P1 is\n * a pair of source packets whose wire-stated authored order and SBN order\n * disagree: a later MPU in an earlier block, a later data unit of one MPU\n * (by movie_fragment_sequence_number, sample_number, then DU offset) in an\n * earlier block, or one data unit in two blocks. That is the signature of a\n * round-robin interleave, which scatters one run over several concurrent\n * blocks. Non-adjacency alone is not: a sample larger than K packets\n * legitimately spans blocks SBN..SBN+n.\n */\nexport class BlockClassifier {\n #geometry: BlockClassifierGeometry\n #mode: ClassifierMode\n #reason: ClassifierReason | null\n /**\n * False once the stream showed that an MPU boundary does not bound its\n * RAPs (a RAP inside an MPU, or an MPU longer than a GOP). Recorded in\n * every mode: the stall/conceal decision relies on it even when the\n * catalog geometry already runs the classifier `all-protected`.\n */\n #mpuBoundsRaps = true\n #blocks = new Map<number, BlockEvidence>()\n /**\n * P1 ledger, kept for the MPUs within the classification horizon (the\n * highest MPU seen and the one before it): the SBN span of every source\n * packet of each MPU, and each MPU's data-unit starts in authored order.\n * Valid only within one continuous SBN sequence; a source discontinuity\n * clears it (`noteSourceDiscontinuity`).\n */\n #mpuSbnSpans = new Map<number, { min: number; max: number }>()\n #dataUnitStarts = new Map<number, DataUnitStart[]>()\n #highestMpu: number | null = null\n /**\n * The DU headers held, per MPU in authored order, for the MPU rule. Kept in\n * every mode (the rule needs no catalog cadence) for the same horizon and\n * the same continuous SBN sequence as the P1 ledger.\n */\n #headers = new Map<number, HeldHeader[]>()\n /**\n * The source packets that arrived, per MPU. The MPU rule asks it whether\n * every packet between two held DU headers arrived, and where. Same\n * horizon as the headers.\n */\n #arrived = new Map<number, ArrivedPackets>()\n #heldHighestMpu: number | null = null\n /** Two DU headers of this sequence lay in blocks against their authored order: the MPU rule proves nothing. */\n #headerOrderRefuted = false\n /**\n * A DU header held carried RAP_flag and was not of its MPU's first sample:\n * not the first sample of its movie fragment, or in another movie fragment\n * than the first DU header held of its MPU. This stream puts a RAP inside\n * an MPU, and neither rule proves anything for the rest of the epoch. It is\n * the MPU rule's own reading, in every DU-header layout and of rebuilt\n * headers too. The first case is read on a header of an MPU behind the two\n * kept as well. `mpuBoundsRaps`, which the stall or conceal decision reads,\n * is set as before and not from here.\n */\n #rapInsideMpu = false\n /** What the catalog lacks for the MPU rule, or null when it states a keyframe interval equal to the group duration. */\n #mpuRuleCatalog: MpuRuleOffReason | null = null\n /**\n * The lowest and highest decode time known in an MPU, for the two MPUs of\n * the highest numbers: those of the samples that held movie fragment\n * metadata times (noteDecodeTimes). Valid within one MPU sequence, as the\n * P1 ledger is; if MPU numbers go back with no source discontinuity, the\n * new ones are not read until then, as their DU headers are not.\n */\n #decodeSpans = new Map<number, { readonly min: bigint; readonly max: bigint; readonly mediaTimescale: number }>()\n /**\n * An MPU held a sample one keyframe interval or more after another by\n * decode time, so it lasts longer than the interval. A track of an earlier\n * revision whose interval equals its group duration can hold a further RAP\n * only in such an MPU: neither rule proves anything for the rest of the\n * epoch.\n */\n #mpuOutlastsInterval = false\n /**\n * P3 layout, kept for the MPUs within the classification horizon and valid\n * within one continuous SBN sequence (`noteSourceDiscontinuity`).\n */\n #mpus = new Map<number, MpuLayout>()\n /** An MPU of this sequence showed two movie fragments: each frame is one. */\n #fragmentPerFrame = false\n /** A DU header of this sequence stated sample_number above 1. */\n #multiSampleFragment = false\n /**\n * The anchor received last, whether or not its MPU is still in the\n * horizon. Each new anchor, and the anchor of every DU header's MPU, is\n * checked against it.\n */\n #lastAnchor: { mpu: number; fragment: number } | null = null\n /** Two anchors were exactly G fragments per MPU apart. */\n #fragmentsProven = false\n /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */\n #lastRap: { mpu: number; presentationTime: bigint; mediaTimescale: number; decodeTime?: bigint } | null = null\n\n constructor(geometry: BlockClassifierGeometry) {\n this.#geometry = geometry\n this.#mode = 'classifying'\n this.#reason = null\n this.reset(geometry)\n }\n\n get geometry(): BlockClassifierGeometry {\n return this.#geometry\n }\n\n get mode(): ClassifierMode {\n return this.#mode\n }\n\n get reason(): ClassifierReason | null {\n return this.#reason\n }\n\n /**\n * Whether \"same MPU on both sides of a gap\" still proves the gap held no\n * RAP. It stops holding for the rest of the epoch once a RAP was received\n * inside an MPU or an MPU ran longer than a GOP.\n */\n get mpuBoundsRaps(): boolean {\n return this.#mpuBoundsRaps\n }\n\n /**\n * Why the MPU rule classes no block on this track now, or null while it\n * can. A catalog reason is known from the start of the epoch; the others\n * name what the stream showed. A block the rule would have classed reads\n * `unknown` under every one of them, and so does one the window rule would\n * have classed, under every one but `du-headers-out-of-order`.\n */\n get mpuRuleOff(): MpuRuleOffReason | null {\n if (this.#mpuRuleCatalog !== null) return this.#mpuRuleCatalog\n if (this.#rapInsideMpu) return 'rap-inside-mpu'\n if (this.#mpuOutlastsInterval) return 'mpu-longer-than-keyframe-interval'\n if (!this.#mpuBoundsRaps) return 'mpu-bounds-raps-refuted'\n return this.#headerOrderRefuted ? 'du-headers-out-of-order' : null\n }\n\n /** Begin a fresh epoch (catalog change or track reset). */\n reset(geometry: BlockClassifierGeometry = this.#geometry): void {\n this.#geometry = geometry\n this.#blocks.clear()\n this.#clearContiguityLedger()\n this.#clearMpuLayout()\n this.#lastRap = null\n this.#mpuBoundsRaps = true\n this.#rapInsideMpu = false\n this.#mpuOutlastsInterval = false\n this.#mpuRuleCatalog = geometry.trackKind === 'video' ? mpuRuleCatalogReason(geometry) : null\n if (geometry.trackKind === 'video' && geometry.mode === 'all-protected') {\n this.#mode = 'all-protected'\n this.#reason = geometry.reason\n } else {\n this.#mode = 'classifying'\n this.#reason = null\n }\n }\n\n /**\n * Retire this classifier (its stream moves to a new catalog epoch). Every\n * block it had classified `delta` loses the evidence behind that class and\n * reads `unknown` from now on; the returned changes say so.\n */\n retire(): ClassifierChange[] {\n const changes: ClassifierChange[] = []\n for (const [sbn, block] of this.#blocks) {\n if (block.cls !== 'delta') continue\n block.cls = 'unknown'\n changes.push({\n kind: 'reclassified',\n sbn,\n from: 'delta',\n to: 'unknown',\n evidence: 'classifier-disabled',\n })\n }\n return changes\n }\n\n /**\n * The stream's SBN sequence restarted (FECManager source discontinuity:\n * a publisher restart, or the SS_ID space wrapped). Authored order and SBN\n * order are comparable only within one continuous sequence, and a\n * restarted publisher numbers MPUs and movie fragments again, so the P1\n * ledger and the P3 layout start again.\n */\n noteSourceDiscontinuity(): void {\n this.#clearContiguityLedger()\n this.#clearMpuLayout()\n // A restarted publisher numbers MPUs again: its first RAP is no second\n // RAP of the MPU the old sequence last released one in.\n this.#lastRap = null\n }\n\n /**\n * Register a block that exists without evidence of its own: a vanished\n * block, or one only repair symbols state. The DU headers already held\n * around it class it now (the MPU rule); no later header need come between\n * them to ask again.\n */\n touch(sbn: number): ClassifierChange[] {\n const changes: ClassifierChange[] = []\n this.#reclassify(sbn, this.#blockFor(sbn), changes)\n return changes\n }\n\n /** Forget a resolved block. */\n forget(sbn: number): void {\n this.#blocks.delete(sbn)\n }\n\n classOf(sbn: number): BlockClass {\n if (this.#geometry.trackKind === 'audio') return 'audio'\n return this.#blocks.get(sbn)?.cls ?? 'unknown'\n }\n\n /**\n * Record one first-arrival source symbol's evidence for block `sbn`.\n * `ssId` is its FEC source symbol id (the block's SS_Start plus its ESI,\n * ISO/IEC 23008-1 C.5.2). The publisher numbers the packets of the FEC\n * flow with it, one each, so the MPU rule reads from it whether every\n * packet between two DU headers arrived. Without it the rule's two\n * exceptions prove nothing.\n */\n observe(sbn: number, evidence: SourceSymbolEvidence, ssId?: number): ClassifierChange[] {\n if (this.#geometry.trackKind === 'audio') return []\n const changes: ClassifierChange[] = []\n const block = this.#blockFor(sbn)\n const placement = this.#place(evidence)\n\n if (evidence.rap) block.rapSeen = true\n if (evidence.mpu !== undefined) block.mpus.add(evidence.mpu)\n const { position } = placement\n if (position !== undefined) {\n block.positionMin =\n block.positionMin === undefined ? position : Math.min(block.positionMin, position)\n block.positionMax =\n block.positionMax === undefined ? position : Math.max(block.positionMax, position)\n }\n\n // A RAP inside an MPU refutes \"an MPU boundary bounds RAPs\" whatever the\n // classifier mode, because gap decisions rely on it in every mode.\n if (placement.rapNotMpuStart) this.#refuteMpuBounds(changes)\n\n const violation = this.#checkInvariants(sbn, block, evidence, placement)\n if (violation !== null) changes.push(...this.#disable(violation))\n\n this.#noteArrived(sbn, evidence.mpu, ssId)\n const bounds = this.#noteHeader(sbn, evidence, position, ssId, changes)\n this.#reclassify(sbn, block, changes)\n // A new DU header can bound any block held: it may have had its last\n // symbol already.\n if (bounds) this.#reclassifyOthers(sbn, changes)\n return changes\n }\n\n /**\n * A first-arrival source symbol placed in a repair-less span (IsoBlockLocator:\n * the SS_IDs between two stated blocks whose every repair was lost). A span\n * is no block: it can hold several producer blocks, so nothing block-scoped\n * is read from it (no record, P1, P2 or MPU-rule bound) and its blocks stay\n * unknown. What its DU header says of its MPU (P3) still counts (BLO-57323).\n */\n observeInSpan(evidence: SourceSymbolEvidence): ClassifierChange[] {\n if (this.#geometry.trackKind === 'audio') return []\n const changes: ClassifierChange[] = []\n const placement = this.#place(evidence)\n if (placement.rapNotMpuStart) this.#refuteMpuBounds(changes)\n const geometry = this.#geometry\n if (this.#mode === 'all-protected' || geometry.mode !== 'classifying') return changes\n if (placement.rapNotMpuStart) changes.push(...this.#disable('rap-not-mpu-start'))\n else if (placement.position !== undefined && placement.position >= geometry.gopFrames) {\n changes.push(...this.#disable('mpu-longer-than-gop'))\n } else if (placement.violation !== undefined) changes.push(...this.#disable(placement.violation))\n return changes\n }\n\n /**\n * The DU header of a source packet that a decode rebuilt, in block `sbn`.\n * It bounds the blocks around that block for the MPU rule as a header that\n * arrived does: the rule reads the DU headers the receiver holds. The\n * rebuilt block is whole, so it gets no class and no record, and the\n * packet is no evidence for P1 or P3, which rest on what arrived: it\n * supports no class by the window rule, and can only end it. It is not\n * counted as a packet that arrived either (#arrivedBetween).\n */\n observeRecovered(sbn: number, evidence: SourceSymbolEvidence): ClassifierChange[] {\n if (this.#geometry.trackKind === 'audio') return []\n const { mpu, idx, movieFragment } = evidence\n if (mpu === undefined || idx === undefined || movieFragment === undefined) return []\n const changes: ClassifierChange[] = []\n // A second sample in a movie fragment is a fact of the stream whoever\n // shows it. Fragment numbers stop counting samples, and where an MPU has\n // shown two fragments the layout the window rule stands on is gone: say\n // so now, as #place does for a header that arrives.\n if (idx !== 0) {\n this.#multiSampleFragment = true\n const geometry = this.#geometry\n if (this.#fragmentPerFrame && geometry.trackKind === 'video' && geometry.mode === 'classifying') {\n changes.push(...this.#disable('mpu-multiple-fragments'))\n }\n }\n if (this.#noteHeader(sbn, evidence, this.#positionHeld(mpu, idx, movieFragment), undefined, changes)) {\n this.#reclassifyOthers(sbn, changes)\n }\n return changes\n }\n\n /**\n * Decode times the receiver can determine: `first` and `last` are those of\n * the first and the last sample that one held movie fragment's metadata\n * (FT=1) times, of MPU `mpu`, in ticks of `mediaTimescale`; a `trun` lists\n * samples in decode order, so `first` is not after `last`. They are read\n * for one thing, and only on a track the MPU rule applies to: an MPU with\n * two samples a keyframe interval or more apart lasts longer than the\n * interval, so its first sample need not be its only RAP. The rule then\n * stops for the rest of the epoch, the window rule with it, and every delta\n * class goes (fec-multicast-01 Block Classification). No class comes from\n * a decode time. The MPU's first sample is never later than the earliest\n * one known, so the known span is no longer than the real one.\n */\n noteDecodeTimes(mpu: number, first: bigint, last: bigint, mediaTimescale: number): ClassifierChange[] {\n const changes: ClassifierChange[] = []\n const geometry = this.#geometry\n if (geometry.trackKind !== 'video' || this.#mpuRuleCatalog !== null || !isPositiveSafeInteger(mediaTimescale)) {\n return changes\n }\n const held = this.#decodeSpans.get(mpu)\n // Ticks of another timescale are another clock: the MPU's span starts again.\n const known = held?.mediaTimescale === mediaTimescale ? held : undefined\n let late = false\n if (held === undefined && this.#decodeSpans.size >= 2) {\n // Kept by MPU number, as the DU headers are: the two highest. A report for an MPU behind both is late (a\n // slow repair) and must not push out the MPU the stream is in: it is not kept, and only its own span is read.\n const lowest = Math.min(...this.#decodeSpans.keys())\n late = mpu < lowest\n if (!late) this.#decodeSpans.delete(lowest)\n }\n const min = known !== undefined && known.min < first ? known.min : first\n const max = known !== undefined && known.max > last ? known.max : last\n if (!late) this.#decodeSpans.set(mpu, { min, max, mediaTimescale })\n // The catalog test passed, so the interval is stated in whole ticks.\n const { ticks, timescale } = geometry.keyframeInterval!\n if ((max - min) * BigInt(timescale) >= BigInt(ticks) * BigInt(mediaTimescale)) {\n this.#mpuOutlastsInterval = true\n this.#withdraw(changes)\n }\n return changes\n }\n\n /** Ask again for every block held but `own`: a new DU header can bound any of them. */\n #reclassifyOthers(own: number, changes: ClassifierChange[]): void {\n for (const [sbn, block] of this.#blocks) {\n if (sbn !== own) this.#reclassify(sbn, block, changes)\n }\n }\n\n /**\n * Move delta blocks back to unknown: a premise their class stood on is\n * gone. After DU headers out of block order, what the window rule still\n * holds for is classed again as its blocks are seen.\n */\n #withdraw(changes: ClassifierChange[]): void {\n for (const [sbn, block] of this.#blocks) {\n if (block.cls !== 'delta') continue\n block.cls = 'unknown'\n changes.push({ kind: 'reclassified', sbn, from: 'delta', to: 'unknown', evidence: 'classifier-disabled' })\n }\n }\n\n /**\n * An MPU boundary stopped bounding this stream's RAPs: neither rule proves\n * anything from now on, and every delta class goes.\n */\n #refuteMpuBounds(changes: ClassifierChange[]): void {\n if (!this.#mpuBoundsRaps) return\n this.#mpuBoundsRaps = false\n this.#withdraw(changes)\n }\n\n #reclassify(sbn: number, block: BlockEvidence, changes: ClassifierChange[]): void {\n const next = this.#classify(block, sbn)\n if (next === block.cls || !this.#allowed(block.cls, next)) return\n changes.push({\n kind: 'reclassified',\n sbn,\n from: block.cls,\n to: next,\n evidence: this.#evidenceFor(block, next),\n })\n block.cls = next\n }\n\n /**\n * Record a RAP frame released in order. Released MPU-start RAPs of MPUs m\n * and m+n must be exactly n keyframe intervals apart in the media\n * timescale, compared as integers.\n *\n * Comparing only consecutive MPUs would miss exactly the case the window\n * rule cannot survive: a short MPU whose successor's RAP was lost (that\n * RAP-bearing block is the one a wrong G calls delta), because the next\n * released RAP then belongs to m+2. Every MPU is one interval long, so the\n * span to any later released RAP proves or refutes all MPUs in between.\n *\n * In every mode it keeps each MPU's first released RAP, with its decode\n * time, as the start keyframeFreeBetween measures the catalog interval\n * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`\n * when it lies off the catalog lattice (not a whole number of intervals\n * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to\n * it): with no repair, released RAPs are the only evidence of where they\n * lie. Without a usable interval, or a decode time on either, any second\n * RAP with another presentation time refutes.\n */\n noteReleasedRap(\n mpu: number,\n presentationTime: bigint,\n mediaTimescale: number,\n decodeTime?: bigint,\n ): ClassifierChange[] {\n if (this.#geometry.trackKind === 'audio') return []\n const previous = this.#lastRap\n // A further RAP inside an already-anchored MPU is not an MPU start; the\n // MPU keeps its first RAP as the spacing anchor (rap-not-mpu-start owns\n // mid-MPU RAPs). The same RAP released again is no further one.\n if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {\n if (presentationTime === previous.presentationTime) return []\n const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale)\n if (\n interval === null ||\n decodeTime === undefined ||\n previous.decodeTime === undefined ||\n (decodeTime - previous.decodeTime) % interval !== 0n\n ) {\n const changes: ClassifierChange[] = []\n this.#refuteMpuBounds(changes)\n return changes\n }\n return []\n }\n // A late copy of an earlier MPU's RAP (the gate reports stale releases\n // too) moves no anchor back: the newest MPU's gaps are measured from its\n // own. MPU sequence numbers wrap at 2^32, so \"earlier\" is serial; it is\n // bounded, and a late copy is older in presentation time than the anchor.\n // Any other RAP behind the anchor is a restarted MPU sequence nothing\n // signalled, which re-anchors, or no same-MPU gap could ever be measured\n // again. A restart inside the bound whose presentation time went back\n // too still reads as late, and fails closed: its same-MPU gaps stay\n // rap-unknown until its MPU numbers pass the old newest, and unless it\n // repeats the old timeline the spacing checks then end the epoch\n // all-protected.\n if (previous !== null && previous.mediaTimescale === mediaTimescale) {\n const back = (previous.mpu - mpu) >>> 0\n if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return []\n }\n this.#lastRap = { mpu, presentationTime, mediaTimescale, ...(decodeTime === undefined ? {} : { decodeTime }) }\n if (this.#mode === 'all-protected') return []\n // Verification compares integers in the media timescale. When the\n // catalog interval is not an exact tick count there, spacing is\n // unprovable: fail closed, naming the cause, rather than blaming the\n // encoder with rap-spacing-mismatch on a perfectly spaced RAP.\n const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale)\n if (interval === null) return this.#disable('keyframe-interval-not-media-integral')\n if (\n previous === null ||\n mpu < previous.mpu ||\n previous.mediaTimescale !== mediaTimescale\n ) {\n return []\n }\n if (\n presentationTime - previous.presentationTime === interval * BigInt(mpu - previous.mpu)\n ) {\n return []\n }\n return this.#disable('rap-spacing-mismatch')\n }\n\n /**\n * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`\n * of the frames on either side, holds no keyframe: MPU boundaries still\n * bound RAPs, the catalog states an interval exact in this timescale, and\n * none of its instants after the MPU's first released RAP lies in\n * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything\n * unknown counts as a keyframe.\n */\n keyframeFreeBetween(mpu: number, from: bigint, to: bigint, mediaTimescale: number): boolean {\n const rap = this.#lastRap\n if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === undefined) {\n return false\n }\n const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale)\n return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to)\n }\n\n #blockFor(sbn: number): BlockEvidence {\n let block = this.#blocks.get(sbn)\n if (!block) {\n block = { rapSeen: false, mpus: new Set(), cls: 'unknown' }\n this.#blocks.set(sbn, block)\n }\n return block\n }\n\n #checkInvariants(\n sbn: number,\n block: BlockEvidence,\n evidence: SourceSymbolEvidence,\n placement: Placement,\n ): ClassifierReason | null {\n if (this.#mode === 'all-protected' || this.#geometry.trackKind !== 'video') return null\n const geometry = this.#geometry\n if (geometry.mode !== 'classifying') return null\n if (placement.rapNotMpuStart) return 'rap-not-mpu-start'\n if (placement.position !== undefined && placement.position >= geometry.gopFrames) {\n return 'mpu-longer-than-gop'\n }\n // A block closes at the latest after D media units, so the DU headers it\n // carries from one MPU lie within D consecutive positions. A wider span\n // means the producer closes blocks some other way (at K symbols, or\n // round-robin across concurrent blocks) and the window rule is void.\n if (\n block.mpus.size === 1 &&\n block.positionMin !== undefined &&\n block.positionMax !== undefined &&\n block.positionMax - block.positionMin >= geometry.interleaveUnits\n ) {\n return 'block-wider-than-interleave'\n }\n if (placement.violation !== undefined) return placement.violation\n if (evidence.mpu !== undefined && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {\n return 'block-not-contiguous'\n }\n return null\n }\n\n /**\n * The MPU position a source symbol's DU header proves (P3), and what it\n * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.\n */\n #place(evidence: SourceSymbolEvidence): Placement {\n const { mpu, idx, movieFragment: fragment } = evidence\n if (idx === undefined) return UNPLACED\n const bySample: Placement = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 }\n // Every wire DU header states both; evidence without them keeps the\n // one-fragment rule unless the sequence is fragment-per-frame.\n if (mpu === undefined || fragment === undefined) {\n return this.#fragmentPerFrame && !this.#multiSampleFragment\n ? { rapNotMpuStart: bySample.rapNotMpuStart }\n : bySample\n }\n let layout = this.#mpus.get(mpu)\n if (layout === undefined) {\n layout = { low: fragment }\n this.#mpus.set(mpu, layout)\n // One entry per MPU still inside the classification horizon.\n for (const other of this.#mpus.keys()) {\n if (other + 1 < mpu) this.#mpus.delete(other)\n }\n } else if (fragment !== layout.low) {\n this.#fragmentPerFrame = true\n if (((fragment - layout.low) | 0) < 0) layout.low = fragment\n }\n if (idx !== 0) this.#multiSampleFragment = true\n let arrival: number | undefined\n if (evidence.rap && layout.anchor === undefined) {\n layout.anchor = fragment\n arrival = this.#anchorDrift(mpu, fragment)\n // Proof takes two MPUs: an MPU's RAP header seen again proves nothing.\n if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true\n this.#lastAnchor = { mpu, fragment }\n }\n // Until an MPU shows two fragments, sample_number \u2212 1 is the position.\n // Once one has, a sample_number above 1 leaves neither layout.\n if (!this.#fragmentPerFrame) return bySample\n if (this.#multiSampleFragment) return { ...bySample, violation: 'mpu-multiple-fragments' }\n const { anchor } = layout\n if (anchor === undefined) return UNPLACED\n // A new anchor against the anchor received before it; any other DU\n // header's anchor against the anchor received last, so an anchor that\n // arrived before the layout was known is held to the spacing too.\n const drift = arrival ?? this.#anchorDrift(mpu, anchor)\n // RFC 1982 distance from the anchor: positive for a later fragment.\n const offset = (fragment - anchor) | 0\n return {\n ...(offset === 0 || (offset > 0 && this.#fragmentsProven) ? { position: offset } : {}),\n rapNotMpuStart:\n (evidence.rap && offset !== 0) ||\n ((layout.low - anchor) | 0) < 0 ||\n // Fragments count frames: an anchor arriving past the spacing is a\n // RAP inside its MPU, or an earlier MPU outran G.\n (arrival !== undefined && arrival > 0 && this.#fragmentsProven),\n ...(drift === undefined || drift === 0 ? {} : { violation: 'rap-spacing-mismatch' }),\n }\n }\n\n /**\n * The MPU position #place gives a DU header, read from the layout the\n * arrived headers built and recording nothing: where a rebuilt header\n * stands for the catalog interval's check in the MPU rule.\n */\n #positionHeld(mpu: number, idx: number, fragment: number): number | undefined {\n if (!this.#fragmentPerFrame || this.#multiSampleFragment) return idx\n const anchor = this.#mpus.get(mpu)?.anchor\n if (anchor === undefined) return undefined\n const offset = (fragment - anchor) | 0\n return offset === 0 || (offset > 0 && this.#fragmentsProven) ? offset : undefined\n }\n\n /**\n * How many fragments MPU m's anchor `fragment` lies past the start that\n * the anchor received last predicts for MPU m: one frame per fragment and\n * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')\n * fragments apart, modulo 2^32. Undefined without a last anchor, a\n * cadence, or this layout.\n */\n #anchorDrift(mpu: number, fragment: number): number | undefined {\n const geometry = this.#geometry\n const last = this.#lastAnchor\n if (\n last === null ||\n !this.#fragmentPerFrame ||\n this.#multiSampleFragment ||\n geometry.trackKind !== 'video' ||\n geometry.mode !== 'classifying'\n ) {\n return undefined\n }\n return (fragment - last.fragment - geometry.gopFrames * (mpu - last.mpu)) | 0\n }\n\n #clearMpuLayout(): void {\n this.#mpus.clear()\n this.#fragmentPerFrame = false\n this.#multiSampleFragment = false\n this.#lastAnchor = null\n this.#fragmentsProven = false\n }\n\n #clearContiguityLedger(): void {\n this.#mpuSbnSpans.clear()\n this.#dataUnitStarts.clear()\n this.#highestMpu = null\n this.#headers.clear()\n this.#arrived.clear()\n this.#heldHighestMpu = null\n this.#headerOrderRefuted = false\n this.#decodeSpans.clear()\n }\n\n /**\n * P1 check for one source packet of MPU `mpu` in block `sbn`, then record\n * it. True when some recorded packet's authored order and SBN order\n * disagree with this one's (see the class comment). Only positions the\n * wire states are compared: MPU order for every packet, and data-unit\n * order for packets that carry a DU header. A packet of one data unit\n * that continues into the next block carries no DU header and so only\n * takes part through its MPU, which is exactly what makes an adjacent\n * straddle consistent.\n */\n #contradictsAuthoredOrder(sbn: number, mpu: number, evidence: SourceSymbolEvidence): boolean {\n // Every packet of MPU m precedes every packet of MPU m' > m.\n for (const [other, span] of this.#mpuSbnSpans) {\n if (other < mpu && span.max > sbn) return true\n if (other > mpu && span.min < sbn) return true\n }\n const inHorizon = this.#highestMpu === null || mpu + 1 >= this.#highestMpu\n let insertAt = -1\n let starts: DataUnitStart[] | undefined\n let start: DataUnitStart | undefined\n if (evidence.idx !== undefined) {\n start = {\n movieFragment: evidence.movieFragment ?? 0,\n idx: evidence.idx,\n offset: evidence.offset ?? 0,\n sbn,\n }\n starts = this.#dataUnitStarts.get(mpu)\n if (starts !== undefined) {\n let lo = 0\n let hi = starts.length\n while (lo < hi) {\n const mid = (lo + hi) >>> 1\n if (compareDataUnitStarts(starts[mid]!, start) < 0) lo = mid + 1\n else hi = mid\n }\n const at = starts[lo]\n if (at !== undefined && compareDataUnitStarts(at, start) === 0) {\n // One data unit has one first packet: seen in another block, the\n // SBN-to-authored-order map is not a function.\n if (at.sbn !== sbn) return true\n } else {\n const before = starts[lo - 1]\n if (before !== undefined && before.sbn > sbn) return true\n if (at !== undefined && at.sbn < sbn) return true\n insertAt = lo\n }\n }\n }\n if (!inHorizon) return false\n const span = this.#mpuSbnSpans.get(mpu)\n if (span === undefined) this.#mpuSbnSpans.set(mpu, { min: sbn, max: sbn })\n else {\n if (sbn < span.min) span.min = sbn\n if (sbn > span.max) span.max = sbn\n }\n if (start !== undefined) {\n if (starts === undefined) this.#dataUnitStarts.set(mpu, [start])\n else if (insertAt >= 0) starts.splice(insertAt, 0, start)\n }\n if (this.#highestMpu === null || mpu > this.#highestMpu) {\n this.#highestMpu = mpu\n for (const other of [...this.#mpuSbnSpans.keys()]) {\n if (other + 1 < mpu) {\n this.#mpuSbnSpans.delete(other)\n this.#dataUnitStarts.delete(other)\n }\n }\n }\n return false\n }\n\n #disable(reason: ClassifierReason): ClassifierChange[] {\n if (reason === 'rap-not-mpu-start' || reason === 'mpu-longer-than-gop') {\n this.#mpuBoundsRaps = false\n }\n if (this.#mode === 'all-protected') return []\n this.#mode = 'all-protected'\n this.#reason = reason\n const changes: ClassifierChange[] = [{ kind: 'mode', mode: 'all-protected', reason }]\n for (const [sbn, block] of this.#blocks) {\n if (block.cls !== 'delta') continue\n block.cls = 'unknown'\n changes.push({\n kind: 'reclassified',\n sbn,\n from: 'delta',\n to: 'unknown',\n evidence: 'classifier-disabled',\n })\n }\n return changes\n }\n\n #classify(block: BlockEvidence, sbn: number): BlockClass {\n if (block.rapSeen || block.mpus.size >= 2) return 'keyframe'\n // Only a keyframe or a withdrawal moves a delta block: no symbol re-proves it.\n if (block.cls === 'delta') return 'delta'\n if (this.#windowHolds(block) || this.#mpuRuleHolds(block, sbn)) return 'delta'\n return 'unknown'\n }\n\n #windowHolds(block: BlockEvidence): boolean {\n // A track the MPU rule does not apply to gets no delta at all (fec-multicast-01 Block Classification): one whose\n // catalog fails the test, or that showed a RAP inside an MPU or an MPU longer than the keyframe interval. DU\n // headers out of block order stop the MPU rule alone: this rule has its own check of the order (P1).\n const off = this.mpuRuleOff\n if (this.#mode === 'all-protected' || (off !== null && off !== 'du-headers-out-of-order')) return false\n const geometry = this.#geometry\n if (geometry.trackKind !== 'video' || geometry.mode !== 'classifying') return false\n if (\n block.mpus.size !== 1 ||\n block.positionMin === undefined ||\n block.positionMax === undefined\n ) {\n return false\n }\n // A block closes every D media units, so its frames are contiguous and\n // lie in [positionMax \u2212 D + 1, positionMin + D \u2212 1] of MPU m. Position\n // 0 is the only RAP of an MPU and G bounds its length.\n const span = geometry.interleaveUnits - 1\n return block.positionMax - span >= 1 && block.positionMin + span <= geometry.gopFrames - 1\n }\n\n /**\n * Keep the header and arrival ledgers to the two newest MPUs. False for an\n * MPU behind them, which is not kept: no block still asked lies there, and\n * the ledgers stay bounded when MPU numbers go back with no source\n * discontinuity (a restart nothing signalled, or the 2^32 wrap). The rule\n * is then silent until the next one.\n */\n #noteHeldMpu(mpu: number): boolean {\n const highest = this.#heldHighestMpu\n if (highest !== null && mpu <= highest) return mpu + 1 >= highest\n this.#heldHighestMpu = mpu\n for (const held of [this.#headers, this.#arrived]) {\n for (const other of [...held.keys()]) {\n if (other + 1 < mpu) held.delete(other)\n }\n }\n return true\n }\n\n /** Record a source packet that arrived as source symbol `ssId`, for #arrivedBetween. */\n #noteArrived(sbn: number, mpu: number | undefined, ssId: number | undefined): void {\n if (mpu === undefined || ssId === undefined || !this.#noteHeldMpu(mpu)) return\n const arrived = this.#arrived.get(mpu)\n if (arrived === undefined) this.#arrived.set(mpu, { start: new Map([[ssId, sbn]]), last: ssId })\n else {\n if (arrived.start.size < ARRIVED_START_MAX) arrived.start.set(ssId, sbn)\n if (ssId > arrived.last) arrived.last = ssId\n }\n }\n\n /**\n * Record a held DU header for the MPU rule; `ssId` is its source symbol id\n * when it arrived, undefined for one that FEC rebuilt. True when it is new\n * and in order: the blocks held are then asked again. Blocks follow\n * authored order (P1), so the first header that lies against it withdraws\n * every class, and the rule proves nothing for the rest of the sequence.\n */\n #noteHeader(\n sbn: number,\n evidence: SourceSymbolEvidence,\n position: number | undefined,\n ssId: number | undefined,\n changes: ClassifierChange[],\n ): boolean {\n const { mpu, idx, movieFragment } = evidence\n if (this.#geometry.trackKind !== 'video' || mpu === undefined || idx === undefined || movieFragment === undefined) {\n return false\n }\n if (!this.#noteHeldMpu(mpu)) {\n // A header of an MPU behind the two newest is not kept. A RAP that is not the first sample of its movie\n // fragment needs nothing else held to show it, so that much is still read.\n if (evidence.rap && idx !== 0 && !this.#rapInsideMpu) {\n this.#rapInsideMpu = true\n this.#withdraw(changes)\n }\n return false\n }\n const header: HeldHeader = {\n movieFragment,\n idx,\n offset: evidence.offset ?? 0,\n sbn,\n rap: evidence.rap,\n ...(ssId === undefined ? {} : { ssId }),\n ...(position === undefined ? {} : { position }),\n }\n let headers = this.#headers.get(mpu)\n if (headers === undefined) {\n headers = []\n this.#headers.set(mpu, headers)\n }\n let at = 0\n let end = headers.length\n while (at < end) {\n const mid = (at + end) >>> 1\n if (compareDataUnitStarts(headers[mid]!, header) < 0) at = mid + 1\n else end = mid\n }\n if (at < headers.length && compareDataUnitStarts(headers[at]!, header) === 0) return false\n headers.splice(at, 0, header)\n // A RAP is an MPU's first sample. A RAP-flagged header is a RAP inside the MPU when it is not the first sample of\n // its movie fragment (whatever else is held: a header that FEC rebuilt may be the only one of its MPU), or when\n // its movie fragment is not that of the first header held.\n const first = headers[0]!\n if (\n !this.#rapInsideMpu &&\n ((header.rap && header.idx !== 0) ||\n (at === 0 ? headers : [header]).some((held) => held.rap && held.movieFragment !== first.movieFragment))\n ) {\n this.#rapInsideMpu = true\n this.#withdraw(changes)\n }\n const before = headers[at - 1]?.sbn\n const after = headers[at + 1]?.sbn\n if ((before !== undefined && before > sbn) || (after !== undefined && after < sbn)) {\n if (!this.#headerOrderRefuted) {\n this.#headerOrderRefuted = true\n this.#withdraw(changes)\n }\n return false\n }\n return true\n }\n\n /**\n * The MPU rule. L is the DU header held last before the block and U the\n * one held first after it. Every packet carries its MPU number, and an MPU\n * holds one RAP: its first sample.\n *\n * - R1, L and U in one MPU: the block holds no part of a RAP, provided the\n * MPU's first sample ended before the block (#firstSampleEndedBefore).\n * - R2, U in the next MPU: the block may hold the start of that MPU,\n * unless that start arrived whole (#startArrivedWhole). The block is\n * then the tail of L's MPU, and R1's proviso decides.\n * - R3, more than one MPU apart: a whole MPU is gone, its RAP with it.\n * - R4, no U held yet (or no L): not known. The next DU header asks again.\n *\n * It rests on the publisher keeping one RAP to an MPU, which no packet\n * says. So it classes nothing unless the catalog states a keyframe interval\n * equal to the group duration, and nothing once the stream showed\n * otherwise: a RAP inside an MPU (mpuBoundsRaps, or a RAP-flagged DU header\n * held that is not of its MPU's first sample: #noteHeader), an MPU longer than the\n * keyframe interval by the decode times known (noteDecodeTimes), or DU\n * headers against the block order. `mpuRuleOff` names which. `dep_counter`\n * is not read.\n */\n #mpuRuleHolds(block: BlockEvidence, sbn: number): boolean {\n // shortcut: reads the DU headers of the blocks around this one, not the nearest inside it, so it classes fewer blocks than the rule allows; upgrade when observe() is given symbol positions.\n if (this.mpuRuleOff !== null) return false\n let lower: HeldHeader | undefined\n let upper: HeldHeader | undefined\n let lowerMpu = 0\n let upperMpu = 0\n let lowerAt = 0\n let upperAt = 0\n for (const [mpu, headers] of this.#headers) {\n // While the order holds, sbn never decreases along a list: split it at this block.\n const before = firstStartAtOrAfter(headers, sbn) - 1\n const after = firstStartAtOrAfter(headers, sbn + 1)\n const below = headers[before]\n const above = headers[after]\n // The nearest block decides. Where two MPUs meet in one block, the later MPU is the nearer below and the earlier above.\n if (\n below !== undefined &&\n (lower === undefined || below.sbn > lower.sbn || (below.sbn === lower.sbn && mpu > lowerMpu))\n ) {\n lower = below\n lowerMpu = mpu\n lowerAt = before\n }\n if (\n above !== undefined &&\n (upper === undefined || above.sbn < upper.sbn || (above.sbn === upper.sbn && mpu < upperMpu))\n ) {\n upper = above\n upperMpu = mpu\n upperAt = after\n }\n }\n if (lower === undefined || upper === undefined) return false\n if (block.mpus.size === 1 && !block.mpus.has(lowerMpu)) return false\n if (upperMpu === lowerMpu) {\n // A RAP header after L in L's MPU is L's own sample again: the block lies inside the MPU's first sample.\n if (upper.rap) return false\n // The catalog interval wins where it places a keyframe between the two.\n const geometry = this.#geometry\n if (\n geometry.trackKind === 'video' &&\n geometry.mode === 'classifying' &&\n lower.position !== undefined &&\n upper.position !== undefined &&\n Math.floor(upper.position / geometry.gopFrames) > Math.floor(lower.position / geometry.gopFrames)\n ) {\n return false\n }\n } else if (upperMpu !== lowerMpu + 1 || !this.#startArrivedWhole(upperMpu, upperAt)) {\n // R3 is stated here, and kept by the ledgers too: a header two MPUs behind the newest is not held.\n return false\n }\n return this.#firstSampleEndedBefore(sbn, lowerMpu, lowerAt)\n }\n\n /**\n * R1's proviso for block `sbn`, where header `at` of MPU `mpu` is the one\n * held last before it: no part of the MPU's first sample lies in the\n * block. A sample start without RAP_flag is not the first sample. Any\n * other header may be of it (a later data unit of a sample need not repeat\n * the flag). That sample ended before the block only if every packet from\n * the header to the next sample's DU header arrived, in earlier blocks.\n */\n #firstSampleEndedBefore(sbn: number, mpu: number, at: number): boolean {\n const headers = this.#headers.get(mpu)!\n const lower = headers[at]!\n if (lower.offset === 0 && !lower.rap) return true\n // shortcut: a packet between the two headers that lies in the block itself counts as one of the first sample, though it may be the next fragment's metadata, so where every block opens with movie fragment metadata (FFmpeg's muxer) the block after a keyframe stays unknown; upgrade when the evidence says which packets are metadata.\n const next = nextSampleHeader(headers, at)\n return next !== undefined && this.#arrivedBetween(mpu, lower, next, sbn)\n }\n\n /**\n * R2's exception: the start of MPU `mpu` arrived whole. Its header `at`,\n * the DU header held first after the block, is of the MPU's RAP. Every\n * packet before it arrived, back to the last packet of the MPU before: so\n * did the MPU and movie fragment metadata sent before the sample. And\n * every packet after it arrived, up to the next sample's DU header.\n */\n #startArrivedWhole(mpu: number, at: number): boolean {\n const headers = this.#headers.get(mpu)!\n const first = headers[at]!\n const arrived = this.#arrived.get(mpu)\n const previous = this.#arrived.get(mpu - 1)\n if (!first.rap || first.ssId === undefined || arrived === undefined || previous === undefined) return false\n let ssId = first.ssId - 1\n while (arrived.start.has(ssId)) ssId--\n if (ssId !== previous.last) return false\n const next = nextSampleHeader(headers, at)\n return next !== undefined && this.#arrivedBetween(mpu, first, next)\n }\n\n /**\n * Whether every packet sent after DU header `from` and before DU header\n * `to`, both of MPU `mpu`, arrived as a packet of that MPU, each in a block\n * before `before` when one is given. The source symbol id counts every\n * packet of the FEC flow, so no id may be missing between the two. Ids are\n * read as plain numbers, as block starts are: past the 2^32 wrap of the id\n * nothing is proved.\n */\n #arrivedBetween(mpu: number, from: HeldHeader, to: HeldHeader, before?: number): boolean {\n // shortcut: a packet that FEC rebuilt does not count as arrived (only the DU headers of rebuilt packets are handed over), so a start that FEC completed proves nothing here; upgrade when the router hands every rebuilt packet over with its source symbol id.\n const arrived = this.#arrived.get(mpu)\n if (arrived === undefined || from.ssId === undefined || to.ssId === undefined) return false\n for (let ssId = from.ssId + 1; ssId !== to.ssId; ssId++) {\n const sbn = arrived.start.get(ssId)\n if (sbn === undefined || (before !== undefined && sbn >= before)) return false\n }\n return true\n }\n\n #allowed(from: BlockClass, to: BlockClass): boolean {\n if (from === 'keyframe') return false\n if (from === 'unknown') return to === 'delta' || to === 'keyframe'\n if (from === 'delta') return to === 'keyframe'\n return false\n }\n\n #evidenceFor(block: BlockEvidence, to: BlockClass): ReclassificationEvidence {\n if (to === 'delta') return this.#windowHolds(block) ? 'window' : 'mpu-rule'\n return block.rapSeen ? 'rap' : 'mpu-span'\n }\n}\n\n// \u2500\u2500\u2500 Stall vs conceal \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\nexport interface GapStreamIdentity {\n readonly packetId: number\n /** Non-empty catalog identity, or null when the producer has no track name. */\n readonly catalogTrackName: string | null\n}\n\n/** What the sink knows about one side of a released gap. */\nexport interface GapFrameEvidence {\n /**\n * Codec-aware RAP check: `MmtpContainerParser.isKeyframe(data, rapFlag,\n * codec)`, bitstream-only for recovered frames. Never the priority hint.\n */\n readonly rap: boolean\n /**\n * MPU_sequence_number of the frame. Omit it once the stream showed that\n * an MPU boundary does not bound its RAPs (`BlockClassifier.mpuBoundsRaps`):\n * same-MPU then no longer proves a gap lost only deltas.\n */\n readonly mpu?: number\n /**\n * 0-based sample position within its movie fragment (sample_number \u2212 1).\n * State it on both sides only when both frames are in one movie fragment:\n * decideGap reads `after.idx \u2212 before.idx \u2212 1` as the samples missed\n * between them.\n */\n readonly idx?: number\n /** Authored presentation time in `timescale` ticks. */\n readonly pts?: bigint\n /** Authored sample duration in `timescale` ticks. */\n readonly durationTicks?: number\n /** The media timescale of `pts` and `durationTicks`. */\n readonly timescale?: number\n}\n\nexport type FrameGapAction = 'stall' | 'conceal'\n\nexport type FrameGapReason =\n | 'rap-lost'\n | 'rap-unknown'\n | 'discontinuity'\n | 'delta-lost'\n | 'rap-next'\n | 'audio-gap'\n | 'audio-discontinuity'\n\n/**\n * The decision attached to the first frame released after a gap\n * (`RoutedFrameMeta.gapBefore`). It is the same frozen object the manager\n * emits as its `gap` repair lifecycle event, so a sink that acts on the frame\n * and an observer that counts events see one fact.\n */\nexport interface FrameGapDecision {\n readonly version: 2\n readonly type: 'gap'\n readonly stream: GapStreamIdentity\n readonly trackKind: TrackKind\n readonly action: FrameGapAction\n readonly reason: FrameGapReason\n /** FEC blocks in the gap whose media was lost (failed or vanished). */\n readonly blocks: readonly number[]\n /** Missing video frames or audio access units, when exactly known. */\n readonly missingFrames: number | null\n /** Authored duration of the missing media in milliseconds, when known. */\n readonly missingMs: number | null\n /** Manager epoch of the stream when the decision was made. */\n readonly epoch: number\n}\n\nexport interface DecideGapInput {\n readonly stream: GapStreamIdentity\n readonly trackKind: TrackKind\n /** Last frame released before the gap. */\n readonly before: GapFrameEvidence\n /** First frame released after the gap. */\n readonly after: GapFrameEvidence\n /** The stream restarted (FEC SBN went backwards or the publisher reset). */\n readonly discontinuity: boolean\n readonly blocks: readonly number[]\n /**\n * The most media units the gap can hold: the FEC blocks spanned from the\n * frame before to the frame after, times D (media units per block,\n * ceil(interleaveDepthMs / unit duration), \u00A75.1). A block touches at most D\n * units whether it closes at D or at K symbols. Null when the span or D is\n * unknown. An audio PTS delta that implies more AUs than this is a clock\n * jump, not loss, and re-anchors instead of concealing every slot.\n */\n readonly maxMissingUnits: number | null\n readonly epoch: number\n}\n\nfunction durationMs(units: number, before: GapFrameEvidence): number | null {\n if (\n before.durationTicks === undefined ||\n before.timescale === undefined ||\n before.timescale <= 0\n ) {\n return null\n }\n return (units * before.durationTicks * 1000) / before.timescale\n}\n\n/**\n * Pure stall/conceal decision for the first frame released after a gap.\n *\n * Video stalls only when a RAP may be inside the gap: the frame after it is\n * not a RAP and either sits in another MPU (`rap-lost`) or the MPU cannot be\n * proven on both sides (`rap-unknown`), or the stream restarted\n * (`discontinuity`). A gap inside one MPU lost only deltas (`delta-lost`) and\n * a RAP after the gap resynchronises by itself (`rap-next`). Audio never\n * stalls: an exact gap is concealed per access unit (`audio-gap`), anything\n * else re-anchors at the next frame (`audio-discontinuity`).\n */\nexport function decideGap(input: DecideGapInput): FrameGapDecision {\n const { before, after } = input\n let action: FrameGapAction\n let reason: FrameGapReason\n let missingFrames: number | null = null\n\n if (input.trackKind === 'audio') {\n action = 'conceal'\n reason = 'audio-discontinuity'\n if (\n !input.discontinuity &&\n before.pts !== undefined &&\n after.pts !== undefined &&\n before.durationTicks !== undefined &&\n Number.isSafeInteger(before.durationTicks) &&\n before.durationTicks > 0\n ) {\n const auDuration = BigInt(before.durationTicks)\n const missingTicks = after.pts - before.pts - auDuration\n const bound = input.maxMissingUnits\n if (\n missingTicks > 0n &&\n missingTicks % auDuration === 0n &&\n bound !== null &&\n missingTicks / auDuration <= BigInt(bound)\n ) {\n reason = 'audio-gap'\n missingFrames = Number(missingTicks / auDuration)\n }\n }\n } else if (input.discontinuity) {\n action = 'stall'\n reason = 'discontinuity'\n } else if (after.rap) {\n action = 'conceal'\n reason = 'rap-next'\n } else if (before.mpu === undefined || after.mpu === undefined) {\n action = 'stall'\n reason = 'rap-unknown'\n } else if (before.mpu !== after.mpu) {\n action = 'stall'\n reason = 'rap-lost'\n } else {\n action = 'conceal'\n reason = 'delta-lost'\n if (before.idx !== undefined && after.idx !== undefined) {\n const missing = after.idx - before.idx - 1\n missingFrames = missing > 0 ? missing : null\n }\n }\n\n return Object.freeze({\n version: 2 as const,\n type: 'gap' as const,\n stream: Object.freeze({\n packetId: input.stream.packetId,\n catalogTrackName: input.stream.catalogTrackName,\n }),\n trackKind: input.trackKind,\n action,\n reason,\n blocks: Object.freeze([...input.blocks]),\n missingFrames,\n missingMs: missingFrames === null ? null : durationMs(missingFrames, before),\n epoch: input.epoch,\n })\n}\n", "// Resolved repair layer and overlay shapes (draft-ramadan-moq-fec-catalog-00,\n// fec-core-00): the output of `resolveRepairLayers`. Every base layer comes\n// from one instance's partition and differs only in P_i; layer i owns RS_IDs\n// [O_i, O_i + P_i) with O_i = sum(P_j, j < i), and ESI = K + RS_ID. A keyframe\n// overlay is a second instance with its own K, P and RS_ID space.\n//\n// Binding (which repair tracks belong to which instance) is\n// `resolveFecBindings` in mmt-base; nothing here reads a catalog.\n\n/** Lowest MoQT-scale priority a repair track may declare. */\nexport const REPAIR_PRIORITY_MIN = 192;\n/** Highest MoQT-scale priority a repair track may declare. */\nexport const REPAIR_PRIORITY_MAX = 255;\n/** Priority of a base layer 0 track that declares none. */\nexport const DEFAULT_REPAIR_PRIORITY = 240;\n/** RFC 6330 \u00A74.4.1.2: the largest number of source symbols in one RaptorQ source block. */\nexport const MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;\n/** The 24-bit RS_ID field (\u00A77.1) bounds the repair total of one FEC instance. */\nexport const MAX_REPAIR_SYMBOLS = 0xffffff;\n/** The 24-bit ESI bounds K + totalP - 1 for one FEC instance. */\nexport const MAX_ENCODING_SYMBOL_ID = 0xffffff;\n/** Reed-Solomon block bound: K + P <= 255 (draft-ramadan-moq-fec-01 4.5, 6.3.4 rule 12). */\nexport const MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;\n\n/** A resolved base repair layer with its derived RS_ID range. */\nexport type RepairLayerParams = {\n\t/** Layer index; 0 is the track named by the source's `fec.repairTrack`. */\n\tlayer: number;\n\trepairTrackName: string;\n\t/** P_i: repair symbols per block carried by this layer. */\n\trepairSymbols: number;\n\t/** O_i = sum(P_j for j < i): the first RS_ID this layer carries. ESI = K + RS_ID. */\n\trsIdOffset: number;\n\t/** MoQT-scale priority (lower first); 240 when layer 0 declares none. */\n\tpriority: number;\n};\n\n/** A resolved keyframe overlay: a separate FEC instance over RAP fragments only. */\nexport type RepairOverlayParams = {\n\trepairTrackName: string;\n\tscope: \"keyframe\";\n\t/** K_overlay: source symbols of the overlay instance. */\n\tsourceSymbols: number;\n\t/** P_overlay: repair symbols per overlay block; also the overlay's own RSB_length. */\n\trepairSymbols: number;\n\t/** MoQT-scale priority, independent of the base layer chain. */\n\tpriority: number;\n};\n\nexport type RepairLayersResolution = {\n\tsourceTrackName: string;\n\t/** Base layers in layer order, layer 0 first. Never empty. */\n\tbaseLayers: readonly RepairLayerParams[];\n\t/** Keyframe overlay instances, in catalog order. Empty when none is declared. */\n\t/** At most one entry: the wire carries one overlay trailer per RAP packet. */\n\toverlays: readonly RepairOverlayParams[];\n\t/** Sum of P over base layers: the wire RSB_length on every base layer packet. */\n\ttotalBaseRepairSymbols: number;\n};\n\n"],
5
+ "mappings": ";AAqEO,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAI/B,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B,kBAAkB;AAM7C,IAAM,qBAAqB;AAyB5B,SAAU,gBAAgB,QAAkB;AAChD,MAAI,OAAO,SAAS,kBAAkB;AACpC,UAAM,IAAI,MAAM,0BAA0B,OAAO,MAAM,QAAQ;EACjE;AAEA,QAAM,OAAO,IAAI,SAAS,OAAO,QAAQ,OAAO,YAAY,OAAO,UAAU;AAE7E,QAAM,UAAW,OAAO,CAAC,KAAM,IAAK;AACpC,MAAI,YAAY,GAAG;AACjB,UAAM,IAAI,MAAM,6BAA6B,OA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