@blockcast/mmt-container 0.1.0 → 0.3.0-main.ef68de90edb3
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.
- package/README.md +524 -0
- package/dist/.build-stamp +0 -0
- package/dist/__tests__/test-utils.d.ts +71 -0
- package/dist/__tests__/test-utils.d.ts.map +1 -0
- package/dist/align.d.ts +152 -0
- package/dist/align.d.ts.map +1 -0
- package/dist/align.js +88 -0
- package/dist/align.js.map +7 -0
- package/dist/audio-init-parser.d.ts +66 -0
- package/dist/audio-init-parser.d.ts.map +1 -0
- package/dist/audio-init-parser.js +118 -0
- package/dist/audio-init-parser.js.map +7 -0
- package/dist/audio-ring-buffer.d.ts +50 -0
- package/dist/audio-ring-buffer.d.ts.map +1 -0
- package/dist/audio-ring-buffer.js +80 -0
- package/dist/audio-ring-buffer.js.map +7 -0
- package/dist/authored-timing.d.ts +32 -0
- package/dist/authored-timing.d.ts.map +1 -0
- package/dist/authored-timing.js +32 -0
- package/dist/authored-timing.js.map +7 -0
- package/dist/block-policy.d.ts +314 -0
- package/dist/block-policy.d.ts.map +1 -0
- package/dist/block-policy.js +466 -0
- package/dist/block-policy.js.map +7 -0
- package/dist/browser-runtime.js +26549 -0
- package/dist/browser-runtime.js.map +7 -0
- package/dist/carp-catalog.d.ts +429 -0
- package/dist/carp-catalog.d.ts.map +1 -0
- package/dist/carp-catalog.js +985 -0
- package/dist/carp-catalog.js.map +7 -0
- package/dist/catalog-fec-params.d.ts +275 -0
- package/dist/catalog-fec-params.d.ts.map +1 -0
- package/dist/catalog-fec-params.js +702 -0
- package/dist/catalog-fec-params.js.map +7 -0
- package/dist/catalog-network-source.d.ts +42 -0
- package/dist/catalog-network-source.d.ts.map +1 -0
- package/dist/catalog-network-source.js +47 -0
- package/dist/catalog-network-source.js.map +7 -0
- package/dist/catalog-validator.d.ts +18 -0
- package/dist/catalog-validator.d.ts.map +1 -0
- package/dist/catalog-validator.js +7747 -0
- package/dist/catalog-validator.js.map +7 -0
- package/dist/cmaf-block-assembler.d.ts +285 -0
- package/dist/cmaf-block-assembler.d.ts.map +1 -0
- package/dist/cmaf-block-assembler.js +1966 -0
- package/dist/cmaf-block-assembler.js.map +7 -0
- package/dist/cmaf-group-batcher.d.ts +38 -0
- package/dist/cmaf-group-batcher.d.ts.map +1 -0
- package/dist/cmaf-group-batcher.js +176 -0
- package/dist/cmaf-group-batcher.js.map +7 -0
- package/dist/cmcd-producer.d.ts +104 -0
- package/dist/cmcd-producer.d.ts.map +1 -0
- package/dist/cmcd-producer.js +183 -0
- package/dist/cmcd-producer.js.map +7 -0
- package/dist/codec-utils.d.ts +384 -0
- package/dist/codec-utils.d.ts.map +1 -0
- package/dist/codec-utils.js +1546 -0
- package/dist/codec-utils.js.map +7 -0
- package/dist/conceal-timeline.d.ts +146 -0
- package/dist/conceal-timeline.d.ts.map +1 -0
- package/dist/conceal-timeline.js +137 -0
- package/dist/conceal-timeline.js.map +7 -0
- package/dist/delivery-gap.d.ts +75 -0
- package/dist/delivery-gap.d.ts.map +1 -0
- package/dist/delivery-gap.js +88 -0
- package/dist/delivery-gap.js.map +7 -0
- package/dist/duplicate-ledger.d.ts +197 -0
- package/dist/duplicate-ledger.d.ts.map +1 -0
- package/dist/duplicate-ledger.js +226 -0
- package/dist/duplicate-ledger.js.map +7 -0
- package/dist/fec-codec.d.ts +32 -0
- package/dist/fec-codec.d.ts.map +1 -0
- package/dist/fec-codec.js +47 -0
- package/dist/fec-codec.js.map +7 -0
- package/dist/fec-manager.d.ts +583 -0
- package/dist/fec-manager.d.ts.map +1 -0
- package/dist/fec-manager.js +3899 -0
- package/dist/fec-manager.js.map +7 -0
- package/dist/fec-starvation-detector.d.ts +59 -0
- package/dist/fec-starvation-detector.d.ts.map +1 -0
- package/dist/fec-starvation-detector.js +60 -0
- package/dist/fec-starvation-detector.js.map +7 -0
- package/dist/fec-state.d.ts +131 -0
- package/dist/fec-state.d.ts.map +1 -0
- package/dist/fec-state.js +87 -0
- package/dist/fec-state.js.map +7 -0
- package/dist/fec-worker-setup.d.ts +94 -0
- package/dist/fec-worker-setup.d.ts.map +1 -0
- package/dist/fec-worker-setup.js +673 -0
- package/dist/fec-worker-setup.js.map +7 -0
- package/dist/fmp4-completion.d.ts +30 -0
- package/dist/fmp4-completion.d.ts.map +1 -0
- package/dist/fmp4-completion.js +21 -0
- package/dist/fmp4-completion.js.map +7 -0
- package/dist/fmp4-reader.d.ts +37 -0
- package/dist/fmp4-reader.d.ts.map +1 -0
- package/dist/fmp4-reader.js +100 -0
- package/dist/fmp4-reader.js.map +7 -0
- package/dist/index.d.ts +44 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +460 -14
- package/dist/index.js.map +7 -1
- package/dist/iso-block-locator.d.ts +118 -0
- package/dist/iso-block-locator.d.ts.map +1 -0
- package/dist/iso-block-locator.js +289 -0
- package/dist/iso-block-locator.js.map +7 -0
- package/dist/iso-bmff-timing.d.ts +78 -0
- package/dist/iso-bmff-timing.d.ts.map +1 -0
- package/dist/iso-bmff-timing.js +593 -0
- package/dist/iso-bmff-timing.js.map +7 -0
- package/dist/loc.d.ts +70 -75
- package/dist/loc.d.ts.map +1 -1
- package/dist/loc.js +106 -192
- package/dist/loc.js.map +7 -1
- package/dist/manifest-auth-plan.d.ts +30 -0
- package/dist/manifest-auth-plan.d.ts.map +1 -0
- package/dist/manifest-auth-plan.js +1266 -0
- package/dist/manifest-auth-plan.js.map +7 -0
- package/dist/media-router.d.ts +262 -0
- package/dist/media-router.d.ts.map +1 -0
- package/dist/media-router.js +584 -0
- package/dist/media-router.js.map +7 -0
- package/dist/mfu-reassembler.d.ts +313 -9
- package/dist/mfu-reassembler.d.ts.map +1 -1
- package/dist/mfu-reassembler.js +3051 -285
- package/dist/mfu-reassembler.js.map +7 -1
- package/dist/mfu-reassembly-policy.d.ts +24 -0
- package/dist/mfu-reassembly-policy.d.ts.map +1 -0
- package/dist/mfu-reassembly-policy.js +99 -0
- package/dist/mfu-reassembly-policy.js.map +7 -0
- package/dist/mmtp-container-parser.d.ts +568 -0
- package/dist/mmtp-container-parser.d.ts.map +1 -0
- package/dist/mmtp-container-parser.js +6580 -0
- package/dist/mmtp-container-parser.js.map +7 -0
- package/dist/mmtp-container-parser.no-modules.js +9616 -0
- package/dist/mmtp-container-parser.no-modules.js.map +7 -0
- package/dist/mmtp-decode-pipeline.d.ts +138 -0
- package/dist/mmtp-decode-pipeline.d.ts.map +1 -0
- package/dist/mmtp-decode-pipeline.js +6814 -0
- package/dist/mmtp-decode-pipeline.js.map +7 -0
- package/dist/mmtp-router.d.ts +679 -0
- package/dist/mmtp-router.d.ts.map +1 -0
- package/dist/mmtp-router.js +11278 -0
- package/dist/mmtp-router.js.map +7 -0
- package/dist/mmtp-to-cmaf.d.ts +187 -0
- package/dist/mmtp-to-cmaf.d.ts.map +1 -0
- package/dist/mmtp-to-cmaf.js +716 -0
- package/dist/mmtp-to-cmaf.js.map +7 -0
- package/dist/multicast-auth-catalog.d.ts +115 -0
- package/dist/multicast-auth-catalog.d.ts.map +1 -0
- package/dist/multicast-auth-catalog.js +202 -0
- package/dist/multicast-auth-catalog.js.map +7 -0
- package/dist/multicast-input.d.ts +141 -0
- package/dist/multicast-input.d.ts.map +1 -0
- package/dist/multicast-input.js +390 -0
- package/dist/multicast-input.js.map +7 -0
- package/dist/multicast-manager.d.ts +669 -0
- package/dist/multicast-manager.d.ts.map +1 -0
- package/dist/multicast-manager.js +19101 -0
- package/dist/multicast-manager.js.map +7 -0
- package/dist/multicast-transport.d.ts +271 -0
- package/dist/multicast-transport.d.ts.map +1 -0
- package/dist/multicast-transport.js +2264 -0
- package/dist/multicast-transport.js.map +7 -0
- package/dist/multicast-unwrap.d.ts +57 -0
- package/dist/multicast-unwrap.d.ts.map +1 -0
- package/dist/multicast-unwrap.js +418 -0
- package/dist/multicast-unwrap.js.map +7 -0
- package/dist/no-modules.d.ts +10 -0
- package/dist/no-modules.d.ts.map +1 -0
- package/dist/no-modules.js +9491 -0
- package/dist/no-modules.js.map +7 -0
- package/dist/phase14-catalog-override.d.ts +126 -0
- package/dist/phase14-catalog-override.d.ts.map +1 -0
- package/dist/phase14-catalog-override.js +155 -0
- package/dist/phase14-catalog-override.js.map +7 -0
- package/dist/repair-fetch.d.ts +270 -0
- package/dist/repair-fetch.d.ts.map +1 -0
- package/dist/repair-fetch.js +381 -0
- package/dist/repair-fetch.js.map +7 -0
- package/dist/repair-layers.d.ts +158 -0
- package/dist/repair-layers.d.ts.map +1 -0
- package/dist/repair-layers.js +344 -0
- package/dist/repair-layers.js.map +7 -0
- package/dist/sample-combiner.d.ts +212 -0
- package/dist/sample-combiner.d.ts.map +1 -0
- package/dist/sample-combiner.js +595 -0
- package/dist/sample-combiner.js.map +7 -0
- package/dist/signaling.d.ts +29 -0
- package/dist/signaling.d.ts.map +1 -0
- package/dist/signaling.js +572 -0
- package/dist/signaling.js.map +7 -0
- package/dist/source-auth.d.ts +2 -0
- package/dist/source-auth.d.ts.map +1 -0
- package/dist/source-auth.js +1209 -0
- package/dist/source-auth.js.map +7 -0
- package/dist/switching-set-alignment.d.ts +61 -0
- package/dist/switching-set-alignment.d.ts.map +1 -0
- package/dist/switching-set-alignment.js +70 -0
- package/dist/switching-set-alignment.js.map +7 -0
- package/dist/timestamp-codec.d.ts +34 -0
- package/dist/timestamp-codec.d.ts.map +1 -0
- package/dist/timestamp-codec.js +473 -0
- package/dist/timestamp-codec.js.map +7 -0
- package/dist/track-pipeline-setup.d.ts +83 -0
- package/dist/track-pipeline-setup.d.ts.map +1 -0
- package/dist/track-pipeline-setup.js +291 -0
- package/dist/track-pipeline-setup.js.map +7 -0
- package/dist/track-pipeline.d.ts +121 -0
- package/dist/track-pipeline.d.ts.map +1 -0
- package/dist/track-pipeline.js +209 -0
- package/dist/track-pipeline.js.map +7 -0
- package/dist/track-session.d.ts +414 -0
- package/dist/track-session.d.ts.map +1 -0
- package/dist/track-session.js +754 -0
- package/dist/track-session.js.map +7 -0
- package/dist/transport-pool.d.ts +69 -0
- package/dist/transport-pool.d.ts.map +1 -0
- package/dist/transport-pool.js +74 -0
- package/dist/transport-pool.js.map +7 -0
- package/dist/wasm-mfu-reassembler.d.ts +97 -0
- package/dist/wasm-mfu-reassembler.d.ts.map +1 -0
- package/dist/wasm-mfu-reassembler.js +2133 -0
- package/dist/wasm-mfu-reassembler.js.map +7 -0
- package/dist/wasm-mmtp-container-parser.d.ts +10 -0
- package/dist/wasm-mmtp-container-parser.d.ts.map +1 -0
- package/dist/wasm-mmtp-container-parser.js +6834 -0
- package/dist/wasm-mmtp-container-parser.js.map +7 -0
- package/node_modules/@blockcast/fec-worker/README.md +223 -0
- package/node_modules/@blockcast/fec-worker/dist/.build-stamp +0 -0
- package/node_modules/@blockcast/fec-worker/dist/block-order.d.ts +38 -0
- package/node_modules/@blockcast/fec-worker/dist/block-order.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/block-order.js +78 -0
- package/node_modules/@blockcast/fec-worker/dist/block-order.js.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +93 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +346 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts +380 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.js +11 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.js.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker.d.ts +14 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker.js +859 -0
- package/node_modules/@blockcast/fec-worker/dist/fec-worker.js.map +7 -0
- package/node_modules/@blockcast/fec-worker/dist/index.d.ts +10 -0
- package/node_modules/@blockcast/fec-worker/dist/index.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/index.js +8 -0
- package/node_modules/@blockcast/fec-worker/dist/index.js.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.d.ts +20 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.js +370 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-fec-worker.js.map +7 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.d.ts +104 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.js +181 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-client.js.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.d.ts +194 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.js +62 -0
- package/node_modules/@blockcast/fec-worker/dist/shred-worker-types.js.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/transfer.d.ts +9 -0
- package/node_modules/@blockcast/fec-worker/dist/transfer.d.ts.map +1 -0
- package/node_modules/@blockcast/fec-worker/dist/transfer.js +13 -0
- package/node_modules/@blockcast/fec-worker/dist/transfer.js.map +1 -0
- package/node_modules/@blockcast/fec-worker/package.json +59 -0
- package/node_modules/@blockcast/fec-worker/src/block-order.ts +93 -0
- package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +392 -0
- package/node_modules/@blockcast/fec-worker/src/fec-worker-types.ts +399 -0
- package/node_modules/@blockcast/fec-worker/src/fec-worker.ts +1502 -0
- package/node_modules/@blockcast/fec-worker/src/index.ts +35 -0
- package/node_modules/@blockcast/fec-worker/src/shred-fec-worker.ts +589 -0
- package/node_modules/@blockcast/fec-worker/src/shred-worker-client.ts +222 -0
- package/node_modules/@blockcast/fec-worker/src/shred-worker-types.ts +209 -0
- package/node_modules/@blockcast/fec-worker/src/transfer.ts +12 -0
- package/node_modules/@blockcast/mmt-alta-parse/README.md +181 -0
- package/node_modules/@blockcast/mmt-alta-parse/dist/.build-stamp +0 -0
- package/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts +57 -0
- package/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-alta-parse/dist/index.js +115 -0
- package/node_modules/@blockcast/mmt-alta-parse/dist/index.js.map +1 -0
- package/node_modules/@blockcast/mmt-alta-parse/package.json +50 -0
- package/node_modules/@blockcast/mmt-alta-parse/src/index.ts +136 -0
- package/node_modules/@blockcast/mmt-base/README.md +134 -0
- package/node_modules/@blockcast/mmt-base/dist/.build-stamp +0 -0
- package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts +55 -0
- package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js +128 -0
- package/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/index.d.ts +7 -0
- package/node_modules/@blockcast/mmt-base/dist/index.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/index.js +7 -0
- package/node_modules/@blockcast/mmt-base/dist/index.js.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +292 -0
- package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/mmtp.js +612 -0
- package/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts +18 -0
- package/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/net-constants.js +18 -0
- package/node_modules/@blockcast/mmt-base/dist/net-constants.js.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts +47 -0
- package/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/ntp-short.js +54 -0
- package/node_modules/@blockcast/mmt-base/dist/ntp-short.js.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts +57 -0
- package/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/serial-number.js +98 -0
- package/node_modules/@blockcast/mmt-base/dist/serial-number.js.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/signalling.d.ts +312 -0
- package/node_modules/@blockcast/mmt-base/dist/signalling.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-base/dist/signalling.js +637 -0
- package/node_modules/@blockcast/mmt-base/dist/signalling.js.map +1 -0
- package/node_modules/@blockcast/mmt-base/package.json +49 -0
- package/node_modules/@blockcast/mmt-base/src/fec-block-profile.ts +145 -0
- package/node_modules/@blockcast/mmt-base/src/index.ts +6 -0
- package/node_modules/@blockcast/mmt-base/src/mmtp.ts +892 -0
- package/node_modules/@blockcast/mmt-base/src/net-constants.ts +17 -0
- package/node_modules/@blockcast/mmt-base/src/ntp-short.ts +67 -0
- package/node_modules/@blockcast/mmt-base/src/serial-number.ts +107 -0
- package/node_modules/@blockcast/mmt-base/src/signalling.ts +862 -0
- package/node_modules/@blockcast/mmt-fec/README.md +271 -0
- package/node_modules/@blockcast/mmt-fec/dist/.build-stamp +0 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-manager.d.ts +82 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-manager.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-manager.js +296 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-manager.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-processor.d.ts +106 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-processor.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-processor.js +288 -0
- package/node_modules/@blockcast/mmt-fec/dist/block-processor.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.d.ts +46 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.js +96 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-recovery.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.d.ts +33 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.js +57 -0
- package/node_modules/@blockcast/mmt-fec/dist/cmaf-symbols.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.d.ts +205 -0
- package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.js +240 -0
- package/node_modules/@blockcast/mmt-fec/dist/fec-block-mapper.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/index.d.ts +28 -0
- package/node_modules/@blockcast/mmt-fec/dist/index.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/index.js +28 -0
- package/node_modules/@blockcast/mmt-fec/dist/index.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.d.ts +20 -0
- package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.js +28 -0
- package/node_modules/@blockcast/mmt-fec/dist/loc-symbols.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/oti.d.ts +258 -0
- package/node_modules/@blockcast/mmt-fec/dist/oti.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/oti.js +382 -0
- package/node_modules/@blockcast/mmt-fec/dist/oti.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.d.ts +41 -0
- package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.js +81 -0
- package/node_modules/@blockcast/mmt-fec/dist/reorder-buffer.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/repair-group.d.ts +82 -0
- package/node_modules/@blockcast/mmt-fec/dist/repair-group.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/dist/repair-group.js +170 -0
- package/node_modules/@blockcast/mmt-fec/dist/repair-group.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/README.md +181 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/.build-stamp +0 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts +57 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.js +115 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/dist/index.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/package.json +50 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-alta-parse/src/index.ts +136 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/README.md +134 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/.build-stamp +0 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts +55 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js +128 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/fec-block-profile.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.d.ts +7 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.js +7 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/index.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +292 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js +612 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts +18 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.js +18 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/net-constants.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts +47 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.js +54 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/ntp-short.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts +57 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.js +98 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/serial-number.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.d.ts +312 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.js +637 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/signalling.js.map +1 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/package.json +49 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/fec-block-profile.ts +145 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/index.ts +6 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/mmtp.ts +892 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/net-constants.ts +17 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/ntp-short.ts +67 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/serial-number.ts +107 -0
- package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/signalling.ts +862 -0
- package/node_modules/@blockcast/mmt-fec/package.json +79 -0
- package/node_modules/@blockcast/mmt-fec/src/block-manager.ts +371 -0
- package/node_modules/@blockcast/mmt-fec/src/block-processor.ts +439 -0
- package/node_modules/@blockcast/mmt-fec/src/cmaf-recovery.ts +127 -0
- package/node_modules/@blockcast/mmt-fec/src/cmaf-symbols.ts +68 -0
- package/node_modules/@blockcast/mmt-fec/src/fec-block-mapper.ts +310 -0
- package/node_modules/@blockcast/mmt-fec/src/index.ts +94 -0
- package/node_modules/@blockcast/mmt-fec/src/loc-symbols.ts +34 -0
- package/node_modules/@blockcast/mmt-fec/src/oti.ts +463 -0
- package/node_modules/@blockcast/mmt-fec/src/reorder-buffer.ts +101 -0
- package/node_modules/@blockcast/mmt-fec/src/repair-group.ts +195 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/.build-stamp +0 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.d.ts +28 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.js +128 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/admission.js.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/index.d.ts +4 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/index.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/index.js +4 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/index.js.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.d.ts +37 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.js +179 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/source-auth.js.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.d.ts +99 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.d.ts.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.js +492 -0
- package/node_modules/@blockcast/mmt-manifest-verify/dist/verifier.js.map +1 -0
- package/node_modules/@blockcast/mmt-manifest-verify/package.json +45 -0
- package/node_modules/@blockcast/mmt-manifest-verify/src/admission.ts +171 -0
- package/node_modules/@blockcast/mmt-manifest-verify/src/index.ts +3 -0
- package/node_modules/@blockcast/mmt-manifest-verify/src/source-auth.ts +230 -0
- package/node_modules/@blockcast/mmt-manifest-verify/src/verifier.ts +669 -0
- package/node_modules/@noble/hashes/LICENSE +21 -0
- package/node_modules/@noble/hashes/README.md +521 -0
- package/node_modules/@noble/hashes/_assert.d.ts +17 -0
- package/node_modules/@noble/hashes/_assert.d.ts.map +1 -0
- package/node_modules/@noble/hashes/_assert.js +18 -0
- package/node_modules/@noble/hashes/_assert.js.map +1 -0
- package/node_modules/@noble/hashes/_blake.d.ts +14 -0
- package/node_modules/@noble/hashes/_blake.d.ts.map +1 -0
- package/node_modules/@noble/hashes/_blake.js +50 -0
- package/node_modules/@noble/hashes/_blake.js.map +1 -0
- package/node_modules/@noble/hashes/_md.d.ts +51 -0
- package/node_modules/@noble/hashes/_md.d.ts.map +1 -0
- package/node_modules/@noble/hashes/_md.js +162 -0
- package/node_modules/@noble/hashes/_md.js.map +1 -0
- package/node_modules/@noble/hashes/_u64.d.ts +55 -0
- package/node_modules/@noble/hashes/_u64.d.ts.map +1 -0
- package/node_modules/@noble/hashes/_u64.js +90 -0
- package/node_modules/@noble/hashes/_u64.js.map +1 -0
- package/node_modules/@noble/hashes/argon2.d.ts +32 -0
- package/node_modules/@noble/hashes/argon2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/argon2.js +401 -0
- package/node_modules/@noble/hashes/argon2.js.map +1 -0
- package/node_modules/@noble/hashes/blake1.d.ts +106 -0
- package/node_modules/@noble/hashes/blake1.d.ts.map +1 -0
- package/node_modules/@noble/hashes/blake1.js +459 -0
- package/node_modules/@noble/hashes/blake1.js.map +1 -0
- package/node_modules/@noble/hashes/blake2.d.ts +116 -0
- package/node_modules/@noble/hashes/blake2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/blake2.js +420 -0
- package/node_modules/@noble/hashes/blake2.js.map +1 -0
- package/node_modules/@noble/hashes/blake2b.d.ts +11 -0
- package/node_modules/@noble/hashes/blake2b.d.ts.map +1 -0
- package/node_modules/@noble/hashes/blake2b.js +14 -0
- package/node_modules/@noble/hashes/blake2b.js.map +1 -0
- package/node_modules/@noble/hashes/blake2s.d.ts +20 -0
- package/node_modules/@noble/hashes/blake2s.d.ts.map +1 -0
- package/node_modules/@noble/hashes/blake2s.js +24 -0
- package/node_modules/@noble/hashes/blake2s.js.map +1 -0
- package/node_modules/@noble/hashes/blake3.d.ts +54 -0
- package/node_modules/@noble/hashes/blake3.d.ts.map +1 -0
- package/node_modules/@noble/hashes/blake3.js +255 -0
- package/node_modules/@noble/hashes/blake3.js.map +1 -0
- package/node_modules/@noble/hashes/crypto.d.ts +2 -0
- package/node_modules/@noble/hashes/crypto.d.ts.map +1 -0
- package/node_modules/@noble/hashes/crypto.js +5 -0
- package/node_modules/@noble/hashes/crypto.js.map +1 -0
- package/node_modules/@noble/hashes/cryptoNode.d.ts +2 -0
- package/node_modules/@noble/hashes/cryptoNode.d.ts.map +1 -0
- package/node_modules/@noble/hashes/cryptoNode.js +18 -0
- package/node_modules/@noble/hashes/cryptoNode.js.map +1 -0
- package/node_modules/@noble/hashes/eskdf.d.ts +47 -0
- package/node_modules/@noble/hashes/eskdf.d.ts.map +1 -0
- package/node_modules/@noble/hashes/eskdf.js +166 -0
- package/node_modules/@noble/hashes/eskdf.js.map +1 -0
- package/node_modules/@noble/hashes/esm/_assert.d.ts +17 -0
- package/node_modules/@noble/hashes/esm/_assert.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/_assert.js +15 -0
- package/node_modules/@noble/hashes/esm/_assert.js.map +1 -0
- package/node_modules/@noble/hashes/esm/_blake.d.ts +14 -0
- package/node_modules/@noble/hashes/esm/_blake.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/_blake.js +45 -0
- package/node_modules/@noble/hashes/esm/_blake.js.map +1 -0
- package/node_modules/@noble/hashes/esm/_md.d.ts +51 -0
- package/node_modules/@noble/hashes/esm/_md.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/_md.js +155 -0
- package/node_modules/@noble/hashes/esm/_md.js.map +1 -0
- package/node_modules/@noble/hashes/esm/_u64.d.ts +55 -0
- package/node_modules/@noble/hashes/esm/_u64.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/_u64.js +67 -0
- package/node_modules/@noble/hashes/esm/_u64.js.map +1 -0
- package/node_modules/@noble/hashes/esm/argon2.d.ts +32 -0
- package/node_modules/@noble/hashes/esm/argon2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/argon2.js +392 -0
- package/node_modules/@noble/hashes/esm/argon2.js.map +1 -0
- package/node_modules/@noble/hashes/esm/blake1.d.ts +106 -0
- package/node_modules/@noble/hashes/esm/blake1.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/blake1.js +452 -0
- package/node_modules/@noble/hashes/esm/blake1.js.map +1 -0
- package/node_modules/@noble/hashes/esm/blake2.d.ts +116 -0
- package/node_modules/@noble/hashes/esm/blake2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/blake2.js +413 -0
- package/node_modules/@noble/hashes/esm/blake2.js.map +1 -0
- package/node_modules/@noble/hashes/esm/blake2b.d.ts +11 -0
- package/node_modules/@noble/hashes/esm/blake2b.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/blake2b.js +11 -0
- package/node_modules/@noble/hashes/esm/blake2b.js.map +1 -0
- package/node_modules/@noble/hashes/esm/blake2s.d.ts +20 -0
- package/node_modules/@noble/hashes/esm/blake2s.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/blake2s.js +21 -0
- package/node_modules/@noble/hashes/esm/blake2s.js.map +1 -0
- package/node_modules/@noble/hashes/esm/blake3.d.ts +54 -0
- package/node_modules/@noble/hashes/esm/blake3.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/blake3.js +251 -0
- package/node_modules/@noble/hashes/esm/blake3.js.map +1 -0
- package/node_modules/@noble/hashes/esm/crypto.d.ts +2 -0
- package/node_modules/@noble/hashes/esm/crypto.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/crypto.js +2 -0
- package/node_modules/@noble/hashes/esm/crypto.js.map +1 -0
- package/node_modules/@noble/hashes/esm/cryptoNode.d.ts +2 -0
- package/node_modules/@noble/hashes/esm/cryptoNode.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/cryptoNode.js +15 -0
- package/node_modules/@noble/hashes/esm/cryptoNode.js.map +1 -0
- package/node_modules/@noble/hashes/esm/eskdf.d.ts +47 -0
- package/node_modules/@noble/hashes/esm/eskdf.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/eskdf.js +160 -0
- package/node_modules/@noble/hashes/esm/eskdf.js.map +1 -0
- package/node_modules/@noble/hashes/esm/hkdf.d.ts +36 -0
- package/node_modules/@noble/hashes/esm/hkdf.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/hkdf.js +82 -0
- package/node_modules/@noble/hashes/esm/hkdf.js.map +1 -0
- package/node_modules/@noble/hashes/esm/hmac.d.ts +35 -0
- package/node_modules/@noble/hashes/esm/hmac.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/hmac.js +86 -0
- package/node_modules/@noble/hashes/esm/hmac.js.map +1 -0
- package/node_modules/@noble/hashes/esm/index.d.ts +2 -0
- package/node_modules/@noble/hashes/esm/index.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/index.js +33 -0
- package/node_modules/@noble/hashes/esm/index.js.map +1 -0
- package/node_modules/@noble/hashes/esm/legacy.d.ts +71 -0
- package/node_modules/@noble/hashes/esm/legacy.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/legacy.js +281 -0
- package/node_modules/@noble/hashes/esm/legacy.js.map +1 -0
- package/node_modules/@noble/hashes/esm/package.json +10 -0
- package/node_modules/@noble/hashes/esm/pbkdf2.d.ts +23 -0
- package/node_modules/@noble/hashes/esm/pbkdf2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/pbkdf2.js +97 -0
- package/node_modules/@noble/hashes/esm/pbkdf2.js.map +1 -0
- package/node_modules/@noble/hashes/esm/ripemd160.d.ts +13 -0
- package/node_modules/@noble/hashes/esm/ripemd160.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/ripemd160.js +13 -0
- package/node_modules/@noble/hashes/esm/ripemd160.js.map +1 -0
- package/node_modules/@noble/hashes/esm/scrypt.d.ts +34 -0
- package/node_modules/@noble/hashes/esm/scrypt.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/scrypt.js +228 -0
- package/node_modules/@noble/hashes/esm/scrypt.js.map +1 -0
- package/node_modules/@noble/hashes/esm/sha1.d.ts +11 -0
- package/node_modules/@noble/hashes/esm/sha1.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/sha1.js +11 -0
- package/node_modules/@noble/hashes/esm/sha1.js.map +1 -0
- package/node_modules/@noble/hashes/esm/sha2.d.ts +159 -0
- package/node_modules/@noble/hashes/esm/sha2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/sha2.js +375 -0
- package/node_modules/@noble/hashes/esm/sha2.js.map +1 -0
- package/node_modules/@noble/hashes/esm/sha256.d.ts +20 -0
- package/node_modules/@noble/hashes/esm/sha256.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/sha256.js +20 -0
- package/node_modules/@noble/hashes/esm/sha256.js.map +1 -0
- package/node_modules/@noble/hashes/esm/sha3-addons.d.ts +142 -0
- package/node_modules/@noble/hashes/esm/sha3-addons.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/sha3-addons.js +393 -0
- package/node_modules/@noble/hashes/esm/sha3-addons.js.map +1 -0
- package/node_modules/@noble/hashes/esm/sha3.d.ts +53 -0
- package/node_modules/@noble/hashes/esm/sha3.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/sha3.js +234 -0
- package/node_modules/@noble/hashes/esm/sha3.js.map +1 -0
- package/node_modules/@noble/hashes/esm/sha512.d.ts +26 -0
- package/node_modules/@noble/hashes/esm/sha512.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/sha512.js +26 -0
- package/node_modules/@noble/hashes/esm/sha512.js.map +1 -0
- package/node_modules/@noble/hashes/esm/utils.d.ts +161 -0
- package/node_modules/@noble/hashes/esm/utils.d.ts.map +1 -0
- package/node_modules/@noble/hashes/esm/utils.js +281 -0
- package/node_modules/@noble/hashes/esm/utils.js.map +1 -0
- package/node_modules/@noble/hashes/hkdf.d.ts +36 -0
- package/node_modules/@noble/hashes/hkdf.d.ts.map +1 -0
- package/node_modules/@noble/hashes/hkdf.js +88 -0
- package/node_modules/@noble/hashes/hkdf.js.map +1 -0
- package/node_modules/@noble/hashes/hmac.d.ts +35 -0
- package/node_modules/@noble/hashes/hmac.d.ts.map +1 -0
- package/node_modules/@noble/hashes/hmac.js +91 -0
- package/node_modules/@noble/hashes/hmac.js.map +1 -0
- package/node_modules/@noble/hashes/index.d.ts +1 -0
- package/node_modules/@noble/hashes/index.d.ts.map +1 -0
- package/node_modules/@noble/hashes/index.js +33 -0
- package/node_modules/@noble/hashes/index.js.map +1 -0
- package/node_modules/@noble/hashes/legacy.d.ts +71 -0
- package/node_modules/@noble/hashes/legacy.d.ts.map +1 -0
- package/node_modules/@noble/hashes/legacy.js +287 -0
- package/node_modules/@noble/hashes/legacy.js.map +1 -0
- package/node_modules/@noble/hashes/package.json +266 -0
- package/node_modules/@noble/hashes/pbkdf2.d.ts +23 -0
- package/node_modules/@noble/hashes/pbkdf2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/pbkdf2.js +101 -0
- package/node_modules/@noble/hashes/pbkdf2.js.map +1 -0
- package/node_modules/@noble/hashes/ripemd160.d.ts +13 -0
- package/node_modules/@noble/hashes/ripemd160.d.ts.map +1 -0
- package/node_modules/@noble/hashes/ripemd160.js +16 -0
- package/node_modules/@noble/hashes/ripemd160.js.map +1 -0
- package/node_modules/@noble/hashes/scrypt.d.ts +34 -0
- package/node_modules/@noble/hashes/scrypt.d.ts.map +1 -0
- package/node_modules/@noble/hashes/scrypt.js +232 -0
- package/node_modules/@noble/hashes/scrypt.js.map +1 -0
- package/node_modules/@noble/hashes/sha1.d.ts +11 -0
- package/node_modules/@noble/hashes/sha1.d.ts.map +1 -0
- package/node_modules/@noble/hashes/sha1.js +14 -0
- package/node_modules/@noble/hashes/sha1.js.map +1 -0
- package/node_modules/@noble/hashes/sha2.d.ts +159 -0
- package/node_modules/@noble/hashes/sha2.d.ts.map +1 -0
- package/node_modules/@noble/hashes/sha2.js +384 -0
- package/node_modules/@noble/hashes/sha2.js.map +1 -0
- package/node_modules/@noble/hashes/sha256.d.ts +20 -0
- package/node_modules/@noble/hashes/sha256.d.ts.map +1 -0
- package/node_modules/@noble/hashes/sha256.js +23 -0
- package/node_modules/@noble/hashes/sha256.js.map +1 -0
- package/node_modules/@noble/hashes/sha3-addons.d.ts +142 -0
- package/node_modules/@noble/hashes/sha3-addons.d.ts.map +1 -0
- package/node_modules/@noble/hashes/sha3-addons.js +402 -0
- package/node_modules/@noble/hashes/sha3-addons.js.map +1 -0
- package/node_modules/@noble/hashes/sha3.d.ts +53 -0
- package/node_modules/@noble/hashes/sha3.d.ts.map +1 -0
- package/node_modules/@noble/hashes/sha3.js +239 -0
- package/node_modules/@noble/hashes/sha3.js.map +1 -0
- package/node_modules/@noble/hashes/sha512.d.ts +26 -0
- package/node_modules/@noble/hashes/sha512.d.ts.map +1 -0
- package/node_modules/@noble/hashes/sha512.js +29 -0
- package/node_modules/@noble/hashes/sha512.js.map +1 -0
- package/node_modules/@noble/hashes/src/_assert.ts +22 -0
- package/node_modules/@noble/hashes/src/_blake.ts +50 -0
- package/node_modules/@noble/hashes/src/_md.ts +176 -0
- package/node_modules/@noble/hashes/src/_u64.ts +91 -0
- package/node_modules/@noble/hashes/src/argon2.ts +497 -0
- package/node_modules/@noble/hashes/src/blake1.ts +534 -0
- package/node_modules/@noble/hashes/src/blake2.ts +486 -0
- package/node_modules/@noble/hashes/src/blake2b.ts +10 -0
- package/node_modules/@noble/hashes/src/blake2s.ts +20 -0
- package/node_modules/@noble/hashes/src/blake3.ts +272 -0
- package/node_modules/@noble/hashes/src/crypto.ts +9 -0
- package/node_modules/@noble/hashes/src/cryptoNode.ts +15 -0
- package/node_modules/@noble/hashes/src/eskdf.ts +187 -0
- package/node_modules/@noble/hashes/src/hkdf.ts +88 -0
- package/node_modules/@noble/hashes/src/hmac.ts +94 -0
- package/node_modules/@noble/hashes/src/index.ts +31 -0
- package/node_modules/@noble/hashes/src/legacy.ts +293 -0
- package/node_modules/@noble/hashes/src/pbkdf2.ts +122 -0
- package/node_modules/@noble/hashes/src/ripemd160.ts +12 -0
- package/node_modules/@noble/hashes/src/scrypt.ts +257 -0
- package/node_modules/@noble/hashes/src/sha1.ts +10 -0
- package/node_modules/@noble/hashes/src/sha2.ts +402 -0
- package/node_modules/@noble/hashes/src/sha256.ts +24 -0
- package/node_modules/@noble/hashes/src/sha3-addons.ts +499 -0
- package/node_modules/@noble/hashes/src/sha3.ts +258 -0
- package/node_modules/@noble/hashes/src/sha512.ts +34 -0
- package/node_modules/@noble/hashes/src/utils.ts +395 -0
- package/node_modules/@noble/hashes/utils.d.ts +161 -0
- package/node_modules/@noble/hashes/utils.d.ts.map +1 -0
- package/node_modules/@noble/hashes/utils.js +313 -0
- package/node_modules/@noble/hashes/utils.js.map +1 -0
- package/package.json +179 -8
- package/schemas/catalog.schema.json +357 -0
- package/src/align.ts +239 -0
- package/src/audio-init-parser.ts +189 -0
- package/src/audio-ring-buffer.ts +120 -0
- package/src/authored-timing.ts +63 -0
- package/src/block-policy.ts +903 -0
- package/src/carp-catalog.ts +1065 -0
- package/src/catalog-fec-params.ts +729 -0
- package/src/catalog-network-source.ts +74 -0
- package/src/catalog-validator.ts +34 -0
- package/src/cmaf-block-assembler.ts +1255 -0
- package/src/cmaf-group-batcher.ts +104 -0
- package/src/cmcd-producer.ts +329 -0
- package/src/codec-utils.ts +1984 -0
- package/src/conceal-timeline.ts +293 -0
- package/src/delivery-gap.ts +147 -0
- package/src/duplicate-ledger.ts +372 -0
- package/src/fec-codec.ts +61 -0
- package/src/fec-manager.ts +4298 -0
- package/src/fec-starvation-detector.ts +128 -0
- package/src/fec-state.ts +219 -0
- package/src/fec-worker-setup.ts +283 -0
- package/src/fmp4-completion.ts +47 -0
- package/src/fmp4-reader.ts +112 -0
- package/src/index.ts +590 -21
- package/src/iso-block-locator.ts +329 -0
- package/src/iso-bmff-timing.ts +813 -0
- package/src/loc.ts +128 -154
- package/src/manifest-auth-plan.ts +107 -0
- package/src/media-router.ts +841 -0
- package/src/mfu-reassembler.ts +3480 -155
- package/src/mfu-reassembly-policy.ts +134 -0
- package/src/mmtp-container-parser.ts +2380 -0
- package/src/mmtp-decode-pipeline.ts +406 -0
- package/src/mmtp-router.ts +4860 -0
- package/src/mmtp-to-cmaf.ts +977 -0
- package/src/multicast-auth-catalog.ts +340 -0
- package/src/multicast-input.ts +793 -0
- package/src/multicast-manager.ts +2783 -0
- package/src/multicast-transport.ts +1058 -0
- package/src/multicast-unwrap.ts +132 -0
- package/src/no-modules.ts +21 -0
- package/src/phase14-catalog-override.ts +336 -0
- package/src/repair-fetch.ts +772 -0
- package/src/repair-layers.ts +533 -0
- package/src/sample-combiner.ts +938 -0
- package/src/signaling.ts +78 -0
- package/src/source-auth.ts +1 -0
- package/src/switching-set-alignment.ts +109 -0
- package/src/timestamp-codec.ts +265 -0
- package/src/track-pipeline-setup.ts +205 -0
- package/src/track-pipeline.ts +332 -0
- package/src/track-session.ts +1010 -0
- package/src/transport-pool.ts +128 -0
- package/src/wasm-mfu-reassembler.ts +405 -0
- package/src/wasm-mmtp-container-parser.ts +23 -0
- package/test-vectors/align.json +199 -0
- package/test-vectors/catalog/README.md +106 -0
- package/test-vectors/catalog/negative/archive-origin-with-path.json +33 -0
- package/test-vectors/catalog/negative/archive-unknown-field.json +34 -0
- package/test-vectors/catalog/negative/fec-block-profile-missing.json +51 -0
- package/test-vectors/catalog/negative/fec-block-profile-unknown.json +52 -0
- package/test-vectors/catalog/negative/fec-enhancement-repair-removed.json +28 -0
- package/test-vectors/catalog/negative/fec-repair-layer-geometry.json +33 -0
- package/test-vectors/catalog/negative/fec-repair-layer-missing-symbols.json +31 -0
- package/test-vectors/catalog/negative/fec-repair-multiple-depends.json +32 -0
- package/test-vectors/catalog/negative/fec-repair-overlay-with-layer.json +34 -0
- package/test-vectors/catalog/negative/fec-repair-priority-out-of-band.json +24 -0
- package/test-vectors/catalog/negative/fec-repair-source-symbols-without-scope.json +33 -0
- package/test-vectors/catalog/negative/legacy-selection-params.json +15 -0
- package/test-vectors/catalog/negative/media-track-repair-layer.json +16 -0
- package/test-vectors/catalog/negative/missing-mmtp-fields.json +12 -0
- package/test-vectors/catalog/negative/multicast-auth-padded-key.json +37 -0
- package/test-vectors/catalog/negative/multicast-auth-reused-track-format.json +53 -0
- package/test-vectors/catalog/negative/multicast-auth-trailing-pad-bits.json +37 -0
- package/test-vectors/catalog/negative/multicast-endpoint-missing-protocol-and-source.json +24 -0
- package/test-vectors/catalog/negative/multicast-network-source-empty.json +44 -0
- package/test-vectors/catalog/negative/multicast-packet-id-signaling.json +26 -0
- package/test-vectors/catalog/negative/network-source-object.json +25 -0
- package/test-vectors/catalog/negative/raptorq-source-symbols-over-max.json +24 -0
- package/test-vectors/catalog/negative/raptorq-unaligned-symbol.json +27 -0
- package/test-vectors/catalog/negative/repair-track-legacy-shape.json +19 -0
- package/test-vectors/catalog/negative/track-role-empty.json +16 -0
- package/test-vectors/catalog/negative/track-role-non-string.json +16 -0
- package/test-vectors/catalog/positive/archive-origin.json +34 -0
- package/test-vectors/catalog/positive/fec-iso-ssbg1.json +52 -0
- package/test-vectors/catalog/positive/fec-layered-repair.json +106 -0
- package/test-vectors/catalog/positive/fec-multicast.json +52 -0
- package/test-vectors/catalog/positive/flat-av.json +30 -0
- package/test-vectors/catalog/positive/multicast-auth-rotation.json +55 -0
- package/test-vectors/catalog/positive/multicast-native-ssm-no-network-source.json +43 -0
- package/test-vectors/catalog/positive/ticks-and-mixed-timescales.json +39 -0
- package/test-vectors/catalog/positive/track-role.json +49 -0
- package/test-vectors/catalog/releases/moqcast-native-v16-v1/catalog.json +65 -0
- package/test-vectors/catalog/releases/moqcast-native-v16-v1.archive.sha256 +1 -0
- package/test-vectors/catalog-multicast-auth-v1.json +26 -0
- package/test-vectors/catalog-validation.json +732 -0
- package/test-vectors/catalog-validator-public-api.mjs +25 -0
- package/test-vectors/generate-source-auth-fixture.mjs +114 -0
- package/test-vectors/hevc-x265-repeat-headers-v1.json +40 -0
- package/test-vectors/source-auth-v1.json +61 -0
- package/test-vectors/source-contiguity-v1.json +131 -0
- package/test-vectors/subsample-placement-v1.json +230 -0
- package/dist/mmtp.d.ts +0 -73
- package/dist/mmtp.d.ts.map +0 -1
- package/dist/mmtp.js +0 -210
- package/dist/mmtp.js.map +0 -1
- package/src/mmtp.ts +0 -277
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../mmt-alta-parse/src/index.ts", "../../mmt-base/src/mmtp.ts", "../../mmt-base/src/ntp-short.ts", "../../mmt-base/src/serial-number.ts", "../../mmt-base/src/fec-block-profile.ts", "../src/mfu-reassembler.ts", "../src/codec-utils.ts", "../src/authored-timing.ts", "../src/mmtp-router.ts", "../src/mmtp-to-cmaf.ts", "../src/conceal-timeline.ts", "../src/cmaf-block-assembler.ts", "../src/sample-combiner.ts", "../src/mfu-reassembly-policy.ts", "../src/iso-bmff-timing.ts", "../src/mmtp-container-parser.ts", "../src/block-policy.ts", "../src/duplicate-ledger.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Zero-dependency helper for extracting the detached ALTA authenticator trailer\n * from an MMTP source packet.\n *\n * Lives in its own leaf package so both `@blockcast/mmt-container` (wire-path\n * parsing) and `@blockcast/fec-worker` (FEC-recovered-source parsing) can share\n * one implementation without creating a package cycle between them.\n *\n * Spec: ISO/IEC 23008-1:2023 + draft-ramadan-moq-mmt \u00A712 (detached trailer, Path 2).\n */\n\n// --- Private MMTP/MPU/MFU constants (ISO/IEC 23008-1 \u00A79.2.2\u20139.2.3) ---\n// Duplicated here as immutable spec values so this package stays a leaf with\n// zero `@blockcast/*` dependencies. Re-deriving from `mmt-container` would\n// reintroduce the package cycle this split exists to avoid.\n\nconst MMTP_HEADER_SIZE = 12\nconst MPU_HEADER_SIZE = 8\nconst MPU_LENGTH_FIELD_SIZE = 2\nconst MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE\nconst TIMED_MFU_DU_HEADER_SIZE = 14\nconst NONTIMED_MFU_DU_HEADER_SIZE = 4\nconst PACKET_TYPE_MPU = 0x00\n\n// --- Public ALTA trailer constants ---\n\n/**\n * MMTP header-extension ext_type assigned to the detached ALTA authenticator\n * trailer (Path 2 / 08-07). Carried in an `[ext_type][ext_length][auth]`\n * block appended after the MPU's declared payload bytes, before the 4-byte\n * Source FEC Payload ID. MMTP X-bit stays 0 \u2014 non-ALTA MMTP receivers treat\n * the trailer as bytes past `payload_length` and skip it (per ISO 23008-1\n * \u00A79.2.2 \"may be discarded without impacting correct processing\").\n */\nexport const MMTP_EXT_TYPE_ALTA_AUTH = 0xf0a1\n\n/** Fixed size of the trailer's `[ext_type][ext_length]` prefix (2 + 2 BE). */\nexport const MMTP_EXT_TRAILER_HEADER_SIZE = 4\n\n/** Result of extracting the detached ALTA authenticator from an MMTP packet. */\nexport interface AltaTrailer {\n /** Authenticator bytes (no ext_type/ext_length prefix, no trailing padding). */\n auth: Uint8Array\n /**\n * Wire-packet byte offset where the signed payload ends, i.e. where the\n * trailer begins. Caller uses this to produce\n * `payload = wirePacket.subarray(0, signedEnd)` for verify_detached.\n */\n signedEnd: number\n}\n\n/**\n * Extract the detached ALTA authenticator trailer from an MMTP source packet.\n *\n * Wire layout:\n * `[MMTP hdr][length(2)][remaining MPU hdr(6)][DU?][media][TRAILER][SS_ID?]`\n * `payload_length = 6 + DU bytes + media bytes`\n *\n * Returns `null` when:\n * - the packet is too small / malformed,\n * - `payload_length` cannot contain the remaining six MPU-header bytes,\n * - the declared payload overruns the packet,\n * - no bytes remain between `payload_length` and the SS_ID,\n * - the trailer's `ext_type` isn't {@link MMTP_EXT_TYPE_ALTA_AUTH},\n * - the declared `ext_length` would extend past the SS_ID boundary.\n *\n * Non-MPU packets (repair, signaling) always return `null`.\n *\n * @param options.skipFecId When true, do NOT reserve 4 trailing bytes for the\n * Source FEC Payload ID. Use on FEC-recovered symbols where the PID has\n * already been stripped upstream.\n */\nexport function extractAltaTrailer(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n): AltaTrailer | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n // ISO/IEC 23008-1:2023 Figure 8 places V=0 packet_type in the low six bits.\n const packetType = mmtpPacket[1]! & 0x3f\n if (packetType !== PACKET_TYPE_MPU) return null\n\n const fecType = (mmtpPacket[0]! >> 3) & 0x03\n let headerLength = MMTP_HEADER_SIZE\n if (fecType < 2 && (mmtpPacket[0]! & 0x20) !== 0) headerLength += 4\n if (fecType < 2 && (mmtpPacket[0]! & 0x02) !== 0) {\n if (headerLength + 4 > mmtpPacket.length) return null\n const extensionLength = new DataView(\n mmtpPacket.buffer,\n mmtpPacket.byteOffset + headerLength + 2,\n 2,\n ).getUint16(0, false)\n headerLength += 4 + extensionLength\n }\n if (headerLength + MPU_HEADER_SIZE > mmtpPacket.length) return null\n\n const payload = mmtpPacket.subarray(headerLength)\n\n // Inline a minimal MPU-header read \u2014 only the fields extractAltaTrailer needs.\n // payloadLength: 16 BE at bytes 0-1.\n // Byte 2 packs FT(4) | T(1) | FI(2) | A(1).\n const payloadLength = (payload[0]! << 8) | payload[1]!\n const flagsByte = payload[2]!\n const fragmentType = (flagsByte >> 4) & 0x0f\n const timed = ((flagsByte >> 3) & 0x01) === 1\n const fragmentationIndicator = (flagsByte >> 1) & 0x03\n\n // Only MFU packets (FT=2) carry the detached trailer.\n if (fragmentType !== 2) return null\n\n // FI=0/1 structurally carries a DU header; FI=2/3 does not. Require at\n // least one media byte after that deterministic layout so the bytes at the\n // declared boundary cannot impersonate ALTA for a header-only fragment.\n const dataUnitHeaderSize = fragmentationIndicator <= 1\n ? (timed ? TIMED_MFU_DU_HEADER_SIZE : NONTIMED_MFU_DU_HEADER_SIZE)\n : 0\n if (payloadLength <= MPU_HEADER_REMAINDER_SIZE + dataUnitHeaderSize) return null\n\n if (fecType > 1) return null\n const hasFecId = !options?.skipFecId && fecType === 1\n const payloadEnd = hasFecId ? payload.length - 4 : payload.length\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + payloadLength\n if (declaredEnd > payloadEnd) return null\n\n if (declaredEnd + MMTP_EXT_TRAILER_HEADER_SIZE > payloadEnd) return null\n const extType = (payload[declaredEnd]! << 8) | payload[declaredEnd + 1]!\n if (extType !== MMTP_EXT_TYPE_ALTA_AUTH) return null\n const extLen = (payload[declaredEnd + 2]! << 8) | payload[declaredEnd + 3]!\n\n const authStart = declaredEnd + MMTP_EXT_TRAILER_HEADER_SIZE\n if (authStart + extLen !== payloadEnd) return null\n\n return {\n auth: payload.subarray(authStart, payloadEnd),\n signedEnd: headerLength + declaredEnd,\n }\n}\n", "import {\n MMTP_EXT_TYPE_ALTA_AUTH as _LEAF_MMTP_EXT_TYPE_ALTA_AUTH,\n MMTP_EXT_TRAILER_HEADER_SIZE as _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE,\n extractAltaTrailer as _leafExtractAltaTrailer,\n type AltaTrailer as _LeafAltaTrailer,\n} from '@blockcast/mmt-alta-parse'\n\n/**\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\nconst 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 IDs\nexport const FEC_CODE_XOR = 1\nexport const FEC_CODE_RAPTORQ = 2\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\nfunction isEmptyOrExactAltaTrailer(payload: Uint8Array, start: number, end: number): boolean {\n if (start === end) return true\n if (start < 0 || end > payload.length || start + _LEAF_MMTP_EXT_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) !== _LEAF_MMTP_EXT_TYPE_ALTA_AUTH) return false\n\n const authLength = view.getUint16(2, false)\n return start + _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE + authLength === end\n}\n\ninterface DeclaredTrailerLayout {\n hasFecId: boolean\n}\n\nfunction resolveDeclaredTrailers(\n payload: Uint8Array,\n declaredEnd: number,\n fecType: number,\n options?: { skipFecId?: boolean },\n): DeclaredTrailerLayout | null {\n if (declaredEnd > payload.length) return null\n\n if (options?.skipFecId) {\n return isEmptyOrExactAltaTrailer(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 || !isEmptyOrExactAltaTrailer(payload, declaredEnd, fecStart)) {\n return null\n }\n return { hasFecId: true }\n }\n if (fecType !== 0) return null\n\n if (isEmptyOrExactAltaTrailer(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. ALTA and Source FEC\n * trailers 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-00 \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?: { skipFecId?: boolean },\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 if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {\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 ${SOURCE_FEC_PAYLOAD_ID_SIZE} ` +\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 ALTA 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?: { skipFecId?: boolean },\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?: { skipFecId?: boolean },\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?: { skipFecId?: boolean },\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 SOURCE_FEC_PAYLOAD_ID_SIZE,\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/**\n * MMTP header-extension ext_type assigned to the detached ALTA authenticator\n * trailer (Path 2 / 08-07). Carried in an `[ext_type][ext_length][auth]`\n * block appended after the MPU's declared payload bytes, before the 4-byte\n * Source FEC Payload ID. MMTP X-bit stays 0 \u2014 non-ALTA MMTP receivers treat\n * the trailer as bytes past `payload_length` and skip it (per ISO 23008-1\n * \u00A79.2.2 \"may be discarded without impacting correct processing\").\n */\n// Re-export the ALTA trailer helper from the zero-dep leaf package. The leaf\n// owns the implementation so container and FEC consumers share one parser\n// without creating a package cycle.\nexport const MMTP_EXT_TYPE_ALTA_AUTH = _LEAF_MMTP_EXT_TYPE_ALTA_AUTH\nexport const MMTP_EXT_TRAILER_HEADER_SIZE = _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE\nexport type AltaTrailer = _LeafAltaTrailer\nexport const extractAltaTrailer = _leafExtractAltaTrailer\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): MoqRepairFrame | null {\n if (!repairId) return null\n\n const symbolData = frame.subarray(repairId.dataOffset)\n if (\n repairId.rsbLength === 0 ||\n repairId.ssbLength === 0 ||\n 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// 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/**\n * First SS_ID of block `sbn` under the K-stride numbering every current\n * sender uses (`SS_ID = SBN * K + ESI`, C.5.2), reduced mod 2^32.\n */\nexport function kStrideBlockStart(sbn: number, k: number): number {\n assertUint32(sbn, 'sbn')\n if (!Number.isInteger(k) || k < 1 || k >= SERIAL32_HALF) {\n throw new RangeError(`k must be a positive integer below 2^31 (got ${k})`)\n }\n // sbn < 2^32 and k < 2^31 keep the product below 2^63, but a double is\n // exact only to 2^53; split the product so every step is exact.\n const high = Math.floor(sbn / 0x1_0000) // < 2^16\n const low = sbn % 0x1_0000 // < 2^16\n return (((high * k) % SERIAL32_SPAN) * 0x1_0000 + low * k) % SERIAL32_SPAN\n}\n\n/**\n * Whether block `a` precedes block `b`, ordering the blocks by their first\n * SS_ID in serial arithmetic. Identical to `a < b` for any two blocks of a\n * stream that has not wrapped SS_ID.\n */\nexport function kStrideBlockPrecedes(a: number, b: number, k: number): boolean {\n return serial32Precedes(kStrideBlockStart(a, k), kStrideBlockStart(b, k))\n}\n\n/**\n * How many blocks `a` lies behind `b`: 0 when `a` does not precede `b`,\n * otherwise `ceil(distance / K)` over the SS_ID distance between their first\n * symbols. Without a wrap that is exactly `b - a`; across the wrap the one\n * short pre-wrap block (2^32 mod K symbols) still counts as one block.\n */\nexport function kStrideBlocksBehind(a: number, b: number, k: number): number {\n const from = kStrideBlockStart(a, k)\n const to = kStrideBlockStart(b, k)\n if (!serial32Precedes(from, to)) return 0\n return Math.ceil(serial32Distance(from, to) / k)\n}\n\n/**\n * Whether `sbn` and `k` describe a block of the K-stride numbering:\n * `sbn` a uint32, `k` an integer in 1..2^31-1.\n */\nexport function isKStrideBlock(sbn: number, k: number): boolean {\n return Number.isInteger(sbn) && sbn >= 0 && sbn < SERIAL32_SPAN &&\n Number.isInteger(k) && k >= 1 && k < SERIAL32_HALF\n}\n\n/**\n * The block after `sbn`: `sbn + 1`, or 0 once `(sbn + 1) * K` reaches 2^32\n * and the next SS_ID wraps (C.5.2). There are `ceil(2^32 / K)` blocks per\n * wrap, the last of them short when K does not divide 2^32.\n */\nexport function kStrideNextBlock(sbn: number, k: number): number {\n assertUint32(sbn, 'sbn')\n kStrideBlockStart(sbn, k) // validates k\n return (sbn + 1) * k >= SERIAL32_SPAN ? 0 : sbn + 1\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 exactly one\n * block profile in `fec.blockProfile`. A receiver applies all of a profile's\n * rules or none of them, so the token is the one explicit per-stream\n * discriminator: it is never defaulted and never inferred from the wire.\n *\n * - `k-padded-v1` (legacy, Blockcast-private): a source symbol is the\n * protected MMTP packet zero-padded to T with no length field; every block\n * is a K-symbol RaptorQ block whose ESIs `SSB_length..K-1` are implicit\n * zero padding; `SS_ID = SBN*K + ESI`, so `SS_Start = SBN*K`; repair\n * ESI = K + RS_ID; the MoQ repair group id is the SBN.\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 */\nimport { serial32Add, serial32Distance, serial32Precedes } from './serial-number.js'\n\n/** The two block profiles a catalog `fec.blockProfile` may name. */\nexport type FecBlockProfile = 'k-padded-v1' | 'iso-ssbg1-v1'\n\n/** Every accepted `fec.blockProfile` token, legacy first. */\nexport const FEC_BLOCK_PROFILES: readonly FecBlockProfile[] = Object.freeze([\n 'k-padded-v1',\n 'iso-ssbg1-v1',\n])\n\n/** True for a known block-profile token. */\nexport function isFecBlockProfile(value: unknown): value is FecBlockProfile {\n return value === 'k-padded-v1' || value === 'iso-ssbg1-v1'\n}\n\n/**\n * Read a required `fec.blockProfile`. Throws on an absent or unknown token:\n * there is no default and nothing is inferred, because the two profiles carry\n * identical wire tuples whose repair math differs.\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(\n `${where} is required: name the FEC block profile (\"k-padded-v1\" or \"iso-ssbg1-v1\")`,\n )\n }\n throw new Error(\n `${where} must be \"k-padded-v1\" or \"iso-ssbg1-v1\" (got ${JSON.stringify(value)})`,\n )\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 * @mmt/container - MFU Fragment Reassembler\n *\n * Handles authored fragmented MFUs (Media Fragment Units) according to\n * ISO/IEC 23008-1:2023 Section 9.2.3.3. Fragmented runs are admitted in the\n * exact FI/fragment_counter countdown carried on the wire. FI=1 supplies the\n * intrinsic data-unit key. Every fragmented fragment is addressed by\n * (stream scope, MPU, packetSequenceNumber + fragmentCounter mod 2^32); a\n * continuation joins, parks under, or is stale against the one run holding\n * its address, and other runs are never consulted.\n *\n * Fragmentation Indicator (FI) values:\n * - 0: Complete MFU (single packet, no fragmentation)\n * - 1: First fragment\n * - 2: Middle fragment\n * - 3: Last fragment\n *\n * @packageDocumentation\n */\n\nimport { extractMFUPayload, isFecRepairPacket } from '@blockcast/mmt-base'\n\n/** Source transport admitted by the MMTP router. */\nexport type MmtpSourcePath = 'multicast' | 'moq'\n\n/**\n * Strict whole-frame delivery provenance, folded over EVERY contributing\n * fragment rather than the head fragment alone.\n *\n * This is deliberately NOT `source`. `source` answers a routing question \u2014\n * \"is this the reliable-MoQ copy that must not confirm multicast takeover?\" \u2014\n * and head-fragment-wins is the documented, deterministic answer to it.\n * Provenance answers an evidence question: \"did every byte of this frame\n * physically arrive over multicast?\" A frame with a multicast head and a\n * QUIC-delivered tail is a legitimate routing win for `source: 'multicast'`\n * and is emphatically NOT multicast-exclusive delivery.\n *\n * - 'multicast' \u2014 every contributing fragment was explicitly multicast.\n * The ONLY value that may be counted as physical-delivery evidence.\n * - 'mixed' \u2014 at least one contributing fragment arrived over MoQ.\n * - 'unknown' \u2014 no fragment arrived over MoQ, but at least one carried no\n * attribution at all. Absence is preserved as its own state rather than\n * defaulted, so a consumer cannot mistake \"never recorded\" for \"proven\".\n */\nexport type MmtpDeliveryProvenance = 'multicast' | 'mixed' | 'unknown'\n\n/**\n * Fold one fragment's `source` into a running provenance verdict.\n *\n * Fail-closed, order-independent and associative: 'mixed' absorbs everything,\n * a missing attribution degrades 'multicast' to 'unknown', and nothing ever\n * upgrades a verdict. Fold over an empty set is 'unknown' \u2014 no fragment ever\n * proved anything.\n */\nexport function foldDeliveryProvenance(\n verdict: MmtpDeliveryProvenance,\n source: MmtpSourcePath | undefined\n): MmtpDeliveryProvenance {\n if (verdict === 'mixed') return 'mixed'\n if (source === 'moq') return 'mixed'\n if (source === undefined) return 'unknown'\n return verdict\n}\n\n/**\n * One fragment's own provenance.\n *\n * An explicit `deliveryProvenance` wins: FEC-recovered fragments carry no\n * `source` (they were never delivered as themselves) but their block's symbol\n * provenance IS known, and the router supplies it. Falling back to `source`\n * keeps directly-delivered fragments working unchanged.\n */\nfunction fragmentProvenance(fragment: {\n source?: MmtpSourcePath\n deliveryProvenance?: MmtpDeliveryProvenance\n}): MmtpDeliveryProvenance {\n if (fragment.deliveryProvenance !== undefined) return fragment.deliveryProvenance\n if (fragment.source === 'moq') return 'mixed'\n if (fragment.source === 'multicast') return 'multicast'\n return 'unknown'\n}\n\n/** Strict provenance for a complete fragment set. */\nexport function deliveryProvenanceOf(\n fragments: readonly {\n source?: MmtpSourcePath\n deliveryProvenance?: MmtpDeliveryProvenance\n }[]\n): MmtpDeliveryProvenance {\n if (fragments.length === 0) return 'unknown'\n let verdict: MmtpDeliveryProvenance = 'multicast'\n for (const fragment of fragments) {\n const own = fragmentProvenance(fragment)\n verdict =\n verdict === 'mixed' || own === 'mixed'\n ? 'mixed'\n : verdict === 'unknown' || own === 'unknown'\n ? 'unknown'\n : 'multicast'\n }\n return verdict\n}\n\n/**\n * MFU Fragment for reassembly\n */\nexport interface MFUFragment {\n fragmentationIndicator: number\n mpuSequenceNumber: number\n fragmentCounter: number\n data: Uint8Array\n timestamp: bigint\n /** Random Access Point flag from MMTP header - indicates keyframe */\n rapFlag: boolean\n /** MFU DU priority. FFmpeg marks random-access samples with high priority. */\n priority?: number\n sampleNumber?: number\n movieFragmentSequenceNumber?: number\n sampleOffset?: number\n /** Non-timed MFU Item_ID from the 4-byte DU header. */\n itemId?: number\n /** Authored u32 MMTP packet_sequence_number, including on recovered packets. */\n packetSequenceNumber?: number\n /** True when this accepted source packet was reconstructed by FEC. */\n recovered?: boolean\n /** Transport that supplied this accepted fragment. Absent for recovered data. */\n source?: MmtpSourcePath\n /**\n * Explicit provenance for this fragment, overriding what `source` implies.\n * Set by the router for FEC-recovered fragments, which have no `source` of\n * their own but whose FEC block's symbol provenance is known.\n */\n deliveryProvenance?: MmtpDeliveryProvenance\n /** Immutable catalog identity supplied by the owning ingress subscription. */\n catalogTrackName?: string\n /** Physical MMTP stream identity when no catalog identity is available. */\n packetId?: number\n}\n\n/**\n * Reassembled MFU result\n */\nexport interface ReassembledMFU {\n mpuSequenceNumber: number\n /** MMTP packet_sequence_number of the first fragment in delivery order. */\n packetSequenceNumber?: number\n /** Every authoritative MMTP source-packet sequence that formed this MFU. */\n packetSequenceNumbers?: number[]\n /** Subset of packetSequenceNumbers reconstructed by FEC. */\n repairedPacketSequenceNumbers?: number[]\n data: Uint8Array\n timestamp: bigint\n fragmentCount: number\n /** Random Access Point flag - indicates keyframe (from first fragment) */\n rapFlag: boolean\n /** MFU DU priority from the first fragment that carried it. */\n priority?: number\n sampleNumber?: number\n movieFragmentSequenceNumber?: number\n /**\n * This DU's authored base byte offset within its sample (moqcast #37). 0\n * for a whole-sample DU; nonzero identifies one subsample DU among\n * siblings partitioning an oversized sample. Constant across the DU's own\n * fragments \u2014 feed into a sample combiner to reassemble the full sample.\n */\n sampleOffset?: number\n /**\n * Transport that supplied the accepted FI=1 head fragment (or the complete\n * FI=0 frame). This is the deterministic winner for mixed-path assembly.\n *\n * ROUTING ONLY. It describes one fragment, so it is not evidence about the\n * whole frame \u2014 read {@link ReassembledMFU.deliveryProvenance} for that.\n */\n source?: MmtpSourcePath\n /**\n * Strict provenance folded over every contributing fragment. Only\n * 'multicast' proves multicast-exclusive delivery of this frame.\n */\n deliveryProvenance: MmtpDeliveryProvenance\n /** Catalog identity from the accepted FI=1 head fragment, or FI=0 frame. */\n catalogTrackName?: string\n}\n\n/**\n * Reassembler statistics\n */\nexport interface ReassemblerStats {\n totalFragments: number\n reassembledMFUs: number\n /** Fragments rejected by strict authored DU-state validation. */\n rejectedFragments: number\n /** Incomplete MFUs discarded after their configured deadline. */\n timedOutMFUs: number\n /** Incomplete MFUs discarded to enforce the configured memory bound. */\n evictedMemoryLimit: number\n outOfOrderFragments: number\n}\n\nexport const MFU_REASSEMBLY_ERROR_CODES = [\n 'invalid-fragment-state',\n 'missing-data-unit-identity',\n 'missing-packet-sequence',\n 'conflicting-data-unit-identity',\n 'overlapping-data-unit',\n 'fragment-counter-mismatch',\n 'data-unit-identity-mismatch',\n 'offset-overflow',\n 'active-data-unit-limit',\n 'incomplete-terminal-fragment',\n 'ambiguous-continuation',\n] as const\n\nexport type MfuReassemblyErrorCode = (typeof MFU_REASSEMBLY_ERROR_CODES)[number]\n\nconst mfuReassemblyErrorCodes = new Set<string>(MFU_REASSEMBLY_ERROR_CODES)\n\nexport function isMfuReassemblyErrorCode(value: unknown): value is MfuReassemblyErrorCode {\n return typeof value === 'string' && mfuReassemblyErrorCodes.has(value)\n}\n\nexport class MfuReassemblyError extends Error {\n readonly name = 'MfuReassemblyError'\n\n constructor(\n readonly code: MfuReassemblyErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n\n/**\n * Identity-free test for a reassembly rejection.\n *\n * Consumers that inline `@blockcast/mmt-container` more than once (a component\n * bundle whose `@blockcast/*` dependencies each carry their own copy) end up\n * with several distinct `MfuReassemblyError` classes. An `instanceof` check\n * against one copy then misses rejections raised by another, and a per-fragment\n * rejection escapes as an uncaught throw that aborts the rest of the packet's\n * processing. The wire contract of a rejection is its name plus one of the\n * closed error codes, so that is what this guard checks.\n */\nexport function isMfuReassemblyError(error: unknown): error is MfuReassemblyError {\n if (error instanceof MfuReassemblyError) return true\n if (typeof error !== 'object' || error === null) return false\n return (\n Reflect.get(error, 'name') === 'MfuReassemblyError' &&\n isMfuReassemblyErrorCode(Reflect.get(error, 'code'))\n )\n}\n\nfunction assembledPacketSequences(fragments: readonly MFUFragment[]): {\n packetSequenceNumbers?: number[]\n repairedPacketSequenceNumbers?: number[]\n} {\n const packetSequenceNumbers: number[] = []\n const repairedPacketSequenceNumbers: number[] = []\n const seen = new Set<number>()\n const repaired = new Set<number>()\n for (const fragment of fragments) {\n const sequence = fragment.packetSequenceNumber\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0 || sequence > 0xffffffff) {\n return {}\n }\n if (!seen.has(sequence)) {\n seen.add(sequence)\n packetSequenceNumbers.push(sequence)\n }\n if (fragment.recovered === true && !repaired.has(sequence)) {\n repaired.add(sequence)\n repairedPacketSequenceNumbers.push(sequence)\n }\n }\n return { packetSequenceNumbers, repairedPacketSequenceNumbers }\n}\n\nexport interface PendingMfuDebug {\n key: string\n fragments: number\n fi0: number\n fi1: number\n fi2: number\n fi3: number\n firstFi: number\n lastFi: number\n firstOrder: number\n lastOrder: number\n minCounter: number\n maxCounter: number\n minOffset?: number\n maxOffset?: number\n movieFragmentSequenceNumber?: number\n sampleNumber?: number\n mpuSequenceNumber?: number\n sortedHead: Array<{\n fi: number\n counter: number\n order: number\n seq?: number\n offset?: number\n }>\n sortedTail: Array<{\n fi: number\n counter: number\n order: number\n seq?: number\n offset?: number\n }>\n}\n\nexport interface MFUReassemblerOptions {\n /** Timeout (ms) for incomplete MFUs. Derive from frame duration or FEC interleaveDepthMs.\n * Pass null for live clock-free operation; memory remains bounded by maxBuffered. */\n timeoutMs: number | null\n /** Max concurrent incomplete MFUs, including continuations awaiting FI=1. */\n maxBuffered?: number\n}\n\n/** Reassembly surface consumed by MmtpContainerParser and MmtpRouter.\n * Implemented by both the TypeScript engine and the shared\n * Rust/WASM IFC adapter. */\nexport interface MfuReassemblerBackend {\n timeoutMs: number | null\n readonly stats: ReassemblerStats\n onDeferredAssembly?: (result: ReassembledMFU) => void\n /** Returns null only for a valid incomplete DU; strict rejection throws\n * `MfuReassemblyError`. */\n addFragment(fragment: MFUFragment): ReassembledMFU | null\n flush(): void\n resetStream(catalogTrackName: string): void\n reset(): void\n readonly pendingCount: number\n getStatus(): {\n bufferedMFUs: number\n pendingFragments: number\n pendingSamples: PendingMfuDebug[]\n stats: ReassemblerStats\n }\n}\n\nfunction streamScope(fragment: MFUFragment): readonly [kind: string, identity: string | number | null] {\n if (fragment.catalogTrackName !== undefined) return ['catalog', fragment.catalogTrackName]\n if (fragment.packetId !== undefined) return ['packet', fragment.packetId]\n return ['unspecified', null]\n}\n\nfunction isU32(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 0xffffffff\n}\n\n/**\n * Wire address of one fragmented data unit: the physical stream scope, the\n * MPU, and `packetSequenceNumber + fragmentCounter` mod 2^32. Under the\n * contiguous-source producer profile every fragment of one data unit occupies\n * consecutive packet sequence numbers on its packet ID while\n * `fragmentCounter` counts the payloads that follow, so the sum is the\n * sequence number of the data unit's last fragment: equal for every fragment\n * of one data unit and distinct between data units of one MPU. Transport\n * association only; objectKey remains the intrinsic DU identity.\n */\nfunction dataUnitAddress(fragment: MFUFragment, packetSequenceNumber: number): string {\n return JSON.stringify([\n ...streamScope(fragment),\n fragment.mpuSequenceNumber,\n (packetSequenceNumber + fragment.fragmentCounter) >>> 0,\n ])\n}\n\nfunction hasAnySampleIdentityField(fragment: MFUFragment): boolean {\n return (\n fragment.movieFragmentSequenceNumber !== undefined ||\n fragment.sampleNumber !== undefined ||\n fragment.sampleOffset !== undefined\n )\n}\n\ntype IdentifiedSampleFragment = MFUFragment &\n Required<Pick<MFUFragment, 'movieFragmentSequenceNumber' | 'sampleNumber' | 'sampleOffset'>>\n\nfunction hasSampleIdentity(fragment: MFUFragment): fragment is IdentifiedSampleFragment {\n return (\n isU32(fragment.movieFragmentSequenceNumber) &&\n fragment.movieFragmentSequenceNumber > 0 &&\n isU32(fragment.sampleNumber) &&\n fragment.sampleNumber > 0 &&\n isU32(fragment.sampleOffset)\n )\n}\n\nfunction hasValidFragmentHeader(fragment: MFUFragment): boolean {\n const { fragmentationIndicator: fi, fragmentCounter: counter } = fragment\n if (!Number.isInteger(fi) || fi < 0 || fi > 3) return false\n if (!Number.isInteger(counter) || counter < 0 || counter > 0xff) return false\n return fi === 0 || fi === 3 ? counter === 0 : counter > 0\n}\n\nfunction fragmentCounterOrder(fragment: MFUFragment): number {\n return 0xff - fragment.fragmentCounter\n}\n\nfunction objectKey(fragment: MFUFragment): string {\n const scope = streamScope(fragment)\n if (fragment.itemId !== undefined) {\n return JSON.stringify([...scope, fragment.mpuSequenceNumber, 'item', fragment.itemId])\n }\n if (hasSampleIdentity(fragment)) {\n return JSON.stringify([\n ...scope,\n fragment.mpuSequenceNumber,\n 'sample',\n fragment.movieFragmentSequenceNumber,\n fragment.sampleNumber,\n // The DU's authored base offset (moqcast #37): sibling subsample DUs\n // of one sample get distinct keys instead of colliding. Only ever\n // called with the unmutated FI=1 (or FI=0) fragment, whose\n // sampleOffset is that authored base -- never the accumulating\n // per-continuation value written by #associateDataUnit.\n fragment.sampleOffset,\n ])\n }\n return JSON.stringify([...scope, fragment.mpuSequenceNumber, 'unidentified'])\n}\n\nfunction ordersByOffset(fragments: MFUFragment[]): boolean {\n return fragments.every(fragment => hasSampleIdentity(fragment))\n}\n\ntype ActiveDataUnit = {\n /** Wire address every continuation of this data unit carries. */\n address: string\n bufferKey: string\n nextFragmentCounter: number\n /** Monotonic admission ordinal of this data unit's slot. Never a clock. */\n admissionSeq: number\n catalogTrackName?: string\n} & (\n | {\n kind: 'sample'\n movieFragmentSequenceNumber: number\n sampleNumber: number\n nextOffset: number\n }\n | {\n kind: 'item'\n itemId: number\n }\n)\n\ninterface DataUnitAssociation {\n bufferKey: string\n first: boolean\n terminal: boolean\n}\n\ninterface PendingContinuationRun {\n fragments: Map<number, MFUFragment>\n startedAt: number\n /** Monotonic admission ordinal of this data unit's slot. Never a clock. */\n admissionSeq: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\ninterface BufferTimeoutState {\n startedAt: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nfunction checkedSampleEnd(offset: number, byteLength: number): number | null {\n const end = offset + byteLength\n return Number.isSafeInteger(end) && end <= 0xffffffff ? end : null\n}\n\n/**\n * MFU Reassembler with bounded reordered-fragment association\n * Based on ISO/IEC 23008-1:2023 Section 9.2.3.3\n */\n\n/**\n * Completed-address window, as a multiple of maxBuffered. A late continuation\n * is refused as stale while its data unit's address is within this window and\n * parks as a headless data unit once the address has been forgotten. The\n * value is a cross-engine invariant shared with the Rust reassembler\n * (mmt-core COMPLETED_ADDRESS_WINDOW_MULTIPLE); change both together.\n */\nexport const COMPLETED_ADDRESS_WINDOW_MULTIPLE = 2\n\n/**\n * Cross-engine anchors for the clock-free eviction guard. The bound itself is\n * `maxBuffered`, a host parameter \u2014 these fix the one scenario both regression\n * corpora drive so the Rust and TypeScript guards assert the same boundary\n * rather than each deriving its own. Shared with the Rust reassembler\n * (`EVICTION_GUARD_MAX_BUFFERED` / `EVICTION_GUARD_DATA_UNITS` in\n * `mmt-core/src/reassembler/policy/mmt.rs`); change both together.\n *\n * `EVICTION_GUARD_DATA_UNITS` headless data units admitted against a bound of\n * `EVICTION_GUARD_MAX_BUFFERED` must evict exactly the difference.\n */\nexport const EVICTION_GUARD_MAX_BUFFERED = 4\nexport const EVICTION_GUARD_DATA_UNITS = 12\n\n/**\n * Does a parked continuation queue hold a `maxBuffered` slot of its own?\n *\n * One rule, four call sites. Two read the bound: the queue that is *counted*\n * toward it (`#unopenedParkedRunCount`) is exactly the queue that is *offered*\n * to eviction (`#evictLeastRecentlyAdmitted`). Two gate admission against it:\n * `#parkContinuation` and the FI=1 arm of `#associateDataUnit` each ask whether\n * this address is already charged before moving the bound. Stating the rule once\n * is what keeps those four answers from drifting apart \u2014 a queue that charges a\n * slot no eviction can reclaim wedges the receiver, because the bound then\n * refuses every new data unit forever with `active-data-unit-limit`.\n *\n * Two exclusions, for two different reasons:\n *\n * - **An open run owns the address.** The data unit is already charged through\n * that run, so its queue costs nothing further.\n * - **The queue is empty.** It holds nothing, so it charges nothing and offers\n * nothing.\n *\n * The emptiness half is belt-and-braces, not load-bearing. Both engines discard\n * an emptied queue eagerly \u2014 `#deletePendingRun` here on every drain exit,\n * `discard_empty_parked_run` in Rust \u2014 and `#parkContinuation` always inserts\n * into a queue it just created, so an empty queue is not observable today.\n * Correctness must not depend on that invariant holding in all three places per\n * engine: routing every site that asks the question through this one predicate\n * is what keeps the engines agreeing if a future edit ever misses one of them.\n *\n * Scope: this rule decides *slot accounting* \u2014 counted, offered, admitted. A\n * queue carries two further per-slot facts, its admission ordinal and its\n * retention anchor (`startedAt` plus the timer armed from it), and both must\n * move when an empty queue is charged again. `#parkContinuation` resets them\n * explicitly; Rust gets the same contract structurally, by deriving each from\n * the queue's live entries. Same contract, two mechanisms.\n *\n * The *reap schedule* asks the same question, and every site that arms a\n * parked queue reaches one function, `#armHeadlessPendingTimeout`, which takes\n * the test through this rule: `set timeoutMs` calls it for every queue when\n * the policy changes, `#parkContinuation` calls it after a created or\n * re-anchored queue holds its first fragment, and a run closing without\n * completing calls it for the queue it leaves behind. It never arms a timer\n * for an empty queue, because a timeout reports a data unit that failed to\n * complete in time and an empty queue holds no such data unit. Charging one\n * would record an MFU that never existed. No site installs a parked-queue\n * timer of its own, so neither the slot rule nor the `startedAt` anchoring can\n * drift one site at a time.\n *\n * That is the answer Rust reaches structurally: `next_timeout_at` derives\n * candidate deadlines from the queue's live entries, so an empty queue yields\n * none and no sweep is ever scheduled on its account, and `cleanup_timeouts`\n * retains by `parked_run_holds_a_slot`, so a sweep arriving for any *other*\n * queue leaves an empty one in place rather than charging\n * `record_policy_timeout` for it. Both engines therefore agree on when the\n * reap is scheduled, and the recorded statistic is unchanged for every queue\n * that really did hold a data unit: `#onPendingTimeout` charges\n * `stats.timedOutMFUs`, the shape Rust's `record_policy_timeout` produces, and\n * takes the same slot test before charging, so the statistic cannot be\n * recorded for an empty queue whatever order the arming sites run in.\n *\n * The trade this makes, in both engines: a queue that is emptied without being\n * discarded is invisible to the reap schedule, to the slot count, and to\n * eviction, so nothing reclaims it until `reset()` clears the policy state.\n * Disposal of an emptied queue therefore rests entirely on the eager discard\n * sites (`#deletePendingRun` here, `discard_empty_parked_run` in Rust), where\n * it is housekeeping rather than an expiry; a drain exit that skips that call\n * leaks the queue for the life of the reassembler rather than charging a\n * phantom timeout for it. Converged under BLO-32420. The arming half of this\n * rule is pinned in `mfu-reassembler-eviction.test.ts`: a headless queue that\n * holds fragments is armed by `set timeoutMs` and by its run closing, and\n * disarmed by `timeoutMs = null`. The emptiness half is Rust-only, because\n * `#pendingContinuations` is unreachable from this package's tests.\n *\n * The public counters are a separate matter and *are* governed: `pendingCount`\n * \u2014 and through it `getStatus().bufferedMFUs` \u2014 delegates to\n * `#unopenedParkedRunCount`, exactly as Rust's `buffered_count` is built on\n * `unopened_parked_run_count`. Filtering either on the open run alone makes the\n * engines report different numbers for the same state out of a host-observable\n * API.\n *\n * Twin of `parked_run_holds_a_slot` in\n * `mmt-core/src/reassembler/policy/mmt.rs`; change both together.\n */\nexport function parkedRunHoldsASlot(hasOpenRun: boolean, fragmentCount: number): boolean {\n return !hasOpenRun && fragmentCount > 0\n}\n\nexport class MFUReassembler {\n // Fragment buffers and active runs use the authored MFU DU identity.\n // Continuations may wait in one counter-indexed queue per data-unit address\n // until FI=1 supplies that identity. The address is transport association\n // only; the object key stays the intrinsic DU identity.\n #buffers: Map<string, MFUFragment[]> = new Map()\n #timeouts: Map<string, BufferTimeoutState> = new Map()\n #activeDataUnits: Map<string, ActiveDataUnit> = new Map()\n #pendingContinuations: Map<string, PendingContinuationRun> = new Map()\n #emitted: Set<string> = new Set() // same sample keys, so FEC-recovered duplicate heads are dropped\n #emittedOrder: string[] = []\n // Addresses of emitted data units. A continuation addressed to one of them\n // is a late copy of a fragment the run already consumed (FEC recovery\n // supplied it first), so it is rejected as stale rather than parked as a\n // headless data unit that would hold a slot until reset. Bounded at\n // COMPLETED_ADDRESS_WINDOW_MULTIPLE x maxBuffered, the same window the Rust\n // engine keeps, so both engines forget an address after the same number of\n // completions. (#emitted is a separate, per-engine window: this engine keeps\n // maxBuffered sample keys where Rust keeps 2x; the completed set does not\n // derive from it.)\n #completed: Set<string> = new Set()\n #completedOrder: string[] = []\n #timeoutMs: number | null\n #maxBuffered: number\n /**\n * Monotonic admission ordinal. Counts slot admissions, never reads a clock,\n * so eviction order survives on hosts that run `timeoutMs: null`.\n */\n #nextAdmissionSeq = 0\n\n /** Statistics for debugging */\n readonly stats: ReassemblerStats = {\n totalFragments: 0,\n reassembledMFUs: 0,\n rejectedFragments: 0,\n timedOutMFUs: 0,\n evictedMemoryLimit: 0,\n outOfOrderFragments: 0,\n }\n\n constructor(options: MFUReassemblerOptions) {\n if (options.timeoutMs !== null && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) {\n throw new Error('[MFUReassembler] timeoutMs must be > 0 (derive from frame duration or FEC config)')\n }\n const maxBuffered = options.maxBuffered ?? 100\n if (!Number.isInteger(maxBuffered) || maxBuffered <= 0) {\n throw new Error('[MFUReassembler] maxBuffered must be a positive integer')\n }\n this.#timeoutMs = options.timeoutMs\n this.#maxBuffered = maxBuffered\n }\n\n /** Update the expiry policy for all retained and future incomplete MFUs. */\n set timeoutMs(ms: number | null) {\n if (ms !== null && (!Number.isFinite(ms) || ms <= 0)) {\n throw new Error('[MFUReassembler] timeoutMs must be > 0 (derive from frame duration or FEC config)')\n }\n this.#timeoutMs = ms\n const now = Date.now()\n for (const [bufferKey, state] of this.#timeouts) {\n if (state.timeoutId !== undefined) clearTimeout(state.timeoutId)\n delete state.timeoutId\n if (ms !== null) {\n state.timeoutId = setTimeout(() => this.#onTimeout(bufferKey), Math.max(0, state.startedAt + ms - now))\n }\n }\n // Parked queues re-arm through the one arming function, which reads the\n // new policy from `#timeoutMs` (assigned above) and keeps each queue on its\n // own `startedAt` anchor. Clearing first releases any timer armed under the\n // old policy so the helper's already-armed guard cannot skip the re-arm.\n for (const address of this.#pendingContinuations.keys()) {\n this.#clearPendingTimeout(address)\n this.#armHeadlessPendingTimeout(address)\n }\n }\n get timeoutMs(): number | null {\n return this.#timeoutMs\n }\n\n /**\n * Add a fragment and return reassembled MFU if complete\n */\n addFragment(fragment: MFUFragment): ReassembledMFU | null {\n this.stats.totalFragments++\n\n if (!hasValidFragmentHeader(fragment)) {\n this.#reject('invalid-fragment-state', 'invalid MFU fragmentation indicator or counter')\n }\n if (fragment.itemId !== undefined && hasAnySampleIdentityField(fragment)) {\n this.#reject('conflicting-data-unit-identity', 'MFU carries timed and non-timed DU identities')\n }\n\n const { mpuSequenceNumber, fragmentationIndicator } = fragment\n\n // A complete FT=2 data unit still requires its intrinsic DU identity.\n // The transport parser strips the deterministic timed/non-timed DU header\n // before calling this layer; direct callers must provide the same identity.\n // Don't check or update #emitted: in MMTP over MoQ, multiple complete MFUs\n // share the same mpuSequenceNumber (all frames in a GOP have the same mpuSeq).\n // Blocking FI=0 would prevent keyframe fragment assembly at the same mpuSeq.\n if (fragmentationIndicator === 0) {\n const sampleIdentity = hasSampleIdentity(fragment)\n const hasSampleFields = hasAnySampleIdentityField(fragment)\n const hasItemIdentity = fragment.itemId !== undefined\n if (!sampleIdentity && !hasItemIdentity) {\n this.#reject('missing-data-unit-identity', 'complete MFU has no intrinsic DU identity')\n }\n if (hasSampleFields && !sampleIdentity) {\n this.#reject('missing-data-unit-identity', 'complete MFU has an incomplete sample identity')\n }\n if (hasItemIdentity && !isU32(fragment.itemId)) {\n this.#reject('missing-data-unit-identity', 'complete MFU has an invalid Item_ID')\n }\n this.stats.reassembledMFUs++\n return {\n mpuSequenceNumber,\n packetSequenceNumber: fragment.packetSequenceNumber,\n ...assembledPacketSequences([fragment]),\n data: fragment.data,\n timestamp: fragment.timestamp,\n fragmentCount: 1,\n rapFlag: fragment.rapFlag,\n priority: fragment.priority,\n sampleNumber: fragment.sampleNumber,\n movieFragmentSequenceNumber: fragment.movieFragmentSequenceNumber,\n sampleOffset: fragment.sampleOffset,\n source: fragment.source,\n deliveryProvenance: deliveryProvenanceOf([fragment]),\n catalogTrackName: fragment.catalogTrackName,\n }\n }\n\n const sequence = fragment.packetSequenceNumber\n if (!isU32(sequence)) {\n this.#reject('missing-packet-sequence', 'fragmented MFU has no MMTP packet sequence number')\n }\n const address = dataUnitAddress(fragment, sequence)\n\n if (fragmentationIndicator !== 1) {\n // Attribution is an exact per-data-unit lookup. The continuation joins\n // the one open run holding its address when its counter is that run's\n // next. It is stale when the run has already counted past the counter,\n // or when the data unit was already emitted: the position was accepted\n // once, so no run can ever take it again. Otherwise (no open run at this\n // address, or the run has not reached the counter yet) it parks under\n // its own address. Other runs' counters are never consulted.\n const open = this.#openRunAt(address)\n if (open === undefined) {\n if (this.#completed.has(address)) {\n this.#reject('fragment-counter-mismatch', 'MFU continuation names a data unit that already completed')\n }\n this.#parkContinuation(address, fragment)\n return null\n }\n const [runKey, active] = open\n if (active.nextFragmentCounter > fragment.fragmentCounter) {\n this.#parkContinuation(address, fragment)\n return null\n }\n if (active.nextFragmentCounter < fragment.fragmentCounter) {\n this.#reject('fragment-counter-mismatch', 'MFU continuation is behind the authored fragment-counter countdown')\n }\n const result = this.#addAssociatedFragment(fragment, runKey, address)\n if (result !== null) return result\n return this.#drainPendingContinuations(address, runKey)\n }\n\n const runKey = objectKey(fragment)\n if ((hasSampleIdentity(fragment) || isU32(fragment.itemId)) && this.#emitted.has(runKey)) {\n // The identity already emitted, so this first fragment is a duplicate\n // and is dropped. Queues under other addresses belong to other data\n // units and are untouched.\n return null\n }\n if (this.#activeDataUnits.has(runKey)) {\n this.#reject('overlapping-data-unit', 'fragmented MFU overlaps an active data unit')\n }\n // Two heads with one address are one data unit delivered twice or an\n // identity clash on the wire. The established run keeps the address.\n if (this.#openRunAt(address) !== undefined) {\n this.#reject('overlapping-data-unit', 'fragmented MFU opens on an address held by an open data unit')\n }\n const pending = this.#pendingContinuations.get(address)\n // A parked continuation of this data unit cannot carry a counter at or\n // above its own head's countdown.\n if (pending !== undefined && [...pending.fragments.keys()].some(counter => counter >= fragment.fragmentCounter)) {\n this.#reject(\n 'fragment-counter-mismatch',\n 'queued continuation counter is not below the authored first-fragment counter'\n )\n }\n\n // The run's deadline starts at the earliest arrival of its own fragments.\n const result = this.#addAssociatedFragment(fragment, runKey, address, pending?.startedAt)\n this.#clearPendingTimeout(address)\n if (result !== null) return result\n return this.#drainPendingContinuations(address, runKey)\n }\n\n #addAssociatedFragment(\n fragment: MFUFragment,\n runKey: string,\n address: string,\n startedAt?: number\n ): ReassembledMFU | null {\n const association = this.#associateDataUnit(fragment, runKey, address)\n const { bufferKey, first, terminal } = association\n\n let fragments = this.#buffers.get(bufferKey)\n if (first) {\n if (fragments !== undefined) {\n this.#reject('overlapping-data-unit', 'intrinsic data-unit buffer already exists')\n }\n fragments = []\n this.#buffers.set(bufferKey, fragments)\n } else if (fragments === undefined) {\n throw new Error('[MFUReassembler] active data unit has no fragment buffer')\n }\n\n // A lossy-path deadline is measured from the first received fragment,\n // including a continuation that arrived before FI=1. Reliable paths are\n // clock-free and never install this timer.\n if (first) this.#setTimeout(bufferKey, startedAt)\n fragments.push(fragment)\n\n if (!terminal) return null\n const result = this.#tryReassemble(bufferKey)\n this.#activeDataUnits.delete(runKey)\n if (result === null) {\n this.#clearTimeout(bufferKey)\n this.#buffers.delete(bufferKey)\n this.#reject('incomplete-terminal-fragment', 'validated terminal fragment did not complete its data unit')\n }\n this.#markCompleted(address)\n return result\n }\n\n #parkContinuation(address: string, fragment: MFUFragment): void {\n let pending = this.#pendingContinuations.get(address)\n const open = this.#openRunAt(address)\n // A data unit is charged one slot: through its open run, or through its\n // queue while no run is open. Parking under an address that is already\n // charged adds nothing to the bound, so admission is judged by what this\n // fragment would add, not by the total alone. The queue half routes through\n // `parkedRunHoldsASlot` rather than restating it, so this gate cannot drift\n // from the sites that count and evict by it: an empty queue charges nothing\n // here for the same reason it is offered nothing there. Gating on\n // `pending === undefined` instead would skip the bound entirely for a queue\n // that exists but holds nothing, overshooting `maxBuffered` by one while\n // Rust evicts \u2014 the cross-engine split BLO-31813 exists to close.\n const alreadyCharged =\n open !== undefined || parkedRunHoldsASlot(open !== undefined, pending?.fragments.size ?? 0)\n if (!alreadyCharged && this.#incompleteRunCount() >= this.#maxBuffered) {\n // `open` and `pending` are captured above, and eviction can delete from\n // `#pendingContinuations` \u2014 so both are read across a mutation. Neither\n // goes stale, and the predicate is what makes that true: eviction only\n // runs when `open === undefined`, and an empty queue is not a candidate,\n // so the record the `else if` below writes to cannot be the one released\n // here. Re-read both if that rule is ever loosened.\n if (!this.#evictLeastRecentlyAdmitted()) {\n this.#reject('active-data-unit-limit', 'active MFU data-unit limit reached')\n }\n }\n // Both branches below leave the timer to `#armHeadlessPendingTimeout`,\n // called once the fragment is in, so the queue is armed only while it\n // holds a data unit and through the same slot rule as every other site.\n let armAfterInsert = false\n if (pending === undefined) {\n // A queue opened under an already-charged address inherits that slot's\n // ordinal, so a run does not renew its admission by parking a fragment.\n // The arm below is a no-op under an open run: the run's own deadline\n // covers the data unit, and `#armHeadlessPendingTimeout` tests for it.\n pending = {\n fragments: new Map(),\n startedAt: Date.now(),\n admissionSeq: open !== undefined ? open[1].admissionSeq : this.#nextAdmissionSeq++,\n }\n this.#pendingContinuations.set(address, pending)\n armAfterInsert = true\n } else if (!alreadyCharged) {\n // A queue that exists but holds nothing charged no slot, so this fragment\n // is a fresh admission \u2014 and every per-slot fact the record still carries\n // describes an occupancy that ended when its last entry left. Rust derives\n // all of them from the queue's *live* entries, so re-parking moves them\n // together; TypeScript caches them as fields written once at creation, so\n // they have to be reset together here or the queue goes transparent to the\n // bound while staying stale on its deadline:\n //\n // - Ordinal. `slot_admission_seq` mins over the entries and an empty queue\n // has none, so Rust mints a fresh one. Decides victim ordering.\n // - Retention anchor. `cleanup_timeouts` retains on `min(received_at)`,\n // which a re-parked entry moves forward. Left stale, `#onPendingTimeout`\n // can discard the queue on the emptied queue's deadline while it holds a\n // fragment that was just charged a slot \u2014 and that may have evicted\n // another data unit to get it.\n // - Armed timer. `#armHeadlessPendingTimeout` anchors on `startedAt` and\n // arms only a queue that holds a fragment, so the re-arm runs once this\n // fragment is in (below), where the creation branch arms too, rather\n // than here, where the queue is still empty and the call would arm\n // nothing. Any timer left on the record is cleared first so the queue\n // cannot keep running on the old anchor.\n //\n // `Date.now()` here is the same retention anchor the queue-creation branch\n // above already reads, not a clock in the admission order: the ordinal\n // stays a monotonic sequence, so eviction remains clock-free per PR #93.\n //\n // Unreachable while every drain exit discards an emptied queue; pinned so\n // the engines cannot pick different victims \u2014 or different expiries \u2014 if\n // one ever misses a discard site.\n pending.admissionSeq = this.#nextAdmissionSeq++\n pending.startedAt = Date.now()\n this.#clearPendingTimeout(address)\n armAfterInsert = true\n }\n // The same data unit naming the same countdown position twice: the first\n // parked copy is kept.\n if (pending.fragments.has(fragment.fragmentCounter)) {\n this.#reject('fragment-counter-mismatch', 'duplicate queued continuation counter would replace retained media')\n }\n pending.fragments.set(fragment.fragmentCounter, fragment)\n // A created or re-anchored queue holds its first fragment only now, so this\n // is the first point at which `#armHeadlessPendingTimeout` arms it. With\n // `startedAt` set one tick earlier the deadline it computes is the full\n // `timeoutMs`, the same schedule a raw timer armed at creation would have\n // kept. The duplicate check above cannot reject on this path: both branches\n // that set the flag run exactly when the queue is empty.\n if (armAfterInsert) this.#armHeadlessPendingTimeout(address)\n }\n\n #drainPendingContinuations(address: string, runKey: string): ReassembledMFU | null {\n while (true) {\n const active = this.#activeDataUnits.get(runKey)\n const pending = this.#pendingContinuations.get(address)\n if (active === undefined) {\n // The run closed. Its queue holds only this data unit's fragments;\n // drop it once empty so it is not counted as a headless data unit.\n if (pending?.fragments.size === 0) this.#deletePendingRun(address)\n return null\n }\n const fragment = pending?.fragments.get(active.nextFragmentCounter)\n if (fragment === undefined) {\n if (pending?.fragments.size === 0) this.#deletePendingRun(address)\n return null\n }\n pending!.fragments.delete(active.nextFragmentCounter)\n if (pending!.fragments.size === 0) this.#deletePendingRun(address)\n const result = this.#addAssociatedFragment(fragment, runKey, address)\n if (result !== null) {\n return result\n }\n }\n }\n\n /** Parked data units that hold a `maxBuffered` slot of their own. Membership\n * is `parkedRunHoldsASlot`, the same rule #evictLeastRecentlyAdmitted offers\n * as candidates, so nothing can be counted here that eviction cannot reclaim.\n *\n * One site, two callers \u2014 `#incompleteRunCount` and `pendingCount` \u2014 mirroring\n * Rust's `unopened_parked_run_count`, which `incomplete_run_count` and\n * `buffered_count` both delegate to. Both callers used to inline this loop\n * verbatim, so converging the *rule* moved one copy and left the other as the\n * divergence (Ally's review of #400). The rule can no longer drift now that\n * every site routes through `parkedRunHoldsASlot`; keeping the loop itself at\n * one site is what stops the scaffolding drifting the next time this question\n * grows an argument. */\n #unopenedParkedRunCount(): number {\n let count = 0\n for (const [address, pending] of this.#pendingContinuations) {\n if (parkedRunHoldsASlot(this.#openRunAt(address) !== undefined, pending.fragments.size)) {\n count++\n }\n }\n return count\n }\n\n /** Every open run plus every headless parked data unit that holds a slot,\n * one slot each. This is the quantity maxBuffered bounds. The parked term is\n * `#unopenedParkedRunCount`, whose membership is `parkedRunHoldsASlot` \u2014 the\n * same rule #evictLeastRecentlyAdmitted offers as candidates, so nothing can\n * be counted here that eviction cannot reclaim. */\n #incompleteRunCount(): number {\n return this.#activeDataUnits.size + this.#unopenedParkedRunCount()\n }\n\n /**\n * Drop the incomplete data unit admitted longest ago so a newly arriving one\n * can take its slot. Selection is by monotonic admission ordinal, never by\n * wall clock, so this is a bounded-capacity replacement policy and not a\n * timeout: it behaves identically on hosts that never drive `cleanup_timeouts`\n * (`timeoutMs: null`). Only incomplete data units are candidates \u2014 a data\n * unit that completed has already left both maps.\n *\n * Returns false only if no slot is charged, which cannot happen at the bound\n * (`maxBuffered` is a positive integer); admission then falls back to the\n * fail-closed `active-data-unit-limit` reject, which stays a stable host code.\n * That holds because the candidate set here is built from the same\n * `parkedRunHoldsASlot` rule `#incompleteRunCount` counts by, so reaching the\n * bound implies at least one candidate. Filtering one and not the other would\n * make the claim false: a queue counted but not offered charges a slot no\n * eviction can reclaim, and the receiver refuses every later data unit\n * permanently.\n */\n #evictLeastRecentlyAdmitted(): boolean {\n let victimAddress: string | undefined\n let victimSeq = Number.POSITIVE_INFINITY\n for (const [, active] of this.#activeDataUnits) {\n if (active.admissionSeq < victimSeq) {\n victimSeq = active.admissionSeq\n victimAddress = active.address\n }\n }\n for (const [address, pending] of this.#pendingContinuations) {\n // Exactly the queues #incompleteRunCount charges a slot to: a queue under\n // an open run is that run's slot, already considered above, and an empty\n // queue holds nothing to evict.\n if (!parkedRunHoldsASlot(this.#openRunAt(address) !== undefined, pending.fragments.size)) {\n continue\n }\n if (pending.admissionSeq < victimSeq) {\n victimSeq = pending.admissionSeq\n victimAddress = address\n }\n }\n if (victimAddress === undefined) return false\n this.#releaseSlot(victimAddress)\n this.stats.evictedMemoryLimit++\n return true\n }\n\n /**\n * Release every form of state one address holds: its open run, that run's\n * buffered fragments and deadline, and its continuation queue. The address is\n * deliberately not marked completed \u2014 the data unit never emitted, so a later\n * fragment of it may open a fresh slot rather than being rejected as stale.\n */\n #releaseSlot(address: string): void {\n const open = this.#openRunAt(address)\n if (open !== undefined) {\n const [runKey, active] = open\n this.#activeDataUnits.delete(runKey)\n this.#clearTimeout(active.bufferKey)\n this.#buffers.delete(active.bufferKey)\n }\n this.#deletePendingRun(address)\n }\n\n #reject(code: MfuReassemblyErrorCode, message: string): never {\n this.stats.rejectedFragments++\n throw new MfuReassemblyError(code, message)\n }\n\n #associateDataUnit(fragment: MFUFragment, runKey: string, address: string): DataUnitAssociation {\n const fi = fragment.fragmentationIndicator\n if (fi === 1) {\n // Opening a run is free when this data unit already holds a parked\n // slot: the run inherits it, so the bound does not move.\n //\n // A second head on an open address is refused upstream, so no run is open\n // here. Read that live rather than assume it, and route the answer through\n // `parkedRunHoldsASlot`, so this gate is the fourth site of one rule\n // instead of a fourth restatement of it. `parked` is non-null wherever\n // this is true, because the rule requires a non-empty queue.\n const parked = this.#pendingContinuations.get(address)\n const inheritsParkedSlot = parkedRunHoldsASlot(\n this.#openRunAt(address) !== undefined,\n parked?.fragments.size ?? 0,\n )\n\n // Resolve identity and byte extent BEFORE taking a slot. Eviction\n // replaces a healthy data unit, so it must only ever run for a fragment\n // that is going to be admitted -- a reject reached after eviction would\n // destroy valid state and break the contract these rejects exist to\n // uphold (\"without advancing or replacing valid state\"). addFragment\n // pre-validates only the FI/counter pair and the itemId/sample-field\n // conflict, so every reject below is reachable at the bound.\n const sampleIdentity = hasSampleIdentity(fragment)\n const hasSampleFields = hasAnySampleIdentityField(fragment)\n const hasItemIdentity = fragment.itemId !== undefined\n if (sampleIdentity && hasItemIdentity) {\n this.#reject('conflicting-data-unit-identity', 'fragmented MFU carries timed and non-timed DU identities')\n }\n if (!sampleIdentity && !hasItemIdentity) {\n this.#reject('missing-data-unit-identity', 'first fragment has no intrinsic DU identity')\n }\n if (hasSampleFields && !sampleIdentity) {\n this.#reject('missing-data-unit-identity', 'first fragment has an incomplete sample identity')\n }\n if (hasItemIdentity && !isU32(fragment.itemId)) {\n this.#reject('missing-data-unit-identity', 'first fragment has an invalid Item_ID')\n }\n\n const bufferKey = objectKey(fragment)\n if (this.#buffers.has(bufferKey)) {\n this.#reject('overlapping-data-unit', 'intrinsic data-unit buffer already exists')\n }\n\n let sampleEnd: number | null = null\n if (sampleIdentity) {\n sampleEnd = checkedSampleEnd(fragment.sampleOffset, fragment.data.byteLength)\n if (sampleEnd === null) this.#reject('offset-overflow', 'sample byte offset overflow')\n }\n\n // The fragment is admissible from here on, so charging it a slot cannot\n // be undone by a later reject. A second head on an open address was\n // already refused upstream, so this address holds no run and can never\n // be its own eviction victim.\n if (!inheritsParkedSlot && this.#incompleteRunCount() >= this.#maxBuffered) {\n if (!this.#evictLeastRecentlyAdmitted()) {\n this.#reject('active-data-unit-limit', 'active MFU data-unit limit reached')\n }\n }\n // An inherited slot keeps the ordinal it was admitted with: the head\n // arriving late does not make the data unit younger than one parked\n // after it.\n const admissionSeq = inheritsParkedSlot ? parked!.admissionSeq : this.#nextAdmissionSeq++\n\n let active: ActiveDataUnit\n if (sampleIdentity) {\n active = {\n address,\n kind: 'sample',\n bufferKey,\n nextFragmentCounter: fragment.fragmentCounter - 1,\n admissionSeq,\n movieFragmentSequenceNumber: fragment.movieFragmentSequenceNumber,\n sampleNumber: fragment.sampleNumber,\n nextOffset: sampleEnd!,\n ...(fragment.catalogTrackName === undefined ? {} : { catalogTrackName: fragment.catalogTrackName }),\n }\n } else {\n active = {\n address,\n kind: 'item',\n bufferKey,\n nextFragmentCounter: fragment.fragmentCounter - 1,\n admissionSeq,\n itemId: fragment.itemId!,\n ...(fragment.catalogTrackName === undefined ? {} : { catalogTrackName: fragment.catalogTrackName }),\n }\n }\n this.#activeDataUnits.set(objectKey(fragment), active)\n return { bufferKey, first: true, terminal: false }\n }\n\n const active = this.#activeDataUnits.get(runKey)\n if (active === undefined) {\n throw new Error('[MFUReassembler] continuation was not parked before association')\n }\n if (fragment.fragmentCounter !== active.nextFragmentCounter) {\n this.#reject(\n 'fragment-counter-mismatch',\n 'MFU continuation does not follow the authored fragment-counter countdown'\n )\n }\n\n if (active.kind === 'sample') {\n if (fragment.itemId !== undefined) {\n this.#reject('data-unit-identity-mismatch', 'sample continuation carries an Item_ID')\n }\n if (\n hasAnySampleIdentityField(fragment) &&\n (!hasSampleIdentity(fragment) ||\n fragment.movieFragmentSequenceNumber !== active.movieFragmentSequenceNumber ||\n fragment.sampleNumber !== active.sampleNumber ||\n fragment.sampleOffset !== active.nextOffset)\n ) {\n this.#reject('data-unit-identity-mismatch', 'sample continuation identity does not match')\n }\n const nextOffset = checkedSampleEnd(active.nextOffset, fragment.data.byteLength)\n if (nextOffset === null) this.#reject('offset-overflow', 'sample byte offset overflow')\n fragment.movieFragmentSequenceNumber = active.movieFragmentSequenceNumber\n fragment.sampleNumber = active.sampleNumber\n fragment.sampleOffset = active.nextOffset\n if (fi === 2) {\n active.nextOffset = nextOffset\n active.nextFragmentCounter = fragment.fragmentCounter - 1\n }\n } else {\n if (hasAnySampleIdentityField(fragment) || (fragment.itemId !== undefined && fragment.itemId !== active.itemId)) {\n this.#reject('data-unit-identity-mismatch', 'Item_ID continuation identity does not match')\n }\n fragment.itemId = active.itemId\n if (fi === 2) active.nextFragmentCounter = fragment.fragmentCounter - 1\n }\n\n return {\n bufferKey: active.bufferKey,\n first: false,\n terminal: fi === 3,\n }\n }\n\n #tryReassemble(bufferKey: string): ReassembledMFU | null {\n const fragments = this.#buffers.get(bufferKey)\n if (!fragments || fragments.length === 0) {\n return null\n }\n\n const sorted = [...fragments].sort((a, b) => this.#orderValue(a) - this.#orderValue(b))\n\n if (sorted[0]!.fragmentationIndicator !== 1 || sorted[sorted.length - 1]!.fragmentationIndicator !== 3) {\n return null\n }\n if (sorted.slice(1, -1).some(fragment => fragment.fragmentationIndicator !== 2)) {\n return null\n }\n\n // ISO fragment_counter is the number of succeeding payloads. After\n // normalization (`255 - counter`), a complete non-wrapping chain is strictly\n // consecutive. This also caps a data unit at 256 payloads.\n for (let i = 1; i < sorted.length; i++) {\n if (this.#orderValue(sorted[i]!) !== this.#orderValue(sorted[i - 1]!) + 1) {\n return null\n }\n }\n\n // When every fragment carries a timed-MFU byte offset, independently prove\n // byte adjacency within this data unit. Counter order remains authoritative;\n // conflicting offsets fail closed instead of changing the fragment order.\n // sorted[0]'s offset is this DU's authored base (moqcast #37: zero for a\n // whole-sample DU, nonzero for one subsample DU of a partitioned sample) --\n // never asserted against a literal zero.\n if (ordersByOffset(sorted)) {\n for (let i = 1; i < sorted.length; i++) {\n const previous = sorted[i - 1]!\n if (sorted[i]!.sampleOffset !== previous.sampleOffset! + previous.data.byteLength) {\n return null\n }\n }\n }\n\n fragments.splice(0, fragments.length, ...sorted)\n return this.#assemble(bufferKey, fragments)\n }\n\n #assemble(bufferKey: string, fragments: MFUFragment[]): ReassembledMFU {\n // Reassemble: concatenate all fragment data\n const totalSize = fragments.reduce((sum, f) => sum + f.data.length, 0)\n const data = new Uint8Array(totalSize)\n\n let offset = 0\n for (const fragment of fragments) {\n data.set(fragment.data, offset)\n offset += fragment.data.length\n }\n\n // Cleanup + mark the intrinsic identity as emitted to prevent a recovered\n // duplicate from starting another fragmented run.\n this.#clearTimeout(bufferKey)\n this.#buffers.delete(bufferKey)\n this.#markEmitted(bufferKey)\n this.stats.reassembledMFUs++\n\n return {\n mpuSequenceNumber: fragments[0]!.mpuSequenceNumber,\n packetSequenceNumber: fragments[0]!.packetSequenceNumber,\n ...assembledPacketSequences(fragments),\n data,\n timestamp: fragments[0]!.timestamp,\n fragmentCount: fragments.length,\n rapFlag: fragments[0]!.rapFlag,\n priority: fragments.find(f => f.priority !== undefined)?.priority,\n sampleNumber: fragments[0]!.sampleNumber,\n movieFragmentSequenceNumber: fragments[0]!.movieFragmentSequenceNumber,\n sampleOffset: fragments[0]!.sampleOffset,\n source: fragments[0]!.source,\n deliveryProvenance: deliveryProvenanceOf(fragments),\n catalogTrackName: fragments[0]!.catalogTrackName,\n }\n }\n\n #setTimeout(bufferKey: string, startedAt = Date.now()): void {\n const state: BufferTimeoutState = { startedAt }\n if (this.#timeoutMs !== null) {\n state.timeoutId = setTimeout(\n () => this.#onTimeout(bufferKey),\n Math.max(0, startedAt + this.#timeoutMs - Date.now())\n )\n }\n this.#timeouts.set(bufferKey, state)\n }\n\n #clearPendingTimeout(address: string): void {\n const pending = this.#pendingContinuations.get(address)\n if (pending?.timeoutId !== undefined) clearTimeout(pending.timeoutId)\n if (pending !== undefined) {\n delete pending.timeoutId\n }\n }\n\n /**\n * A queue whose run closed without completing is headless again and expires\n * from its own first arrival, exactly as it would had the head never come.\n *\n * An empty queue is not armed: it holds no data unit that could fail to\n * complete, so there is nothing for a deadline to expire. Every arming site\n * reaches this function, which takes that test through `parkedRunHoldsASlot`\n * rather than filtering on the open run alone, which is how this engine\n * reaches Rust's answer: its\n * `next_timeout_at` derives candidate deadlines from the queue's live\n * entries, so an empty queue yields none (BLO-32420).\n */\n #armHeadlessPendingTimeout(address: string): void {\n const pending = this.#pendingContinuations.get(address)\n if (pending === undefined || pending.timeoutId !== undefined || this.#timeoutMs === null) return\n if (!parkedRunHoldsASlot(this.#openRunAt(address) !== undefined, pending.fragments.size)) return\n pending.timeoutId = setTimeout(\n () => this.#onPendingTimeout(address),\n Math.max(0, pending.startedAt + this.#timeoutMs - Date.now())\n )\n }\n\n #deletePendingRun(address: string): void {\n this.#clearPendingTimeout(address)\n this.#pendingContinuations.delete(address)\n }\n\n #onPendingTimeout(address: string): void {\n const pending = this.#pendingContinuations.get(address)\n if (pending === undefined) return\n // The charging site takes the same slot rule as the arming sites, evaluated\n // live at expiry the way Rust's `cleanup_timeouts` evaluates it at sweep\n // time: a queue that holds no slot is retained rather than charged\n // `record_policy_timeout`. That makes \"an empty queue is never charged a\n // timeout\" a property of this method, not of arming order. The fired timer\n // is released so a later re-park can arm the queue again.\n if (!parkedRunHoldsASlot(this.#openRunAt(address) !== undefined, pending.fragments.size)) {\n this.#clearPendingTimeout(address)\n return\n }\n this.stats.timedOutMFUs++\n console.warn(\n `[MfuReassembler] timeout: run=${address} fragments=${pending.fragments.size} ` +\n '(continuations awaiting first fragment, discarded)'\n )\n this.#pendingContinuations.delete(address)\n }\n\n #clearTimeout(bufferKey: string): void {\n const state = this.#timeouts.get(bufferKey)\n if (state !== undefined) {\n if (state.timeoutId !== undefined) clearTimeout(state.timeoutId)\n this.#timeouts.delete(bufferKey)\n }\n }\n\n /** Callback for deferred assembly results (set by caller for async frame delivery) */\n onDeferredAssembly?: (result: ReassembledMFU) => void\n\n #markEmitted(bufferKey: string): void {\n if (this.#emitted.has(bufferKey)) return\n this.#emitted.add(bufferKey)\n this.#emittedOrder.push(bufferKey)\n while (this.#emittedOrder.length > this.#maxBuffered) {\n const oldest = this.#emittedOrder.shift()\n if (oldest !== undefined) this.#emitted.delete(oldest)\n }\n }\n\n #markCompleted(address: string): void {\n if (this.#completed.has(address)) return\n this.#completed.add(address)\n this.#completedOrder.push(address)\n const cap = this.#maxBuffered * COMPLETED_ADDRESS_WINDOW_MULTIPLE\n while (this.#completedOrder.length > cap) {\n const oldest = this.#completedOrder.shift()\n if (oldest !== undefined) this.#completed.delete(oldest)\n }\n }\n\n #orderValue(fragment: MFUFragment): number {\n return fragmentCounterOrder(fragment)\n }\n\n /** Close the run behind an expired buffer. Early arrivals parked under its\n * address stay, now headless, and expire from their own arrival. */\n #removeActiveDataUnitForBuffer(bufferKey: string): void {\n for (const [objectKey, active] of this.#activeDataUnits) {\n if (active.bufferKey === bufferKey) {\n this.#activeDataUnits.delete(objectKey)\n this.#armHeadlessPendingTimeout(active.address)\n }\n }\n }\n\n /** The one open run holding this address, with its object key. Admission\n * rejects a second head on an open address, so at most one run can match. */\n #openRunAt(address: string): readonly [string, ActiveDataUnit] | undefined {\n for (const entry of this.#activeDataUnits) {\n if (entry[1].address === address) return entry\n }\n return undefined\n }\n\n #onTimeout(bufferKey: string): void {\n const fragments = this.#buffers.get(bufferKey)\n if (!fragments || fragments.length === 0) {\n this.#buffers.delete(bufferKey)\n this.#timeouts.delete(bufferKey)\n this.#removeActiveDataUnitForBuffer(bufferKey)\n this.stats.timedOutMFUs++\n console.warn(`[MfuReassembler] timeout: key=${bufferKey} fragments=0 (no data buffered)`)\n return\n }\n\n // Discard partial MFUs \u2014 incomplete AVCC data crashes WebCodecs with\n // \"Unable to determine size of bitstream buffer\". FEC recovery handles\n // loss; partial assembly only produces garbage frames.\n this.stats.timedOutMFUs++\n console.warn(`[MfuReassembler] timeout: key=${bufferKey} fragments=${fragments.length} (partial, discarded)`)\n\n this.#buffers.delete(bufferKey)\n this.#timeouts.delete(bufferKey)\n this.#removeActiveDataUnitForBuffer(bufferKey)\n }\n\n /**\n * Flush all buffered fragments\n */\n flush(): void {\n for (const key of this.#buffers.keys()) {\n this.#clearTimeout(key)\n }\n this.#buffers.clear()\n this.#timeouts.clear()\n this.#activeDataUnits.clear()\n for (const address of this.#pendingContinuations.keys()) {\n this.#clearPendingTimeout(address)\n }\n this.#pendingContinuations.clear()\n this.#emitted.clear()\n this.#emittedOrder.length = 0\n this.#completed.clear()\n this.#completedOrder.length = 0\n }\n\n /** Drop one catalog stream's incomplete and dedup state. */\n resetStream(catalogTrackName: string): void {\n const belongsToStream = (key: string): boolean => {\n try {\n const decoded = JSON.parse(key)\n return Array.isArray(decoded) && decoded[0] === 'catalog' && decoded[1] === catalogTrackName\n } catch {\n return false\n }\n }\n const discarded = new Set<string>()\n for (const [key, fragments] of this.#buffers) {\n if (fragments.some(fragment => fragment.catalogTrackName === catalogTrackName)) {\n discarded.add(key)\n }\n }\n for (const [objectKey, active] of this.#activeDataUnits) {\n if (active.catalogTrackName === catalogTrackName) {\n discarded.add(active.bufferKey)\n this.#activeDataUnits.delete(objectKey)\n }\n }\n for (const [address, pending] of this.#pendingContinuations) {\n if (\n [...pending.fragments.values()].some(fragment => fragment.catalogTrackName === catalogTrackName) ||\n belongsToStream(address)\n )\n this.#deletePendingRun(address)\n }\n for (const key of this.#emitted) {\n if (belongsToStream(key)) discarded.add(key)\n }\n for (const key of discarded) {\n this.#clearTimeout(key)\n this.#buffers.delete(key)\n this.#emitted.delete(key)\n }\n this.#emittedOrder = this.#emittedOrder.filter(key => !discarded.has(key))\n for (const address of this.#completed) {\n if (belongsToStream(address)) this.#completed.delete(address)\n }\n this.#completedOrder = this.#completedOrder.filter(address => this.#completed.has(address))\n }\n\n /** Reset all state \u2014 flush buffers and zero stats */\n reset(): void {\n this.flush()\n this.stats.totalFragments = 0\n this.stats.reassembledMFUs = 0\n this.stats.rejectedFragments = 0\n this.stats.timedOutMFUs = 0\n this.stats.evictedMemoryLimit = 0\n this.stats.outOfOrderFragments = 0\n }\n\n /**\n * Get number of pending MFUs: engine buffers plus every headless parked data\n * unit that holds a slot.\n *\n * This is not one of the four charging sites, but it shares their second term,\n * so it takes the same rule \u2014 by delegating to `#unopenedParkedRunCount`, the\n * one site that applies it. Rust's public `buffered_count()` is\n * `inner.buffered_count() + unopened_parked_run_count()`, and that count is\n * `parked_run_holds_a_slot` \u2014 so filtering here on the open run alone would\n * report a phantom slot for an empty published queue in TypeScript and not in\n * Rust, out of a *host-observable* counter (`getStatus().bufferedMFUs`). Same\n * state, two numbers, decided by which engine the host loaded: the divergence\n * class this file exists to close, so the public counters have to agree too.\n *\n * Distinct from `#incompleteRunCount`, which sums `#activeDataUnits` rather\n * than `#buffers`. Those are different quantities by design and are not being\n * merged; only the parked term they share is required to agree, which is what\n * routing both through one method makes structural rather than conventional.\n */\n get pendingCount(): number {\n return this.#buffers.size + this.#unopenedParkedRunCount()\n }\n\n /**\n * Get current buffer status\n */\n getStatus(): {\n bufferedMFUs: number\n pendingFragments: number\n pendingSamples: PendingMfuDebug[]\n stats: ReassemblerStats\n } {\n let pendingFragments = 0\n for (const fragments of this.#buffers.values()) {\n pendingFragments += fragments.length\n }\n for (const pending of this.#pendingContinuations.values()) {\n pendingFragments += pending.fragments.size\n }\n\n return {\n bufferedMFUs: this.pendingCount,\n pendingFragments,\n pendingSamples: this.#pendingDebugSamples(),\n stats: { ...this.stats },\n }\n }\n\n #pendingDebugSamples(): PendingMfuDebug[] {\n const out: PendingMfuDebug[] = []\n for (const [key, fragments] of this.#buffers) {\n if (fragments.length === 0) continue\n const sorted = [...fragments].sort((a, b) => this.#orderValue(a) - this.#orderValue(b))\n const fiCounts = [0, 0, 0, 0]\n let minCounter = Infinity\n let maxCounter = -Infinity\n let minOffset = Infinity\n let maxOffset = -Infinity\n for (const fragment of sorted) {\n fiCounts[fragment.fragmentationIndicator] = (fiCounts[fragment.fragmentationIndicator] ?? 0) + 1\n minCounter = Math.min(minCounter, fragment.fragmentCounter)\n maxCounter = Math.max(maxCounter, fragment.fragmentCounter)\n if (typeof fragment.sampleOffset === 'number') {\n minOffset = Math.min(minOffset, fragment.sampleOffset)\n maxOffset = Math.max(maxOffset, fragment.sampleOffset)\n }\n }\n const point = (fragment: MFUFragment) => ({\n fi: fragment.fragmentationIndicator,\n counter: fragment.fragmentCounter,\n order: this.#orderValue(fragment),\n ...(typeof fragment.packetSequenceNumber === 'number' ? { seq: fragment.packetSequenceNumber } : {}),\n ...(typeof fragment.sampleOffset === 'number' ? { offset: fragment.sampleOffset } : {}),\n })\n const summary: PendingMfuDebug = {\n key,\n fragments: sorted.length,\n fi0: fiCounts[0] ?? 0,\n fi1: fiCounts[1] ?? 0,\n fi2: fiCounts[2] ?? 0,\n fi3: fiCounts[3] ?? 0,\n firstFi: sorted[0]!.fragmentationIndicator,\n lastFi: sorted[sorted.length - 1]!.fragmentationIndicator,\n firstOrder: this.#orderValue(sorted[0]!),\n lastOrder: this.#orderValue(sorted[sorted.length - 1]!),\n minCounter,\n maxCounter,\n movieFragmentSequenceNumber: sorted.find(f => f.movieFragmentSequenceNumber !== undefined)\n ?.movieFragmentSequenceNumber,\n sampleNumber: sorted.find(f => f.sampleNumber !== undefined)?.sampleNumber,\n mpuSequenceNumber: sorted[0]!.mpuSequenceNumber,\n sortedHead: sorted.slice(0, 6).map(point),\n sortedTail: sorted.slice(-6).map(point),\n }\n if (minOffset !== Infinity) summary.minOffset = minOffset\n if (maxOffset !== -Infinity) summary.maxOffset = maxOffset\n out.push(summary)\n if (out.length >= 12) break\n }\n return out\n }\n}\n\n/**\n * Create MFU fragment from MMTP packet for reassembly\n */\nexport function createFragment(mmtpPacket: Uint8Array): MFUFragment {\n const extraction = extractMFUPayload(mmtpPacket)\n if (!extraction) throw new Error('Unable to extract MFU payload from MMTP packet')\n const { header, mpu, data, mfuDuHeader, itemId } = extraction\n\n return {\n fragmentationIndicator: mpu.fragmentationIndicator,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentCounter: mpu.fragmentCounter,\n data,\n timestamp: header.timestamp,\n rapFlag: header.rapFlag,\n sampleNumber: mfuDuHeader?.sampleNumber,\n movieFragmentSequenceNumber: mfuDuHeader?.movieFragmentSequenceNumber,\n sampleOffset: mfuDuHeader?.offset,\n priority: mfuDuHeader?.priority,\n itemId: itemId ?? undefined,\n packetSequenceNumber: header.sequenceNumber,\n packetId: header.packetId,\n }\n}\n\n/**\n * Process MMTP packet with fragment reassembly\n */\nexport function processMMTPWithReassembly(mmtpPacket: Uint8Array, reassembler: MFUReassembler): ReassembledMFU | null {\n // Skip FEC repair packets\n if (isFecRepairPacket(mmtpPacket)) {\n return null\n }\n\n const fragment = createFragment(mmtpPacket)\n return reassembler.addFragment(fragment)\n}\n\n// =============================================================================\n// Inline Tests (vitest)\n// =============================================================================\n\nif (import.meta.vitest) {\n const { describe, test, expect, vi } = import.meta.vitest\n\n const expectRejection = (call: () => unknown, code: MfuReassemblyErrorCode): void => {\n let rejection: unknown\n try {\n call()\n } catch (error) {\n rejection = error\n }\n expect(rejection).toBeInstanceOf(MfuReassemblyError)\n expect((rejection as MfuReassemblyError).code).toBe(code)\n }\n\n const testPacketSequence = (mpu: number, counter: number, run = 0): number =>\n (mpu * 1000 + run - counter + 0x1_0000_0000) % 0x1_0000_0000\n\n describe('MFUReassembler', () => {\n test('should return complete MFU for FI=0', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const result = reassembler.addFragment({\n fragmentationIndicator: 0,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n itemId: 1,\n data: new Uint8Array([1, 2, 3, 4]),\n timestamp: 1000n,\n\n rapFlag: true,\n })\n expect(result).not.toBeNull()\n expect(result?.data).toEqual(new Uint8Array([1, 2, 3, 4]))\n expect(result?.fragmentCount).toBe(1)\n expect(result?.rapFlag).toBe(true)\n })\n\n test('rejects a complete MFU without a valid sample identity', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const complete = (identity: Partial<MFUFragment>): MFUFragment => ({\n fragmentationIndicator: 0,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: true,\n ...identity,\n })\n expectRejection(() => reassembler.addFragment(complete({})), 'missing-data-unit-identity')\n expectRejection(\n () =>\n reassembler.addFragment(\n complete({\n movieFragmentSequenceNumber: 2,\n sampleNumber: 1,\n })\n ),\n 'missing-data-unit-identity'\n )\n })\n\n test('accepts a complete subsample MFU with a nonzero authored offset', () => {\n // moqcast #37: a subsample DU's offset is its authored base byte\n // position within the sample -- nonzero identifies one subsample DU\n // among siblings partitioning an oversized sample.\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const result = reassembler.addFragment({\n fragmentationIndicator: 0,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n movieFragmentSequenceNumber: 2,\n sampleNumber: 1,\n sampleOffset: 4,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: true,\n })\n expect(result).not.toBeNull()\n expect(result?.sampleOffset).toBe(4)\n })\n\n test('accepts a fragmented subsample DU whose first fragment has a nonzero authored offset', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 2,\n fragmentCounter: 1,\n movieFragmentSequenceNumber: 2,\n sampleNumber: 1,\n sampleOffset: 4,\n packetSequenceNumber: testPacketSequence(2, 1),\n data: new Uint8Array([0xa1]),\n timestamp: 1000n,\n rapFlag: true,\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n expect(reassembler.getStatus().pendingFragments).toBe(1)\n\n const out = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 2,\n fragmentCounter: 0,\n data: new Uint8Array([0xa2]),\n timestamp: 1001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(2, 0),\n })\n expect(out?.data).toEqual(new Uint8Array([0xa1, 0xa2]))\n expect(out?.sampleOffset).toBe(4)\n })\n\n // Rust twin: `a_mid_data_unit_sequence_gap_strands_the_data_unit` in\n // `mmt-core/src/reassembler/policy/mmt.rs`.\n //\n // One data unit's fragments occupy sequences 100, 102, 103 with an\n // unrelated complete unit at 101 -- an interleave *inside* the fragmented\n // unit rather than after it. ISO/IEC 23008-1 permits that, so this is the\n // boundary of the contiguous-source producer profile, not a bug within it.\n //\n // This test exists because no fixture in either corpus could previously\n // express a mid-data-unit sequence gap at all: the helpers derive\n // continuation sequences arithmetically from the head, so every fixture\n // was contiguous by construction and the profile's edge was untestable\n // (BLO-33550). It pins current behaviour rather than the guarantee we\n // would prefer -- change the association path and update it deliberately.\n test('a mid-data-unit packet sequence gap strands the data unit', () => {\n const reassembler = new MFUReassembler({ timeoutMs: null, maxBuffered: 10 })\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 7,\n fragmentCounter: 2,\n movieFragmentSequenceNumber: 9,\n sampleNumber: 17,\n sampleOffset: 0,\n packetSequenceNumber: 100,\n data: new Uint8Array([0xa1]),\n timestamp: 1100n,\n rapFlag: true,\n })\n ).toBeNull()\n\n // An unrelated complete unit of the same MPU consumes sequence 101,\n // *between* the fragmented unit's head and its next fragment.\n const interleaved = reassembler.addFragment({\n fragmentationIndicator: 0,\n mpuSequenceNumber: 7,\n fragmentCounter: 0,\n movieFragmentSequenceNumber: 9,\n sampleNumber: 18,\n sampleOffset: 0,\n packetSequenceNumber: 101,\n data: new Uint8Array([0xff]),\n timestamp: 1101n,\n rapFlag: true,\n })\n expect(interleaved?.data).toEqual(new Uint8Array([0xff]))\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 7,\n fragmentCounter: 1,\n packetSequenceNumber: 102,\n data: new Uint8Array([0xa2]),\n timestamp: 1102n,\n rapFlag: false,\n })\n ).toBeNull()\n\n const output = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 7,\n fragmentCounter: 0,\n packetSequenceNumber: 103,\n data: new Uint8Array([0xa3]),\n timestamp: 1103n,\n rapFlag: false,\n })\n\n // What we would want, and do not get: `output` carrying a1 a2 a3. The\n // head addresses 100+2=102; both continuations address 102+1 = 103+0 =\n // 103, so they are two data units and neither can complete.\n expect(output).toBeNull()\n\n // Fail-closed, not corrupt: only the interleaver emitted, and no\n // fragment was donated across data units.\n expect(reassembler.stats.reassembledMFUs).toBe(1)\n expect(reassembler.stats.rejectedFragments).toBe(0)\n\n // The loss is invisible at this scale -- since BLO-31513 the bound is\n // enforced by replacement, so at `maxBuffered` this same stranding is\n // charged only to `evictedMemoryLimit` and presents as intermittent\n // missing media rather than an error.\n expect(reassembler.stats.evictedMemoryLimit).toBe(0)\n\n // Two slots for one data unit -- the open run at 102 plus the headless\n // parked queue at 103 -- so sustained profile-violating interleave\n // consumes `maxBuffered` at twice the expected rate and evicts healthy\n // data units alongside the stranded one. Matches the Rust twin's\n // `buffered_count() == 2` / `pending_fragment_count() == 3`.\n expect(reassembler.getStatus().bufferedMFUs).toBe(2)\n expect(reassembler.getStatus().pendingFragments).toBe(3)\n })\n\n test('sibling subsample DUs of one sample reassemble independently by offset', () => {\n // moqcast #37: each subsample DU of a partitioned sample runs its own\n // FI chain and gets its own buffer, keyed in part by its authored base\n // offset -- distinct from a sibling DU sharing (movie, sample).\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n expect(\n reassembler.addFragment({\n mpuSequenceNumber: 3,\n movieFragmentSequenceNumber: 5,\n sampleNumber: 9,\n fragmentationIndicator: 1,\n fragmentCounter: 1,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp: 2000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(3, 1, 0),\n })\n ).toBeNull()\n // The sibling's head sits at its own packet sequence, so its address\n // (packetSequenceNumber + fragmentCounter) differs from the first's.\n // Both stay open at once and every headerless continuation names exactly\n // one of them by that address. A second head on an already-open address\n // is refused instead ('rejects an overlapping non-timed item without\n // replacing the active run').\n expect(\n reassembler.addFragment({\n mpuSequenceNumber: 3,\n movieFragmentSequenceNumber: 5,\n sampleNumber: 9,\n fragmentationIndicator: 1,\n fragmentCounter: 2,\n sampleOffset: 3,\n data: new Uint8Array([0xb1]),\n timestamp: 2001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(3, 1, 1),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(2)\n\n const first = reassembler.addFragment({\n mpuSequenceNumber: 3,\n fragmentationIndicator: 3,\n fragmentCounter: 0,\n data: new Uint8Array([0xa2]),\n timestamp: 2000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(3, 0, 0),\n })\n expect(first?.data).toEqual(new Uint8Array([0xa1, 0xa2]))\n expect(first?.sampleOffset).toBe(0)\n\n expect(\n reassembler.addFragment({\n mpuSequenceNumber: 3,\n fragmentationIndicator: 2,\n fragmentCounter: 1,\n data: new Uint8Array([0xb2]),\n timestamp: 2001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(3, 0, 1),\n })\n ).toBeNull()\n const second = reassembler.addFragment({\n mpuSequenceNumber: 3,\n fragmentationIndicator: 3,\n fragmentCounter: 0,\n data: new Uint8Array([0xb3]),\n timestamp: 2001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(3, 0, 2),\n })\n expect(second?.data).toEqual(new Uint8Array([0xb1, 0xb2, 0xb3]))\n expect(second?.sampleOffset).toBe(3)\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('isolates colliding fragment coordinates by catalog track identity', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const fragment = (\n catalogTrackName: string,\n fragmentationIndicator: number,\n fragmentCounter: number,\n byte: number\n ): MFUFragment => ({\n itemId: 1,\n fragmentationIndicator,\n fragmentCounter,\n mpuSequenceNumber: 1,\n data: new Uint8Array([byte]),\n timestamp: 1000n,\n rapFlag: fragmentationIndicator === 1,\n catalogTrackName,\n packetSequenceNumber: testPacketSequence(1, fragmentCounter),\n })\n\n expect(reassembler.addFragment(fragment('video/720p', 1, 1, 0x71))).toBeNull()\n expect(reassembler.addFragment(fragment('video/540p', 1, 1, 0x51))).toBeNull()\n const high = reassembler.addFragment(fragment('video/720p', 3, 0, 0x72))\n const low = reassembler.addFragment(fragment('video/540p', 3, 0, 0x52))\n\n expect(high?.data).toEqual(new Uint8Array([0x71, 0x72]))\n expect(high?.catalogTrackName).toBe('video/720p')\n expect(low?.data).toEqual(new Uint8Array([0x51, 0x52]))\n expect(low?.catalogTrackName).toBe('video/540p')\n })\n\n test('rejects an overlapping non-timed item without replacing the active run', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const fragment = (\n itemId: number,\n fragmentationIndicator: number,\n fragmentCounter: number,\n byte: number\n ): MFUFragment => ({\n itemId,\n fragmentationIndicator,\n fragmentCounter,\n mpuSequenceNumber: 1,\n data: new Uint8Array([byte]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, fragmentCounter),\n })\n\n expect(reassembler.addFragment(fragment(10, 1, 1, 0x10))).toBeNull()\n expectRejection(() => reassembler.addFragment(fragment(20, 1, 1, 0x20)), 'overlapping-data-unit')\n expect(reassembler.pendingCount).toBe(1)\n expect(reassembler.addFragment(fragment(10, 3, 0, 0x11))?.data).toEqual(new Uint8Array([0x10, 0x11]))\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('associates continuations by authored state when packet timestamps change', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const fragment = (\n itemId: number | undefined,\n fragmentationIndicator: number,\n fragmentCounter: number,\n byte: number,\n timestamp: bigint\n ): MFUFragment => ({\n ...(itemId === undefined ? {} : { itemId }),\n fragmentationIndicator,\n fragmentCounter,\n mpuSequenceNumber: 1,\n data: new Uint8Array([byte]),\n timestamp,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, fragmentCounter),\n })\n\n expect(reassembler.addFragment(fragment(10, 1, 2, 0x10, 1000n))).toBeNull()\n expect(reassembler.addFragment(fragment(undefined, 2, 1, 0x11, 1001n))).toBeNull()\n const out = reassembler.addFragment(fragment(undefined, 3, 0, 0x12, 1002n))\n expect(out?.data).toEqual(new Uint8Array([0x10, 0x11, 0x12]))\n expect(out?.timestamp).toBe(1000n)\n })\n\n test('should buffer and reassemble 2 fragments', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // First fragment (FI=1)\n const result1 = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([1, 2]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n expect(result1).toBeNull()\n\n // Last fragment (FI=3)\n const result2 = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([3, 4]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n expect(result2).not.toBeNull()\n expect(result2?.data).toEqual(new Uint8Array([1, 2, 3, 4]))\n expect(result2?.fragmentCount).toBe(2)\n expect(result2?.rapFlag).toBe(true) // Should use first fragment's rapFlag\n })\n\n test('buffers a terminal continuation until its authored first fragment arrives', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // Last fragment first (FI=3)\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([3, 4]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n\n // Then first fragment (FI=1)\n const completed = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([1, 2]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n\n expect(completed?.data).toEqual(new Uint8Array([1, 2, 3, 4]))\n expect(completed?.rapFlag).toBe(true)\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('clock-free mode keeps an admitted MFU until completion', async () => {\n const reassembler = new MFUReassembler({ timeoutMs: null })\n\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([1, 2]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n\n await new Promise(resolve => setTimeout(resolve, 5))\n\n const result = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([3, 4]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n\n expect(result).not.toBeNull()\n expect(result?.data).toEqual(new Uint8Array([1, 2, 3, 4]))\n expect(reassembler.stats.timedOutMFUs).toBe(0)\n })\n\n test('should track pending count', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n expect(reassembler.pendingCount).toBe(0)\n\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n expect(reassembler.pendingCount).toBe(1)\n\n reassembler.flush()\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('should reassemble 3 fragments (FI=1, FI=2, FI=3)', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // First fragment\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 10,\n fragmentCounter: 2,\n itemId: 1,\n data: new Uint8Array([0xaa, 0xbb]),\n timestamp: 5000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(10, 2),\n })\n ).toBeNull()\n\n // Middle fragment\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 10,\n fragmentCounter: 1,\n data: new Uint8Array([0xcc, 0xdd]),\n timestamp: 5000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(10, 1),\n })\n ).toBeNull()\n\n // Last fragment \u2014 triggers reassembly\n const result = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 10,\n fragmentCounter: 0,\n data: new Uint8Array([0xee, 0xff]),\n timestamp: 5000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(10, 0),\n })\n\n expect(result).not.toBeNull()\n expect(result!.data).toEqual(new Uint8Array([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]))\n expect(result!.fragmentCount).toBe(3)\n expect(result!.rapFlag).toBe(true) // from first fragment\n expect(result!.mpuSequenceNumber).toBe(10)\n })\n\n test('should handle interleaved MPU sequences', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // MPU 1: first fragment\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0x01]),\n timestamp: 100n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n // MPU 2: complete (FI=0)\n const r2 = reassembler.addFragment({\n fragmentationIndicator: 0,\n mpuSequenceNumber: 2,\n fragmentCounter: 0,\n itemId: 2,\n data: new Uint8Array([0x02]),\n timestamp: 200n,\n rapFlag: false,\n })\n expect(r2).not.toBeNull()\n expect(r2!.mpuSequenceNumber).toBe(2)\n\n // MPU 1: last fragment\n const r1 = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([0x03]),\n timestamp: 100n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n expect(r1).not.toBeNull()\n expect(r1!.data).toEqual(new Uint8Array([0x01, 0x03]))\n })\n\n test('rejects overlapping fragmented MFUs sharing one stream and MPU', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const mpuSeq = 5\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: mpuSeq,\n fragmentCounter: 1,\n itemId: 10,\n data: new Uint8Array([0xa1]),\n timestamp: 100n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(mpuSeq, 1),\n })\n ).toBeNull()\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: mpuSeq,\n fragmentCounter: 1,\n itemId: 20,\n data: new Uint8Array([0xb1]),\n timestamp: 200n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(mpuSeq, 1),\n }),\n 'overlapping-data-unit'\n )\n expect(reassembler.pendingCount).toBe(1)\n\n const a = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: mpuSeq,\n fragmentCounter: 0,\n data: new Uint8Array([0xa2]),\n timestamp: 101n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(mpuSeq, 0),\n })\n expect(a).not.toBeNull()\n expect(a!.data).toEqual(new Uint8Array([0xa1, 0xa2]))\n expect(a!.rapFlag).toBe(true) // from A's first fragment\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: mpuSeq,\n fragmentCounter: 1,\n itemId: 20,\n data: new Uint8Array([0xb1]),\n timestamp: 200n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(mpuSeq, 1, 10),\n })\n ).toBeNull()\n const b = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: mpuSeq,\n fragmentCounter: 0,\n data: new Uint8Array([0xb2]),\n timestamp: 201n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(mpuSeq, 0, 10),\n })\n expect(b).not.toBeNull()\n expect(b!.data).toEqual(new Uint8Array([0xb1, 0xb2]))\n })\n\n test('reassembles FFmpeg timed MFU fragments by sample number and byte offset', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const common = {\n mpuSequenceNumber: 0,\n movieFragmentSequenceNumber: 9,\n sampleNumber: 17,\n }\n\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 1,\n fragmentCounter: 2,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(0, 2),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 2,\n fragmentCounter: 1,\n sampleOffset: 1,\n data: new Uint8Array([0xb2]),\n timestamp: 1001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(0, 1),\n })\n ).toBeNull()\n const out = reassembler.addFragment({\n ...common,\n fragmentationIndicator: 3,\n fragmentCounter: 0,\n sampleOffset: 2,\n data: new Uint8Array([0xc3]),\n timestamp: 1002n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(0, 0),\n })\n\n expect(out).not.toBeNull()\n expect(out!.data).toEqual(new Uint8Array([0xa1, 0xb2, 0xc3]))\n expect(out!.timestamp).toBe(1000n)\n expect(out!.sampleNumber).toBe(17)\n expect(out!.movieFragmentSequenceNumber).toBe(9)\n })\n\n test('buffers a counter gap without advancing the active data unit', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const common = {\n mpuSequenceNumber: 0,\n movieFragmentSequenceNumber: 9,\n sampleNumber: 17,\n timestamp: 1000n,\n rapFlag: true,\n }\n\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 1,\n fragmentCounter: 2,\n sampleOffset: 0,\n data: new Uint8Array([0xa1, 0xa2]),\n packetSequenceNumber: testPacketSequence(0, 2),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 3,\n fragmentCounter: 0,\n sampleOffset: 4,\n data: new Uint8Array([0xc1, 0xc2]),\n packetSequenceNumber: testPacketSequence(0, 0),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n\n const out = reassembler.addFragment({\n ...common,\n fragmentationIndicator: 2,\n fragmentCounter: 1,\n sampleOffset: 2,\n data: new Uint8Array([0xb1, 0xb2]),\n packetSequenceNumber: testPacketSequence(0, 1),\n })\n expect(out?.data).toEqual(new Uint8Array([0xa1, 0xa2, 0xb1, 0xb2, 0xc1, 0xc2]))\n })\n\n test('reassembles first-only DU-header fragments across changing packet timestamps', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 44,\n fragmentCounter: 2,\n movieFragmentSequenceNumber: 9,\n sampleNumber: 17,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp: 12345n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(44, 2),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 44,\n fragmentCounter: 1,\n data: new Uint8Array([0xb2]),\n timestamp: 12346n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(44, 1),\n })\n ).toBeNull()\n const out = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 44,\n fragmentCounter: 0,\n data: new Uint8Array([0xc3]),\n timestamp: 12347n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(44, 0),\n })\n\n expect(out).not.toBeNull()\n expect(out!.data).toEqual(new Uint8Array([0xa1, 0xb2, 0xc3]))\n expect(out!.timestamp).toBe(12345n)\n expect(out!.sampleNumber).toBe(17)\n expect(out!.movieFragmentSequenceNumber).toBe(9)\n })\n\n test('reassembles first-only DU-header fragments with an ISO countdown', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const timestamp = 12345n\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 44,\n fragmentCounter: 3,\n movieFragmentSequenceNumber: 9,\n sampleNumber: 17,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(44, 3),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 44,\n fragmentCounter: 2,\n data: new Uint8Array([0xb2]),\n timestamp,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(44, 2),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 44,\n fragmentCounter: 1,\n data: new Uint8Array([0xc3]),\n timestamp,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(44, 1),\n })\n ).toBeNull()\n const out = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 44,\n fragmentCounter: 0,\n data: new Uint8Array([0xd4]),\n timestamp,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(44, 0),\n })\n\n expect(out).not.toBeNull()\n expect(out!.data).toEqual(new Uint8Array([0xa1, 0xb2, 0xc3, 0xd4]))\n expect(out!.sampleNumber).toBe(17)\n expect(out!.movieFragmentSequenceNumber).toBe(9)\n })\n\n test('rejects fragmented MFUs without an authored DU identity', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const timestamp = 22222n\n\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 55,\n fragmentCounter: 2,\n data: new Uint8Array([0xa1]),\n timestamp,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(55, 2),\n }),\n 'missing-data-unit-identity'\n )\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('rejects fragmented MFUs without an authored packet sequence', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 55,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xa1]),\n timestamp: 22222n,\n rapFlag: true,\n }),\n 'missing-packet-sequence'\n )\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('rejects fragmented MFUs whose authored packet sequence is not u32', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n for (const packetSequenceNumber of [-1, 0x1_0000_0000, 1.5, Number.NaN]) {\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 55,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xa1]),\n timestamp: 22222n,\n rapFlag: true,\n packetSequenceNumber,\n }),\n 'missing-packet-sequence'\n )\n }\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('a packet sequence gap inside a fragmented DU splits it and never completes', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const timestamp = 66666n\n\n // The head is addressed 1000 + 3 = 1003. One unrelated same-pid packet\n // consumed psn 1001, so every later fragment is addressed 1004: a\n // second data unit on the wire, parked headless and never merged with\n // the head by scope, counter, timestamp, or arrival order.\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 80,\n fragmentCounter: 3,\n movieFragmentSequenceNumber: 241,\n sampleNumber: 1,\n sampleOffset: 0,\n packetSequenceNumber: 1000,\n data: new Uint8Array([0xa0]),\n timestamp,\n rapFlag: true,\n })\n ).toBeNull()\n for (const [counter, psn] of [\n [2, 1002],\n [1, 1003],\n ] as const) {\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 80,\n fragmentCounter: counter,\n packetSequenceNumber: psn,\n data: new Uint8Array([0xa0 + counter]),\n timestamp,\n rapFlag: false,\n })\n ).toBeNull()\n }\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 80,\n fragmentCounter: 0,\n packetSequenceNumber: 1004,\n data: new Uint8Array([0xb1]),\n timestamp,\n rapFlag: false,\n })\n ).toBeNull()\n\n // The open head plus one headless parked data unit, one slot each.\n expect(reassembler.pendingCount).toBe(2)\n expect(reassembler.getStatus().pendingFragments).toBe(4)\n expect(reassembler.stats.reassembledMFUs).toBe(0)\n expect(reassembler.stats.rejectedFragments).toBe(0)\n })\n\n test('keeps adjacent MFUs with equal countdowns in one MPU separate', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const common = { mpuSequenceNumber: 80, packetId: 7, timestamp: 66666n }\n\n // Two adjacent samples of one MPU fragmented into the same countdown are\n // both open at once. Each continuation carries its unit's terminal\n // sequence (100 + 1 and 102 + 1), so each run completes with its own\n // terminal fragment.\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 1,\n fragmentCounter: 1,\n packetSequenceNumber: 100,\n movieFragmentSequenceNumber: 241,\n sampleNumber: 1,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n rapFlag: true,\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 1,\n fragmentCounter: 1,\n packetSequenceNumber: 102,\n movieFragmentSequenceNumber: 241,\n sampleNumber: 2,\n sampleOffset: 0,\n data: new Uint8Array([0xb1]),\n rapFlag: false,\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(2)\n\n const earlier = reassembler.addFragment({\n ...common,\n fragmentationIndicator: 3,\n fragmentCounter: 0,\n packetSequenceNumber: 101,\n data: new Uint8Array([0xa2]),\n rapFlag: false,\n })\n expect(earlier?.data).toEqual(new Uint8Array([0xa1, 0xa2]))\n expect(earlier?.packetSequenceNumbers).toEqual([100, 101])\n\n const later = reassembler.addFragment({\n ...common,\n fragmentationIndicator: 3,\n fragmentCounter: 0,\n packetSequenceNumber: 103,\n data: new Uint8Array([0xb2]),\n rapFlag: false,\n })\n expect(later?.data).toEqual(new Uint8Array([0xb1, 0xb2]))\n expect(later?.packetSequenceNumbers).toEqual([102, 103])\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('wraps the fragmented run coordinate at u32 packet sequence', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 81,\n fragmentCounter: 1,\n packetSequenceNumber: 0xffffffff,\n itemId: 1,\n data: new Uint8Array([0xa1]),\n timestamp: 66666n,\n rapFlag: true,\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 81,\n fragmentCounter: 0,\n packetSequenceNumber: 0,\n data: new Uint8Array([0xa2]),\n timestamp: 66667n,\n rapFlag: false,\n })?.data\n ).toEqual(new Uint8Array([0xa1, 0xa2]))\n })\n\n test('dedupes recovered copies by ISO fragment-counter position', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const timestamp = 44444n\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 77,\n fragmentCounter: 2,\n movieFragmentSequenceNumber: 12,\n sampleNumber: 1,\n sampleOffset: 0,\n packetSequenceNumber: 2000,\n data: new Uint8Array([0xa1]),\n timestamp,\n rapFlag: true,\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 77,\n fragmentCounter: 1,\n packetSequenceNumber: 2001,\n data: new Uint8Array([0xb2]),\n timestamp,\n rapFlag: false,\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 77,\n fragmentCounter: 0,\n packetSequenceNumber: 2002,\n data: new Uint8Array([0xc3]),\n timestamp,\n rapFlag: false,\n })\n ).not.toBeNull()\n\n reassembler.flush()\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 78,\n fragmentCounter: 2,\n movieFragmentSequenceNumber: 13,\n sampleNumber: 1,\n sampleOffset: 0,\n packetSequenceNumber: 3000,\n data: new Uint8Array([0xd4]),\n timestamp,\n rapFlag: true,\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 78,\n fragmentCounter: 1,\n packetSequenceNumber: 3001,\n data: new Uint8Array([0xe5]),\n timestamp,\n rapFlag: false,\n })\n ).toBeNull()\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 78,\n fragmentCounter: 1,\n packetSequenceNumber: 3001,\n data: new Uint8Array([0xe5]),\n timestamp,\n rapFlag: false,\n }),\n 'fragment-counter-mismatch'\n )\n const out = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 78,\n fragmentCounter: 0,\n packetSequenceNumber: 3002,\n data: new Uint8Array([0xf6]),\n timestamp,\n rapFlag: false,\n })\n\n expect(out).not.toBeNull()\n expect(out!.data).toEqual(new Uint8Array([0xd4, 0xe5, 0xf6]))\n })\n\n test('reassembles middle and terminal continuations that arrive before first', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const timestamp = 54321n\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 45,\n fragmentCounter: 1,\n data: new Uint8Array([0xb2]),\n timestamp,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(45, 1),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 45,\n fragmentCounter: 0,\n data: new Uint8Array([0xc3]),\n timestamp: timestamp + 1n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(45, 0),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n const out = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 45,\n fragmentCounter: 2,\n movieFragmentSequenceNumber: 10,\n sampleNumber: 18,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(45, 2),\n })\n\n expect(out).not.toBeNull()\n expect(out!.data).toEqual(new Uint8Array([0xa1, 0xb2, 0xc3]))\n expect(out!.sampleNumber).toBe(18)\n expect(out!.movieFragmentSequenceNumber).toBe(10)\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('rejects a duplicate continuation before first without replacing retained media', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const timestamp = 54322n\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 46,\n fragmentCounter: 0,\n data: new Uint8Array([0xc3]),\n timestamp,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(46, 0),\n })\n ).toBeNull()\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 46,\n fragmentCounter: 0,\n data: new Uint8Array([0xff]),\n timestamp: timestamp + 1n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(46, 0),\n }),\n 'fragment-counter-mismatch'\n )\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 46,\n fragmentCounter: 1,\n data: new Uint8Array([0xb2]),\n timestamp: timestamp + 2n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(46, 1),\n })\n ).toBeNull()\n\n const out = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 46,\n fragmentCounter: 2,\n movieFragmentSequenceNumber: 10,\n sampleNumber: 19,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp: timestamp + 3n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(46, 2),\n })\n\n expect(out).not.toBeNull()\n expect(out!.data).toEqual(new Uint8Array([0xa1, 0xb2, 0xc3]))\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('rejects invalid ISO fragmentation-indicator and counter combinations', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const invalidHeaders = [\n { fragmentationIndicator: 0, fragmentCounter: 1 },\n { fragmentationIndicator: 3, fragmentCounter: 1 },\n { fragmentationIndicator: 1, fragmentCounter: 0 },\n { fragmentationIndicator: 2, fragmentCounter: 0 },\n { fragmentationIndicator: -1, fragmentCounter: 1 },\n { fragmentationIndicator: 4, fragmentCounter: 1 },\n { fragmentationIndicator: 1.5, fragmentCounter: 1 },\n { fragmentationIndicator: 1, fragmentCounter: -1 },\n { fragmentationIndicator: 1, fragmentCounter: 256 },\n { fragmentationIndicator: 1, fragmentCounter: 1.5 },\n { fragmentationIndicator: 1, fragmentCounter: Number.NaN },\n ]\n\n for (const header of invalidHeaders) {\n expectRejection(\n () =>\n reassembler.addFragment({\n ...header,\n mpuSequenceNumber: 48,\n data: new Uint8Array([0xa1]),\n timestamp: 54324n,\n rapFlag: false,\n }),\n 'invalid-fragment-state'\n )\n }\n\n expect(reassembler.pendingCount).toBe(0)\n expect(reassembler.stats.reassembledMFUs).toBe(0)\n })\n\n test('reassembles the maximum ISO chain of 256 payloads', () => {\n const reassembler = new MFUReassembler({ timeoutMs: null })\n const common = {\n mpuSequenceNumber: 47,\n timestamp: 54323n,\n rapFlag: false,\n }\n\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 1,\n fragmentCounter: 255,\n itemId: 1,\n data: new Uint8Array([0]),\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(47, 255),\n })\n ).toBeNull()\n for (let counter = 254; counter > 0; counter--) {\n expect(\n reassembler.addFragment({\n ...common,\n fragmentationIndicator: 2,\n fragmentCounter: counter,\n data: new Uint8Array([255 - counter]),\n packetSequenceNumber: testPacketSequence(47, counter),\n })\n ).toBeNull()\n }\n const out = reassembler.addFragment({\n ...common,\n fragmentationIndicator: 3,\n fragmentCounter: 0,\n data: new Uint8Array([255]),\n packetSequenceNumber: testPacketSequence(47, 0),\n })\n\n expect(out?.fragmentCount).toBe(256)\n expect(out?.data).toEqual(Uint8Array.from({ length: 256 }, (_, index) => index))\n })\n\n test('should not reassemble without last fragment (FI=3)', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 2,\n itemId: 1,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 2),\n })\n const result = reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n data: new Uint8Array([2]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n expect(result).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n })\n\n test('bounds continuations that arrive before their first fragments', () => {\n const reassembler = new MFUReassembler({\n timeoutMs: null,\n maxBuffered: 1,\n })\n // Data unit 1 parks headless at address 1000 and takes the only slot.\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n\n // Data unit 2 parks headless at address 2000. The bound holds by\n // replacement: data unit 1, admitted first, yields its slot.\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 2,\n fragmentCounter: 0,\n data: new Uint8Array([2]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(2, 0),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n expect(reassembler.getStatus().pendingFragments).toBe(1)\n expect(reassembler.stats.evictedMemoryLimit).toBe(1)\n\n // Data unit 2's head inherits the slot its queue already holds, so it\n // evicts nothing and completes from the parked continuation.\n const completed = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 2,\n fragmentCounter: 1,\n itemId: 2,\n data: new Uint8Array([4]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(2, 1),\n })\n expect(completed?.data).toEqual(new Uint8Array([4, 2]))\n expect(reassembler.stats.evictedMemoryLimit).toBe(1)\n expect(reassembler.pendingCount).toBe(0)\n\n // Data unit 1's continuation was released with its slot, so its head\n // opens a fresh run and waits rather than completing from evicted state.\n const result = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([3]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n expect(result).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n })\n\n test('expires a continuation that never receives its first fragment', () => {\n vi.useFakeTimers()\n try {\n const reassembler = new MFUReassembler({\n timeoutMs: 50,\n maxBuffered: 1,\n })\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n ).toBeNull()\n vi.advanceTimersByTime(50)\n expect(reassembler.pendingCount).toBe(0)\n expect(reassembler.stats.timedOutMFUs).toBe(1)\n } finally {\n vi.useRealTimers()\n }\n })\n\n test('retimes retained continuations when the timeout policy changes', () => {\n vi.useFakeTimers()\n try {\n const enabled = new MFUReassembler({ timeoutMs: null, maxBuffered: 1 })\n expect(\n enabled.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n ).toBeNull()\n enabled.timeoutMs = 10\n vi.advanceTimersByTime(10)\n expect(enabled.pendingCount).toBe(0)\n\n const disabled = new MFUReassembler({ timeoutMs: 10, maxBuffered: 1 })\n expect(\n disabled.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 2,\n fragmentCounter: 0,\n data: new Uint8Array([2]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(2, 0),\n })\n ).toBeNull()\n disabled.timeoutMs = null\n vi.advanceTimersByTime(10)\n expect(disabled.pendingCount).toBe(1)\n disabled.flush()\n } finally {\n vi.useRealTimers()\n }\n })\n\n test('bounds active data units by evicting the oldest at maxBuffered', () => {\n const reassembler = new MFUReassembler({\n timeoutMs: 1000,\n maxBuffered: 2,\n })\n\n // Two runs remain active; the third first fragment displaces the run\n // admitted longest ago instead of being refused.\n for (let i = 0; i < 2; i++) {\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: i,\n fragmentCounter: 1,\n itemId: i,\n data: new Uint8Array([i]),\n timestamp: BigInt(i * 100),\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(i, 1),\n })\n }\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 2,\n fragmentCounter: 1,\n itemId: 2,\n data: new Uint8Array([2]),\n timestamp: 200n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(2, 1),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(2)\n // Eviction is a replacement policy, not a deadline: it must not be\n // reported as a timeout, and it must be separately countable.\n expect(reassembler.stats.timedOutMFUs).toBe(0)\n expect(reassembler.stats.evictedMemoryLimit).toBe(1)\n\n // The evicted run's continuation no longer has a run to join; it parks\n // as a fresh headless data unit, which displaces the next-oldest run.\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 0,\n fragmentCounter: 0,\n data: new Uint8Array([9]),\n timestamp: 300n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(0, 0),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(2)\n expect(reassembler.stats.evictedMemoryLimit).toBe(2)\n expect(reassembler.stats.timedOutMFUs).toBe(0)\n })\n\n test('should report stats correctly', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // One complete MFU\n reassembler.addFragment({\n fragmentationIndicator: 0,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n itemId: 1,\n data: new Uint8Array([1]),\n timestamp: 1000n,\n rapFlag: false,\n })\n\n const status = reassembler.getStatus()\n expect(status.bufferedMFUs).toBe(0)\n expect(status.stats.totalFragments).toBe(1)\n expect(status.stats.reassembledMFUs).toBe(1)\n })\n\n test('rejects an overlapping first without replacing the original fragment', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xaa]),\n timestamp: 1000n,\n rapFlag: true,\n source: 'multicast',\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n // Duplicate of fragmentCounter=1\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 2,\n data: new Uint8Array([0xbb]),\n timestamp: 1000n,\n rapFlag: true,\n source: 'moq',\n packetSequenceNumber: testPacketSequence(1, 1),\n }),\n 'overlapping-data-unit'\n )\n\n const result = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([0xcc]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n expect(result).not.toBeNull()\n expect(result!.data).toEqual(new Uint8Array([0xaa, 0xcc]))\n expect(result!.fragmentCount).toBe(2)\n expect(result!.source).toBe('multicast')\n })\n })\n\n test('should retain an assembly with a gap in fragment counters', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // First fragment declares three succeeding payloads.\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 3,\n itemId: 1,\n data: new Uint8Array([0xaa]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(1, 3),\n })\n // Counter 1 arrives while counter 2 is missing.\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n data: new Uint8Array([0xcc]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n ).toBeNull()\n // Last fragment has the required zero counter.\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([0xdd]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n expect(reassembler.getStatus().pendingFragments).toBe(3)\n })\n\n test('accepts a reordered countdown and rejects a stale duplicate', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // Counters 3, 1, 0 arrive (gap at 2).\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 3,\n itemId: 1,\n data: new Uint8Array([0xaa]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(1, 3),\n })\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n data: new Uint8Array([0xcc]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 1,\n fragmentCounter: 2,\n data: new Uint8Array([0xbb]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 2),\n })\n ).toBeNull()\n expectRejection(\n () =>\n reassembler.addFragment({\n fragmentationIndicator: 2,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n data: new Uint8Array([0xcc]),\n timestamp: 1001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 1),\n }),\n 'fragment-counter-mismatch'\n )\n const result = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([0xdd]),\n timestamp: 1002n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n expect(result).not.toBeNull()\n expect(result!.data).toEqual(new Uint8Array([0xaa, 0xbb, 0xcc, 0xdd]))\n expect(result!.fragmentCount).toBe(4)\n })\n\n test('rejects an overlapping first without discarding queued continuations', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const fragment = (fragmentationIndicator: number, fragmentCounter: number, byte: number): MFUFragment => ({\n fragmentationIndicator,\n mpuSequenceNumber: 2,\n fragmentCounter,\n data: new Uint8Array([byte]),\n timestamp: 1000n,\n rapFlag: fragmentationIndicator === 1,\n packetSequenceNumber: testPacketSequence(2, fragmentCounter),\n ...(fragmentationIndicator === 1 ? { itemId: 9 } : {}),\n })\n\n expect(reassembler.addFragment(fragment(1, 3, 0xaa))).toBeNull()\n expect(reassembler.addFragment(fragment(2, 1, 0xcc))).toBeNull()\n expectRejection(() => reassembler.addFragment(fragment(1, 1, 0xee)), 'overlapping-data-unit')\n expect(reassembler.addFragment(fragment(2, 2, 0xbb))).toBeNull()\n expect(reassembler.addFragment(fragment(3, 0, 0xdd))?.data).toEqual(new Uint8Array([0xaa, 0xbb, 0xcc, 0xdd]))\n })\n\n test('rejects a duplicate emitted intrinsic identity', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 42,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xaa]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(42, 1),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 42,\n fragmentCounter: 0,\n data: new Uint8Array([0xab]),\n timestamp: 1001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(42, 0),\n })\n ).not.toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 42,\n fragmentCounter: 0,\n data: new Uint8Array([0xbc]),\n timestamp: 1002n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(42, 0, 10),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(1)\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 42,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xbb]),\n timestamp: 2000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(42, 1, 10),\n })\n ).toBeNull()\n // The queued FI=3 above is addressed to a data unit of MPU 42 whose own\n // FI=1 has not arrived. This duplicate head names that same address, but\n // its identity already emitted, so it is dropped before it can open a run\n // and touches nothing: the queue is retained and reclaimed by its own\n // arrival timeout.\n expect(reassembler.pendingCount).toBe(1)\n\n const result = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 43,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xcc]),\n timestamp: 2000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(43, 1),\n })\n expect(result).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 43,\n fragmentCounter: 0,\n data: new Uint8Array([0xdd]),\n timestamp: 2001n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(43, 0),\n })?.data\n ).toEqual(new Uint8Array([0xcc, 0xdd]))\n })\n\n test('does not create active state for an emitted identity duplicate', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 50,\n fragmentCounter: 1,\n movieFragmentSequenceNumber: 10,\n sampleNumber: 18,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(50, 1),\n })\n ).toBeNull()\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 50,\n fragmentCounter: 0,\n data: new Uint8Array([0xb2]),\n timestamp: 1000n,\n rapFlag: false,\n packetSequenceNumber: testPacketSequence(50, 0),\n })?.data\n ).toEqual(new Uint8Array([0xa1, 0xb2]))\n expect(reassembler.pendingCount).toBe(0)\n\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 50,\n fragmentCounter: 1,\n movieFragmentSequenceNumber: 10,\n sampleNumber: 18,\n sampleOffset: 0,\n data: new Uint8Array([0xa1]),\n timestamp: 2000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(50, 1, 10),\n })\n ).toBeNull()\n expect(reassembler.pendingCount).toBe(0)\n })\n\n test('flush should clear emitted set and allow re-assembly', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n\n // Use fragmented MFU (FI=1 start + FI=3 end) \u2014 only fragmented MFUs\n // go through the #emitted dedup set. FI=0 (complete) bypasses it.\n const first = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 42,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xaa]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(42, 1),\n })\n expect(first).toBeNull() // first fragment, not yet complete\n const assembled = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 42,\n fragmentCounter: 0,\n data: new Uint8Array([0xbb]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(42, 0),\n })\n expect(assembled).not.toBeNull() // complete \u2014 mpuSeq 42 now in emitted set\n\n // Rejected before flush \u2014 same mpuSeq already emitted\n expect(\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 42,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xcc]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(42, 1, 10),\n })\n ).toBeNull()\n\n // After flush, same mpuSeq should work again\n reassembler.flush()\n const r2 = reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 42,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xdd]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(42, 1),\n })\n expect(r2).toBeNull() // first fragment of new assembly\n const r3 = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 42,\n fragmentCounter: 0,\n data: new Uint8Array([0xee]),\n timestamp: 1000n,\n rapFlag: true,\n packetSequenceNumber: testPacketSequence(42, 0),\n })\n expect(r3).not.toBeNull()\n expect(r3!.data).toEqual(new Uint8Array([0xdd, 0xee]))\n })\n\n describe('createFragment', () => {\n test('should create fragment from complete timed MMTP packet', () => {\n // Build: MMTP(12) + MPU(8, T=1 FI=0 payloadLength=25) + MFU_DU(14) + data(5)\n const packet = new Uint8Array(12 + 8 + 14 + 5)\n // MMTP header: byte0 = rap=1, byte1 = MPU type\n packet[0] = 0x01 // RAP flag set\n packet[1] = 0x00 // packet_type = MPU\n // packetId = 1\n const view = new DataView(packet.buffer)\n view.setUint16(2, 1, false)\n view.setUint32(4, 42, false) // timestamp\n view.setUint32(8, 100, false) // sequence number\n\n // MPU header at offset 12\n view.setUint16(12, 25, false) // 6 remaining MPU bytes + 14 DU + 5 media\n packet[14] = 0x28 // FT=2, T=1, FI=0, A=0\n packet[15] = 0 // fragment_counter\n view.setUint32(16, 999, false) // mpuSequenceNumber\n\n // MFU DU header (14 bytes) at offset 20.\n view.setUint32(20, 7, false) // movie_fragment_sequence_number\n view.setUint32(24, 1, false) // sample_number\n // Video data at offset 34\n packet[34] = 0xde\n packet[35] = 0xad\n packet[36] = 0xbe\n packet[37] = 0xef\n packet[38] = 0x01\n\n const frag = createFragment(packet)\n expect(frag.mpuSequenceNumber).toBe(999)\n expect(frag.fragmentationIndicator).toBe(0)\n expect(frag.rapFlag).toBe(true)\n expect(frag.movieFragmentSequenceNumber).toBe(7)\n expect(frag.sampleNumber).toBe(1)\n expect(frag.sampleOffset).toBe(0)\n expect(frag.data.length).toBe(5) // 5 bytes of video data\n })\n\n test('reads Item_ID from a non-timed MFU DU header', () => {\n const packet = new Uint8Array(12 + 8 + 4 + 2)\n const view = new DataView(packet.buffer)\n view.setUint16(2, 1, false)\n view.setUint32(4, 42, false)\n view.setUint32(8, 100, false)\n view.setUint16(12, 12, false) // 6 remaining MPU bytes + 4 DU + 2 media\n packet[14] = 0x20 // FT=2, T=0, FI=0\n view.setUint32(16, 999, false)\n view.setUint32(20, 0x01020304, false)\n packet.set([0xde, 0xad], 24)\n\n const fragment = createFragment(packet)\n expect(fragment.itemId).toBe(0x01020304)\n expect(fragment.data).toEqual(new Uint8Array([0xde, 0xad]))\n })\n })\n\n describe('processMMTPWithReassembly', () => {\n test('should skip FEC repair packets', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const packet = new Uint8Array(12 + 8 + 14 + 4)\n packet[0] = 0x10 // fecType=2 (repair)\n const result = processMMTPWithReassembly(packet, reassembler)\n expect(result).toBeNull()\n })\n\n test('should return reassembled MFU for complete packet', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const packet = new Uint8Array(12 + 8 + 14 + 4)\n packet[0] = 0x01 // RAP\n packet[1] = 0x00 // MPU\n const view = new DataView(packet.buffer)\n view.setUint16(2, 1, false) // packetId\n view.setUint32(4, 100, false) // timestamp\n view.setUint32(8, 1, false) // seq\n // MPU: payloadLength=24 (6 + 14 + 4), FT=2 T=1 FI=0 A=0\n view.setUint16(12, 24, false)\n packet[14] = 0x28\n view.setUint32(16, 42, false) // mpuSeq\n view.setUint32(20, 7, false) // movie_fragment_sequence_number\n view.setUint32(24, 1, false) // sample_number\n\n packet[34] = 0x00\n packet[35] = 0x00\n packet[36] = 0x00\n packet[37] = 0x01\n\n const result = processMMTPWithReassembly(packet, reassembler)\n expect(result).not.toBeNull()\n expect(result!.mpuSequenceNumber).toBe(42)\n expect(result!.rapFlag).toBe(true)\n })\n })\n\n describe('strict delivery provenance', () => {\n test('folds to multicast only when every fragment is explicitly multicast', () => {\n expect(deliveryProvenanceOf([{ source: 'multicast' }, { source: 'multicast' }])).toBe('multicast')\n })\n\n test('a single moq fragment makes the whole frame mixed', () => {\n expect(deliveryProvenanceOf([{ source: 'multicast' }, { source: 'moq' }])).toBe('mixed')\n // ...and it does not matter where in the run it lands.\n expect(deliveryProvenanceOf([{ source: 'moq' }, { source: 'multicast' }])).toBe('mixed')\n })\n\n test('an unattributed fragment degrades multicast to unknown, never to proven', () => {\n expect(deliveryProvenanceOf([{ source: 'multicast' }, {}])).toBe('unknown')\n expect(deliveryProvenanceOf([{}])).toBe('unknown')\n })\n\n test('mixed absorbs unknown \u2014 a moq byte is worse news than a missing label', () => {\n expect(deliveryProvenanceOf([{ source: 'moq' }, {}])).toBe('mixed')\n expect(deliveryProvenanceOf([{}, { source: 'moq' }])).toBe('mixed')\n })\n\n test('an empty fragment set proves nothing', () => {\n expect(deliveryProvenanceOf([])).toBe('unknown')\n })\n\n test('the fold never upgrades a verdict', () => {\n expect(foldDeliveryProvenance('mixed', 'multicast')).toBe('mixed')\n expect(foldDeliveryProvenance('unknown', 'multicast')).toBe('unknown')\n expect(foldDeliveryProvenance('unknown', 'moq')).toBe('mixed')\n })\n\n test('a multicast head with a non-multicast tail is NOT multicast-exclusive', () => {\n // This is the leak this field exists to close. `source` legitimately\n // reports 'multicast' \u2014 head-fragment-wins is the routing contract \u2014\n // but the frame contains bytes that never crossed a multicast socket,\n // so it must never be counted as physical-delivery evidence.\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 1,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xaa]),\n timestamp: 1000n,\n rapFlag: true,\n source: 'multicast',\n packetSequenceNumber: testPacketSequence(1, 1),\n })\n const result = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 1,\n fragmentCounter: 0,\n data: new Uint8Array([0xcc]),\n timestamp: 1000n,\n rapFlag: false,\n source: 'moq',\n packetSequenceNumber: testPacketSequence(1, 0),\n })\n expect(result).not.toBeNull()\n expect(result!.fragmentCount).toBe(2)\n expect(result!.source).toBe('multicast')\n expect(result!.deliveryProvenance).toBe('mixed')\n })\n\n test('an all-multicast fragmented frame is multicast-exclusive', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n reassembler.addFragment({\n fragmentationIndicator: 1,\n mpuSequenceNumber: 2,\n fragmentCounter: 1,\n itemId: 1,\n data: new Uint8Array([0xaa]),\n timestamp: 2000n,\n rapFlag: true,\n source: 'multicast',\n packetSequenceNumber: testPacketSequence(2, 1),\n })\n const result = reassembler.addFragment({\n fragmentationIndicator: 3,\n mpuSequenceNumber: 2,\n fragmentCounter: 0,\n data: new Uint8Array([0xcc]),\n timestamp: 2000n,\n rapFlag: false,\n source: 'multicast',\n packetSequenceNumber: testPacketSequence(2, 0),\n })\n expect(result).not.toBeNull()\n expect(result!.deliveryProvenance).toBe('multicast')\n })\n\n test('an unlabelled complete frame proves nothing', () => {\n const reassembler = new MFUReassembler({ timeoutMs: 1000 })\n const result = reassembler.addFragment({\n fragmentationIndicator: 0,\n mpuSequenceNumber: 3,\n fragmentCounter: 0,\n itemId: 1,\n data: new Uint8Array([1]),\n timestamp: 3000n,\n rapFlag: true,\n })\n expect(result).not.toBeNull()\n expect(result!.deliveryProvenance).toBe('unknown')\n })\n })\n}\n", "/**\n * H.264/AVC and H.265/HEVC codec utilities for MMTP container format conversion.\n *\n * Shared between moq-lib (hang-mmt-fec) and moqtail players.\n * Handles AVCC\u2194Annex-B conversion, SPS/PPS extraction, fallback avcC generation,\n * HEVC keyframe (IRAP) detection, HEVC codec strings and hvcC records, and MMTP\n * timestamp conversion. The video codec family is always selected from the\n * catalog codec string ({@link videoSampleEntryFromCodecString}), never sniffed.\n *\n * @packageDocumentation\n */\n\n// \u2500\u2500\u2500 Public Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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/** Result of extracting a video codec configuration record from an fMP4 init segment. */\nexport interface AvcCInfo {\n codec: string\n description: Uint8Array\n}\n\n/** Result of extracting AAC AudioSpecificConfig from an fMP4 init segment. */\nexport interface AacAscInfo {\n /** Codec string like \"mp4a.40.2\" (AAC-LC). Derived from AOT in ASC[0] >> 3. */\n codec: string\n /** AudioSpecificConfig bytes \u2014 what AudioDecoder.configure({description}) needs for raw AAC. */\n description: Uint8Array\n}\n\n/** SPS and PPS NAL units extracted from an avcC record. */\nexport interface SpsPps {\n sps: Uint8Array\n pps: Uint8Array\n}\n\n/** Options for fallback avcC generation. */\nexport interface FallbackAvcCOptions {\n /** Codec string like \"avc1.640033\". Profile/constraint/level parsed from hex triplet. */\n codec?: string\n /** Coded width in pixels. Used in SPS pic_width_in_mbs. */\n width?: number\n /** Coded height in pixels. Used in SPS pic_height_in_map_units. */\n height?: number\n}\n\n// \u2500\u2500\u2500 Public Functions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 * Extract the codec configuration record (avcC/hvcC/av1C/vpcC) from\n * an fMP4 init segment (moov box).\n * MMTP FT=0 packets contain a complete fMP4: moov > trak > mdia > minf > stbl > stsd > sample entry > codec config.\n *\n * Walks every trak and returns the first supported video sample entry. This\n * handles both per-track CMSF init segments and multiplexed ftyp+moov blobs\n * where the audio trak may appear before video.\n */\nexport function extractAvcCFromInitSegment(data: Uint8Array): AvcCInfo | undefined {\n if (!hasIsoBmffMagic(data)) return undefined\n\n for (const stsd of findTrackStsdBoxes(data)) {\n const info = extractVideoConfigFromStsd(data, stsd)\n if (info) return info\n }\n\n return undefined\n}\n\nfunction extractVideoConfigFromStsd(data: Uint8Array, stsd: { o: number; sz: number }): AvcCInfo | undefined {\n let s = stsd.o + 16\n const e = stsd.o + stsd.sz\n\n // H.264: avc1 VisualSampleEntry \u2192 avcC.\n const avc1 = findBox(data, s, e, 'avc1')\n if (avc1 && avc1.sz >= 86) {\n const avcC = findBox(data, avc1.o + 86, avc1.o + avc1.sz, 'avcC')\n if (avcC && avcC.sz >= 12) {\n const d = data.subarray(avcC.o + 8, avcC.o + avcC.sz)\n const codec = `avc1.${hex2(d[1])}${hex2(d[2])}${hex2(d[3])}`\n return { codec, description: d }\n }\n }\n // HEVC: hvc1/hev1 VisualSampleEntry \u2192 hvcC. Same +86 child-box offset as\n // avc1 (identical VisualSampleEntry layout). Without this branch, HEVC\n // ftyp+moov inits yield no descriptor, so the WebCodecs path configures the\n // VideoDecoder with no `description` and the first length-prefixed hvc1\n // keyframe decode() throws DataError (\"must fill out the description field\"),\n // which the player's MoQ pump catch swallows \u2192 video track silently 0-fps\n // (BLO-8054).\n // The codec string's first element is the sample entry actually present\n // (ISO/IEC 14496-15 Annex E.3), so an hev1 entry yields \"hev1.*\".\n for (const sampleEntry of ['hvc1', 'hev1'] as const) {\n const hvc = findBox(data, s, e, sampleEntry)\n if (!hvc || hvc.sz < 86) continue\n const hvcC = findBox(data, hvc.o + 86, hvc.o + hvc.sz, 'hvcC')\n // HEVCDecoderConfigurationRecord is \u226523 bytes (+8 box header).\n if (hvcC && hvcC.sz >= 8 + 23) {\n const d = data.subarray(hvcC.o + 8, hvcC.o + hvcC.sz)\n return { codec: hevcCodecStringFromHvcC(d, sampleEntry), description: d }\n }\n }\n // AV1: av01 VisualSampleEntry -> av1C. Real FFmpeg MMTP inits can carry an\n // empty av1C box (size=8) while still providing the authoritative sample\n // entry/codec signal. Return an empty description for that shape so callers\n // can open their FT=0 gate without passing a zero-byte WebCodecs description.\n const av01 = findBox(data, s, e, 'av01')\n if (av01 && av01.sz >= 86) {\n const av1C = findBox(data, av01.o + 86, av01.o + av01.sz, 'av1C')\n if (av1C && av1C.sz >= 8) {\n const d = data.subarray(av1C.o + 8, av1C.o + av1C.sz)\n return { codec: codecStringFromAv1C(d), description: d }\n }\n }\n // VP9: vp09 VisualSampleEntry -> vpcC. Some encoders omit the VP codec record\n // payload; use the sample entry as readiness evidence and fall back to a\n // conservative vp09 codec string in that case.\n const vp09 = findBox(data, s, e, 'vp09')\n if (vp09 && vp09.sz >= 86) {\n const vpcC = findBox(data, vp09.o + 86, vp09.o + vp09.sz, 'vpcC')\n if (vpcC && vpcC.sz >= 8) {\n const d = data.subarray(vpcC.o + 8, vpcC.o + vpcC.sz)\n return { codec: codecStringFromVpcC(d), description: d }\n }\n }\n return undefined\n}\n\n/**\n * Generate a minimal avcC (AVCDecoderConfigurationRecord) from codec parameters.\n * Parses \"avc1.XXYYZZ\" \u2192 profile_idc=0xXX, constraint_flags=0xYY, level_idc=0xZZ.\n * Width/height are encoded in the SPS; if not provided, they're inferred from the\n * H.264 level's max frame size (e.g. level 4.2 \u2192 2048x1088).\n * Used when late MoQ subscribers miss the FT=0 init segment (moov/avcC).\n */\nexport function generateFallbackAvcC(options?: FallbackAvcCOptions | string): Uint8Array {\n const opts: FallbackAvcCOptions = typeof options === 'string' ? { codec: options } : (options ?? {})\n\n let profile = 0x64\n let constraint = 0x00\n let level = 0x2a\n\n if (opts.codec) {\n const match = opts.codec.match(/^avc[13]\\.([0-9a-fA-F]{6})$/)\n if (match) {\n profile = Number.parseInt(match[1].substring(0, 2), 16)\n constraint = Number.parseInt(match[1].substring(2, 4), 16)\n level = Number.parseInt(match[1].substring(4, 6), 16)\n }\n }\n\n const { width, height } = resolveResolution(opts.width, opts.height, level)\n const sps = buildMinimalSps(profile, constraint, level, width, height)\n const pps = buildMinimalPps(profile)\n\n const avcC = new Uint8Array(5 + 1 + 2 + sps.length + 1 + 2 + pps.length)\n let w = 0\n avcC[w++] = 0x01\n avcC[w++] = profile\n avcC[w++] = constraint\n avcC[w++] = level\n avcC[w++] = 0xff\n avcC[w++] = 0xe1\n avcC[w++] = (sps.length >> 8) & 0xff\n avcC[w++] = sps.length & 0xff\n avcC.set(sps, w)\n w += sps.length\n avcC[w++] = 0x01\n avcC[w++] = (pps.length >> 8) & 0xff\n avcC[w++] = pps.length & 0xff\n avcC.set(pps, w)\n return avcC\n}\n\n/**\n * Extract raw SPS and PPS NAL unit bytes from an avcC (AVCDecoderConfigurationRecord).\n * Returns the first SPS and first PPS found.\n */\nexport function extractSpsPpsFromAvcC(avcC: Uint8Array): SpsPps | undefined {\n if (avcC.length < 8) return undefined\n const numSPS = avcC[5] & 0x1f\n let offset = 6\n let sps: Uint8Array | undefined\n for (let i = 0; i < numSPS && offset + 2 <= avcC.length; i++) {\n const spsLen = (avcC[offset] << 8) | avcC[offset + 1]\n offset += 2\n if (offset + spsLen <= avcC.length) {\n if (!sps) sps = avcC.subarray(offset, offset + spsLen)\n offset += spsLen\n }\n }\n let pps: Uint8Array | undefined\n if (offset < avcC.length) {\n const numPPS = avcC[offset] & 0x1f\n offset++\n for (let i = 0; i < numPPS && offset + 2 <= avcC.length; i++) {\n const ppsLen = (avcC[offset] << 8) | avcC[offset + 1]\n offset += 2\n if (offset + ppsLen <= avcC.length) {\n if (!pps) pps = avcC.subarray(offset, offset + ppsLen)\n offset += ppsLen\n }\n }\n }\n return sps && pps ? { sps, pps } : undefined\n}\n\n/**\n * Convert AVCC (4-byte NAL length prefixed) to Annex-B (start code prefixed).\n * Prepends SPS/PPS NALs before keyframes.\n */\nexport function avccToAnnexB(avccData: Uint8Array, isKeyframe: boolean, spsPps: SpsPps): Uint8Array {\n let offset = 0\n let totalNalSize = 0\n let nalCount = 0\n while (offset + 4 <= avccData.length) {\n const nalLen =\n (avccData[offset] << 24) |\n (avccData[offset + 1] << 16) |\n (avccData[offset + 2] << 8) |\n avccData[offset + 3]\n offset += 4\n if (nalLen <= 0 || offset + nalLen > avccData.length) break\n totalNalSize += nalLen\n nalCount++\n offset += nalLen\n }\n if (nalCount === 0) return avccData\n\n let outSize = nalCount * 4 + totalNalSize\n if (isKeyframe) {\n outSize += 4 + spsPps.sps.length + 4 + spsPps.pps.length\n }\n const out = new Uint8Array(outSize)\n let w = 0\n\n if (isKeyframe) {\n out[w++] = 0; out[w++] = 0; out[w++] = 0; out[w++] = 1\n out.set(spsPps.sps, w); w += spsPps.sps.length\n out[w++] = 0; out[w++] = 0; out[w++] = 0; out[w++] = 1\n out.set(spsPps.pps, w); w += spsPps.pps.length\n }\n\n offset = 0\n while (offset + 4 <= avccData.length) {\n const nalLen =\n (avccData[offset] << 24) |\n (avccData[offset + 1] << 16) |\n (avccData[offset + 2] << 8) |\n avccData[offset + 3]\n offset += 4\n if (nalLen <= 0 || offset + nalLen > avccData.length) break\n out[w++] = 0; out[w++] = 0; out[w++] = 0; out[w++] = 1\n out.set(avccData.subarray(offset, offset + nalLen), w)\n w += nalLen\n offset += nalLen\n }\n return out\n}\n\n/**\n * Build an avcC record by parsing Annex-B data to extract SPS (NAL type 7) and PPS (NAL type 8).\n * Returns the avcC record, or null if SPS/PPS not found.\n */\nexport function extractCodecDescriptionFromAnnexB(data: Uint8Array): Uint8Array | null {\n const nalUnits: Array<{ type: number; data: Uint8Array }> = []\n let i = 0\n while (i < data.length - 4) {\n if (data[i] === 0 && data[i + 1] === 0) {\n let nalStart = 0\n if (data[i + 2] === 1) {\n nalStart = i + 3\n } else if (data[i + 2] === 0 && data[i + 3] === 1) {\n nalStart = i + 4\n }\n if (nalStart > 0 && nalStart < data.length) {\n let nalEnd = data.length\n for (let j = nalStart; j < data.length - 3; j++) {\n if (data[j] === 0 && data[j + 1] === 0 &&\n (data[j + 2] === 1 || (data[j + 2] === 0 && data[j + 3] === 1))) {\n nalEnd = j\n break\n }\n }\n const nalType = data[nalStart] & 0x1f\n nalUnits.push({ type: nalType, data: data.slice(nalStart, nalEnd) })\n i = nalEnd\n continue\n }\n }\n i++\n }\n\n const sps = nalUnits.find(n => n.type === 7)\n const pps = nalUnits.find(n => n.type === 8)\n if (!sps || !pps) return null\n\n const avcCLength = 6 + 2 + sps.data.length + 1 + 2 + pps.data.length\n const avcC = new Uint8Array(avcCLength)\n let offset = 0\n avcC[offset++] = 1\n avcC[offset++] = sps.data[1]\n avcC[offset++] = sps.data[2]\n avcC[offset++] = sps.data[3]\n avcC[offset++] = 0xff\n avcC[offset++] = 0xe1\n avcC[offset++] = (sps.data.length >> 8) & 0xff\n avcC[offset++] = sps.data.length & 0xff\n avcC.set(sps.data, offset); offset += sps.data.length\n avcC[offset++] = 1\n avcC[offset++] = (pps.data.length >> 8) & 0xff\n avcC[offset++] = pps.data.length & 0xff\n avcC.set(pps.data, offset)\n return avcC\n}\n\n/**\n * Derive codec string from avcC record (e.g. \"avc1.640033\").\n */\nexport function codecStringFromAvcC(avcC: Uint8Array): string {\n if (avcC.length < 4) return 'avc1.640033'\n return `avc1.${hex2(avcC[1])}${hex2(avcC[2])}${hex2(avcC[3])}`\n}\n\n/** VPS/SPS/PPS NAL units extracted from an HEVC keyframe (raw NAL bytes, no start code/length prefix). */\nexport interface HevcParameterSets {\n vps?: Uint8Array\n sps?: Uint8Array\n pps?: Uint8Array\n}\n\n/** True for HEVC/H.265 codec strings (hev1.* / hvc1.*). */\nexport function isHevcCodec(codec: string): boolean {\n return codec.startsWith('hev1') || codec.startsWith('hvc1')\n}\n\n/** Video sample entries this package decodes (ISO/IEC 14496-15 5.4.2, 8.4.1). */\nexport type VideoSampleEntry = 'avc1' | 'avc3' | 'hev1' | 'hvc1'\n\n/** Video codec family of a sample entry. */\nexport type VideoCodecFamily = 'avc' | 'hevc'\n\n/**\n * Select the video sample entry named by a catalog codec string's first\n * element (RFC 6381 \u00A73.3). The match is exact and case-sensitive; any other\n * string, including an empty one, throws. There is no default family and the\n * bitstream is never sniffed.\n */\nexport function videoSampleEntryFromCodecString(codec: string): VideoSampleEntry {\n const fourCc = codec.split('.')[0]\n if (fourCc === 'avc1' || fourCc === 'avc3' || fourCc === 'hev1' || fourCc === 'hvc1') return fourCc\n throw new Error(`Unsupported video codec family in codec string ${JSON.stringify(codec)}`)\n}\n\n/** Codec family of a sample entry. */\nexport function videoCodecFamily(sampleEntry: VideoSampleEntry): VideoCodecFamily {\n return sampleEntry === 'avc1' || sampleEntry === 'avc3' ? 'avc' : 'hevc'\n}\n\n/**\n * HEVC `nal_unit_type` codes (ITU-T H.265 Table 7-1). The HEVC NAL unit header\n * is two bytes (H.265 \u00A77.3.1.2): forbidden_zero_bit u(1) | nal_unit_type u(6) |\n * nuh_layer_id u(6) | nuh_temporal_id_plus1 u(3).\n */\nexport const HEVC_NAL_UNIT_TYPE = {\n TRAIL_R: 1,\n /** First IRAP type. */\n BLA_W_LP: 16,\n IDR_W_RADL: 19,\n IDR_N_LP: 20,\n CRA_NUT: 21,\n /** Last IRAP type (reserved IRAP VCL). */\n RSV_IRAP_VCL23: 23,\n /** Last VCL type; 32..=63 are non-VCL. */\n LAST_VCL: 31,\n VPS_NUT: 32,\n SPS_NUT: 33,\n PPS_NUT: 34,\n AUD_NUT: 35,\n PREFIX_SEI_NUT: 39,\n SUFFIX_SEI_NUT: 40,\n} as const\n\n/** Bytes in the HEVC NAL unit header (H.265 \u00A77.3.1.2). */\nexport const HEVC_NAL_HEADER_LENGTH = 2\n\n/**\n * Highest `bitDepth{Luma,Chroma}Minus8` an `hvcC` can carry: both are u(3)\n * (ISO/IEC 14496-15 \u00A78.3.3.1.2). H.265 allows the SPS fields up to 8.\n */\nconst HVCC_MAX_BIT_DEPTH_MINUS8 = 7\n\n/** HEVC `nal_unit_type` from the first NAL header byte: (byte >> 1) & 0x3f. */\nexport function hevcNalUnitType(nal: Uint8Array): number {\n return (nal[0]! >> 1) & 0x3f\n}\n\n/**\n * True for an IRAP picture's `nal_unit_type`: BLA_W_LP..=RSV_IRAP_VCL23\n * (16..=23, H.265 Table 7-1 / \u00A77.4.2.2), including the reserved IRAP types 22\n * and 23. An IRAP picture is the HEVC keyframe.\n */\nexport function isHevcIrapNalUnitType(nalUnitType: number): boolean {\n return nalUnitType >= HEVC_NAL_UNIT_TYPE.BLA_W_LP && nalUnitType <= HEVC_NAL_UNIT_TYPE.RSV_IRAP_VCL23\n}\n\n/** Internal alias kept for the existing helpers below. */\nfunction hevcNalType(nal: Uint8Array): number {\n return hevcNalUnitType(nal)\n}\n\n/**\n * Remove H.26x emulation-prevention bytes from a NAL unit so fixed-position\n * fields (e.g. HEVC profile_tier_level) can be read by byte offset.\n *\n * H.265 \u00A77.3.1.1 / \u00A77.4.2: every 0x03 that follows two zero bytes inside a NAL\n * unit is an emulation_prevention_three_byte and is discarded, including one\n * that ends the NAL unit (the cabac_zero_words case).\n */\nexport function removeEmulationPrevention(rbsp: Uint8Array): Uint8Array {\n const out: number[] = []\n let zeros = 0\n for (let i = 0; i < rbsp.length; i++) {\n const b = rbsp[i]!\n if (zeros >= 2 && b === 0x03) {\n zeros = 0\n continue\n }\n out.push(b)\n zeros = b === 0 ? zeros + 1 : 0\n }\n return Uint8Array.from(out)\n}\n\n/**\n * Fields of an HEVC SPS (H.265 \u00A77.3.2.2.1) needed for the codec string and the\n * hvcC record. `profileCompatibilityFlags` holds the 32 flags in bitstream\n * order (flag 0 is the most significant bit); `constraintIndicatorFlags` holds\n * the 48 bits from general_progressive_source_flag onward.\n */\nexport interface HevcSpsInfo {\n profileSpace: number\n tierFlag: boolean\n profileIdc: number\n profileCompatibilityFlags: number\n constraintIndicatorFlags: Uint8Array\n levelIdc: number\n maxSubLayersMinus1: number\n temporalIdNestingFlag: boolean\n seqParameterSetId: number\n chromaFormatIdc: number\n picWidthInLumaSamples: number\n picHeightInLumaSamples: number\n bitDepthLumaMinus8: number\n bitDepthChromaMinus8: number\n}\n\n/** MSB-first RBSP bit reader (H.265 \u00A77.2 read_bits, \u00A79.2 ue(v)). */\nclass RbspReader {\n #bit = 0\n constructor(private readonly data: Uint8Array) {}\n\n bits(count: number): number {\n if (this.#bit + count > this.data.length * 8) throw new Error('HEVC SPS: RBSP truncated')\n let value = 0\n for (let i = 0; i < count; i++, this.#bit++) {\n value = value * 2 + ((this.data[this.#bit >> 3]! >> (7 - (this.#bit & 7))) & 1)\n }\n return value\n }\n\n skip(count: number): void {\n if (this.#bit + count > this.data.length * 8) throw new Error('HEVC SPS: RBSP truncated')\n this.#bit += count\n }\n\n ue(): number {\n let leadingZeros = 0\n while (this.bits(1) === 0) {\n if (++leadingZeros > 31) throw new Error('HEVC SPS: ue(v) exceeds 32 bits')\n }\n return leadingZeros === 0 ? 0 : 2 ** leadingZeros - 1 + this.bits(leadingZeros)\n }\n}\n\n/**\n * Parse the leading fields of an HEVC SPS NAL unit (2-byte header included, no\n * start code). Emulation prevention is removed first. Throws on a non-SPS or\n * non-base-layer NAL unit, truncation, or a value outside its H.265 \u00A77.4.3.2.1\n * range: a malformed SPS must not yield a guessed record.\n */\nexport function parseHevcSps(sps: Uint8Array): HevcSpsInfo {\n if (sps.length < HEVC_NAL_HEADER_LENGTH || (sps[0]! & 0x80) !== 0 || (sps[1]! & 0x07) === 0) {\n throw new Error('HEVC SPS: invalid NAL unit header')\n }\n if (hevcNalUnitType(sps) !== HEVC_NAL_UNIT_TYPE.SPS_NUT) throw new Error('HEVC SPS: NAL unit is not an SPS')\n if (((sps[0]! & 0x01) << 5 | sps[1]! >> 3) !== 0) {\n throw new Error('HEVC SPS: not in the base layer (nuh_layer_id != 0)')\n }\n const r = new RbspReader(removeEmulationPrevention(sps).subarray(HEVC_NAL_HEADER_LENGTH))\n r.bits(4) // sps_video_parameter_set_id\n const maxSubLayersMinus1 = r.bits(3)\n if (maxSubLayersMinus1 > 6) throw new Error('HEVC SPS: sps_max_sub_layers_minus1 is greater than 6')\n const temporalIdNestingFlag = r.bits(1) === 1\n // profile_tier_level(1, sps_max_sub_layers_minus1), H.265 \u00A77.3.3.\n const profileSpace = r.bits(2)\n const tierFlag = r.bits(1) === 1\n const profileIdc = r.bits(5)\n const profileCompatibilityFlags = r.bits(32) >>> 0\n const constraintIndicatorFlags = new Uint8Array(6)\n for (let i = 0; i < 6; i++) constraintIndicatorFlags[i] = r.bits(8)\n const levelIdc = r.bits(8)\n const subLayerProfilePresent: boolean[] = []\n const subLayerLevelPresent: boolean[] = []\n for (let i = 0; i < maxSubLayersMinus1; i++) {\n subLayerProfilePresent.push(r.bits(1) === 1)\n subLayerLevelPresent.push(r.bits(1) === 1)\n }\n if (maxSubLayersMinus1 > 0) {\n for (let i = maxSubLayersMinus1; i < 8; i++) r.skip(2) // reserved_zero_2bits\n }\n for (let i = 0; i < maxSubLayersMinus1; i++) {\n if (subLayerProfilePresent[i]) r.skip(88) // sub-layer profile fields\n if (subLayerLevelPresent[i]) r.skip(8) // sub_layer_level_idc\n }\n const seqParameterSetId = r.ue()\n if (seqParameterSetId > 15) throw new Error('HEVC SPS: sps_seq_parameter_set_id is greater than 15')\n const chromaFormatIdc = r.ue()\n if (chromaFormatIdc > 3) throw new Error('HEVC SPS: chroma_format_idc is greater than 3')\n if (chromaFormatIdc === 3) r.skip(1) // separate_colour_plane_flag\n const picWidthInLumaSamples = r.ue()\n const picHeightInLumaSamples = r.ue()\n if (picWidthInLumaSamples === 0 || picHeightInLumaSamples === 0) {\n throw new Error('HEVC SPS: picture dimension is zero')\n }\n if (r.bits(1) === 1) for (let i = 0; i < 4; i++) r.ue() // conformance window offsets\n const bitDepthLumaMinus8 = r.ue()\n const bitDepthChromaMinus8 = r.ue()\n if (bitDepthLumaMinus8 > 8 || bitDepthChromaMinus8 > 8) throw new Error('HEVC SPS: bit depth is greater than 16')\n return {\n profileSpace,\n tierFlag,\n profileIdc,\n profileCompatibilityFlags,\n constraintIndicatorFlags,\n levelIdc,\n maxSubLayersMinus1,\n temporalIdNestingFlag,\n seqParameterSetId,\n chromaFormatIdc,\n picWidthInLumaSamples,\n picHeightInLumaSamples,\n bitDepthLumaMinus8,\n bitDepthChromaMinus8,\n }\n}\n\n/**\n * RFC 6381 codec string of an HEVC stream from its SPS, per ISO/IEC 14496-15\n * Annex E.3 (e.g. \"hev1.1.6.L93.B0\"); the first element is `sampleEntry`.\n */\nexport function hevcCodecStringFromSps(sps: Uint8Array, sampleEntry: 'hev1' | 'hvc1'): string {\n const info = parseHevcSps(sps)\n return formatHevcCodecString(\n sampleEntry,\n info.profileSpace,\n info.tierFlag,\n info.profileIdc,\n info.profileCompatibilityFlags,\n info.constraintIndicatorFlags,\n info.levelIdc,\n )\n}\n\n/**\n * ISO/IEC 14496-15 Annex E.3 codec string: sample entry; profile space\n * (none/A/B/C) + decimal profile_idc; the 32 compatibility flags in reverse bit\n * order as hex without leading zeros; L/H tier + decimal level_idc; each\n * constraint byte as hex, trailing zero bytes omitted. Hex digits are upper\n * case, as in the Annex E.3 examples.\n */\nfunction formatHevcCodecString(\n sampleEntry: 'hev1' | 'hvc1',\n profileSpace: number,\n tierFlag: boolean,\n profileIdc: number,\n profileCompatibilityFlags: number,\n constraintIndicatorFlags: Uint8Array,\n levelIdc: number,\n): string {\n let reversed = 0\n let v = profileCompatibilityFlags >>> 0\n for (let i = 0; i < 32; i++) {\n reversed = ((reversed << 1) | (v & 1)) >>> 0\n v >>>= 1\n }\n let lastNonZero = -1\n for (let i = 0; i < constraintIndicatorFlags.length; i++) if (constraintIndicatorFlags[i] !== 0) lastNonZero = i\n const space = profileSpace === 0 ? '' : String.fromCharCode(64 + profileSpace) // 1\u2192'A', 2\u2192'B', 3\u2192'C'\n let codec = `${sampleEntry}.${space}${profileIdc}.${reversed.toString(16).toUpperCase()}.${tierFlag ? 'H' : 'L'}${levelIdc}`\n for (let i = 0; i <= lastNonZero; i++) codec += `.${constraintIndicatorFlags[i]!.toString(16).toUpperCase()}`\n return codec\n}\n\n/**\n * The NAL units of an HEVC sample, split by its framing: a complete 4-byte\n * length-prefixed sample is read as such, otherwise Annex B. Null when the\n * sample is neither \u2014 there is no third framing to read it as.\n */\nfunction splitHevcSample(data: Uint8Array): { nals: Uint8Array[]; lengthPrefixed: boolean } | null {\n if (isCompleteAvccSample(data)) return { nals: splitAvccNalUnits(data), lengthPrefixed: true }\n if (isAnnexB(data)) return { nals: splitAnnexBNalUnits(data), lengthPrefixed: false }\n return null\n}\n\n/** IRAP classification of split NAL units; undefined when none has a header. */\nfunction hevcNalUnitsContainIrap(nals: Uint8Array[]): boolean | undefined {\n let sawNal = false\n for (const nal of nals) {\n if (nal.length < HEVC_NAL_HEADER_LENGTH) continue\n sawNal = true\n if (isHevcIrapNalUnitType(hevcNalUnitType(nal))) return true\n }\n return sawNal ? false : undefined\n}\n\n/**\n * Classify an HEVC access unit as a keyframe (contains an IRAP slice,\n * {@link isHevcIrapNalUnitType}). Complete 4-byte length-prefixed samples are\n * read as such; otherwise Annex B. Returns undefined when no NAL unit is found\n * \u2014 an unreadable sample, which is not the same as a delta frame.\n */\nexport function classifyHevcKeyframe(data: Uint8Array): boolean | undefined {\n const split = splitHevcSample(data)\n return split === null ? undefined : hevcNalUnitsContainIrap(split.nals)\n}\n\n/**\n * True when an HEVC access unit contains an IRAP slice. Collapses \"unreadable\"\n * into false; a caller that must tell the two apart (anything about to write\n * the sample into an mdat) uses {@link prepareHevcCmafSample} instead.\n */\nexport function detectHevcKeyframe(data: Uint8Array): boolean {\n return classifyHevcKeyframe(data) === true\n}\n\n/** An HEVC sample ready for an fMP4 mdat whose hvcC has lengthSizeMinusOne = 3. */\nexport interface HevcCmafSample {\n /** The access unit contains an IRAP slice ({@link isHevcIrapNalUnitType}). */\n keyframe: boolean\n /** 4-byte length-prefixed NAL units (the input itself when already so). */\n data: Uint8Array\n}\n\n/**\n * Classify and normalize an HEVC sample for an fMP4 mdat from one split of its\n * NAL units. Returns null \u2014 the sample must not be written \u2014 when its framing\n * is neither a complete 4-byte length-prefixed sample nor Annex B, when it\n * holds no NAL unit, or when nothing is left after `hvc1` drops the parameter\n * sets: bytes the hvcC's lengthSizeMinusOne = 3 does not describe would be\n * misparsed by the decoder, and an unreadable sample is not a delta frame.\n * Normalization as in {@link normalizeHevcSampleToLengthPrefixed}.\n */\nexport function prepareHevcCmafSample(data: Uint8Array, sampleEntry: 'hev1' | 'hvc1'): HevcCmafSample | null {\n const split = splitHevcSample(data)\n if (split === null) return null\n const keyframe = hevcNalUnitsContainIrap(split.nals)\n if (keyframe === undefined) return null\n const normalized = hevcNalUnitsToLengthPrefixed(data, split.nals, split.lengthPrefixed, sampleEntry)\n return normalized === null ? null : { keyframe, data: normalized }\n}\n\n/**\n * Normalize an HEVC sample to 4-byte length-prefixed NAL units for an fMP4\n * mdat whose hvcC declares lengthSizeMinusOne = 3. Complete length-prefixed\n * samples pass through; Annex B is converted. For `hvc1` the VPS/SPS/PPS are\n * dropped (ISO/IEC 14496-15 8.4.1.1: they live only in the hvcC); for `hev1`\n * they are kept in-band. Throws when the sample cannot be read\n * ({@link prepareHevcCmafSample} returns null) rather than pass it through.\n */\nexport function normalizeHevcSampleToLengthPrefixed(data: Uint8Array, sampleEntry: 'hev1' | 'hvc1'): Uint8Array {\n const prepared = prepareHevcCmafSample(data, sampleEntry)\n if (prepared === null) {\n throw new Error('HEVC sample is neither 4-byte length-prefixed nor Annex B, or holds no NAL unit to write')\n }\n return prepared.data\n}\n\nfunction hevcNalUnitsToLengthPrefixed(\n data: Uint8Array,\n nals: Uint8Array[],\n lengthPrefixed: boolean,\n sampleEntry: 'hev1' | 'hvc1',\n): Uint8Array | null {\n const kept = sampleEntry === 'hvc1'\n ? nals.filter((nal) => {\n const t = hevcNalUnitType(nal)\n return t !== HEVC_NAL_UNIT_TYPE.VPS_NUT && t !== HEVC_NAL_UNIT_TYPE.SPS_NUT && t !== HEVC_NAL_UNIT_TYPE.PPS_NUT\n })\n : nals\n if (kept.length === 0) return null\n if (lengthPrefixed && kept.length === nals.length) return data\n const out = new Uint8Array(kept.reduce((sum, nal) => sum + 4 + nal.length, 0))\n let w = 0\n for (const nal of kept) {\n w = writeNalLength(out, w, nal.length)\n out.set(nal, w)\n w += nal.length\n }\n return out\n}\n\n/**\n * Split an AVCC/hvcC bitstream (length-prefixed NAL units) into raw NAL byte slices.\n * `lengthSize` is the NAL length prefix width (4 for FFmpeg LOC / fMP4 sample data).\n */\nexport function splitAvccNalUnits(data: Uint8Array, lengthSize = 4): Uint8Array[] {\n const nals: Uint8Array[] = []\n let i = 0\n while (i + lengthSize <= data.length) {\n let len = 0\n for (let k = 0; k < lengthSize; k++) len = (len << 8) | data[i + k]\n i += lengthSize\n if (len <= 0 || i + len > data.length) break\n nals.push(data.subarray(i, i + len))\n i += len\n }\n return nals\n}\n\n/**\n * True when `data` is exactly one or more length-prefixed NAL units.\n *\n * This is intentionally stricter than \"starts with a plausible length\": a\n * H.264 AVCC access unit may begin with bytes `00 00 00 01` when the first\n * NAL is a one-byte AUD. That byte pattern is also an Annex-B start code, so\n * callers must prove the whole buffer is complete AVCC before falling back to\n * Annex-B detection/conversion.\n */\nexport function isCompleteAvccSample(data: Uint8Array, lengthSize = 4): boolean {\n let i = 0\n let count = 0\n while (i + lengthSize <= data.length) {\n let len = 0\n for (let k = 0; k < lengthSize; k++) len = (len << 8) | data[i + k]\n i += lengthSize\n if (len <= 0 || i + len > data.length) return false\n i += len\n count++\n }\n return count > 0 && i === data.length\n}\n\nexport type H264SampleFormat = 'avcc' | 'annexb' | 'raw-nal' | 'unknown'\nexport type H264NalUnitFormat = H264SampleFormat | 'partial-avcc'\n\nexport interface H264AvccSample {\n data: Uint8Array\n format: H264SampleFormat\n}\n\nexport interface H264NalUnitSample {\n nals: Uint8Array[]\n format: H264NalUnitFormat\n}\n\n/**\n * Normalize a H.264 access unit/sample to length-prefixed AVCC for fMP4 mdat\n * payloads. Already-AVCC samples are returned as-is. Annex-B and single raw\n * NAL samples are converted one-way to AVCC at the MSE/fMP4 boundary.\n */\nexport function normalizeH264SampleToAvcc(data: Uint8Array): H264AvccSample {\n if (isCompleteAvccSample(data)) return { data, format: 'avcc' }\n if (isAnnexB(data)) return { data: annexBToAvcc(data), format: 'annexb' }\n if (isLikelyRawH264NalUnit(data)) return { data: rawH264NalToAvcc(data), format: 'raw-nal' }\n return { data, format: 'unknown' }\n}\n\n/**\n * Split a H.264 access unit/sample into NAL units without changing its framing.\n * Use this for routing, keyframe gates, and diagnostics. Conversion to AVCC is\n * reserved for `normalizeH264SampleToAvcc` at the fMP4/MSE boundary.\n */\nexport function splitH264SampleNalUnits(\n data: Uint8Array,\n options: H264KeyframeDetectionOptions = {},\n): H264NalUnitSample {\n if (isCompleteAvccSample(data)) return { nals: splitAvccNalUnits(data), format: 'avcc' }\n if (isAnnexB(data)) return { nals: splitAnnexBNalUnits(data), format: 'annexb' }\n if (options.allowPartialAvcc === true) {\n const partial = splitPartialAvccNalUnits(data)\n if (partial.length > 0) return { nals: partial, format: 'partial-avcc' }\n }\n if (isLikelyRawH264NalUnit(data)) return { nals: [data], format: 'raw-nal' }\n const nals = splitAvccNalUnits(data)\n return { nals, format: nals.length > 0 ? 'avcc' : 'unknown' }\n}\n\n/**\n * Extract HEVC VPS (type 32) / SPS (33) / PPS (34) NAL units from a keyframe access\n * unit. Accepts either Annex-B (start-code delimited) or AVCC/hvcC (length-prefixed)\n * framing \u2014 FFmpeg LOC delivers the latter.\n */\nexport function extractHevcParameterSets(keyframe: Uint8Array): HevcParameterSets {\n const nals = isAnnexB(keyframe) ? splitAnnexBNalUnits(keyframe) : splitAvccNalUnits(keyframe)\n const out: HevcParameterSets = {}\n for (const nal of nals) {\n if (nal.length === 0) continue\n const t = hevcNalType(nal)\n if (t === 32 && !out.vps) out.vps = nal\n else if (t === 33 && !out.sps) out.sps = nal\n else if (t === 34 && !out.pps) out.pps = nal\n }\n return out\n}\n\n/**\n * Build an hvcC (HEVCDecoderConfigurationRecord, ISO/IEC 14496-15 \u00A78.3.3.1) from\n * VPS/SPS/PPS NAL units. Suitable as the `description` for a WebCodecs HEVC\n * VideoDecoderConfig and as the fMP4 `hvcC` box payload.\n *\n * Field sources (\u00A78.3.3.1.2): general profile/tier/level, chromaFormat,\n * bitDepth{Luma,Chroma}Minus8, numTemporalLayers (= sps_max_sub_layers_minus1\n * + 1) and temporalIdNested come from the parsed SPS. min_spatial_segmentation\n * _idc = 0, parallelismType = 0, avgFrameRate = 0 and constantFrameRate = 0\n * are the record's \"no restriction / unknown / unspecified\" encodings (the VUI\n * and PPS fields that could tighten them are not parsed). lengthSizeMinusOne =\n * 3 (4-byte NAL lengths). array_completeness = 0: the record is derived from\n * in-band parameter sets, which is the `hev1` arrangement (\u00A78.4.1.1).\n *\n * Returns null when the SPS or PPS is absent; throws when the SPS is malformed\n * or its bit depth (16) is not representable in the record.\n *\n * WebCodecs REQUIRES a description for length-prefixed HEVC \u2014 unlike H.264, Chrome will\n * not self-configure HEVC from the bitstream (BLO-7764).\n */\nexport function generateHvcCFromParameterSets(sets: HevcParameterSets): Uint8Array | null {\n const { vps, sps, pps } = sets\n if (!sps || !pps) return null\n const info = parseHevcSps(sps)\n // bitDepth{Luma,Chroma}Minus8 are u(3) in the record (\u00A78.3.3.1.2), so 0..7.\n // H.265 also allows 8 (16-bit), which `0xf8 | 8` would write as 0 \u2014 a\n // record declaring 8-bit \u2014 so a 16-bit SPS is refused, not mis-described.\n if (info.bitDepthLumaMinus8 > HVCC_MAX_BIT_DEPTH_MINUS8 || info.bitDepthChromaMinus8 > HVCC_MAX_BIT_DEPTH_MINUS8) {\n throw new Error('HEVC SPS: bit depth of 16 is not representable in an hvcC record')\n }\n const arrays = [\n { type: 32, nal: vps },\n { type: 33, nal: sps },\n { type: 34, nal: pps },\n ].filter((a): a is { type: number; nal: Uint8Array } => a.nal !== undefined)\n\n let size = 23\n for (const a of arrays) size += 5 + a.nal.length\n const h = new Uint8Array(size)\n let o = 0\n h[o++] = 1 // configurationVersion\n h[o++] = (info.profileSpace << 6) | ((info.tierFlag ? 1 : 0) << 5) | info.profileIdc\n h[o++] = (info.profileCompatibilityFlags >>> 24) & 0xff\n h[o++] = (info.profileCompatibilityFlags >>> 16) & 0xff\n h[o++] = (info.profileCompatibilityFlags >>> 8) & 0xff\n h[o++] = info.profileCompatibilityFlags & 0xff\n h.set(info.constraintIndicatorFlags, o); o += 6 // general_constraint_indicator_flags\n h[o++] = info.levelIdc // general_level_idc\n h[o++] = 0xf0; h[o++] = 0x00 // reserved(1111) + min_spatial_segmentation_idc(0)\n h[o++] = 0xfc // reserved(111111) + parallelismType(0)\n h[o++] = 0xfc | info.chromaFormatIdc // reserved(111111) + chromaFormat\n h[o++] = 0xf8 | info.bitDepthLumaMinus8 // reserved(11111) + bitDepthLumaMinus8\n h[o++] = 0xf8 | info.bitDepthChromaMinus8 // reserved(11111) + bitDepthChromaMinus8\n h[o++] = 0x00; h[o++] = 0x00 // avgFrameRate(0 = unspecified)\n // constantFrameRate(0) | numTemporalLayers | temporalIdNested | lengthSizeMinusOne(3)\n h[o++] = ((info.maxSubLayersMinus1 + 1) << 3) | ((info.temporalIdNestingFlag ? 1 : 0) << 2) | 3\n h[o++] = arrays.length // numOfArrays\n for (const a of arrays) {\n h[o++] = a.type & 0x3f // array_completeness(0) + NAL_unit_type\n h[o++] = 0; h[o++] = 1 // numNalus = 1\n h[o++] = (a.nal.length >> 8) & 0xff\n h[o++] = a.nal.length & 0xff\n h.set(a.nal, o); o += a.nal.length\n }\n return h.subarray(0, o)\n}\n\n/**\n * Build an hvcC `description` for a WebCodecs HEVC VideoDecoderConfig directly from a\n * keyframe access unit (Annex-B or length-prefixed). Returns null if VPS/SPS/PPS aren't\n * present in-band. HEVC analogue of {@link extractCodecDescriptionFromAnnexB}.\n */\nexport function extractHevcCodecDescription(keyframe: Uint8Array): Uint8Array | null {\n return generateHvcCFromParameterSets(extractHevcParameterSets(keyframe))\n}\n\n/**\n * Strip non-VCL NAL units (VPS/SPS/PPS/SEI/AUD, type >= 32) from an HEVC access unit,\n * returning only the VCL NAL units (type <= 31) as a 4-byte length-prefixed buffer.\n *\n * Required when decoding `hvc1` with an explicit hvcC `description`: WebCodecs rejects a\n * sample whose data still carries in-band parameter sets (\"Unable to determine size of\n * bitstream buffer\"). Accepts Annex-B or length-prefixed input. Returns the input\n * unchanged if it already contains only VCL NALs (cheap no-op for delta frames).\n */\nexport function hevcVclOnly(data: Uint8Array): Uint8Array {\n const nals = isAnnexB(data) ? splitAnnexBNalUnits(data) : splitAvccNalUnits(data)\n const vcl = nals.filter((n) => n.length > 0 && hevcNalType(n) <= 31)\n if (vcl.length === nals.length && !isAnnexB(data)) return data\n let size = 0\n for (const n of vcl) size += 4 + n.length\n const out = new Uint8Array(size)\n let o = 0\n for (const n of vcl) {\n out[o++] = (n.length >> 24) & 0xff\n out[o++] = (n.length >> 16) & 0xff\n out[o++] = (n.length >> 8) & 0xff\n out[o++] = n.length & 0xff\n out.set(n, o); o += n.length\n }\n return out\n}\n\n/**\n * Check if data starts with an Annex-B start code (00 00 01 or 00 00 00 01).\n */\nexport function isAnnexB(data: Uint8Array): boolean {\n if (data.length >= 4 && data[0] === 0 && data[1] === 0 &&\n (data[2] === 1 || (data[2] === 0 && data[3] === 1))) {\n return true\n }\n return false\n}\n\n/**\n * Find the byte offset of the first Annex-B start code in data.\n * Returns -1 if no start code found.\n */\nexport function findAnnexBStartCode(data: Uint8Array): number {\n for (let i = 0; i < data.length - 3; i++) {\n if (data[i] === 0 && data[i + 1] === 0) {\n if (data[i + 2] === 1) return i\n if (data[i + 2] === 0 && data[i + 3] === 1) return i\n }\n }\n return -1\n}\n\n/**\n * Split Annex-B bitstream into NAL units.\n * Returns array of NAL unit byte slices (without start codes).\n */\nexport function splitAnnexBNalUnits(data: Uint8Array): Uint8Array[] {\n const nalUnits: Uint8Array[] = []\n let i = 0\n while (i < data.length - 3) {\n if (data[i] === 0 && data[i + 1] === 0) {\n let scLen = 0\n if (data[i + 2] === 1) scLen = 3\n else if (data[i + 2] === 0 && i + 3 < data.length && data[i + 3] === 1) scLen = 4\n if (scLen > 0) {\n const nalStart = i + scLen\n let nalEnd = data.length\n for (let j = nalStart + 1; j < data.length - 2; j++) {\n if (data[j] === 0 && data[j + 1] === 0 &&\n (data[j + 2] === 1 || (data[j + 2] === 0 && j + 3 < data.length && data[j + 3] === 1))) {\n nalEnd = j\n break\n }\n }\n if (nalEnd > nalStart) nalUnits.push(data.subarray(nalStart, nalEnd))\n i = nalEnd\n continue\n }\n }\n i++\n }\n return nalUnits\n}\n\n/**\n * Convert Annex-B (start-code delimited) to AVCC (4-byte length prefixed).\n * Optionally prepends SPS/PPS NALs for keyframes.\n */\nexport function annexBToAvcc(data: Uint8Array, spsPps?: SpsPps): Uint8Array {\n const nalUnits = splitAnnexBNalUnits(data)\n if (nalUnits.length === 0) return data\n\n let extraSize = 0\n if (spsPps) {\n extraSize = 4 + spsPps.sps.length + 4 + spsPps.pps.length\n }\n const frameSize = nalUnits.reduce((sum, nal) => sum + 4 + nal.length, 0)\n const output = new Uint8Array(extraSize + frameSize)\n let w = 0\n\n if (spsPps) {\n w = writeNalLength(output, w, spsPps.sps.length)\n output.set(spsPps.sps, w); w += spsPps.sps.length\n w = writeNalLength(output, w, spsPps.pps.length)\n output.set(spsPps.pps, w); w += spsPps.pps.length\n }\n\n for (const nal of nalUnits) {\n w = writeNalLength(output, w, nal.length)\n output.set(nal, w); w += nal.length\n }\n return output\n}\n\nexport interface H264KeyframeDetectionOptions {\n /**\n * Allow classifying a length-prefixed NAL when the declared NAL length runs\n * beyond this buffer. MMTP routing can see only the first packet fragment of\n * a sample, where the NAL header is present but the full NAL is not.\n */\n allowPartialAvcc?: boolean\n}\n\n/**\n * Classify H.264 keyframe status by scanning NAL units. Returns undefined when\n * the payload is not H.264-classifiable. Handles Annex-B and AVCC formats.\n */\nexport function classifyH264Keyframe(\n data: Uint8Array,\n options: H264KeyframeDetectionOptions = {},\n): boolean | undefined {\n const nals = h264NalUnitsForKeyframeDetection(data, options)\n if (nals.length === 0) return undefined\n let sawIntraSlice = false\n let sawNonIntraVcl = false\n let sawNal = false\n for (const nal of nals) {\n sawNal = true\n const nalType = nal[0] !== undefined ? nal[0] & 0x1f : -1\n if (nalType === 5 || nalType === 7) return true\n if (nalType === 1) {\n if (isH264IntraSlice(nal)) sawIntraSlice = true\n else sawNonIntraVcl = true\n }\n }\n if (sawIntraSlice && !sawNonIntraVcl) return true\n return sawNal ? false : undefined\n}\n\n/**\n * Detect H.264 keyframe by scanning for IDR/SPS or intra non-IDR slices.\n * Handles both Annex-B and AVCC formats.\n */\nexport function detectH264Keyframe(\n data: Uint8Array,\n options: H264KeyframeDetectionOptions = {},\n): boolean {\n return classifyH264Keyframe(data, options) === true\n}\n\n/**\n * Convert MMTP timestamp (NTP short format) to monotonic microseconds.\n * Per ISO 23008-1 \u00A79.2.2 / RFC 5905: upper 16 bits = seconds (lower 16\n * of NTP seconds), lower 16 bits = fractional seconds.\n * Returns a monotonically increasing \u00B5s value within an ~18-hour window.\n */\nexport function mmtpTimestampToMicros(rawTs: bigint | number): number {\n // MMTP carries an NTP short timestamp as an unsigned 32-bit integer. Do not\n // use `Number(rawTs) >>> 0` here: bitwise coercion silently turns malformed\n // values such as -1, 2**32, fractions, and strings into plausible timestamps\n // and can poison downstream latency observations.\n const ts = typeof rawTs === 'bigint'\n ? rawTs >= 0n && rawTs <= 0xffff_ffffn\n ? Number(rawTs)\n : undefined\n : Number.isSafeInteger(rawTs) && rawTs >= 0 && rawTs <= 0xffff_ffff\n ? rawTs\n : undefined\n if (ts === undefined) {\n throw new RangeError(`MMTP timestamp must be an unsigned 32-bit integer, got ${String(rawTs)}`)\n }\n if (ts === 0) return 0\n const seconds = ts >>> 16\n const frac = ts & 0xFFFF\n return seconds * 1_000_000 + Math.floor(frac * 1_000_000 / 65536)\n}\n\n/** Validate the CMSF/MMTP catalog initData contract: complete top-level ftyp+moov. */\nexport function isFmp4InitSegment(data: Uint8Array): boolean {\n let offset = 0\n let sawFtyp = false\n let sawMoov = false\n\n while (offset + 8 <= data.byteLength) {\n const view = new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset)\n let size = view.getUint32(0, false)\n const type = String.fromCharCode(data[offset + 4]!, data[offset + 5]!, data[offset + 6]!, data[offset + 7]!)\n let headerSize = 8\n\n if (size === 1) {\n if (offset + 16 > data.byteLength) return false\n const largeSize = view.getBigUint64(8, false)\n if (largeSize > BigInt(Number.MAX_SAFE_INTEGER)) return false\n size = Number(largeSize)\n headerSize = 16\n } else if (size === 0) {\n size = data.byteLength - offset\n }\n\n if (size < headerSize || offset + size > data.byteLength) return false\n // `mmpu` is the ISO MMT MPU metadata box. It is valid inside an MMTP\n // FT=0 payload but is not an ISO-BMFF initialization box that an MSE\n // SourceBuffer can append as a top-level box.\n if (type === 'mmpu') return false\n if (type === 'ftyp') sawFtyp = true\n if (type === 'moov') {\n if (!sawFtyp) return false\n sawMoov = true\n }\n offset += size\n }\n\n return offset === data.byteLength && sawFtyp && sawMoov\n}\n\n/**\n * Return the fMP4 initialization segment carried by MMTP MPU metadata.\n *\n * ISO MMTP FT=0 metadata may contain an `mmpu` box between the top-level\n * `ftyp` and `moov` boxes (`ftyp + mmpu + moov`). `mmpu` is an MMT metadata\n * box, not an ISO-BMFF initialization box accepted by an MSE SourceBuffer;\n * appending it produces Chromium's `Invalid top-level ISO BMFF box type mmpu`\n * error, most visibly when a rendition switch delivers a fresh FT=0 packet.\n * The returned bytes retain every other top-level box, in wire order, and are\n * only returned when the resulting bytes are a complete `ftyp` + `moov` init.\n * Inputs that are already a valid fMP4 init are returned unchanged.\n */\nexport function normalizeMmtpInitSegment(data: Uint8Array): Uint8Array | undefined {\n if (isFmp4InitSegment(data)) return data\n\n const parts: Uint8Array[] = []\n let offset = 0\n let removedMpu = false\n\n while (offset + 8 <= data.byteLength) {\n const view = new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset)\n let size = view.getUint32(0, false)\n let headerSize = 8\n if (size === 1) {\n if (offset + 16 > data.byteLength) return undefined\n const largeSize = view.getBigUint64(8, false)\n if (largeSize > BigInt(Number.MAX_SAFE_INTEGER)) return undefined\n size = Number(largeSize)\n headerSize = 16\n } else if (size === 0) {\n size = data.byteLength - offset\n }\n if (size < headerSize || offset + size > data.byteLength) return undefined\n\n const type = String.fromCharCode(\n data[offset + 4]!,\n data[offset + 5]!,\n data[offset + 6]!,\n data[offset + 7]!,\n )\n if (type === 'mmpu') removedMpu = true\n else parts.push(data.subarray(offset, offset + size))\n offset += size\n }\n\n if (!removedMpu || offset !== data.byteLength) return undefined\n const normalized = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0))\n let writeOffset = 0\n for (const part of parts) {\n normalized.set(part, writeOffset)\n writeOffset += part.byteLength\n }\n return isFmp4InitSegment(normalized) ? normalized : undefined\n}\n\n// \u2500\u2500\u2500 Internal Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction hasIsoBmffMagic(data: Uint8Array): boolean {\n for (let i = 0; i + 8 <= data.length && i < 32; i += 4) {\n const tag = String.fromCharCode(data[i + 4], data[i + 5], data[i + 6], data[i + 7])\n if (tag === 'ftyp' || tag === 'moov') return true\n }\n return false\n}\n\nfunction findTrackStsdBoxes(data: Uint8Array): Array<{ o: number; sz: number }> {\n const moov = findBox(data, 0, data.length, 'moov')\n if (!moov) return []\n\n const out: Array<{ o: number; sz: number }> = []\n for (const trak of findBoxes(data, moov.o + 8, moov.o + moov.sz, 'trak')) {\n const stsd = findNestedBox(data, trak.o + 8, trak.o + trak.sz, ['mdia', 'minf', 'stbl', 'stsd'])\n if (stsd) out.push(stsd)\n }\n return out\n}\n\nfunction findNestedBox(\n buf: Uint8Array,\n start: number,\n end: number,\n path: string[],\n): { o: number; sz: number } | undefined {\n let s = start\n let e = end\n let current: { o: number; sz: number } | undefined\n for (const type of path) {\n current = findBox(buf, s, e, type)\n if (!current) return undefined\n s = current.o + 8\n e = current.o + current.sz\n }\n return current\n}\n\nfunction findBox(buf: Uint8Array, start: number, end: number, type: string): { o: number; sz: number } | undefined {\n return findBoxes(buf, start, end, type)[0]\n}\n\nfunction findBoxes(buf: Uint8Array, start: number, end: number, type: string): Array<{ o: number; sz: number }> {\n const boxes: Array<{ o: number; sz: number }> = []\n let o = start\n while (o + 8 <= end) {\n let sz = (buf[o] << 24) | (buf[o + 1] << 16) | (buf[o + 2] << 8) | buf[o + 3]\n const t = String.fromCharCode(buf[o + 4], buf[o + 5], buf[o + 6], buf[o + 7])\n if (sz === 0) sz = end - o\n if (sz < 8 || o + sz > end) break\n if (t === type) boxes.push({ o, sz })\n o += sz\n }\n return boxes\n}\n\nfunction writeNalLength(buf: Uint8Array, offset: number, len: number): number {\n buf[offset] = (len >> 24) & 0xff\n buf[offset + 1] = (len >> 16) & 0xff\n buf[offset + 2] = (len >> 8) & 0xff\n buf[offset + 3] = len & 0xff\n return offset + 4\n}\n\nfunction h264NalUnitsForKeyframeDetection(\n data: Uint8Array,\n options: H264KeyframeDetectionOptions,\n): Uint8Array[] {\n return splitH264SampleNalUnits(data, options).nals\n}\n\nfunction splitPartialAvccNalUnits(data: Uint8Array, lengthSize = 4): Uint8Array[] {\n const nals: Uint8Array[] = []\n let i = 0\n while (i + lengthSize < data.length) {\n let len = 0\n for (let k = 0; k < lengthSize; k++) len = (len << 8) | data[i + k]\n i += lengthSize\n if (len <= 0 || i >= data.length) break\n const end = Math.min(i + len, data.length)\n nals.push(data.subarray(i, end))\n if (end < i + len) break\n i = end\n }\n return nals\n}\n\nfunction isLikelyRawH264NalUnit(data: Uint8Array): boolean {\n if (data.length === 0) return false\n const header = data[0]!\n if ((header & 0x80) !== 0) return false\n const nalType = header & 0x1f\n return nalType > 0 && nalType < 24\n}\n\nfunction rawH264NalToAvcc(data: Uint8Array): Uint8Array {\n const out = new Uint8Array(4 + data.length)\n new DataView(out.buffer, out.byteOffset, out.byteLength).setUint32(0, data.length)\n out.set(data, 4)\n return out\n}\n\nfunction isH264IntraSlice(nal: Uint8Array): boolean {\n const sliceType = readH264SliceType(nal)\n return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9\n}\n\nfunction readH264SliceType(nal: Uint8Array): number | null {\n if (nal.length < 2 || (nal[0]! & 0x1f) !== 1) return null\n const rbsp = removeEmulationPrevention(nal.subarray(1))\n const state = { bitOffset: 0 }\n if (readUnsignedExpGolomb(rbsp, state) === null) return null\n return readUnsignedExpGolomb(rbsp, state)\n}\n\nfunction readUnsignedExpGolomb(data: Uint8Array, state: { bitOffset: number }): number | null {\n let leadingZeroBits = 0\n while (true) {\n const bit = readBit(data, state)\n if (bit === null) return null\n if (bit === 1) break\n leadingZeroBits++\n if (leadingZeroBits > 30) return null\n }\n\n let suffix = 0\n for (let i = 0; i < leadingZeroBits; i++) {\n const bit = readBit(data, state)\n if (bit === null) return null\n suffix = (suffix << 1) | bit\n }\n return (1 << leadingZeroBits) - 1 + suffix\n}\n\nfunction readBit(data: Uint8Array, state: { bitOffset: number }): 0 | 1 | null {\n if (state.bitOffset >= data.length * 8) return null\n const byte = data[state.bitOffset >> 3]!\n const bit = (byte >> (7 - (state.bitOffset & 7))) & 1\n state.bitOffset++\n return bit as 0 | 1\n}\n\nfunction hex2(n: number): string {\n return n.toString(16).padStart(2, '0')\n}\n\nfunction pad2(n: number): string {\n return String(n).padStart(2, '0')\n}\n\nfunction codecStringFromAv1C(av1C: Uint8Array): string {\n if (av1C.length < 4) return 'av01.0.01M.08'\n const profile = (av1C[1]! >>> 5) & 0x07\n const level = av1C[1]! & 0x1f\n const tier = (av1C[2]! & 0x80) !== 0 ? 'H' : 'M'\n let bitDepth = 8\n if ((av1C[2]! & 0x40) !== 0) {\n bitDepth = (av1C[2]! & 0x20) !== 0 ? 12 : 10\n }\n return `av01.${profile}.${pad2(level)}${tier}.${pad2(bitDepth)}`\n}\n\nfunction codecStringFromVpcC(vpcC: Uint8Array): string {\n if (vpcC.length < 3) return 'vp09.00.10.08'\n // ISO/IEC 14496-15 defines vpcC as a FullBox. Some tooling hands callers\n // the VPCodecConfigurationRecord after the 4-byte FullBox header; tolerate\n // both shapes because WebCodecs callers only need a stable RFC 6381 fallback.\n const offset = vpcC.length >= 7 && vpcC[0] <= 1 ? 4 : 0\n if (offset + 2 >= vpcC.length) return 'vp09.00.10.08'\n const profile = vpcC[offset]!\n const level = vpcC[offset + 1]!\n const bitDepth = (vpcC[offset + 2]! >>> 4) || 8\n return `vp09.${pad2(profile)}.${pad2(level)}.${pad2(bitDepth)}`\n}\n\n/**\n * Derive an RFC 6381 HEVC codec string (e.g. \"hvc1.1.6.L93.90\") from the\n * payload of an hvcC box (the HEVCDecoderConfigurationRecord, ISO 14496-15 \u00A78.3.3.1).\n * Only the general_* fields in the fixed 23-byte header are needed:\n * byte 1: general_profile_space(2) | general_tier_flag(1) | general_profile_idc(5)\n * bytes 2-5: general_profile_compatibility_flags (32 bits)\n * bytes 6-11: general_constraint_indicator_flags (48 bits)\n * byte 12: general_level_idc\n */\nfunction hevcCodecStringFromHvcC(c: Uint8Array, sampleEntry: 'hev1' | 'hvc1'): string {\n return formatHevcCodecString(\n sampleEntry,\n (c[1]! >> 6) & 0x3,\n ((c[1]! >> 5) & 0x1) === 1,\n c[1]! & 0x1f,\n ((c[2]! << 24) | (c[3]! << 16) | (c[4]! << 8) | c[5]!) >>> 0,\n c.subarray(6, 12),\n c[12]!,\n )\n}\n\n/** Exp-Golomb bitstream writer for SPS/PPS generation. */\nclass BitWriter {\n buf: number[] = []\n byte = 0\n bit = 7\n\n u(val: number, bits: number) {\n for (let i = bits - 1; i >= 0; i--) {\n this.byte |= ((val >> i) & 1) << this.bit\n if (--this.bit < 0) {\n this.buf.push(this.byte)\n this.byte = 0\n this.bit = 7\n }\n }\n }\n\n ue(val: number) {\n const v = val + 1\n const bits = Math.floor(Math.log2(v)) + 1\n this.u(0, bits - 1)\n this.u(v, bits)\n }\n\n se(val: number) {\n this.ue(val <= 0 ? -val * 2 : val * 2 - 1)\n }\n\n finish(): Uint8Array {\n if (this.bit < 7) {\n this.byte |= 1 << this.bit\n this.buf.push(this.byte)\n }\n return new Uint8Array(this.buf)\n }\n}\n\nfunction resolveResolution(\n explicitW: number | undefined,\n explicitH: number | undefined,\n level: number,\n): { width: number; height: number } {\n if (explicitW && explicitH) return { width: explicitW, height: explicitH }\n\n const levelResolutions: Record<number, [number, number]> = {\n 10: [176, 144], 11: [352, 288], 12: [352, 288], 13: [352, 288],\n 20: [352, 288], 21: [720, 576], 22: [720, 576],\n 30: [1280, 720], 31: [1280, 720], 32: [1280, 1024],\n 40: [1920, 1088], 41: [1920, 1088], 42: [2048, 1088],\n 50: [4096, 2160], 51: [4096, 2160], 52: [4096, 2160],\n }\n\n const [w, h] = levelResolutions[level] ?? [1920, 1088]\n return { width: explicitW ?? w, height: explicitH ?? h }\n}\n\nfunction buildMinimalSps(\n profile: number, constraint: number, level: number,\n width: number, height: number,\n): Uint8Array {\n const widthInMbs = Math.ceil(width / 16)\n const heightInMapUnits = Math.ceil(height / 16)\n\n const w = new BitWriter()\n w.u(0, 1); w.u(3, 2); w.u(7, 5) // NAL header: SPS\n w.u(profile, 8); w.u(constraint, 8); w.u(level, 8)\n w.ue(0) // seq_parameter_set_id\n\n if (profile === 100 || profile === 110 || profile === 122 || profile === 244 || profile === 44) {\n w.ue(1); w.ue(0); w.ue(0) // chroma + bit depth\n w.u(0, 1); w.u(0, 1) // transform bypass + scaling matrix\n }\n\n w.ue(0) // log2_max_frame_num_minus4\n w.ue(2) // pic_order_cnt_type=2\n w.ue(1) // max_num_ref_frames\n w.u(0, 1) // gaps_in_frame_num\n w.ue(widthInMbs - 1)\n w.ue(heightInMapUnits - 1)\n w.u(1, 1) // frame_mbs_only\n w.u(1, 1) // direct_8x8_inference\n\n const cropRight = widthInMbs * 16 - width\n const cropBottom = heightInMapUnits * 16 - height\n if (cropRight > 0 || cropBottom > 0) {\n w.u(1, 1)\n w.ue(0); w.ue(cropRight / 2); w.ue(0); w.ue(cropBottom / 2)\n } else {\n w.u(0, 1)\n }\n\n w.u(0, 1) // vui_parameters_present\n return w.finish()\n}\n\nfunction buildMinimalPps(profile: number): Uint8Array {\n const isHighProfile = profile === 100 || profile === 110 || profile === 122 || profile === 244 || profile === 44\n const w = new BitWriter()\n w.u(0, 1); w.u(3, 2); w.u(8, 5) // NAL header: PPS\n\n w.ue(0); w.ue(0) // pps_id, sps_id\n w.u(isHighProfile ? 1 : 0, 1) // entropy_coding_mode\n w.u(0, 1) // bottom_field_pic_order\n w.ue(0); w.ue(0); w.ue(0) // slice groups, ref_idx defaults\n w.u(0, 1); w.u(0, 2) // weighted_pred\n w.se(0); w.se(0); w.se(0) // qp offsets\n w.u(1, 1); w.u(0, 1); w.u(0, 1) // deblock, constrained_intra, redundant_pic_cnt\n\n if (isHighProfile) {\n w.u(1, 1); w.u(0, 1); w.se(0) // transform_8x8, scaling_matrix, chroma_qp_offset\n }\n\n return w.finish()\n}\n\n// \u2500\u2500\u2500 AAC / ADTS Utilities \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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/** ISO 14496-3 sampling frequency index lookup. */\nconst ADTS_SAMPLE_RATES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350] as const\n\n/**\n * Prepend a 7-byte ADTS header to a raw AAC access unit.\n *\n * WebCodecs AudioDecoder configured WITHOUT an AudioSpecificConfig `description`\n * expects ADTS-framed AAC. MMTP carries raw AAC (no ADTS sync), so this wrapper\n * must be applied before calling `AudioDecoder.decode()`.\n */\nexport function wrapAdtsFrame(raw: Uint8Array, sampleRate: number, channels: number): Uint8Array {\n const sri = ADTS_SAMPLE_RATES.indexOf(sampleRate as typeof ADTS_SAMPLE_RATES[number])\n const idx = sri >= 0 ? sri : 3 // default 48 kHz\n const len = 7 + raw.length\n const out = new Uint8Array(len)\n out[0] = 0xFF\n out[1] = 0xF1 // MPEG-4, Layer 0, no CRC\n out[2] = (1 << 6) | (idx << 2) | (channels >> 2) // profile=AAC-LC(1), freq, ch high\n out[3] = ((channels & 3) << 6) | ((len >> 11) & 3)\n out[4] = (len >> 3) & 0xFF\n out[5] = ((len & 7) << 5) | 0x1F\n out[6] = 0xFC\n out.set(raw, 7)\n return out\n}\n\n/**\n * Extract AAC AudioSpecificConfig (ASC) from an fMP4 init segment.\n *\n * Walks moov > trak > mdia > minf > stbl > stsd > mp4a > esds, then descends\n * the MPEG-4 descriptor chain (ES_Descriptor 0x03 > DecoderConfigDescriptor\n * 0x04 > DecoderSpecificInfo 0x05) to return the ASC payload.\n *\n * Sibling of extractAvcCFromInitSegment, used by the same BLO-4830 / CMSF \u00A73.1\n * path: when the catalog initData is the full ftyp+moov, WebCodecs' AudioDecoder\n * needs the raw ASC (~2 bytes for AAC-LC) as `description`, NOT the whole\n * segment. Without this extraction the configure() succeeds but every decode()\n * silently produces zero output (no error fires), exactly the symptom that\n * shows up as \"Audio continuity FAILED: energy unstable CV=1.00\" in the\n * 7-point E2E test (CV=1.00 is the meanEnergy=0 sentinel from audio-fft.mjs).\n *\n * Returns undefined when:\n * - data has no ftyp/moov magic in the first 32 bytes\n * - no mp4a sample entry exists in any trak's stbl\n * - the esds descriptor chain doesn't yield a DecoderSpecificInfo\n * - the ASC payload is shorter than 2 bytes (AOT + sampling-freq nibble)\n *\n * Walks every trak and returns the first AAC sample entry. This mirrors\n * extractAvcCFromInitSegment so multiplexed ftyp+moov init blobs work\n * regardless of track order.\n */\nexport function extractAacAscFromInitSegment(data: Uint8Array): AacAscInfo | undefined {\n if (!hasIsoBmffMagic(data)) return undefined\n\n for (const stsd of findTrackStsdBoxes(data)) {\n const info = extractAacAscFromStsd(data, stsd)\n if (info) return info\n }\n\n return undefined\n}\n\nfunction extractAacAscFromStsd(data: Uint8Array, stsd: { o: number; sz: number }): AacAscInfo | undefined {\n // stsd: 8 box header + 4 version+flags + 4 entry_count = 16 bytes before entries.\n const s = stsd.o + 16\n const e = stsd.o + stsd.sz\n // mp4a AudioSampleEntry minimum length: 8 box header + 28 fixed fields = 36 bytes\n // before any child boxes (esds lives here).\n const mp4a = findBox(data, s, e, 'mp4a')\n if (!mp4a || mp4a.sz < 36) return undefined\n const esds = findBox(data, mp4a.o + 36, mp4a.o + mp4a.sz, 'esds')\n // esds = 8 box header + 4 full-box version+flags = 12 bytes minimum before descriptors.\n if (!esds || esds.sz < 12) return undefined\n const esdsPayload = data.subarray(esds.o + 8, esds.o + esds.sz)\n const asc = extractAudioSpecificConfig(esdsPayload)\n if (!asc || asc.length < 2) return undefined\n // AudioObjectType = top 5 bits of ASC[0]. AAC-LC = 2, HE-AAC = 5, etc.\n const aot = asc[0] >> 3\n return { codec: `mp4a.40.${aot}`, description: asc }\n}\n\n/**\n * Walk an esds descriptor chain to find DecoderSpecificInfo (tag 0x05).\n * Step over fixed-size headers of container descriptors (0x03, 0x04) so the\n * scan continues into their children rather than skipping their full payload.\n *\n * Assumes the ES_Descriptor flags byte is zero (no streamDependence, URL, OCR\n * ES_ID fields). FFmpeg's mov/mp4 muxer emits exactly that for all standard\n * AAC tracks; the assumption is the same one extractAvcCFromInitSegment makes\n * about the avc1 sample entry's reserved fields.\n *\n * Input is the esds box payload AFTER the 8-byte box header; the first 4 bytes\n * (full-box version+flags) are skipped here.\n */\nfunction extractAudioSpecificConfig(esds: Uint8Array): Uint8Array | undefined {\n let offset = 4 // skip esds version+flags\n while (offset < esds.length) {\n const tag = esds[offset++]\n let size = 0\n for (let i = 0; i < 4 && offset < esds.length; i++) {\n const b = esds[offset++]\n size = (size << 7) | (b & 0x7f)\n if ((b & 0x80) === 0) break\n }\n if (tag === 0x05) {\n if (offset + size > esds.length) return undefined\n return esds.subarray(offset, offset + size)\n }\n if (tag === 0x03) {\n offset += 3 // ES_ID (2) + flags (1)\n } else if (tag === 0x04) {\n offset += 13 // OTI (1) + streamType (1) + bufferSizeDB (3) + maxBitrate (4) + avgBitrate (4)\n } else {\n offset += size\n }\n }\n return undefined\n}\n\n// =============================================================================\n// Inline Tests (vitest)\n// =============================================================================\n\nif (import.meta.vitest) {\n const { describe, test, expect } = import.meta.vitest\n\n describe('codec-utils', () => {\n describe('isAnnexB', () => {\n test('4-byte start code', () => {\n expect(isAnnexB(new Uint8Array([0, 0, 0, 1, 0x65]))).toBe(true)\n })\n test('3-byte start code', () => {\n expect(isAnnexB(new Uint8Array([0, 0, 1, 0x65]))).toBe(true)\n })\n test('rejects AVCC', () => {\n expect(isAnnexB(new Uint8Array([0, 0, 0, 10, 0x65]))).toBe(false)\n })\n })\n\n describe('findAnnexBStartCode', () => {\n test('at offset 0', () => {\n expect(findAnnexBStartCode(new Uint8Array([0, 0, 0, 1, 0x65]))).toBe(0)\n })\n test('at offset 5', () => {\n expect(findAnnexBStartCode(new Uint8Array([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0, 0, 1, 0x65]))).toBe(5)\n })\n test('returns -1 when none', () => {\n expect(findAnnexBStartCode(new Uint8Array([0xAA, 0xBB, 0xCC]))).toBe(-1)\n })\n })\n\n describe('splitAnnexBNalUnits', () => {\n test('splits two NALs', () => {\n const data = new Uint8Array([0, 0, 0, 1, 0x65, 0xAA, 0xBB, 0, 0, 0, 1, 0x41, 0xCC])\n const nals = splitAnnexBNalUnits(data)\n expect(nals.length).toBe(2)\n expect(nals[0]).toEqual(new Uint8Array([0x65, 0xAA, 0xBB]))\n expect(nals[1]).toEqual(new Uint8Array([0x41, 0xCC]))\n })\n test('handles 3-byte start codes', () => {\n const nals = splitAnnexBNalUnits(new Uint8Array([0, 0, 1, 0x67, 0x42, 0, 0, 1, 0x68, 0x01]))\n expect(nals.length).toBe(2)\n })\n })\n\n describe('annexBToAvcc', () => {\n test('converts single NAL', () => {\n const annexB = new Uint8Array([0, 0, 0, 1, 0x41, 0xAA, 0xBB])\n const avcc = annexBToAvcc(annexB)\n expect(avcc[3]).toBe(3) // NAL length\n expect(avcc[4]).toBe(0x41)\n })\n test('prepends SPS/PPS', () => {\n const annexB = new Uint8Array([0, 0, 0, 1, 0x65, 0x01])\n const avcc = annexBToAvcc(annexB, { sps: new Uint8Array([0x67, 0x42]), pps: new Uint8Array([0x68, 0x01]) })\n expect(avcc[3]).toBe(2) // SPS length\n expect(avcc[4]).toBe(0x67)\n })\n })\n\n describe('detectH264Keyframe', () => {\n test('IDR in Annex-B', () => {\n expect(detectH264Keyframe(new Uint8Array([0, 0, 0, 1, 0x65]))).toBe(true)\n })\n test('SPS in Annex-B', () => {\n expect(detectH264Keyframe(new Uint8Array([0, 0, 0, 1, 0x67]))).toBe(true)\n })\n test('IDR in AVCC', () => {\n expect(detectH264Keyframe(new Uint8Array([0, 0, 0, 5, 0x65, 1, 2, 3, 4]))).toBe(true)\n })\n test('IDR after AVCC AUD', () => {\n expect(detectH264Keyframe(new Uint8Array([\n 0, 0, 0, 1, 0x09,\n 0, 0, 0, 2, 0x65, 0xaa,\n ]))).toBe(true)\n })\n test('non-IDR AVC I-slice in AVCC', () => {\n expect(detectH264Keyframe(new Uint8Array([\n 0, 0, 0, 2, 0x41, 0x88,\n ]))).toBe(true)\n })\n test('raw H.264 IDR NAL', () => {\n expect(detectH264Keyframe(new Uint8Array([0x65, 0x88, 0x84]))).toBe(true)\n })\n test('raw H.264 non-IDR I-slice NAL', () => {\n expect(detectH264Keyframe(new Uint8Array([0x41, 0x88]))).toBe(true)\n })\n test('classifies partial length-prefixed IDR only when requested', () => {\n const partial = new Uint8Array([0, 0, 0x20, 0, 0x65])\n expect(classifyH264Keyframe(partial)).toBeUndefined()\n expect(classifyH264Keyframe(partial, { allowPartialAvcc: true })).toBe(true)\n })\n test('rejects P-frame', () => {\n expect(detectH264Keyframe(new Uint8Array([0, 0, 0, 1, 0x41]))).toBe(false)\n })\n test('rejects AVCC sample with only non-IDR slices', () => {\n expect(detectH264Keyframe(new Uint8Array([\n 0, 0, 0, 2, 0x41, 0xc0,\n 0, 0, 0, 2, 0x41, 0xc0,\n ]))).toBe(false)\n })\n })\n\n describe('avccToAnnexB', () => {\n test('converts with SPS/PPS on keyframe', () => {\n const avcc = new Uint8Array([0, 0, 0, 3, 0x65, 0xAA, 0xBB])\n const spsPps: SpsPps = { sps: new Uint8Array([0x67, 0x42]), pps: new Uint8Array([0x68, 0x01]) }\n const annexB = avccToAnnexB(avcc, true, spsPps)\n expect(annexB[3]).toBe(1) // start code\n expect(annexB[4]).toBe(0x67) // SPS\n })\n })\n\n describe('codecStringFromAvcC', () => {\n test('derives avc1.64002a', () => {\n expect(codecStringFromAvcC(new Uint8Array([1, 100, 0, 42]))).toBe('avc1.64002a')\n })\n })\n\n describe('extractAacAscFromInitSegment', () => {\n // Build a minimal valid ftyp+moov containing one mp4a sample entry whose\n // esds carries the supplied AudioSpecificConfig. The walker only needs\n // the box hierarchy moov > trak > mdia > minf > stbl > stsd > mp4a > esds;\n // mvhd/tkhd/mdhd/hdlr/smhd/dinf/stts/stsc/stsz/stco are spec-required for\n // a truly valid init but the extractor never reads them, so we omit them\n // to keep the fixture tight (~150 bytes vs ~500). FFmpeg's real output\n // includes them; the production path passes through `findBox` exactly\n // the same way.\n function buildMinimalAacInit(asc: Uint8Array): Uint8Array {\n const box = (type: string, payload: Uint8Array): Uint8Array => {\n const sz = 8 + payload.length\n const out = new Uint8Array(sz)\n out[0] = (sz >>> 24) & 0xff\n out[1] = (sz >>> 16) & 0xff\n out[2] = (sz >>> 8) & 0xff\n out[3] = sz & 0xff\n out[4] = type.charCodeAt(0); out[5] = type.charCodeAt(1)\n out[6] = type.charCodeAt(2); out[7] = type.charCodeAt(3)\n out.set(payload, 8)\n return out\n }\n const concat = (...arrs: Uint8Array[]): Uint8Array => {\n const total = arrs.reduce((n, a) => n + a.length, 0)\n const out = new Uint8Array(total)\n let off = 0\n for (const a of arrs) { out.set(a, off); off += a.length }\n return out\n }\n // ftyp: major_brand=iso5, minor=0x200, compat=iso5,iso6\n const ftyp = box('ftyp', new Uint8Array([\n 0x69, 0x73, 0x6f, 0x35, // 'iso5'\n 0x00, 0x00, 0x02, 0x00, // minor 0x200\n 0x69, 0x73, 0x6f, 0x35, // 'iso5'\n 0x69, 0x73, 0x6f, 0x36, // 'iso6'\n ]))\n\n // ESDescriptor (0x03) > DecoderConfigDescriptor (0x04) > DecoderSpecificInfo (0x05) > ASC.\n // Use 1-byte BER sizes (all payloads < 128).\n const dsi = new Uint8Array(2 + asc.length)\n dsi[0] = 0x05; dsi[1] = asc.length\n dsi.set(asc, 2)\n // DCD = 13 fixed bytes + DSI: OTI=0x40 (AAC), streamType=0x05<<2|0x01 (audio, upStream=0)\n const dcd = new Uint8Array(2 + 13 + dsi.length)\n dcd[0] = 0x04; dcd[1] = 13 + dsi.length\n dcd[2] = 0x40 // objectTypeIndication: Audio ISO/IEC 14496-3\n dcd[3] = (0x05 << 2) | 1 // streamType=AudioStream(5), upStream=0, reserved=1\n // bufferSizeDB(3) + maxBitrate(4) + avgBitrate(4) all zero is fine for the walker.\n dcd.set(dsi, 15)\n // ESDescriptor: ES_ID=0, flags=0, then DCD\n const esd = new Uint8Array(2 + 3 + dcd.length)\n esd[0] = 0x03; esd[1] = 3 + dcd.length\n // ES_ID(2) + flags(1) all zero\n esd.set(dcd, 5)\n // esds box = full-box (4-byte version+flags) + ES_Descriptor chain\n const esdsPayload = new Uint8Array(4 + esd.length)\n esdsPayload.set(esd, 4)\n const esds = box('esds', esdsPayload)\n\n // mp4a sample entry: 6 reserved + 2 dref_idx + 8 reserved + 2 channels + 2 samplesize +\n // 2 pre_defined + 2 reserved + 4 samplerate(48000<<16) = 28 bytes,\n // then esds child.\n const mp4aFixed = new Uint8Array(28)\n mp4aFixed[7] = 0x01 // data_reference_index = 1\n mp4aFixed[16] = 0x00; mp4aFixed[17] = 0x01 // channelcount = 1\n mp4aFixed[18] = 0x00; mp4aFixed[19] = 0x10 // samplesize = 16\n // samplerate at offset 24-27 (top 16 bits = sampleRate). 48000 = 0xBB80.\n mp4aFixed[24] = 0xBB; mp4aFixed[25] = 0x80\n const mp4a = box('mp4a', concat(mp4aFixed, esds))\n\n // stsd: 4 ver+flags + 4 entry_count(=1) + entries\n const stsdPayload = new Uint8Array(8 + mp4a.length)\n stsdPayload[7] = 0x01 // entry_count = 1\n stsdPayload.set(mp4a, 8)\n const stsd = box('stsd', stsdPayload)\n\n const stbl = box('stbl', stsd)\n const minf = box('minf', stbl)\n const mdia = box('mdia', minf)\n const trak = box('trak', mdia)\n const moov = box('moov', trak)\n\n return concat(ftyp, moov)\n }\n\n test('extracts AAC-LC mono 48k ASC and derives codec', () => {\n // AOT=2 (00010), samplingFrequencyIndex=3 (0011, 48000Hz), channelConfig=1 (0001),\n // GA: frameLengthFlag=0, dependsOnCoreCoder=0, extensionFlag=0 \u2192 0x11 0x88.\n const asc = new Uint8Array([0x11, 0x88])\n const init = buildMinimalAacInit(asc)\n const result = extractAacAscFromInitSegment(init)\n expect(result).toBeDefined()\n expect(result!.codec).toBe('mp4a.40.2')\n expect(Array.from(result!.description)).toEqual([0x11, 0x88])\n })\n\n test('derives AOT 5 (HE-AAC) from ASC[0] >> 3', () => {\n // AOT=5 (00101), rest don't matter for codec derivation.\n const asc = new Uint8Array([0x29, 0x88]) // 00101 001 1000 1000\n const init = buildMinimalAacInit(asc)\n expect(extractAacAscFromInitSegment(init)?.codec).toBe('mp4a.40.5')\n })\n\n test('rejects data without ftyp/moov magic', () => {\n expect(extractAacAscFromInitSegment(new Uint8Array(64))).toBeUndefined()\n })\n\n test('rejects ftyp+moov with no audio (no mp4a sample entry)', () => {\n // ftyp + moov with empty trak chain \u2014 no stsd, let alone mp4a.\n const ftyp = new Uint8Array([\n 0, 0, 0, 24, 0x66, 0x74, 0x79, 0x70,\n 0x69, 0x73, 0x6f, 0x35, 0, 0, 2, 0,\n 0x69, 0x73, 0x6f, 0x35, 0x69, 0x73, 0x6f, 0x36,\n ])\n const moov = new Uint8Array([0, 0, 0, 8, 0x6d, 0x6f, 0x6f, 0x76]) // empty moov\n const cat = new Uint8Array(ftyp.length + moov.length)\n cat.set(ftyp); cat.set(moov, ftyp.length)\n expect(extractAacAscFromInitSegment(cat)).toBeUndefined()\n })\n })\n\n describe('hevc', () => {\n // Minimal HEVC NAL units: header byte0 = (type << 1). VPS=32(0x40), SPS=33(0x42), PPS=34(0x44).\n // Real x265 repeat-headers=1 parameter sets (the cast encoder profile); the\n // SPS carries emulation-prevention bytes inside profile_tier_level. See\n // test-vectors/hevc-x265-repeat-headers-v1.json for the full access units.\n const vps = new Uint8Array([\n 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00,\n 0x03, 0x00, 0x00, 0x03, 0x00, 0x3c, 0x92, 0x80, 0x90,\n ])\n const sps = new Uint8Array([\n 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00,\n 0x03, 0x00, 0x3c, 0xa0, 0x0a, 0x08, 0x0f, 0x16, 0x59, 0x2a, 0x49, 0x32, 0xbc, 0x05, 0xa0,\n 0x20, 0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, 0x03, 0x03, 0xc1,\n ])\n const pps = new Uint8Array([0x44, 0x01, 0xc1, 0x72, 0xb4, 0x62, 0x40])\n const idr = new Uint8Array([0x26, 0x01, 0xaf, 0x06]) // type 19 (IDR_W_RADL)\n const lp = (...nals: Uint8Array[]) => {\n const parts: number[] = []\n for (const n of nals) { parts.push((n.length >> 24) & 0xff, (n.length >> 16) & 0xff, (n.length >> 8) & 0xff, n.length & 0xff, ...n) }\n return Uint8Array.from(parts)\n }\n\n test('isHevcCodec', () => {\n expect(isHevcCodec('hev1.1.6.L93.B0')).toBe(true)\n expect(isHevcCodec('hvc1.1.6.L93.B0')).toBe(true)\n expect(isHevcCodec('avc1.640033')).toBe(false)\n })\n\n test('removeEmulationPrevention strips 0x03', () => {\n expect(Array.from(removeEmulationPrevention(new Uint8Array([0, 0, 0x03, 1])))).toEqual([0, 0, 1])\n expect(Array.from(removeEmulationPrevention(new Uint8Array([0xaa, 0xbb])))).toEqual([0xaa, 0xbb])\n })\n\n test('splitAvccNalUnits splits length-prefixed NALs', () => {\n const nals = splitAvccNalUnits(lp(vps, sps))\n expect(nals.length).toBe(2)\n expect(nals[0]).toEqual(vps)\n expect(nals[1]).toEqual(sps)\n })\n\n test('isCompleteAvccSample accepts complete length-prefixed NAL samples', () => {\n expect(isCompleteAvccSample(lp(new Uint8Array([0x09]), idr))).toBe(true)\n })\n\n test('isCompleteAvccSample rejects Annex-B start-code samples', () => {\n expect(isCompleteAvccSample(new Uint8Array([0, 0, 0, 1, 0x65, 0xaa]))).toBe(false)\n })\n\n test('isCompleteAvccSample rejects truncated length-prefixed samples', () => {\n expect(isCompleteAvccSample(new Uint8Array([0, 0, 0, 4, 0x65, 0xaa]))).toBe(false)\n })\n\n test('normalizeH264SampleToAvcc leaves complete AVCC samples unchanged', () => {\n const avcc = lp(new Uint8Array([0x09]), idr)\n const normalized = normalizeH264SampleToAvcc(avcc)\n expect(normalized.format).toBe('avcc')\n expect(normalized.data).toBe(avcc)\n })\n\n test('normalizeH264SampleToAvcc converts a single raw H.264 NAL to AVCC', () => {\n const raw = new Uint8Array([0x65, 0x88, 0x84])\n const normalized = normalizeH264SampleToAvcc(raw)\n expect(normalized.format).toBe('raw-nal')\n expect(normalized.data).toEqual(new Uint8Array([0, 0, 0, 3, 0x65, 0x88, 0x84]))\n })\n\n test('splitH264SampleNalUnits exposes Annex-B NALs without AVCC conversion', () => {\n const annexB = new Uint8Array([0, 0, 0, 1, 0x65, 0x88, 0x84])\n const sample = splitH264SampleNalUnits(annexB)\n expect(sample.format).toBe('annexb')\n expect(sample.nals).toHaveLength(1)\n expect(sample.nals[0]).toEqual(new Uint8Array([0x65, 0x88, 0x84]))\n })\n\n test('splitH264SampleNalUnits exposes single raw H.264 NALs without wrapping', () => {\n const raw = new Uint8Array([0x65, 0x88, 0x84])\n const sample = splitH264SampleNalUnits(raw)\n expect(sample.format).toBe('raw-nal')\n expect(sample.nals).toEqual([raw])\n })\n\n test('splitH264SampleNalUnits can expose partial AVCC NAL headers', () => {\n const partial = new Uint8Array([0, 0, 0, 5, 0x65, 0x88])\n const sample = splitH264SampleNalUnits(partial, { allowPartialAvcc: true })\n expect(sample.format).toBe('partial-avcc')\n expect(sample.nals).toHaveLength(1)\n expect(sample.nals[0]).toEqual(new Uint8Array([0x65, 0x88]))\n })\n\n test('extractHevcParameterSets finds VPS/SPS/PPS (length-prefixed)', () => {\n const sets = extractHevcParameterSets(lp(vps, sps, pps, idr))\n expect(sets.vps).toEqual(vps)\n expect(sets.sps).toEqual(sps)\n expect(sets.pps).toEqual(pps)\n })\n\n test('extractHevcParameterSets finds VPS/SPS/PPS (Annex-B)', () => {\n const sc = new Uint8Array([0, 0, 0, 1])\n const annexb = Uint8Array.from([...sc, ...vps, ...sc, ...sps, ...sc, ...pps, ...sc, ...idr])\n const sets = extractHevcParameterSets(annexb)\n expect(sets.vps).toEqual(vps)\n expect(sets.sps).toEqual(sps)\n expect(sets.pps).toEqual(pps)\n })\n\n test('generateHvcCFromParameterSets builds a valid hvcC', () => {\n const hvcc = generateHvcCFromParameterSets({ vps, sps, pps })!\n expect(hvcc).not.toBeNull()\n expect(hvcc[0]).toBe(1) // configurationVersion\n expect(hvcc[1]).toBe(sps[3]) // general profile_tier_level byte 0 copied from SPS[3]\n expect(hvcc[22]).toBe(3) // numOfArrays (VPS+SPS+PPS)\n // first array entry: NAL_unit_type 32 (VPS), numNalus 1\n expect(hvcc[23] & 0x3f).toBe(32)\n expect((hvcc[24] << 8) | hvcc[25]).toBe(1)\n })\n\n test('generateHvcCFromParameterSets returns null without SPS/PPS', () => {\n expect(generateHvcCFromParameterSets({ vps })).toBeNull()\n })\n\n test('extractHevcCodecDescription end-to-end from keyframe', () => {\n const desc = extractHevcCodecDescription(lp(vps, sps, pps, idr))\n expect(desc).not.toBeNull()\n expect(desc![0]).toBe(1)\n })\n\n test('hevcVclOnly strips parameter-set NALs, keeps VCL', () => {\n const stripped = hevcVclOnly(lp(vps, sps, pps, idr))\n const nals = splitAvccNalUnits(stripped)\n expect(nals.length).toBe(1) // only the IDR VCL NAL remains\n expect(nals[0]).toEqual(idr)\n })\n\n test('hevcVclOnly is a no-op for VCL-only length-prefixed input', () => {\n const vclOnly = lp(idr)\n expect(hevcVclOnly(vclOnly)).toBe(vclOnly)\n })\n })\n })\n}\n", "/**\n * Exact timing authored by an ISO-BMFF media fragment.\n *\n * `timestamp`/`duration` fields on the browser-facing APIs are converted to\n * microseconds for legacy callers. This value remains in the media track's\n * native timescale so consumers that own a CMAF/WebCodecs timeline do not\n * have to reconstruct integer ticks from rounded wall-clock values.\n */\nexport interface AuthoredTiming {\n /** Exact decode time in the media track's timescale. */\n decodeTime: bigint\n /** Exact presentation time in the media track's timescale, including CTS. */\n presentationTime: bigint\n /**\n * Exact sample duration in the media track's timescale. This remains a\n * number because ISO-BMFF stores sample_duration as an unsigned 32-bit\n * field, whose full range is exactly representable by JavaScript numbers.\n */\n durationTicks: number\n /** `mdhd` timescale for all values above. */\n mediaTimescale: number\n}\n\n/** Convert authored media ticks to an integer target timescale without first\n * narrowing the authored tick value to a wall-clock float. */\nexport function scaleAuthoredTicks(\n ticks: bigint,\n mediaTimescale: number,\n targetTimescale: number,\n): number | null {\n if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0 ||\n !Number.isSafeInteger(targetTimescale) || targetTimescale <= 0) return null\n\n const negative = ticks < 0n\n const numerator = (negative ? -ticks : ticks) * BigInt(targetTimescale)\n const denominator = BigInt(mediaTimescale)\n const whole = numerator / denominator\n const remainder = numerator % denominator\n if (whole > BigInt(Number.MAX_SAFE_INTEGER)) return null\n const value = Number(whole) + Number(remainder) / mediaTimescale\n return Number.isFinite(value) ? (negative ? -value : value) : null\n}\n\n/** Convert exact authored presentation time and duration to an assembler's\n * public timestamp scale. */\nexport function scaleAuthoredTiming(\n timing: AuthoredTiming,\n targetTimescale: number,\n): { timestamp: number; duration: number } | null {\n if (!Number.isSafeInteger(timing.durationTicks) || timing.durationTicks <= 0) return null\n const timestamp = scaleAuthoredTicks(\n timing.presentationTime,\n timing.mediaTimescale,\n targetTimescale,\n )\n const duration = scaleAuthoredTicks(\n BigInt(timing.durationTicks),\n timing.mediaTimescale,\n targetTimescale,\n )\n if (timestamp === null || duration === null || duration <= 0) return null\n return { timestamp, duration }\n}\n", "/**\n * MMTP packet processing and frame routing layer.\n *\n * Delegates MMTP header parsing, MFU extraction, reassembly, and keyframe\n * detection to MmtpContainerParser while owning FEC orchestration, sync\n * gating, CMAF assembly, and callback routing.\n *\n * Extracted from MulticastManager \u2014 this module owns MMTP-layer concerns:\n * FEC symbol feeding, sync gating, MSE segment assembly, and frame routing.\n * It does NOT own network I/O, watchdog timers, or multicast join/leave.\n *\n * @packageDocumentation\n */\n\nimport {\n MMTP_SIGNALING_PACKET_ID,\n parseMMTPHeader,\n parseMoqRepairFrameWithHeader,\n serial32Add,\n serial32Distance,\n serial32Precedes,\n type FecBlockProfile,\n type MMTPHeader,\n} from \"@blockcast/mmt-base\";\nimport type { IsoHeldSource } from \"./fec-manager.js\";\nimport type { IsoPlacedSource, IsoRepairPlacement } from \"./iso-block-locator.js\";\nimport { isMfuReassemblyError } from \"./mfu-reassembler.js\";\nimport type {\n MfuReassemblerBackend,\n MmtpSourcePath,\n MmtpDeliveryProvenance,\n} from \"./mfu-reassembler.js\";\nimport type { MfuReassemblyPolicy } from \"./mfu-reassembly-policy.js\";\nimport { mmtpTimestampToMicros } from \"./codec-utils.js\";\nimport { scaleAuthoredTiming, type AuthoredTiming } from \"./authored-timing.js\";\nimport {\n processFecBlock,\n processFecSymbol,\n FecBlockMapper,\n type ProcessFecBlockResult,\n} from \"@blockcast/mmt-fec\";\nimport {\n CmafBlockAssembler,\n type BlockAssemblerConfig,\n type CmafBlockSample,\n} from \"./cmaf-block-assembler.js\";\nimport {\n MmtpContainerParser,\n isMfuKeyframeMetadata,\n type FecReleaseGate,\n type FrameMeta as ParserFrameMeta,\n type ParsedMmtpPacket,\n} from \"./mmtp-container-parser.js\";\nimport { type TrackRole } from \"./carp-catalog.js\";\nimport {\n decideGap,\n type BlockClass,\n type ClassifierMode,\n type ClassifierReason,\n type FrameGapDecision,\n type GapFrameEvidence,\n type SourceSymbolEvidence,\n} from \"./block-policy.js\";\nimport {\n duplicateRetentionMs,\n StreamDuplicateLedgers,\n type DuplicateHorizon,\n} from \"./duplicate-ledger.js\";\nimport type {\n ManifestAuthMode,\n ManifestObjectIdentity,\n ManifestTrackContext,\n ManifestVerifier,\n} from \"@blockcast/mmt-manifest-verify\";\n\n// \u2500\u2500\u2500 Constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 * Keyframe loss timeout slack factor (Phase 13, tracks WITHOUT FEC only).\n *\n * FEC tracks never arm the keyframe-lost timer: vanished FEC blocks are\n * materialised from SBN evidence and resolve through their catalog-derived\n * repair and fail deadlines, and the stall/conceal decision rides on the\n * first frame released after the gap (`RoutedFrameMeta.gapBefore`).\n *\n * Derivation: The keyframe loss timer must fire after one full keyframe group\n * has been missed. Group duration must come from explicit catalog timing; FEC\n * sourceSymbols is a block width, not a GOP length. Multicast jitter means the\n * last packet of a group may arrive up to ~0.5 group durations late (network\n * reordering + FEC recovery latency). The total timeout is therefore:\n *\n * timeout = group_duration * (1.0 + 0.5_jitter) = group_duration * 1.5\n *\n * The 0.5 jitter margin covers: (a) FEC interleave recovery window (up to D\n * frames), (b) network reordering within one interleave depth, and (c) OS\n * socket buffer draining latency. This is tight enough to detect loss within\n * one missing group while avoiding false positives from normal jitter.\n */\nexport const KEYFRAME_LOST_TIMEOUT_SLACK = 1.5;\n\n/**\n * Largest delay a JavaScript timer honours: HTML and Node store it as a signed\n * 32-bit millisecond count, and a larger value overflows to fire almost at\n * once. A keyframe-lost timeout above it, fixed or read, would therefore\n * declare every keyframe lost immediately, so it is refused like any other\n * unusable value.\n */\nconst MAX_TIMER_DELAY_MS = 0x7fffffff;\n\nfunction isRouterDebugEnabled(): boolean {\n const globalDebug = (globalThis as { __MMTP_ROUTER_DEBUG?: unknown }).__MMTP_ROUTER_DEBUG;\n if (globalDebug === true || globalDebug === \"true\" || globalDebug === \"1\") return true;\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n return env?.[\"MMTP_ROUTER_DEBUG\"] === \"1\" || env?.[\"MMTP_ROUTER_DEBUG\"] === \"true\";\n}\nfunction debugRouter(message: string): void {\n if (isRouterDebugEnabled()) console.debug(message);\n}\n\n// \u2500\u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 RoutedFrameMeta = {\n /** Authored ISO-BMFF presentation timestamp, in microseconds. */\n timestamp: number;\n /**\n * Raw MMTP short-NTP header timestamp. This is transport timing metadata\n * only; it is deliberately separate from the authored media timestamp.\n */\n mmtpTimestamp?: bigint;\n keyframe: boolean;\n /** Exact ISO-BMFF timing in the media track's native timescale. */\n authoredTiming?: AuthoredTiming;\n /** Transport that supplied the accepted FI=1 head (or complete FI=0 frame). */\n source?: MmtpSourcePath;\n /**\n * Whole-frame delivery verdict folded across every contributing fragment.\n *\n * Distinct from `source` on purpose. `source` answers a routing question \u2014\n * which transport's copy is this \u2014 and deliberately lets the head fragment\n * decide. This answers an evidence question: did every byte of this frame\n * physically arrive over multicast? A frame can be routed as 'multicast'\n * and still be 'mixed'.\n */\n deliveryProvenance?: MmtpDeliveryProvenance;\n packetId?: number;\n packetSequenceNumber?: number;\n /** Every authoritative MMTP source-packet sequence that formed this frame. */\n packetSequenceNumbers?: number[];\n /** Subset of packetSequenceNumbers reconstructed by FEC. */\n repairedPacketSequenceNumbers?: number[];\n /** Native MMTP MPU group coordinate. */\n mpuSequenceNumber?: number;\n /**\n * Timed-MFU sample identity `(movie_fragment_sequence_number, sample_number)`\n * from the MFU data-unit header. Absent when the MFU header is untimed.\n */\n movieFragmentSequenceNumber?: number;\n sampleNumber?: number;\n /** Immutable catalog identity supplied by the owning ingress subscription. */\n catalogTrackName?: string;\n recovered?: boolean;\n /**\n * True when this frame opens playback after the router suppressed earlier\n * video deltas while waiting for a sync keyframe. Downstream decoders can\n * use this to treat the following dependency chain as provisional.\n */\n sourceDiscontinuity?: boolean;\n /**\n * Stall/conceal decision for the first frame released after a gap: its\n * FEC blocks resolved with lost media, or authored decode time shows a\n * missing sample. Sinks act on it in order, on this frame. It is the same\n * object the manager emits as its `gap` event.\n */\n gapBefore?: FrameGapDecision;\n};\n\nexport interface MmtpIngressContext {\n tracks: readonly Readonly<{ name: string; packetId: number }>[];\n}\n\n/** One physical stream: an MMTP packet ID and the catalog track it carries. */\nexport interface MmtpStreamIdentity {\n readonly packetId: number;\n readonly catalogTrackName: string;\n}\n\n/**\n * Where a staged stream switch committed, relative to the outgoing stream.\n *\n * - `outgoing-reached-rap`: the outgoing stream was about to deliver a frame\n * at or past the incoming RAP's presentation time. The splice is exact:\n * the outgoing stream delivered every frame before the RAP that reached\n * the router, and none at or after it. An MSE assembler is the one\n * exception, since its flush is unbounded (see `stageStreamSwitch`).\n * - `outgoing-ahead`: when the incoming RAP arrived, the outgoing stream had\n * already delivered a frame at or past it. The switch commits on that RAP\n * at once; incoming frames up to `outgoingHighWater` cover media time the\n * outgoing stream already delivered.\n * - `outgoing-overdue`: the incoming stream reached its next RAP before the\n * outgoing stream reached the one held for it, so the outgoing stream is at\n * least a GOP behind (stalled, or losing media) and waiting longer only\n * widens the gap. The switch commits on the held RAP: the held GOP is\n * delivered, then the newer RAP. It overlaps nothing, since every outgoing\n * frame delivered was compared against the held RAP and is before it.\n */\nexport type StreamSwitchCommitReason =\n | \"outgoing-reached-rap\"\n | \"outgoing-ahead\"\n | \"outgoing-overdue\";\n\n/** Presentation position of one frame, in the router's frame vocabulary. */\nexport interface StreamSwitchPosition {\n /** Authored presentation timestamp, in microseconds. */\n readonly timestamp: number;\n /** Exact authored timing, when the frame carried it. */\n readonly authoredTiming?: Readonly<AuthoredTiming>;\n}\n\n/** A staged stream switch, at the moment it commits. */\nexport interface StreamSwitchCommit {\n readonly from: MmtpStreamIdentity;\n readonly to: MmtpStreamIdentity;\n /** The incoming RAP the switch commits on: the first `to` frame delivered. */\n readonly rap: StreamSwitchPosition & {\n readonly mpuSequenceNumber?: number;\n };\n /**\n * The furthest-presented outgoing frame delivered before the commit,\n * counting the gap fills the commit released, or undefined when the\n * outgoing stream delivered none.\n */\n readonly outgoingHighWater: StreamSwitchPosition | undefined;\n readonly reason: StreamSwitchCommitReason;\n /**\n * Incoming frames never delivered: the deltas before the incoming stream's\n * first RAP (the GOP it was admitted into mid-way), and a held GOP a reset\n * of the incoming stream invalidated.\n */\n readonly droppedIncomingFrames: number;\n}\n\n/** What MmtpRouter.stageStreamSwitch needs. */\nexport interface StreamSwitchOptions {\n /** The stream being replaced: a registered video packet ID. */\n readonly from: MmtpStreamIdentity;\n /** The replacing stream: a registered video packet ID other than `from`'s. */\n readonly to: MmtpStreamIdentity;\n /**\n * Called synchronously at the commit, after `from`'s packet ID is retired\n * and before `to`'s withheld init and its RAP are delivered. Throwing fails\n * the commit closed: `to` is retired as well and nothing of it is\n * delivered, since `from` can no longer be restored.\n */\n readonly onCommit: (commit: StreamSwitchCommit) => void;\n}\n\n/** A switch MmtpRouter.stageStreamSwitch staged. */\nexport interface StagedStreamSwitch {\n /**\n * Abandon the switch before it commits: `to` is no longer withheld and its\n * withheld init is dropped. Returns false when the switch already committed\n * or was cancelled.\n */\n cancel(): boolean;\n}\n\n/** One incoming frame withheld until the switch commits. */\ninterface HeldSwitchFrame {\n readonly data: Uint8Array;\n readonly meta: ParserFrameMeta;\n /** The FEC coordinates the frame arrived under, for its MSE assembler. */\n readonly fecInfo: { sbn: number; esi: number; oversized?: boolean } | undefined;\n}\n\n/** Router-side state of a staged stream switch. */\ninterface StreamSwitchState {\n readonly from: MmtpStreamIdentity;\n readonly to: MmtpStreamIdentity;\n readonly onCommit: (commit: StreamSwitchCommit) => void;\n /** Null until the incoming stream's first RAP; then that RAP and every incoming frame after it. */\n held: HeldSwitchFrame[] | null;\n /** The incoming stream's newest init, withheld until the commit. */\n heldInit: Uint8Array | undefined;\n droppedIncomingFrames: number;\n}\n\nfunction assertStreamIdentity(role: string, stream: MmtpStreamIdentity | undefined): void {\n if (\n stream === undefined ||\n !Number.isInteger(stream.packetId) ||\n stream.packetId <= MMTP_SIGNALING_PACKET_ID ||\n typeof stream.catalogTrackName !== \"string\" ||\n stream.catalogTrackName.length === 0\n ) {\n throw new Error(\n `[MmtpRouter] stream switch ${role} needs a track packet ID and a non-empty catalog track name`,\n );\n }\n}\n\nfunction isStream(\n meta: { packetId: number; catalogTrackName?: string },\n stream: MmtpStreamIdentity,\n): boolean {\n return meta.packetId === stream.packetId && meta.catalogTrackName === stream.catalogTrackName;\n}\n\n/**\n * Presentation order of two frames of different renditions. Exact when both\n * carry authored timing (renditions may use different timescales); otherwise\n * by the microsecond timestamps the router emits.\n */\nfunction comparePresentation(a: StreamSwitchPosition, b: StreamSwitchPosition): number {\n const at = a.authoredTiming;\n const bt = b.authoredTiming;\n if (at !== undefined && bt !== undefined) {\n const left = at.presentationTime * BigInt(bt.mediaTimescale);\n const right = bt.presentationTime * BigInt(at.mediaTimescale);\n return left < right ? -1 : left > right ? 1 : 0;\n }\n return a.timestamp - b.timestamp;\n}\n\nfunction switchPosition(meta: {\n timestamp: number;\n authoredTiming?: AuthoredTiming;\n}): StreamSwitchPosition {\n return Object.freeze({\n timestamp: meta.timestamp,\n ...(meta.authoredTiming === undefined\n ? {}\n : { authoredTiming: Object.freeze({ ...meta.authoredTiming }) }),\n });\n}\n\n/** What one ingress track list says about one packet ID. */\ninterface IngressPacketEntry {\n /** The one non-empty catalog name the list gives the packet ID, if exactly one. */\n readonly name?: string;\n /** More than one non-empty catalog name claims the packet ID. */\n readonly ambiguous: boolean;\n}\n\nfunction indexIngressTracks(\n tracks: MmtpIngressContext[\"tracks\"],\n): ReadonlyMap<number, IngressPacketEntry> {\n const names = new Map<number, Set<string>>();\n for (const track of tracks) {\n let packetNames = names.get(track.packetId);\n if (!packetNames) {\n packetNames = new Set();\n names.set(track.packetId, packetNames);\n }\n if (track.name.length > 0) packetNames.add(track.name);\n }\n const index = new Map<number, IngressPacketEntry>();\n for (const [packetId, packetNames] of names) {\n index.set(\n packetId,\n packetNames.size === 1\n ? { name: packetNames.values().next().value, ambiguous: false }\n : { ambiguous: packetNames.size > 1 },\n );\n }\n return index;\n}\n\n/**\n * Index of each frozen ingress track list (BLO-36599). MulticastManager.join\n * freezes the list it hands the transport, which passes that same list with\n * every packet, so the packetId -> name mapping is derived once per join\n * rather than filtered up to four times per packet. A list that is not frozen\n * may still change, so it is indexed afresh on every packet as before.\n */\nconst frozenIngressIndexes = new WeakMap<object, ReadonlyMap<number, IngressPacketEntry>>();\n\nfunction ingressEntry(\n ingress: MmtpIngressContext,\n packetId: number,\n): IngressPacketEntry | undefined {\n const tracks = ingress.tracks;\n if (!Object.isFrozen(tracks)) return indexIngressTracks(tracks).get(packetId);\n let index = frozenIngressIndexes.get(tracks);\n if (!index) {\n index = indexIngressTracks(tracks);\n frozenIngressIndexes.set(tracks, index);\n }\n return index.get(packetId);\n}\n\nfunction catalogTrackNameForPacket(\n ingress: MmtpIngressContext | undefined,\n packetId: number,\n): string | undefined {\n if (!ingress) return undefined;\n return ingressEntry(ingress, packetId)?.name;\n}\n\nfunction hasAmbiguousCatalogTrackName(\n ingress: MmtpIngressContext | undefined,\n packetId: number,\n): boolean {\n if (!ingress) return false;\n return ingressEntry(ingress, packetId)?.ambiguous === true;\n}\n\nfunction ingressHasPacketId(\n ingress: MmtpIngressContext | undefined,\n packetId: number,\n): boolean {\n // packet_id 0 is the MMTP signaling flow, never a track's, whatever the ingress.\n if (packetId === MMTP_SIGNALING_PACKET_ID) return false;\n // Direct/legacy callers have no catalog-backed ingress policy to enforce.\n // MulticastManager supplies a populated context whenever packetIds are selected.\n return ingress === undefined || ingressEntry(ingress, packetId) !== undefined;\n}\n\n/** Callback for decoded video/audio frames. */\nexport type FrameCallback = (data: Uint8Array, meta: RoutedFrameMeta) => void;\n\n/** Metadata accompanying an accepted raw MMTP source packet. */\nexport type RoutedPacketMeta = {\n packetId: number;\n packetSequenceNumber: number;\n /** True when FEC reconstructed this source packet. */\n recovered: boolean;\n /** True when the packet has no trailing Source FEC Payload ID. */\n skipFecPayloadId: boolean;\n /** Immutable catalog identity supplied by the owning ingress subscription. */\n catalogTrackName?: string;\n /**\n * Strict provenance for the fragments this packet produces. Set for\n * FEC-recovered packets, which carry no `source` of their own but inherit\n * their FEC block's symbol provenance.\n */\n deliveryProvenance?: MmtpDeliveryProvenance;\n};\n\n/** Callback for accepted raw MMTP source packets. */\nexport type TrackPacketCallback = (packet: Uint8Array, meta: RoutedPacketMeta) => void;\n\ntype PendingRecoveredVideoFrame = {\n data: Uint8Array;\n meta: RoutedFrameMeta;\n};\n\ntype PendingRecoveredAudioFrame = {\n data: Uint8Array;\n meta: RoutedFrameMeta;\n};\n\ntype DirectAudioCursor = {\n timestamp: number;\n sequenceNumber: number;\n};\n\n/**\n * One physical stream's stable key and duplicate ledgers, keyed by wire\n * numbers rather than strings.\n */\ninterface StreamLedgers {\n /** JSON tuple naming the stream; see #mediaStreamKey. */\n readonly key: string;\n /**\n * The stream's three duplicate ledgers, each retained for the stream's FEC\n * horizon (see duplicate-ledger.ts):\n *\n * - `sourceSeqs`: packet_sequence_numbers already received on the direct\n * source path. Recovered FEC blocks contain all K source symbols, so skip\n * direct-path duplicates even when the source frame is still buffered by\n * parser reordering.\n * - `routedSeqs`: packet_sequence_numbers already handed to the track packet\n * callback.\n * - `parsedSymbols`: Source FEC Payload IDs (SS_ID) already parsed for\n * playback. An overlap copy and its multicast twin carry the same symbol,\n * and the copy never feeds FEC, so FEC's first-arrival check cannot dedup\n * the pair.\n */\n readonly duplicates: StreamDuplicateLedgers;\n}\n\nconst NO_FEC_MANAGER_HORIZON: DuplicateHorizon = Object.freeze({\n kind: \"none\",\n reason: \"no-fec-manager\",\n});\nconst NO_FEC_GEOMETRY_HORIZON: DuplicateHorizon = Object.freeze({\n kind: \"none\",\n reason: \"no-fec-geometry\",\n});\nconst NO_BLOCK_SPAN_HORIZON: DuplicateHorizon = Object.freeze({\n kind: \"none\",\n reason: \"no-block-span\",\n});\n\nconst DIRECT_RECOVERED_VIDEO_QUEUE_LIMIT = 512;\nconst DIRECT_RECOVERED_AUDIO_QUEUE_LIMIT = 512;\n\ntype ParserDiagnostics = {\n packets: number;\n frames: number;\n initSegments: number;\n noFragment: number;\n fragments: number;\n reassembled: number;\n pendingBuffers: number;\n pendingFragments: number;\n pendingSamples?: unknown[];\n lastPacketLength: number;\n lastSequenceNumber: number;\n lastFecSsId?: number;\n lastFrameTimestamp?: number;\n directAudioSourceEmitted: number;\n directAudioSourceRegressions: number;\n directAudioRecoveredQueued: number;\n directAudioRecoveredDrained: number;\n directAudioRecoveredStaleDropped: number;\n};\n\n/**\n * FECManager interface \u2014 the contract MmtpRouter expects for FEC\n * source/repair symbol processing and block lifecycle events.\n *\n * Concrete implementation: `FECManager` class in `./fec-manager.ts`.\n * MmtpRouter only interacts with FEC through this interface.\n */\nexport interface FECManagerLike {\n /** Feed a source symbol to the FEC decoder for a given track.\n * Returns recovered block bytes if recovery completes, else null.\n *\n * `symbolData` is the complete MMTP packet without its Source FEC Payload\n * ID, unpadded and possibly a view into the received packet. The manager\n * zero-pads it to the packet's own symbol size T.\n *\n * Optional `alta` carries the detached ALTA authenticator extracted from\n * the MMTP header-extension trailer (08-07 Path 2) \u2014 present on signed\n * source packets, absent on relay-reassembled / unsigned streams. When\n * provided, the fec-worker runs verify_detached instead of counting the\n * symbol as `altaPending`. */\n feedSourceSymbol(\n packetId: number,\n ssId: number,\n symbolData: Uint8Array,\n alta?: { auth: Uint8Array; payloadEnd: number },\n catalogTrackName?: string,\n ): Uint8Array | null;\n\n /** Feed a repair symbol to the FEC decoder for a given track.\n * Returns recovered block bytes if recovery completes, else null. */\n feedRepairSymbol(\n packetId: number,\n ssStart: number,\n ssbLength: number,\n rsId: number,\n repairData: Uint8Array,\n catalogTrackName?: string,\n ): Uint8Array | null;\n\n /** Delivery-gap sample for one multicast packet (FECManager.noteMulticastArrival). */\n noteMulticastArrival?(packetId: number, packetSequenceNumber: number): void;\n\n /** Record a transport symbol for first-arrival-wins dedup and path counters. */\n feedSymbolFromSource(\n packetId: number,\n sbn: number,\n esi: number,\n data: Uint8Array,\n source: \"multicast\" | \"moq\",\n catalogTrackName?: string,\n ): boolean;\n\n /** Strict provenance for a block: 'multicast' only when no symbol arrived\n * over MoQ. Recovered bytes inherit it, since a recovered symbol is a\n * function of every symbol that entered the block. */\n blockDeliveryProvenance?(\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): MmtpDeliveryProvenance;\n\n /** Track a first-arrival network source symbol for block completion and\n * classification. Refreshes the inactivity deadline and marks clean when\n * K arrive. */\n trackBlock(\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n esi: number,\n evidence: SourceSymbolEvidence,\n ): void;\n\n /** True once the packetId has a per-track FEC configuration. */\n isTrackConfigured?(packetId: number): boolean;\n\n /** Lifecycle resolution of one block for in-order frame release. */\n blockResolution?(\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ): \"pending\" | \"complete\" | \"failed\" | \"untracked\";\n\n /** Highest SBN seen for a stream in the current epoch. */\n highestSbn?(packetId: number, catalogTrackName?: string): number | undefined;\n\n /** Catalog/reset epoch of a packet's streams. */\n epochFor?(packetId: number): number;\n\n /**\n * Catalog `fec.interleaveDepthMs` (\u00A75.1 full block span) of a packetId; 0\n * when the stream has none.\n */\n interleaveDepthMsForPacket?(packetId: number): number;\n\n /**\n * How long a terminal block stays authoritative before it retires to\n * untracked. The release gate holds a frame at most this long, so its loss\n * scan never reads a retired, delivered block as lost. Required whenever\n * blockResolution is.\n */\n terminalRetentionMsForPacket?(packetId: number): number;\n\n /** Configured codec of a packetId. */\n codecFor?(packetId: number): string | undefined;\n\n /** Current classifier mode of a stream. */\n classifierModeFor?(\n packetId: number,\n catalogTrackName?: string,\n ): { mode: ClassifierMode; reason: ClassifierReason | null };\n\n /** Whether an MPU boundary still bounds the stream's RAPs. */\n mpuBoundsRapsFor?(packetId: number, catalogTrackName?: string): boolean;\n\n /** Record a RAP released in order (RAP-spacing invariant). */\n noteReleasedRap?(\n packetId: number,\n catalogTrackName: string | undefined,\n mpu: number,\n presentationTime: bigint,\n mediaTimescale: number,\n ): void;\n\n /** Refresh the block inactivity deadline after accepted repair progress. */\n noteBlockActivity?(sbn: number, packetId: number, catalogTrackName?: string): void;\n\n /** Cancel block timeout (block completed via clean or FEC recovery). */\n cancelBlockTimeout(sbn: number, packetId?: number, catalogTrackName?: string): void;\n\n /** Check if a block is already completed (clean or recovered). */\n isBlockCompleted(sbn: number, packetId?: number, catalogTrackName?: string): boolean;\n\n /** Mark a block as completed externally (after routing recovered data). */\n markBlockCompleted(sbn: number, packetId?: number, catalogTrackName?: string): void;\n\n /** Increment blocksRecovered stat (called after routing recovery). */\n countRecovery(packetId?: number, sbn?: number, catalogTrackName?: string): void;\n\n /**\n * The configured catalog `fec.blockProfile` of a packetId, or undefined\n * while it is unconfigured. Required: a Source or Repair FEC Payload ID is\n * read under exactly one profile, and the router never guesses it.\n */\n blockProfileForPacket(packetId: number): FecBlockProfile | undefined;\n /** iso-ssbg1-v1: whether a protected packet fits one ssbg_mode1 symbol. */\n isoSourceFits?(packetId: number, packetLength: number): boolean;\n /** iso-ssbg1-v1: locate a source in a block a repair already stated. */\n locateIsoSource?(\n packetId: number,\n catalogTrackName: string | undefined,\n ssId: number,\n ): { sbn: number; esi: number } | null;\n /** iso-ssbg1-v1: hold a first-arrival source until a repair states its block. */\n holdIsoSource?(\n packetId: number,\n catalogTrackName: string | undefined,\n ssId: number,\n source: IsoHeldSource,\n ): boolean;\n /** iso-ssbg1-v1: state a repair's block and hand back the held sources it places. */\n placeIsoRepair?(\n packetId: number,\n catalogTrackName: string | undefined,\n ssStart: number,\n ssbLength: number,\n ): IsoRepairPlacement<IsoHeldSource>;\n /** iso-ssbg1-v1: resolution of the SS_IDs strictly between two released frames. */\n isoSpanResolution?(\n packetId: number,\n catalogTrackName: string | undefined,\n fromSsId: number,\n toSsId: number,\n ): readonly number[] | null;\n\n /** FEC source symbol count K per block. */\n readonly k: number;\n kForPacket?(packetId: number): number;\n\n /**\n * The longest a block stays open after its last symbol (inactivity fail\n * bound plus D-28 repair grace). With interleaveDepthMsForPacket it bounds\n * how long the router keeps a stream's duplicate ledgers.\n */\n blockLifetimeMsForPacket?(packetId: number): number;\n\n /** FEC symbol size T in bytes (0 = unknown / no FEC). */\n readonly symbolSize: number;\n symbolSizeForPacket?(packetId: number): number;\n\n /** Update framerate \u2014 used to refine FEC block timeout. */\n setFramerate(fps: number): void;\n\n /** Per-block state snapshot for FecBlockGrid visualization. */\n getBlockStates(): Array<{\n sbn: number;\n packetId?: number;\n state: \"collecting\" | \"complete\" | \"failed\";\n sourceCount: number;\n k: number;\n progress: number;\n }>;\n\n /** FEC statistics snapshot. */\n readonly fecStats: {\n sourcePackets: number;\n repairPackets: number;\n blocksClean: number;\n blocksRecovered: number;\n blocksFailed: number;\n };\n\n // \u2500\u2500 Event hooks (set by MmtpRouter in constructor) \u2500\u2500\n\n /** Called when a block receives its first source symbol. */\n onBlockStarted:\n | ((sbn: number, packetId: number, catalogTrackName?: string) => void)\n | null;\n\n /** Called when a block completes cleanly (all K sources arrived). */\n onBlockComplete:\n | ((sbn: number, packetId: number, catalogTrackName?: string) => void)\n | null;\n\n /** Called when a block times out (unrecoverable), with its class. */\n onBlockFailed:\n | ((\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n ) => void)\n | null;\n\n /** Called when a block reaches any terminal state. */\n onBlockResolved?:\n | ((sbn: number, packetId: number, catalogTrackName: string | undefined) => void)\n | null;\n\n /** Called when a stream's FEC source restarted (SBN discontinuity). */\n onSourceDiscontinuity?:\n | ((packetId: number, catalogTrackName: string | undefined) => void)\n | null;\n\n /** Dispose timers and state. */\n dispose(): void;\n}\n\n// \u2500\u2500\u2500 MmtpRouter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 ManifestIdentityResolutionInput {\n packetId: number;\n sbn: number;\n esi: number;\n /**\n * The packet's SS_ID and its MPU's mpu_sequence_number. Under\n * iso-ssbg1-v1 blocks vary in length, so a packet's media group comes from\n * its own MPU header, never from SBN arithmetic (BLO-35597 D2a).\n */\n ssId?: number;\n mpuSequenceNumber?: number;\n catalogTrackName?: string;\n recovered: boolean;\n sourceSymbolFormat: \"full-mmtp-packet\" | \"fec-padded-recovery\";\n}\n\nexport type ManifestIdentityResolver = (\n input: ManifestIdentityResolutionInput,\n) => ManifestObjectIdentity | null;\n\n/**\n * Classification evidence carried by one first-arrival network source\n * packet: the MMTP header R bit and the MPU / data-unit identity it states\n * (movie fragment, sample, DU offset). `idx` is the 0-based sample position\n * (`sample_number` is 1-based). The packet_sequence_number rides along for\n * FECManager's forward-jump bound.\n */\nfunction sourceSymbolEvidence(\n packet: Uint8Array,\n header: MMTPHeader,\n rapFlag: boolean,\n packetSequenceNumber: number,\n): SourceSymbolEvidence {\n const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);\n return {\n rap: rapFlag,\n packetSequenceNumber,\n ...(identity === null ? {} : { mpu: identity.mpuSequenceNumber }),\n ...(identity?.sampleNumber !== undefined && identity.sampleNumber >= 1\n ? { idx: identity.sampleNumber - 1 }\n : {}),\n ...(identity?.movieFragmentSequenceNumber !== undefined\n ? { movieFragment: identity.movieFragmentSequenceNumber }\n : {}),\n ...(identity?.offset !== undefined ? { offset: identity.offset } : {}),\n };\n}\n\nexport class MmtpRouter {\n readonly #parser: MmtpContainerParser;\n // Source AND FEC-recovered MFU fragments share ONE reassembler \u2014 the parser's\n // (see #parser.reassembler). A keyframe split between source-received and\n // FEC-recovered fragments must reassemble in a single buffer (BLO-8151).\n readonly #fecManager: FECManagerLike | null;\n #defaultFecMapper: FecBlockMapper | null;\n #fecMappersByPacketId = new Map<number, FecBlockMapper>();\n readonly #manifestVerifier: ManifestVerifier | null;\n readonly #ownsManifestVerifier: boolean;\n readonly #resolveManifestIdentity:\n | ((\n packetId: number,\n sbn: number,\n esi: number,\n catalogTrackName?: string,\n ) => ManifestObjectIdentity | null)\n | null;\n readonly #resolveManifestIdentityForRoute: ManifestIdentityResolver | null;\n #manifestRecoveryQueues = new Map<\n string,\n Array<{\n blockId: number;\n result: ProcessFecBlockResult;\n ownerPacketId: number;\n catalogTrackName?: string;\n }>\n >();\n\n // Temp state set by #processMMTP before calling parser.feed(),\n // read by the parser's onFrame callback for CMAF assembly + dedup.\n #currentFecInfo:\n | { sbn: number; esi: number; oversized?: boolean }\n | undefined;\n #currentSeqNum = 0;\n\n // Track type registry: which packetIds are video vs audio (from catalog)\n #videoPacketIds = new Set<number>();\n #audioPacketIds = new Set<number>();\n #catalogTrackNamesByPacketId = new Map<number, Set<string>>();\n\n // Per-track codec string for keyframe detection (e.g. 'avc1.42001e', 'av01.0.04M.08')\n #trackCodecs = new Map<number, string>();\n\n // Per-track frame callbacks keyed by packetId \u2014 used for ABR / multi-track routing\n #trackCallbacks = new Map<\n number,\n FrameCallback\n >();\n #trackPacketCallbacks = new Map<number, TrackPacketCallback>();\n // Cached resolved callbacks: per-track + legacy composite per packetId.\n // Invalidated when any callback is registered (onTrackFrame, onVideoFrame, onAudioFrame).\n #resolvedCallbacks = new Map<number, FrameCallback>();\n\n // Per-ingress-stream sync flag: suppress direct frame emission until the first complete\n // FEC block confirms we've joined mid-stream cleanly. Prevents corrupt partial\n // frames from reaching the decoder on multicast mid-stream join. Catalog\n // identity keeps renditions that reuse a packet ID from opening each other's gate.\n #trackSynced = new Set<string>();\n #droppedPreSyncVideo = new Set<string>();\n\n // One entry per physical stream (packetId, catalog track name): its stable\n // JSON key and its per-packet duplicate ledgers. The ledgers used to be\n // three router-wide Sets of \"<streamKey>:<coordinates>\" strings, so every\n // packet built and hashed up to three strings, and resetTrack() scanned\n // every retained key by prefix (BLO-36599). They now hold the wire numbers\n // themselves, and a reset clears one stream's Sets.\n #streams = new Map<number, Map<string | undefined, StreamLedgers>>();\n\n // Live WebCodecs callbacks cannot accept late recovered inter-frame video.\n // MSE recovery routes through CmafBlockAssembler and can reorder by block; the\n // direct callback path has to preserve decode order before frames leave libmmt.\n #latestVideoSeqByStream = new Map<string, number>();\n #lastDirectSourceVideoTsByStream = new Map<string, number>();\n #lastDirectEmittedVideoTsByStream = new Map<string, number>();\n #pendingDirectRecoveredVideoByStream = new Map<string, Map<string, PendingRecoveredVideoFrame>>();\n // AudioDecoder input must remain monotonic too. A repair that completes after\n // the live source cursor passed its AAC access unit is useful for FEC\n // accounting, but injecting it into the decoder can stall PCM output.\n #lastDirectSourceAudioCursorByStream = new Map<string, DirectAudioCursor>();\n #lastDirectEmittedAudioCursorByStream = new Map<string, DirectAudioCursor>();\n #pendingDirectRecoveredAudioByStream = new Map<string, Map<string, PendingRecoveredAudioFrame>>();\n\n // The furthest-presented video frame each stream delivered, which a staged\n // switch reads as its outgoing high water. Recorded where a frame reaches a\n // decoder callback or an MSE assembler, not on arrival: a recovered frame\n // can be queued ahead of the source cursor and discarded at the commit. A\n // max, because an MSE assembler takes a late FEC gap fill below frames\n // already delivered; an under-stated high water reports an overlapping\n // splice as exact.\n #deliveredVideoHighWaterByStream = new Map<string, StreamSwitchPosition>();\n\n // Per-track CMAF block assemblers for MSE mode. When active, frames are buffered per-SBN\n // and emitted as multi-sample CMAF segments on block completion instead of per-frame.\n #mseAssemblers = new Map<string, CmafBlockAssembler>();\n\n // Callbacks (legacy \u2014 used when per-track callbacks are not registered)\n #onVideoFrame: FrameCallback | null = null;\n #onAudioFrame: FrameCallback | null = null;\n\n // Init segment (ftyp+moov) from MMTP MPU metadata \u2014 needed for MSE SourceBuffer\n #onInitSegment: ((data: Uint8Array) => void) | null = null;\n\n // Per-track init segment callbacks keyed by packetId\n #trackInitCallbacks = new Map<number, (data: Uint8Array) => void>();\n // Track whether init has been delivered per physical stream \u2014 prevent duplicates\n #trackInitDelivered = new Set<string>();\n\n // FEC block lifecycle. A failed block is NOT a decoder instruction: the\n // stall/conceal decision rides on the first frame released after the gap.\n #onBlockStarted: ((sbn: number, packetId: number) => void) | null = null;\n /** Diagnostic subscriber for unrecoverable FEC blocks, with their class. */\n #onBlockFailed:\n | ((\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n ) => void)\n | null = null;\n /** Typed observer of every gap decision the release gate makes. */\n readonly #onFrameGap: ((decision: FrameGapDecision) => void) | null;\n // Pokes requested while a packet is being processed are deferred to its\n // end: a synchronous recovery completes its block BEFORE routing the\n // recovered frames, and releasing a held gap in between would strand them.\n #fecPokeDepth = 0;\n #pendingFecPokes = new Map<string, { packetId: number; catalogTrackName?: string }>();\n // \u2500\u2500 Phase 14: per-role packetId dispatch (D-26, D-27, D-28) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Maps packetId \u2192 TrackRole. Default: 'single' when absent (legacy path). */\n #packetIdRoles: Map<number, TrackRole> = new Map();\n /** Explicit catalog ownership for dedicated repair-track packet IDs. */\n #repairOwnersByPacketId = new Map<number, Set<number>>();\n /** Callback fired when a delta-track FEC block completes or fails. */\n #onDeltaBlockCompleteCb:\n | ((packetId: number, failed: boolean) => void)\n | null = null;\n\n // Debug counters\n #pidCounts: Record<number, number> = {};\n #repairPidCounts: Record<number, number> = {};\n #moqRepairPidCounts: Record<number, number> = {};\n #moqRepairOwnerCounts: Record<number, number> = {};\n #parserDiagnostics = new Map<string, ParserDiagnostics>();\n\n // \u2500\u2500 Keyframe loss detection state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Catalog-derived keyframe loss timeout (ms), or a reader evaluated at each arm. null = not configured (warns on video track registration; Phase-13 keyframe repair stays off). */\n #keyframeLostTimeoutMs: number | (() => number) | null;\n /** Why the last reader evaluation left the timer unarmed; null while arming. Dedups the warning. */\n #keyframeLostUnarmedReason: string | null = null;\n /** Active keyframe loss timer handle. Single timer per video track \u2014 cleared on each rapFlag and on dispose(). */\n #keyframeLostTimer: ReturnType<typeof setTimeout> | null = null;\n /** Monotonic counter incremented on each emitted video keyframe. Tracks current GOP position. */\n #lastKeyframeGroupId = 0;\n /** Callback fired when no complete keyframe is emitted within keyframeLostTimeoutMs. Argument: next expected groupId. */\n #onKeyframeLost: ((expectedGroupId: number) => void) | null = null;\n\n /**\n * Owner-held state to reset when a multicast stream's publisher restarts\n * (BLO-36599); see #processMMTP. The router has already reset its own state\n * for the stream when this runs.\n */\n #onPublisherRestart: ((packetId: number, catalogTrackName: string) => void) | null;\n #publisherRestarts = 0;\n // FEC Payload IDs left unread because their (owner) packetId had no\n // configured fec.blockProfile (see #noteUnreadableFecPayloadId).\n #fecPayloadIdsWithoutProfile = 0;\n\n /** The staged in-place stream switch, if any (stageStreamSwitch). */\n #staged: StreamSwitchState | null = null;\n\n #disposed = false;\n\n constructor(config?: {\n fecManager?: FECManagerLike;\n fecMapper?: FecBlockMapper;\n /** MFU reassembly timeout (ms) for FEC recovery path. Derive from FEC interleaveDepthMs. */\n mfuTimeoutMs?: number;\n reassemblyPolicy?: MfuReassemblyPolicy;\n reassembler?: MfuReassemblerBackend;\n maxBufferedMfus?: number;\n /** Catalog-derived keyframe loss timeout (ms). Derive from explicit\n * keyframe/group duration; do not use FEC sourceSymbols as GOP length.\n * Pass a reader when its inputs are measured later; see\n * setKeyframeLostTimeoutMs. */\n keyframeLostTimeoutMs?: number | (() => number);\n manifestVerifier?: ManifestVerifier;\n /** Existing behavior is router ownership; shared browser plans opt into caller ownership. */\n manifestVerifierOwnership?: \"caller\" | \"router\";\n resolveManifestIdentity?: (\n packetId: number,\n sbn: number,\n esi: number,\n catalogTrackName?: string,\n ) => ManifestObjectIdentity | null;\n resolveManifestIdentityForRoute?: ManifestIdentityResolver;\n /** Internal terminal-failure sink owned by the composing transport. */\n onBlockFailed?: (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n ) => void;\n /** Internal gap-decision sink owned by the composing transport. */\n onFrameGap?: (decision: FrameGapDecision) => void;\n /**\n * Called when a multicast stream's publisher restarted its wire counters,\n * after the router reset its own state for the stream, so the composing\n * transport can reset what it holds (FEC blocks, repair I/O) before the\n * packet that revealed the restart is processed.\n */\n onPublisherRestart?: (packetId: number, catalogTrackName: string) => void;\n }) {\n this.#onPublisherRestart = config?.onPublisherRestart ?? null;\n this.#keyframeLostTimeoutMs = config?.keyframeLostTimeoutMs ?? null;\n this.#fecManager = config?.fecManager ?? null;\n this.#onFrameGap = config?.onFrameGap ?? null;\n this.#defaultFecMapper = config?.fecMapper ?? null;\n this.#manifestVerifier = config?.manifestVerifier ?? null;\n this.#ownsManifestVerifier = config?.manifestVerifierOwnership !== \"caller\";\n this.#resolveManifestIdentity = config?.resolveManifestIdentity ?? null;\n this.#resolveManifestIdentityForRoute = config?.resolveManifestIdentityForRoute ?? null;\n\n // Create MMTP parser \u2014 handles MFU extraction, reassembly, keyframe detection.\n // Its MFUReassembler is the single reassembler for BOTH the source path\n // (parser.feed) and the FEC-recovery path (#routeRecoveredBlock), so a frame\n // split across both completes (BLO-8151). mfuTimeoutMs threads the\n // catalog-derived timeout through.\n this.#parser = new MmtpContainerParser({\n mfuTimeoutMs: config?.mfuTimeoutMs,\n reassemblyPolicy: config?.reassemblyPolicy,\n reassembler: config?.reassembler,\n maxBufferedMfus: config?.maxBufferedMfus,\n ...(this.#fecManager ? { fecReleaseGate: this.#createFecReleaseGate() } : {}),\n });\n\n // Wire parser init callback \u2192 router's init delivery (dedup).\n this.#parser.onInit((data, packetId, catalogTrackName) => {\n this.#diagFor(packetId, catalogTrackName).initSegments++;\n this.#deliverInit(packetId, data, catalogTrackName);\n });\n\n // Wire parser frame callback \u2192 router's callback routing + CMAF assembly.\n this.#parser.onFrame((data, meta) => this.#routeParsedFrame(data, meta));\n\n // Wire up FECManager block lifecycle events.\n // NOTE: Recovery routing is handled from feedSourceSymbol/feedRepairSymbol\n // return values in #processMMTP \u2014 no onBlockRecovered event needed.\n this.#wireFecLifecycle(config?.onBlockFailed);\n }\n\n /**\n * Deliver one parser frame: MSE assembly, sync gating, and callback\n * routing. Reads #currentFecInfo, the FEC coordinates of the packet the\n * frame completed on.\n */\n #deliverParsedFrame(data: Uint8Array, meta: ParserFrameMeta): void {\n const packetId = meta.packetId;\n const diag = this.#diagFor(packetId, meta.catalogTrackName);\n diag.frames++;\n diag.lastFrameTimestamp = meta.timestamp;\n const isVideo = this.#classifyPacketId(packetId) === true;\n const frameMeta: RoutedFrameMeta = {\n timestamp: meta.timestamp,\n ...(meta.mmtpTimestamp === undefined\n ? {}\n : { mmtpTimestamp: meta.mmtpTimestamp }),\n keyframe: isVideo ? meta.keyframe : true,\n packetId,\n packetSequenceNumber: meta.packetSequenceNumber ?? this.#currentSeqNum,\n ...(meta.authoredTiming === undefined\n ? {}\n : { authoredTiming: meta.authoredTiming }),\n ...(meta.packetSequenceNumbers === undefined\n ? {}\n : { packetSequenceNumbers: meta.packetSequenceNumbers }),\n ...(meta.repairedPacketSequenceNumbers === undefined\n ? {}\n : { repairedPacketSequenceNumbers: meta.repairedPacketSequenceNumbers }),\n ...(meta.mpuSequenceNumber === undefined\n ? {}\n : { mpuSequenceNumber: meta.mpuSequenceNumber }),\n ...(meta.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: meta.movieFragmentSequenceNumber }),\n ...(meta.sampleNumber === undefined\n ? {}\n : { sampleNumber: meta.sampleNumber }),\n ...(meta.catalogTrackName === undefined\n ? {}\n : { catalogTrackName: meta.catalogTrackName }),\n };\n if (meta.source) frameMeta.source = meta.source;\n // Forward whenever present, not when truthy: 'unknown' is a verdict the\n // parser reached, not a value to drop.\n if (meta.deliveryProvenance !== undefined)\n frameMeta.deliveryProvenance = meta.deliveryProvenance;\n if (meta.recovered) frameMeta.recovered = true;\n if (meta.gapBefore) frameMeta.gapBefore = meta.gapBefore;\n const sourceDiscontinuity = this.#opensFecSync(\n packetId,\n frameMeta.keyframe,\n frameMeta.catalogTrackName,\n );\n\n // Route to MSE assembler if active for this track.\n const assembler = this.#mseAssemblerFor(packetId, frameMeta.catalogTrackName);\n if (assembler && frameMeta.recovered) {\n // An FEC-recovered frame released in order by the FEC release gate.\n assembler.addRecoveredBlock(meta.fecSbn ?? -1, [{\n data,\n timestamp: frameMeta.timestamp,\n keyframe: frameMeta.keyframe,\n ...(frameMeta.mmtpTimestamp === undefined ? {} : { mmtpTimestamp: frameMeta.mmtpTimestamp }),\n ...(frameMeta.authoredTiming === undefined ? {} : { authoredTiming: frameMeta.authoredTiming }),\n ...(frameMeta.packetSequenceNumber === undefined\n ? {}\n : { packetSequenceNumber: frameMeta.packetSequenceNumber }),\n ...(frameMeta.packetSequenceNumbers === undefined\n ? {}\n : { packetSequenceNumbers: frameMeta.packetSequenceNumbers }),\n ...(frameMeta.repairedPacketSequenceNumbers === undefined\n ? {}\n : { repairedPacketSequenceNumbers: frameMeta.repairedPacketSequenceNumbers }),\n ...(frameMeta.mpuSequenceNumber === undefined ? {} : { mpuSequenceNumber: frameMeta.mpuSequenceNumber }),\n ...(frameMeta.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: frameMeta.movieFragmentSequenceNumber }),\n ...(frameMeta.sampleNumber === undefined ? {} : { sampleNumber: frameMeta.sampleNumber }),\n ...(frameMeta.catalogTrackName === undefined ? {} : { catalogTrackName: frameMeta.catalogTrackName }),\n ...(frameMeta.deliveryProvenance === undefined\n ? {}\n : { deliveryProvenance: frameMeta.deliveryProvenance }),\n ...(frameMeta.gapBefore === undefined ? {} : { gapBefore: frameMeta.gapBefore }),\n }]);\n } else if (assembler) {\n const fecInfo = this.#currentFecInfo;\n if (fecInfo && !fecInfo.oversized) {\n assembler.addFrame(\n fecInfo.sbn,\n fecInfo.esi,\n data,\n frameMeta.timestamp,\n frameMeta.keyframe,\n frameMeta.catalogTrackName,\n frameMeta.mpuSequenceNumber,\n frameMeta.packetSequenceNumber,\n frameMeta.packetSequenceNumbers,\n frameMeta.repairedPacketSequenceNumbers,\n frameMeta.authoredTiming,\n frameMeta.deliveryProvenance,\n frameMeta.mmtpTimestamp,\n frameMeta.movieFragmentSequenceNumber,\n frameMeta.sampleNumber,\n frameMeta.gapBefore,\n );\n } else {\n assembler.addBypassFrame(\n data,\n frameMeta.timestamp,\n frameMeta.keyframe,\n frameMeta.catalogTrackName,\n frameMeta.mpuSequenceNumber,\n frameMeta.packetSequenceNumber,\n frameMeta.packetSequenceNumbers,\n frameMeta.repairedPacketSequenceNumbers,\n frameMeta.authoredTiming,\n frameMeta.deliveryProvenance,\n frameMeta.mmtpTimestamp,\n frameMeta.movieFragmentSequenceNumber,\n frameMeta.sampleNumber,\n frameMeta.gapBefore,\n );\n }\n }\n\n if (assembler && isVideo) {\n this.#noteDeliveredVideo(this.#mediaStreamKey(packetId, frameMeta.catalogTrackName), frameMeta);\n }\n\n if (!this.#shouldEmitFrame(\n packetId,\n frameMeta.keyframe,\n frameMeta.catalogTrackName,\n )) return;\n if (sourceDiscontinuity) frameMeta.sourceDiscontinuity = true;\n\n this.#noteEmittedKeyframe(packetId, frameMeta.keyframe);\n\n // The emitted-sequence high-water mark (#noteEmittedVideoSeq) is recorded\n // at the actual emit inside #emitDirectVideo, not here \u2014 a recovered frame\n // can be queued ahead of the source cursor, so it must track real emits.\n\n // Route to per-track or legacy callback. Even when an MSE block-assembler\n // is registered, this callback still fires \u2014 downstream consumers\n // (`mc.onVideoFrame` \u2192 takeover detection, multicast frame counter,\n // `confirmVideo`/`confirmAudio`) need every reassembled frame. The\n // SourceBuffer-write side of this callback path is suppressed inside\n // `MseBackend.feedVideo`/`feedAudio` when the assembler owns the track,\n // which is configured via `MseBackend.setAssemblerOwns('video' | 'audio')`.\n // Prevents the dual-CMAF-timeline collision (BLO-3035 layer 3).\n const cb = this.#getFrameCallback(packetId);\n if (isVideo && !assembler) {\n if (frameMeta.recovered) {\n this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);\n } else {\n this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);\n }\n } else if (!isVideo && !assembler) {\n if (frameMeta.recovered) {\n this.#routeDirectRecoveredAudio(packetId, data, frameMeta, cb);\n } else {\n this.#routeDirectSourceAudio(packetId, data, frameMeta, cb);\n }\n } else {\n cb?.(data, frameMeta);\n }\n }\n\n #wireFecLifecycle(\n onBlockFailed:\n | ((\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n ) => void)\n | undefined,\n ): void {\n if (this.#fecManager) {\n this.#fecManager.onBlockStarted = (\n sbn: number,\n packetId: number,\n _catalogTrackName?: string,\n ) => {\n this.#onBlockStarted?.(sbn, packetId);\n };\n\n this.#fecManager.onBlockResolved = (\n _sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n ) => {\n this.#requestFecPoke(packetId, catalogTrackName);\n };\n this.#fecManager.onSourceDiscontinuity = (\n packetId: number,\n catalogTrackName: string | undefined,\n ) => {\n // Mark now, drain through the same deferral as every other gate\n // wake: this fires from inside FECManager.trackBlock, and a\n // synchronous drain would re-enter FECManager (noteReleasedRap) and\n // the downstream sink mid-update.\n this.#parser.markFecDiscontinuity(packetId, catalogTrackName);\n this.#requestFecPoke(packetId, catalogTrackName);\n };\n\n this.#fecManager.onBlockComplete = (\n sbn: number,\n packetId: number,\n catalogTrackName?: string,\n ) => {\n this.#mseAssemblerFor(packetId, catalogTrackName)?.completeBlock(sbn);\n // Phase 14 D-26: fan-out to delta callback when delta-role packetId completes.\n if (\n this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) &&\n this.#packetIdRoles.get(packetId) === \"delta\"\n ) {\n this.#onDeltaBlockCompleteCb?.(packetId, false); // failed=false\n }\n };\n\n this.#fecManager.onBlockFailed = (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n ) => {\n this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);\n if (\n this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) &&\n this.#packetIdRoles.get(packetId) === \"delta\"\n ) {\n this.#onDeltaBlockCompleteCb?.(packetId, true); // failed=true\n }\n onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);\n this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);\n };\n }\n }\n\n // \u2500\u2500 Accessors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 get fecManager(): FECManagerLike | null {\n return this.#fecManager;\n }\n\n /**\n * How long this router keeps a packet ID's duplicate ledgers, derived from\n * the FEC manager's geometry for it (see duplicate-ledger.ts), or why no\n * horizon is derivable (the stream then keeps count-bounded ledgers, or none\n * without an FEC manager). A stream reads this when it moves to a new FEC\n * block, so a catalog change applies from the next block.\n */\n duplicateHorizonFor(packetId: number): DuplicateHorizon {\n const fec = this.#fecManager;\n if (!fec) return NO_FEC_MANAGER_HORIZON;\n if (!fec.interleaveDepthMsForPacket || !fec.blockLifetimeMsForPacket) {\n return NO_FEC_GEOMETRY_HORIZON;\n }\n const blockSpanMs = fec.interleaveDepthMsForPacket(packetId);\n // FECManager reports 0 for a stream the catalog gave no block span.\n if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;\n return {\n kind: \"fec-horizon\",\n retentionMs: duplicateRetentionMs({\n blockSpanMs,\n blockLifetimeMs: fec.blockLifetimeMsForPacket(packetId),\n }),\n };\n }\n\n /** Publisher restarts detected on the multicast leg since construction. */\n get publisherRestartCount(): number {\n return this.#publisherRestarts;\n }\n\n /**\n * Packets whose Source or Repair FEC Payload ID was left unread because\n * their (owner) packetId had no configured `fec.blockProfile`: FEC not\n * configured yet for a track whose packets already flow, or a track whose\n * catalog FEC was unusable. Such a source packet's media is routed as on a\n * track without FEC; such a repair packet is dropped. Neither is read as a\n * block coordinate under a guessed profile, and neither touches FEC state.\n */\n get fecPayloadIdsWithoutProfile(): number {\n return this.#fecPayloadIdsWithoutProfile;\n }\n\n get reassembler(): MfuReassemblerBackend {\n return this.#parser.reassembler;\n }\n\n getDiagnostics(): Record<number, ParserDiagnostics> {\n const out: Record<number, ParserDiagnostics> = {};\n // The reassembler is shared by every stream; its occupancy is one reading\n // taken now, not a per-packet snapshot (BLO-36599).\n const status = this.#parserDiagnostics.size > 0\n ? this.#parser.reassembler.getStatus()\n : null;\n for (const [key, diag] of this.#parserDiagnostics) {\n if (status) {\n diag.pendingBuffers = status.bufferedMFUs;\n diag.pendingFragments = status.pendingFragments;\n diag.pendingSamples = status.pendingSamples;\n }\n const packetId = this.#packetIdFromStreamKey(key);\n const existing = out[packetId];\n if (!existing) {\n out[packetId] = { ...diag };\n continue;\n }\n const latest =\n diag.lastSequenceNumber >= existing.lastSequenceNumber ? diag : existing;\n out[packetId] = {\n packets: existing.packets + diag.packets,\n frames: existing.frames + diag.frames,\n initSegments: existing.initSegments + diag.initSegments,\n noFragment: existing.noFragment + diag.noFragment,\n fragments: existing.fragments + diag.fragments,\n reassembled: existing.reassembled + diag.reassembled,\n pendingBuffers: existing.pendingBuffers + diag.pendingBuffers,\n pendingFragments: existing.pendingFragments + diag.pendingFragments,\n directAudioSourceEmitted:\n existing.directAudioSourceEmitted + diag.directAudioSourceEmitted,\n directAudioSourceRegressions:\n existing.directAudioSourceRegressions + diag.directAudioSourceRegressions,\n directAudioRecoveredQueued:\n existing.directAudioRecoveredQueued + diag.directAudioRecoveredQueued,\n directAudioRecoveredDrained:\n existing.directAudioRecoveredDrained + diag.directAudioRecoveredDrained,\n directAudioRecoveredStaleDropped:\n existing.directAudioRecoveredStaleDropped + diag.directAudioRecoveredStaleDropped,\n pendingSamples: [\n ...((existing.pendingSamples as unknown[]) ?? []),\n ...((diag.pendingSamples as unknown[]) ?? []),\n ],\n lastPacketLength: latest.lastPacketLength,\n lastSequenceNumber: latest.lastSequenceNumber,\n ...(latest.lastFecSsId === undefined ? {} : { lastFecSsId: latest.lastFecSsId }),\n ...(latest.lastFrameTimestamp === undefined\n ? {}\n : { lastFrameTimestamp: latest.lastFrameTimestamp }),\n };\n }\n return out;\n }\n\n // \u2500\u2500 Track configuration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Register callback for keyframe loss detection.\n * Fires when no complete keyframe is emitted within keyframeLostTimeoutMs.\n * Argument: next expected groupId (lastKeyframeGroupId + 1). */\n onKeyframeLost(cb: (expectedGroupId: number) => void): void {\n this.#onKeyframeLost = cb;\n }\n\n /**\n * Set the keyframe loss timeout after construction.\n * Must be called BEFORE setPacketIdType('video').\n * A fixed timeout derives from explicit keyframe/group duration:\n * Math.ceil(groupDurationMs * KEYFRAME_LOST_TIMEOUT_SLACK).\n * A timeout whose inputs are measured after configuration (e.g. keyframe\n * cadence plus measured playout lateness) is passed as a reader, evaluated\n * each time the timer is armed. Both forms pass the same check at each arm:\n * a throw, or a value that is not finite, positive and within the timer\n * maximum, leaves that keyframe unarmed (fail closed per keyframe, not per\n * session). A fixed NaN, e.g. derived from a catalog without a group\n * duration, therefore never reaches setTimeout.\n */\n setKeyframeLostTimeoutMs(ms: number | (() => number)): void {\n this.#keyframeLostTimeoutMs = ms;\n this.#keyframeLostUnarmedReason = null;\n }\n\n /** Update MFU reassembly timeout. Source and FEC-recovery paths share the\n * parser's single reassembler (BLO-8151), so one update covers both. */\n setMfuTimeoutMs(ms: number): void {\n if (ms <= 0) throw new Error(\"[MmtpRouter] mfuTimeoutMs must be > 0\");\n this.#parser.setMfuTimeoutMs(ms);\n }\n\n /** Update parser frame reordering for unordered multicast delivery.\n * Callers derive this from the catalog FEC block span (\u00A75.1 \u2014 the\n * interleave value IS the span): positive round-half-up of span / frameMs. */\n setReorderWindow(windowSize: number): void {\n this.#parser.setReorderWindow(windowSize);\n }\n\n /** Register MMTP packetId \u2192 track type mapping.\n * Call BEFORE packets arrive to ensure correct routing from the first packet.\n * If keyframeLostTimeoutMs is not provided, Phase 13 keyframe repair is\n * disabled (video still routes/decodes normally). framerate is OPTIONAL per\n * draft-ietf-moq-catalogformat-01 \u00A73.2.23, so we can't require the timeout. */\n setPacketIdType(packetId: number, trackType: \"video\" | \"audio\"): void {\n if (trackType === \"video\" && this.#keyframeLostTimeoutMs === null) {\n console.warn(\n \"[MmtpRouter] keyframeLostTimeoutMs not configured \u2014 Phase 13 keyframe \" +\n \"repair disabled for this track. Set it via setKeyframeLostTimeoutMs() \" +\n \"or provide in constructor config to enable: \" +\n \"Math.ceil(groupDurationMs * KEYFRAME_LOST_TIMEOUT_SLACK).\",\n );\n }\n if (trackType === \"video\") this.#videoPacketIds.add(packetId);\n else this.#audioPacketIds.add(packetId);\n // Sync track info to parser for codec-aware keyframe detection.\n const codec = this.#trackCodecs.get(packetId) ?? \"\";\n this.#parser.setTrack(packetId, { type: trackType, codec });\n }\n\n /** Media kind registered for a packetId, if any. */\n trackKindFor(packetId: number): \"video\" | \"audio\" | undefined {\n const classification = this.#classifyPacketId(packetId);\n return classification === null ? undefined : classification ? \"video\" : \"audio\";\n }\n\n /** Register codec string for a packetId \u2014 enables codec-aware keyframe detection.\n * Without this, only H.264 IDR (NAL type 5) is detected as keyframe fallback.\n * AV1 (OBU_SEQUENCE_HEADER) and VP9 (frame_type bit) require the codec string. */\n setTrackCodec(packetId: number, codec: string): void {\n this.#trackCodecs.set(packetId, codec);\n // Sync to parser. Determine track type from existing registration.\n const trackType = this.#videoPacketIds.has(packetId)\n ? (\"video\" as const)\n : this.#audioPacketIds.has(packetId)\n ? (\"audio\" as const)\n : null;\n if (trackType) {\n this.#parser.setTrack(packetId, { type: trackType, codec });\n }\n }\n\n // \u2500\u2500 Frame callbacks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** @deprecated Use onTrackFrame(packetId, cb) for per-track routing */\n onVideoFrame(cb: FrameCallback): void {\n this.#onVideoFrame = cb;\n this.#resolvedCallbacks.clear();\n }\n\n /** @deprecated Use onTrackFrame(packetId, cb) for per-track routing */\n onAudioFrame(cb: FrameCallback): void {\n this.#onAudioFrame = cb;\n this.#resolvedCallbacks.clear();\n }\n\n /** Register a frame callback for a specific MMTP packetId (track).\n * When a legacy callback (onVideoFrame/onAudioFrame) also exists for this\n * packetId's type, both fire: per-track first, then legacy. This ensures\n * element.ts wiring (confirmAudio, feedMulticast) continues working when\n * TrackPipeline registers per-track sources. */\n onTrackFrame(\n packetId: number,\n cb: FrameCallback,\n ): void {\n this.#trackCallbacks.set(packetId, cb);\n this.#resolvedCallbacks.clear();\n }\n\n /** Register a raw MMTP source-packet callback for one track.\n *\n * Direct packets retain their original bytes, including a Source FEC Payload\n * ID when present. FEC-recovered packets are the recovered source-symbol\n * bytes and set `skipFecPayloadId` because that trailer is not part of the\n * protected symbol. Repair packets are never delivered here.\n */\n onTrackPacket(packetId: number, cb: TrackPacketCallback): void {\n this.#trackPacketCallbacks.set(packetId, cb);\n }\n\n /** Register an init segment callback (ftyp+moov from MMTP MPU metadata). */\n onInitSegment(cb: (data: Uint8Array) => void): void {\n this.#onInitSegment = cb;\n }\n\n /** Register an init segment callback for a specific MMTP packetId.\n * Called when FT=0 init arrives via direct source or FEC recovery. */\n onTrackInit(packetId: number, cb: (data: Uint8Array) => void): void {\n this.#trackInitCallbacks.set(packetId, cb);\n }\n\n // \u2500\u2500 MSE integration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** Create a CMAF block assembler for MSE mode on a specific track.\n * When active, source frames are buffered per FEC block and emitted as\n * multi-sample CMAF segments instead of per-frame callbacks. */\n enableMseAssembler(\n packetId: number,\n config: Omit<BlockAssemblerConfig, \"k\">,\n catalogTrackName?: string,\n ): CmafBlockAssembler {\n const k = this.#kForPacket(packetId);\n const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);\n const previous = this.#mseAssemblers.get(assemblerKey);\n if (previous) {\n previous.flush();\n previous.dispose();\n }\n const assembler = new CmafBlockAssembler({ ...config, k });\n this.#mseAssemblers.set(assemblerKey, assembler);\n console.log(\n `[MmtpRouter] MSE assembler enabled for packetId=${packetId}${catalogTrackName === undefined ? \"\" : ` track=${catalogTrackName}`} (K=${k}, ${config.trackType})`,\n );\n return assembler;\n }\n\n /** Register a segment callback for a track's MSE assembler.\n * Called with complete moof+mdat CMAF segments on block completion. */\n onMseSegment(packetId: number, cb: (segment: Uint8Array) => void, catalogTrackName?: string): void {\n const assembler = this.#mseAssemblers.get(this.#mseAssemblerKey(packetId, catalogTrackName));\n if (assembler) assembler.onSegment = cb;\n }\n\n /** Register a raw-sample callback for a track's MSE assembler.\n * Use this when the caller already owns the fMP4/MSE timeline and only wants\n * FEC recovery, keyframe gating, and dedup from the assembler. */\n onMseSample(packetId: number, cb: (sample: CmafBlockSample) => void, catalogTrackName?: string): void {\n const assembler = this.#mseAssemblers.get(this.#mseAssemblerKey(packetId, catalogTrackName));\n if (assembler) assembler.onSample = cb;\n }\n\n /** Register an init segment callback for a track's MSE assembler. */\n onMseInitSegment(packetId: number, cb: (init: Uint8Array) => void, catalogTrackName?: string): void {\n const assembler = this.#mseAssemblers.get(this.#mseAssemblerKey(packetId, catalogTrackName));\n if (assembler) assembler.onInitSegment = cb;\n }\n\n /** Build and emit init segment for a track's MSE assembler from catalog config. */\n emitMseInit(packetId: number, catalogTrackName?: string): void {\n this.#mseAssemblers.get(this.#mseAssemblerKey(packetId, catalogTrackName))?.emitInit();\n }\n\n /** Mark a video track as synchronized by an external path.\n * This opens the MMTP/FEC pre-sync gates without waiting for a multicast\n * keyframe, for MSE timelines already seeded by MoQ with the same track. */\n markExternalVideoSync(packetId?: number, catalogTrackName?: string): void {\n const packetIds =\n packetId === undefined\n ? [...this.#videoPacketIds]\n : this.#videoPacketIds.has(packetId)\n ? [packetId]\n : [];\n for (const id of packetIds) {\n const streamKey = this.#mediaStreamKey(id, catalogTrackName);\n this.#trackSynced.add(streamKey);\n this.#droppedPreSyncVideo.delete(streamKey);\n this.#mseAssemblerFor(id, catalogTrackName)?.markVideoSynced();\n }\n }\n\n // \u2500\u2500 FEC event handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Register callback for FEC blocks when the first source symbol arrives. */\n onFecBlockStarted(cb: (sbn: number, packetId: number) => void): void {\n this.#onBlockStarted = cb;\n }\n\n /** Register a diagnostic callback for FEC blocks that fail. A failure is\n * not a decoder instruction: act on `RoutedFrameMeta.gapBefore`. */\n onFecBlockFailed(\n cb: (\n sbn: number,\n packetId: number,\n catalogTrackName: string | undefined,\n blockClass: BlockClass,\n ) => void,\n ): void {\n this.#onBlockFailed = cb;\n }\n\n // \u2500\u2500 Phase 14: per-role packetId dispatch (D-26, D-27, D-28) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Register a TrackRole for a specific packetId.\n *\n * D-26: Enables per-role block-complete fanout \u2014 delta-role packetIds fire\n * onDeltaBlockComplete when their FEC block completes or fails.\n * Composite callback preserved: legacy onVideoFrame/onAudioFrame still fire\n * (MEMORY.md \"prevents callback stealing\").\n *\n * Valid roles: 'base' | 'delta' | 'repair' | 'single'.\n * Throws on unknown role (error on bad init, CLAUDE.md).\n */\n setPacketIdRole(packetId: number, role: TrackRole): void {\n const VALID_ROLES: readonly TrackRole[] = [\n \"base\",\n \"delta\",\n \"repair\",\n \"single\",\n ];\n if (!VALID_ROLES.includes(role)) {\n throw new Error(\n `[MmtpRouter] setPacketIdRole: unknown role '${role}'. Valid: ${VALID_ROLES.join(\", \")}`,\n );\n }\n this.#packetIdRoles.set(packetId, role);\n }\n\n /** Replace catalog-derived repair ownership before a catalog reconfiguration. */\n clearRepairPacketIdOwners(): void {\n this.#repairOwnersByPacketId.clear();\n }\n\n /** Bind one dedicated repair-track PID to its authoritative media PID. */\n setRepairPacketIdOwner(repairPacketId: number, ownerPacketId: number): void {\n const owners = this.#repairOwnersByPacketId.get(repairPacketId) ?? new Set<number>();\n owners.add(ownerPacketId);\n this.#repairOwnersByPacketId.set(repairPacketId, owners);\n }\n\n /**\n * Register callback fired when a delta-track FEC block completes or fails.\n *\n * @param cb - (packetId, failed) \u2014 packetId identifies the delta track,\n * failed=false means clean/recovered, failed=true means unrecoverable.\n *\n * Called from both onBlockComplete (failed=false) and onBlockFailed (failed=true)\n * for every packetId registered with role='delta' via setPacketIdRole().\n */\n onDeltaBlockComplete(cb: (packetId: number, failed: boolean) => void): void {\n this.#onDeltaBlockCompleteCb = cb;\n }\n\n // \u2500\u2500 Packet processing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** Update framerate \u2014 delegates to FECManager for timeout refinement. */\n setFramerate(fps: number): void {\n this.#fecManager?.setFramerate(fps);\n }\n\n /** Set FEC block mapper (created when FEC config becomes known via configureFec). */\n setFecMapper(mapper: FecBlockMapper, packetId?: number): void {\n if (packetId == null) {\n this.#defaultFecMapper = mapper;\n return;\n }\n this.#fecMappersByPacketId.set(packetId, mapper);\n }\n\n registerManifestTrack(context: ManifestTrackContext): void {\n if (!this.#manifestVerifier) throw new Error(\"manifest verifier is not configured\");\n this.#manifestVerifier.registerTrack(context);\n }\n\n feedManifestFrame(trackName: string, frame: Uint8Array): void {\n this.#manifestVerifier?.ingestManifestFrame(trackName, frame);\n }\n\n setManifestAuthMode(mode: ManifestAuthMode): void {\n this.#manifestVerifier?.setMode(mode);\n if (mode !== \"enforce\") {\n for (const queue of this.#manifestRecoveryQueues.values()) {\n for (const item of queue) {\n this.#routeProcessedFecSymbols(\n item.blockId,\n item.result,\n item.ownerPacketId,\n item.catalogTrackName,\n );\n }\n }\n this.#manifestRecoveryQueues.clear();\n }\n }\n\n /**\n * Main entry point: feed a raw MMTP packet for processing.\n *\n * Source packets are played immediately AND fed to FECManager for recovery.\n * Repair packets are fed to FECManager only (no direct playback).\n */\n /**\n * Feed one MMTP source packet.\n *\n * `source` is REQUIRED. It used to default to \"multicast\", which meant any\n * caller that forgot it silently attributed its bytes to a multicast socket\n * they may never have crossed \u2014 and that attribution is what the physical-\n * delivery evidence path is built on. Absence is not multicast; say which.\n */\n feedPacket(\n packet: Uint8Array,\n source: \"multicast\" | \"moq\",\n manifestIdentity?: ManifestObjectIdentity,\n ingress?: MmtpIngressContext,\n ): void {\n if (this.#disposed) return;\n this.#withDeferredFecPokes(() => {\n this.#processMMTP(packet, source, manifestIdentity, false, ingress);\n });\n }\n\n /**\n * Feed a reliable MoQ duplicate of a source packet that the multicast leg\n * also carries, during make-before-break overlap.\n *\n * The copy is parsed for playback (attributed to \"moq\") so a pending\n * multicast decoder can warm. For an FEC-tagged packet the router keeps a\n * per-symbol (SBN/ESI) parse ledger, so whichever of it and its multicast\n * twin arrives first is parsed and the second is not. The MFU reassembler\n * cannot be that dedup: complete (FI=0) MFUs bypass its #emitted set.\n *\n * The ledger exists only where a symbol coordinate does: a packet with no\n * FEC payload ID, or a router with no FEC manager, has none, so it and its\n * twin are BOTH parsed. On an audio track that delivers the sample twice\n * (#emitDirectSourceAudio counts the regression and still emits). The\n * intended deployment is safe because the multicast leg is FEC-protected,\n * so its media packets carry the ID; the untagged timing packets\n * (init/moof) take this path too, where a re-parse is benign. Do not feed\n * untagged media through here.\n *\n * The copy never enters FEC\n * accounting: no `feedSymbolFromSource`, `trackBlock` or\n * `feedSourceSymbol`. Block completion and the repair deadline therefore\n * follow the multicast leg alone, and a multicast erasure still starves its\n * block and requests repair. Feeding the copy through `feedPacket` instead\n * would let it close the block, hiding exactly the loss repair exists for.\n *\n * MoQ unicast fallback is not an overlap copy: it is the only source, so it\n * uses `feedPacket(packet, \"moq\")` and counts toward completion.\n */\n feedOverlapCopy(packet: Uint8Array, ingress?: MmtpIngressContext): void {\n if (this.#disposed) return;\n this.#withDeferredFecPokes(() => {\n this.#processMMTP(packet, \"moq\", undefined, false, ingress, true);\n });\n }\n\n /**\n * Feed a repair packet from MoQ (reliable QUIC) \u2014 parses MMTP repair\n * header and delegates to FECManager for FEC recovery.\n */\n feedRepairPacket(\n packet: Uint8Array,\n ownerPacketIdHint?: number,\n catalogTrackName?: string,\n ): void {\n if (this.#disposed) return;\n this.#withDeferredFecPokes(() => {\n this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);\n });\n }\n\n #feedRepairPacket(\n packet: Uint8Array,\n ownerPacketIdHint: number | undefined,\n catalogTrackName: string | undefined,\n ): void {\n // One header parse per packet, as on the multicast repair branch: mmt-fec's\n // parseRepairPacket() parsed it once more before this parse (BLO-36599).\n let header: MMTPHeader;\n try {\n header = parseMMTPHeader(packet);\n } catch {\n return;\n }\n const parsed = parseMoqRepairFrameWithHeader(packet, header);\n if (!parsed) return;\n\n // A dedicated repair track can carry a packet ID that differs from the\n // media packet ID. The subscribing track supplies the authoritative owner.\n const repairPacketId = header.packetId;\n\n const hintedOwner =\n ownerPacketIdHint != null && this.#classifyPacketId(ownerPacketIdHint) !== null\n ? ownerPacketIdHint\n : null;\n // A MoQ repair subscription owns a media track explicitly. Dedicated\n // repair PIDs must carry that hint; only same-PID repair is self-describing.\n const ownerPacketId = hintedOwner ??\n (this.#classifyPacketId(repairPacketId) !== null ? repairPacketId : null);\n if (ownerPacketId === null) {\n debugRouter(\n `[MmtpRouter] Dropping MoQ repair packet pid=${repairPacketId}: owner hint is required`,\n );\n }\n\n if (ownerPacketId != null && this.#fecManager) {\n this.#moqRepairPidCounts[repairPacketId] =\n (this.#moqRepairPidCounts[repairPacketId] || 0) + 1;\n this.#moqRepairOwnerCounts[ownerPacketId] =\n (this.#moqRepairOwnerCounts[ownerPacketId] || 0) + 1;\n const pidCount = this.#moqRepairPidCounts[repairPacketId]!;\n const ownerCount = this.#moqRepairOwnerCounts[ownerPacketId]!;\n if (pidCount <= 2 || pidCount % 500 === 0) {\n console.log(\n `[MOQ-REPAIR] pid=${repairPacketId} repairOwner=${ownerPacketId} pidCount=${pidCount} ownerCount=${ownerCount} ssbLength=${parsed.ssbLength} len=${packet.length}`,\n );\n }\n\n if (this.#configuredBlockProfile(ownerPacketId) === undefined) {\n this.#noteUnreadableFecPayloadId(ownerPacketId, \"repair\");\n return;\n }\n if (this.#isIsoPacket(ownerPacketId)) {\n this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, \"moq\");\n return;\n }\n const repairSbn = this.#deriveRepairSbn(parsed.ssStart, parsed.ssbLength, ownerPacketId);\n if (repairSbn === null) return;\n const repairEsi = this.#kForPacket(ownerPacketId) + parsed.rsId;\n\n if (\n !this.#feedFecTransportSymbol(\n ownerPacketId,\n repairSbn,\n repairEsi,\n parsed.symbolData,\n \"moq\",\n catalogTrackName,\n )\n ) return;\n\n // NOTE: Do NOT call trackBlock for repair packets (same as multicast repair path).\n const recovered = catalogTrackName === undefined\n ? this.#fecManager.feedRepairSymbol(\n ownerPacketId,\n parsed.ssStart,\n parsed.ssbLength,\n parsed.rsId,\n parsed.symbolData,\n )\n : this.#fecManager.feedRepairSymbol(\n ownerPacketId,\n parsed.ssStart,\n parsed.ssbLength,\n parsed.rsId,\n parsed.symbolData,\n catalogTrackName,\n );\n if (recovered) {\n const alreadyCompleted = catalogTrackName === undefined\n ? this.#fecManager.isBlockCompleted(repairSbn, ownerPacketId)\n : this.#fecManager.isBlockCompleted(repairSbn, ownerPacketId, catalogTrackName);\n if (catalogTrackName === undefined) {\n this.#fecManager.cancelBlockTimeout(repairSbn, ownerPacketId);\n } else {\n this.#fecManager.cancelBlockTimeout(repairSbn, ownerPacketId, catalogTrackName);\n }\n if (!alreadyCompleted) {\n this.#fecManager.countRecovery(ownerPacketId, repairSbn, catalogTrackName);\n if (catalogTrackName === undefined) {\n this.#fecManager.markBlockCompleted(repairSbn, ownerPacketId);\n } else {\n this.#fecManager.markBlockCompleted(repairSbn, ownerPacketId, catalogTrackName);\n }\n this.#routeRecoveredBlock(\n repairSbn,\n recovered,\n ownerPacketId,\n catalogTrackName,\n );\n }\n }\n }\n }\n\n // \u2500\u2500 SBN/ESI derivation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 #kForPacket(packetId?: number): number {\n // Same packet-scoped rule as #deriveSbnEsi: once the packet ID is known,\n // only its explicitly registered mapper may stand in for the FEC\n // manager's per-packet K \u2014 never the default single-track mapper.\n if (packetId != null)\n return (\n this.#fecManager?.kForPacket?.(packetId) ??\n this.#fecMappersByPacketId.get(packetId)?.k ??\n this.#fecManager?.k ??\n 4\n );\n return this.#defaultFecMapper?.k ?? this.#fecManager?.k ?? 4;\n }\n\n #symbolSizeForPacket(packetId?: number): number {\n if (packetId != null) return this.#fecManager?.symbolSizeForPacket?.(packetId) ?? this.#fecManager?.symbolSize ?? 0;\n return this.#fecManager?.symbolSize ?? 0;\n }\n\n /** Derive SBN/ESI from SS_ID using packet-scoped FEC geometry. */\n #deriveSbnEsi(ssId: number, packetId?: number): { sbn: number; esi: number } {\n // A default mapper describes legacy single-track geometry. Once a packet\n // ID is known, only its explicitly registered mapper may override the\n // FECManager's packet-scoped K. Falling back to the default video mapper\n // here maps audio source symbols with video K while repair SBNs correctly\n // use the audio SSB_length, splitting one block across two coordinates.\n const mapper = packetId == null\n ? this.#defaultFecMapper\n : this.#fecMappersByPacketId.get(packetId) ?? null;\n if (mapper) return mapper.fromSsId(ssId);\n const k = this.#kForPacket(packetId);\n return { sbn: Math.floor(ssId / k), esi: ssId % k };\n }\n\n #deriveRepairSbn(\n ssStart: number,\n ssbLength: number,\n packetId?: number,\n ): number | null {\n const k = this.#kForPacket(packetId);\n if (ssbLength <= 0 || ssbLength > k || ssStart % k !== 0) return null;\n return Math.floor(ssStart / k);\n }\n\n /**\n * The configured block profile of a packetId, or undefined while it is\n * unconfigured. With an FEC manager its per-packet configuration is the\n * only source. A router without one still recovers symbols through its\n * registered mapper, built with the catalog's explicit profile: the\n * packet's own mapper, else the default one (the #deriveSbnEsi rule).\n */\n #configuredBlockProfile(packetId: number): FecBlockProfile | undefined {\n if (this.#fecManager) return this.#fecManager.blockProfileForPacket(packetId);\n const mapper = this.#fecMappersByPacketId.get(packetId) ?? this.#defaultFecMapper;\n return mapper?.blockProfile ?? undefined;\n }\n\n /**\n * The block profile an FEC coordinate of `packetId` is read under. Throws\n * while none is configured: the two profiles carry identical wire tuples\n * with different block math, so there is no default to fall back to.\n * Packet ingress leaves such a packet's FEC Payload ID unread first\n * (#noteUnreadableFecPayloadId); a throw here is a wiring fault on a path\n * that cannot hold an unconfigured packet.\n */\n #blockProfileFor(packetId: number): FecBlockProfile {\n const profile = this.#configuredBlockProfile(packetId);\n if (profile === undefined) {\n throw new Error(\n `[MmtpRouter] packetId=${packetId} carries an FEC payload ID but has no configured ` +\n \"fec.blockProfile; configure the track's FEC from its catalog before routing its packets\",\n );\n }\n return profile;\n }\n\n #isIsoPacket(packetId: number): boolean {\n return this.#blockProfileFor(packetId) === \"iso-ssbg1-v1\";\n }\n\n /**\n * Explicit refusal to read an FEC Payload ID: its (owner) packetId has no\n * configured block profile. Ordering is the host's to guarantee (configure\n * a track's FEC before its packets are routed). Until then a source packet\n * plays as on a track without FEC and a repair packet is dropped; neither\n * is read under a guessed profile or seeds FEC state. Counted and warned.\n */\n #noteUnreadableFecPayloadId(packetId: number, kind: \"source\" | \"repair\"): void {\n this.#fecPayloadIdsWithoutProfile++;\n const count = this.#fecPayloadIdsWithoutProfile;\n if (count <= 5 || count % 500 === 0) {\n console.warn(\n `[MmtpRouter] packetId=${packetId} has no configured fec.blockProfile: ` +\n (kind === \"source\"\n ? \"its FEC payload ID is not read and its media is routed without FEC\"\n : \"dropping its repair packet\") +\n ` (${count} so far)`,\n );\n }\n }\n\n /**\n * The release-gate anchor of a recovered symbol: its block (SBN) under\n * k-padded-v1, its own SS_ID under iso-ssbg1-v1, where a frame is gated by\n * the SS_IDs between it and the last released frame.\n */\n #fecAnchorForRecovered(ownerPacketId: number | undefined, blockId: number, index: number): number {\n return ownerPacketId !== undefined && this.#isIsoPacket(ownerPacketId)\n ? serial32Add(blockId, index)\n : blockId;\n }\n\n /**\n * One iso-ssbg1-v1 repair symbol (ISO/IEC 23008-1 C.5.3). It states the\n * block `[SS_Start, SS_Start + SSB_length)`; repair ESI = SSB_length +\n * RS_ID (K' = SSB_length). The held sources it placed (and those of a\n * repair-less span in front of it) are fed as first-arrival sources, then\n * the repair, the order they had on the wire, so a loss-free block is clean\n * on its repair exactly as under k-padded-v1. A repair contradicting a known\n * block is dropped.\n */\n #handleIsoRepair(\n ownerPacketId: number,\n catalogTrackName: string | undefined,\n repair: { ssStart: number; ssbLength: number; rsId: number; symbolData: Uint8Array },\n source: \"multicast\" | \"moq\",\n ): void {\n const fec = this.#fecManager;\n if (!fec?.placeIsoRepair) {\n throw new Error(\n `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`,\n );\n }\n const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);\n if (placement.status !== \"placed\") return;\n const blockStart = placement.block.start;\n if (placement.span !== undefined) {\n this.#replayIsoSources(ownerPacketId, catalogTrackName, placement.span.block.start, placement.span.placed);\n }\n this.#replayIsoSources(ownerPacketId, catalogTrackName, blockStart, placement.placed);\n if (this.#classifyPacketId(ownerPacketId) === null) return;\n if (!this.#feedFecTransportSymbol(\n ownerPacketId,\n blockStart,\n repair.ssbLength + repair.rsId,\n repair.symbolData,\n source,\n catalogTrackName,\n )) return;\n fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);\n const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);\n const recovered = fec.feedRepairSymbol(\n ownerPacketId,\n repair.ssStart,\n repair.ssbLength,\n repair.rsId,\n repair.symbolData,\n catalogTrackName,\n );\n if (recovered && !alreadyCompleted) {\n fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);\n fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);\n fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);\n this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);\n }\n }\n\n /**\n * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as\n * a first-arrival source is fed once its block is known: transport\n * accounting, block tracking with its own classification evidence, then the\n * decoder. Their media was routed when they arrived.\n */\n #replayIsoSources(\n ownerPacketId: number,\n catalogTrackName: string | undefined,\n blockStart: number,\n placed: readonly IsoPlacedSource<IsoHeldSource>[],\n ): void {\n const fec = this.#fecManager;\n if (!fec) return;\n for (const { ssId, esi, payload } of placed) {\n if (this.#classifyPacketId(ownerPacketId) === null) return;\n if (!this.#feedFecTransportSymbol(\n ownerPacketId,\n blockStart,\n esi,\n payload.symbolData,\n payload.source,\n catalogTrackName,\n )) continue;\n if (fec.isTrackConfigured?.(ownerPacketId) !== false) {\n fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);\n this.#requestFecPoke(ownerPacketId, catalogTrackName);\n }\n if (payload.oversized) continue;\n const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);\n const recovered = fec.feedSourceSymbol(ownerPacketId, ssId, payload.symbolData, undefined, catalogTrackName);\n if (!recovered || alreadyCompleted) continue;\n fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);\n fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);\n fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);\n this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);\n }\n }\n\n #resolveRepairOwnerPacketId(\n packetId: number,\n ingress?: MmtpIngressContext,\n ): number | null {\n if (this.#classifyPacketId(packetId) !== null) return packetId;\n\n if (this.#packetIdRoles.get(packetId) !== \"repair\") {\n debugRouter(\n `[MmtpRouter] Dropping repair packet pid=${packetId}: physical PID is unregistered`,\n );\n return null;\n }\n\n const registeredOwners = this.#repairOwnersByPacketId.get(packetId) ?? new Set<number>();\n const owners = ingress === undefined\n ? [...registeredOwners]\n : [...registeredOwners].filter((ownerPacketId) =>\n ingressHasPacketId(ingress, ownerPacketId));\n if (owners.length === 1) return owners[0]!;\n\n debugRouter(\n `[MmtpRouter] Dropping repair packet pid=${packetId}: catalog owner is ${owners.length === 0 ? \"absent\" : \"ambiguous\"}`,\n );\n return null;\n }\n\n /** Route a recovered FEC block through the parser + dedup pipeline.\n * Sync WASM decoders return K fixed-width source symbols concatenated. */\n routeRecoveredBlock(\n blockId: number,\n data: Uint8Array,\n packetId: number,\n catalogTrackName?: string,\n ): void {\n this.#routeRecoveredBlock(blockId, data, packetId, catalogTrackName);\n }\n\n /** Route a single recovered source symbol through the parser + dedup pipeline.\n * Worker-backed decoders emit one padded source symbol per frame event. */\n routeRecoveredSymbol(\n blockId: number,\n data: Uint8Array,\n packetId: number,\n esi = 0,\n catalogTrackName?: string,\n ): void {\n const blockProfile = this.#blockProfileFor(packetId);\n const result = processFecSymbol(data, { ownerPacketId: packetId, index: esi, blockProfile });\n this.#routeVerifiedFecSymbols(blockId, result, packetId, catalogTrackName);\n }\n\n // \u2500\u2500 Keyframe timer cancellation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** Cancel the active keyframe loss timer.\n * Call on failbackToMoq to prevent a stale timer from firing\n * onKeyframeLost after multicast is no longer the active source. */\n cancelKeyframeLostTimer(): void {\n if (this.#keyframeLostTimer) {\n clearTimeout(this.#keyframeLostTimer);\n this.#keyframeLostTimer = null;\n }\n }\n\n // \u2500\u2500 Dispose \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Emit parser frames buffered for a finite input before teardown. */\n flush(): void {\n if (this.#disposed) return;\n this.#parser.flush();\n }\n\n /** Drop one rendition's parser/router/CMAF epoch without touching peers. */\n resetTrack(packetId: number, catalogTrackName: string): void {\n if (this.#disposed) return;\n const staged = this.#staged;\n if (staged !== null) {\n const stream = { packetId, catalogTrackName };\n // A new epoch of either side invalidates what the switch held about it.\n if (isStream(stream, staged.to)) {\n staged.droppedIncomingFrames += staged.held?.length ?? 0;\n staged.held = null;\n staged.heldInit = undefined;\n }\n }\n this.#parser.resetTrack(packetId, catalogTrackName);\n const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);\n this.#trackSynced.delete(streamKey);\n this.#droppedPreSyncVideo.delete(streamKey);\n this.#latestVideoSeqByStream.delete(streamKey);\n this.#lastDirectSourceVideoTsByStream.delete(streamKey);\n this.#lastDirectEmittedVideoTsByStream.delete(streamKey);\n this.#pendingDirectRecoveredVideoByStream.delete(streamKey);\n this.#lastDirectSourceAudioCursorByStream.delete(streamKey);\n this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);\n this.#pendingDirectRecoveredAudioByStream.delete(streamKey);\n this.#manifestRecoveryQueues.delete(streamKey);\n this.#deliveredVideoHighWaterByStream.delete(streamKey);\n this.#stream(packetId, catalogTrackName).duplicates.clear();\n const assemblersToReset = new Set<CmafBlockAssembler>();\n const exactAssembler = this.#mseAssemblers.get(streamKey);\n if (exactAssembler) assemblersToReset.add(exactAssembler);\n const selectedAssembler = this.#mseAssemblerFor(packetId, catalogTrackName);\n if (selectedAssembler) assemblersToReset.add(selectedAssembler);\n for (const assembler of assemblersToReset) assembler.reset();\n this.#trackInitDelivered.delete(streamKey);\n this.#parserDiagnostics.delete(streamKey);\n }\n\n /**\n * Retire one packet ID, drop-only: remove every registration of it (media\n * kind, codec, frame/packet/init callbacks, FEC mapper, role, repair\n * ownership) and every stream state kept for it (sync gates, emission\n * cursors, duplicate ledgers, queued recovered frames, MSE assemblers,\n * parser buffers and authored timing, MFU reassembly per catalog stream).\n * Nothing buffered is delivered, as on live dispose. A dedicated repair\n * packet ID that this packet ID alone owned loses its repair role with it.\n *\n * Afterwards the packet ID is unknown to the router: its packets and\n * frames are dropped until it is registered again. FEC state lives in the\n * FEC manager and is released there (FECManager.releasePacket).\n */\n retirePacketId(packetId: number): void {\n if (this.#disposed) return;\n if (!Number.isInteger(packetId) || packetId < 0) {\n throw new Error(`[MmtpRouter] retirePacketId: invalid packetId ${packetId}`);\n }\n const staged = this.#staged;\n if (staged !== null && (staged.from.packetId === packetId || staged.to.packetId === packetId)) {\n throw new Error(\n `[MmtpRouter] retirePacketId(${packetId}): the packet ID is in a staged stream switch; ` +\n \"cancel the switch first\",\n );\n }\n const names = new Set<string>(this.#catalogTrackNamesByPacketId.get(packetId) ?? []);\n const streams = this.#streams.get(packetId);\n for (const [name, stream] of streams ?? []) {\n if (name !== undefined) names.add(name);\n const key = stream.key;\n this.#trackSynced.delete(key);\n this.#droppedPreSyncVideo.delete(key);\n this.#latestVideoSeqByStream.delete(key);\n this.#lastDirectSourceVideoTsByStream.delete(key);\n this.#lastDirectEmittedVideoTsByStream.delete(key);\n this.#pendingDirectRecoveredVideoByStream.delete(key);\n this.#lastDirectSourceAudioCursorByStream.delete(key);\n this.#lastDirectEmittedAudioCursorByStream.delete(key);\n this.#pendingDirectRecoveredAudioByStream.delete(key);\n this.#manifestRecoveryQueues.delete(key);\n this.#trackInitDelivered.delete(key);\n this.#parserDiagnostics.delete(key);\n this.#pendingFecPokes.delete(key);\n this.#deliveredVideoHighWaterByStream.delete(key);\n const assembler = this.#mseAssemblers.get(key);\n if (assembler) {\n assembler.dispose();\n this.#mseAssemblers.delete(key);\n }\n }\n this.#streams.delete(packetId);\n\n this.#videoPacketIds.delete(packetId);\n this.#audioPacketIds.delete(packetId);\n this.#trackCodecs.delete(packetId);\n this.#trackCallbacks.delete(packetId);\n this.#trackPacketCallbacks.delete(packetId);\n this.#resolvedCallbacks.delete(packetId);\n this.#trackInitCallbacks.delete(packetId);\n this.#fecMappersByPacketId.delete(packetId);\n this.#packetIdRoles.delete(packetId);\n this.#catalogTrackNamesByPacketId.delete(packetId);\n this.#repairOwnersByPacketId.delete(packetId);\n delete this.#pidCounts[packetId];\n delete this.#repairPidCounts[packetId];\n delete this.#moqRepairPidCounts[packetId];\n delete this.#moqRepairOwnerCounts[packetId];\n for (const [repairPacketId, owners] of [...this.#repairOwnersByPacketId]) {\n if (!owners.delete(packetId) || owners.size > 0) continue;\n this.#repairOwnersByPacketId.delete(repairPacketId);\n if (this.#packetIdRoles.get(repairPacketId) === \"repair\") {\n this.#packetIdRoles.delete(repairPacketId);\n }\n delete this.#repairPidCounts[repairPacketId];\n delete this.#moqRepairPidCounts[repairPacketId];\n }\n\n this.#parser.removeTrack(packetId, names);\n }\n\n /**\n * Stage an in-place switch from one video stream to another, committed at\n * a RAP of the incoming stream without leaving the multicast group.\n *\n * Until the commit the outgoing stream (`from`) is delivered as usual and\n * the incoming stream (`to`) is not: its packets are parsed and feed FEC,\n * so its first RAP arrives FEC-protected, but none of its frames, and not\n * its init, reach any callback or MSE assembler. Incoming deltas before its\n * first RAP are dropped. When that RAP arrives:\n *\n * - if the outgoing stream already delivered a frame at or past the RAP's\n * presentation time, the switch commits on it (`outgoing-ahead`);\n * - otherwise the RAP and the incoming frames after it are held, and the\n * switch commits when the outgoing stream is about to deliver a frame at\n * or past the RAP (`outgoing-reached-rap`): that outgoing frame, and every\n * later one, is never delivered, so the splice is exact. If the incoming\n * stream reaches its next RAP first, the outgoing stream is a GOP or more\n * behind: the switch commits on the held RAP and delivers the held GOP\n * and then the newer RAP (`outgoing-overdue`), the smallest gap left once\n * the outgoing stream stops. The hold is bounded by the incoming stream's\n * own RAP cadence, so no timer is involved.\n *\n * The commit is one synchronous transition inside the frame path: the\n * outgoing stream's already-admitted frames are released (its queued FEC\n * gap fills only up to the RAP, since recovery can queue a frame ahead of\n * the source cursor; its MSE assembler's ordering queue whole, as\n * CmafBlockAssembler.flush has no bound, so on the MSE path a recovered\n * outgoing frame at or past the RAP can still be emitted), its packet ID\n * is retired\n * (retirePacketId), `onCommit` runs, and then the incoming stream's newest\n * init and its RAP are delivered, followed by any held frames. No outgoing\n * frame is delivered after the commit and no incoming frame before it. If\n * `onCommit` throws, `to` is retired too and none of it is delivered.\n *\n * Both packet IDs must be registered video streams; the commit reads RAPs.\n * Admission (the transport allow-list and ingress tracks) is the caller's:\n * MulticastManager.switchRendition drives both.\n */\n stageStreamSwitch(options: StreamSwitchOptions): StagedStreamSwitch {\n if (this.#disposed) throw new Error(\"[MmtpRouter] stageStreamSwitch on a disposed router\");\n if (this.#staged !== null) {\n throw new Error(\n \"[MmtpRouter] a stream switch is already staged; cancel it before staging another\",\n );\n }\n const { from, to, onCommit } = options;\n assertStreamIdentity(\"from\", from);\n assertStreamIdentity(\"to\", to);\n if (typeof onCommit !== \"function\") {\n throw new Error(\"[MmtpRouter] stageStreamSwitch requires an onCommit callback\");\n }\n if (from.packetId === to.packetId) {\n throw new Error(\n `[MmtpRouter] stream switch ${from.catalogTrackName} -> ${to.catalogTrackName} keeps ` +\n `packet ID ${from.packetId}: an in-place switch remaps packet IDs, so each stream needs its own`,\n );\n }\n for (const stream of [from, to]) {\n if (!this.#videoPacketIds.has(stream.packetId)) {\n throw new Error(\n `[MmtpRouter] stream switch: packet ID ${stream.packetId} (${stream.catalogTrackName}) ` +\n \"is not a registered video stream (setPacketIdType): a switch commits on a video RAP\",\n );\n }\n }\n const state: StreamSwitchState = {\n from: Object.freeze({ packetId: from.packetId, catalogTrackName: from.catalogTrackName }),\n to: Object.freeze({ packetId: to.packetId, catalogTrackName: to.catalogTrackName }),\n onCommit,\n held: null,\n heldInit: undefined,\n droppedIncomingFrames: 0,\n };\n this.#staged = state;\n return {\n cancel: () => {\n if (this.#staged !== state) return false;\n this.#staged = null;\n return true;\n },\n };\n }\n\n /**\n * Apply the staged switch to one parser frame of either side. Returns true\n * when the frame was consumed (held, dropped, or past the splice).\n */\n #interceptSwitchFrame(data: Uint8Array, meta: ParserFrameMeta): boolean {\n const state = this.#staged!;\n if (isStream(meta, state.to)) {\n if (state.held === null) {\n if (!meta.keyframe) {\n state.droppedIncomingFrames++;\n return true;\n }\n const high = this.#deliveredVideoHighWaterByStream.get(\n this.#mediaStreamKey(state.from.packetId, state.from.catalogTrackName),\n );\n if (high !== undefined && comparePresentation(high, meta) >= 0) {\n if (this.#commitStreamSwitch(state, meta, \"outgoing-ahead\")) this.#routeParsedFrame(data, meta);\n return true;\n }\n state.held = [this.#holdSwitchFrame(data, meta)];\n return true;\n }\n if (meta.keyframe) {\n // The outgoing stream never reached the held RAP, so everything it\n // delivered is before it: the held GOP is complete, overlaps nothing,\n // and dropping it would only widen the gap by a whole incoming GOP.\n const held = state.held;\n if (this.#commitStreamSwitch(state, held[0]!.meta, \"outgoing-overdue\")) {\n for (const frame of held) this.#replayHeldSwitchFrame(frame);\n this.#routeParsedFrame(data, meta);\n }\n return true;\n }\n state.held.push(this.#holdSwitchFrame(data, meta));\n return true;\n }\n if (!isStream(meta, state.from)) return false;\n const rap = state.held?.[0];\n if (rap !== undefined && comparePresentation(meta, rap.meta) >= 0) {\n const held = state.held!;\n if (this.#commitStreamSwitch(state, rap.meta, \"outgoing-reached-rap\")) {\n for (const frame of held) this.#replayHeldSwitchFrame(frame);\n }\n return true;\n }\n return false;\n }\n\n #holdSwitchFrame(data: Uint8Array, meta: ParserFrameMeta): HeldSwitchFrame {\n const fecInfo = this.#currentFecInfo;\n return {\n data,\n meta: { ...meta },\n fecInfo: fecInfo === undefined ? undefined : { ...fecInfo },\n };\n }\n\n /**\n * Replay a held incoming frame as if it completed now, under its own FEC\n * coordinates, through the same gate as a parser frame, so a switch staged\n * from inside the commit's onCommit sees it.\n */\n #replayHeldSwitchFrame(frame: HeldSwitchFrame): void {\n if (this.#disposed) return;\n const current = this.#currentFecInfo;\n this.#currentFecInfo = frame.fecInfo;\n try {\n this.#routeParsedFrame(frame.data, frame.meta);\n } finally {\n this.#currentFecInfo = current;\n }\n }\n\n /**\n * The one path from a completed frame into delivery: parser frames, held\n * frames a commit replays, and the frame that triggered a commit all pass\n * a staged switch's interception here.\n */\n #routeParsedFrame(data: Uint8Array, meta: ParserFrameMeta): void {\n // A frame of a packet ID retired while it was in flight has no route\n // left: an in-place switch commits from inside the parser's emission,\n // and the retired stream's remaining frames can still drain from the\n // same call. Nothing registers a packet ID mid-frame, so this drops\n // only frames that lost their registration.\n if (this.#classifyPacketId(meta.packetId) === null) return;\n if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;\n this.#deliverParsedFrame(data, meta);\n }\n\n #commitStreamSwitch(\n state: StreamSwitchState,\n rap: ParserFrameMeta,\n reason: StreamSwitchCommitReason,\n ): boolean {\n this.#staged = null;\n // Release the outgoing stream's queued FEC gap fills that precede the\n // splice before the packet ID is retired, which discards everything else.\n // The queue can hold recovered frames ahead of the source cursor, so it is\n // bounded at the RAP by the same comparison that decides the commit: a\n // queued outgoing frame at or past the RAP is never delivered.\n const outgoingKey = this.#mediaStreamKey(state.from.packetId, state.from.catalogTrackName);\n this.#drainDirectRecoveredVideo(\n outgoingKey,\n state.from.packetId,\n frame => comparePresentation(frame, rap) < 0,\n this.#getFrameCallback(state.from.packetId),\n );\n this.#mseAssemblerFor(state.from.packetId, state.from.catalogTrackName)?.flush();\n const outgoingHighWater = this.#deliveredVideoHighWaterByStream.get(outgoingKey);\n this.retirePacketId(state.from.packetId);\n const commit: StreamSwitchCommit = Object.freeze({\n from: state.from,\n to: state.to,\n rap: Object.freeze({\n ...switchPosition(rap),\n ...(rap.mpuSequenceNumber === undefined ? {} : { mpuSequenceNumber: rap.mpuSequenceNumber }),\n }),\n outgoingHighWater,\n reason,\n droppedIncomingFrames: state.droppedIncomingFrames,\n });\n try {\n state.onCommit(commit);\n } catch (error) {\n // The caller could not take the incoming stream (typically a decoder\n // reconfiguration that threw). `from` is already retired, so there is\n // nothing to fall back to, and delivering `to` would feed a decoder\n // still configured for `from`. Fail closed: retire `to` too, so neither\n // its init nor its held GOP nor anything after reaches a callback.\n console.warn(\"[MmtpRouter] stream switch commit callback failed; retiring the incoming stream\", error);\n if (this.#disposed) return false;\n // onCommit may have staged a new switch; one on `to` cannot outlive it\n // (retirePacketId refuses a staged packet ID).\n const restaged = this.#staged as StreamSwitchState | null;\n if (restaged !== null && (restaged.from.packetId === state.to.packetId || restaged.to.packetId === state.to.packetId)) {\n this.#staged = null;\n }\n this.retirePacketId(state.to.packetId);\n return false;\n }\n if (this.#disposed) return false;\n const init = state.heldInit;\n if (init !== undefined) this.#deliverInit(state.to.packetId, init, state.to.catalogTrackName);\n return true;\n }\n\n /** Live teardown is drop-only. Finite inputs must opt into a final flush. */\n dispose(options: { flush?: boolean } = {}): void {\n if (options.flush) this.flush();\n this.#disposed = true;\n this.#staged = null;\n this.cancelKeyframeLostTimer();\n this.#parser.dispose();\n this.#streams.clear();\n this.#trackPacketCallbacks.clear();\n this.#latestVideoSeqByStream.clear();\n this.#lastDirectSourceVideoTsByStream.clear();\n this.#lastDirectEmittedVideoTsByStream.clear();\n this.#pendingDirectRecoveredVideoByStream.clear();\n this.#lastDirectSourceAudioCursorByStream.clear();\n this.#lastDirectEmittedAudioCursorByStream.clear();\n this.#pendingDirectRecoveredAudioByStream.clear();\n this.#trackSynced.clear();\n this.#droppedPreSyncVideo.clear();\n this.#trackInitDelivered.clear();\n this.#deliveredVideoHighWaterByStream.clear();\n this.#repairPidCounts = {};\n this.#moqRepairPidCounts = {};\n this.#moqRepairOwnerCounts = {};\n this.#parserDiagnostics.clear();\n this.#catalogTrackNamesByPacketId.clear();\n this.#repairOwnersByPacketId.clear();\n if (this.#ownsManifestVerifier) this.#manifestVerifier?.dispose();\n this.#manifestRecoveryQueues.clear();\n for (const assembler of this.#mseAssemblers.values()) assembler.dispose();\n this.#mseAssemblers.clear();\n }\n\n // \u2500\u2500 Private: keyframe loss detection \u2500\u2500\u2500\u2500\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 /** Arm (or re-arm) the keyframe loss timer.\n * Clears any existing timer and sets a new one for keyframeLostTimeoutMs.\n * On timeout, fires onKeyframeLost with the next expected groupId.\n * A reader without a valid value leaves the timer cleared and unarmed. */\n #armKeyframeLostTimer(): void {\n if (this.#keyframeLostTimer) {\n clearTimeout(this.#keyframeLostTimer);\n this.#keyframeLostTimer = null;\n }\n const timeoutMs = this.#readKeyframeLostTimeoutMs();\n if (timeoutMs === null) return;\n const expectedNext = this.#lastKeyframeGroupId + 1;\n this.#keyframeLostTimer = setTimeout(() => {\n this.#keyframeLostTimer = null;\n this.#onKeyframeLost?.(expectedNext);\n }, timeoutMs);\n }\n\n /** The configured number, or the reader's current value; null when the\n * reader throws or either form yields a value no timer can honour. Warns\n * on entering that state or when its cause changes (a different exception,\n * or a different class of bad value), not once per keyframe. */\n #readKeyframeLostTimeoutMs(): number | null {\n const timeout = this.#keyframeLostTimeoutMs!;\n let reason: string;\n let detail: unknown;\n try {\n const ms = typeof timeout === \"function\" ? timeout() : timeout;\n if (Number.isFinite(ms) && ms > 0 && ms <= MAX_TIMER_DELAY_MS) {\n this.#keyframeLostUnarmedReason = null;\n return ms;\n }\n reason =\n typeof ms !== \"number\" ? \"yielded a non-number\"\n : Number.isNaN(ms) ? \"yielded NaN\"\n : !Number.isFinite(ms) ? \"yielded an infinite value\"\n : ms <= 0 ? \"yielded a non-positive value\"\n : `exceeds the ${MAX_TIMER_DELAY_MS} ms timer maximum`;\n detail = ms;\n } catch (error) {\n // Keyed on the cause, so a real reader bug (say a TypeError) is still\n // reported after the expected \"unmeasured\" throw.\n reason = `threw ${error instanceof Error ? `${error.name}: ${error.message}` : String(error)}`;\n detail = error;\n }\n if (reason !== this.#keyframeLostUnarmedReason) {\n this.#keyframeLostUnarmedReason = reason;\n console.warn(\n `[MmtpRouter] keyframeLostTimeoutMs ${reason} \u2014 keyframe loss timer ` +\n \"not armed until it yields a finite positive value:\",\n detail,\n );\n }\n return null;\n }\n\n #noteEmittedKeyframe(packetId: number, keyframe: boolean): void {\n if (!keyframe) return;\n if (!this.#videoPacketIds.has(packetId)) return;\n if (this.#keyframeLostTimeoutMs === null) return;\n // FEC tracks resolve lost keyframes through block deadlines and the\n // release gate's stall decision, never through this timer.\n if (this.#isFecTrack(packetId)) return;\n this.#lastKeyframeGroupId++;\n this.#armKeyframeLostTimer();\n }\n\n // \u2500\u2500 Private: FEC release gate \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** A packetId is an FEC track once the FEC manager configured it. */\n #isFecTrack(packetId: number): boolean {\n return this.#fecManager?.isTrackConfigured?.(packetId) === true;\n }\n\n #withDeferredFecPokes(work: () => void): void {\n this.#fecPokeDepth++;\n try {\n work();\n } finally {\n this.#fecPokeDepth--;\n if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {\n const pokes = [...this.#pendingFecPokes.values()];\n this.#pendingFecPokes.clear();\n for (const poke of pokes) {\n this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);\n }\n }\n }\n }\n\n #requestFecPoke(packetId: number, catalogTrackName: string | undefined): void {\n if (this.#disposed) return;\n if (this.#fecPokeDepth > 0) {\n this.#pendingFecPokes.set(this.#mediaStreamKey(packetId, catalogTrackName), {\n packetId,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n });\n return;\n }\n this.#parser.pokeFecRelease(packetId, catalogTrackName);\n }\n\n /**\n * The release policy the parser applies to FEC tracks: a frame after a gap\n * is held until every block that could hold the missing frames resolved,\n * then released with the stall/conceal decision when media was lost.\n */\n #createFecReleaseGate(): FecReleaseGate {\n if (this.#fecManager?.blockResolution && !this.#fecManager.terminalRetentionMsForPacket) {\n throw new Error(\n \"[MmtpRouter] an FEC manager with blockResolution must provide terminalRetentionMsForPacket: \" +\n \"it bounds how long the release gate holds a frame\",\n );\n }\n return {\n gates: (packetId) => this.#isFecTrack(packetId),\n resolvedLoss: (packetId, catalogTrackName, fromSbn, toSbn, releasedSbn) => {\n const fec = this.#fecManager;\n if (!fec?.blockResolution) return [];\n if (this.#isIsoPacket(packetId)) {\n // iso-ssbg1-v1 frames are anchored by their packet's SS_ID: wait\n // until every block that could hold the SS_IDs between the last\n // released frame and this one is stated and resolved.\n const head = fromSbn === releasedSbn ? toSbn : fromSbn;\n return fec.isoSpanResolution?.(packetId, catalogTrackName, releasedSbn, head) ?? null;\n }\n const highest = fec.highestSbn?.(packetId, catalogTrackName);\n const lost: number[] = [];\n for (let sbn = fromSbn; sbn <= toSbn; sbn++) {\n const resolution = fec.blockResolution(sbn, packetId, catalogTrackName);\n if (resolution === \"pending\") return null;\n if (resolution === \"failed\") {\n lost.push(sbn);\n } else if (resolution === \"untracked\") {\n // releasedSbn is the block of the frame the gate last released, so\n // its media arrived: untracked there means it resolved and retired,\n // not that it vanished. Counting it would conceal a delivered block.\n if (sbn === releasedSbn) continue;\n // Not seen yet: a block at or past the stream's frontier may\n // still start. Behind the frontier it vanished without trace.\n if (highest === undefined || sbn > highest) return null;\n lost.push(sbn);\n }\n }\n return lost;\n },\n // The retention window itself: a frame is never still held when a block\n // it waits on retires. Only consulted while resolvedLoss holds a gap,\n // which needs blockResolution, so the check above guarantees the method.\n holdLimitMs: (packetId) => this.#fecManager?.terminalRetentionMsForPacket?.(packetId) ?? Infinity,\n decide: (before, after, lostBlocks, discontinuity) => {\n const decision = this.#decideGap(before, after, lostBlocks, discontinuity);\n this.#onFrameGap?.(decision);\n return decision;\n },\n onReleased: (data, meta) => {\n if (meta.trackType !== \"video\" || meta.mpuSequenceNumber === undefined) return;\n const timing = meta.authoredTiming;\n if (!timing || !this.#isRapForGap(data, meta)) return;\n this.#fecManager?.noteReleasedRap?.(\n meta.packetId,\n meta.catalogTrackName,\n meta.mpuSequenceNumber,\n timing.presentationTime,\n timing.mediaTimescale,\n );\n },\n };\n }\n\n /**\n * Codec-aware RAP check for gap decisions: the bitstream, with the MMTP R\n * bit only as the fallback for source frames. Recovered frames are\n * bitstream-only, and the MFU priority hint never counts.\n */\n #isRapForGap(data: Uint8Array, meta: ParserFrameMeta): boolean {\n const codec = this.#trackCodecs.get(meta.packetId) ??\n this.#fecManager?.codecFor?.(meta.packetId) ?? \"\";\n const rapFlag = meta.recovered ? false : meta.rapFlag === true;\n return MmtpContainerParser.isKeyframe(data, rapFlag, codec);\n }\n\n #decideGap(\n before: { data: Uint8Array; meta: ParserFrameMeta },\n after: { data: Uint8Array; meta: ParserFrameMeta },\n lostBlocks: readonly number[],\n discontinuity: boolean,\n ): FrameGapDecision {\n const { packetId, catalogTrackName } = after.meta;\n const trackKind = this.#classifyPacketId(packetId) === false ? \"audio\" : \"video\";\n // Sample positions are MPU positions only while the classifier verified\n // the geometry (one movie fragment per MPU, RAP at index 0).\n const positionsTrusted =\n this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === \"classifying\";\n // \"Same MPU on both sides\" proves a delta-only gap only while an MPU\n // boundary bounds the stream's RAPs. Once a RAP was seen inside an MPU\n // (or an MPU outran its GOP), a lost RAP can hide inside one MPU, so the\n // MPU is withheld and a non-RAP after the gap stalls as rap-unknown. A\n // manager that cannot answer is treated as unable to prove it.\n const mpuTrusted =\n this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;\n const evidence = (frame: { data: Uint8Array; meta: ParserFrameMeta }): GapFrameEvidence => {\n const timing = frame.meta.authoredTiming;\n const sampleNumber = frame.meta.sampleNumber;\n return {\n rap: trackKind === \"video\" && this.#isRapForGap(frame.data, frame.meta),\n ...(!mpuTrusted || frame.meta.mpuSequenceNumber === undefined\n ? {}\n : { mpu: frame.meta.mpuSequenceNumber }),\n ...(positionsTrusted && sampleNumber !== undefined && sampleNumber >= 1\n ? { idx: sampleNumber - 1 }\n : {}),\n ...(timing === undefined\n ? {}\n : {\n pts: timing.presentationTime,\n durationTicks: timing.durationTicks,\n timescale: timing.mediaTimescale,\n }),\n };\n };\n return decideGap({\n stream: { packetId, catalogTrackName: catalogTrackName ?? null },\n trackKind,\n before: evidence(before),\n after: evidence(after),\n discontinuity,\n blocks: lostBlocks,\n maxMissingUnits: this.#maxMissingUnits(before.meta, after.meta),\n epoch: this.#fecManager?.epochFor?.(packetId) ?? 0,\n });\n }\n\n /**\n * The most media units a gap between two released frames can hold: the\n * FEC blocks from `before`'s SBN to `after`'s, times D, the media units one\n * block touches (ceil(interleaveDepthMs / unit duration), \u00A75.1). Null when\n * either SBN, the unit duration or the catalog interleave is unknown.\n */\n #maxMissingUnits(before: ParserFrameMeta, after: ParserFrameMeta): number | null {\n const from = before.fecSbn;\n const to = after.fecSbn;\n const timing = before.authoredTiming;\n const interleaveMs = this.#fecManager?.interleaveDepthMsForPacket?.(after.packetId);\n if (from === undefined || to === undefined || !timing || interleaveMs === undefined) return null;\n if (!(timing.durationTicks > 0) || !(timing.mediaTimescale > 0) || !(interleaveMs > 0)) return null;\n // D = ceil(interleaveMs * timescale / (durationTicks * 1000)), in integers.\n const numerator = BigInt(Math.ceil(interleaveMs)) * BigInt(timing.mediaTimescale);\n const denominator = BigInt(timing.durationTicks) * 1000n;\n const unitsPerBlock = (numerator + denominator - 1n) / denominator;\n // iso-ssbg1-v1 anchors are SS_IDs: every block holds at least one, so the\n // serial SS_ID distance bounds the blocks between them.\n const blocks = BigInt(\n (this.#isIsoPacket(after.packetId)\n ? (serial32Precedes(from, to) ? serial32Distance(from, to) : serial32Distance(to, from))\n : Math.abs(to - from)) + 1,\n );\n const bound = unitsPerBlock * blocks;\n return bound > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(bound);\n }\n\n // \u2500\u2500 Private: MMTP processing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** Classify a packetId from the catalog. Returns true=video, false=audio, null=unknown (drop). */\n #classifyPacketId(packetId: number): boolean | null {\n if (this.#videoPacketIds.has(packetId)) return true;\n if (this.#audioPacketIds.has(packetId)) return false;\n return null;\n }\n\n /** Resolve callback for a packetId (cached per-packetId, invalidated on registration).\n * When a per-track callback is registered AND a legacy callback exists,\n * fires BOTH: per-track first, then legacy. This ensures element.ts wiring\n * (confirmAudio, feedMulticast) continues to fire even when TrackPipeline\n * registers per-track sources.\n * Returns null for unknown packetIds \u2014 callers must drop the packet. */\n #getFrameCallback(packetId: number): FrameCallback | null {\n const cached = this.#resolvedCallbacks.get(packetId);\n if (cached) return cached;\n\n const perTrack = this.#trackCallbacks.get(packetId);\n const classification = this.#classifyPacketId(packetId);\n const legacy =\n classification === true\n ? this.#onVideoFrame\n : classification === false\n ? this.#onAudioFrame\n : null;\n\n let resolved: FrameCallback | null;\n if (perTrack && legacy) {\n // Composite: fire both so per-track routing AND legacy confirm/feedMulticast work.\n resolved = (data, meta) => {\n perTrack(data, meta);\n legacy(data, meta);\n };\n } else {\n resolved = perTrack ?? legacy ?? null;\n }\n\n if (resolved) this.#resolvedCallbacks.set(packetId, resolved);\n return resolved;\n }\n\n /** Deliver init segment for a track (deduped per physical stream). */\n #deliverInit(packetId: number, data: Uint8Array, catalogTrackName?: string): void {\n const staged = this.#staged;\n if (staged !== null && isStream({ packetId, catalogTrackName }, staged.to)) {\n // The incoming stream's init describes media delivered after the\n // commit. Handing it over before would reconfigure a decoder that is\n // still fed the outgoing stream, so it travels with the RAP instead.\n if (data.byteLength > 8) staged.heldInit = data;\n return;\n }\n const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);\n if (this.#trackInitDelivered.has(streamKey)) return;\n if (data.byteLength <= 8) return;\n this.#trackInitDelivered.add(streamKey);\n const cb = this.#trackInitCallbacks.get(packetId);\n if (cb) {\n cb(data);\n } else if (this.#onInitSegment) {\n this.#onInitSegment(data);\n }\n console.log(\n `[MmtpRouter] Init delivered for packetId=${packetId}${catalogTrackName === undefined ? \"\" : ` track=${catalogTrackName}`} (${data.byteLength}B)`,\n );\n }\n\n /**\n * Core MMTP packet processing \u2014 source packets \u2192 play + FEC, repair \u2192 FEC only.\n * Both source and repair feed FECManager so RaptorQ has enough symbols (source + repair >= K).\n *\n * Two-phase parsing via MmtpContainerParser:\n * 1. parseHeader() \u2192 extract packetId + fecPayloadId for FEC feeding\n * 2. feed() \u2192 MFU extraction, reassembly, keyframe detection, emit via callbacks\n */\n #processMMTP(\n packet: Uint8Array,\n source: \"multicast\" | \"moq\",\n manifestIdentity?: ManifestObjectIdentity,\n manifestAdmitted = false,\n ingress?: MmtpIngressContext,\n overlapCopy = false,\n releasedFromQuarantine = false,\n ): void {\n // One header parse per packet: the parser reuses it in feedParsed()\n // below instead of parsing the same header again (BLO-36599).\n const parsed = this.#parser.parsePacket(packet);\n if (!parsed) return;\n const info = parsed.info;\n // Every multicast packet is a delivery-gap sample, including one dropped\n // below: the gap is a property of the link the FEC deadlines run on, not\n // of which packets this router routes. The re-entry after a manifest\n // admission is the same arrival, not a new one.\n if (source === \"multicast\" && !manifestAdmitted) {\n this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);\n }\n if (source === \"multicast\" && !ingressHasPacketId(ingress, info.packetId)) {\n debugRouter(\n `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`,\n );\n return;\n }\n const packetRole = this.#packetIdRoles.get(info.packetId);\n if (\n source === \"multicast\" &&\n this.#classifyPacketId(info.packetId) === null &&\n (!info.isRepair || packetRole !== \"repair\")\n ) {\n debugRouter(\n `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: physical PID is unregistered`,\n );\n return;\n }\n if (!info.isRepair && hasAmbiguousCatalogTrackName(ingress, info.packetId)) {\n return;\n }\n // A source FEC Payload ID is read under the packet's block profile. Until\n // the track's FEC is configured it has none: nothing (manifest identity,\n // ledgers, FEC state) reads it as a block coordinate, and the media is\n // routed as on a track without FEC.\n const fecUnreadable =\n !info.isRepair &&\n info.fecPayloadId != null &&\n this.#fecManager !== null &&\n this.#classifyPacketId(info.packetId) !== null &&\n this.#configuredBlockProfile(info.packetId) === undefined;\n if (fecUnreadable && !manifestAdmitted) this.#noteUnreadableFecPayloadId(info.packetId, \"source\");\n\n if (!info.isRepair && this.#manifestVerifier && !manifestAdmitted) {\n let identity = manifestIdentity;\n if (!identity && info.fecPayloadId && !fecUnreadable && (this.#resolveManifestIdentityForRoute || this.#resolveManifestIdentity)) {\n const coordinates = this.#deriveSbnEsi(info.fecPayloadId.ssId, info.packetId);\n const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);\n identity = (this.#resolveManifestIdentityForRoute\n ? this.#resolveManifestIdentityForRoute({\n packetId: info.packetId,\n sbn: coordinates.sbn,\n esi: coordinates.esi,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n recovered: false,\n sourceSymbolFormat: \"full-mmtp-packet\",\n })\n : this.#resolveManifestIdentity!(\n info.packetId,\n coordinates.sbn,\n coordinates.esi,\n catalogTrackName,\n )) ?? undefined;\n }\n if (identity) {\n identity = {\n ...identity,\n packetId: info.packetId,\n ...(info.fecPayloadId ? { ssId: info.fecPayloadId.ssId } : {}),\n };\n const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;\n // A `stall` admission quarantines the packet and releases it later,\n // after the stream has moved on; a synchronous release happens inside\n // admitObject, before this flag is set.\n let quarantined = false;\n const admission = this.#manifestVerifier.admitObject(identity, authenticated, () => {\n if (!this.#disposed) {\n this.#processMMTP(packet, source, identity, true, ingress, overlapCopy, quarantined);\n }\n });\n quarantined = admission.action === \"stall\";\n return;\n }\n if (\n this.#manifestVerifier.config.mode === \"enforce\" &&\n this.#manifestVerifier.config.onMissingManifest === \"stall\"\n ) {\n console.warn(`[MmtpRouter] manifest identity absent; stalling packetId=${info.packetId}`);\n return;\n }\n }\n\n if (info.isRepair) {\n // Repair packet \u2014 per ISO 23008-1 \u00A7C.5.3, carries (SS_Start, SSB_length, RS_ID).\n // Read from the header parsed above rather than parsing it again\n // (BLO-36599).\n const repair = parseMoqRepairFrameWithHeader(packet, parsed.header);\n if (!repair) return;\n\n const ownerPacketId = this.#resolveRepairOwnerPacketId(info.packetId, ingress);\n if (ownerPacketId != null && this.#fecManager) {\n if (hasAmbiguousCatalogTrackName(ingress, ownerPacketId)) return;\n this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;\n const count = this.#repairPidCounts[info.packetId]!;\n if (count <= 2 || count % 500 === 0) {\n console.log(\n `[MC-PKT] pid=${info.packetId} repairOwner=${ownerPacketId} type=${info.packetType} count=${count} ssbLength=${repair.ssbLength} len=${packet.length}`,\n );\n }\n\n if (this.#configuredBlockProfile(ownerPacketId) === undefined) {\n this.#noteUnreadableFecPayloadId(ownerPacketId, \"repair\");\n return;\n }\n // NOTE: Do NOT call trackBlock for repair packets. Only source symbols\n // should count toward block completion \u2014 repair inflates blocksClean stats\n // and masks blocks that actually needed FEC recovery.\n if (this.#isIsoPacket(ownerPacketId)) {\n this.#handleIsoRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair, source);\n return;\n }\n const repairSbn = this.#deriveRepairSbn(repair.ssStart, repair.ssbLength, ownerPacketId);\n if (repairSbn === null) return;\n const repairEsi = this.#kForPacket(ownerPacketId) + repair.rsId;\n\n if (\n !this.#feedFecTransportSymbol(\n ownerPacketId,\n repairSbn,\n repairEsi,\n repair.symbolData,\n source,\n catalogTrackNameForPacket(ingress, ownerPacketId),\n )\n ) return;\n\n // Repair symbols are block progress too. The deadline measures\n // inactivity, not total block lifetime.\n const repairCatalogTrackName = catalogTrackNameForPacket(ingress, ownerPacketId);\n if (repairCatalogTrackName === undefined) {\n this.#fecManager.noteBlockActivity?.(repairSbn, ownerPacketId);\n } else {\n this.#fecManager.noteBlockActivity?.(\n repairSbn,\n ownerPacketId,\n repairCatalogTrackName,\n );\n }\n\n const recovered = repairCatalogTrackName === undefined\n ? this.#fecManager.feedRepairSymbol(\n ownerPacketId,\n repair.ssStart,\n repair.ssbLength,\n repair.rsId,\n repair.symbolData,\n )\n : this.#fecManager.feedRepairSymbol(\n ownerPacketId,\n repair.ssStart,\n repair.ssbLength,\n repair.rsId,\n repair.symbolData,\n repairCatalogTrackName,\n );\n if (recovered) {\n const alreadyCompleted = repairCatalogTrackName === undefined\n ? this.#fecManager.isBlockCompleted(repairSbn, ownerPacketId)\n : this.#fecManager.isBlockCompleted(\n repairSbn,\n ownerPacketId,\n repairCatalogTrackName,\n );\n if (repairCatalogTrackName === undefined) {\n this.#fecManager.cancelBlockTimeout(repairSbn, ownerPacketId);\n } else {\n this.#fecManager.cancelBlockTimeout(\n repairSbn,\n ownerPacketId,\n repairCatalogTrackName,\n );\n }\n // Skip routing if block was already completed via source path (all K sources\n // arrived). The parser's feed() already played every frame.\n if (!alreadyCompleted) {\n this.#fecManager.countRecovery(ownerPacketId, repairSbn, repairCatalogTrackName);\n if (repairCatalogTrackName === undefined) {\n this.#fecManager.markBlockCompleted(repairSbn, ownerPacketId);\n } else {\n this.#fecManager.markBlockCompleted(\n repairSbn,\n ownerPacketId,\n repairCatalogTrackName,\n );\n }\n this.#routeRecoveredBlock(\n repairSbn,\n recovered,\n ownerPacketId,\n catalogTrackNameForPacket(ingress, ownerPacketId),\n );\n }\n }\n }\n } else {\n // Drop source packets with unknown packetId \u2014 not in catalog.\n if (this.#classifyPacketId(info.packetId) === null) return;\n\n // Debug: count packets per packetId\n this.#pidCounts[info.packetId] = (this.#pidCounts[info.packetId] || 0) + 1;\n const count = this.#pidCounts[info.packetId]!;\n if (count <= 2 || count % 500 === 0) {\n console.log(\n `[MC-PKT] pid=${info.packetId} type=${info.packetType} count=${count} len=${packet.length}`,\n );\n }\n\n // Source packet \u2014 parse for playback first, then feed FEC only if the\n // source block did not complete cleanly. Feeding FEC before parser/feed\n // lets a source-triggered recovery race ahead of the source timeline.\n let fecInfo:\n | { sbn: number; esi: number; oversized?: boolean }\n | undefined;\n let sourceFec:\n | {\n ssId: number;\n sbn: number;\n symbolData: Uint8Array;\n }\n | null = null;\n let sourceSymbolAccepted = false;\n let sourceSymbolTrackable = false;\n let parseSourceSymbol = false;\n const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);\n if (catalogTrackName !== undefined) {\n const names = this.#catalogTrackNamesByPacketId.get(info.packetId) ?? new Set();\n names.add(catalogTrackName);\n this.#catalogTrackNamesByPacketId.set(info.packetId, names);\n }\n\n const duplicates = this.#stream(info.packetId, catalogTrackName).duplicates;\n // The FEC Payload ID FEC may read: none while the packetId has no\n // configured block profile (fecUnreadable above).\n const fecPayloadId = fecUnreadable ? null : info.fecPayloadId;\n // iso-ssbg1-v1 locates a source by range membership in a block a repair\n // already stated; until then it is held, unplaced (BLO-35597 iso:3).\n const isoSource = this.#fecManager !== null && fecPayloadId != null &&\n this.#isIsoPacket(info.packetId);\n const coords = this.#fecManager && fecPayloadId\n ? (isoSource\n ? this.#fecManager.locateIsoSource?.(info.packetId, catalogTrackName, fecPayloadId.ssId) ?? undefined\n : this.#deriveSbnEsi(fecPayloadId.ssId, info.packetId))\n : undefined;\n // Note the packet's FEC block (none without an FEC coordinate) before\n // any ledger lookup, the restart check below included.\n duplicates.advance(coords?.sbn);\n // A multicast packet that predates everything the stream has kept for a\n // whole FEC horizon is a publisher that restarted its\n // packet_sequence_number / SS_ID counters (BLO-36599,\n // StreamDuplicateLedgers.predatesHorizon). Its first packets would\n // otherwise read as duplicates or as frames behind the reorder cursor.\n // Start a fresh epoch for the stream before this packet is looked up.\n // The reset needs the catalog identity, so a stream without one is not\n // checked; an overlap copy is MoQ bytes and says nothing about the\n // multicast publisher, and neither does a packet the manifest verifier\n // quarantined: it predates the horizon because it waited, not because the\n // publisher restarted.\n if (\n source === \"multicast\" &&\n !overlapCopy &&\n !releasedFromQuarantine &&\n catalogTrackName !== undefined &&\n duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)\n ) {\n this.#publisherRestarts++;\n console.warn(\n `[MmtpRouter] publisher restart on pid=${info.packetId} track=${catalogTrackName}: ` +\n `packet_sequence_number=${info.sequenceNumber} predates the stream's FEC horizon; ` +\n \"starting a new epoch\",\n );\n // Frames the release gate holds belong to the old epoch: release them\n // as a discontinuity stall, as FECManager's source-discontinuity path\n // does, before the reset discards the stream.\n this.#parser.markFecDiscontinuity(info.packetId, catalogTrackName);\n this.#parser.pokeFecRelease(info.packetId, catalogTrackName);\n this.resetTrack(info.packetId, catalogTrackName);\n this.#onPublisherRestart?.(info.packetId, catalogTrackName);\n // The reset cleared the ledgers: note this packet's block in the new epoch.\n duplicates.advance(coords?.sbn);\n }\n if (this.#fecManager && fecPayloadId && coords) {\n const fecId = fecPayloadId;\n const symbolSize = this.#symbolSizeForPacket(info.packetId);\n\n // The mmtp-packet source symbol protects the complete MMTP packet\n // before SS_ID is appended, self-delimiting and zero-padded to T.\n const rawSymbol = packet.subarray(0, packet.length - 4);\n // iso-ssbg1-v1 symbols carry a two-octet length (C.3.3): admission\n // refuses length + 2 > T.\n const oversized = isoSource\n ? !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false)\n : symbolSize > 0 && rawSymbol.length > symbolSize;\n\n // NOTE: trackBlock() is deferred to AFTER #feedViaParser (below).\n // Reason: trackBlock synchronously fires onBlockComplete when the\n // K-th source symbol arrives, which synchronously calls\n // CmafBlockAssembler.completeBlock \u2192 #flushBlock \u2192 emit. If\n // trackBlock fires BEFORE parser.feed, the K-th packet's\n // parser.onFrame \u2192 assembler.addFrame happens AFTER flushBlock\n // already drained the block \u2014 the K-th frame is stranded in a\n // newly-allocated empty block that never gets a completeBlock\n // event again, because that SBN is already in fecManager's\n // #completedBlocks set (BLO-3035 layer 4).\n //\n // Complete-packet symbols larger than T cannot be decoded but still\n // represent a source-symbol arrival, so trackBlock counts them below.\n\n let overlapBlockCompleted = false;\n if (overlapCopy) {\n // Playback only. The multicast twin still feeds FEC when it\n // arrives. The per-symbol parse ledger below parses whichever copy\n // arrives first and drops the second; the MFU reassembler cannot,\n // because complete (FI=0) MFUs bypass its #emitted set. A completed\n // block stays authoritative, as it does for FEC input.\n overlapBlockCompleted = catalogTrackName === undefined\n ? this.#fecManager.isBlockCompleted(coords.sbn, info.packetId)\n : this.#fecManager.isBlockCompleted(\n coords.sbn,\n info.packetId,\n catalogTrackName,\n );\n } else if (oversized) {\n // Oversized packet \u2014 not FEC-encoded by FFmpeg, skip FEC feed.\n // Still emitted via parser.feed() below (direct path).\n sourceSymbolAccepted = this.#feedFecTransportSymbol(\n info.packetId,\n coords.sbn,\n coords.esi,\n rawSymbol,\n source,\n catalogTrackName,\n );\n sourceSymbolTrackable = sourceSymbolAccepted;\n } else {\n // FECManager zero-pads a short symbol to T itself and then owns that\n // buffer outright, so it can transfer it to the FEC Worker without\n // copying it again. Padding here as well cost a second T-byte\n // allocation and copy per short packet (BLO-36599).\n const symbolData = rawSymbol;\n\n sourceSymbolAccepted = this.#feedFecTransportSymbol(\n info.packetId,\n coords.sbn,\n coords.esi,\n symbolData,\n source,\n catalogTrackName,\n );\n sourceSymbolTrackable = sourceSymbolAccepted;\n if (sourceSymbolAccepted) {\n sourceFec = { ssId: fecId.ssId, sbn: coords.sbn, symbolData };\n }\n }\n\n // First copy wins per symbol, in either arrival order.\n parseSourceSymbol =\n (overlapCopy ? !overlapBlockCompleted : sourceSymbolAccepted) &&\n !duplicates.parsedSymbols.has(fecId.ssId);\n\n // Compute FEC block info for the MSE assembler.\n fecInfo = { sbn: coords.sbn, esi: coords.esi, oversized };\n } else if (isoSource && this.#fecManager && fecPayloadId) {\n // iso-ssbg1-v1 source whose block no repair has stated yet: route its\n // media now and hold its FEC symbol until a repair places it.\n const ssId = fecPayloadId.ssId;\n if (overlapCopy) {\n parseSourceSymbol = !duplicates.parsedSymbols.has(ssId);\n } else {\n const rawSymbol = packet.subarray(0, packet.length - 4);\n const held = this.#fecManager.holdIsoSource?.(info.packetId, catalogTrackName, ssId, {\n symbolData: rawSymbol,\n source,\n evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),\n oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false),\n }) ?? false;\n parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);\n }\n } else if (fecUnreadable && info.fecPayloadId) {\n // FEC is unavailable for this packetId: its media is routed as on a\n // track without FEC, first copy per SS_ID. The parse ledger reads\n // SS_ID only as a symbol identity, never as a block coordinate.\n parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);\n }\n\n // Parse only the first copy of an FEC source symbol. A late direct copy\n // of a worker-recovered fragment has the same SBN/ESI and fragment\n // counter; feeding it again can make the MFU buffer non-contiguous even\n // when FI=1..3 were already complete. Non-FEC packets still always flow.\n if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {\n if (this.#fecManager && info.fecPayloadId) {\n duplicates.parsedSymbols.add(info.fecPayloadId.ssId);\n }\n this.#noteSourcePacketSeq(\n info.packetId,\n info.sequenceNumber,\n catalogTrackName,\n );\n this.#routeTrackPacket(packet, info.packetId, info.sequenceNumber, {\n recovered: false,\n skipFecPayloadId: false,\n catalogTrackName,\n });\n this.#feedViaParser(packet, info, fecInfo, {\n source,\n catalogTrackName,\n ...(isoSource && info.fecPayloadId\n ? { fecSbn: info.fecPayloadId.ssId }\n : fecInfo === undefined ? {} : { fecSbn: fecInfo.sbn }),\n }, parsed);\n }\n // The frame this packet completed can commit an in-place switch that\n // retires this very packet ID. Its FEC state is gone then, and feeding\n // the rest of this packet would only rebuild it for a stream that ended.\n if (this.#classifyPacketId(info.packetId) === null) return;\n\n // Deferred trackBlock (BLO-3035 layer 4 race fix). Fire AFTER\n // #feedViaParser \u2192 parser.feed \u2192 addFrame, so the K-th source\n // packet's frame is buffered in CmafBlockAssembler.#blocks BEFORE\n // trackBlock synchronously triggers onBlockComplete \u2192 completeBlock\n // \u2192 #flushBlock. Without this ordering, the K-th frame was lost on\n // every block \u2014 only K-1 frames per block were ever emitted to MSE.\n // Only first-arriving symbols count toward completion or playback.\n if (\n this.#fecManager &&\n fecPayloadId &&\n sourceSymbolAccepted &&\n sourceSymbolTrackable\n ) {\n const { sbn, esi } = isoSource && coords\n ? coords\n : this.#deriveSbnEsi(fecPayloadId.ssId, info.packetId);\n if (\n this.#classifyPacketId(info.packetId) !== null &&\n this.#fecManager.isTrackConfigured?.(info.packetId) !== false\n ) {\n // Only this first-arrival network source symbol is classification\n // evidence: the R bit and the MPU / DU identity it carries.\n // Recovered and repair symbols never reach this call.\n this.#fecManager.trackBlock(\n sbn,\n info.packetId,\n catalogTrackName,\n esi,\n sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),\n );\n this.#requestFecPoke(info.packetId, catalogTrackName);\n }\n }\n\n // Only now feed source symbols into FEC. The decoder must still receive\n // the K-th source symbol after trackBlock() marks a clean block complete:\n // Worker-backed decoders use that symbol for their own block lifecycle\n // and stats. Suppress any synchronous recovered-block return when the\n // manager already completed the block, because every source frame was\n // parsed and emitted above.\n if (this.#fecManager && sourceFec) {\n const alreadyCompleted = catalogTrackName === undefined\n ? this.#fecManager.isBlockCompleted(sourceFec.sbn, info.packetId)\n : this.#fecManager.isBlockCompleted(\n sourceFec.sbn,\n info.packetId,\n catalogTrackName,\n );\n const recovered = catalogTrackName === undefined\n ? this.#fecManager.feedSourceSymbol(\n info.packetId,\n sourceFec.ssId,\n sourceFec.symbolData,\n undefined,\n )\n : this.#fecManager.feedSourceSymbol(\n info.packetId,\n sourceFec.ssId,\n sourceFec.symbolData,\n undefined,\n catalogTrackName,\n );\n if (recovered) {\n if (!alreadyCompleted && this.#classifyPacketId(info.packetId) !== null) {\n if (catalogTrackName === undefined) {\n this.#fecManager.cancelBlockTimeout(sourceFec.sbn, info.packetId);\n } else {\n this.#fecManager.cancelBlockTimeout(\n sourceFec.sbn,\n info.packetId,\n catalogTrackName,\n );\n }\n }\n // Only route recovered blocks that needed actual repair.\n if (!alreadyCompleted) {\n this.#fecManager.countRecovery(info.packetId, sourceFec.sbn, catalogTrackName);\n if (catalogTrackName === undefined) {\n this.#fecManager.markBlockCompleted(sourceFec.sbn, info.packetId);\n } else {\n this.#fecManager.markBlockCompleted(\n sourceFec.sbn,\n info.packetId,\n catalogTrackName,\n );\n }\n this.#routeRecoveredBlock(\n sourceFec.sbn,\n recovered,\n info.packetId,\n catalogTrackName,\n );\n }\n }\n }\n }\n }\n\n /**\n * Set temp context and delegate to parser.feed() for MFU extraction,\n * reassembly, keyframe detection, and frame emission via callbacks.\n */\n #feedViaParser(\n packet: Uint8Array,\n info: {\n packetId: number;\n sequenceNumber: number;\n fecPayloadId?: { ssId: number } | null;\n },\n fecInfo?: { sbn: number; esi: number; oversized?: boolean },\n parserOptions?: {\n skipFecPayloadId?: boolean;\n recovered?: boolean;\n source?: MmtpSourcePath;\n deliveryProvenance?: MmtpDeliveryProvenance;\n catalogTrackName?: string;\n fecSbn?: number;\n },\n parsed?: ParsedMmtpPacket,\n ): void {\n const diag = this.#diagFor(info.packetId, parserOptions?.catalogTrackName);\n // Plain parser counters, not reassembler.getStatus(): on the wasm backend\n // each status read is a stats() crossing, and this runs for every packet\n // (BLO-36599). Buffer occupancy is read once, in getDiagnostics().\n const fragmentsBefore = this.#parser.reassemblerFragmentsFed;\n const reassembledBefore = this.#parser.reassemblerDataUnitsReturned;\n diag.packets++;\n diag.lastPacketLength = packet.byteLength;\n diag.lastSequenceNumber = info.sequenceNumber;\n if (info.fecPayloadId) diag.lastFecSsId = info.fecPayloadId.ssId;\n this.#currentFecInfo = fecInfo;\n this.#currentSeqNum = info.sequenceNumber;\n try {\n const feedOptions = {\n skipFecPayloadId: parserOptions?.skipFecPayloadId,\n recovered: parserOptions?.recovered,\n source: parserOptions?.source,\n deliveryProvenance: parserOptions?.deliveryProvenance,\n catalogTrackName: parserOptions?.catalogTrackName,\n ...(parserOptions?.fecSbn === undefined ? {} : { fecSbn: parserOptions.fecSbn }),\n };\n if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);\n else this.#parser.feed(packet, feedOptions);\n } finally {\n this.#currentFecInfo = undefined;\n }\n const fragmentDelta = this.#parser.reassemblerFragmentsFed - fragmentsBefore;\n const reassembledDelta =\n this.#parser.reassemblerDataUnitsReturned - reassembledBefore;\n if (fragmentDelta > 0) diag.fragments += fragmentDelta;\n else diag.noFragment++;\n if (reassembledDelta > 0) diag.reassembled += reassembledDelta;\n }\n\n #feedFecTransportSymbol(\n packetId: number,\n sbn: number,\n esi: number,\n data: Uint8Array,\n source: MmtpSourcePath,\n catalogTrackName?: string,\n ): boolean {\n const fecManager = this.#fecManager;\n if (!fecManager) return false;\n return catalogTrackName === undefined\n ? fecManager.feedSymbolFromSource(packetId, sbn, esi, data, source)\n : fecManager.feedSymbolFromSource(\n packetId,\n sbn,\n esi,\n data,\n source,\n catalogTrackName,\n );\n }\n\n #diagFor(packetId: number, catalogTrackName?: string): ParserDiagnostics {\n const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);\n let diag = this.#parserDiagnostics.get(streamKey);\n if (!diag) {\n diag = {\n packets: 0,\n frames: 0,\n initSegments: 0,\n noFragment: 0,\n fragments: 0,\n reassembled: 0,\n pendingBuffers: 0,\n pendingFragments: 0,\n lastPacketLength: 0,\n lastSequenceNumber: 0,\n directAudioSourceEmitted: 0,\n directAudioSourceRegressions: 0,\n directAudioRecoveredQueued: 0,\n directAudioRecoveredDrained: 0,\n directAudioRecoveredStaleDropped: 0,\n };\n this.#parserDiagnostics.set(streamKey, diag);\n }\n return diag;\n }\n\n #shouldEmitFrame(\n packetId: number,\n keyframe: boolean,\n catalogTrackName?: string,\n ): boolean {\n if (!this.#fecManager) return true;\n if (!this.#videoPacketIds.has(packetId)) return true;\n const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);\n if (this.#trackSynced.has(streamKey)) return true;\n if (!keyframe) {\n this.#droppedPreSyncVideo.add(streamKey);\n return false;\n }\n this.#trackSynced.add(streamKey);\n this.#droppedPreSyncVideo.delete(streamKey);\n return true;\n }\n\n #opensFecSync(\n packetId: number,\n keyframe: boolean,\n catalogTrackName?: string,\n ): boolean {\n const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);\n return !!this.#fecManager &&\n this.#videoPacketIds.has(packetId) &&\n !this.#trackSynced.has(streamKey) &&\n this.#droppedPreSyncVideo.has(streamKey) &&\n keyframe;\n }\n\n #noteEmittedVideoSeq(streamKey: string, packetSequenceNumber: number | undefined): void {\n if (packetSequenceNumber === undefined || !Number.isFinite(packetSequenceNumber)) return;\n const latest = this.#latestVideoSeqByStream.get(streamKey);\n if (latest === undefined || packetSequenceNumber > latest) {\n this.#latestVideoSeqByStream.set(streamKey, packetSequenceNumber);\n }\n }\n\n #noteSourcePacketSeq(\n packetId: number,\n packetSequenceNumber: number | undefined,\n catalogTrackName?: string,\n ): void {\n if (packetSequenceNumber === undefined || !Number.isFinite(packetSequenceNumber)) return;\n this.#stream(packetId, catalogTrackName).duplicates.sourceSeqs.add(packetSequenceNumber);\n }\n\n #sourceSeqReceived(\n packetId: number,\n packetSequenceNumber: number,\n catalogTrackName?: string,\n ): boolean {\n return this.#stream(packetId, catalogTrackName).duplicates.sourceSeqs.has(packetSequenceNumber);\n }\n\n #routeTrackPacket(\n packet: Uint8Array,\n packetId: number,\n packetSequenceNumber: number,\n meta: Pick<\n RoutedPacketMeta,\n \"recovered\" | \"skipFecPayloadId\" | \"catalogTrackName\" | \"deliveryProvenance\"\n >,\n ): void {\n if (!Number.isFinite(packetSequenceNumber)) return;\n const callback = this.#trackPacketCallbacks.get(packetId);\n if (!callback) return;\n const routedSeqs = this.#stream(packetId, meta.catalogTrackName).duplicates.routedSeqs;\n if (routedSeqs.has(packetSequenceNumber)) return;\n routedSeqs.add(packetSequenceNumber);\n callback(packet, {\n packetId,\n packetSequenceNumber,\n recovered: meta.recovered,\n skipFecPayloadId: meta.skipFecPayloadId,\n ...(meta.catalogTrackName === undefined\n ? {}\n : { catalogTrackName: meta.catalogTrackName }),\n ...(meta.deliveryProvenance === undefined\n ? {}\n : { deliveryProvenance: meta.deliveryProvenance }),\n });\n }\n\n #isStaleRecoveredVideo(\n packetId: number,\n packetSequenceNumber: number,\n catalogTrackName?: string,\n ): boolean {\n const latest = this.#latestVideoSeqByStream.get(\n this.#mediaStreamKey(packetId, catalogTrackName),\n );\n return latest !== undefined && packetSequenceNumber <= latest;\n }\n\n /**\n * JSON tuple naming one physical stream. Built several times per packet, so\n * each (packetId, catalog name) pair is serialized once and reused; the set\n * of pairs is bounded by the catalog (BLO-36599).\n */\n #mediaStreamKey(packetId: number, catalogTrackName?: string): string {\n return this.#stream(packetId, catalogTrackName).key;\n }\n\n /** The (packetId, catalog name) stream's key and duplicate ledgers. */\n #stream(packetId: number, catalogTrackName?: string): StreamLedgers {\n let byName = this.#streams.get(packetId);\n if (!byName) {\n byName = new Map();\n this.#streams.set(packetId, byName);\n }\n let stream = byName.get(catalogTrackName);\n if (stream === undefined) {\n stream = {\n key: JSON.stringify([packetId, catalogTrackName ?? null]),\n duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),\n };\n byName.set(catalogTrackName, stream);\n }\n return stream;\n }\n\n #packetIdFromStreamKey(key: string): number {\n try {\n const decoded = JSON.parse(key);\n if (Array.isArray(decoded) && typeof decoded[0] === \"number\") return decoded[0];\n } catch {\n // Internal keys are JSON tuples; malformed legacy keys should not happen.\n }\n return 0;\n }\n\n #mseAssemblerKey(packetId: number, catalogTrackName?: string): string {\n return this.#mediaStreamKey(packetId, catalogTrackName);\n }\n\n #mseAssemblerFor(\n packetId: number,\n catalogTrackName?: string,\n ): CmafBlockAssembler | undefined {\n const exact = this.#mseAssemblers.get(\n this.#mseAssemblerKey(packetId, catalogTrackName),\n );\n if (exact || catalogTrackName === undefined) return exact;\n if (!this.#isCatalogTrackUnambiguous(packetId, catalogTrackName)) return undefined;\n return this.#mseAssemblers.get(this.#mseAssemblerKey(packetId));\n }\n\n #isCatalogTrackUnambiguous(\n packetId: number,\n catalogTrackName?: string,\n ): boolean {\n if (catalogTrackName === undefined) return true;\n const names = this.#catalogTrackNamesByPacketId.get(packetId);\n return names?.size === 1 && names.has(catalogTrackName);\n }\n\n #resolveRecoveredTiming(\n packetId: number,\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number | undefined,\n sampleNumber: number | undefined,\n mmtpTimestamp: bigint,\n catalogTrackName?: string,\n ): { authoredTiming?: AuthoredTiming; timestamp: number; mmtpTimestamp: bigint } | null {\n // Non-timed MFUs do not carry a movie-fragment/sample identity. They are\n // outside the ISO-BMFF presentation timeline, so retain the raw MMTP\n // timestamp path used by the untimed router contract.\n if (movieFragmentSequenceNumber === undefined || sampleNumber === undefined) {\n return {\n timestamp: mmtpTimestampToMicros(mmtpTimestamp),\n mmtpTimestamp,\n };\n }\n\n // Claim the resolver entry before scaling it. The claim is the single\n // consume operation for a recovered sample; doing lookup \u2192 scale \u2192 claim\n // would leave an invalid entry live forever when scaling rejects it.\n const authoredTiming = this.#parser.consumeAuthoredTimingFor(\n packetId,\n mpuSequenceNumber,\n movieFragmentSequenceNumber,\n sampleNumber,\n catalogTrackName,\n );\n // Recovery is accepted only when the timed stream's FT=1 metadata names\n // this exact sample. MMTP send timestamps describe transport arrival, not\n // the authored presentation timeline, so they are never a fallback.\n if (authoredTiming === null) return null;\n const scaled = scaleAuthoredTiming(authoredTiming, 1_000_000);\n if (scaled === null) return null;\n return { authoredTiming, timestamp: scaled.timestamp, mmtpTimestamp };\n }\n\n #pendingRecoveredKey(meta: RoutedFrameMeta): string {\n return `${meta.timestamp}:${meta.packetSequenceNumber ?? \"\"}`;\n }\n\n #pendingRecoveredQueue(streamKey: string): Map<string, PendingRecoveredVideoFrame> {\n let queue = this.#pendingDirectRecoveredVideoByStream.get(streamKey);\n if (!queue) {\n queue = new Map();\n this.#pendingDirectRecoveredVideoByStream.set(streamKey, queue);\n }\n return queue;\n }\n\n #comparePendingRecoveredVideo(\n a: PendingRecoveredVideoFrame,\n b: PendingRecoveredVideoFrame,\n ): number {\n if (a.meta.timestamp !== b.meta.timestamp) return a.meta.timestamp - b.meta.timestamp;\n const aSeq = a.meta.packetSequenceNumber ?? Number.MAX_SAFE_INTEGER;\n const bSeq = b.meta.packetSequenceNumber ?? Number.MAX_SAFE_INTEGER;\n return aSeq - bSeq;\n }\n\n #noteDeliveredVideo(streamKey: string, meta: StreamSwitchPosition): void {\n const high = this.#deliveredVideoHighWaterByStream.get(streamKey);\n if (high === undefined || comparePresentation(meta, high) > 0) {\n this.#deliveredVideoHighWaterByStream.set(streamKey, switchPosition(meta));\n }\n }\n\n #emitDirectVideo(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n cb: FrameCallback | null,\n ): boolean {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n const lastEmitted = this.#lastDirectEmittedVideoTsByStream.get(streamKey);\n if (lastEmitted !== undefined && meta.timestamp <= lastEmitted) return false;\n this.#lastDirectEmittedVideoTsByStream.set(streamKey, meta.timestamp);\n this.#noteDeliveredVideo(streamKey, meta);\n // Record the emitted sequence number HERE \u2014 at the real emit \u2014 not when a\n // recovered frame is queued. #routeDirectRecoveredVideo may enqueue a frame\n // that is ahead of the source cursor; noting its seq before it drains would\n // make #isStaleRecoveredVideo drop an earlier gap frame that arrives later\n // (it would look <= the queued-but-unemitted seq). The high-water mark must\n // reflect what actually reached the decoder callback.\n this.#noteEmittedVideoSeq(streamKey, meta.packetSequenceNumber);\n cb?.(data, meta);\n return true;\n }\n\n #drainDirectRecoveredVideo(\n streamKey: string,\n packetId: number,\n releases: (meta: RoutedFrameMeta) => boolean,\n cb: FrameCallback | null,\n ): void {\n const queue = this.#pendingDirectRecoveredVideoByStream.get(streamKey);\n if (!queue || queue.size === 0) return;\n\n const ready = [...queue.values()]\n .filter(frame => releases(frame.meta))\n .sort((a, b) => this.#comparePendingRecoveredVideo(a, b));\n\n for (const frame of ready) {\n queue.delete(this.#pendingRecoveredKey(frame.meta));\n this.#emitDirectVideo(packetId, frame.data, frame.meta, cb);\n }\n\n if (queue.size === 0) {\n this.#pendingDirectRecoveredVideoByStream.delete(streamKey);\n }\n }\n\n #enqueueDirectRecoveredVideo(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n ): void {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n const lastEmitted = this.#lastDirectEmittedVideoTsByStream.get(streamKey);\n if (lastEmitted !== undefined && meta.timestamp <= lastEmitted) return;\n\n const queue = this.#pendingRecoveredQueue(streamKey);\n queue.set(this.#pendingRecoveredKey(meta), { data, meta: { ...meta } });\n\n if (queue.size > DIRECT_RECOVERED_VIDEO_QUEUE_LIMIT) {\n const keep = [...queue.entries()]\n .sort((a, b) => this.#comparePendingRecoveredVideo(a[1], b[1]))\n .slice(-Math.floor(DIRECT_RECOVERED_VIDEO_QUEUE_LIMIT / 2));\n queue.clear();\n for (const [key, frame] of keep) queue.set(key, frame);\n }\n }\n\n #routeDirectSourceVideo(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n cb: FrameCallback | null,\n ): void {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);\n if (lastSourceTs === undefined || meta.timestamp > lastSourceTs) {\n this.#lastDirectSourceVideoTsByStream.set(streamKey, meta.timestamp);\n }\n\n // Recovered FEC may arrive before the source stream reaches the same media\n // time. Drain those gap fills immediately before the source frame that proves\n // the live cursor caught up, preserving the decoder dependency chain.\n this.#drainDirectRecoveredVideo(streamKey, packetId, frame => frame.timestamp <= meta.timestamp, cb);\n this.#emitDirectVideo(packetId, data, meta, cb);\n }\n\n #routeDirectRecoveredVideo(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n cb: FrameCallback | null,\n ): void {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n this.#enqueueDirectRecoveredVideo(packetId, data, meta);\n const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);\n this.#drainDirectRecoveredVideo(\n streamKey,\n packetId,\n frame => lastSourceTs === undefined || frame.timestamp <= lastSourceTs,\n cb,\n );\n }\n\n #pendingRecoveredAudioQueue(streamKey: string): Map<string, PendingRecoveredAudioFrame> {\n let queue = this.#pendingDirectRecoveredAudioByStream.get(streamKey);\n if (!queue) {\n queue = new Map();\n this.#pendingDirectRecoveredAudioByStream.set(streamKey, queue);\n }\n return queue;\n }\n\n #directAudioCursor(meta: RoutedFrameMeta): DirectAudioCursor {\n return {\n timestamp: meta.timestamp,\n // A recovered frame without transport sequence metadata must drain before\n // an equal-timestamp source horizon instead of remaining queued forever.\n sequenceNumber: meta.packetSequenceNumber ?? Number.MIN_SAFE_INTEGER,\n };\n }\n\n #compareDirectAudioCursor(a: DirectAudioCursor, b: DirectAudioCursor): number {\n if (a.timestamp !== b.timestamp) return a.timestamp - b.timestamp;\n return a.sequenceNumber - b.sequenceNumber;\n }\n\n #emitDirectAudio(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n cb: FrameCallback | null,\n ): boolean {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n const cursor = this.#directAudioCursor(meta);\n const lastEmitted = this.#lastDirectEmittedAudioCursorByStream.get(streamKey);\n if (\n lastEmitted !== undefined &&\n this.#compareDirectAudioCursor(cursor, lastEmitted) <= 0\n ) return false;\n this.#lastDirectEmittedAudioCursorByStream.set(streamKey, cursor);\n cb?.(data, meta);\n return true;\n }\n\n #emitDirectSourceAudio(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n cb: FrameCallback | null,\n ): void {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n const cursor = this.#directAudioCursor(meta);\n const lastEmitted = this.#lastDirectEmittedAudioCursorByStream.get(streamKey);\n const diag = this.#diagFor(packetId, meta.catalogTrackName);\n diag.directAudioSourceEmitted++;\n if (\n lastEmitted !== undefined &&\n this.#compareDirectAudioCursor(cursor, lastEmitted) <= 0\n ) {\n // Source packets already passed transport/parser validation. Preserve\n // them even when unordered multicast completion moves the callback\n // cursor backward; only recovered frames are optional stale gap fills.\n diag.directAudioSourceRegressions++;\n } else {\n this.#lastDirectEmittedAudioCursorByStream.set(streamKey, cursor);\n }\n cb?.(data, meta);\n }\n\n #drainDirectRecoveredAudioUpTo(\n streamKey: string,\n packetId: number,\n horizon: DirectAudioCursor,\n cb: FrameCallback | null,\n ): void {\n const queue = this.#pendingDirectRecoveredAudioByStream.get(streamKey);\n if (!queue || queue.size === 0) return;\n\n const ready = [...queue.values()]\n .filter(frame => this.#compareDirectAudioCursor(\n this.#directAudioCursor(frame.meta),\n horizon,\n ) <= 0)\n .sort((a, b) => this.#compareDirectAudioCursor(\n this.#directAudioCursor(a.meta),\n this.#directAudioCursor(b.meta),\n ));\n\n for (const frame of ready) {\n queue.delete(this.#pendingRecoveredKey(frame.meta));\n if (this.#emitDirectAudio(packetId, frame.data, frame.meta, cb)) {\n this.#diagFor(packetId, frame.meta.catalogTrackName)\n .directAudioRecoveredDrained++;\n } else {\n this.#diagFor(packetId, frame.meta.catalogTrackName)\n .directAudioRecoveredStaleDropped++;\n }\n }\n\n if (queue.size === 0) {\n this.#pendingDirectRecoveredAudioByStream.delete(streamKey);\n }\n }\n\n #routeDirectSourceAudio(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n cb: FrameCallback | null,\n ): void {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n const cursor = this.#directAudioCursor(meta);\n const lastSource = this.#lastDirectSourceAudioCursorByStream.get(streamKey);\n if (\n lastSource === undefined ||\n this.#compareDirectAudioCursor(cursor, lastSource) > 0\n ) {\n this.#lastDirectSourceAudioCursorByStream.set(streamKey, cursor);\n }\n this.#drainDirectRecoveredAudioUpTo(streamKey, packetId, cursor, cb);\n this.#emitDirectSourceAudio(packetId, data, meta, cb);\n }\n\n #routeDirectRecoveredAudio(\n packetId: number,\n data: Uint8Array,\n meta: RoutedFrameMeta,\n cb: FrameCallback | null,\n ): void {\n const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);\n const cursor = this.#directAudioCursor(meta);\n const lastEmitted = this.#lastDirectEmittedAudioCursorByStream.get(streamKey);\n if (\n lastEmitted !== undefined &&\n this.#compareDirectAudioCursor(cursor, lastEmitted) <= 0\n ) {\n this.#diagFor(packetId, meta.catalogTrackName)\n .directAudioRecoveredStaleDropped++;\n return;\n }\n\n const queue = this.#pendingRecoveredAudioQueue(streamKey);\n queue.set(this.#pendingRecoveredKey(meta), { data, meta: { ...meta } });\n this.#diagFor(packetId, meta.catalogTrackName).directAudioRecoveredQueued++;\n if (queue.size > DIRECT_RECOVERED_AUDIO_QUEUE_LIMIT) {\n const keep = [...queue.entries()]\n .sort((a, b) => this.#compareDirectAudioCursor(\n this.#directAudioCursor(a[1].meta),\n this.#directAudioCursor(b[1].meta),\n ))\n .slice(-Math.floor(DIRECT_RECOVERED_AUDIO_QUEUE_LIMIT / 2));\n queue.clear();\n for (const [key, frame] of keep) queue.set(key, frame);\n }\n\n const lastSource = this.#lastDirectSourceAudioCursorByStream.get(streamKey);\n if (lastSource !== undefined) {\n this.#drainDirectRecoveredAudioUpTo(streamKey, packetId, lastSource, cb);\n }\n }\n\n // \u2500\u2500 Private: FEC recovery routing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** Route WASM-recovered block through appropriate path based on container kind. */\n #routeRecoveredBlock(\n blockId: number,\n recovered: Uint8Array,\n ownerPacketId?: number,\n catalogTrackName?: string,\n ): void {\n // MMTP path: use processFecBlock for MMTP-wrapped recovery.\n // Recovered symbols are individual MMTP packets that may be fragments\n // (FI=1/2/3) of a larger MFU. Route through the reassembler so\n // multi-packet MFUs (e.g., keyframes spanning 15+ packets) are\n // properly assembled before reaching the decoder.\n const k = this.#kForPacket(ownerPacketId);\n const packetSymbolSize = this.#symbolSizeForPacket(ownerPacketId);\n if (ownerPacketId === undefined) {\n throw new Error(\"[MmtpRouter] a recovered FEC block needs its owner packetId to read its fec.blockProfile\");\n }\n const blockProfile = this.#blockProfileFor(ownerPacketId);\n if (!(packetSymbolSize > 0)) {\n throw new Error(\n `[MmtpRouter] recovered FEC block for packetId=${ownerPacketId} needs a configured ` +\n `symbol size (got T=${packetSymbolSize})`,\n );\n }\n const symbolSize = packetSymbolSize;\n // iso-ssbg1-v1 returns K' = SSB_length symbols; k-padded-v1 the authored\n // prefix of a K-symbol block, walked up to K.\n const result = processFecBlock(recovered, {\n ...(blockProfile === \"k-padded-v1\" ? { k } : {}),\n symbolSize,\n ownerPacketId,\n blockProfile,\n });\n this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);\n }\n\n #routeVerifiedFecSymbols(\n blockId: number,\n result: ProcessFecBlockResult,\n ownerPacketId?: number,\n catalogTrackName?: string,\n ): void {\n if (!this.#manifestVerifier || ownerPacketId == null) {\n this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);\n return;\n }\n if (!this.#resolveManifestIdentity && !this.#resolveManifestIdentityForRoute) {\n console.warn(`[MmtpRouter] manifest identity resolver unavailable; recovered media is fail-open for packetId=${ownerPacketId} block=${blockId}`);\n this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);\n return;\n }\n const queueKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);\n const queue = this.#manifestRecoveryQueues.get(queueKey) ?? [];\n queue.push({ blockId, result, ownerPacketId, catalogTrackName });\n this.#manifestRecoveryQueues.set(queueKey, queue);\n if (queue.length > 1) return;\n const drain = (): void => {\n const next = queue[0];\n if (!next) {\n this.#manifestRecoveryQueues.delete(queueKey);\n return;\n }\n this.#admitRecoveredResult(\n next.blockId,\n next.result,\n next.ownerPacketId,\n next.catalogTrackName,\n () => {\n queue.shift();\n drain();\n },\n );\n };\n drain();\n }\n\n #admitRecoveredResult(\n blockId: number,\n result: ProcessFecBlockResult,\n ownerPacketId: number,\n catalogTrackName: string | undefined,\n done: () => void,\n ): void {\n const verifier = this.#manifestVerifier;\n const resolveIdentity = this.#resolveManifestIdentity;\n const resolveIdentityForRoute = this.#resolveManifestIdentityForRoute;\n if (!verifier) {\n this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);\n done();\n return;\n }\n if (!resolveIdentity && !resolveIdentityForRoute) throw new Error(\"manifest identity resolver disappeared during admission\");\n const symbols = result.symbols;\n const admitNext = (index: number): void => {\n const symbol = symbols[index];\n if (!symbol) {\n done();\n return;\n }\n const identity = resolveIdentityForRoute\n ? resolveIdentityForRoute({\n packetId: ownerPacketId,\n sbn: blockId,\n esi: symbol.index,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n recovered: true,\n sourceSymbolFormat: \"fec-padded-recovery\",\n })\n : resolveIdentity!(ownerPacketId, blockId, symbol.index, catalogTrackName);\n if (!identity) {\n console.warn(`[MmtpRouter] manifest identity unresolved; recovered symbol is fail-open for packetId=${ownerPacketId} block=${blockId} esi=${symbol.index}`);\n this.#routeProcessedFecSymbols(\n blockId,\n { ...result, symbols: [symbol] },\n ownerPacketId,\n catalogTrackName,\n );\n admitNext(index + 1);\n return;\n }\n const admission = verifier.admitObject(\n {\n ...identity,\n packetId: ownerPacketId,\n ...(ownerPacketId !== undefined && this.#isIsoPacket(ownerPacketId)\n ? {}\n : { ssId: blockId * this.#kForPacket(ownerPacketId) + symbol.index }),\n },\n symbol.rawSymbol,\n () => {\n if (!this.#disposed) {\n this.#routeProcessedFecSymbols(\n blockId,\n { ...result, symbols: [symbol] },\n ownerPacketId,\n catalogTrackName,\n );\n }\n admitNext(index + 1);\n },\n // A stalled symbol that is later discarded instead of played must still\n // advance this loop; enforce mode never calls the release callback for\n // it (BLO-30095).\n () => admitNext(index + 1),\n );\n if (admission.action === \"drop\") admitNext(index + 1);\n };\n admitNext(0);\n }\n\n #routeProcessedFecSymbols(\n blockId: number,\n result: ProcessFecBlockResult,\n ownerPacketId?: number,\n catalogTrackName?: string,\n ): void {\n // Route recovered symbols to the track's callback. The ownerPacketId tells us\n // which track this block belongs to \u2014 resolves per-track, then legacy fallback.\n if (ownerPacketId == null) return; // no track association\n if (this.#classifyPacketId(ownerPacketId) === null) return; // unknown track\n this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);\n\n // A recovered symbol is a function of EVERY symbol that entered its block,\n // so its provenance is the block's, not the media path's. Repair symbols\n // routinely arrive over reliable QUIC (`feedRepairPacket`), so a block that\n // recovered with MoQ help produced bytes that never crossed a multicast\n // socket. Without this, recovered frames reached the decoder carrying no\n // attribution at all and were counted as multicast by default.\n // A FEC manager that cannot report block provenance yields 'unknown', not\n // a guess: these bytes are then never counted as physical-delivery\n // evidence. `FECManagerLike` is a pluggable structural interface, so an\n // implementation without this method must degrade, not throw.\n const deliveryProvenance: MmtpDeliveryProvenance =\n this.#fecManager?.blockDeliveryProvenance?.(\n blockId,\n ownerPacketId,\n catalogTrackName,\n ) ?? 'unknown';\n\n for (const sym of result.symbols) {\n this.#routeTrackPacket(sym.rawSymbol, ownerPacketId, sym.packetSequenceNumber, {\n recovered: true,\n skipFecPayloadId: true,\n catalogTrackName,\n deliveryProvenance,\n });\n }\n\n // Feed recovered metadata before routing data. FT=0 initializes the timing\n // resolver and FT=1 publishes the sample table that recovered FT=2 data\n // must resolve against. The parser's callbacks dedupe repeated init\n // delivery, while keeping this path in lockstep with direct source input.\n for (const sym of result.symbols) {\n if (sym.fragmentType !== 0 && sym.fragmentType !== 1) continue;\n this.#feedViaParser(\n sym.rawSymbol,\n { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },\n undefined,\n {\n skipFecPayloadId: true,\n recovered: true,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n },\n );\n }\n\n // MSE assembler path: route recovered block as pre-assembled frames (skip FT=0)\n // BLO-3035 layer 3: recovered symbols are RAW MFU fragments, not complete\n // frames. A keyframe can span multiple packets (FI=1/2/3); pushing each\n // fragment as a \"frame\" produces garbage moof+mdat that fails decode.\n // Mirror the non-MSE path's logic: FI=0 \u2192 emit single-packet MFU directly\n // (after dedup against source path), FI=1/2/3 \u2192 feed reassembler, emit when\n // the complete frame is available. Take the keyframe bit from the assembled\n // frame's rapFlag (with `#detectKeyframe` as a bitstream fallback for\n // publishers that don't set rapFlag) \u2014 `sym.isKeyframe` is just rapFlag\n // from a single fragment's header (see `block-processor.ts` where\n // `isKeyframe = hdr.rapFlag`) and isn't meaningful for the reassembled-\n // frame keyframe decision when FI\u22600.\n // FEC tracks release recovered frames through the parser's FEC release\n // gate, in authored order with the source frames they fill in for; the\n // frame callback then applies sync gating and MSE/direct dispatch once.\n const gated = this.#isFecTrack(ownerPacketId);\n const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);\n if (assembler) {\n // A staged switch holds and splices its two streams at the parser's\n // frame callback, and the ungated batch below would bypass it: the\n // incoming stream's recovered frames would be lost from the GOP it\n // replays at the commit, and the outgoing stream's could reach MSE past\n // the splice. Their recovered frames go through the parser instead, as\n // an FEC-gated track's always do.\n const staged = this.#staged;\n const owner = { packetId: ownerPacketId, catalogTrackName };\n const throughParser = gated ||\n (staged !== null && (isStream(owner, staged.from) || isStream(owner, staged.to)));\n const isVideoTrack = this.#classifyPacketId(ownerPacketId) === true;\n const frames: Array<{\n data: Uint8Array;\n timestamp: number;\n keyframe: boolean;\n authoredTiming?: AuthoredTiming;\n packetSequenceNumber?: number;\n packetSequenceNumbers?: number[];\n repairedPacketSequenceNumbers?: number[];\n mmtpTimestamp?: bigint;\n mpuSequenceNumber?: number;\n movieFragmentSequenceNumber?: number;\n sampleNumber?: number;\n catalogTrackName?: string;\n deliveryProvenance?: MmtpDeliveryProvenance;\n sourceDiscontinuity?: boolean;\n }> = [];\n let dedupedAgainstSource = 0;\n let droppedBeforeSync = 0;\n for (const sym of result.symbols) {\n // An in-place switch can retire this owner from inside this loop (a\n // recovered frame that reaches the splice); the rest have no route.\n if (this.#classifyPacketId(ownerPacketId) === null) return;\n if (sym.fragmentType === 0 || sym.fragmentType === 1) continue;\n // FT=0/FT=1 are MPU metadata (initialization/movie fragment), already\n // consumed above to seed the authored timing resolver. Only FT=2 MFU\n // payloads can become media samples here.\n const fi = sym.fragment.fragmentationIndicator;\n if (fi === 0) {\n // Single-packet MFU. Dedup against source path so frames aren't\n // emitted twice. The direct source frame may still be buffered by the\n // parser reorder window, so use source-received sequence numbers.\n if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {\n dedupedAgainstSource++;\n continue;\n }\n const keyframe = isVideoTrack\n ? this.#detectKeyframe(\n ownerPacketId,\n sym.fragment.data,\n isMfuKeyframeMetadata(sym.fragment.rapFlag, sym.fragment.priority),\n )\n : sym.fragment.rapFlag;\n if (throughParser) {\n const gatedTiming = this.#resolveRecoveredTiming(\n ownerPacketId,\n sym.fragment.mpuSequenceNumber,\n sym.fragment.movieFragmentSequenceNumber,\n sym.fragment.sampleNumber,\n sym.fragment.timestamp,\n catalogTrackName,\n );\n if (!gatedTiming) continue;\n this.#parser.routeFrame(sym.fragment.data, {\n timestamp: gatedTiming.timestamp,\n mmtpTimestamp: gatedTiming.mmtpTimestamp,\n ...(gatedTiming.authoredTiming === undefined\n ? {}\n : { authoredTiming: gatedTiming.authoredTiming }),\n keyframe: isVideoTrack ? keyframe : true,\n packetId: ownerPacketId,\n trackType: isVideoTrack ? \"video\" : \"audio\",\n packetSequenceNumber: sym.packetSequenceNumber,\n packetSequenceNumbers: [sym.packetSequenceNumber],\n repairedPacketSequenceNumbers: [sym.packetSequenceNumber],\n mpuSequenceNumber: sym.fragment.mpuSequenceNumber,\n ...(sym.fragment.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber }),\n ...(sym.fragment.sampleNumber === undefined\n ? {}\n : { sampleNumber: sym.fragment.sampleNumber }),\n rapFlag: sym.fragment.rapFlag,\n recovered: true,\n deliveryProvenance,\n fecSbn: this.#fecAnchorForRecovered(ownerPacketId, blockId, sym.index),\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n });\n continue;\n }\n const sourceDiscontinuity = this.#opensFecSync(\n ownerPacketId,\n keyframe,\n catalogTrackName,\n );\n if (!this.#shouldEmitFrame(ownerPacketId, keyframe, catalogTrackName)) {\n droppedBeforeSync++;\n continue;\n }\n const recoveredTiming = this.#resolveRecoveredTiming(\n ownerPacketId,\n sym.fragment.mpuSequenceNumber,\n sym.fragment.movieFragmentSequenceNumber,\n sym.fragment.sampleNumber,\n sym.fragment.timestamp,\n catalogTrackName,\n );\n if (!recoveredTiming) continue;\n frames.push({\n data: sym.fragment.data,\n timestamp: recoveredTiming.timestamp,\n mmtpTimestamp: recoveredTiming.mmtpTimestamp,\n keyframe,\n authoredTiming: recoveredTiming.authoredTiming,\n packetSequenceNumber: sym.packetSequenceNumber,\n packetSequenceNumbers: [sym.packetSequenceNumber],\n repairedPacketSequenceNumbers: [sym.packetSequenceNumber],\n mpuSequenceNumber: sym.fragment.mpuSequenceNumber,\n ...(sym.fragment.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber }),\n ...(sym.fragment.sampleNumber === undefined\n ? {}\n : { sampleNumber: sym.fragment.sampleNumber }),\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n // A single-packet MFU needs the block verdict just as much as a\n // reassembled one. The multi-fragment branch below gets it via the\n // reassembler fold (`assembled.deliveryProvenance`); this branch\n // never touches the reassembler, so it must carry the block-level\n // verdict directly or the sample reaches MSE unattributed.\n deliveryProvenance,\n ...(sourceDiscontinuity ? { sourceDiscontinuity: true } : {}),\n });\n this.#noteEmittedKeyframe(ownerPacketId, keyframe);\n } else {\n // Multi-packet MFU. Feed to reassembler; emit only when complete.\n // A decoded block contains every source symbol, including fragments\n // already accepted on the direct path. Re-feeding those fragments as\n // recovered would replace their original attribution in the shared\n // reassembler and overstate repairedPacketSequenceNumbers.\n if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {\n dedupedAgainstSource++;\n continue;\n }\n let assembled;\n try {\n assembled = this.#parser.reassembler.addFragment({\n fragmentationIndicator: fi,\n mpuSequenceNumber: sym.fragment.mpuSequenceNumber,\n fragmentCounter: sym.fragment.fragmentCounter,\n data: sym.fragment.data,\n timestamp: sym.fragment.timestamp,\n rapFlag: sym.fragment.rapFlag,\n sampleNumber: sym.fragment.sampleNumber,\n movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber,\n sampleOffset: sym.fragment.sampleOffset,\n priority: sym.fragment.priority,\n packetSequenceNumber: sym.packetSequenceNumber,\n recovered: true,\n // Without this the fold sees a fragment with neither `source`\n // nor a verdict, returns 'unknown', and the block-level finding\n // computed above is lost before the frame reaches any consumer.\n deliveryProvenance,\n packetId: ownerPacketId,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n });\n } catch (error) {\n if (!isMfuReassemblyError(error)) throw error;\n console.warn(\n `[MmtpRouter] dropped rejected recovered MFU fragment: block=${blockId} ` +\n `packetId=${ownerPacketId} code=${error.code}`,\n );\n continue;\n }\n if (assembled) {\n const keyframe = isVideoTrack\n ? this.#detectKeyframe(\n ownerPacketId,\n assembled.data,\n isMfuKeyframeMetadata(assembled.rapFlag, assembled.priority),\n )\n : assembled.rapFlag;\n const recoveredCatalogTrackName = assembled.catalogTrackName ?? catalogTrackName;\n if (throughParser) {\n const gatedTiming = this.#resolveRecoveredTiming(\n ownerPacketId,\n assembled.mpuSequenceNumber,\n assembled.movieFragmentSequenceNumber,\n assembled.sampleNumber,\n assembled.timestamp,\n recoveredCatalogTrackName,\n );\n if (!gatedTiming) continue;\n this.#parser.routeFrame(assembled.data, {\n timestamp: gatedTiming.timestamp,\n mmtpTimestamp: gatedTiming.mmtpTimestamp,\n ...(gatedTiming.authoredTiming === undefined\n ? {}\n : { authoredTiming: gatedTiming.authoredTiming }),\n keyframe: isVideoTrack ? keyframe : true,\n packetId: ownerPacketId,\n trackType: isVideoTrack ? \"video\" : \"audio\",\n packetSequenceNumber: sym.packetSequenceNumber,\n ...(assembled.packetSequenceNumbers === undefined\n ? {}\n : { packetSequenceNumbers: assembled.packetSequenceNumbers }),\n ...(assembled.repairedPacketSequenceNumbers === undefined\n ? {}\n : { repairedPacketSequenceNumbers: assembled.repairedPacketSequenceNumbers }),\n mpuSequenceNumber: assembled.mpuSequenceNumber,\n ...(assembled.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber }),\n ...(assembled.sampleNumber === undefined\n ? {}\n : { sampleNumber: assembled.sampleNumber }),\n rapFlag: assembled.rapFlag,\n recovered: true,\n ...(assembled.deliveryProvenance === undefined\n ? {}\n : { deliveryProvenance: assembled.deliveryProvenance }),\n fecSbn: this.#fecAnchorForRecovered(ownerPacketId, blockId, sym.index),\n ...(recoveredCatalogTrackName === undefined\n ? {}\n : { catalogTrackName: recoveredCatalogTrackName }),\n });\n continue;\n }\n const sourceDiscontinuity = this.#opensFecSync(\n ownerPacketId,\n keyframe,\n recoveredCatalogTrackName,\n );\n if (!this.#shouldEmitFrame(\n ownerPacketId,\n keyframe,\n recoveredCatalogTrackName,\n )) {\n droppedBeforeSync++;\n continue;\n }\n const recoveredTiming = this.#resolveRecoveredTiming(\n ownerPacketId,\n assembled.mpuSequenceNumber,\n assembled.movieFragmentSequenceNumber,\n assembled.sampleNumber,\n assembled.timestamp,\n recoveredCatalogTrackName,\n );\n if (!recoveredTiming) continue;\n frames.push({\n data: assembled.data,\n timestamp: recoveredTiming.timestamp,\n mmtpTimestamp: recoveredTiming.mmtpTimestamp,\n keyframe,\n authoredTiming: recoveredTiming.authoredTiming,\n // The singular delivery identity is the fragment that completed\n // and delivered the MFU, matching the callback/parser path.\n packetSequenceNumber: sym.packetSequenceNumber,\n ...(assembled.packetSequenceNumbers === undefined\n ? {}\n : { packetSequenceNumbers: assembled.packetSequenceNumbers }),\n ...(assembled.repairedPacketSequenceNumbers === undefined\n ? {}\n : {\n repairedPacketSequenceNumbers:\n assembled.repairedPacketSequenceNumbers,\n }),\n mpuSequenceNumber: assembled.mpuSequenceNumber,\n ...(assembled.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber }),\n ...(assembled.sampleNumber === undefined\n ? {}\n : { sampleNumber: assembled.sampleNumber }),\n ...(assembled.catalogTrackName === undefined\n ? {}\n : { catalogTrackName: assembled.catalogTrackName }),\n deliveryProvenance: assembled.deliveryProvenance,\n ...(sourceDiscontinuity ? { sourceDiscontinuity: true } : {}),\n });\n this.#noteEmittedKeyframe(ownerPacketId, keyframe);\n }\n }\n }\n if (frames.length > 0) {\n assembler.addRecoveredBlock(blockId, frames);\n // The assembler owns MSE writes, but the normal frame callback still\n // carries transport admission: MulticastManager uses it to confirm\n // video/audio and MediaRouter uses that confirmation to complete the\n // takeover. Recovered frames bypass parser.onFrame, so without this\n // callback MSE can receive samples forever while takeover never fires.\n const cb = this.#getFrameCallback(ownerPacketId);\n for (const frame of frames) {\n cb?.(frame.data, {\n timestamp: frame.timestamp,\n ...(frame.mmtpTimestamp === undefined ? {} : { mmtpTimestamp: frame.mmtpTimestamp }),\n keyframe: frame.keyframe,\n ...(frame.authoredTiming === undefined ? {} : { authoredTiming: frame.authoredTiming }),\n packetId: ownerPacketId,\n ...(frame.packetSequenceNumber === undefined\n ? {}\n : { packetSequenceNumber: frame.packetSequenceNumber }),\n ...(frame.packetSequenceNumbers === undefined\n ? {}\n : { packetSequenceNumbers: frame.packetSequenceNumbers }),\n ...(frame.repairedPacketSequenceNumbers === undefined\n ? {}\n : { repairedPacketSequenceNumbers: frame.repairedPacketSequenceNumbers }),\n ...(frame.mpuSequenceNumber === undefined ? {} : { mpuSequenceNumber: frame.mpuSequenceNumber }),\n ...(frame.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: frame.movieFragmentSequenceNumber }),\n ...(frame.sampleNumber === undefined ? {} : { sampleNumber: frame.sampleNumber }),\n ...(frame.catalogTrackName === undefined ? {} : { catalogTrackName: frame.catalogTrackName }),\n recovered: true,\n deliveryProvenance: frame.deliveryProvenance,\n ...(frame.sourceDiscontinuity ? { sourceDiscontinuity: true } : {}),\n });\n }\n debugRouter(\n `[MmtpRouter] Block ${blockId}: ${result.symbols.length} symbols \u2192 ${frames.length} reassembled frames \u2192 MSE assembler (packetId=${ownerPacketId}, dedupedAgainstSource=${dedupedAgainstSource}, droppedBeforeSync=${droppedBeforeSync})`,\n );\n } else if (result.symbols.length > 0) {\n // Recovery yielded symbols but no complete frames emerged \u2014 either all\n // FI=0 were source-path duplicates, or all FI=1/2/3 are still mid-\n // reassembly. Surface this so an operator debugging \"FEC recovered N\n // symbols but no new frames rendered\" has a signal.\n debugRouter(\n `[MmtpRouter] Block ${blockId}: ${result.symbols.length} symbols recovered \u2192 0 emitted (dedupedAgainstSource=${dedupedAgainstSource}, droppedBeforeSync=${droppedBeforeSync}, pending-reassembly=${result.symbols.length - dedupedAgainstSource - droppedBeforeSync}, packetId=${ownerPacketId})`,\n );\n }\n return;\n }\n\n const cb = this.#getFrameCallback(ownerPacketId);\n const isVideo = this.#classifyPacketId(ownerPacketId) === true;\n let droppedBeforeSync = 0;\n let droppedStale = 0;\n let dedupedAgainstSource = 0;\n\n for (const sym of result.symbols) {\n // An in-place switch can retire this owner from inside this loop (a\n // recovered frame that reaches the splice); the rest have no route.\n if (this.#classifyPacketId(ownerPacketId) === null) return;\n // FT=0 init already delivered above \u2014 skip data routing\n if (sym.fragmentType === 0 || sym.fragmentType === 1) continue;\n // FT=0/FT=1 are metadata, not decoder samples. The metadata pass above\n // has already used them to establish the timed-MFU contract.\n\n if (isVideo) {\n const fi = sym.fragment.fragmentationIndicator;\n if (fi === 0) {\n // Dedup: skip FI=0 frames already received via direct source path.\n // The reassembler deduplicates FI=1/2/3 fragments via #emitted, but\n // FI=0 (single-packet MFU) bypasses it. Without this check, recovery\n // can re-emit a source frame that is only held in the reorder buffer,\n // producing duplicate timestamps when the source path later flushes.\n if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {\n dedupedAgainstSource++;\n continue;\n }\n if (this.#isStaleRecoveredVideo(\n ownerPacketId,\n sym.packetSequenceNumber,\n catalogTrackName,\n )) {\n droppedStale++;\n continue;\n }\n\n const d = sym.fragment.data;\n const keyframe = this.#detectKeyframe(\n ownerPacketId,\n d,\n isMfuKeyframeMetadata(sym.fragment.rapFlag, sym.fragment.priority),\n );\n const recoveredTiming = this.#resolveRecoveredTiming(\n ownerPacketId,\n sym.fragment.mpuSequenceNumber,\n sym.fragment.movieFragmentSequenceNumber,\n sym.fragment.sampleNumber,\n sym.fragment.timestamp,\n catalogTrackName,\n );\n if (!recoveredTiming) continue;\n this.#parser.routeFrame(d, {\n timestamp: recoveredTiming.timestamp,\n mmtpTimestamp: recoveredTiming.mmtpTimestamp,\n authoredTiming: recoveredTiming.authoredTiming,\n keyframe,\n packetId: ownerPacketId,\n trackType: \"video\",\n packetSequenceNumber: sym.packetSequenceNumber,\n packetSequenceNumbers: [sym.packetSequenceNumber],\n repairedPacketSequenceNumbers: [sym.packetSequenceNumber],\n mpuSequenceNumber: sym.fragment.mpuSequenceNumber,\n ...(sym.fragment.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber }),\n ...(sym.fragment.sampleNumber === undefined\n ? {}\n : { sampleNumber: sym.fragment.sampleNumber }),\n rapFlag: sym.fragment.rapFlag,\n recovered: true,\n deliveryProvenance,\n fecSbn: this.#fecAnchorForRecovered(ownerPacketId, blockId, sym.index),\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n });\n } else {\n // Fragment of a multi-packet MFU \u2014 must go through reassembler\n if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {\n dedupedAgainstSource++;\n continue;\n }\n let assembled;\n try {\n assembled = this.#parser.reassembler.addFragment({\n fragmentationIndicator: fi,\n mpuSequenceNumber: sym.fragment.mpuSequenceNumber,\n fragmentCounter: sym.fragment.fragmentCounter,\n data: sym.fragment.data,\n timestamp: sym.fragment.timestamp,\n rapFlag: sym.fragment.rapFlag,\n sampleNumber: sym.fragment.sampleNumber,\n movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber,\n sampleOffset: sym.fragment.sampleOffset,\n priority: sym.fragment.priority,\n packetSequenceNumber: sym.packetSequenceNumber,\n recovered: true,\n // Without this the fold sees a fragment with neither `source`\n // nor a verdict, returns 'unknown', and the block-level finding\n // computed above is lost before the frame reaches any consumer.\n deliveryProvenance,\n packetId: ownerPacketId,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n });\n } catch (error) {\n if (!isMfuReassemblyError(error)) throw error;\n console.warn(\n `[MmtpRouter] dropped rejected recovered MFU fragment: block=${blockId} ` +\n `packetId=${ownerPacketId} code=${error.code}`,\n );\n continue;\n }\n if (assembled) {\n if (this.#isStaleRecoveredVideo(\n ownerPacketId,\n sym.packetSequenceNumber,\n assembled.catalogTrackName,\n )) {\n droppedStale++;\n continue;\n }\n const keyframe = this.#detectKeyframe(\n ownerPacketId,\n assembled.data,\n isMfuKeyframeMetadata(assembled.rapFlag, assembled.priority),\n );\n const recoveredCatalogTrackName = assembled.catalogTrackName ?? catalogTrackName;\n const recoveredTiming = this.#resolveRecoveredTiming(\n ownerPacketId,\n assembled.mpuSequenceNumber,\n assembled.movieFragmentSequenceNumber,\n assembled.sampleNumber,\n assembled.timestamp,\n recoveredCatalogTrackName,\n );\n if (!recoveredTiming) continue;\n this.#parser.routeFrame(assembled.data, {\n timestamp: recoveredTiming.timestamp,\n mmtpTimestamp: recoveredTiming.mmtpTimestamp,\n authoredTiming: recoveredTiming.authoredTiming,\n keyframe,\n packetId: ownerPacketId,\n trackType: \"video\",\n packetSequenceNumber: sym.packetSequenceNumber,\n ...(assembled.packetSequenceNumbers === undefined\n ? {}\n : { packetSequenceNumbers: assembled.packetSequenceNumbers }),\n ...(assembled.repairedPacketSequenceNumbers === undefined\n ? {}\n : {\n repairedPacketSequenceNumbers:\n assembled.repairedPacketSequenceNumbers,\n }),\n mpuSequenceNumber: assembled.mpuSequenceNumber,\n ...(assembled.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber }),\n ...(assembled.sampleNumber === undefined\n ? {}\n : { sampleNumber: assembled.sampleNumber }),\n rapFlag: assembled.rapFlag,\n recovered: true,\n deliveryProvenance,\n fecSbn: this.#fecAnchorForRecovered(ownerPacketId, blockId, sym.index),\n ...(assembled.catalogTrackName === undefined\n ? {}\n : { catalogTrackName: assembled.catalogTrackName }),\n });\n }\n }\n } else {\n // Audio recovery: dedup single-packet MFUs already emitted via direct source path\n // (parity with video FI=0 path at line 993). Prevents re-delivering audio frames\n // with duplicate timestamps \u2014 doubled samples in the FIFO ring buffer corrupt the\n // 1kHz test tone (pitch/energy instability in FFT spectrum).\n if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {\n dedupedAgainstSource++;\n continue;\n }\n const recoveredTiming = this.#resolveRecoveredTiming(\n ownerPacketId,\n sym.fragment.mpuSequenceNumber,\n sym.fragment.movieFragmentSequenceNumber,\n sym.fragment.sampleNumber,\n sym.fragment.timestamp,\n catalogTrackName,\n );\n if (recoveredTiming === null) continue;\n if (gated) {\n this.#parser.routeFrame(sym.fragment.data, {\n timestamp: recoveredTiming.timestamp,\n mmtpTimestamp: recoveredTiming.mmtpTimestamp,\n ...(recoveredTiming.authoredTiming === undefined\n ? {}\n : { authoredTiming: recoveredTiming.authoredTiming }),\n keyframe: true,\n packetId: ownerPacketId,\n trackType: \"audio\",\n packetSequenceNumber: sym.packetSequenceNumber,\n packetSequenceNumbers: [sym.packetSequenceNumber],\n repairedPacketSequenceNumbers: [sym.packetSequenceNumber],\n mpuSequenceNumber: sym.fragment.mpuSequenceNumber,\n ...(sym.fragment.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber }),\n ...(sym.fragment.sampleNumber === undefined\n ? {}\n : { sampleNumber: sym.fragment.sampleNumber }),\n recovered: true,\n deliveryProvenance,\n fecSbn: this.#fecAnchorForRecovered(ownerPacketId, blockId, sym.index),\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n });\n continue;\n }\n const meta = {\n timestamp: recoveredTiming.timestamp,\n mmtpTimestamp: recoveredTiming.mmtpTimestamp,\n authoredTiming: recoveredTiming.authoredTiming,\n keyframe: true,\n packetId: ownerPacketId,\n packetSequenceNumber: sym.packetSequenceNumber,\n packetSequenceNumbers: [sym.packetSequenceNumber],\n repairedPacketSequenceNumbers: [sym.packetSequenceNumber],\n mpuSequenceNumber: sym.fragment.mpuSequenceNumber,\n ...(sym.fragment.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber }),\n ...(sym.fragment.sampleNumber === undefined\n ? {}\n : { sampleNumber: sym.fragment.sampleNumber }),\n recovered: true,\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n };\n this.#routeDirectRecoveredAudio(\n ownerPacketId,\n sym.fragment.data,\n meta,\n cb,\n );\n }\n }\n if (result.symbols.length > 0) {\n debugRouter(\n `[MmtpRouter] Block ${blockId}: ${result.symbols.length} symbols recovered (packetId=${ownerPacketId}, dedupedAgainstSource=${dedupedAgainstSource}, droppedBeforeSync=${droppedBeforeSync}, droppedStale=${droppedStale})`,\n );\n }\n }\n\n // \u2500\u2500 Private: keyframe detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 /** Codec-aware keyframe detection from bitstream data.\n * H.264 IDR (NAL type 5/7), AV1 OBU_SEQUENCE_HEADER (type 1), VP9 frame_type bit. */\n #detectKeyframe(\n packetId: number,\n data: Uint8Array,\n rapFlag = false,\n ): boolean {\n const codec = this.#trackCodecs.get(packetId) ?? \"\";\n return MmtpContainerParser.isKeyframe(data, rapFlag, codec);\n }\n}\n", "/**\n * MMTP \u2192 CMAF converter per draft-ramadan-moq-mmt \u00A75.3.\n *\n * Converts reassembled MFU frames (raw codec samples from MMTP) into\n * fMP4 segments (moof+mdat) suitable for MSE SourceBuffer.appendBuffer().\n *\n * MPU metadata (fragment_type=0) packets from FFmpeg are complete\n * ftyp+moov init segments and can be used directly as MSE init data.\n *\n * MFU data (fragment_type=2) contains raw AVCC samples that must be\n * wrapped in moof+mdat boxes for MSE consumption.\n *\n * ISO 14496-12 (ISOBMFF) box construction is inline \u2014 no dependencies.\n */\n\n// \u2500\u2500 ISOBMFF box helpers \u2500\u2500\n\nfunction box(type: string, ...children: Uint8Array[]): Uint8Array {\n let size = 8\n for (const c of children) size += c.length\n const buf = new Uint8Array(size)\n new DataView(buf.buffer).setUint32(0, size)\n buf[4] = type.charCodeAt(0)\n buf[5] = type.charCodeAt(1)\n buf[6] = type.charCodeAt(2)\n buf[7] = type.charCodeAt(3)\n let pos = 8\n for (const c of children) {\n buf.set(c, pos)\n pos += c.length\n }\n return buf\n}\n\nfunction fullBox(type: string, version: number, flags: number, ...children: Uint8Array[]): Uint8Array {\n let size = 12\n for (const c of children) size += c.length\n const buf = new Uint8Array(size)\n const dv = new DataView(buf.buffer)\n dv.setUint32(0, size)\n buf[4] = type.charCodeAt(0)\n buf[5] = type.charCodeAt(1)\n buf[6] = type.charCodeAt(2)\n buf[7] = type.charCodeAt(3)\n dv.setUint32(8, (version << 24) | (flags & 0xffffff))\n let pos = 12\n for (const c of children) {\n buf.set(c, pos)\n pos += c.length\n }\n return buf\n}\n\nfunction u32(v: number): Uint8Array {\n const b = new Uint8Array(4)\n new DataView(b.buffer).setUint32(0, v)\n return b\n}\n\n// \u2500\u2500 Sample flags per ISO 14496-12 \u00A78.8.3.1 \u2500\u2500\nconst KEYFRAME_FLAGS = 0x02000000\nconst DELTA_FLAGS = 0x01010000\n\n// \u2500\u2500 Track geometry field ranges per ISO 14496-12 \u2500\u2500\n// tkhd/trex/tfhd track_ID and the mdhd/mvhd timescales are all unsigned 32-bit\n// fields, written below with DataView.setUint32. That call takes the value\n// modulo 2^32 without complaint, so an out-of-range configuration does not\n// fail \u2014 it silently emits different geometry than the caller asked for\n// (trackId 2^32 becomes track 0, which no fragment can ever reference).\nconst UINT32_MAX = 0xffffffff\n// mvhd next_track_ID is emitted as track_ID + 1 by both buildVideoInitSegment\n// and buildAudioInitSegment (ISO 14496-12 \u00A78.2.2.3, \"a non-zero integer\"). At\n// track_ID = UINT32_MAX that sum wraps to 0, which is both invalid and\n// indistinguishable from an unset field, so the largest usable track_ID is one\n// below the field maximum. (Cited by symbol, not line: this repo's docs gate\n// exists because line anchors rot silently \u2014 see rustfmt.yml's citation check.)\nconst MAX_TRACK_ID = UINT32_MAX - 1\nconst INT32_MIN = -0x80000000\nconst INT32_MAX = 0x7fffffff\n\n/**\n * Fail closed on a track_ID the fMP4 writers below cannot serialize faithfully.\n *\n * Called from both low-level encoders (encodeDataSegment,\n * encodeMultiSampleSegment) so every fragment path is covered by construction\n * rather than by enumerating callers. The class wrappers and init builders call\n * it earlier as well \u2014 partly for a clearer label, partly because the encoders\n * receive an already-incremented sequence number, so their throw would gap the\n * sequence on a call that emitted nothing.\n */\nfunction assertTrackId(trackId: number, label: string): void {\n if (!Number.isInteger(trackId) || trackId <= 0 || trackId > MAX_TRACK_ID) {\n throw new RangeError(`${label} must be an integer in 1..${MAX_TRACK_ID}, got ${trackId}`)\n }\n}\n\n/** Fail closed on a timescale the mdhd/mvhd uint32 fields cannot hold. */\nfunction assertTimescale(timescale: number, label: string): void {\n if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {\n throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`)\n }\n}\n\n/** Fail closed on a signed trun sample_composition_time_offset. */\nfunction assertCompositionTimeOffsets(\n samples: Array<{ compositionTimeOffset?: number }>,\n): void {\n for (let i = 0; i < samples.length; i++) {\n const offset = samples[i]!.compositionTimeOffset\n if (offset !== undefined &&\n (!Number.isInteger(offset) || offset < INT32_MIN || offset > INT32_MAX)) {\n throw new RangeError(\n `sample ${i} compositionTimeOffset must be an integer in ${INT32_MIN}..${INT32_MAX}, got ${offset}`,\n )\n }\n }\n}\n\n/**\n * Wrap multiple samples in a single moof+mdat fMP4 segment.\n *\n * Builds a trun with N sample entries (duration + size + flags each).\n * Used by CmafBlockAssembler to emit one segment per FEC source block.\n *\n * @param samples - Array of samples with data, duration (timescale units), keyframe flag,\n * and an optional signed composition-time offset (same timescale units)\n * @param baseDecodeTime - Decode time of the first sample in timescale units\n * @param sequence - moof sequence number\n * @param trackId - ISO track ID (default 1)\n * @returns moof+mdat bytes ready for SourceBuffer.appendBuffer()\n */\nexport function encodeMultiSampleSegment(\n samples: Array<{\n data: Uint8Array\n duration: number\n keyframe: boolean\n compositionTimeOffset?: number\n }>,\n baseDecodeTime: number,\n sequence: number,\n trackId = 1,\n): Uint8Array {\n if (samples.length === 0) return new Uint8Array(0)\n assertTrackId(trackId, 'trackId')\n assertCompositionTimeOffsets(samples)\n\n const mfhd = fullBox('mfhd', 0, 0, u32(sequence))\n const tfhd = fullBox('tfhd', 0, 0x020000, u32(trackId))\n\n // tfdt version=1 for 64-bit baseMediaDecodeTime\n const tfdtBody = new Uint8Array(8)\n const tfdtView = new DataView(tfdtBody.buffer)\n tfdtView.setUint32(0, Math.floor(baseDecodeTime / 0x100000000))\n tfdtView.setUint32(4, baseDecodeTime >>> 0)\n const tfdt = fullBox('tfdt', 1, 0, tfdtBody)\n\n // A composition-time offset is signed only in trun version 1. When one is\n // present, every sample gets the field; omitted offsets are encoded as zero.\n const hasCompositionTimeOffset = samples.some(sample => sample.compositionTimeOffset !== undefined)\n const trunVersion = hasCompositionTimeOffset ? 1 : 0\n const trunFlags = 0x000701 | (hasCompositionTimeOffset ? 0x000800 : 0)\n // 4 bytes sample_count + 4 bytes data_offset + N * (4+4+4 [+4]) per sample\n const sampleCount = samples.length\n const sampleEntrySize = hasCompositionTimeOffset ? 16 : 12\n const trunBody = new Uint8Array(8 + sampleCount * sampleEntrySize)\n const trunView = new DataView(trunBody.buffer)\n trunView.setUint32(0, sampleCount)\n trunView.setUint32(4, 0) // dataOffset placeholder\n for (let i = 0; i < sampleCount; i++) {\n const s = samples[i]!\n const off = 8 + i * sampleEntrySize\n trunView.setUint32(off, s.duration >>> 0)\n trunView.setUint32(off + 4, s.data.length)\n trunView.setUint32(off + 8, s.keyframe ? KEYFRAME_FLAGS : DELTA_FLAGS)\n if (hasCompositionTimeOffset) {\n trunView.setInt32(off + 12, s.compositionTimeOffset ?? 0)\n }\n }\n const trun = fullBox('trun', trunVersion, trunFlags, trunBody)\n\n const traf = box('traf', tfhd, tfdt, trun)\n const moof = box('moof', mfhd, traf)\n\n // Concatenate all sample data into mdat\n let mdatSize = 0\n for (const s of samples) mdatSize += s.data.length\n const mdatPayload = new Uint8Array(mdatSize)\n let pos = 0\n for (const s of samples) {\n mdatPayload.set(s.data, pos)\n pos += s.data.length\n }\n const mdat = box('mdat', mdatPayload)\n\n // Fix trun.dataOffset: moof size + 8 (mdat box header)\n const dataOffsetPos = 8 + mfhd.length + 8 + tfhd.length + tfdt.length + 12 + 4\n new DataView(moof.buffer).setUint32(dataOffsetPos, moof.length + 8)\n\n const result = new Uint8Array(moof.length + mdat.length)\n result.set(moof, 0)\n result.set(mdat, moof.length)\n return result\n}\n\n// \u2500\u2500 Silence generator \u2500\u2500\n\n/**\n * Generate a minimal silent audio frame for FEC fill.\n *\n * Supports AAC (mp4a) and Opus codecs. Returns raw frame data (no ADTS/OBU\n * header) suitable for fMP4/CMAF wrapping.\n *\n * @param codec - Audio codec string (e.g. 'mp4a.40.2', 'opus')\n * @param sampleRate - Audio sample rate (e.g. 48000)\n * @param channels - Channel count (e.g. 1 or 2)\n */\nexport function generateSilenceFrame(codec: string, sampleRate: number, channels: number): Uint8Array {\n if (codec.startsWith('opus') || codec.startsWith('Opus')) {\n return generateSilenceOpus(channels)\n }\n return generateSilenceAAC(sampleRate, channels)\n}\n\n/** Minimal silent AAC-LC access unit (raw, no ADTS). */\nfunction generateSilenceAAC(sampleRate: number, channels: number): Uint8Array {\n if (channels >= 2) {\n // CPE (channel pair element) + END\n return new Uint8Array([\n 0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80,\n ])\n }\n // SCE (single channel element) + END\n return new Uint8Array([\n 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,\n ])\n}\n\n/** Minimal silent Opus frame.\n * RFC 6716 \u00A73.1: a 1-byte frame with code 0 encodes silence for SILK/CELT. */\nfunction generateSilenceOpus(channels: number): Uint8Array {\n // Opus TOC byte: config=0 (SILK NB 10ms), s=0 (mono/stereo from channel mapping), c=0 (1 frame)\n // Frame data: single zero byte \u2192 silence\n // For stereo, channel mapping in fMP4 init handles routing; the Opus frame itself is the same.\n return new Uint8Array([0xF8, 0xFF, 0xFE])\n}\n\nexport function normalizeAacSampleForCmaf(data: Uint8Array): Uint8Array {\n if (data.length < 7 || data[0] !== 0xff || (data[1]! & 0xf6) !== 0xf0) {\n return data\n }\n const headerLength = (data[1]! & 0x01) ? 7 : 9\n if (data.length <= headerLength) return data\n const frameLength = ((data[3]! & 0x03) << 11) | (data[4]! << 3) | ((data[5]! & 0xe0) >>> 5)\n if (frameLength !== data.length || frameLength <= headerLength) return data\n return data.subarray(headerLength)\n}\n\n/**\n * Wrap a single raw codec sample in a moof+mdat fMP4 segment.\n *\n * @param data - Raw sample bytes (AVCC H.264 or raw AAC)\n * @param timestamp - Decode time in timescale units\n * @param duration - Sample duration in timescale units\n * @param keyframe - true for IDR/sync sample\n * @param sequence - moof sequence number (monotonically incrementing)\n * @param trackId - ISO track ID (default 1)\n * @returns moof+mdat bytes ready for SourceBuffer.appendBuffer()\n */\nexport function encodeDataSegment(\n data: Uint8Array,\n timestamp: number,\n duration: number,\n keyframe: boolean,\n sequence: number,\n trackId = 1,\n compositionTimeOffset?: number,\n): Uint8Array {\n assertTrackId(trackId, 'trackId')\n assertCompositionTimeOffsets([{ compositionTimeOffset }])\n if (compositionTimeOffset !== undefined) {\n return encodeMultiSampleSegment(\n [{ data, duration, keyframe, compositionTimeOffset }],\n timestamp,\n sequence,\n trackId,\n )\n }\n const sampleFlags = keyframe ? KEYFRAME_FLAGS : DELTA_FLAGS\n\n const mfhd = fullBox('mfhd', 0, 0, u32(sequence))\n const tfhd = fullBox('tfhd', 0, 0x020000, u32(trackId))\n\n // tfdt version=1 for 64-bit baseMediaDecodeTime\n const tfdtBody = new Uint8Array(8)\n const tfdtView = new DataView(tfdtBody.buffer)\n tfdtView.setUint32(0, Math.floor(timestamp / 0x100000000))\n tfdtView.setUint32(4, timestamp >>> 0)\n const tfdt = fullBox('tfdt', 1, 0, tfdtBody)\n\n // trun: flags=0x000701 (data-offset + duration + size + flags)\n const trunBody = new Uint8Array(20)\n const trunView = new DataView(trunBody.buffer)\n trunView.setUint32(0, 1) // sample_count\n trunView.setUint32(4, 0) // dataOffset placeholder\n trunView.setUint32(8, duration >>> 0)\n trunView.setUint32(12, data.length)\n trunView.setUint32(16, sampleFlags)\n const trun = fullBox('trun', 0, 0x000701, trunBody)\n\n const traf = box('traf', tfhd, tfdt, trun)\n const moof = box('moof', mfhd, traf)\n const mdat = box('mdat', data)\n\n // Fix trun.dataOffset: moof size + 8 (mdat box header)\n const dataOffsetPos = 8 + mfhd.length + 8 + tfhd.length + tfdt.length + 12 + 4\n new DataView(moof.buffer).setUint32(dataOffsetPos, moof.length + 8)\n\n const result = new Uint8Array(moof.length + mdat.length)\n result.set(moof, 0)\n result.set(mdat, moof.length)\n return result\n}\n\n/**\n * Build an ftyp+moov init segment for H.264 video MSE from an avcC box.\n *\n * @param avcC - Raw avcC box payload (SPS/PPS configuration)\n * @param width - Video width in pixels\n * @param height - Video height in pixels\n * @param timescale - Timescale (default 1_000_000 = microseconds)\n * @param trackId - Track ID (default 1)\n */\nexport function buildVideoInitSegment(\n avcC: Uint8Array,\n width: number,\n height: number,\n timescale = 1_000_000,\n trackId = 1,\n): Uint8Array {\n return buildVisualInitSegment('avc1', 'avcC', avcC, width, height, timescale, trackId)\n}\n\n/**\n * Build an ftyp+moov init segment for H.265/HEVC video MSE.\n *\n * The sample entry is `hev1` or `hvc1` (ISO/IEC 14496-15 \u00A78.4.1.1) carrying an\n * `hvcC` HEVCDecoderConfigurationRecord (\u00A78.3.3.1). Choose the entry from the\n * catalog codec string's first element, never by inspecting the bitstream:\n * `hev1` permits VPS/SPS/PPS to stay in-band in the samples (cast's\n * `repeat-headers=1` stream), `hvc1` requires every parameter set in the\n * `hvcC` and none in the samples.\n *\n * @param sampleEntry - `hev1` or `hvc1`\n * @param hvcC - Raw hvcC record payload (e.g. from `generateHvcCFromParameterSets`)\n * @param width - Video width in pixels\n * @param height - Video height in pixels\n * @param timescale - Media timescale\n * @param trackId - ISO track ID\n */\nexport function buildHevcVideoInitSegment(\n sampleEntry: 'hev1' | 'hvc1',\n hvcC: Uint8Array,\n width: number,\n height: number,\n timescale: number,\n trackId: number,\n): Uint8Array {\n if (sampleEntry !== 'hev1' && sampleEntry !== 'hvc1') {\n throw new Error(`HEVC init segment requires an hev1 or hvc1 sample entry, got ${String(sampleEntry)}`)\n }\n return buildVisualInitSegment(sampleEntry, 'hvcC', hvcC, width, height, timescale, trackId)\n}\n\n/**\n * ftyp+moov for one video track whose VisualSampleEntry (ISO/IEC 14496-12\n * \u00A712.1.3) carries a single codec configuration box. AVC (`avc1`/`avcC`) and\n * HEVC (`hev1`|`hvc1`/`hvcC`) share this layout byte for byte.\n */\nfunction buildVisualInitSegment(\n sampleEntryType: 'avc1' | 'hev1' | 'hvc1',\n configBoxType: 'avcC' | 'hvcC',\n configRecord: Uint8Array,\n width: number,\n height: number,\n timescale: number,\n trackId: number,\n): Uint8Array {\n // Validated here as well as in setVideoTrackParams: the builders are exported\n // from the package index, so a direct caller reaches the same uint32 tkhd /\n // trex / mdhd / mvhd fields without passing through the class.\n assertTrackId(trackId, 'video trackId')\n assertTimescale(timescale, 'video timescale')\n const ftyp = box('ftyp', new Uint8Array([\n 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0,\n 0x69, 0x73, 0x6f, 0x6d,\n 0x69, 0x73, 0x6f, 0x36,\n 0x6d, 0x70, 0x34, 0x31,\n ]))\n\n const configBox = box(configBoxType, configRecord)\n const sampleEntryBody = new Uint8Array(78 + configBox.length)\n const sampleEntryView = new DataView(sampleEntryBody.buffer)\n sampleEntryView.setUint16(6, 1)\n sampleEntryView.setUint16(24, width)\n sampleEntryView.setUint16(26, height)\n sampleEntryView.setUint32(28, 0x00480000)\n sampleEntryView.setUint32(32, 0x00480000)\n sampleEntryView.setUint16(40, 1)\n sampleEntryView.setUint16(74, 0x0018)\n sampleEntryView.setInt16(76, -1)\n sampleEntryBody.set(configBox, 78)\n const visualSampleEntry = box(sampleEntryType, sampleEntryBody)\n\n const stsd = fullBox('stsd', 0, 0, u32(1), visualSampleEntry)\n const stbl = box('stbl', stsd,\n fullBox('stts', 0, 0, u32(0)),\n fullBox('stsc', 0, 0, u32(0)),\n fullBox('stsz', 0, 0, u32(0), u32(0)),\n fullBox('stco', 0, 0, u32(0)),\n )\n const dinf = box('dinf', fullBox('dref', 0, 0, u32(1), fullBox('url ', 0, 1)))\n // ISO/IEC 14496-12 \u00A712.1.2: VideoMediaHeaderBox is a FullBox (flags = 1)\n // followed by graphicsmode (uint16) and opcolor (uint16[3]), all zero for\n // copy mode. WebKit's MSE parser rejects the whole init segment when those\n // 8 bytes are missing (SourceBuffer error on iPhone Safari); Chromium\n // tolerates it, which is how the short box went unnoticed.\n const minf = box('minf', fullBox('vmhd', 0, 1, new Uint8Array(8)), dinf, stbl)\n const hdlr = fullBox('hdlr', 0, 0, new Uint8Array([\n 0, 0, 0, 0, 0x76, 0x69, 0x64, 0x65,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0x56, 0x69, 0x64, 0x65, 0x6f, 0,\n ]))\n const mdhdBody = new Uint8Array(20)\n new DataView(mdhdBody.buffer).setUint32(8, timescale)\n const mdhd = fullBox('mdhd', 0, 0, mdhdBody)\n const mdia = box('mdia', mdhd, hdlr, minf)\n\n const tkhdBody = new Uint8Array(80)\n const tkhdView = new DataView(tkhdBody.buffer)\n tkhdView.setUint32(8, trackId)\n tkhdView.setUint32(36, 0x00010000)\n tkhdView.setUint32(52, 0x00010000)\n tkhdView.setUint32(64, 0x40000000)\n tkhdView.setUint32(72, width << 16)\n tkhdView.setUint32(76, height << 16)\n const tkhd = fullBox('tkhd', 0, 3, tkhdBody)\n const trak = box('trak', tkhd, mdia)\n\n const mvhdBody = new Uint8Array(96)\n const mvhdView = new DataView(mvhdBody.buffer)\n mvhdView.setUint32(8, timescale)\n mvhdView.setUint32(16, 0x00010000)\n mvhdView.setUint16(20, 0x0100)\n mvhdView.setUint32(32, 0x00010000)\n mvhdView.setUint32(48, 0x00010000)\n mvhdView.setUint32(60, 0x40000000)\n mvhdView.setUint32(92, trackId + 1)\n const mvhd = fullBox('mvhd', 0, 0, mvhdBody)\n\n const trexBody = new Uint8Array(20)\n new DataView(trexBody.buffer).setUint32(0, trackId)\n new DataView(trexBody.buffer).setUint32(4, 1)\n const mvex = box('mvex', fullBox('trex', 0, 0, trexBody))\n\n const moov = box('moov', mvhd, trak, mvex)\n const result = new Uint8Array(ftyp.length + moov.length)\n result.set(ftyp, 0)\n result.set(moov, ftyp.length)\n return result\n}\n\n/**\n * Build ftyp+moov init segment for AAC audio MSE.\n */\nexport function buildAudioInitSegment(\n sampleRate: number,\n channels: number,\n asc?: Uint8Array,\n timescale?: number,\n trackId = 1,\n): Uint8Array {\n // Validated here as well as in setAudioTimescale, for the same reason the\n // video builder is: this function is exported from the package index, so a\n // direct caller reaches the same uint32 tkhd / trex / mdhd / mvhd fields\n // without passing through the class.\n assertTrackId(trackId, 'audio trackId')\n const ts = timescale ?? sampleRate\n assertTimescale(ts, 'audio timescale')\n\n if (!asc) {\n const freqTable = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]\n const fi = freqTable.indexOf(sampleRate)\n const freqIdx = fi >= 0 ? fi : 0x0f\n if (freqIdx <= 0x0e) {\n const v = (2 << 11) | (freqIdx << 7) | (channels << 3)\n asc = new Uint8Array([(v >> 8) & 0xff, v & 0xff])\n } else {\n asc = new Uint8Array([\n (2 << 3) | 0x07,\n (0x08 | ((sampleRate >> 20) & 0x07)) & 0xff,\n (sampleRate >> 12) & 0xff,\n (sampleRate >> 4) & 0xff,\n (((sampleRate & 0x0f) << 4) | (channels << 0)) & 0xff,\n ])\n }\n }\n\n // esds: ES_Descriptor \u2192 DecoderConfigDescriptor \u2192 AudioSpecificConfig\n const dsi = new Uint8Array(2 + asc.length)\n dsi[0] = 0x05; dsi[1] = asc.length; dsi.set(asc, 2)\n const dcdBody = new Uint8Array(13 + dsi.length)\n dcdBody[0] = 0x40; dcdBody[1] = 0x15; dcdBody.set(dsi, 13)\n const dcd = new Uint8Array(2 + dcdBody.length)\n dcd[0] = 0x04; dcd[1] = dcdBody.length; dcd.set(dcdBody, 2)\n const esBody = new Uint8Array(3 + dcd.length)\n esBody[0] = 0; esBody[1] = 0x01; esBody[2] = 0; esBody.set(dcd, 3)\n const es = new Uint8Array(2 + esBody.length)\n es[0] = 0x03; es[1] = esBody.length; es.set(esBody, 2)\n const esdsBox = fullBox('esds', 0, 0, es)\n\n const mp4aBody = new Uint8Array(28 + esdsBox.length)\n const mp4aView = new DataView(mp4aBody.buffer)\n mp4aView.setUint16(6, 1)\n mp4aView.setUint16(16, channels)\n mp4aView.setUint16(18, 16)\n mp4aView.setUint32(24, sampleRate << 16)\n mp4aBody.set(esdsBox, 28)\n const mp4a = box('mp4a', mp4aBody)\n\n const stsd = fullBox('stsd', 0, 0, u32(1), mp4a)\n const stbl = box('stbl', stsd,\n fullBox('stts', 0, 0, u32(0)),\n fullBox('stsc', 0, 0, u32(0)),\n fullBox('stsz', 0, 0, u32(0), u32(0)),\n fullBox('stco', 0, 0, u32(0)),\n )\n const dinf = box('dinf', fullBox('dref', 0, 0, u32(1), fullBox('url ', 0, 1)))\n const minf = box('minf', fullBox('smhd', 0, 0, new Uint8Array(4)), dinf, stbl)\n const hdlr = fullBox('hdlr', 0, 0, new Uint8Array([\n 0, 0, 0, 0, 0x73, 0x6f, 0x75, 0x6e,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0x53, 0x6f, 0x75, 0x6e, 0x64, 0,\n ]))\n const mdhdBody = new Uint8Array(20)\n new DataView(mdhdBody.buffer).setUint32(8, ts)\n const mdhd = fullBox('mdhd', 0, 0, mdhdBody)\n const mdia = box('mdia', mdhd, hdlr, minf)\n\n const tkhdBody = new Uint8Array(80)\n const tkhdView = new DataView(tkhdBody.buffer)\n tkhdView.setUint32(8, trackId)\n tkhdView.setUint32(36, 0x00010000)\n tkhdView.setUint32(52, 0x00010000)\n tkhdView.setUint32(64, 0x40000000)\n const tkhd = fullBox('tkhd', 0, 3, tkhdBody)\n const trak = box('trak', tkhd, mdia)\n\n const mvhdBody = new Uint8Array(96)\n const mvhdView = new DataView(mvhdBody.buffer)\n mvhdView.setUint32(8, ts)\n mvhdView.setUint32(16, 0x00010000)\n mvhdView.setUint16(20, 0x0100)\n mvhdView.setUint32(32, 0x00010000)\n mvhdView.setUint32(48, 0x00010000)\n mvhdView.setUint32(60, 0x40000000)\n mvhdView.setUint32(92, trackId + 1)\n const mvhd = fullBox('mvhd', 0, 0, mvhdBody)\n\n const trexBody = new Uint8Array(20)\n new DataView(trexBody.buffer).setUint32(0, trackId)\n new DataView(trexBody.buffer).setUint32(4, 1)\n const mvex = box('mvex', fullBox('trex', 0, 0, trexBody))\n\n const moov = box('moov', mvhd, trak, mvex)\n const ftyp = box('ftyp', new Uint8Array([\n 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0,\n 0x69, 0x73, 0x6f, 0x6d,\n 0x69, 0x73, 0x6f, 0x36,\n 0x6d, 0x70, 0x34, 0x31,\n ]))\n const result = new Uint8Array(ftyp.length + moov.length)\n result.set(ftyp, 0)\n result.set(moov, ftyp.length)\n return result\n}\n\n/**\n * MMTP \u2192 CMAF converter.\n *\n * Accepts reassembled MFU frames (raw codec samples) from MmtpDecoder\n * and produces fMP4 segments for MSE SourceBuffer.\n *\n * Per draft-ramadan-moq-mmt \u00A75.3:\n * MPU metadata (ftyp+moov) \u2192 init segment\n * MFU sample bytes \u2192 moof+mdat data segment\n *\n * Timescale is microseconds (1_000_000) matching MMTP NTP short timestamps\n * converted via mmtpTimestampToMicros().\n */\nexport class MmtpToCmaf {\n #videoSeq = 1\n #audioSeq = 1\n #videoInitSegment: Uint8Array | null = null\n // Known only for locally-built init segments. Wire-supplied MPU metadata is\n // intentionally opaque here, so setVideoTrackParams remains the API that\n // lets a caller declare its track geometry before wrapping samples.\n #videoInitTrackId: number | null = null\n #audioInitSegment: Uint8Array | null = null\n #lastVideoTimestamp = 0\n // Sticky sample duration in video timescale units, updated from caller-\n // supplied durations or adjacent-timestamp deltas. null means \"nothing\n // observed yet\", in which case #videoFrameDuration derives ~30fps from the\n // configured timescale (33333 at the 1_000_000 default, i.e. unchanged).\n #frameDuration: number | null = null\n // Per-track rebase: each track anchors on its OWN first sample so\n // baseMediaDecodeTime is never negative. A shared base was wrong \u2014 if the\n // first sample of one track arrives later than the other's first sample,\n // the earlier track computes `timestamp - sharedBase` as a negative number,\n // which serializes into tfdt as a huge unsigned uint64 (~2^64 - 46) and\n // Chromium rejects the segment with CHUNK_DEMUXER_ERROR_APPEND_FAILED,\n // closing the MediaSource and detaching all SourceBuffers.\n // For A/V alignment, choose a COMMON anchor: set when the first sample of\n // EITHER track arrives, but only if that sample's timestamp is <= any\n // subsequent track's first sample. Implementation: each track rebases to\n // the minimum timestamp seen across tracks on their respective first sample.\n #videoBaseTs = -1\n #audioBaseTs = -1\n\n // Video track geometry. These pair with the video init segment's tkhd\n // track_ID and mdhd/mvhd timescale: every moof this converter emits must\n // reference the same track at the same rate or the browser either drops the\n // fragment (unknown track) or plays it at the wrong rate. They are\n // configuration rather than stream state, so \u2014 unlike the sequence numbers\n // and time bases above \u2014 reset() deliberately preserves them, matching the\n // fact that reset() also preserves #videoInitSegment.\n #videoTrackId = 1\n #videoTimescale = 1_000_000\n\n /**\n * Point the single-sample video wrappers at a specific track and rate.\n *\n * Call this when the init segment came off the wire (setInitSegmentFromMpu)\n * rather than from buildVideoInit, so the wrappers match the publisher's\n * tkhd/mdhd instead of assuming trackId=1 at microsecond rate. Consumers\n * that build their init through buildVideoInit can pass the same values\n * there instead and skip this call.\n *\n * The rate is settable only until the first single-sample wrap \u2014 see the\n * throw below for why.\n */\n setVideoTrackParams(trackId: number, timescale: number) {\n assertTrackId(trackId, 'video trackId')\n assertTimescale(timescale, 'video timescale')\n // #frameDuration, #lastVideoTimestamp and #videoBaseTs are all denominated\n // in #videoTimescale, so moving the rate out from under them reinterprets\n // every one at the new rate. Both consequences are silent:\n // - a duration latched as 33333 (1 MHz ~30fps) re-emits as 33333 ticks of\n // 90 kHz, a 370 ms frame;\n // - a base captured on the old scale rebases new-scale timestamps to a\n // negative relTs, which tfdt serializes as a ~2^64 uint64 and Chromium\n // rejects with CHUNK_DEMUXER_ERROR_APPEND_FAILED, closing the\n // MediaSource (same failure the #videoBaseTs comment above describes).\n // Rescaling instead of refusing would be a guess: the class cannot tell\n // whether the caller's next timestamps continue this timeline in new units\n // or open a fresh epoch. reset() is the exact mechanism for that\n // discontinuity \u2014 it clears all three fields while preserving geometry \u2014\n // so require it rather than infer. Re-asserting the same rate is a no-op.\n // A cached init also fixes the track ID in tkhd/trex; changing only the\n // wrapper setting would make later tfhd IDs disagree with that init.\n if (trackId !== this.#videoTrackId && this.#videoInitTrackId !== null) {\n throw new Error(\n `video track ID cannot change from ${this.#videoTrackId} to ${trackId} ` +\n 'after a video init has been cached; replace the init atomically',\n )\n }\n if (timescale !== this.#videoTimescale && this.#videoBaseTs >= 0) {\n throw new Error(\n `video timescale cannot change from ${this.#videoTimescale} to ${timescale} ` +\n `after video samples have been wrapped; call reset() first`,\n )\n }\n this.#videoTrackId = trackId\n this.#videoTimescale = timescale\n }\n\n /** Set init segment from MPU metadata packet (fragment_type=0).\n * These are complete ftyp+moov bytes from FFmpeg \u2014 use directly. */\n setInitSegmentFromMpu(data: Uint8Array, isAudio: boolean) {\n if (isAudio) {\n this.#audioInitSegment = data\n } else {\n this.#videoInitSegment = data\n this.#videoInitTrackId = null\n }\n }\n\n /** Build init segment from codec config (catalog path \u2014 no MPU metadata available).\n * Passing timescale/trackId also configures the wrappers via\n * setVideoTrackParams, so init and media segments cannot disagree. */\n buildVideoInit(avcC: Uint8Array, width: number, height: number, timescale?: number, trackId?: number) {\n const nextTimescale = timescale ?? this.#videoTimescale\n const nextTrackId = trackId ?? this.#videoTrackId\n assertTrackId(nextTrackId, 'video trackId')\n assertTimescale(nextTimescale, 'video timescale')\n if (nextTimescale !== this.#videoTimescale && this.#videoBaseTs >= 0) {\n throw new Error(\n `video timescale cannot change from ${this.#videoTimescale} to ${nextTimescale} ` +\n 'after video samples have been wrapped; call reset() first',\n )\n }\n // Build first, then publish both geometry and init together. This is the\n // sanctioned path for replacing a cached init with a new track ID.\n const init = buildVideoInitSegment(\n avcC,\n width,\n height,\n nextTimescale,\n nextTrackId,\n )\n this.#videoTimescale = nextTimescale\n this.#videoTrackId = nextTrackId\n this.#videoInitSegment = init\n this.#videoInitTrackId = nextTrackId\n }\n\n buildAudioInit(sampleRate: number, channels: number, asc?: Uint8Array, timescale?: number) {\n const ts = timescale ?? sampleRate\n // Build first, then publish, as the video path does: buildAudioInitSegment\n // validates, so assigning the field first would leave a rejected timescale\n // latched on the instance with no init segment to match it.\n const init = buildAudioInitSegment(sampleRate, channels, asc, ts)\n this.#audioTimescale = ts\n this.#audioInitSegment = init\n }\n\n get videoInitSegment(): Uint8Array | null { return this.#videoInitSegment }\n get audioInitSegment(): Uint8Array | null { return this.#audioInitSegment }\n\n /** Convert a raw video sample to an fMP4 moof+mdat segment. */\n wrapVideoSample(\n data: Uint8Array,\n timestamp: number,\n keyframe: boolean,\n duration?: number,\n compositionTimeOffset?: number,\n ): Uint8Array {\n return this.wrapVideoSampleWithTiming(data, timestamp, keyframe, duration, compositionTimeOffset).segment\n }\n\n /**\n * Convert a raw video sample and return the exact browser media interval\n * encoded into tfdt/trun. Consumers that correlate SourceBuffer appends with\n * requestVideoFrameCallback must use this rebased timestamp, not the wire or\n * caller-owned timestamp passed above.\n *\n * `compositionTimeOffset` is the signed authored PTS-DTS delta, in the same\n * #videoTimescale units as `timestamp` and `duration` \u2014 unlike wrapAudioSample,\n * which takes microseconds and rescales, because every other quantity on this\n * path is already denominated in #videoTimescale (see setVideoTrackParams).\n * Passing it therefore needs no conversion here; rescaling would double-convert.\n * Absent leaves the trun at version 0 with no offset field; a declared 0 is an\n * authored value and still promotes to version 1. Never reconstruct it from\n * arrival time.\n */\n wrapVideoSampleWithTiming(\n data: Uint8Array,\n timestamp: number,\n keyframe: boolean,\n duration?: number,\n compositionTimeOffset?: number,\n ): Readonly<{ segment: Uint8Array; mediaTimestamp: number; duration: number }> {\n // Checked before #videoSeq++ and before the duration/base-timestamp latches\n // below, for the same reason as wrapAudioSample and wrapVideoSamples: the\n // encoder validates too, but by then the sequence number is spent and a\n // caller that corrects the offset and retries emits a gapped mfhd.\n assertCompositionTimeOffsets([{ compositionTimeOffset }])\n // Prefer a caller-provided media duration when the browser append timeline\n // is intentionally decoupled from sparse MMTP wire timestamps. Fall back to\n // estimating from adjacent timestamps for legacy/direct callers. A delta of\n // a full second or more is not a frame interval, so it is rejected as a\n // discontinuity rather than latched.\n if (duration !== undefined && Number.isFinite(duration) && duration > 0) {\n this.#frameDuration = Math.round(duration)\n } else if (this.#lastVideoTimestamp > 0 && timestamp > this.#lastVideoTimestamp) {\n const delta = timestamp - this.#lastVideoTimestamp\n if (delta > 0 && delta < this.#videoTimescale) this.#frameDuration = delta\n }\n this.#lastVideoTimestamp = timestamp\n if (this.#videoBaseTs < 0) this.#videoBaseTs = timestamp\n const relTs = timestamp - this.#videoBaseTs\n const frameDuration = this.#videoFrameDuration\n return Object.freeze({\n segment: encodeDataSegment(\n data,\n relTs,\n frameDuration,\n keyframe,\n this.#videoSeq++,\n this.#videoTrackId,\n compositionTimeOffset,\n ),\n mediaTimestamp: relTs,\n duration: frameDuration,\n })\n }\n\n /** Sticky duration if one has been observed, else ~30fps at the current rate. */\n get #videoFrameDuration(): number {\n return this.#frameDuration ?? Math.max(1, Math.round(this.#videoTimescale / 30))\n }\n\n /** Convert an append-safe video batch using the caller-owned timeline.\n * Durations, baseDecodeTime, and compositionTimeOffset are in the\n * configured video timescale. compositionTimeOffset is the signed PTS-DTS\n * delta; its presence selects a version-1 trun for the whole batch.\n * An explicit trackId is range-checked before #videoSeq++ for the same\n * reason as wrapAudioSamples: the encoder's own check fires too late to\n * keep the sequence ungapped. */\n wrapVideoSamples(\n samples: Array<{\n data: Uint8Array\n duration: number\n keyframe: boolean\n compositionTimeOffset?: number\n }>,\n baseDecodeTime: number,\n trackId = this.#videoTrackId,\n ): Uint8Array {\n assertTrackId(trackId, 'video trackId')\n assertCompositionTimeOffsets(samples)\n return encodeMultiSampleSegment(samples, baseDecodeTime, this.#videoSeq++, trackId)\n }\n\n // Audio timescale from init segment (default 1M \u00B5s; real FFmpeg init uses sampleRate).\n // Set by buildAudioInit or setAudioTimescale.\n #audioTimescale = 1_000_000\n\n /** Set audio timescale to match the init segment's mdhd timescale.\n * Call after appending the real encoder init (FT=0 ftyp+moov).\n * Fails closed on a value the mdhd uint32 cannot hold, as the video paths\n * already do. wrapAudioSample rescales the authored composition offset by\n * this value, so the two failure modes are both silent: a 0 multiplies\n * every authored offset to 0 \u2014 indistinguishable from a feed that authored\n * none \u2014 while a value above uint32 scales the trun to a timescale the\n * mdhd cannot declare, since it is emitted with setUint32 modulo 2^32. */\n setAudioTimescale(timescale: number) {\n assertTimescale(timescale, 'audio timescale')\n this.#audioTimescale = timescale\n }\n\n // Audio sample counter for drift-free baseMediaDecodeTime.\n // AAC frames are exactly 1024 samples at sampleRate. Using sequential\n // counter \u00D7 1024 avoids floating-point rounding drift from timestamp conversion.\n #audioSampleCount = 0\n\n /** AAC access-unit length in samples. ISO/IEC 14496-3: an AAC-LC frame is\n * exactly 1024 samples at every sample rate \u2014 it is not rate-dependent. */\n readonly #aacFrameSamples = 1024\n\n /** Convert a raw audio sample to an fMP4 moof+mdat segment. */\n wrapAudioSample(\n data: Uint8Array,\n timestamp: number,\n sampleDuration = 21333,\n compositionTimeOffset?: number,\n ): Uint8Array {\n assertCompositionTimeOffsets([{ compositionTimeOffset }])\n const sampleData = normalizeAacSampleForCmaf(data)\n if (this.#audioBaseTs < 0) this.#audioBaseTs = timestamp\n\n // When timescale matches sampleRate (e.g. 48000), use integer sample counting\n // for exact baseMediaDecodeTime alignment. This eliminates cumulative rounding\n // drift from Math.round(\u00B5s * sampleRate / 1_000_000) that causes frequency\n // wandering in FFT analysis (42% consistency \u2192 99%+ with exact counting).\n //\n // samplesPerFrame is the AAC access-unit length, NOT a rescaled duration.\n // Deriving it as Math.round(sampleDuration * timescale / 1e6) only lands on\n // 1024 when the rate happens to be 48 kHz (21333 * 48000 / 1e6 = 1023.98),\n // which made the default silently correct at 48 kHz and wrong everywhere\n // else: at 44.1 kHz it yields 941, so every moof declared ~8% short frames\n // and Chrome rejected the first packet with PIPELINE_ERROR_DECODE\n // (\"Failed to send audio packet for decoding\", duration=21337\u00B5s = 941/44100).\n const samplesPerFrame = this.#audioTimescale !== 1_000_000\n ? this.#aacFrameSamples\n : sampleDuration\n const scaledTs = this.#audioTimescale !== 1_000_000\n ? this.#audioSampleCount * samplesPerFrame\n : (timestamp - this.#audioBaseTs)\n this.#audioSampleCount++\n\n // compositionTimeOffset arrives in microsecond ticks, like timestamp and\n // sampleDuration: the block assembler scales authored PTS-DTS into its own\n // timescale, which defaults to 1e6 whenever the caller omits `timescale`\n // (cmaf-block-assembler.ts). The trun it lands in is at #audioTimescale, so\n // on the sample-counting branch it needs the same rescale its two siblings\n // above already get. Without it a 10 ms authored offset is written as\n // 10_000 ticks of a 48 kHz track \u2014 1e6/48000 = 20.83x, ~208 ms of A/V\n // desync \u2014 which is the samplesPerFrame hazard documented above, one field\n // over. Undefined stays undefined so raw feeds keep a v0 trun with no\n // composition-offset field rather than claiming an authored zero.\n //\n // This 1e6 is the assembler's default timescale, not a free constant, so\n // the two move together. Configuring the audio assembler with\n // `timescale: sampleRate` makes its offsets already trun ticks and turns\n // this rescale into a 20.83x *under*-count: an authored 480 arrives as 23.\n //\n // The two bridges currently disagree on that config, so this rescale is\n // correct for exactly one of them at a time. moqtail omits `timescale`\n // (apps/client-js/src/lib/player.ts, audio enableMseAssembler) and needs\n // the rescale. hang passes `timescale: sampleRate` (js/watch/src/element.ts,\n // audio enableMseAssembler) and must not get it. hang is safe today only\n // because it pins a libmmt revision older than this rescale. Bumping that\n // pin past this commit without dropping hang's `timescale` in the same\n // change is the 20.83x under-count, so the pin bump and the hang edit are\n // one atomic change. mmtp-to-cmaf-audio-composition-offset.test.ts pins\n // both configs against a real CmafBlockAssembler so the pairing is checked\n // by CI rather than by this comment.\n const scaledCompositionTimeOffset =\n compositionTimeOffset === undefined || this.#audioTimescale === 1_000_000\n ? compositionTimeOffset\n : Math.round((compositionTimeOffset * this.#audioTimescale) / 1_000_000)\n\n return encodeDataSegment(\n sampleData,\n scaledTs,\n samplesPerFrame,\n true,\n this.#audioSeq++,\n 1,\n scaledCompositionTimeOffset,\n )\n }\n\n /** Convert an ordered audio batch using the caller-owned timeline. */\n wrapAudioSamples(\n samples: Array<{\n data: Uint8Array\n duration: number\n compositionTimeOffset?: number\n }>,\n baseDecodeTime: number,\n trackId = 1,\n ): Uint8Array {\n // Checked before #audioSeq++ below: the encoder validates too, but its\n // throw would land after the counter had already advanced, leaving the\n // sequence gapped by a call that produced no segment.\n assertTrackId(trackId, 'audio trackId')\n assertCompositionTimeOffsets(samples)\n return encodeMultiSampleSegment(\n samples.map(sample => ({\n data: normalizeAacSampleForCmaf(sample.data),\n duration: sample.duration,\n keyframe: true,\n compositionTimeOffset: sample.compositionTimeOffset,\n })),\n baseDecodeTime,\n this.#audioSeq++,\n trackId,\n )\n }\n\n /** Clear per-stream sequencing and time bases.\n * Cached init segments and the video track geometry survive, so a converter\n * reset mid-subscription keeps emitting moofs the existing init can resolve.\n * Clearing the timescale-denominated timing state also re-opens the video\n * rate for change \u2014 this is the sanctioned way to retarget mid-subscription. */\n reset() {\n this.#videoSeq = 1\n this.#audioSeq = 1\n this.#audioSampleCount = 0\n this.#lastVideoTimestamp = 0\n this.#frameDuration = null\n this.#videoBaseTs = -1\n this.#audioBaseTs = -1\n this.#audioTimescale = 1_000_000\n }\n}\n", "/**\n * Sink-side concealment helpers for the keyframe-protected FEC policy.\n *\n * Concealment is hold-last-good-frame. No bitstream is ever synthesised:\n * a generated \"fill\" picture is codec-specific, resets the reference chain\n * (an IDR) or is not a picture at all, and every later delta would decode\n * against it until the next RAP. Instead the sink keeps presenting the last\n * good frame, sized exactly from authored timestamps, until media resumes.\n *\n * - {@link videoConcealModeForCodec} says whether a video decoder can be fed\n * straight through a delta gap (H.264 conceals missing references itself)\n * or must hold until the next RAP.\n * - {@link HoldLastTimeline} gives MSE sinks gapless per-sample durations.\n * - {@link AudioGapConcealer} sizes audio concealment exactly: repeat the last\n * good access unit (MSE) or insert PCM silence (WebCodecs).\n */\n\nimport type { FrameGapDecision } from './block-policy.js'\n\n// \u2500\u2500\u2500 Video conceal mode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 * `feed-through`: keep feeding deltas after a delta-only gap; the decoder\n * conceals missing references and the canvas keeps the last frame.\n * `hold-to-rap`: drop non-RAP frames until the next RAP (no queue flush, no\n * A/V sync reset).\n */\nexport type VideoConcealMode = 'feed-through' | 'hold-to-rap'\n\n/**\n * AVC decoders conceal a missing reference and resynchronise on their own;\n * HEVC, AV1 and VP9 decoders error or freeze on a broken reference chain.\n * Any codec not known to conceal is held to the next RAP (fail-closed).\n */\nexport function videoConcealModeForCodec(codec: string): VideoConcealMode {\n const lower = codec.toLowerCase()\n if (lower.startsWith('avc1') || lower.startsWith('avc3')) return 'feed-through'\n return 'hold-to-rap'\n}\n\n// \u2500\u2500\u2500 HoldLastTimeline \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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/** One video sample in its media timescale. */\nexport interface TimelineSample<T> {\n readonly payload: T\n readonly dts: bigint\n readonly pts: bigint\n /** Authored duration in media ticks. */\n readonly duration: number\n /** Codec-aware RAP. */\n readonly keyframe: boolean\n readonly mpu?: number\n /** Decision attached by libmmt to the first frame released after a gap. */\n readonly gapBefore?: FrameGapDecision\n}\n\n/** A sample ready to append, with an explicit per-sample duration. */\nexport interface TimelineEmit<T> {\n readonly payload: T\n readonly dts: bigint\n readonly pts: bigint\n readonly duration: number\n readonly keyframe: boolean\n}\n\nexport interface HoldLastTimelineOptions {\n readonly concealMode: VideoConcealMode\n}\n\nexport interface HoldLastTimelineStats {\n /** Non-RAP frames dropped while waiting for a RAP. */\n droppedFrames: number\n /** Held frames whose duration was extended over a gap. */\n extendedHolds: number\n}\n\nconst U32_MAX = 0xffff_ffffn\n\n/**\n * Holds one video sample back so its duration can run to the next emitted\n * sample's dts. That costs exactly one frame of MSE latency (1000/framerate\n * ms, from the catalog) and buys a gapless hold-last without synthesising a\n * bitstream: a gap simply lengthens the last good frame.\n *\n * On a stall, or on any conceal under `hold-to-rap` except a RAP arriving\n * right after the gap, frames are dropped until the next RAP and the held\n * frame stays held until that RAP arrives, then runs exactly to its dts. The\n * element waits on the held frame for the length of the outage, but the\n * buffer never gets a hole, however many RAPs the outage took. Once the\n * stream shows composition offsets (dts \u2260 pts), samples pass straight\n * through with their authored durations and MSE starves until the RAP is\n * appended \u2014 the one documented case where the element also waits on audio.\n */\nexport class HoldLastTimeline<T> {\n readonly #concealMode: VideoConcealMode\n #held: TimelineSample<T> | null = null\n #dropping = false\n #compositionOffsets = false\n readonly #stats: HoldLastTimelineStats = { droppedFrames: 0, extendedHolds: 0 }\n\n constructor(options: HoldLastTimelineOptions) {\n this.#concealMode = options.concealMode\n }\n\n get stats(): Readonly<HoldLastTimelineStats> {\n return { ...this.#stats }\n }\n\n push(sample: TimelineSample<T>): TimelineEmit<T>[] {\n if (sample.dts !== sample.pts) this.#compositionOffsets = true\n\n if (this.#dropping) {\n if (!sample.keyframe) {\n this.#stats.droppedFrames++\n return []\n }\n this.#dropping = false\n return this.#accept(sample)\n }\n\n if (this.#dropsUntilRap(sample)) {\n this.#dropping = true\n this.#stats.droppedFrames++\n // The held frame stays held: the RAP's #accept sizes it exactly.\n return this.#compositionOffsets ? this.#releaseHeld() : []\n }\n\n return this.#accept(sample)\n }\n\n /** Release the held sample with its authored duration (end of stream). */\n flush(): TimelineEmit<T>[] {\n return this.#releaseHeld()\n }\n\n /** Drop all state for a new epoch. */\n reset(): void {\n this.#held = null\n this.#dropping = false\n this.#compositionOffsets = false\n }\n\n #accept(sample: TimelineSample<T>): TimelineEmit<T>[] {\n if (this.#compositionOffsets) {\n const out = this.#releaseHeld()\n out.push(this.#emit(sample, sample.duration))\n return out\n }\n const out: TimelineEmit<T>[] = []\n const held = this.#held\n if (held) out.push(this.#emit(held, this.#durationTo(held, sample.dts)))\n this.#held = sample\n return out\n }\n\n #dropsUntilRap(sample: TimelineSample<T>): boolean {\n const gap = sample.gapBefore\n if (!gap || gap.trackKind !== 'video' || sample.keyframe) return false\n if (gap.action === 'stall') return true\n return this.#concealMode === 'hold-to-rap' && gap.reason !== 'rap-next'\n }\n\n #durationTo(held: TimelineSample<T>, target: bigint): number {\n if (target <= held.dts) return held.duration\n const span = target - held.dts\n if (span > U32_MAX) return held.duration\n const duration = Number(span)\n if (duration !== held.duration) this.#stats.extendedHolds++\n return duration\n }\n\n #releaseHeld(): TimelineEmit<T>[] {\n const held = this.#held\n this.#held = null\n return held ? [this.#emit(held, held.duration)] : []\n }\n\n #emit(sample: TimelineSample<T>, duration: number): TimelineEmit<T> {\n return {\n payload: sample.payload,\n dts: sample.dts,\n pts: sample.pts,\n duration,\n keyframe: sample.keyframe,\n }\n }\n}\n\n// \u2500\u2500\u2500 AudioGapConcealer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 * One audio access unit on its track's authored clock: the ISO-BMFF media\n * timescale the `audio-gap` decision was computed in (`decideGap`, from\n * `AuthoredTiming`). An AAC AU is exactly 1024 ticks there. Never pass values\n * rescaled to another timescale: 1024 samples at 48 kHz is 21333.33... \u00B5s,\n * which no integer tick count can hold.\n */\nexport interface AudioAccessUnit<T> {\n readonly payload: T\n /** Authored presentation time in media ticks (`AuthoredTiming.presentationTime`). */\n readonly pts: bigint\n /** Authored duration in media ticks (`AuthoredTiming.durationTicks`): a positive safe integer. */\n readonly duration: number\n}\n\nexport interface AudioGapConcealerStats {\n /**\n * Access units `note()` refused because their duration was not a positive\n * safe integer: not media ticks, so the AU cannot size a gap. The concealer\n * then holds no good AU and the next gap re-anchors. Non-zero means a caller\n * noted a rescaled value (e.g. microseconds) instead of authored ticks.\n */\n rejectedUnits: number\n}\n\nexport type AudioGapPlan<T> =\n | { readonly kind: 'none' }\n | {\n readonly kind: 'conceal'\n /**\n * MSE: the last good AU repeated into each missing slot. Empty when no\n * good AU has been seen yet; an AAC access unit is not portable across\n * AudioSpecificConfigs, so none is ever synthesised.\n */\n readonly repeat: AudioAccessUnit<T>[]\n /** WebCodecs: exactly this much PCM silence, in media ticks. */\n readonly silenceTicks: bigint\n }\n | {\n /** The gap is not a whole number of AUs: re-anchor at `pts`. */\n readonly kind: 're-anchor'\n readonly pts: bigint\n }\n\n/**\n * Sizes an audio gap from the libmmt gap decision. Audio never touches video\n * state: every plan is local to the audio sink.\n */\nexport class AudioGapConcealer<T> {\n #last: AudioAccessUnit<T> | null = null\n readonly #stats: AudioGapConcealerStats = { rejectedUnits: 0 }\n\n get stats(): Readonly<AudioGapConcealerStats> {\n return { ...this.#stats }\n }\n\n /**\n * Record a good access unit as it is emitted. An AU whose duration is not\n * whole media ticks is refused and counted (`stats.rejectedUnits`), and the\n * concealer forgets its previous AU: that one no longer precedes the gap, so\n * sizing from it would misplace every slot. Refusing here keeps `plan()`\n * total, so a bad AU never throws out of the packet path.\n */\n note(au: AudioAccessUnit<T>): void {\n if (!Number.isSafeInteger(au.duration) || au.duration <= 0) {\n this.#stats.rejectedUnits++\n this.#last = null\n return\n }\n this.#last = au\n }\n\n plan(decision: FrameGapDecision | undefined, next: { readonly pts: bigint }): AudioGapPlan<T> {\n if (!decision || decision.trackKind !== 'audio') return { kind: 'none' }\n const missing = decision.missingFrames\n if (\n decision.reason !== 'audio-gap' ||\n missing === null ||\n !Number.isSafeInteger(missing) ||\n missing <= 0\n ) {\n return { kind: 're-anchor', pts: next.pts }\n }\n const last = this.#last\n // Exact sizing needs the preceding AU's duration; a sink that has not\n // emitted one yet has nothing to hold and simply starts at the next AU.\n if (last === null) return { kind: 're-anchor', pts: next.pts }\n const duration = BigInt(last.duration)\n const repeat: AudioAccessUnit<T>[] = []\n for (let slot = 1; slot <= missing; slot++) {\n repeat.push({\n payload: last.payload,\n pts: last.pts + BigInt(slot) * duration,\n duration: last.duration,\n })\n }\n return { kind: 'conceal', repeat, silenceTicks: BigInt(missing) * duration }\n }\n\n reset(): void {\n this.#last = null\n }\n}\n", "/**\n * FEC-aware CMAF sample assembler for MSE multicast.\n *\n * Emits source frames on arrival and FEC-recovered frames in media order.\n * Nothing is synthesised for a lost video block: the sink holds the last good\n * frame (HoldLastTimeline). A lost audio span is concealed only when libmmt's\n * release gate decided it (`gapBefore` with reason `audio-gap`), by repeating\n * the last good access unit into each missing slot (AudioGapConcealer).\n *\n * One assembler instance per track (video or audio). MulticastManager owns\n * these instances and calls them directly with SBN/ESI from the FEC pipeline.\n */\n\nimport {\n encodeDataSegment,\n buildVideoInitSegment,\n buildHevcVideoInitSegment,\n buildAudioInitSegment,\n normalizeAacSampleForCmaf,\n} from './mmtp-to-cmaf.js'\nimport { AudioGapConcealer } from './conceal-timeline.js'\nimport type { FrameGapDecision } from './block-policy.js'\nimport {\n classifyH264Keyframe,\n detectH264Keyframe,\n hevcNalUnitType,\n isAnnexB,\n isCompleteAvccSample,\n prepareHevcCmafSample,\n splitAnnexBNalUnits,\n splitAvccNalUnits,\n splitH264SampleNalUnits,\n videoCodecFamily,\n videoSampleEntryFromCodecString,\n type VideoCodecFamily,\n type VideoSampleEntry,\n} from './codec-utils.js'\nimport {\n scaleAuthoredTicks,\n scaleAuthoredTiming,\n type AuthoredTiming,\n} from './authored-timing.js'\nimport type { MmtpDeliveryProvenance } from './mfu-reassembler.js'\n\nconst INT32_MIN = -0x80000000\nconst INT32_MAX = 0x7fffffff\n\ninterface BlockFrame {\n data: Uint8Array\n timestamp: number\n keyframe: boolean\n /** True only for locally generated concealment frames. */\n synthetic?: boolean\n /** Raw MMTP short-NTP header timestamp; never used for CMAF timing. */\n mmtpTimestamp?: bigint\n /** Exact ISO-BMFF timing retained from the parser for FEC/source ordering. */\n authoredTiming?: AuthoredTiming\n /** MMTP packet_sequence_number identifying the delivered access unit. */\n packetSequenceNumber?: number\n /** Every authoritative MMTP source-packet sequence that formed this sample. */\n packetSequenceNumbers?: number[]\n /** Subset of packetSequenceNumbers reconstructed by FEC. */\n repairedPacketSequenceNumbers?: number[]\n /** Native MMTP MPU group coordinate retained across source/FEC ordering. */\n mpuSequenceNumber?: number\n /** Timed-MFU sample identity; absent when the MFU header is untimed. */\n movieFragmentSequenceNumber?: number\n sampleNumber?: number\n catalogTrackName?: string\n /**\n * Whole-frame delivery verdict folded across every contributing fragment.\n * Absent means no caller declared one; it is never an implied 'multicast'.\n */\n deliveryProvenance?: MmtpDeliveryProvenance\n /** libmmt's stall/conceal decision for the gap before this frame. */\n gapBefore?: FrameGapDecision\n}\n\nexport interface CmafBlockSample {\n data: Uint8Array\n timestamp: number\n duration: number\n keyframe: boolean\n /**\n * True only for locally generated concealment samples. These samples carry\n * codec bytes and a media timestamp, but no authored MMTP identity; object\n * consumers must not validate them as source MFUs.\n */\n synthetic?: boolean\n /**\n * Raw MMTP short-NTP header timestamp retained for timing telemetry.\n * This is intentionally separate from the authored media timestamp above.\n */\n mmtpTimestamp?: bigint\n /** Signed PTS-DTS offset in the configured CMAF timescale. */\n compositionTimeOffset?: number\n /** Exact ISO-BMFF timing in the media track's native timescale. */\n authoredTiming?: AuthoredTiming\n /** MMTP packet_sequence_number identifying the delivered access unit. */\n packetSequenceNumber?: number\n /** Every authoritative MMTP source-packet sequence that formed this sample. */\n packetSequenceNumbers?: number[]\n /** Subset of packetSequenceNumbers reconstructed by FEC. */\n repairedPacketSequenceNumbers?: number[]\n /** Native MMTP MPU group coordinate retained for exact replay selection. */\n mpuSequenceNumber?: number\n /**\n * Timed-MFU sample identity `(movie_fragment_sequence_number,\n * sample_number)` from the MFU data-unit header, carried alongside\n * `mpuSequenceNumber` so a consumer can address the sample by its native\n * MMTP coordinates. Absent when the MFU header is untimed.\n */\n movieFragmentSequenceNumber?: number\n sampleNumber?: number\n /** Immutable catalog identity supplied by the owning ingress subscription. */\n catalogTrackName?: string\n /**\n * Whole-frame delivery verdict, carried so MSE `onSample` consumers can see\n * the same evidence the non-MSE frame path gets. Without it the MSE branch\n * silently loses a computed 'mixed' or 'multicast' finding.\n */\n deliveryProvenance?: MmtpDeliveryProvenance\n /**\n * libmmt's stall/conceal decision for the gap before this sample\n * (`RoutedFrameMeta.gapBefore`). MSE sinks feed it to HoldLastTimeline.\n */\n gapBefore?: FrameGapDecision\n}\n\nexport type CmafSampleOrderPolicy =\n | { mode: 'arrival' }\n | {\n /** Release samples according to media progression, without a wall clock. */\n mode: 'media-window'\n /** Delivery window in the same units as CmafBlockSample.timestamp. */\n deliveryWindow: number\n /** Optional modulo period for wrapped input timestamps, in timestamp units. */\n timestampWrapPeriod?: number\n }\n\nexport interface CmafSampleOrderStats {\n staleSamples: number\n duplicateSamples: number\n preRapDeadlineDrops: number\n noRapFlushDrops: number\n forcedReleases: number\n /**\n * Samples refused because they carried `authoredTiming` while this track's\n * `admitAuthoredTiming` was false. Non-zero means the contract rollback\n * switch is engaged AND the producer is still sending authored batches \u2014\n * a rollback is meant to be paired with that producer reverting to raw.\n */\n unadmittedAuthoredSamples: number\n /**\n * Video samples refused because their bitstream could not be read: HEVC\n * whose framing is neither a complete 4-byte length-prefixed sample nor\n * Annex B, or that holds no NAL unit to write. Writing them would put bytes\n * the hvcC's lengthSizeMinusOne = 3 does not describe into the mdat.\n */\n unreadableVideoSamples: number\n}\n\n/**\n * Cumulative counters of what the assembler emitted and which block events\n * it saw. `emits` counts emit calls (one per direct frame, recovered block,\n * recovered drain or block flush); `samples` and `keyframes` count the\n * samples those calls carried.\n */\nexport interface CmafEmitStats {\n emits: number\n samples: number\n keyframes: number\n addedFrames: number\n recoveredBlocks: number\n completedBlocks: number\n failedBlocks: number\n}\n\n/**\n * Cumulative audio gap concealment counters since construction. Every audio\n * gap decision the assembler sees lands in exactly one of the gap counters.\n */\nexport interface CmafAudioConcealStats {\n /** Last-good AUs written into the slots of `audio-gap` decisions. */\n repeatedUnits: number\n /**\n * Gap decisions re-anchored at the next AU by design: an\n * `audio-discontinuity`, or no good AU emitted yet.\n */\n reanchoredGaps: number\n /**\n * `audio-gap` decisions that could not be sized and were re-anchored\n * instead: the AU after the gap, or the last good AU, carried no authored\n * ISO-BMFF timing, or the two were authored in different media timescales.\n * libmmt only decides an `audio-gap` from authored ticks (`decideGap`), so\n * non-zero means a caller handed the assembler a decision without the\n * timing it was computed from.\n */\n untimedGaps: number\n}\n\nexport interface BlockAssemblerConfig {\n /** Number of source symbols per FEC block */\n k: number\n /** Timescale for CMAF segments (default 1_000_000 = microseconds) */\n timescale?: number\n /** ISO track ID (default 1) */\n trackId?: number\n /** Track type \u2014 determines init segment format and audio concealment */\n trackType: 'video' | 'audio'\n /** Video/audio codec string (e.g. 'avc1.64002a', 'mp4a.40.2'). */\n codec?: string\n // Video config (required when trackType='video')\n /** Raw avcC payload from catalog description \u2014 for the init segment */\n avcC?: Uint8Array\n /** Raw hvcC payload for an HEVC init segment (e.g. built from in-band\n * VPS/SPS/PPS by `generateHvcCFromParameterSets`). Requires `codec` to name\n * the `hev1` or `hvc1` sample entry. */\n hvcC?: Uint8Array\n /** Video width in pixels */\n width?: number\n /** Video height in pixels */\n height?: number\n // Audio config (required when trackType='audio')\n /** Audio codec string (e.g. 'mp4a.40.2', 'opus') */\n audioCodec?: string\n /** Audio sample rate (e.g. 48000) */\n sampleRate?: number\n /** Audio channel count (e.g. 1 or 2) */\n channels?: number\n /** Raw AudioSpecificConfig from catalog */\n asc?: Uint8Array\n // Shared\n /** Frames per second \u2014 fallback for duration estimation */\n fps?: number\n /** Explicit sample ordering policy. Datagram/FEC callers use media-window. */\n sampleOrder?: CmafSampleOrderPolicy\n /**\n * Bounded sample reorder depth for callback mode.\n *\n * Default 0 preserves immediate emission. When set on video tracks with\n * onSample enabled, samples are sorted by timestamp and the oldest sample is\n * emitted only after this many newer samples are available.\n * @deprecated Use sampleOrder with an explicit policy.\n */\n sampleReorderWindow?: number\n /**\n * Authored-timing admission for this track (default `true` \u2014 admitted).\n *\n * This is the rollback switch named by the authored-audio-CTS contract's\n * removal gate (BLO-30397). Assemblers are keyed on\n * `(packetId, catalogTrackName)` (`mmtp-router.ts` `#mseAssemblerKey`), so\n * this switch is per **track**. A producer feeding several tracks must be\n * de-admitted on each of them: nothing applies it across a track set\n * (BLO-34821).\n *\n * Set `false` and a sample carrying `authoredTiming` is **rejected**, not\n * zeroed: the contract forbids rolling back \"by zeroing already-authored\n * offsets\", because a zeroed offset is byte-indistinguishable from a feed\n * that authored nothing (BLO-30401 measured both as 0 A/V skew). Raw samples\n * \u2014 those with no `authoredTiming` at all \u2014 are unaffected and keep emitting\n * a v0 trun with no composition-offset field.\n */\n admitAuthoredTiming?: boolean\n}\n\ninterface OrderedSample extends CmafBlockSample {\n advancesHorizon: boolean\n}\n\nexport class CmafBlockAssembler {\n #config: Required<\n Pick<\n BlockAssemblerConfig,\n 'k' | 'timescale' | 'trackId' | 'trackType' | 'admitAuthoredTiming'\n >\n >\n #pendingRecovered = new Map<number, BlockFrame>()\n #sequence = 1\n #baseTs = -1\n /**\n * Last decoder-proven audio AU, repeated into slots a gap decision names.\n * It is noted and planned on the AU's authored clock (`AuthoredTiming`\n * ticks), never on this assembler's CMAF timescale: on the default\n * 1_000_000 an AAC AU is 1024e6 / sampleRate \u00B5s, which is not an integer.\n */\n #audioConcealer = new AudioGapConcealer<Uint8Array>()\n /**\n * Media timescale of the AU the concealer holds; `'untimed'` when the last\n * emitted audio AU carried no authored timing, `null` before any AU.\n */\n #audioConcealClock: number | 'untimed' | null = null\n #audioConcealStats: CmafAudioConcealStats = {\n repeatedUnits: 0,\n reanchoredGaps: 0,\n untimedGaps: 0,\n }\n #frameDuration: number\n #lastEmittedTs = -1\n #lastSourceTs = -1\n #sampleReorderWindow = 0\n #sampleOrder: CmafSampleOrderPolicy = { mode: 'arrival' }\n #sampleOrderCapacity = 0\n #sampleReorderQueue: OrderedSample[] = []\n #recoveredHorizonTs = -1\n #sampleOrderStats: CmafSampleOrderStats = {\n staleSamples: 0,\n duplicateSamples: 0,\n preRapDeadlineDrops: 0,\n noRapFlushDrops: 0,\n forcedReleases: 0,\n unadmittedAuthoredSamples: 0,\n unreadableVideoSamples: 0,\n }\n /** Codec family whose bitstream keyframe rule overrides the metadata flag\n * (AVC IDR, HEVC IRAP), or null when the bitstream is not validated. */\n #videoKeyframeFamily: VideoCodecFamily | null = null\n /** HEVC sample entry chosen from the catalog codec string. */\n #hevcSampleEntry: 'hev1' | 'hvc1' | null = null\n #keyframeRejectDumpCount = 0\n\n /** Callback: emits a complete moof+mdat CMAF segment */\n onSegment: ((segment: Uint8Array) => void) | null = null\n /** Callback: emits a gated/deduped raw sample for callers that already own the MSE timeline. */\n onSample: ((sample: CmafBlockSample) => void) | null = null\n /** Callback: emits an init segment (ftyp+moov) */\n onInitSegment: ((init: Uint8Array) => void) | null = null\n\n // Video keyframe gate (BLO-3035 layer 3): Chrome's CHUNK_DEMUXER rejects a\n // moof+mdat whose first sample is non-sync with no prior reference frames\n // (\"CHUNK_DEMUXER_ERROR_APPEND_FAILED: Failed to prepare video sample for\n // decode\") and detaches the SourceBuffer for the rest of the session.\n // Mid-stream join almost guarantees the first FEC blocks are mid-GOP \u2014 all\n // delta frames. Gate emission until the first block containing an IDR;\n // within that block, splice samples to start at the IDR index. Audio passes\n // unconditionally \u2014 valid for the codecs supported here (AAC, Opus) where\n // every frame is independently decodable. SBR-only AAC, USAC, or HE-AAC v2\n // with PCE re-entry would need a similar gate.\n #armedVideo = false\n\n /** Truncate `frames` to start at the first keyframe for video tracks before\n * the first emission. Returns the (possibly spliced) frames, or null to\n * drop the block entirely. Audio + already-armed video: identity. */\n #applyVideoKeyframeGate<T extends { data: Uint8Array; keyframe: boolean }>(frames: T[]): T[] | null {\n const keyedFrames = this.#normalizeVideoKeyframes(frames)\n if (this.#config.trackType !== 'video' || this.#armedVideo) return keyedFrames\n const firstKfIdx = keyedFrames.findIndex(f => f.keyframe)\n if (firstKfIdx < 0) return null\n return firstKfIdx === 0 ? keyedFrames : keyedFrames.slice(firstKfIdx)\n }\n\n #normalizeVideoKeyframes<T extends { data: Uint8Array; keyframe: boolean }>(frames: T[]): T[] {\n if (this.#config.trackType !== 'video' || this.#videoKeyframeFamily === null) return frames\n const out: T[] = []\n for (const frame of frames) {\n const effective = this.#withEffectiveVideoKeyframe(frame)\n if (effective !== null) out.push(effective)\n }\n return out\n }\n\n /** The frame with its bitstream keyframe (and, for HEVC, mdat framing);\n * null when the frame is refused and must not be emitted. */\n #withEffectiveVideoKeyframe<T extends { data: Uint8Array; keyframe: boolean }>(frame: T): T | null {\n if (this.#config.trackType !== 'video' || this.#videoKeyframeFamily === null) return frame\n if (this.#videoKeyframeFamily === 'hevc') {\n // HEVC keyframe = IRAP (H.265 Table 7-1). The mdat carries 4-byte\n // length-prefixed NAL units to match the hvcC's lengthSizeMinusOne = 3;\n // normalization is idempotent, so a frame seen twice is unchanged. A\n // frame that cannot be read is refused, not written as-is and not\n // passed off as a delta frame.\n const prepared = prepareHevcCmafSample(frame.data, this.#hevcSampleEntry!)\n if (prepared === null) {\n this.#sampleOrderStats.unreadableVideoSamples++\n return null\n }\n const { keyframe, data } = prepared\n if (!keyframe) this.#dumpRejectedVideoKeyframe(frame.data, frame.keyframe)\n return keyframe === frame.keyframe && data === frame.data ? frame : { ...frame, keyframe, data }\n }\n const keyframe = detectH264Keyframe(frame.data)\n if (!keyframe) this.#dumpRejectedVideoKeyframe(frame.data, frame.keyframe)\n return keyframe === frame.keyframe ? frame : { ...frame, keyframe }\n }\n\n #dumpRejectedVideoKeyframe(data: Uint8Array, metadataKeyframe: boolean): void {\n if (this.#keyframeRejectDumpCount >= 12) return\n this.#keyframeRejectDumpCount++\n if (this.#videoKeyframeFamily === 'hevc') {\n const nals = isCompleteAvccSample(data)\n ? splitAvccNalUnits(data)\n : isAnnexB(data) ? splitAnnexBNalUnits(data) : []\n console.log(\n `[L4-KF-GATE] reject#${this.#keyframeRejectDumpCount} len=${data.length} ` +\n `metadataKf=${metadataKeyframe} family=hevc ` +\n `nalTypes=[${nals.slice(0, 16).map((nal) => (nal.length >= 2 ? hevcNalUnitType(nal) : -1)).join(',')}]`,\n )\n return\n }\n const sample = splitH264SampleNalUnits(data)\n const nalTypes = describeH264NalTypes(sample.nals)\n const classify = classifyH264Keyframe(data)\n const hex = Array.from(data.subarray(0, Math.min(48, data.length)))\n .map(b => (b as number).toString(16).padStart(2, '0'))\n .join(' ')\n console.log(\n `[L4-KF-GATE] reject#${this.#keyframeRejectDumpCount} len=${data.length} ` +\n `metadataKf=${metadataKeyframe} classify=${classify} format=${sample.format} ` +\n `nalTypes=[${nalTypes.join(',')}] first48=[${hex}]`,\n )\n }\n\n /** Mark video as already synchronized by an external decoder path.\n * Used by MoQ\u2192multicast MSE continuity when MoQ has already appended a\n * keyframe to the same SourceBuffer timeline before multicast takeover. */\n markVideoSynced(): void {\n if (this.#config.trackType === 'video') this.#armedVideo = true\n }\n\n /** Emit each frame as its own single-sample moof+mdat segment. Matches the\n * case-20 path (`MmtpToCmaf.wrapVideoSample` \u2192 `encodeDataSegment`) byte-\n * for-byte per frame. Working hypothesis (pending Chromium-source\n * validation against `media/filters/chunk_demuxer.cc`):\n * `encodeMultiSampleSegment` blobs are accepted by ChunkDemuxer in this\n * pipeline but only the first sample renders for live, possibly because\n * the pipeline expects per-frame moof boundaries. Track in BLO-3035.\n *\n * Stale-tfdt defense-in-depth: drops any frame whose timestamp is older\n * than `#lastEmittedTs`. The SBN watermark already prevents out-of-order\n * FEC-block emissions, but `addBypassFrame` (oversized MFU / no-FEC path)\n * doesn't touch the watermark \u2014 a bypass frame at t=T followed by a FEC\n * block whose frames precede T would otherwise inject earlier tfdt and\n * detach the SourceBuffer. */\n #ordersSamples(): boolean {\n return this.#sampleOrder.mode === 'media-window' || this.#sampleReorderWindow > 0\n }\n\n #unwrapTimestamp(timestamp: number): number {\n const wrapPeriod = this.#sampleOrder.mode === 'media-window'\n ? this.#sampleOrder.timestampWrapPeriod\n : undefined\n if (!wrapPeriod) return timestamp\n const reference = this.#lastSourceTs >= 0\n ? this.#lastSourceTs\n : this.#recoveredHorizonTs >= 0\n ? this.#recoveredHorizonTs\n : this.#lastEmittedTs\n if (reference < 0) return timestamp\n return timestamp + Math.round((reference - timestamp) / wrapPeriod) * wrapPeriod\n }\n\n #emitSample(\n data: Uint8Array,\n timestamp: number,\n duration: number,\n keyframe: boolean,\n advancesHorizon: boolean,\n catalogTrackName: string | undefined,\n mpuSequenceNumber: number | undefined,\n packetSequenceNumber: number | undefined,\n packetSequenceNumbers: number[] | undefined,\n repairedPacketSequenceNumbers: number[] | undefined,\n authoredTiming: AuthoredTiming | undefined,\n // Required, not optional: an omitted optional argument is silently\n // undefined, which is exactly how this field went missing from the\n // recovered path in the first place. Callers with nothing to declare pass\n // `undefined` on purpose.\n deliveryProvenance: MmtpDeliveryProvenance | undefined,\n /** Raw MMTP short-NTP header timestamp for telemetry only. */\n mmtpTimestamp: bigint | undefined,\n // Same rule as deliveryProvenance: required so a caller cannot drop the\n // timed-MFU identity by omission. Untimed MFUs pass `undefined`.\n movieFragmentSequenceNumber: number | undefined,\n sampleNumber: number | undefined,\n /** True only for locally generated concealment samples. */\n synthetic: boolean | undefined,\n /** libmmt's decision for the gap before this sample, carried to sinks. */\n gapBefore: FrameGapDecision | undefined,\n ): void {\n // Authored-timing admission \u2014 the rollback switch the BLO-30397 removal\n // gate names. Refuse the sample outright rather than stripping its offset:\n // the contract forbids rolling back \"by zeroing already-authored offsets\",\n // and BLO-30401 measured why \u2014 a zeroed offset and a never-authored one are\n // behaviourally identical downstream (same buffered ranges, same duration,\n // no diagnostic), so a silent strip would look exactly like success while\n // audio ran early forever. A de-admitted producer is expected to revert to\n // raw batches, which are untouched by this branch.\n if (authoredTiming !== undefined && !this.#config.admitAuthoredTiming) {\n this.#sampleOrderStats.unadmittedAuthoredSamples++\n return\n }\n const scaledTiming = authoredTiming === undefined\n ? null\n : scaleAuthoredTiming(authoredTiming, this.#config.timescale)\n if (authoredTiming !== undefined && scaledTiming === null) return\n const authoredTimestamp = scaledTiming?.timestamp ?? timestamp\n const authoredDuration = scaledTiming?.duration ?? duration\n let compositionTimeOffset: number | undefined\n if (authoredTiming !== undefined) {\n const scaledOffset = scaleAuthoredTicks(\n authoredTiming.presentationTime - authoredTiming.decodeTime,\n authoredTiming.mediaTimescale,\n this.#config.timescale,\n )\n if (scaledOffset === null) return\n // trun stores composition offsets as integer target-timescale ticks.\n // Preserve the nearest representable tick, then enforce the signed\n // int32 serialization range on the rounded value.\n const roundedOffset = Math.round(scaledOffset)\n if (\n !Number.isSafeInteger(roundedOffset) ||\n roundedOffset < INT32_MIN ||\n roundedOffset > INT32_MAX\n ) return\n compositionTimeOffset = roundedOffset\n }\n const unwrappedTimestamp = this.#unwrapTimestamp(authoredTimestamp)\n if (unwrappedTimestamp <= this.#lastEmittedTs) {\n this.#sampleOrderStats.staleSamples++\n return\n }\n\n const sample = this.#withEffectiveVideoKeyframe({\n data,\n timestamp: unwrappedTimestamp,\n duration: authoredDuration,\n keyframe,\n ...(mmtpTimestamp === undefined ? {} : { mmtpTimestamp }),\n ...(compositionTimeOffset === undefined ? {} : { compositionTimeOffset }),\n advancesHorizon,\n ...(authoredTiming === undefined ? {} : { authoredTiming }),\n ...(packetSequenceNumber === undefined ? {} : { packetSequenceNumber }),\n ...(packetSequenceNumbers === undefined ? {} : { packetSequenceNumbers }),\n ...(repairedPacketSequenceNumbers === undefined\n ? {}\n : { repairedPacketSequenceNumbers }),\n ...(mpuSequenceNumber === undefined ? {} : { mpuSequenceNumber }),\n ...(movieFragmentSequenceNumber === undefined ? {} : { movieFragmentSequenceNumber }),\n ...(sampleNumber === undefined ? {} : { sampleNumber }),\n ...(catalogTrackName === undefined ? {} : { catalogTrackName }),\n ...(deliveryProvenance === undefined ? {} : { deliveryProvenance }),\n ...(synthetic === undefined ? {} : { synthetic }),\n ...(gapBefore === undefined ? {} : { gapBefore }),\n })\n if (sample === null) return\n if (advancesHorizon && unwrappedTimestamp > this.#lastSourceTs) {\n this.#lastSourceTs = unwrappedTimestamp\n } else if (!advancesHorizon && unwrappedTimestamp > this.#recoveredHorizonTs) {\n this.#recoveredHorizonTs = unwrappedTimestamp\n }\n\n if (this.#ordersSamples()) {\n this.#queueSample(sample)\n return\n }\n this.#emitArrivalOrdered(sample)\n }\n\n #emitArrivalOrdered(sample: OrderedSample): void {\n if (this.#config.trackType === 'video' && !this.#armedVideo && !sample.keyframe) {\n this.#sampleOrderStats.preRapDeadlineDrops++\n return\n }\n this.#emitSampleNow(sample)\n }\n\n #queueSample(sample: OrderedSample): void {\n if (this.#sampleReorderQueue.some(s => s.timestamp === sample.timestamp)) {\n this.#sampleOrderStats.duplicateSamples++\n return\n }\n this.#sampleReorderQueue.push(sample)\n this.#sampleReorderQueue.sort((a, b) => a.timestamp - b.timestamp)\n this.#drainSampleReorder(false)\n this.#enforceSampleOrderCapacity()\n }\n\n #releaseHorizon(): number {\n return this.#lastSourceTs >= 0 ? this.#lastSourceTs : this.#recoveredHorizonTs\n }\n\n #sampleIsReleasable(sample: OrderedSample, flushAll: boolean): boolean {\n if (flushAll) return true\n if (this.#sampleOrder.mode === 'media-window') {\n const horizon = this.#releaseHorizon()\n return horizon >= 0 && sample.timestamp < horizon - this.#sampleOrder.deliveryWindow\n }\n return this.#sampleReorderQueue.length > this.#sampleReorderWindow\n }\n\n #dropPreRapSamples(flushAll: boolean): boolean {\n if (this.#config.trackType !== 'video' || this.#armedVideo) return false\n\n const firstRap = this.#sampleReorderQueue.findIndex(\n sample => sample.keyframe && this.#sampleIsReleasable(sample, flushAll),\n )\n if (firstRap >= 0) {\n if (firstRap > 0) {\n this.#sampleOrderStats.preRapDeadlineDrops += firstRap\n this.#sampleReorderQueue.splice(0, firstRap)\n }\n return false\n }\n\n let dropped = 0\n while (\n this.#sampleReorderQueue[0] &&\n this.#sampleIsReleasable(this.#sampleReorderQueue[0]!, flushAll)\n ) {\n this.#sampleReorderQueue.shift()\n dropped++\n }\n if (flushAll) this.#sampleOrderStats.noRapFlushDrops += dropped\n else this.#sampleOrderStats.preRapDeadlineDrops += dropped\n return dropped > 0\n }\n\n #drainSampleReorder(flushAll: boolean): void {\n while (this.#sampleReorderQueue.length > 0) {\n if (this.#dropPreRapSamples(flushAll) && this.#sampleReorderQueue.length === 0) return\n const sample = this.#sampleReorderQueue[0]\n if (!sample || !this.#sampleIsReleasable(sample, flushAll)) return\n this.#sampleReorderQueue.shift()\n this.#emitQueuedSample(sample)\n }\n }\n\n #emitQueuedSample(sample: OrderedSample): void {\n const next = this.#sampleReorderQueue.find(s => s.timestamp > sample.timestamp)\n const duration = sample.authoredTiming\n ? sample.duration\n : next ? next.timestamp - sample.timestamp : sample.duration\n this.#emitSampleNow({\n ...sample,\n duration: duration > 0\n ? duration\n : sample.authoredTiming ? sample.duration : this.#frameDuration,\n })\n }\n\n #enforceSampleOrderCapacity(): void {\n if (this.#sampleOrder.mode !== 'media-window') return\n while (this.#sampleReorderQueue.length > this.#sampleOrderCapacity) {\n const sample = this.#sampleReorderQueue.shift()\n if (!sample) return\n this.#sampleOrderStats.forcedReleases++\n console.warn(\n `[CmafBlockAssembler] ${this.#config.trackType} media-window queue exceeded ` +\n `${this.#sampleOrderCapacity} samples; force-releasing timestamp=${sample.timestamp}`,\n )\n if (this.#config.trackType === 'video' && !this.#armedVideo && !sample.keyframe) {\n this.#sampleOrderStats.preRapDeadlineDrops++\n continue\n }\n this.#emitQueuedSample(sample)\n }\n }\n\n #emitSampleNow(sample: CmafBlockSample): void {\n if (sample.timestamp <= this.#lastEmittedTs) {\n this.#sampleOrderStats.staleSamples++\n return\n }\n this.#concealAudioGapBefore(sample)\n this.#writeSampleNow(sample, true)\n }\n\n #writeSampleNow(sample: CmafBlockSample, rememberAudio: boolean): void {\n const { timestamp, duration, keyframe } = sample\n this.#lastEmittedTs = timestamp\n if (this.#config.trackType === 'video' && keyframe) this.#armedVideo = true\n const data = this.#normalizeSampleData(sample.data)\n if (this.#config.trackType === 'audio' && rememberAudio && data.length > 0) {\n // Keep decoder-proven codec data for concealment of a later gap that\n // libmmt's release gate decided, on the AU's own authored clock.\n this.#noteAudioAccessUnit(data, sample.authoredTiming)\n }\n if (this.onSample) {\n this.onSample(data === sample.data ? sample : { ...sample, data })\n } else {\n const baseTime = this.#rebase(timestamp)\n const segment = encodeDataSegment(\n data,\n baseTime,\n duration,\n keyframe,\n this.#sequence++,\n this.#config.trackId,\n sample.compositionTimeOffset,\n )\n this.onSegment?.(segment)\n }\n }\n\n /**\n * Record an emitted audio AU for concealment in its authored media ticks \u2014\n * the clock libmmt's `audio-gap` decision was computed in, where an AAC AU\n * is exactly 1024 ticks. An AU with no authored timing has no exact clock,\n * so nothing is held for it and a later `audio-gap` is counted as untimed.\n */\n #noteAudioAccessUnit(data: Uint8Array, timing: AuthoredTiming | undefined): void {\n if (timing === undefined) {\n this.#audioConcealer.reset()\n this.#audioConcealClock = 'untimed'\n return\n }\n this.#audioConcealer.note({\n payload: data,\n pts: timing.presentationTime,\n duration: timing.durationTicks,\n })\n this.#audioConcealClock = timing.mediaTimescale\n }\n\n /**\n * Repeat the last good AU into exactly the slots an `audio-gap` decision\n * names. A synthesised AAC access unit is not portable across every\n * AudioSpecificConfig, so only known-good encoded audio is repeated; with\n * no good AU yet, or on `audio-discontinuity`, the sink re-anchors at the\n * next sample and nothing is written.\n *\n * The gap is sized in authored ticks and each slot is mapped onto this\n * assembler's timescale by `scaleAuthoredTiming`, the conversion every\n * source AU goes through, so a slot lands exactly where the AU it replaces\n * would have. Nothing here can throw into the packet path: a gap that\n * cannot be sized exactly is re-anchored and counted.\n */\n #concealAudioGapBefore(sample: CmafBlockSample): void {\n const decision = sample.gapBefore\n if (this.#config.trackType !== 'audio' || !decision || decision.trackKind !== 'audio') return\n const timing = sample.authoredTiming\n const clock = this.#audioConcealClock\n if (\n timing === undefined ||\n clock === 'untimed' ||\n (clock !== null && clock !== timing.mediaTimescale)\n ) {\n // No single authored clock covers both this AU and the one held, so\n // the gap has no exact size in ticks.\n if (decision.reason === 'audio-gap') this.#audioConcealStats.untimedGaps++\n else this.#audioConcealStats.reanchoredGaps++\n return\n }\n const plan = this.#audioConcealer.plan(decision, { pts: timing.presentationTime })\n if (plan.kind !== 'conceal') {\n this.#audioConcealStats.reanchoredGaps++\n return\n }\n for (const slot of plan.repeat) {\n // Every input here is one this sample's own timing already scaled\n // successfully (same media timescale and duration, an earlier pts), so\n // the conversion cannot fail for a slot.\n const scaled = scaleAuthoredTiming({\n decodeTime: slot.pts,\n presentationTime: slot.pts,\n durationTicks: slot.duration,\n mediaTimescale: timing.mediaTimescale,\n }, this.#config.timescale)\n if (scaled === null) continue\n const slotTimestamp = this.#unwrapTimestamp(scaled.timestamp)\n if (slotTimestamp <= this.#lastEmittedTs || slotTimestamp >= sample.timestamp) continue\n this.#writeSampleNow({\n data: slot.payload.slice(),\n timestamp: slotTimestamp,\n duration: scaled.duration,\n keyframe: true,\n synthetic: true,\n }, false)\n this.#audioConcealStats.repeatedUnits++\n }\n }\n\n #emitPerSample(\n frames: BlockFrame[],\n audioDurationOverride?: number,\n advancesHorizon = false,\n ): void {\n for (let i = 0; i < frames.length; i++) {\n const f = frames[i]!\n // Per-frame duration from delta to next frame, or fallback.\n let duration: number\n if (this.#config.trackType === 'audio') {\n duration = audioDurationOverride ?? this.#frameDuration\n } else if (i < frames.length - 1) {\n duration = frames[i + 1]!.timestamp - f.timestamp\n } else if (i > 0) {\n duration = f.timestamp - frames[i - 1]!.timestamp\n } else {\n duration = audioDurationOverride ?? this.#frameDuration\n }\n if (duration <= 0) duration = audioDurationOverride ?? this.#frameDuration\n this.#emitSample(\n f.data,\n f.timestamp,\n duration,\n f.keyframe,\n advancesHorizon,\n f.catalogTrackName,\n f.mpuSequenceNumber,\n f.packetSequenceNumber,\n f.packetSequenceNumbers,\n f.repairedPacketSequenceNumbers,\n f.authoredTiming,\n f.deliveryProvenance,\n f.mmtpTimestamp,\n f.movieFragmentSequenceNumber,\n f.sampleNumber,\n f.synthetic,\n f.gapBefore,\n )\n }\n }\n\n // Cumulative emit counters (see emitStats). They replace the BLO-3035 L4\n // diagnostics, which hashed and hex-dumped every video keyframe and ran a\n // 1 s setInterval console aggregate on the MSE path (BLO-36599).\n #emitStats: CmafEmitStats = {\n emits: 0,\n samples: 0,\n keyframes: 0,\n addedFrames: 0,\n recoveredBlocks: 0,\n completedBlocks: 0,\n failedBlocks: 0,\n }\n\n #countEmit(samples: ReadonlyArray<{ keyframe: boolean }>): void {\n this.#emitStats.emits++\n this.#emitStats.samples += samples.length\n for (const sample of samples) if (sample.keyframe) this.#emitStats.keyframes++\n }\n\n constructor(config: BlockAssemblerConfig) {\n this.#config = {\n k: config.k,\n timescale: config.timescale ?? 1_000_000,\n trackId: config.trackId ?? 1,\n trackType: config.trackType,\n admitAuthoredTiming: config.admitAuthoredTiming ?? true,\n }\n\n // Compute default frame duration from fps (updated from timestamp deltas at runtime)\n if (config.fps && config.fps > 0) {\n this.#frameDuration = Math.round(this.#config.timescale / config.fps)\n } else if (config.trackType === 'audio' && config.sampleRate) {\n this.#frameDuration = Math.round(this.#config.timescale * 1024 / config.sampleRate)\n } else {\n // No fps info \u2014 will be refined from actual timestamp deltas\n this.#frameDuration = 33333\n }\n\n const sampleReorderWindow = config.sampleReorderWindow ?? 0\n if (!Number.isFinite(sampleReorderWindow) || sampleReorderWindow < 0) {\n throw new Error('[CmafBlockAssembler] sampleReorderWindow must be finite and non-negative')\n }\n if (config.sampleOrder && sampleReorderWindow > 0) {\n throw new Error('[CmafBlockAssembler] configure sampleOrder or sampleReorderWindow, not both')\n }\n this.#sampleReorderWindow = Math.floor(sampleReorderWindow)\n this.#sampleOrder = config.sampleOrder ?? { mode: 'arrival' }\n if (this.#sampleOrder.mode === 'media-window') {\n const { deliveryWindow, timestampWrapPeriod } = this.#sampleOrder\n if (!Number.isSafeInteger(deliveryWindow) || deliveryWindow <= 0) {\n throw new Error(\n '[CmafBlockAssembler] media-window deliveryWindow must be a positive safe integer',\n )\n }\n if (\n timestampWrapPeriod !== undefined &&\n (!Number.isSafeInteger(timestampWrapPeriod) || timestampWrapPeriod <= deliveryWindow * 2)\n ) {\n throw new Error(\n '[CmafBlockAssembler] timestampWrapPeriod must be a safe integer larger than two delivery windows',\n )\n }\n const samplesPerSecond = config.trackType === 'audio' && config.sampleRate\n ? config.sampleRate / 1024\n : config.fps\n if (!samplesPerSecond || !Number.isFinite(samplesPerSecond) || samplesPerSecond <= 0) {\n throw new Error(\n '[CmafBlockAssembler] media-window ordering requires catalog-derived media cadence',\n )\n }\n this.#sampleOrderCapacity =\n Math.ceil(deliveryWindow * samplesPerSecond / this.#config.timescale) + 1\n }\n const videoSampleEntry = config.trackType === 'video' ? resolveVideoSampleEntry(config) : null\n this.#videoKeyframeFamily = videoSampleEntry === null\n ? null\n : videoSampleEntry === 'unvalidated' ? null : videoCodecFamily(videoSampleEntry)\n this.#hevcSampleEntry = videoSampleEntry === 'hev1' || videoSampleEntry === 'hvc1' ? videoSampleEntry : null\n if (config.trackType === 'video') {\n console.log(\n `[L4-KF-CONFIG] validate=${this.#videoKeyframeFamily ?? false} ` +\n `codec=${config.codec ?? ''} avcC=${config.avcC?.length ?? 0} hvcC=${config.hvcC?.length ?? 0}`,\n )\n }\n\n // Store config for init segment generation\n this._videoConfig = config.trackType === 'video' && config.avcC\n ? { avcC: config.avcC, width: config.width ?? 0, height: config.height ?? 0 }\n : config.trackType === 'video' && config.hvcC && this.#hevcSampleEntry\n ? {\n hvcC: config.hvcC,\n hevcSampleEntry: this.#hevcSampleEntry,\n width: config.width ?? 0,\n height: config.height ?? 0,\n }\n : null\n this._audioConfig = config.trackType === 'audio' && config.sampleRate && config.channels\n ? { sampleRate: config.sampleRate, channels: config.channels, asc: config.asc }\n : null\n }\n\n private _videoConfig: {\n avcC?: Uint8Array\n hvcC?: Uint8Array\n hevcSampleEntry?: 'hev1' | 'hvc1'\n width: number\n height: number\n } | null\n private _audioConfig: { sampleRate: number; channels: number; asc?: Uint8Array } | null\n\n get sampleOrderStats(): Readonly<CmafSampleOrderStats> {\n return { ...this.#sampleOrderStats }\n }\n\n /** Cumulative emit and block-event counters since construction. */\n get emitStats(): Readonly<CmafEmitStats> {\n return { ...this.#emitStats }\n }\n\n /** Cumulative audio gap concealment counters since construction. */\n get audioConcealStats(): Readonly<CmafAudioConcealStats> {\n return { ...this.#audioConcealStats }\n }\n\n /** Emit a single frame immediately as a one-sample moof+mdat segment.\n *\n * BLO-3035 layer 4 (4b): the prior SBN-grouped buffering scheme stranded\n * frames whenever a multi-packet frame spanned FEC block boundaries \u2014\n * intermediate SBNs had packets-but-no-frames and got `completeBlock`\n * events that landed on empty `#blocks` (\u2192 `pendingFlush` leak), while\n * the SBN where the multi-packet frame finally completed received the\n * `addFrame` but its `trackBlock` count never reached K (\u2192 `pendingBlocks`\n * leak). Result: ~50% of received frames never reached MSE.\n *\n * This path now mirrors `addBypassFrame` \u2014 emit on arrival, no buffering.\n * FEC recovery (`addRecoveredBlock`) keeps its SBN-watermark dedup against\n * the same SBN being re-emitted from two paths. Out-of-order regression\n * is guarded by the per-frame `lastEmittedTs` check (also enforced in\n * `#emitPerSample`). The `sbn`/`esi` parameters are kept for the call-site\n * signature but no longer affect routing. */\n addFrame(\n sbn: number,\n esi: number,\n data: Uint8Array,\n timestamp: number,\n keyframe: boolean,\n catalogTrackName?: string,\n mpuSequenceNumber?: number,\n packetSequenceNumber?: number,\n packetSequenceNumbers?: number[],\n repairedPacketSequenceNumbers?: number[],\n authoredTiming?: AuthoredTiming,\n deliveryProvenance?: MmtpDeliveryProvenance,\n mmtpTimestamp?: bigint,\n movieFragmentSequenceNumber?: number,\n sampleNumber?: number,\n gapBefore?: FrameGapDecision,\n ): void {\n void sbn; void esi\n this.#emitStats.addedFrames++\n\n if (!this.#ordersSamples()) this.#drainRecoveredUpTo(timestamp)\n\n // Per-frame duration: default to catalog-derived `#frameDuration`. For\n // variable-rate content Chrome refines duration from the next sample's\n // DTS at append time, so a fallback here is safe.\n this.#emitSample(\n data,\n timestamp,\n this.#frameDuration,\n keyframe,\n true,\n catalogTrackName,\n mpuSequenceNumber,\n packetSequenceNumber,\n packetSequenceNumbers,\n repairedPacketSequenceNumbers,\n authoredTiming,\n deliveryProvenance,\n mmtpTimestamp,\n movieFragmentSequenceNumber,\n sampleNumber,\n undefined,\n gapBefore,\n )\n\n this.#countEmit([{ keyframe }])\n }\n\n /** Mark a block as complete (all K source symbols received or FEC recovery succeeded).\n * If all frames are already buffered, flushes immediately. Otherwise sets pending-flush. */\n completeBlock(sbn: number): void {\n void sbn\n this.#emitStats.completedBlocks++\n // Source samples are emitted directly from addFrame(). A clean FEC block\n // completion is still useful for stats, but it must not enqueue stale\n // pending flushes from the retired block-buffered path.\n }\n\n /**\n * Record an unrecoverable block. Nothing is synthesised: the release gate\n * attaches the stall/conceal decision to the next released frame, and the\n * sink holds the last good frame (video) or repeats the last good AU into\n * the decided slots (audio).\n */\n failBlock(sbn: number): void {\n void sbn\n this.#emitStats.failedBlocks++\n }\n\n /** Add all frames from a FEC-recovered block at once and emit immediately. */\n addRecoveredBlock(sbn: number, frames: BlockFrame[]): void {\n void sbn\n this.#emitStats.recoveredBlocks++\n\n if (frames.length === 0) return\n const normalized = this.#normalizeVideoKeyframes(frames)\n if (normalized.length === 0) return\n this.#countEmit(normalized)\n if (this.#ordersSamples()) {\n this.#emitPerSample(normalized, undefined, false)\n return\n }\n\n // Arrival mode preserves the legacy protection against future recovered\n // samples advancing past source media. Explicit media-window mode routes\n // both paths through one queue instead.\n if (this.#lastSourceTs >= 0) {\n this.#enqueueRecovered(normalized)\n this.#drainRecoveredUpTo(this.#lastSourceTs)\n } else {\n const gated = this.#applyVideoKeyframeGate(normalized)\n if (gated) this.#emitPerSample(gated, undefined, false)\n }\n }\n\n /** Emit a single frame immediately as a one-sample segment (for oversized packets bypassing FEC). */\n addBypassFrame(\n data: Uint8Array,\n timestamp: number,\n keyframe: boolean,\n catalogTrackName?: string,\n mpuSequenceNumber?: number,\n packetSequenceNumber?: number,\n packetSequenceNumbers?: number[],\n repairedPacketSequenceNumbers?: number[],\n authoredTiming?: AuthoredTiming,\n deliveryProvenance?: MmtpDeliveryProvenance,\n mmtpTimestamp?: bigint,\n movieFragmentSequenceNumber?: number,\n sampleNumber?: number,\n gapBefore?: FrameGapDecision,\n ): void {\n if (!this.#ordersSamples()) this.#drainRecoveredUpTo(timestamp)\n this.#emitSample(\n data,\n timestamp,\n this.#frameDuration,\n keyframe,\n true,\n catalogTrackName,\n mpuSequenceNumber,\n packetSequenceNumber,\n packetSequenceNumbers,\n repairedPacketSequenceNumbers,\n authoredTiming,\n deliveryProvenance,\n mmtpTimestamp,\n movieFragmentSequenceNumber,\n sampleNumber,\n undefined,\n gapBefore,\n )\n }\n\n /** Build and emit init segment from catalog config. */\n emitInit(): void {\n let init: Uint8Array | null = null\n if (this._videoConfig?.avcC) {\n init = buildVideoInitSegment(\n this._videoConfig.avcC,\n this._videoConfig.width,\n this._videoConfig.height,\n this.#config.timescale,\n this.#config.trackId,\n )\n } else if (this._videoConfig?.hvcC && this._videoConfig.hevcSampleEntry) {\n init = buildHevcVideoInitSegment(\n this._videoConfig.hevcSampleEntry,\n this._videoConfig.hvcC,\n this._videoConfig.width,\n this._videoConfig.height,\n this.#config.timescale,\n this.#config.trackId,\n )\n } else if (this._audioConfig) {\n init = buildAudioInitSegment(\n this._audioConfig.sampleRate,\n this._audioConfig.channels,\n this._audioConfig.asc,\n this.#config.timescale,\n this.#config.trackId,\n )\n }\n if (init) this.onInitSegment?.(init)\n }\n\n /** Drain all ordered samples at end-of-stream or before reconfiguration. */\n flush(): void {\n if (this.#ordersSamples()) {\n this.#drainSampleReorder(true)\n return\n }\n if (this.#pendingRecovered.size === 0) return\n const frames = [...this.#pendingRecovered.values()].sort((a, b) => a.timestamp - b.timestamp)\n this.#pendingRecovered.clear()\n const gated = this.#applyVideoKeyframeGate(frames)\n if (gated) this.#emitPerSample(gated, undefined, false)\n else if (this.#config.trackType === 'video') {\n this.#sampleOrderStats.noRapFlushDrops += frames.length\n }\n }\n\n /** Drop all queued state and begin a fresh timestamp epoch. */\n reset(): void {\n this.#pendingRecovered.clear()\n this.#sequence = 1\n this.#baseTs = -1\n this.#lastEmittedTs = -1\n this.#lastSourceTs = -1\n this.#recoveredHorizonTs = -1\n this.#audioConcealer.reset()\n this.#audioConcealClock = null\n this.#armedVideo = false\n this.#sampleReorderQueue = []\n }\n\n dispose(): void {\n this.reset()\n this.onSegment = null\n this.onSample = null\n this.onInitSegment = null\n }\n\n // \u2500\u2500 Private \u2500\u2500\n\n /** Rebase an absolute timestamp to relative media time (starting near 0). */\n #rebase(timestamp: number): number {\n if (this.#baseTs < 0) this.#baseTs = timestamp\n return timestamp - this.#baseTs\n }\n\n #normalizeSampleData(data: Uint8Array): Uint8Array {\n return this.#config.trackType === 'audio' ? normalizeAacSampleForCmaf(data) : data\n }\n\n #enqueueRecovered(frames: BlockFrame[]): void {\n for (const frame of frames) {\n if (this.#lastEmittedTs >= 0 && frame.timestamp <= this.#lastEmittedTs) {\n this.#sampleOrderStats.staleSamples++\n continue\n }\n if (this.#pendingRecovered.has(frame.timestamp)) {\n this.#sampleOrderStats.duplicateSamples++\n continue\n }\n this.#pendingRecovered.set(frame.timestamp, frame)\n }\n }\n\n #drainRecoveredUpTo(horizonTs: number): void {\n if (this.#pendingRecovered.size === 0) return\n const ready = [...this.#pendingRecovered.values()]\n .filter(frame => frame.timestamp <= horizonTs)\n .sort((a, b) => a.timestamp - b.timestamp)\n\n for (const frame of ready) {\n this.#pendingRecovered.delete(frame.timestamp)\n this.#emitSample(\n frame.data,\n frame.timestamp,\n this.#frameDuration,\n frame.keyframe,\n false,\n frame.catalogTrackName,\n frame.mpuSequenceNumber,\n frame.packetSequenceNumber,\n frame.packetSequenceNumbers,\n frame.repairedPacketSequenceNumbers,\n frame.authoredTiming,\n frame.deliveryProvenance,\n frame.mmtpTimestamp,\n frame.movieFragmentSequenceNumber,\n frame.sampleNumber,\n frame.synthetic,\n frame.gapBefore,\n )\n this.#countEmit([frame])\n }\n }\n}\n\n/**\n * Video sample entry whose bitstream keyframe rule the assembler enforces,\n * selected from the catalog codec string (never sniffed):\n *\n * - `avc1`/`avc3`/`hev1`/`hvc1` from `config.codec`.\n * - No codec string: `avc1` (the legacy H.264 contract, which an avcC\n * confirms). An hvcC without a codec string is refused because the sample\n * entry (hev1 vs hvc1) cannot be chosen without it.\n * - Any other video codec (AV1, VP9): 'unvalidated' \u2014 its metadata keyframe\n * flag is trusted, as before.\n *\n * A configuration record that contradicts the codec family is refused.\n */\nfunction resolveVideoSampleEntry(config: BlockAssemblerConfig): VideoSampleEntry | 'unvalidated' {\n if (!config.codec) {\n if (config.hvcC) {\n throw new Error('[CmafBlockAssembler] hvcC requires a catalog codec string naming hev1 or hvc1')\n }\n return 'avc1'\n }\n const fourCc = config.codec.split('.')[0]\n if (fourCc !== 'avc1' && fourCc !== 'avc3' && fourCc !== 'hev1' && fourCc !== 'hvc1') {\n if (config.avcC || config.hvcC) {\n throw new Error(`[CmafBlockAssembler] codec ${config.codec} contradicts the supplied avcC/hvcC`)\n }\n return 'unvalidated'\n }\n const sampleEntry = videoSampleEntryFromCodecString(config.codec)\n const family = videoCodecFamily(sampleEntry)\n if ((family === 'avc' && config.hvcC) || (family === 'hevc' && config.avcC)) {\n throw new Error(`[CmafBlockAssembler] codec ${config.codec} contradicts the supplied avcC/hvcC`)\n }\n return sampleEntry\n}\n\nfunction describeH264NalTypes(nals: Uint8Array[]): number[] {\n return nals.slice(0, 16).map((nal) => (\n nal[0] !== undefined ? nal[0] & 0x1f : -1\n ))\n}\n", "/**\n * @mmt/container - Sample-level combining of subsample data units (moqcast #37)\n *\n * {@link MFUReassembler} reassembles exactly one data unit -- a whole-sample\n * DU, or one subsample DU of a partitioned sample. When a timed sample\n * exceeds one data unit's 256-payload capacity, the origin packetizer\n * partitions it into multiple subsample data units (each its own FI chain,\n * its own authored base offset). This module combines those\n * already-reassembled data units back into one contiguous sample.\n *\n * Container-blind, matching {@link MFUReassembler}'s own doctrine: it never\n * parses ISOBMFF itself. The authored sample size a subsample-partitioned\n * sample must total to comes from the host's own FT=1 (movie-fragment-\n * metadata) parse, supplied via {@link SampleCombiner.registerAuthoredSize}.\n * Completion is a protocol event -- every constituent data unit reassembled,\n * byte-adjacent from zero, totaling the registered size -- never a\n * timer-based guess; on lossy paths the existing per-data-unit deadline in\n * {@link MFUReassembler} already bounds each constituent, so this module adds\n * no second timer tier, matching moqcast #37 section 5.2.1.\n *\n * A whole-sample data unit whose length already equals the registered\n * authored size passes through immediately, with no buffering. When\n * `requireAuthoredSize` is false, an offset-zero data unit with no registered\n * size at all also passes through immediately -- the pre-amendment shape, for\n * a host that does not drive FT=1. When true, that same data unit instead\n * buffers and waits for a size to be registered: FT=1 always publishes before\n * any FT=2 sample referencing it (moqcast #37), but on a lossy path FT=1 can\n * still *arrive* after an offset-zero data unit (reordering, or FT=1's own DU\n * FEC-recovered late) -- treating \"no size yet\" as \"whole sample\" in that\n * window would silently truncate a subsample-partitioned sample.\n *\n * Both `#pending` (incomplete samples) and `#authoredSizes` (registered but\n * not yet consumed) are bounded. `#pending` is bounded by `maxBuffered`\n * samples and `maxSegmentsPerSample` data units per sample; a full table\n * evicts its oldest sample by insertion order rather than throwing, so one\n * FEC-lost subsample DU cannot wedge every future sample. `#authoredSizes` is\n * bounded by retiring each key the moment its sample completes, keeping only a\n * bounded recent-retirement set so a late duplicate or FEC-recovered\n * retransmission for that same sample is dropped rather than silently\n * re-emitted or misread as a fresh whole sample.\n *\n * @packageDocumentation\n */\n\nimport type {\n MmtpSourcePath,\n ReassembledMFU,\n MmtpDeliveryProvenance,\n} from './mfu-reassembler.js'\n\n/** Identifies one authored sample: `(catalogTrackName, mpu, movieFragmentSequenceNumber, sampleNumber)`. */\ntype SampleKey = string\n\nfunction sampleKey(\n catalogTrackName: string | undefined,\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number,\n sampleNumber: number,\n): SampleKey {\n return JSON.stringify([catalogTrackName ?? null, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber])\n}\n\n/** The `catalogTrackName` a key was built from, or undefined when it had none. */\nfunction trackNameOfKey(key: SampleKey): string | undefined {\n const name = (JSON.parse(key) as [string | null, number, number, number])[0]\n return name ?? undefined\n}\n\n/** The full authored-sample identity a key was built from. */\nfunction identityOfKey(key: SampleKey): AbandonedSample {\n const [name, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber] =\n JSON.parse(key) as [string | null, number, number, number]\n return {\n catalogTrackName: name ?? undefined,\n mpuSequenceNumber,\n movieFragmentSequenceNumber,\n sampleNumber,\n }\n}\n\n/**\n * An authored sample that provably will not be delivered, reported to the\n * owner of any per-sample state keyed on this identity so that state can be\n * released. See {@link SampleCombinerOptions.onAbandon}.\n */\nexport interface AbandonedSample {\n catalogTrackName: string | undefined\n mpuSequenceNumber: number\n movieFragmentSequenceNumber: number\n sampleNumber: number\n}\n\n/** One authored sample combined from its constituent data unit(s). */\nexport interface CombinedSample {\n mpuSequenceNumber: number\n movieFragmentSequenceNumber: number\n sampleNumber: number\n /** The full sample's media bytes, in ascending-offset order. */\n data: Uint8Array\n /** Raw MMTP short-NTP header timestamp for the offset-zero data unit. */\n mmtpTimestamp?: bigint\n timestamp: bigint\n /**\n * The sample's RAP flag is the RAP flag of the FI=0 or FI=1 object of its\n * offset-0 data unit (moqcast #37).\n */\n rapFlag: boolean\n priority?: number\n /** Every authoritative source-packet sequence across all constituent data units, in offset order. */\n packetSequenceNumbers?: number[]\n /** Subset of packetSequenceNumbers reconstructed by FEC. */\n repairedPacketSequenceNumbers?: number[]\n catalogTrackName?: string\n /** Number of subsample data units combined (1 for a whole-sample DU or a non-timed passthrough). */\n subsampleCount: number\n /** MMTP fragments that formed the sample, summed across constituent data units. */\n fragmentCount: number\n /**\n * Transport that supplied the offset-zero data unit's head fragment. Taken\n * from that data unit alone -- like {@link CombinedSample.rapFlag} -- rather\n * than from whichever sibling happened to complete last.\n */\n source?: MmtpSourcePath\n /**\n * Strict provenance folded across EVERY constituent data unit, and within\n * each of them across every MMTP fragment. Unlike {@link CombinedSample.source},\n * which is the offset-zero DU's routing tag, this is whole-sample evidence:\n * only 'multicast' proves that no byte of this sample arrived another way.\n */\n deliveryProvenance: MmtpDeliveryProvenance\n}\n\nexport const SAMPLE_COMBINE_ERROR_CODES = [\n 'duplicate-subsample-offset',\n 'overlapping-subsample',\n 'exceeds-authored-size',\n 'too-many-subsample-segments',\n] as const\n\nexport type SampleCombineErrorCode = typeof SAMPLE_COMBINE_ERROR_CODES[number]\n\n/**\n * Fail-closed rejection reasons for subsample combining. Distinct from\n * {@link MfuReassemblyError}, which governs one data unit's own fragment\n * chain; these govern combining already-reassembled data units into a\n * sample.\n */\nexport class SampleCombineError extends Error {\n readonly name = 'SampleCombineError'\n\n constructor(readonly code: SampleCombineErrorCode, message: string) {\n super(message)\n }\n}\n\nexport interface SampleCombinerStats {\n combinedSamples: number\n passthroughSamples: number\n timedOutSamples: number\n /** Incomplete samples discarded to enforce `maxBuffered`. */\n evictedSamples: number\n}\n\nexport interface SampleCombinerOptions {\n /**\n * Max concurrent incomplete samples. Enforced by evicting the oldest by\n * insertion order, never by throwing, so a host that never calls\n * {@link SampleCombiner.cleanupTimeouts} still recovers from a permanently\n * lost subsample data unit instead of wedging.\n */\n maxBuffered: number\n /**\n * When true, an offset-zero data unit with no registered authored size\n * buffers and waits for one rather than passing through immediately. See\n * the module doc.\n */\n requireAuthoredSize: boolean\n /**\n * Max subsample data units held for one sample at once. Bounds both memory\n * and the per-insert overlap scan; a legitimate subsample-partitioned\n * sample needs at most `ceil(sampleSize / (256 * maxPayload))` data units.\n */\n maxSegmentsPerSample: number\n /**\n * Called once per sample discarded by eviction or timeout -- the two paths\n * where a sample is abandoned while its stream keeps running.\n *\n * Completion and passthrough are deliberately excluded: those samples were\n * delivered, and their consumer releases whatever per-sample state it held.\n * Wholesale resets (`flush`, `resetStream`) are excluded too, because they\n * already discard that state in bulk.\n *\n * Exists because per-sample state elsewhere -- notably the ISO-BMFF\n * timing-sample budget -- is otherwise only released on delivery, making it\n * a one-way ratchet that wedges the stream once it saturates. The combiner\n * is where abandonment is actually detected, so it is where the signal has\n * to come from; inferring it downstream would require a timer or an age\n * bound, neither of which is derivable from the catalog.\n */\n onAbandon?: (sample: AbandonedSample) => void\n}\n\ninterface PendingSample {\n /** Held data units keyed by their authored base offset. */\n segments: Map<number, ReassembledMFU>\n startedAt: number\n}\n\n/** Combines subsample data units of one sample into a contiguous whole. */\nexport class SampleCombiner {\n #maxBuffered: number\n #requireAuthoredSize: boolean\n #maxSegmentsPerSample: number\n #onAbandon: ((sample: AbandonedSample) => void) | undefined\n #authoredSizes: Map<SampleKey, number> = new Map()\n /** Map iteration is insertion-ordered, so the first key is the oldest. */\n #pending: Map<SampleKey, PendingSample> = new Map()\n /**\n * Bounded, insertion-ordered set of recently-completed sample keys, so a\n * late duplicate or FEC-recovered retransmission is dropped rather than\n * re-emitted or misread as a fresh whole sample.\n */\n #retired: Set<SampleKey> = new Set()\n #stats: SampleCombinerStats = {\n combinedSamples: 0,\n passthroughSamples: 0,\n timedOutSamples: 0,\n evictedSamples: 0,\n }\n\n constructor(options: SampleCombinerOptions) {\n const { maxBuffered, requireAuthoredSize, maxSegmentsPerSample, onAbandon } = options\n if (!Number.isInteger(maxBuffered) || maxBuffered <= 0) {\n throw new Error('[SampleCombiner] maxBuffered must be a positive integer')\n }\n if (!Number.isInteger(maxSegmentsPerSample) || maxSegmentsPerSample <= 0) {\n throw new Error('[SampleCombiner] maxSegmentsPerSample must be a positive integer')\n }\n this.#maxBuffered = maxBuffered\n this.#requireAuthoredSize = requireAuthoredSize\n this.#maxSegmentsPerSample = maxSegmentsPerSample\n this.#onAbandon = onAbandon\n }\n\n /** Report one abandoned sample to the owner of any state keyed on it. */\n #abandon(key: SampleKey): void {\n this.#onAbandon?.(identityOfKey(key))\n }\n\n /**\n * Register the authored sample size from the host's own FT=1 parse. Per\n * moqcast #37, FT=1 for a movie fragment publishes before any FT=2 sample\n * referencing it, so a host driving FT=1 as it arrives registers each\n * sample's size before that sample's own data unit(s) arrive.\n *\n * On a lossy path FT=1 can still *arrive* late, after data units this\n * combiner has already buffered. Registering a size therefore re-drives the\n * completion check and returns the combined sample when the buffered data\n * units already satisfy the newly-known size. Callers MUST consume the\n * return value: for a sample carried by a single data unit there is no\n * later {@link SampleCombiner.addMfu} to re-enter, so discarding it\n * silently drops the sample.\n *\n * Registering also clears the key from the retired set. Retirement exists\n * to drop data units that arrive *passively* after a sample completed \u2014 a\n * late duplicate, an FEC-recovered retransmission. A host calling this\n * method is instead asserting that a sample with this identity is authored\n * now, which is what happens when a publisher restarts and its MPU\n * sequence numbers begin again, or when MPU sequence wraps. Without this,\n * such a stream would silently drop every sample whose identity collided\n * with a retired one until the bounded set aged the key out.\n */\n registerAuthoredSize(\n catalogTrackName: string | undefined,\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number,\n sampleNumber: number,\n size: number,\n ): CombinedSample | null {\n const key = sampleKey(catalogTrackName, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber)\n this.#retired.delete(key)\n this.#authoredSizes.set(key, size)\n return this.#tryComplete(key, size)\n }\n\n /**\n * Add one reassembled data unit. Returns the combined sample once every\n * constituent data unit has arrived and totals the authored size.\n */\n addMfu(mfu: ReassembledMFU): CombinedSample | null {\n if (mfu.movieFragmentSequenceNumber === undefined || mfu.sampleNumber === undefined) {\n // Non-timed (Item) MFU: sample combining does not apply.\n this.#stats.passthroughSamples++\n return fromPassthrough(mfu)\n }\n const offset = mfu.sampleOffset ?? 0\n const key = sampleKey(\n mfu.catalogTrackName,\n mfu.mpuSequenceNumber,\n mfu.movieFragmentSequenceNumber,\n mfu.sampleNumber,\n )\n\n if (this.#retired.has(key)) {\n // Duplicate or late data unit for an already-retired sample (a\n // FEC-recovered retransmission, reordering after completion, or a\n // sample discarded by eviction/timeout). Drop it rather than\n // re-emitting a duplicate downstream or misreading a stray fragment as\n // a fresh whole sample.\n return null\n }\n\n const dataLen = mfu.data.byteLength\n const authoredSize = this.#authoredSizes.get(key)\n\n if (offset === 0 && !this.#pending.has(key)) {\n const passesThrough = authoredSize === undefined\n ? !this.#requireAuthoredSize\n : dataLen === authoredSize\n if (passesThrough) {\n this.#stats.passthroughSamples++\n this.#retire(key)\n return fromPassthrough(mfu)\n }\n // Either shorter than the authored total (a subsample), or awaiting a\n // size under requireAuthoredSize -- buffer below.\n }\n\n // Reject BEFORE mutating any state. An earlier revision allocated the\n // pending entry (evicting the oldest sample to make room) and only then\n // validated, so a data unit the combiner went on to reject could destroy\n // an unrelated in-flight sample and leave an empty entry in its slot.\n const thisEnd = offset + dataLen\n if (authoredSize !== undefined && thisEnd > authoredSize) {\n throw new SampleCombineError(\n 'exceeds-authored-size',\n 'combined subsample data would exceed the registered authored sample size',\n )\n }\n const existing = this.#pending.get(key)\n if (existing !== undefined) {\n if (existing.segments.has(offset)) {\n throw new SampleCombineError(\n 'duplicate-subsample-offset',\n 'subsample data unit duplicates an offset already held for this sample',\n )\n }\n if (existing.segments.size >= this.#maxSegmentsPerSample) {\n throw new SampleCombineError(\n 'too-many-subsample-segments',\n 'a sample already holds the maximum number of subsample data units',\n )\n }\n for (const [segOffset, seg] of existing.segments) {\n const segEnd = segOffset + seg.data.byteLength\n if (offset < segEnd && segOffset < thisEnd) {\n throw new SampleCombineError(\n 'overlapping-subsample',\n \"subsample data unit overlaps a preceding data unit's byte range\",\n )\n }\n }\n }\n\n let pending = existing\n if (pending === undefined) {\n if (this.#pending.size >= this.#maxBuffered) this.#evictOldestPending()\n pending = { segments: new Map(), startedAt: Date.now() }\n this.#pending.set(key, pending)\n }\n pending.segments.set(offset, mfu)\n\n if (authoredSize === undefined) return null\n return this.#tryComplete(key, authoredSize)\n }\n\n /**\n * Emit the sample when its held data units are byte-adjacent from zero and\n * total `size`. Completion is a protocol event, never a timer.\n */\n #tryComplete(key: SampleKey, size: number): CombinedSample | null {\n const pending = this.#pending.get(key)\n if (pending === undefined) return null\n let expected = 0\n const sortedOffsets = [...pending.segments.keys()].sort((a, b) => a - b)\n for (const segOffset of sortedOffsets) {\n if (segOffset !== expected) return null // gap: not yet contiguous from zero.\n expected += pending.segments.get(segOffset)!.data.byteLength\n }\n if (expected !== size) return null // contiguous so far, short of the authored total.\n\n this.#pending.delete(key)\n this.#stats.combinedSamples++\n this.#retire(key)\n return fromSegments(pending.segments, sortedOffsets)\n }\n\n /**\n * Retire a sample's key: free its registered authored size and remember the\n * key in a bounded recency set. Called on every path that removes a sample\n * -- completion, passthrough, eviction, and timeout -- so `#authoredSizes`\n * cannot accumulate entries for samples that never complete, and so a later\n * data unit for a discarded sample is dropped rather than starting a fresh\n * buffer or being misread as a whole sample.\n *\n * The recency set holds `maxBuffered` keys. A duplicate delayed by more\n * than that many retirements escapes it; on a reliable path there is no\n * such duplicate, and on a lossy path the per-data-unit deadline in\n * {@link MFUReassembler} bounds the delay well inside this window.\n */\n #retire(key: SampleKey): void {\n this.#authoredSizes.delete(key)\n this.#retired.add(key)\n while (this.#retired.size > this.#maxBuffered) {\n const oldest = this.#retired.values().next().value\n if (oldest === undefined) break\n this.#retired.delete(oldest)\n }\n }\n\n /**\n * Discard the oldest pending sample by insertion order. This is the only\n * backstop against one FEC-lost subsample data unit wedging\n * {@link SampleCombiner.addMfu} for every future sample once `maxBuffered`\n * is reached, for a host that never drives\n * {@link SampleCombiner.cleanupTimeouts}.\n */\n #evictOldestPending(): void {\n const oldest = this.#pending.keys().next().value\n if (oldest === undefined) return\n this.#pending.delete(oldest)\n this.#stats.evictedSamples++\n this.#retire(oldest)\n this.#abandon(oldest)\n }\n\n /**\n * Discard samples whose oldest held segment has waited past `timeoutMs`.\n * Mirrors {@link MFUReassembler}'s clock-driven shape; the per-data-unit\n * deadline inside {@link MFUReassembler} already bounds each constituent,\n * so this is a backstop against a host that registers an authored size but\n * never supplies every subsample DU.\n */\n cleanupTimeouts(timeoutMs: number): void {\n const now = Date.now()\n for (const [key, pending] of [...this.#pending]) {\n if (now - pending.startedAt > timeoutMs) {\n this.#pending.delete(key)\n this.#stats.timedOutSamples++\n this.#retire(key)\n this.#abandon(key)\n }\n }\n }\n\n flush(): void {\n this.#pending.clear()\n this.#authoredSizes.clear()\n this.#retired.clear()\n }\n\n /**\n * Drop one stream's in-flight, registered-size, and retired state while\n * preserving every other stream (mirrors\n * {@link MFUReassembler.resetStream}).\n */\n resetStream(catalogTrackName: string): void {\n for (const key of this.#pending.keys()) {\n if (trackNameOfKey(key) === catalogTrackName) this.#pending.delete(key)\n }\n for (const key of this.#authoredSizes.keys()) {\n if (trackNameOfKey(key) === catalogTrackName) this.#authoredSizes.delete(key)\n }\n for (const key of this.#retired) {\n if (trackNameOfKey(key) === catalogTrackName) this.#retired.delete(key)\n }\n }\n\n get stats(): SampleCombinerStats {\n return { ...this.#stats }\n }\n\n get pendingCount(): number {\n return this.#pending.size\n }\n\n /**\n * Registered authored sizes still held. Diagnostic only: it exists so tests\n * and health reporting can assert this table stays bounded, since an\n * unbounded one is invisible from `pendingCount` alone.\n */\n get debugAuthoredSizeCount(): number {\n return this.#authoredSizes.size\n }\n\n /** Retired keys still remembered. Diagnostic only, bounded by `maxBuffered`. */\n get debugRetiredCount(): number {\n return this.#retired.size\n }\n}\n\nfunction fromPassthrough(mfu: ReassembledMFU): CombinedSample {\n return {\n mpuSequenceNumber: mfu.mpuSequenceNumber,\n movieFragmentSequenceNumber: mfu.movieFragmentSequenceNumber ?? 0,\n sampleNumber: mfu.sampleNumber ?? 0,\n data: mfu.data,\n mmtpTimestamp: mfu.timestamp,\n timestamp: mfu.timestamp,\n rapFlag: mfu.rapFlag,\n priority: mfu.priority,\n packetSequenceNumbers: mfu.packetSequenceNumbers,\n repairedPacketSequenceNumbers: mfu.repairedPacketSequenceNumbers,\n catalogTrackName: mfu.catalogTrackName,\n subsampleCount: 1,\n fragmentCount: mfu.fragmentCount,\n source: mfu.source,\n // One data unit in, one sample out: its provenance IS the sample's.\n deliveryProvenance: mfu.deliveryProvenance\n }\n}\n\nfunction fromSegments(\n segments: Map<number, ReassembledMFU>,\n sortedOffsets: number[],\n): CombinedSample {\n const totalSize = sortedOffsets.reduce((sum, offset) => sum + segments.get(offset)!.data.byteLength, 0)\n const data = new Uint8Array(totalSize)\n let packetSequenceNumbers: number[] | undefined\n let repairedPacketSequenceNumbers: number[] | undefined\n let writeOffset = 0\n let first: ReassembledMFU | undefined\n let fragmentCount = 0\n // Fold across data units the same way the reassembler folds across the\n // fragments inside one: a sample is multicast-exclusive only if every\n // subsample that formed it was.\n let combinedProvenance: MmtpDeliveryProvenance =\n sortedOffsets.length === 0 ? 'unknown' : 'multicast'\n for (const offset of sortedOffsets) {\n const seg = segments.get(offset)!\n combinedProvenance =\n combinedProvenance === 'mixed' || seg.deliveryProvenance === 'mixed'\n ? 'mixed'\n : combinedProvenance === 'unknown' || seg.deliveryProvenance === 'unknown'\n ? 'unknown'\n : 'multicast'\n data.set(seg.data, writeOffset)\n writeOffset += seg.data.byteLength\n fragmentCount += seg.fragmentCount\n if (seg.packetSequenceNumbers !== undefined) {\n (packetSequenceNumbers ??= []).push(...seg.packetSequenceNumbers)\n }\n if (seg.repairedPacketSequenceNumbers !== undefined) {\n (repairedPacketSequenceNumbers ??= []).push(...seg.repairedPacketSequenceNumbers)\n }\n if (first === undefined) first = seg\n }\n return {\n mpuSequenceNumber: first!.mpuSequenceNumber,\n movieFragmentSequenceNumber: first!.movieFragmentSequenceNumber!,\n sampleNumber: first!.sampleNumber!,\n data,\n mmtpTimestamp: first!.timestamp,\n timestamp: first!.timestamp,\n rapFlag: first!.rapFlag,\n priority: first!.priority,\n packetSequenceNumbers,\n repairedPacketSequenceNumbers,\n catalogTrackName: first!.catalogTrackName,\n subsampleCount: segments.size,\n fragmentCount,\n source: first!.source,\n deliveryProvenance: combinedProvenance,\n }\n}\n\n// =============================================================================\n// Inline Tests (vitest)\n// =============================================================================\n\nif (import.meta.vitest) {\n const { describe, test, expect } = import.meta.vitest\n\n const combiner = (overrides: Partial<SampleCombinerOptions> = {}) =>\n new SampleCombiner({\n maxBuffered: 10,\n requireAuthoredSize: false,\n maxSegmentsPerSample: 8,\n ...overrides,\n })\n\n const mfu = (\n mpu: number,\n movie: number,\n sample: number,\n offset: number,\n data: number[],\n timestamp: bigint,\n rapFlag: boolean,\n deliveryProvenance: MmtpDeliveryProvenance = 'multicast',\n ): ReassembledMFU => ({\n mpuSequenceNumber: mpu,\n data: new Uint8Array(data),\n timestamp,\n fragmentCount: 1,\n rapFlag,\n sampleNumber: sample,\n movieFragmentSequenceNumber: movie,\n sampleOffset: offset,\n packetSequenceNumbers: [offset],\n deliveryProvenance,\n })\n\n describe('SampleCombiner', () => {\n test('whole-sample DU passes through immediately with no registered size', () => {\n const c = combiner()\n const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))\n expect(out).not.toBeNull()\n expect(out!.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]))\n expect(out!.subsampleCount).toBe(1)\n expect(c.pendingCount).toBe(0)\n })\n\n test('whole-sample DU passes through when it matches the registered size', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 5)\n const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))\n expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]))\n })\n\n test('subsample data units combine once the authored size is met', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))).toBeNull()\n expect(c.pendingCount).toBe(1)\n\n const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false))\n expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\n expect(out?.subsampleCount).toBe(2)\n expect(out?.rapFlag).toBe(true) // offset-0 DU's RAP flag, per moqcast #37.\n expect(out?.timestamp).toBe(1000n)\n expect(c.pendingCount).toBe(0)\n expect(c.stats.combinedSamples).toBe(1)\n })\n\n test('subsample data units combine out of order', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n\n expect(c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false))).toBeNull()\n const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))\n expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\n })\n\n test('subsample without a registered size never completes', () => {\n // A non-zero-offset DU always buffers (it can never be a whole\n // sample). Without a registered authored size there is nothing to\n // combine against, so it -- and a sibling that arrives after it --\n // stay pending rather than being guessed complete.\n const c = combiner()\n expect(c.addMfu(mfu(1, 9, 17, 3, [1, 2, 3], 1001n, false))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3], 1000n, true))).toBeNull()\n expect(c.pendingCount).toBe(1)\n })\n\n test('requireAuthoredSize buffers an offset-zero DU instead of guessing complete', () => {\n // A moqcast-#37-aware host opts into fail-closed buffering: on a lossy\n // path FT=1 can arrive after an offset-zero data unit (reordering, or\n // FT=1's own DU recovered late by FEC). Treating \"no size yet\" as\n // \"whole sample\" would silently truncate a partitioned sample.\n const c = combiner({ requireAuthoredSize: true })\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))).toBeNull()\n expect(c.pendingCount).toBe(1)\n\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false))\n expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\n })\n\n test('duplicate offset is rejected', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))).toBeNull()\n expect(() => c.addMfu(mfu(1, 9, 17, 0, [9, 9, 9, 9, 9], 2000n, true)))\n .toThrow(SampleCombineError)\n })\n\n test('overlapping subsample is rejected', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))).toBeNull()\n expect(() => c.addMfu(mfu(1, 9, 17, 3, [9, 9, 9, 9, 9], 2000n, true)))\n .toThrow(SampleCombineError)\n })\n\n test('exceeding the authored size is rejected', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 8)\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))).toBeNull()\n expect(() => c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 2000n, false)))\n .toThrow(SampleCombineError)\n })\n\n test('exceeding maxSegmentsPerSample is rejected', () => {\n const c = combiner({ maxSegmentsPerSample: 2 })\n c.registerAuthoredSize(undefined, 1, 9, 17, 100)\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2], 1000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 17, 2, [3, 4], 1001n, false))).toBeNull()\n expect(() => c.addMfu(mfu(1, 9, 17, 4, [5, 6], 1002n, false)))\n .toThrow(SampleCombineError)\n })\n\n test('reports every abandoned sample so its per-sample state can be freed', () => {\n // Regression (BLO-31103): eviction and timeout are the two paths where\n // a sample is abandoned while its stream keeps running. State keyed on\n // that sample elsewhere -- notably the ISO-BMFF timing-sample budget --\n // is otherwise released only on delivery, so an abandoned sample holds\n // its slot forever and the budget becomes a one-way ratchet that wedges\n // the stream at saturation.\n const abandoned: AbandonedSample[] = []\n const c = combiner({ maxBuffered: 2, onAbandon: s => abandoned.push(s) })\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n c.registerAuthoredSize(undefined, 1, 9, 18, 10)\n c.registerAuthoredSize(undefined, 1, 9, 19, 10)\n\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 1, 1, 1, 1], 1000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 18, 0, [2, 2, 2, 2, 2], 1001n, true))).toBeNull()\n expect(abandoned).toEqual([])\n\n // Eviction reports the evicted identity, not the incoming one.\n expect(c.addMfu(mfu(1, 9, 19, 0, [3, 3, 3, 3, 3], 1002n, true))).toBeNull()\n expect(abandoned).toEqual([{\n catalogTrackName: undefined,\n mpuSequenceNumber: 1,\n movieFragmentSequenceNumber: 9,\n sampleNumber: 17,\n }])\n\n // Timeout reports too; both survivors are still incomplete here.\n c.cleanupTimeouts(-1)\n expect(abandoned.map(s => s.sampleNumber)).toEqual([17, 18, 19])\n\n // A delivered sample is NOT reported: its consumer releases that state.\n const d = combiner({ maxBuffered: 2, onAbandon: s => abandoned.push(s) })\n d.registerAuthoredSize(undefined, 1, 9, 20, 10)\n expect(d.addMfu(mfu(1, 9, 20, 0, [4, 4, 4, 4, 4], 1003n, true))).toBeNull()\n expect(d.addMfu(mfu(1, 9, 20, 5, [5, 5, 5, 5, 5], 1004n, false))).not.toBeNull()\n expect(abandoned.map(s => s.sampleNumber)).toEqual([17, 18, 19])\n })\n\n test('a full combiner evicts the oldest pending sample instead of throwing', () => {\n // Eviction is by insertion order, which is also the only backstop\n // against one permanently-lost subsample DU wedging every future\n // sample once maxBuffered incomplete samples accumulate.\n const c = combiner({ maxBuffered: 2 })\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n c.registerAuthoredSize(undefined, 1, 9, 18, 10)\n c.registerAuthoredSize(undefined, 1, 9, 19, 10)\n\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 1, 1, 1, 1], 1000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 18, 0, [2, 2, 2, 2, 2], 1001n, true))).toBeNull()\n expect(c.pendingCount).toBe(2)\n\n // A third distinct incomplete sample evicts sample 17, the oldest.\n expect(c.addMfu(mfu(1, 9, 19, 0, [3, 3, 3, 3, 3], 1002n, true))).toBeNull()\n expect(c.pendingCount).toBe(2)\n expect(c.stats.evictedSamples).toBe(1)\n\n // The surviving samples are undisturbed and still complete normally.\n expect(c.addMfu(mfu(1, 9, 18, 5, [8, 8, 8, 8, 8], 2001n, false))?.data)\n .toEqual(new Uint8Array([2, 2, 2, 2, 2, 8, 8, 8, 8, 8]))\n expect(c.addMfu(mfu(1, 9, 19, 5, [9, 9, 9, 9, 9], 2002n, false))?.data)\n .toEqual(new Uint8Array([3, 3, 3, 3, 3, 9, 9, 9, 9, 9]))\n\n // The combiner still accepts new work rather than being wedged.\n c.registerAuthoredSize(undefined, 1, 9, 20, 10)\n expect(c.addMfu(mfu(1, 9, 20, 0, [4, 4, 4, 4, 4], 3000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 20, 5, [7, 7, 7, 7, 7], 3001n, false))?.data)\n .toEqual(new Uint8Array([4, 4, 4, 4, 4, 7, 7, 7, 7, 7]))\n })\n\n test('a completed sample frees its authored size and drops a late duplicate', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 10)\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false))).not.toBeNull()\n\n // A FEC-recovered retransmission of the completed sample's offset-0\n // data unit must not be re-emitted as a second complete sample.\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 2000n, true))).toBeNull()\n })\n\n test('resetStream drops one track and preserves the others', () => {\n const c = combiner()\n c.registerAuthoredSize('video/720p', 1, 9, 17, 10)\n c.registerAuthoredSize('audio', 1, 9, 17, 10)\n const video = { ...mfu(1, 9, 17, 0, [1, 1, 1, 1, 1], 1000n, true), catalogTrackName: 'video/720p' }\n const audio = { ...mfu(1, 9, 17, 0, [2, 2, 2, 2, 2], 1000n, true), catalogTrackName: 'audio' }\n expect(c.addMfu(video)).toBeNull()\n expect(c.addMfu(audio)).toBeNull()\n\n c.resetStream('video/720p')\n expect(c.pendingCount).toBe(1)\n\n const audioTail = { ...mfu(1, 9, 17, 5, [3, 3, 3, 3, 3], 1001n, false), catalogTrackName: 'audio' }\n expect(c.addMfu(audioTail)?.data).toEqual(new Uint8Array([2, 2, 2, 2, 2, 3, 3, 3, 3, 3]))\n })\n\n test('flush clears registered authored sizes', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 9, 17, 5)\n c.flush()\n // A now-unregistered size means an offset-zero DU passes through\n // immediately again (requireAuthoredSize is false here) rather than\n // waiting on a size flush() already discarded.\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))?.data)\n .toEqual(new Uint8Array([1, 2, 3, 4, 5]))\n })\n\n test('a healthy stream accumulates no bookkeeping', () => {\n // Regression: retirement ran only on completion paths, so an\n // abandoned sample's registered size stayed resident forever.\n const c = combiner({ maxBuffered: 4, requireAuthoredSize: true })\n for (let i = 0; i < 1000; i++) {\n expect(c.registerAuthoredSize(undefined, 1, 9, i, 10)).toBeNull()\n expect(c.addMfu(mfu(1, 9, i, 0, [1, 1, 1, 1, 1], 1000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, i, 5, [2, 2, 2, 2, 2], 1001n, false))).not.toBeNull()\n }\n expect(c.stats.combinedSamples).toBe(1000)\n expect(c.pendingCount).toBe(0)\n expect(c.debugAuthoredSizeCount).toBe(0)\n expect(c.debugRetiredCount).toBeLessThanOrEqual(4)\n })\n\n test('samples that never complete release their authored size', () => {\n const c = combiner({ maxBuffered: 4, requireAuthoredSize: true })\n for (let i = 0; i < 1000; i++) {\n expect(c.registerAuthoredSize(undefined, 1, 9, i, 10)).toBeNull()\n expect(c.addMfu(mfu(1, 9, i, 0, [1, 1, 1, 1, 1], 1000n, true))).toBeNull()\n // Deliberately never supply the tail.\n }\n c.cleanupTimeouts(-1) // expire everything still held\n expect(c.pendingCount).toBe(0)\n expect(c.debugAuthoredSizeCount).toBe(0)\n })\n\n test('a late authored size completes an already-buffered sample', () => {\n // Regression: with requireAuthoredSize the completion check ran only\n // inside addMfu, so a sample carried by a SINGLE data unit whose FT=1\n // arrived afterwards had no later data unit to re-enter on and was\n // silently lost.\n const c = combiner({ requireAuthoredSize: true })\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true))).toBeNull()\n expect(c.pendingCount).toBe(1)\n\n const out = c.registerAuthoredSize(undefined, 1, 9, 17, 5)\n expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]))\n expect(out?.subsampleCount).toBe(1)\n expect(c.pendingCount).toBe(0)\n })\n\n test('a rejected data unit does not evict a live sample', () => {\n // Regression: the pending slot was allocated (evicting the oldest\n // sample to make room) BEFORE validation, so a data unit the combiner\n // went on to reject destroyed an unrelated in-flight sample.\n const c = combiner({ maxBuffered: 2 })\n for (const s of [17, 18, 19]) c.registerAuthoredSize(undefined, 1, 9, s, 10)\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 1, 1, 1, 1], 1000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 18, 0, [2, 2, 2, 2, 2], 1001n, true))).toBeNull()\n expect(c.pendingCount).toBe(2)\n\n // 8 + 5 = 13 exceeds sample 19's authored size of 10.\n expect(() => c.addMfu(mfu(1, 9, 19, 8, [9, 9, 9, 9, 9], 2000n, false)))\n .toThrow(SampleCombineError)\n expect(c.stats.evictedSamples).toBe(0)\n expect(c.pendingCount).toBe(2)\n\n // Sample 17 is untouched and still completes.\n expect(c.addMfu(mfu(1, 9, 17, 5, [3, 3, 3, 3, 3], 2001n, false))?.data)\n .toEqual(new Uint8Array([1, 1, 1, 1, 1, 3, 3, 3, 3, 3]))\n })\n\n test('an evicted sample is retired rather than reopened', () => {\n const c = combiner({ maxBuffered: 1 })\n for (const s of [17, 18]) c.registerAuthoredSize(undefined, 1, 9, s, 10)\n expect(c.addMfu(mfu(1, 9, 17, 0, [1, 1, 1, 1, 1], 1000n, true))).toBeNull()\n expect(c.addMfu(mfu(1, 9, 18, 0, [2, 2, 2, 2, 2], 1001n, true))).toBeNull()\n expect(c.stats.evictedSamples).toBe(1)\n\n // Sample 17's tail arrives after its eviction; it must not reopen.\n expect(c.addMfu(mfu(1, 9, 17, 5, [3, 3, 3, 3, 3], 2000n, false))).toBeNull()\n expect(c.pendingCount).toBe(1)\n })\n })\n\n describe('sample-level delivery provenance', () => {\n test('one non-multicast subsample makes the whole sample non-exclusive', () => {\n // A 4K/8K sample is split across subsample DUs. If any one of them\n // arrived over QUIC, the assembled sample contains bytes that never\n // crossed a multicast socket, so the sample is not physical evidence\n // even though every other DU was multicast.\n const c = combiner()\n c.registerAuthoredSize(undefined, 1, 1, 1, 4)\n expect(c.addMfu(mfu(1, 1, 1, 0, [1, 2], 100n, true, 'multicast'))).toBeNull()\n const done = c.addMfu(mfu(1, 1, 1, 2, [3, 4], 100n, false, 'mixed'))\n expect(done).not.toBeNull()\n expect(done!.subsampleCount).toBe(2)\n expect(done!.deliveryProvenance).toBe('mixed')\n })\n\n test('an unattributed subsample degrades the sample to unknown', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 2, 1, 1, 4)\n expect(c.addMfu(mfu(2, 1, 1, 0, [1, 2], 100n, true, 'multicast'))).toBeNull()\n const done = c.addMfu(mfu(2, 1, 1, 2, [3, 4], 100n, false, 'unknown'))\n expect(done).not.toBeNull()\n expect(done!.deliveryProvenance).toBe('unknown')\n })\n\n test('an all-multicast sample stays multicast-exclusive', () => {\n const c = combiner()\n c.registerAuthoredSize(undefined, 3, 1, 1, 4)\n expect(c.addMfu(mfu(3, 1, 1, 0, [1, 2], 100n, true, 'multicast'))).toBeNull()\n const done = c.addMfu(mfu(3, 1, 1, 2, [3, 4], 100n, false, 'multicast'))\n expect(done).not.toBeNull()\n expect(done!.deliveryProvenance).toBe('multicast')\n })\n\n test('a passthrough sample inherits its data unit provenance verbatim', () => {\n const c = combiner()\n const done = c.addMfu(mfu(4, 1, 1, 0, [1, 2], 100n, true, 'mixed'))\n expect(done).not.toBeNull()\n expect(done!.subsampleCount).toBe(1)\n expect(done!.deliveryProvenance).toBe('mixed')\n })\n })\n}\n", "export type MfuReassemblyPolicy =\n | ReliableMoqReassemblyPolicy\n | { transport: 'datagram'; deadlineMs: number }\n\nexport interface ReliableMoqReassemblyPolicy {\n transport: 'reliable-moq'\n startsAtRandomAccessGroup?: true\n}\n\nexport type MmtpTrackType = 'video' | 'audio' | null\n\nexport interface ReliableMoqReassemblyOptions {\n /**\n * The transport starts at a complete independently decodable media group.\n * The parser still requires an observed RAP before decoder startup.\n */\n startsAtRandomAccessGroup?: boolean\n}\n\nfunction validateReliableMoqOptionShape(value: Record<string, unknown>): void {\n const unsupported = Object.keys(value).filter(\n key => key !== 'transport' && key !== 'startsAtRandomAccessGroup',\n )\n if (unsupported.length > 0) {\n if (unsupported.includes('maxRacingGroups')) {\n throw new Error(\n '[MFU reassembly] maxRacingGroups was removed; reliable MoQ completion is transport-owned',\n )\n }\n throw new Error(\n `[MFU reassembly] unsupported reliable MoQ option(s): ${unsupported.join(', ')}`,\n )\n }\n const startsAtRandomAccessGroup = value['startsAtRandomAccessGroup']\n if (\n typeof startsAtRandomAccessGroup !== 'boolean' &&\n startsAtRandomAccessGroup !== undefined\n ) {\n throw new Error('[MFU reassembly] startsAtRandomAccessGroup must be boolean')\n }\n}\n\nexport function reliableMoqMfuReassembly(\n options: ReliableMoqReassemblyOptions = {},\n): ReliableMoqReassemblyPolicy {\n if (\n arguments.length > 1 ||\n typeof options !== 'object' ||\n options === null ||\n Array.isArray(options)\n ) {\n throw new Error(\n '[MFU reassembly] the positional maxRacingGroups API was removed; pass a reliable MoQ options object',\n )\n }\n validateReliableMoqOptionShape(options as Record<string, unknown>)\n return options.startsAtRandomAccessGroup\n ? {\n transport: 'reliable-moq',\n startsAtRandomAccessGroup: true,\n }\n : { transport: 'reliable-moq' }\n}\n\nfunction assertValidDatagramDeadline(deadlineMs: unknown): asserts deadlineMs is number {\n if (typeof deadlineMs !== 'number' || !Number.isFinite(deadlineMs) || deadlineMs <= 0) {\n throw new Error('[MFU reassembly] datagram deadlineMs must be a finite number > 0')\n }\n}\n\nexport function datagramMfuReassembly(deadlineMs: number): MfuReassemblyPolicy {\n assertValidDatagramDeadline(deadlineMs)\n return { transport: 'datagram', deadlineMs }\n}\n\n/** Validate the complete runtime shape even when a caller bypasses the policy factories. */\nexport function assertValidMfuReassemblyPolicy(policy: MfuReassemblyPolicy): void {\n if (typeof policy !== 'object' || policy === null || Array.isArray(policy)) {\n throw new Error('[MFU reassembly] policy must be an object')\n }\n\n const value = policy as unknown as Record<string, unknown>\n if (value['transport'] === 'reliable-moq') {\n validateReliableMoqOptionShape(value)\n if (value['startsAtRandomAccessGroup'] === false) {\n throw new Error(\n '[MFU reassembly] startsAtRandomAccessGroup must be true when present in a policy',\n )\n }\n return\n }\n if (value['transport'] === 'datagram') {\n const unsupported = Object.keys(value).filter(\n key => key !== 'transport' && key !== 'deadlineMs',\n )\n if (unsupported.length > 0) {\n throw new Error(\n `[MFU reassembly] unsupported datagram option(s): ${unsupported.join(', ')}`,\n )\n }\n assertValidDatagramDeadline(value['deadlineMs'])\n return\n }\n throw new Error(\n `[MFU reassembly] unsupported transport: ${String(value['transport'])}`,\n )\n}\n\nexport function mfuReassemblyTimeoutMs(policy: MfuReassemblyPolicy): number | null {\n assertValidMfuReassemblyPolicy(policy)\n return policy.transport === 'reliable-moq' ? null : policy.deadlineMs\n}\n\n/** Resolve the parser reorder window without inferring reliable-stream completion. */\nexport function mmtpFrameReorderWindowFrames(\n policy: MfuReassemblyPolicy,\n configuredWindow = 0,\n): number {\n assertValidMfuReassemblyPolicy(policy)\n if (!Number.isFinite(configuredWindow) || configuredWindow < 0) {\n throw new Error('[MFU reassembly] configuredWindow must be a finite number >= 0')\n }\n\n const requested = Math.ceil(configuredWindow)\n if (policy.transport === 'reliable-moq') {\n if (requested > 0) {\n throw new Error(\n '[MFU reassembly] reliable MoQ paths do not accept a frame reorder window in the parser',\n )\n }\n return 0\n }\n return requested\n}\n", "/**\n * Strict ISO-BMFF timing extraction for the timed-MFU browser path.\n *\n * This intentionally implements only the current single-track MMT profile:\n * one media track in FT=0, and one matching traf/trun in each FT=1. It does\n * not infer timing from packet arrival, MMTP send timestamps, or cadence.\n */\n\nconst U64_MAX = 0xffff_ffff_ffff_ffffn\nconst I64_MIN = -0x8000_0000_0000_0000n\nconst I64_MAX = 0x7fff_ffff_ffff_ffffn\nconst MICROSECONDS_PER_SECOND = 1_000_000n\n\nconst TFHD_BASE_DATA_OFFSET_PRESENT = 0x000001\nconst TFHD_SAMPLE_DESCRIPTION_INDEX_PRESENT = 0x000002\nconst TFHD_DEFAULT_SAMPLE_DURATION_PRESENT = 0x000008\nconst TFHD_DEFAULT_SAMPLE_SIZE_PRESENT = 0x000010\nconst TFHD_DEFAULT_SAMPLE_FLAGS_PRESENT = 0x000020\nconst TFHD_DURATION_IS_EMPTY = 0x010000\nconst TFHD_DEFAULT_BASE_IS_MOOF = 0x020000\nconst TFHD_KNOWN_FLAGS =\n TFHD_BASE_DATA_OFFSET_PRESENT |\n TFHD_SAMPLE_DESCRIPTION_INDEX_PRESENT |\n TFHD_DEFAULT_SAMPLE_DURATION_PRESENT |\n TFHD_DEFAULT_SAMPLE_SIZE_PRESENT |\n TFHD_DEFAULT_SAMPLE_FLAGS_PRESENT |\n TFHD_DURATION_IS_EMPTY |\n TFHD_DEFAULT_BASE_IS_MOOF\n\nconst TRUN_DATA_OFFSET_PRESENT = 0x000001\nconst TRUN_FIRST_SAMPLE_FLAGS_PRESENT = 0x000004\nconst TRUN_SAMPLE_DURATION_PRESENT = 0x000100\nconst TRUN_SAMPLE_SIZE_PRESENT = 0x000200\nconst TRUN_SAMPLE_FLAGS_PRESENT = 0x000400\nconst TRUN_SAMPLE_CTS_OFFSET_PRESENT = 0x000800\nconst TRUN_KNOWN_FLAGS =\n TRUN_DATA_OFFSET_PRESENT |\n TRUN_FIRST_SAMPLE_FLAGS_PRESENT |\n TRUN_SAMPLE_DURATION_PRESENT |\n TRUN_SAMPLE_SIZE_PRESENT |\n TRUN_SAMPLE_FLAGS_PRESENT |\n TRUN_SAMPLE_CTS_OFFSET_PRESENT\n\nexport interface IsoBmffTrackTiming {\n trackId: number\n timescale: number\n defaultSampleDuration?: number\n defaultSampleSize?: number\n}\n\nexport interface IsoBmffSampleTiming {\n /** Exact decode time in mdhd timescale units. */\n decodeTime: bigint\n /** Exact presentation time in mdhd timescale units, including signed CTS. */\n presentationTime: bigint\n /** Exact authored duration in mdhd timescale units. */\n duration: number\n timescale: number\n /** Exact elementary-stream sample size declared by trun/tfhd/trex. */\n size: number\n /** Byte position of the sample relative to the beginning of the moof. */\n bytePosition: bigint\n}\n\nexport interface IsoBmffMovieFragmentTiming {\n movieFragmentSequenceNumber: number\n samples: readonly IsoBmffSampleTiming[]\n}\n\nexport type IsoBmffMovieFragmentRejection = 'invalid' | 'budget'\n\ninterface IsoBox {\n type: string\n start: number\n bodyStart: number\n end: number\n}\n\ninterface FullBox {\n version: number\n flags: number\n bodyStart: number\n}\n\ninterface ParsedTrack {\n trackId: number\n handlerType: string\n timescale: number\n hasEdits: boolean\n}\n\ninterface ParsedTfhd {\n trackId: number\n defaultSampleDuration?: number\n defaultSampleSize?: number\n}\n\ninterface MdatLayout {\n dataStart: bigint\n declaredEnd: bigint\n}\n\nfunction view(data: Uint8Array): DataView {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n}\n\nfunction boxType(data: Uint8Array, offset: number): string {\n return String.fromCharCode(\n data[offset]!,\n data[offset + 1]!,\n data[offset + 2]!,\n data[offset + 3]!,\n )\n}\n\nfunction readU64(data: Uint8Array, offset: number): bigint | null {\n if (offset < 0 || offset + 8 > data.length) return null\n const dataView = view(data)\n return (BigInt(dataView.getUint32(offset, false)) << 32n) |\n BigInt(dataView.getUint32(offset + 4, false))\n}\n\nfunction parseBox(data: Uint8Array, start: number, limit: number): IsoBox | null {\n if (start < 0 || limit > data.length || start + 8 > limit) return null\n const dataView = view(data)\n const shortSize = dataView.getUint32(start, false)\n let headerSize = 8\n let size: number\n if (shortSize === 0) {\n size = limit - start\n } else if (shortSize === 1) {\n if (start + 16 > limit) return null\n const extendedSize = readU64(data, start + 8)\n if (extendedSize === null || extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null\n headerSize = 16\n size = Number(extendedSize)\n } else {\n size = shortSize\n }\n if (size < headerSize || start + size > limit) return null\n return {\n type: boxType(data, start + 4),\n start,\n bodyStart: start + headerSize,\n end: start + size,\n }\n}\n\nfunction parseBoxes(data: Uint8Array, start: number, end: number): IsoBox[] | null {\n if (start < 0 || end < start || end > data.length) return null\n const boxes: IsoBox[] = []\n let offset = start\n while (offset < end) {\n const box = parseBox(data, offset, end)\n if (!box || box.end <= offset) return null\n boxes.push(box)\n offset = box.end\n }\n return offset === end ? boxes : null\n}\n\nfunction children(data: Uint8Array, parent: IsoBox): IsoBox[] | null {\n return parseBoxes(data, parent.bodyStart, parent.end)\n}\n\nfunction exactlyOne(boxes: readonly IsoBox[], type: string): IsoBox | null {\n const matches = boxes.filter(box => box.type === type)\n return matches.length === 1 ? matches[0]! : null\n}\n\nfunction parseFullBox(data: Uint8Array, box: IsoBox): FullBox | null {\n if (box.bodyStart + 4 > box.end) return null\n const versionAndFlags = view(data).getUint32(box.bodyStart, false)\n return {\n version: versionAndFlags >>> 24,\n flags: versionAndFlags & 0x00ff_ffff,\n bodyStart: box.bodyStart + 4,\n }\n}\n\nfunction parseTkhdTrackId(data: Uint8Array, box: IsoBox): number | null {\n const full = parseFullBox(data, box)\n if (!full || full.flags & ~0x00000f) return null\n const bodyLength = box.end - full.bodyStart\n const trackIdOffset = full.version === 0\n ? full.bodyStart + 8\n : full.version === 1\n ? full.bodyStart + 16\n : -1\n const expectedBodyLength = full.version === 0 ? 80 : full.version === 1 ? 92 : -1\n if (trackIdOffset < 0 || bodyLength !== expectedBodyLength) return null\n return view(data).getUint32(trackIdOffset, false)\n}\n\nfunction parseMdhdTimescale(data: Uint8Array, box: IsoBox): number | null {\n const full = parseFullBox(data, box)\n if (!full || full.flags !== 0) return null\n const bodyLength = box.end - full.bodyStart\n const timescaleOffset = full.version === 0\n ? full.bodyStart + 8\n : full.version === 1\n ? full.bodyStart + 16\n : -1\n const expectedBodyLength = full.version === 0 ? 20 : full.version === 1 ? 32 : -1\n if (timescaleOffset < 0 || bodyLength !== expectedBodyLength) return null\n return view(data).getUint32(timescaleOffset, false)\n}\n\nfunction parseHandlerType(data: Uint8Array, box: IsoBox): string | null {\n const full = parseFullBox(data, box)\n if (!full || full.version !== 0 || full.flags !== 0 || full.bodyStart + 20 > box.end) {\n return null\n }\n return boxType(data, full.bodyStart + 4)\n}\n\nfunction editListHasEntries(data: Uint8Array, box: IsoBox): boolean | null {\n const full = parseFullBox(data, box)\n if (!full || full.flags !== 0 || (full.version !== 0 && full.version !== 1)) return null\n if (full.bodyStart + 4 > box.end) return null\n const entryCount = view(data).getUint32(full.bodyStart, false)\n const entrySize = full.version === 0 ? 12 : 20\n const expectedEnd = full.bodyStart + 4 + entryCount * entrySize\n if (!Number.isSafeInteger(expectedEnd) || expectedEnd !== box.end) return null\n return entryCount !== 0\n}\n\nfunction parseTrack(data: Uint8Array, trak: IsoBox): ParsedTrack | null {\n const trakChildren = children(data, trak)\n if (!trakChildren) return null\n const tkhd = exactlyOne(trakChildren, 'tkhd')\n const mdia = exactlyOne(trakChildren, 'mdia')\n if (!tkhd || !mdia) return null\n const trackId = parseTkhdTrackId(data, tkhd)\n if (trackId === null || trackId === 0) return null\n\n const mdiaChildren = children(data, mdia)\n if (!mdiaChildren) return null\n const mdhd = exactlyOne(mdiaChildren, 'mdhd')\n const hdlr = exactlyOne(mdiaChildren, 'hdlr')\n if (!mdhd || !hdlr) return null\n const timescale = parseMdhdTimescale(data, mdhd)\n const handlerType = parseHandlerType(data, hdlr)\n if (timescale === null || timescale === 0 || handlerType === null) return null\n\n const edtsBoxes = trakChildren.filter(box => box.type === 'edts')\n if (edtsBoxes.length > 1) return null\n let hasEdits = false\n if (edtsBoxes.length === 1) {\n const edtsChildren = children(data, edtsBoxes[0]!)\n if (!edtsChildren) return null\n const editLists = edtsChildren.filter(box => box.type === 'elst')\n if (editLists.length > 1) return null\n if (editLists.length === 1) {\n const result = editListHasEntries(data, editLists[0]!)\n if (result === null) return null\n hasEdits = result\n }\n }\n\n return { trackId, handlerType, timescale, hasEdits }\n}\n\nfunction parseTrex(data: Uint8Array, box: IsoBox): IsoBmffTrackTiming | null {\n const full = parseFullBox(data, box)\n if (!full || full.version !== 0 || full.flags !== 0 || box.end - full.bodyStart !== 20) {\n return null\n }\n const dataView = view(data)\n const trackId = dataView.getUint32(full.bodyStart, false)\n const defaultSampleDuration = dataView.getUint32(full.bodyStart + 8, false)\n const defaultSampleSize = dataView.getUint32(full.bodyStart + 12, false)\n return {\n trackId,\n timescale: 0,\n ...(defaultSampleDuration === 0 ? {} : { defaultSampleDuration }),\n ...(defaultSampleSize === 0 ? {} : { defaultSampleSize }),\n }\n}\n\nexport function parseIsoBmffInitializationTiming(\n data: Uint8Array,\n): IsoBmffTrackTiming | null {\n const topLevel = parseBoxes(data, 0, data.length)\n if (!topLevel) return null\n const ftyp = exactlyOne(topLevel, 'ftyp')\n const moov = exactlyOne(topLevel, 'moov')\n if (!ftyp || !moov || ftyp.start > moov.start) return null\n if (topLevel.some(box => box.type === 'moof' || box.type === 'mdat')) return null\n\n const moovChildren = children(data, moov)\n if (!moovChildren) return null\n const parsedTracks: ParsedTrack[] = []\n for (const trak of moovChildren.filter(box => box.type === 'trak')) {\n const parsed = parseTrack(data, trak)\n if (!parsed) return null\n parsedTracks.push(parsed)\n }\n const mediaTracks = parsedTracks.filter(\n track => track.handlerType === 'vide' || track.handlerType === 'soun',\n )\n if (mediaTracks.length !== 1) return null\n const mediaTrack = mediaTracks[0]!\n if (mediaTrack.hasEdits) return null\n\n const mvex = exactlyOne(moovChildren, 'mvex')\n if (!mvex) return null\n const mvexChildren = children(data, mvex)\n if (!mvexChildren) return null\n const trexEntries: IsoBmffTrackTiming[] = []\n for (const trexBox of mvexChildren.filter(box => box.type === 'trex')) {\n const trex = parseTrex(data, trexBox)\n if (!trex) return null\n trexEntries.push(trex)\n }\n const matchingTrex = trexEntries.filter(trex => trex.trackId === mediaTrack.trackId)\n if (matchingTrex.length !== 1) return null\n const trex = matchingTrex[0]!\n return {\n trackId: mediaTrack.trackId,\n timescale: mediaTrack.timescale,\n ...(trex.defaultSampleDuration === undefined\n ? {}\n : { defaultSampleDuration: trex.defaultSampleDuration }),\n ...(trex.defaultSampleSize === undefined\n ? {}\n : { defaultSampleSize: trex.defaultSampleSize }),\n }\n}\n\nfunction parseMfhdSequence(data: Uint8Array, box: IsoBox): number | null {\n const full = parseFullBox(data, box)\n if (!full || full.version !== 0 || full.flags !== 0 || box.end - full.bodyStart !== 4) {\n return null\n }\n return view(data).getUint32(full.bodyStart, false)\n}\n\nfunction parseTfhd(data: Uint8Array, box: IsoBox): ParsedTfhd | null {\n const full = parseFullBox(data, box)\n if (!full || full.version !== 0 || (full.flags & ~TFHD_KNOWN_FLAGS) !== 0) return null\n if ((full.flags & TFHD_BASE_DATA_OFFSET_PRESENT) !== 0 ||\n (full.flags & TFHD_DEFAULT_BASE_IS_MOOF) === 0 ||\n (full.flags & TFHD_DURATION_IS_EMPTY) !== 0) {\n return null\n }\n const dataView = view(data)\n let offset = full.bodyStart\n if (offset + 4 > box.end) return null\n const trackId = dataView.getUint32(offset, false)\n offset += 4\n if ((full.flags & TFHD_SAMPLE_DESCRIPTION_INDEX_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n offset += 4\n }\n let defaultSampleDuration: number | undefined\n if ((full.flags & TFHD_DEFAULT_SAMPLE_DURATION_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n defaultSampleDuration = dataView.getUint32(offset, false)\n offset += 4\n }\n let defaultSampleSize: number | undefined\n if ((full.flags & TFHD_DEFAULT_SAMPLE_SIZE_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n defaultSampleSize = dataView.getUint32(offset, false)\n offset += 4\n }\n if ((full.flags & TFHD_DEFAULT_SAMPLE_FLAGS_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n offset += 4\n }\n if (offset !== box.end) return null\n return {\n trackId,\n ...(defaultSampleDuration === undefined ? {} : { defaultSampleDuration }),\n ...(defaultSampleSize === undefined ? {} : { defaultSampleSize }),\n }\n}\n\nfunction parseTfdt(data: Uint8Array, box: IsoBox): bigint | null {\n const full = parseFullBox(data, box)\n if (!full || full.flags !== 0) return null\n if (full.version === 0 && box.end - full.bodyStart === 4) {\n return BigInt(view(data).getUint32(full.bodyStart, false))\n }\n if (full.version === 1 && box.end - full.bodyStart === 8) {\n return readU64(data, full.bodyStart)\n }\n return null\n}\n\nfunction parseMdatLayout(data: Uint8Array, offset: number): MdatLayout | null {\n if (offset < 0 || offset + 8 > data.length || boxType(data, offset + 4) !== 'mdat') return null\n const dataView = view(data)\n const shortSize = dataView.getUint32(offset, false)\n let headerSize = 8\n let declaredSize: bigint\n if (shortSize === 0) {\n return null\n } else if (shortSize === 1) {\n const extended = readU64(data, offset + 8)\n if (extended === null) return null\n headerSize = 16\n declaredSize = extended\n } else {\n declaredSize = BigInt(shortSize)\n }\n if (declaredSize < BigInt(headerSize) || declaredSize < BigInt(data.length - offset)) {\n return null\n }\n const declaredEnd = BigInt(offset) + declaredSize\n if (declaredEnd > U64_MAX) return null\n return { dataStart: BigInt(offset + headerSize), declaredEnd }\n}\n\nfunction resolvedDefault(\n entryValue: number | undefined,\n tfhdValue: number | undefined,\n trexValue: number | undefined,\n): number | null {\n const value = entryValue ?? tfhdValue ?? trexValue\n return value === undefined || value === 0 ? null : value\n}\n\nfunction parseTrunSamples(\n data: Uint8Array,\n box: IsoBox,\n moofStart: number,\n baseDecodeTime: bigint,\n tfhd: ParsedTfhd,\n track: IsoBmffTrackTiming,\n mdat: MdatLayout,\n maxSamples: number,\n): IsoBmffSampleTiming[] | null {\n const full = parseFullBox(data, box)\n if (!full || (full.version !== 0 && full.version !== 1) ||\n (full.flags & ~TRUN_KNOWN_FLAGS) !== 0 ||\n (full.flags & TRUN_DATA_OFFSET_PRESENT) === 0 ||\n ((full.flags & TRUN_FIRST_SAMPLE_FLAGS_PRESENT) !== 0 &&\n (full.flags & TRUN_SAMPLE_FLAGS_PRESENT) !== 0)) {\n return null\n }\n const dataView = view(data)\n let offset = full.bodyStart\n if (offset + 8 > box.end) return null\n const sampleCount = dataView.getUint32(offset, false)\n offset += 4\n if (sampleCount === 0 || sampleCount > maxSamples) return null\n const relativeDataOffset = dataView.getInt32(offset, false)\n offset += 4\n if (relativeDataOffset < 0) return null\n const dataOffset = BigInt(relativeDataOffset)\n const absoluteDataOffset = BigInt(moofStart) + dataOffset\n if (absoluteDataOffset > BigInt(data.length) || absoluteDataOffset < mdat.dataStart) return null\n if ((full.flags & TRUN_FIRST_SAMPLE_FLAGS_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n offset += 4\n }\n\n let decodeTime = baseDecodeTime\n let bytePosition = dataOffset\n const samples: IsoBmffSampleTiming[] = []\n for (let index = 0; index < sampleCount; index++) {\n let entryDuration: number | undefined\n if ((full.flags & TRUN_SAMPLE_DURATION_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n entryDuration = dataView.getUint32(offset, false)\n offset += 4\n }\n let entrySize: number | undefined\n if ((full.flags & TRUN_SAMPLE_SIZE_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n entrySize = dataView.getUint32(offset, false)\n offset += 4\n }\n if ((full.flags & TRUN_SAMPLE_FLAGS_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n offset += 4\n }\n let compositionOffset = 0\n if ((full.flags & TRUN_SAMPLE_CTS_OFFSET_PRESENT) !== 0) {\n if (offset + 4 > box.end) return null\n compositionOffset = full.version === 1\n ? dataView.getInt32(offset, false)\n : dataView.getUint32(offset, false)\n offset += 4\n }\n if (offset > box.end) return null\n\n const duration = resolvedDefault(\n entryDuration,\n tfhd.defaultSampleDuration,\n track.defaultSampleDuration,\n )\n const size = resolvedDefault(entrySize, tfhd.defaultSampleSize, track.defaultSampleSize)\n if (duration === null || size === null) return null\n const sampleEnd = bytePosition + BigInt(size)\n const absoluteSampleEnd = BigInt(moofStart) + sampleEnd\n if (absoluteSampleEnd > mdat.declaredEnd || absoluteSampleEnd > U64_MAX) return null\n const presentationTime = decodeTime + BigInt(compositionOffset)\n if (presentationTime < I64_MIN || presentationTime > I64_MAX) return null\n samples.push({\n decodeTime,\n presentationTime,\n duration,\n timescale: track.timescale,\n size,\n bytePosition,\n })\n decodeTime += BigInt(duration)\n if (decodeTime > U64_MAX) return null\n bytePosition = sampleEnd\n }\n return offset === box.end ? samples : null\n}\n\nexport function parseIsoBmffMovieFragmentTiming(\n data: Uint8Array,\n track: IsoBmffTrackTiming,\n maxSamples: number,\n): IsoBmffMovieFragmentTiming | null {\n if (!Number.isInteger(maxSamples) || maxSamples <= 0) return null\n const first = parseBox(data, 0, data.length)\n if (!first) return null\n const moof = first.type === 'styp'\n ? parseBox(data, first.end, data.length)\n : first\n if (!moof || moof.type !== 'moof' || moof.end >= data.length) return null\n const moofChildren = children(data, moof)\n if (!moofChildren) return null\n const mfhd = exactlyOne(moofChildren, 'mfhd')\n const traf = exactlyOne(moofChildren, 'traf')\n if (!mfhd || !traf) return null\n const movieFragmentSequenceNumber = parseMfhdSequence(data, mfhd)\n if (movieFragmentSequenceNumber === null || movieFragmentSequenceNumber === 0) return null\n\n const trafChildren = children(data, traf)\n if (!trafChildren) return null\n const tfhdBox = exactlyOne(trafChildren, 'tfhd')\n const tfdtBox = exactlyOne(trafChildren, 'tfdt')\n const trunBox = exactlyOne(trafChildren, 'trun')\n if (!tfhdBox || !tfdtBox || !trunBox) return null\n const tfhd = parseTfhd(data, tfhdBox)\n const baseDecodeTime = parseTfdt(data, tfdtBox)\n if (!tfhd || tfhd.trackId !== track.trackId || baseDecodeTime === null) return null\n const mdat = parseMdatLayout(data, moof.end)\n if (!mdat) return null\n const samples = parseTrunSamples(\n data,\n trunBox,\n moof.start,\n baseDecodeTime,\n tfhd,\n track,\n mdat,\n maxSamples,\n )\n if (!samples) return null\n return { movieFragmentSequenceNumber, samples }\n}\n\nfunction sameTrack(a: IsoBmffTrackTiming, b: IsoBmffTrackTiming): boolean {\n return a.trackId === b.trackId &&\n a.timescale === b.timescale &&\n a.defaultSampleDuration === b.defaultSampleDuration &&\n a.defaultSampleSize === b.defaultSampleSize\n}\n\nfunction sameSample(a: IsoBmffSampleTiming, b: IsoBmffSampleTiming): boolean {\n return a.decodeTime === b.decodeTime &&\n a.presentationTime === b.presentationTime &&\n a.duration === b.duration &&\n a.timescale === b.timescale &&\n a.size === b.size &&\n a.bytePosition === b.bytePosition\n}\n\ntype PendingMovieFragment = Array<IsoBmffSampleTiming | null>\n\n/** Bounded per-track FT=0/FT=1 timing state. */\nexport class IsoBmffTimingResolver {\n #track: IsoBmffTrackTiming | null = null\n #fragments = new Map<string, PendingMovieFragment>()\n #pendingSamples = 0\n #evictedSamples = 0\n #lastMovieFragmentRejection: IsoBmffMovieFragmentRejection | null = null\n\n constructor(readonly maxPendingSamples: number) {\n if (!Number.isInteger(maxPendingSamples) || maxPendingSamples <= 0) {\n throw new Error('[IsoBmffTimingResolver] maxPendingSamples must be a positive integer')\n }\n }\n\n get pendingSampleCount(): number {\n return this.#pendingSamples\n }\n\n /**\n * Slots reclaimed by window displacement rather than by delivery or\n * abandonment. Deliberately separate from the combiner's own release count:\n * \"nobody ever saw this sample\" and \"the combiner gave up on it\" are\n * different failures with different owners, and one number cannot say which.\n */\n get evictedSampleCount(): number {\n return this.#evictedSamples\n }\n\n /** Typed reason for the most recent rejected movie fragment. */\n get lastMovieFragmentRejection(): IsoBmffMovieFragmentRejection | null {\n return this.#lastMovieFragmentRejection\n }\n\n addInitialization(data: Uint8Array): boolean {\n const timing = parseIsoBmffInitializationTiming(data)\n if (!timing) return false\n if (this.#track) return sameTrack(this.#track, timing)\n this.#track = timing\n return true\n }\n\n addMovieFragment(\n mpuSequenceNumber: number,\n data: Uint8Array,\n additionalSampleLimit = this.maxPendingSamples,\n ): boolean {\n this.#lastMovieFragmentRejection = null\n if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {\n this.#lastMovieFragmentRejection = 'invalid'\n return false\n }\n if (!this.#track || !isU32(mpuSequenceNumber)) {\n this.#lastMovieFragmentRejection = 'invalid'\n return false\n }\n const parsed = parseIsoBmffMovieFragmentTiming(\n data,\n this.#track,\n this.maxPendingSamples,\n )\n if (!parsed) {\n this.#lastMovieFragmentRejection = 'invalid'\n return false\n }\n const key = fragmentKey(mpuSequenceNumber, parsed.movieFragmentSequenceNumber)\n const existing = this.#fragments.get(key)\n if (existing) {\n return existing.length === parsed.samples.length && existing.every(\n (sample, index) => sample !== null && sameSample(sample, parsed.samples[index]!),\n )\n }\n // Sliding window, not a one-way ratchet. `consumeSample` and\n // `releaseSample` between them cover every sample some component observed\n // -- but a sample whose data units never arrive at all is observed by\n // nobody, so neither path ever runs and its slot is held until `reset()`.\n // Under sustained loss those orphans accumulate until the budget is full\n // of samples that can never arrive, at which point every later moof is\n // refused and media stops permanently with no error.\n //\n // Displacement is the signal no component can raise: once the budget is\n // full and a newer fragment is in hand, the oldest pending fragment's\n // samples are older than the whole window and cannot still be in flight.\n // Reclaiming them keeps the timing that is arriving now and discards the\n // timing that is not; refusing the new fragment does exactly the reverse,\n // which is what wedged the stream. Evicted timing is not silent loss --\n // a late data unit then finds no entry and is dropped against a named\n // reason, which is attributable, bounded, and recoverable.\n let freed = 0\n while (\n this.#fragments.size > 0 &&\n (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples ||\n parsed.samples.length - freed > additionalSampleLimit)\n ) {\n freed += this.#evictOldestFragment()\n }\n // Net new charge against the caller's pool is what it must afford: `freed`\n // slots were already counted there and are handed back by this call.\n if (parsed.samples.length - freed > additionalSampleLimit) {\n this.#lastMovieFragmentRejection = 'budget'\n return false\n }\n if (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples) {\n this.#lastMovieFragmentRejection = 'budget'\n return false\n }\n this.#fragments.set(key, [...parsed.samples])\n this.#pendingSamples += parsed.samples.length\n return true\n }\n\n sampleTiming(\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number,\n sampleNumber: number,\n ): IsoBmffSampleTiming | null {\n if (!isU32(mpuSequenceNumber) || !isU32(movieFragmentSequenceNumber) ||\n movieFragmentSequenceNumber === 0 || !isU32(sampleNumber) || sampleNumber === 0) {\n return null\n }\n const samples = this.#fragments.get(\n fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber),\n )\n return samples?.[sampleNumber - 1] ?? null\n }\n\n consumeSample(\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number,\n sampleNumber: number,\n expected: IsoBmffSampleTiming,\n ): boolean {\n const samples = this.#fragments.get(\n fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber),\n )\n const sample = samples?.[sampleNumber - 1]\n if (!sample || !sameSample(sample, expected)) return false\n return this.#clearSlot(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber)\n }\n\n /**\n * Free the budget slot of a sample that will never be delivered.\n *\n * `consumeSample` is the delivery path and is the only decrement on a\n * healthy stream. A sample whose data units never complete is never\n * delivered; window displacement in `addMovieFragment` eventually reclaims\n * it, but only after it has aged out of the whole window. This path frees\n * the slot as soon as the combiner knows the sample is gone, so the budget\n * tracks what is actually in flight rather than what has merely aged.\n *\n * The caller is whoever abandoned the sample, so the release is driven by\n * the abandonment itself rather than by a timer, an LRU, or an age bound --\n * the slot is freed exactly when its sample provably cannot arrive, which\n * is a protocol event the combiner already detects and counts.\n *\n * Deliberately takes no `expected` timing: the caller is discarding, not\n * matching, and requiring it would make the release fail exactly when the\n * timing entry is the thing being reclaimed. Returns false when the slot\n * was already freed, so a double release cannot drive the count negative.\n */\n releaseSample(\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number,\n sampleNumber: number,\n ): boolean {\n return this.#clearSlot(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber)\n }\n\n /**\n * Drop the oldest pending fragment whole and return the slots it held.\n *\n * Oldest is insertion order, which for a moof stream is arrival order, so\n * this is the least-recently-declared timing -- the entries least likely to\n * still have data units in flight.\n */\n #evictOldestFragment(): number {\n const oldest = this.#fragments.keys().next().value\n if (oldest === undefined) return 0\n const samples = this.#fragments.get(oldest)!\n let live = 0\n for (const sample of samples) if (sample !== null) live++\n this.#fragments.delete(oldest)\n this.#pendingSamples -= live\n this.#evictedSamples += live\n return live\n }\n\n /** Null one slot, decrement the budget, and drop the fragment when empty. */\n #clearSlot(\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number,\n sampleNumber: number,\n ): boolean {\n if (!isU32(mpuSequenceNumber) || !isU32(movieFragmentSequenceNumber) ||\n movieFragmentSequenceNumber === 0 || !isU32(sampleNumber) || sampleNumber === 0) {\n return false\n }\n const key = fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber)\n const samples = this.#fragments.get(key)\n const index = sampleNumber - 1\n if (!samples || !samples[index]) return false\n samples[index] = null\n this.#pendingSamples--\n if (samples.every(value => value === null)) this.#fragments.delete(key)\n return true\n }\n\n reset(): void {\n this.#track = null\n this.#fragments.clear()\n this.#pendingSamples = 0\n }\n}\n\nfunction fragmentKey(mpuSequenceNumber: number, movieFragmentSequenceNumber: number): string {\n return `${mpuSequenceNumber}:${movieFragmentSequenceNumber}`\n}\n\nfunction isU32(value: number): boolean {\n return Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff\n}\n\n/** Convert exact media ticks to microseconds without first narrowing the ticks. */\nexport function mediaTicksToMicroseconds(ticks: bigint, timescale: number): number | null {\n if (!Number.isInteger(timescale) || timescale <= 0) return null\n const numerator = ticks * MICROSECONDS_PER_SECOND\n const scale = BigInt(timescale)\n const whole = numerator / scale\n const remainder = numerator % scale\n if (whole < BigInt(Number.MIN_SAFE_INTEGER) || whole > BigInt(Number.MAX_SAFE_INTEGER)) {\n return null\n }\n const result = Number(whole) + Number(remainder) / timescale\n return Number.isFinite(result) ? result : null\n}\n", "import {\n parseMMTPHeader,\n extractMFUPayloadWithHeader,\n sourceFecPayloadIdOf,\n extractAltaTrailer,\n PACKET_TYPE_MPU,\n PACKET_TYPE_REPAIR,\n type MMTPHeader,\n} from '@blockcast/mmt-base'\nimport {\n MFUReassembler,\n MfuReassemblyError,\n isMfuReassemblyError,\n type MfuReassemblerBackend,\n type MmtpSourcePath,\n type MmtpDeliveryProvenance,\n type ReassembledMFU,\n} from './mfu-reassembler.js'\nimport {\n SampleCombiner,\n SampleCombineError,\n type AbandonedSample,\n type CombinedSample,\n type SampleCombinerOptions,\n type SampleCombinerStats,\n} from './sample-combiner.js'\nimport {\n classifyH264Keyframe,\n isHevcIrapNalUnitType,\n mmtpTimestampToMicros,\n normalizeMmtpInitSegment,\n} from './codec-utils.js'\nimport {\n mmtpFrameReorderWindowFrames,\n mfuReassemblyTimeoutMs,\n type MfuReassemblyPolicy,\n} from './mfu-reassembly-policy.js'\nimport {\n IsoBmffTimingResolver,\n mediaTicksToMicroseconds,\n type IsoBmffSampleTiming,\n} from './iso-bmff-timing.js'\nimport type { AuthoredTiming } from './authored-timing.js'\nimport type { FrameGapDecision } from './block-policy.js'\n\n// \u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 TrackInfo {\n type: 'video' | 'audio'\n codec: string\n /** Catalog/in-band frame cadence available to downstream media stages. */\n framerate?: number\n /** Catalog MMTP group duration available to downstream media stages. */\n groupDurationMs?: number\n}\n\nexport interface MmtpParserConfig {\n tracks?: Map<number, TrackInfo>\n reorderWindow?: number\n /** MFU reassembly timeout (ms). Derive from FEC interleaveDepthMs or frame duration.\n * Pass null for live clock-free operation; memory remains bounded by maxBuffered.\n * Defaults to 1000ms if not provided. */\n mfuTimeoutMs?: number | null\n /** Explicit transport policy. Reliable MoQ is clock-free; datagrams require\n * a catalog/in-band-derived deadline. Mutually exclusive with mfuTimeoutMs. */\n reassemblyPolicy?: MfuReassemblyPolicy\n /** Max concurrent active MFUs. A new first fragment is rejected at the bound. */\n maxBufferedMfus?: number\n /**\n * Max subsample data units held for one partitioned sample (moqcast #37).\n * A sample needs `ceil(sampleSize / (256 * maxPayload))` data units; at the\n * ~1300-byte payloads this producer emits, one data unit spans ~327 KB, so\n * the default admits a ~5 MB sample \u2014 beyond any 8K intra frame \u2014 while\n * still bounding the per-insert overlap scan. Raise it only alongside a\n * larger authored frame size, never to paper over a lost data unit.\n */\n maxSubsampleSegments?: number\n /** Alternate backend. The TypeScript and Rust/WASM implementations enforce\n * the same authored active-DU contract. */\n reassembler?: MfuReassemblerBackend\n /** Default track info for auto-discovered packetIds.\n * When the parser receives an MMTP packet with an unregistered packetId,\n * it creates a new track entry using this info. Required for correct\n * keyframe detection with HEVC/AV1/VP9 (without it, defaults to H.264). */\n defaultTrack?: TrackInfo\n /** In-order release policy for FEC-protected streams (see FecReleaseGate). */\n fecReleaseGate?: FecReleaseGate\n}\n\n/** Structured result from parseHeader(). Used by MmtpRouter for two-phase parsing:\n * 1. parseHeader() \u2192 get packetId + fecPayloadId for FEC feeding\n * 2. feed() \u2192 MFU extraction, reassembly, keyframe detection, emit */\nexport interface PacketInfo {\n packetId: number\n packetType: number\n timestamp: bigint\n /** MMTP timestamp converted to monotonic microseconds for pacing/sync users. */\n timestampUs: number\n sequenceNumber: number\n rapFlag: boolean\n fecType: number\n /** FEC source symbol ID (from 4-byte FEC Payload ID at packet end). Null if no FEC. */\n fecPayloadId: { ssId: number } | null\n /** True if this is a repair packet (packetType=0x03). */\n isRepair: boolean\n}\n\n/**\n * One parse of an MMTP packet's header, as returned by\n * MmtpContainerParser.parsePacket(). Hand it back to feedParsed() so the same\n * packet's header is not parsed again (BLO-36599).\n */\nexport interface ParsedMmtpPacket {\n readonly info: PacketInfo\n /** parseMMTPHeader() of the packet this was parsed from. */\n readonly header: MMTPHeader\n /** The skipFecPayloadId option `info.fecPayloadId` was resolved under. */\n readonly skipFecPayloadId: boolean\n}\n\nexport interface FrameMeta {\n /** Authored ISO-BMFF presentation time converted to microseconds. */\n timestamp: number\n /** Authored ISO-BMFF decode time converted to microseconds. */\n decodeTimestamp?: number\n /** Authored ISO-BMFF sample duration converted to microseconds. */\n duration?: number\n /** Exact authored decode time in mediaTimescale units. */\n decodeTime?: bigint\n /** Exact authored presentation time in mediaTimescale units. */\n presentationTime?: bigint\n /** Exact authored duration in mediaTimescale units. */\n durationTicks?: number\n /** mdhd media timescale for the exact timing fields. */\n mediaTimescale?: number\n /** Exact authored ISO-BMFF timing carried without narrowing to microseconds. */\n authoredTiming?: AuthoredTiming\n keyframe: boolean\n packetId: number\n trackType: 'video' | 'audio' | null\n packetSequenceNumber?: number\n /** Every authoritative MMTP source-packet sequence that formed this frame. */\n packetSequenceNumbers?: number[]\n /** Subset of packetSequenceNumbers reconstructed by FEC. */\n repairedPacketSequenceNumbers?: number[]\n /** Immutable catalog identity supplied by the owning ingress subscription. */\n catalogTrackName?: string\n /** Raw MMTP short-NTP timestamp retained for adapters that own the timeline. */\n mmtpTimestamp?: bigint\n mpuSequenceNumber?: number\n movieFragmentSequenceNumber?: number\n sampleNumber?: number\n fragmentCount?: number\n rapFlag?: boolean\n priority?: number\n recovered?: boolean\n /** Starts a new publisher/source epoch for ordering and timestamp state. */\n sourceDiscontinuity?: boolean\n /** Source of the accepted FI=1/FI=0 frame path. Absent for recovery. */\n source?: MmtpSourcePath\n /**\n * Strict whole-frame delivery provenance. Unlike `source`, which names the\n * head fragment's transport for routing, this is folded over every\n * contributing fragment (and, for FEC-recovered frames, over the transports\n * that supplied the block's symbols). Only 'multicast' is evidence of\n * multicast-exclusive delivery. Absent means no producer on this path\n * recorded provenance \u2014 consumers MUST treat that as unproven, never as\n * multicast.\n */\n deliveryProvenance?: MmtpDeliveryProvenance\n /**\n * FEC source block (SBN) this frame completed in, when it came from an\n * FEC-protected packet or an FEC-recovered block. Drives in-order release\n * on FEC-gated streams.\n */\n fecSbn?: number\n /**\n * Set on the first frame released after a gap: the blocks between it and\n * the previous release resolved with lost media, or authored decode time\n * shows a missing sample. The sink must stall or conceal exactly as decided.\n */\n gapBefore?: FrameGapDecision\n}\n\n/**\n * Per-packet MPU and data-unit identity, read without reassembly. The router\n * uses it as classification evidence for the FEC block the packet belongs to.\n */\nexport interface SourcePacketIdentity {\n mpuSequenceNumber: number\n /** 1-based MFU DU-header sample_number, when this packet carries a DU header. */\n sampleNumber?: number\n movieFragmentSequenceNumber?: number\n /** DU-header offset: the data unit's authored byte position in its sample. */\n offset?: number\n}\n\n/**\n * In-order release policy for FEC-protected streams. For such a stream a\n * frame after a gap is released only once every FEC block that could hold\n * the missing frames has resolved (completed or failed); the frame-count\n * reorder window applies only to streams without FEC.\n */\nexport interface FecReleaseGate {\n /** True when this physical stream's frames are FEC-gated. */\n gates(packetId: number, catalogTrackName?: string): boolean\n /**\n * Resolution of the blocks `[fromSbn, toSbn]`: null while any of them can\n * still complete, otherwise the SBNs whose media was lost (empty when no\n * block failed; the release still carries a decision when authored decode\n * time shows a missing sample). `releasedSbn` is the block of the frame\n * released before the gap: that frame arrived, so its block is not lost\n * merely because it has since retired.\n */\n resolvedLoss(\n packetId: number,\n catalogTrackName: string | undefined,\n fromSbn: number,\n toSbn: number,\n releasedSbn: number,\n ): readonly number[] | null\n /**\n * Longest a frame may wait behind unresolved blocks, in milliseconds from\n * its arrival: by then every block that could hold the frames before it\n * must have resolved. Past it the frame is released as a discontinuity.\n * It must not exceed how long a resolved block stays readable as resolved.\n */\n holdLimitMs(packetId: number, catalogTrackName?: string): number\n /** Decide stall/conceal for the first frame released after a gap. */\n decide(\n before: { data: Uint8Array; meta: FrameMeta },\n after: { data: Uint8Array; meta: FrameMeta },\n lostBlocks: readonly number[],\n discontinuity: boolean,\n ): FrameGapDecision\n /** Every frame released in order from a gated stream. */\n onReleased?(data: Uint8Array, meta: FrameMeta): void\n}\n\n/** Typed ISO-BMFF timing-sample budget counters. See `timingBudgetStats`. */\nexport interface MmtpTimingBudgetStats {\n /** Slots currently charged to declared-but-undelivered samples. */\n pending: number\n /** Total slots available; `pending === capacity` rejects every new moof. */\n capacity: number\n /** Slots returned by samples the combiner abandoned (evicted or timed out). */\n reclaimed: number\n /**\n * Slots reclaimed by window displacement \u2014 samples no component ever saw,\n * so no abandonment event could be raised for them. Separate from\n * `reclaimed` because the owners differ: `reclaimed` is the combiner giving\n * up, `evicted` is loss that was never observable at all.\n */\n evicted: number\n /** Movie fragments refused because the budget had no room for their samples. */\n rejectedMovieFragments: number\n}\n\nexport interface MmtpReorderStats {\n droppedBeforeStartupKeyframe: number\n droppedIncompleteStartupInterval: number\n droppedStale: number\n forcedWindowFlushes: number\n droppedOnLiveDispose: number\n publisherResets: number\n droppedOnPublisherReset: number\n bufferedFrames: number\n}\n\nexport interface MmtpReorderFrameDiagnostics {\n timestampUs: number\n keyframe: boolean\n sequenceNumber: number\n packetSequenceNumber?: number\n movieFragmentSequenceNumber?: number\n sampleNumber?: number\n fragmentCount?: number\n}\n\nexport interface MmtpReorderStreamDiagnostics {\n packetId: number\n bufferedFrames: number\n lastEmitted: MmtpReorderFrameDiagnostics | null\n startupKeyframe: MmtpReorderFrameDiagnostics | null\n head: MmtpReorderFrameDiagnostics[]\n tail: MmtpReorderFrameDiagnostics[]\n keyframes: MmtpReorderFrameDiagnostics[]\n}\n\nexport type MmtpParserRecord =\n | {\n kind: 'repair' | 'non-media'\n packet: PacketInfo\n byteLength: number\n }\n | {\n kind: 'init' | 'fragment'\n packet: PacketInfo\n data: Uint8Array\n mpuSequenceNumber: number\n fragmentationIndicator: number\n fragmentCounter: number\n }\n | {\n kind: 'pending'\n packet: PacketInfo\n mpuSequenceNumber: number\n fragmentationIndicator: number\n fragmentCounter: number\n }\n | {\n kind: 'rejected'\n packet: PacketInfo\n mpuSequenceNumber: number\n fragmentationIndicator: number\n fragmentCounter: number\n error: {\n /**\n * Either a single data unit's own fragment chain was rejected, or\n * combining reassembled data units into a sample was (moqcast #37).\n * Both are fail-closed drops of the same packet, so they share this\n * record; the code says which class it came from.\n */\n code: MfuReassemblyError['code'] | SampleCombineError['code']\n message: string\n }\n }\n | {\n kind: 'frame'\n packet: PacketInfo\n data: Uint8Array\n meta: FrameMeta\n mpuSequenceNumber: number\n fragmentCount: number\n rapFlag: boolean\n priority?: number\n }\n\n/**\n * Why feed() returned no record. Every `return null` inside feed() names one\n * of these, so a packet that produced nothing is attributable to the stage\n * that rejected it rather than to one collapsed failure bucket.\n *\n * The distinction is what makes a wedged receive path readable: a media track\n * that stops producing records looks identical from outside whether the header\n * failed to parse, MFU extraction failed, or the timing resolver refused the\n * sample \u2014 and those name three different components.\n */\nexport type MmtpFeedDropReason =\n /** feed() after dispose(); the host is still pushing at a torn-down parser. */\n | 'disposed'\n | 'header-parse-failed'\n | 'mfu-extract-failed'\n /** MPU present but not a timed MFU, so no media payload to reassemble. */\n | 'untimed-mpu'\n | 'init-unexpected-fragmentation'\n | 'init-normalize-failed'\n /** No timing resolver, or it refused the initialization segment. */\n | 'init-timing-refused'\n | 'fragment-unexpected-fragmentation'\n | 'fragment-no-resolver'\n /** addMovieFragment refused \u2014 includes the pending-timing-sample budget. */\n | 'fragment-timing-refused'\n | 'unknown-fragment-type'\n | 'mfu-no-resolver'\n | 'mfu-empty-payload'\n | 'mfu-du-header-missing'\n | 'mfu-sample-timing-missing'\n | 'mfu-offset-out-of-range'\n | 'mfu-size-mismatch'\n | 'assembled-identity-missing'\n | 'assembled-timing-missing'\n | 'assembled-mpu-mismatch'\n /**\n * Refusals inside the combined-sample delivery step, which runs after the\n * combiner has already produced a whole sample. These are distinct from\n * their `assembled-*` counterparts: those reject a data unit on the way in,\n * these reject a sample that was fully reassembled and then found\n * undeliverable, so collapsing the two would hide a combiner that completes\n * samples nothing can present.\n */\n | 'combined-timing-missing'\n | 'combined-size-mismatch'\n /** Frame metadata could not be built \u2014 an fMP4 box arrived as a timed MFU\n * payload, or the authored timing converts to a non-positive duration. */\n | 'combined-meta-build-failed'\n | 'combined-timing-consume-refused'\n /** feed() threw. Counted so the tally still sums to fedObjects; the error\n * is rethrown, never swallowed. */\n | 'threw'\n\n/**\n * Every key `outcomes` can carry: one per record kind, one per drop reason.\n *\n * Derived from the two unions rather than written out, so a new record kind or\n * drop reason cannot be counted under a key the type does not admit, and a\n * consumer can enumerate the vocabulary from the type instead of from prose.\n */\nexport type MmtpFeedOutcomeKey =\n | MmtpParserRecord['kind']\n | `drop:${MmtpFeedDropReason}`\n\n/**\n * Feed tallies owned by the parser.\n *\n * These live here rather than on MmtpDecodePipeline because the two players\n * sit at different layers of this library: hang-mmt-fec drives the pipeline,\n * while moqtail constructs MmtpContainerParser directly and never builds the\n * wrapper. feed() is the one chokepoint both cross, so a tally maintained here\n * instruments both by construction.\n *\n * Logs are diagnostic output, not an acceptance API \u2014 this is the typed\n * counter a harness should read instead of scraping console histograms.\n */\nexport interface MmtpParserFeedStats {\n /** Every packet handed to feed(), including post-dispose calls. */\n fedObjects: number\n /**\n * Mutually exclusive outcome tally: record kinds under their own `kind`,\n * drops under `drop:<reason>`. The values sum to exactly `fedObjects`, which\n * is the property that makes a frozen media bucket beside a still-climbing\n * non-media bucket a readable signal rather than two unrelated numbers.\n *\n * Partial because a key appears only once it has been counted; absent and\n * zero mean the same thing to a reader.\n */\n outcomes: Partial<Record<MmtpFeedOutcomeKey, number>>\n /**\n * Refusals from a completed older sample delivered while registering a\n * later packet's authored size. Kept separate because that side effect is\n * not the packet's own feed outcome.\n */\n deferredOutcomes: Partial<Record<MmtpFeedDropReason, number>>\n}\n\ntype FrameCallback = (data: Uint8Array, meta: FrameMeta) => void\ntype InitCallback = (data: Uint8Array, packetId: number, catalogTrackName?: string) => void\n\n/**\n * Result of one combined-sample delivery attempt: either the record to return\n * or the reason the sample could not be delivered.\n *\n * Internal to the parser. A bare `null` would be indistinguishable from the\n * other refusals `feed()` can take, and the whole point of the drop-reason\n * vocabulary is that a stage which stops producing frames says which stage it\n * was.\n */\ntype CombinedSampleOutcome =\n | { readonly record: MmtpParserRecord; readonly reason?: undefined }\n | { readonly record?: undefined; readonly reason: MmtpFeedDropReason }\n\nexport function isMfuKeyframeMetadata(rapFlag: boolean, priority?: number): boolean {\n return rapFlag || (priority ?? 0) > 0x80\n}\n\n/** Per-packet detached ALTA authenticator trailer (08-07 Path 2).\n * - `auth`: the authenticator bytes (length-prefixed at packet end).\n * - `payloadEnd`: byte offset within the source packet where signed\n * payload ends \u2014 consumers reconstruct `payload = packet[0..payloadEnd]`\n * for verify_detached. */\nexport interface ParsedAltaTrailer {\n auth: Uint8Array\n payloadEnd: number\n}\n\n/** Source-symbol exposure for FEC consumers.\n *\n * Fires from {@link MmtpContainerParser.feed} once per FEC-protected source\n * packet \u2014 after parseHeader confirms fec_payload_id is present, before MFU\n * extraction.\n *\n * Arguments:\n * - `packetId` \u2013 MMTP header `packet_id` (track identifier)\n * - `ssId` \u2013 flat Source Symbol ID from the 4-byte fec_payload_id trailer\n * - `rawSymbol` \u2013 packet bytes minus the 4-byte fec_payload_id trailer.\n * NOT zero-padded to FEC symbol size \u2014 consumer pads if needed\n * (FEC symbol size is FEC-config, not parser-config).\n * - `alta` \u2013 detached ALTA authenticator if present, else undefined\n *\n * Designed so consumers (player, Shaka shim, upstream moqtail) can wire\n * source-symbol delivery to whatever FEC pipeline they own, without depending\n * on libmmt's MulticastManager/MmtpRouter/FECManager stack. */\ntype SourceSymbolCallback = (\n packetId: number,\n ssId: number,\n rawSymbol: Uint8Array,\n alta: ParsedAltaTrailer | undefined,\n) => void\n\nexport interface ParseHeaderOptions {\n /** Recovered source symbols already had the trailing Source FEC Payload ID stripped. */\n skipFecPayloadId?: boolean\n /** Mark frames emitted from this packet as FEC-recovered. */\n recovered?: boolean\n /** Exact catalog track bound to this packet by its ingress subscription. */\n catalogTrackName?: string\n /** Source transport for parser-owned frame attribution. */\n source?: MmtpSourcePath\n /**\n * Explicit strict provenance for the fragments this packet produces.\n * The router sets it for FEC-recovered packets, which carry no `source`\n * but whose FEC block's symbol provenance is known.\n */\n deliveryProvenance?: MmtpDeliveryProvenance\n /** FEC source block this packet belongs to (FEC-protected packets only). */\n fecSbn?: number\n}\n\n// \u2500\u2500 FrameSequencer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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\ninterface PendingFrame {\n data: Uint8Array\n meta: FrameMeta\n seq: number\n}\n\ninterface SequencerStream {\n buf: PendingFrame[]\n lastEmitted: PendingFrame | null\n}\n\nfunction reorderFrameDiagnostics(frame: PendingFrame): MmtpReorderFrameDiagnostics {\n return {\n timestampUs: frame.meta.timestamp,\n keyframe: frame.meta.keyframe,\n sequenceNumber: frame.seq,\n ...(frame.meta.packetSequenceNumber === undefined\n ? {}\n : { packetSequenceNumber: frame.meta.packetSequenceNumber }),\n ...(frame.meta.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: frame.meta.movieFragmentSequenceNumber }),\n ...(frame.meta.sampleNumber === undefined ? {} : { sampleNumber: frame.meta.sampleNumber }),\n ...(frame.meta.fragmentCount === undefined\n ? {}\n : { fragmentCount: frame.meta.fragmentCount }),\n }\n}\n\ntype SequencerStat = Exclude<keyof MmtpReorderStats, 'bufferedFrames'>\n\nfunction serialSequenceDelta(a: number, b: number): number {\n return (a - b) | 0\n}\n\nfunction compareFrameOrder(\n a: PendingFrame,\n b: PendingFrame,\n): number {\n if (a.meta.decodeTime !== undefined && b.meta.decodeTime !== undefined &&\n a.meta.mediaTimescale === b.meta.mediaTimescale) {\n if (a.meta.decodeTime < b.meta.decodeTime) return -1\n if (a.meta.decodeTime > b.meta.decodeTime) return 1\n } else {\n const decodeDelta = (a.meta.decodeTimestamp ?? a.meta.timestamp) -\n (b.meta.decodeTimestamp ?? b.meta.timestamp)\n if (decodeDelta !== 0) return decodeDelta\n }\n const movieDelta = serialSequenceDelta(\n a.meta.movieFragmentSequenceNumber ?? 0,\n b.meta.movieFragmentSequenceNumber ?? 0,\n )\n if (movieDelta !== 0) return movieDelta\n const sampleDelta = (a.meta.sampleNumber ?? 0) - (b.meta.sampleNumber ?? 0)\n return sampleDelta !== 0 ? sampleDelta : serialSequenceDelta(a.seq, b.seq)\n}\n\nclass FrameSequencer {\n #streams = new Map<number, SequencerStream>()\n #windowSize: number\n #emit: (data: Uint8Array, meta: FrameMeta) => void\n #recordStat: (stat: SequencerStat, count?: number) => void\n\n constructor(\n windowSize: number,\n emit: (data: Uint8Array, meta: FrameMeta) => void,\n recordStat: (stat: SequencerStat, count?: number) => void = () => {},\n ) {\n this.#windowSize = windowSize\n this.#emit = emit\n this.#recordStat = recordStat\n }\n\n push(data: Uint8Array, meta: FrameMeta, seq: number): void {\n if (this.#windowSize <= 0) {\n this.#emit(data, meta)\n return\n }\n const frame: PendingFrame = { data, meta: { ...meta }, seq }\n const stream = this.#streamFor(meta.packetId)\n if (meta.sourceDiscontinuity) {\n this.#recordStat('publisherResets')\n this.#recordStat('droppedOnPublisherReset', stream.buf.length)\n stream.buf = []\n stream.lastEmitted = null\n frame.meta.sourceDiscontinuity = true\n }\n if (this.#isStale(stream, frame)) {\n this.#recordStat('droppedStale')\n return\n }\n if (meta.keyframe && stream.lastEmitted === null) {\n // The first RAP establishes decoder sync. Discard any pre-RAP media and\n // emit it immediately so startup does not pay the reorder-window delay.\n this.#recordStat('droppedBeforeStartupKeyframe', stream.buf.length)\n stream.buf = []\n this.#emitFrame(stream, frame)\n return\n }\n let lo = 0, hi = stream.buf.length\n while (lo < hi) {\n const mid = (lo + hi) >>> 1\n if (compareFrameOrder(stream.buf[mid]!, frame) < 0) lo = mid + 1\n else hi = mid\n }\n stream.buf.splice(lo, 0, frame)\n while (stream.buf.length > this.#windowSize) this.#flushHead(stream)\n }\n\n flush(): void {\n for (const packetId of [...this.#streams.keys()].sort((a, b) => a - b)) {\n const stream = this.#streams.get(packetId)\n while (stream && stream.buf.length > 0) this.#flushHead(stream)\n }\n }\n\n get buffered(): number {\n let total = 0\n for (const stream of this.#streams.values()) total += stream.buf.length\n return total\n }\n\n get diagnostics(): Omit<MmtpReorderStreamDiagnostics, 'packetId'>[] {\n return [...this.#streams.values()].map(stream => ({\n bufferedFrames: stream.buf.length,\n lastEmitted: stream.lastEmitted ? reorderFrameDiagnostics(stream.lastEmitted) : null,\n startupKeyframe: null,\n head: stream.buf.slice(0, 4).map(reorderFrameDiagnostics),\n tail: stream.buf.slice(-4).map(reorderFrameDiagnostics),\n keyframes: stream.buf.filter(frame => frame.meta.keyframe).slice(0, 8)\n .map(reorderFrameDiagnostics),\n }))\n }\n\n discard(): void {\n for (const stream of this.#streams.values()) {\n this.#recordStat('droppedOnLiveDispose', stream.buf.length)\n stream.buf = []\n }\n this.#streams.clear()\n }\n\n #streamFor(packetId: number): SequencerStream {\n let stream = this.#streams.get(packetId)\n if (!stream) {\n stream = { buf: [], lastEmitted: null }\n this.#streams.set(packetId, stream)\n }\n return stream\n }\n\n #flushHead(stream: SequencerStream): boolean {\n const f = stream.buf.shift()\n if (!f) return false\n return this.#emitFrame(stream, f)\n }\n\n #isStale(stream: SequencerStream, frame: PendingFrame): boolean {\n return stream.lastEmitted !== null &&\n compareFrameOrder(frame, stream.lastEmitted) <= 0\n }\n\n #emitFrame(stream: SequencerStream, frame: PendingFrame): boolean {\n if (this.#isStale(stream, frame)) {\n this.#recordStat('droppedStale')\n return false\n }\n stream.lastEmitted = frame\n this.#emit(frame.data, frame.meta)\n return true\n }\n}\n\n// \u2500\u2500 FecReleaseSequencer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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/** Authored decode-time adjacency: the next frame starts where this one ends. */\nfunction authoredAdjacent(before: FrameMeta, after: FrameMeta): boolean {\n const a = before.authoredTiming\n const b = after.authoredTiming\n if (!a || !b || a.mediaTimescale !== b.mediaTimescale) return false\n return b.decodeTime === a.decodeTime + BigInt(a.durationTicks)\n}\n\n/**\n * Authored decode time proves media is missing between two frames: the next\n * frame starts after this one ends. ISO-BMFF decode times of one track are\n * contiguous, so this is positive evidence of a missing sample whatever the\n * reason it went missing (a failed FEC block, or a frame the parser or the\n * recovery path could not deliver although its block completed).\n */\nfunction authoredGap(before: FrameMeta, after: FrameMeta): boolean {\n const a = before.authoredTiming\n const b = after.authoredTiming\n if (!a || !b || a.mediaTimescale !== b.mediaTimescale) return false\n return b.decodeTime > a.decodeTime + BigInt(a.durationTicks)\n}\n\ninterface GatedFrame extends PendingFrame {\n /** performance.now() at push; measures the hold against the gate's limit. */\n arrivedAtMs: number\n}\n\ninterface GatedStream {\n packetId: number\n catalogTrackName?: string\n buf: GatedFrame[]\n last: PendingFrame | null\n lastSbn: number | undefined\n discontinuity: boolean\n}\n\n/**\n * In-order release for FEC-protected streams, driven by block resolution\n * instead of a frame-count window. A frame adjacent (in authored decode time)\n * to the last released frame is released immediately. A frame after a gap\n * waits until every block between the last released frame's block and its\n * own has resolved; a D-28 repair or a late in-band recovery can therefore\n * still fill the gap. When the resolved blocks lost media, or authored decode\n * time shows a missing sample, the release carries the gate's stall/conceal\n * decision as `gapBefore`.\n *\n * The wait is bounded here, not by the blocks: a frame held longer than the\n * gate's `holdLimitMs` since it arrived is released with the gate's\n * discontinuity decision (a stall), so a block that never resolves cannot\n * grow the buffer without limit. There is no timer: the check runs on the\n * next push or poke, so after a total outage held frames are released by the\n * first packet that arrives, not at the ceiling itself.\n */\nclass FecReleaseSequencer {\n #streams = new Map<string, GatedStream>()\n readonly #gate: FecReleaseGate\n readonly #emit: (data: Uint8Array, meta: FrameMeta) => void\n readonly #recordStat: (stat: SequencerStat, count?: number) => void\n\n constructor(\n gate: FecReleaseGate,\n emit: (data: Uint8Array, meta: FrameMeta) => void,\n recordStat: (stat: SequencerStat, count?: number) => void,\n ) {\n this.#gate = gate\n this.#emit = emit\n this.#recordStat = recordStat\n }\n\n get buffered(): number {\n let total = 0\n for (const stream of this.#streams.values()) total += stream.buf.length\n return total\n }\n\n push(streamKey: string, data: Uint8Array, meta: FrameMeta, seq: number): void {\n const frame: GatedFrame = { data, meta: { ...meta }, seq, arrivedAtMs: performance.now() }\n const stream = this.#streamFor(streamKey, meta)\n if (meta.sourceDiscontinuity) {\n this.#recordStat('publisherResets')\n this.#recordStat('droppedOnPublisherReset', stream.buf.length)\n stream.buf = []\n stream.last = null\n stream.lastSbn = undefined\n stream.discontinuity = false\n }\n if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {\n this.#recordStat('droppedStale')\n return\n }\n if (stream.last === null) {\n // The first release establishes decoder sync: video must start on a\n // RAP; earlier deltas are undecodable and are dropped.\n if (meta.trackType === 'video' && !meta.keyframe) {\n this.#recordStat('droppedBeforeStartupKeyframe')\n return\n }\n this.#release(stream, frame, undefined)\n this.#drain(stream)\n return\n }\n let lo = 0\n let hi = stream.buf.length\n while (lo < hi) {\n const mid = (lo + hi) >>> 1\n if (compareFrameOrder(stream.buf[mid]!, frame) < 0) lo = mid + 1\n else hi = mid\n }\n stream.buf.splice(lo, 0, frame)\n this.#drain(stream)\n }\n\n /** Re-evaluate held gaps after FEC state changed. */\n poke(streamKey?: string): void {\n if (streamKey !== undefined) {\n const stream = this.#streams.get(streamKey)\n if (stream) this.#drain(stream)\n return\n }\n for (const stream of this.#streams.values()) this.#drain(stream)\n }\n\n /**\n * The source restarted: the next release stalls with `discontinuity`.\n * Only marks the stream. Frames held behind the restart are released by\n * the next `poke` (or push), so the caller decides when the drain runs; a\n * drain from inside FEC bookkeeping would re-enter it mid-update.\n */\n markDiscontinuity(streamKey: string): void {\n const stream = this.#streams.get(streamKey)\n if (!stream || stream.last === null) return\n stream.discontinuity = true\n }\n\n /** Release everything buffered, in order (finite inputs). */\n flush(): void {\n for (const stream of this.#streams.values()) {\n this.#drain(stream)\n while (stream.buf.length > 0) {\n const head = stream.buf[0]!\n stream.buf.shift()\n this.#release(stream, head, undefined)\n }\n }\n }\n\n discardStream(streamKey: string): void {\n const stream = this.#streams.get(streamKey)\n if (!stream) return\n this.#recordStat('droppedOnLiveDispose', stream.buf.length)\n // Empty the buffer too: a discard can run from inside this stream's own\n // drain (a released frame whose sink retires the stream), and the drain\n // loop reads `buf` on every iteration. Deleting the entry alone would let\n // it keep releasing frames of a stream that no longer exists.\n stream.buf = []\n this.#streams.delete(streamKey)\n }\n\n /** Release one packet's buffered frames in order and forget its streams. */\n flushPacket(packetId: number): void {\n for (const [key, stream] of this.#streams) {\n if (stream.packetId !== packetId) continue\n this.#drain(stream)\n while (stream.buf.length > 0) {\n const head = stream.buf[0]!\n stream.buf.shift()\n this.#release(stream, head, undefined)\n }\n this.#streams.delete(key)\n }\n }\n\n discardPacket(packetId: number): void {\n for (const [key, stream] of this.#streams) {\n if (stream.packetId !== packetId) continue\n this.#recordStat('droppedOnLiveDispose', stream.buf.length)\n stream.buf = []\n this.#streams.delete(key)\n }\n }\n\n discard(): void {\n for (const stream of this.#streams.values()) {\n this.#recordStat('droppedOnLiveDispose', stream.buf.length)\n stream.buf = []\n }\n this.#streams.clear()\n }\n\n #streamFor(streamKey: string, meta: FrameMeta): GatedStream {\n let stream = this.#streams.get(streamKey)\n if (!stream) {\n stream = {\n packetId: meta.packetId,\n ...(meta.catalogTrackName === undefined ? {} : { catalogTrackName: meta.catalogTrackName }),\n buf: [],\n last: null,\n lastSbn: undefined,\n discontinuity: false,\n }\n this.#streams.set(streamKey, stream)\n }\n return stream\n }\n\n #drain(stream: GatedStream): void {\n while (stream.buf.length > 0 && stream.last !== null) {\n const head = stream.buf[0]!\n const last = stream.last\n if (stream.discontinuity) {\n stream.discontinuity = false\n stream.buf.shift()\n this.#release(stream, head, this.#gate.decide(last, head, [], true))\n continue\n }\n if (authoredAdjacent(last.meta, head.meta)) {\n stream.buf.shift()\n this.#release(stream, head, undefined)\n continue\n }\n const headSbn = head.meta.fecSbn\n const from = stream.lastSbn ?? headSbn\n const to = headSbn ?? stream.lastSbn\n let lost: readonly number[] = []\n // Neither side carries a Source FEC Payload ID: on a catalog-declared\n // FEC track that is the trailer-stripped profile violation, and there\n // are no blocks to wait on. The gap is still a gap: never release across\n // it undecided (fail closed), let the gate decide with no known blocks.\n const unanchored = from === undefined && to === undefined\n if (from !== undefined && to !== undefined) {\n const resolved = this.#gate.resolvedLoss(\n stream.packetId,\n stream.catalogTrackName,\n Math.min(from, to),\n Math.max(from, to),\n from,\n )\n if (resolved === null) {\n const heldMs = performance.now() - head.arrivedAtMs\n if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return\n // Past the point where these blocks must have resolved: nothing\n // is known about the gap, so stall rather than hold forever.\n this.#recordStat('forcedWindowFlushes')\n stream.buf.shift()\n this.#release(stream, head, this.#gate.decide(last, head, [], true))\n continue\n }\n lost = resolved\n }\n stream.buf.shift()\n // Every gap in the frame sequence gets a decision, not only one whose\n // blocks failed: a frame can go missing although its block completed\n // (recovered media whose authored timing is gone, a parser drop), and\n // releasing the next frame undecided would feed the decoder past a\n // hole with no stall or hold.\n this.#release(\n stream,\n head,\n lost.length > 0 || unanchored || authoredGap(last.meta, head.meta)\n ? this.#gate.decide(last, head, lost, false)\n : undefined,\n )\n }\n }\n\n #release(stream: GatedStream, frame: PendingFrame, decision: FrameGapDecision | undefined): void {\n if (decision) frame.meta.gapBefore = decision\n stream.last = frame\n if (frame.meta.fecSbn !== undefined) stream.lastSbn = frame.meta.fecSbn\n this.#gate.onReleased?.(frame.data, frame.meta)\n this.#emit(frame.data, frame.meta)\n }\n}\n\n// \u2500\u2500 fMP4 box detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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\nconst FMPU_BOX_TYPES = new Set(['ftyp', 'moov', 'moof'])\n\nfunction isFmp4Box(data: Uint8Array): boolean {\n if (data.length < 8) return false\n const type = String.fromCharCode(data[4]!, data[5]!, data[6]!, data[7]!)\n return FMPU_BOX_TYPES.has(type)\n}\n\ninterface TimingStreamState {\n packetId: number\n resolver: IsoBmffTimingResolver\n}\n\n// \u2500\u2500 MmtpContainerParser \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 class MmtpContainerParser {\n #tracks = new Map<number, TrackInfo>()\n #defaultTrack: TrackInfo | null = null\n #reassembler: MfuReassemblerBackend\n /**\n * Combines subsample data units back into whole samples (moqcast #37), one\n * combiner per parser stream. Per-stream is required, not an optimization:\n * {@link SampleCombiner} identifies a sample by\n * `(catalogTrackName, mpu, movieFragment, sampleNumber)`, so two streams\n * that carry no catalog identity would collide on every sample number and\n * each would see the other's data units as duplicates of its own. The\n * parser already isolates timing and reordering by this same stream key.\n *\n * Inert until a producer partitions \u2014 which it does the moment a frame\n * exceeds one data unit's 256-payload capacity (~327 KB here, routinely\n * exceeded by 4K/8K intra frames).\n */\n #sampleCombiners = new Map<string, SampleCombiner>()\n #sampleCombinerOptions: SampleCombinerOptions\n /** Counters folded in from combiners dropped by a track reset, so the\n * totals below stay monotonic across a publisher change. */\n #retiredSampleCombinerStats: SampleCombinerStats = {\n combinedSamples: 0,\n passthroughSamples: 0,\n timedOutSamples: 0,\n evictedSamples: 0,\n }\n #timingStreams = new Map<string, TimingStreamState>()\n #maxPendingTimingSamples: number\n #pendingTimingSamples = 0\n #reclaimedTimingSamples = 0\n #evictedTimingSamples = 0\n #rejectedMovieFragments = 0\n #sequencers = new Map<string, { packetId: number; sequencer: FrameSequencer }>()\n #fecGate: FecReleaseGate | null = null\n #fecSequencer: FecReleaseSequencer | null = null\n #reorderWindow = 0\n #reassemblyPolicy: MfuReassemblyPolicy | null = null\n #frameCb: FrameCallback | null = null\n #initCb: InitCallback | null = null\n #sourceSymbolCb: SourceSymbolCallback | null = null\n #trackFrameCbs = new Map<number, FrameCallback>()\n #reorderStats: Omit<MmtpReorderStats, 'bufferedFrames'> = {\n droppedBeforeStartupKeyframe: 0,\n droppedIncompleteStartupInterval: 0,\n droppedStale: 0,\n forcedWindowFlushes: 0,\n droppedOnLiveDispose: 0,\n publisherResets: 0,\n droppedOnPublisherReset: 0,\n }\n /** Streams (keyed by physical parser stream, value is packetId) that have\n * observed their first RAP under a reliable-moq policy. Reliable MoQ\n * resolves to a zero parser reorder window (transport ordering is\n * protocol-owned), so #sequencerFor returns null and its own startup gate\n * never runs; this map preserves an order-independent \"discard delta\n * frames before the first RAP\" gate for that path without reintroducing\n * reordering into the parser. */\n #reliableMoqStartupGate = new Map<string, number>()\n #disposed = false\n #fedObjects = 0\n #reassemblerFragmentsFed = 0\n #reassemblerDataUnitsReturned = 0\n #feedOutcomes = new Map<MmtpFeedOutcomeKey, number>()\n #deferredFeedOutcomes = new Map<MmtpFeedDropReason, number>()\n #lastOutcome: MmtpFeedOutcomeKey | null = null\n #lastOutcomeCount = 0\n\n #streamKey(packetId: number, catalogTrackName?: string): string {\n return JSON.stringify([packetId, catalogTrackName ?? null])\n }\n\n #sampleCombinerFor(streamKey: string): SampleCombiner {\n let combiner = this.#sampleCombiners.get(streamKey)\n if (combiner === undefined) {\n combiner = new SampleCombiner({\n ...this.#sampleCombinerOptions,\n onAbandon: sample => this.#releaseTimingSlot(streamKey, sample),\n })\n this.#sampleCombiners.set(streamKey, combiner)\n }\n return combiner\n }\n\n /**\n * Return the timing budget slot of a sample the combiner abandoned.\n *\n * Without this, `#pendingTimingSamples` is charged for every sample a moof\n * declares but credited only when that sample is delivered, so each sample\n * lost to eviction or timeout burns a slot until the window displaces it.\n * Window displacement bounds that leak but only reclaims the OLDEST entries;\n * this path returns a slot the moment the combiner knows the sample is gone,\n * which keeps the live window as wide as the stream actually needs.\n *\n * The parser total is decremented only when the resolver reports it\n * actually freed a slot, so a resolver already dropped by a track reset, or\n * a sample released twice, cannot drive the accounting negative.\n */\n #releaseTimingSlot(streamKey: string, sample: AbandonedSample): void {\n const resolver = this.#timingStreams.get(streamKey)?.resolver\n if (!resolver) return\n if (!resolver.releaseSample(\n sample.mpuSequenceNumber,\n sample.movieFragmentSequenceNumber,\n sample.sampleNumber,\n )) return\n this.#pendingTimingSamples--\n this.#reclaimedTimingSamples++\n if (this.#pendingTimingSamples < 0) {\n throw new Error('[MmtpContainerParser] pending timing sample accounting underflow')\n }\n }\n\n /** Drop one stream's combiner, folding its counters into the retained\n * totals so a reset cannot make the exposed stats run backwards. */\n #dropSampleCombiner(streamKey: string): void {\n const combiner = this.#sampleCombiners.get(streamKey)\n if (combiner === undefined) return\n const stats = combiner.stats\n this.#retiredSampleCombinerStats.combinedSamples += stats.combinedSamples\n this.#retiredSampleCombinerStats.passthroughSamples += stats.passthroughSamples\n this.#retiredSampleCombinerStats.timedOutSamples += stats.timedOutSamples\n this.#retiredSampleCombinerStats.evictedSamples += stats.evictedSamples\n this.#sampleCombiners.delete(streamKey)\n }\n\n constructor(config?: MmtpParserConfig) {\n if (config?.reassemblyPolicy && config.mfuTimeoutMs !== undefined) {\n throw new Error('[MmtpContainerParser] use reassemblyPolicy or mfuTimeoutMs, not both')\n }\n const reassemblyPolicy = config?.reassemblyPolicy ?? null\n const requestedReorderWindow = config?.reorderWindow ?? 0\n if (!Number.isFinite(requestedReorderWindow) || requestedReorderWindow < 0) {\n throw new Error('[MmtpContainerParser] reorderWindow must be a finite number >= 0')\n }\n const normalizedReorderWindow = Math.ceil(requestedReorderWindow)\n const requestedMfuTimeout = reassemblyPolicy\n ? mfuReassemblyTimeoutMs(reassemblyPolicy)\n : config?.mfuTimeoutMs\n if (reassemblyPolicy) {\n mmtpFrameReorderWindowFrames(reassemblyPolicy, normalizedReorderWindow)\n }\n if (\n requestedMfuTimeout !== undefined &&\n requestedMfuTimeout !== null &&\n requestedMfuTimeout <= 0\n ) {\n throw new Error('[MmtpContainerParser] mfuTimeoutMs must be > 0')\n }\n const maxPendingTimingSamples = config?.maxBufferedMfus ?? 100\n if (!Number.isInteger(maxPendingTimingSamples) || maxPendingTimingSamples <= 0) {\n throw new Error('[MmtpContainerParser] maxBufferedMfus must be a positive integer')\n }\n this.#maxPendingTimingSamples = maxPendingTimingSamples\n\n const maxSubsampleSegments = config?.maxSubsampleSegments ?? 16\n if (!Number.isInteger(maxSubsampleSegments) || maxSubsampleSegments <= 0) {\n throw new Error('[MmtpContainerParser] maxSubsampleSegments must be a positive integer')\n }\n\n // Everything above only reads `config` \u2014 the full policy/window\n // combination is validated before this point, so it is now safe to\n // mutate this instance or an injected, caller-owned reassembler.\n this.#reassemblyPolicy = reassemblyPolicy\n if (config?.reassembler) {\n this.#reassembler = config.reassembler\n // An injected backend owns its existing transport policy unless this\n // parser was given an explicit policy/legacy timeout override.\n if (requestedMfuTimeout !== undefined) {\n this.#reassembler.timeoutMs = requestedMfuTimeout\n }\n } else {\n this.#reassembler = new MFUReassembler({\n timeoutMs: requestedMfuTimeout === undefined ? 1000 : requestedMfuTimeout,\n ...(config?.maxBufferedMfus === undefined ? {} : { maxBuffered: config.maxBufferedMfus }),\n })\n }\n this.#reorderWindow = normalizedReorderWindow\n this.#sampleCombinerOptions = {\n maxBuffered: maxPendingTimingSamples,\n // The parser resolves every timed sample's authored size from FT=1\n // before its data units reach the combiner, so \"no size yet\" always\n // means the size has not arrived -- never that the host declines to\n // supply one. Waiting is therefore correct: treating an offset-zero\n // data unit as a whole sample in that window would truncate a\n // partitioned sample instead of completing it.\n requireAuthoredSize: true,\n maxSegmentsPerSample: maxSubsampleSegments,\n }\n this.#defaultTrack = config?.defaultTrack ?? null\n if (config?.fecReleaseGate) this.setFecReleaseGate(config.fecReleaseGate)\n if (this.#defaultTrack) this.#validateReassemblyPolicy()\n if (config?.tracks) {\n for (const [id, info] of config.tracks) {\n this.#validateReassemblyPolicy()\n this.#tracks.set(id, info)\n }\n }\n }\n\n /** The MFU reassembler that buffers fragmented MFUs fed via feed().\n * Exposed so a co-operating FEC-recovery layer (MmtpRouter) feeds recovered\n * fragments into the SAME reassembler: a frame split between source-received\n * and FEC-recovered fragments must share one buffer to complete (BLO-8151).\n * Before this was shared, recovered video symbols reported \"0 emitted,\n * pending-reassembly=N\" because they landed in a separate instance. */\n get reassembler(): MfuReassemblerBackend {\n return this.#reassembler\n }\n\n /**\n * Subsample-combining counters (moqcast #37). `combinedSamples` counts\n * samples reassembled from two or more data units and `passthroughSamples`\n * those that arrived whole; the two are deliberately separate, so a\n * producer that silently stopped partitioning cannot hide behind a single\n * \"samples delivered\" total. This is the typed acceptance signal for\n * large-frame playback \u2014 never parse the console for it.\n */\n get sampleCombinerStats(): Readonly<SampleCombinerStats> {\n const total = { ...this.#retiredSampleCombinerStats }\n for (const combiner of this.#sampleCombiners.values()) {\n const stats = combiner.stats\n total.combinedSamples += stats.combinedSamples\n total.passthroughSamples += stats.passthroughSamples\n total.timedOutSamples += stats.timedOutSamples\n total.evictedSamples += stats.evictedSamples\n }\n return total\n }\n\n /**\n * Typed view of the ISO-BMFF timing-sample budget.\n *\n * This is the acceptance signal for the budget ratchet: `pending` walking\n * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,\n * and it is observable here rather than only as media silently stopping.\n * Per repo policy this is a producer-owned counter -- never infer budget\n * state by parsing logs.\n */\n get timingBudgetStats(): Readonly<MmtpTimingBudgetStats> {\n return {\n pending: this.#pendingTimingSamples,\n capacity: this.#maxPendingTimingSamples,\n reclaimed: this.#reclaimedTimingSamples,\n evicted: this.#evictedTimingSamples,\n rejectedMovieFragments: this.#rejectedMovieFragments,\n }\n }\n\n get reorderStats(): Readonly<MmtpReorderStats> {\n let bufferedFrames = this.#fecSequencer?.buffered ?? 0\n for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered\n return { ...this.#reorderStats, bufferedFrames }\n }\n\n /**\n * Install (or remove) the in-order release policy for FEC-protected\n * streams. Streams the gate claims are released by block resolution; all\n * others keep the frame-count reorder window.\n */\n setFecReleaseGate(gate: FecReleaseGate | null): void {\n this.#fecSequencer?.flush()\n this.#fecGate = gate\n this.#fecSequencer = gate\n ? new FecReleaseSequencer(\n gate,\n (data, meta) => this.#emitFrame(data, meta),\n (stat, count = 1) => {\n this.#reorderStats[stat] += count\n },\n )\n : null\n }\n\n /** Re-evaluate held gaps after FEC block state changed. */\n pokeFecRelease(packetId?: number, catalogTrackName?: string): void {\n if (!this.#fecSequencer) return\n this.#fecSequencer.poke(\n packetId === undefined ? undefined : this.#streamKey(packetId, catalogTrackName),\n )\n }\n\n /**\n * The FEC source of a stream restarted: stall the next release. Marks\n * only; follow with `pokeFecRelease` to release frames held behind it.\n */\n markFecDiscontinuity(packetId: number, catalogTrackName?: string): void {\n this.#fecSequencer?.markDiscontinuity(this.#streamKey(packetId, catalogTrackName))\n }\n\n /**\n * MPU and data-unit identity of one MMTP packet, parsed in place (no copy,\n * no reassembly). Null for non-MPU packets and packets that do not parse.\n * `header` is the packet's already-parsed MMTP header (parsePacket()), so\n * the header is not parsed a second time (BLO-36599).\n */\n static sourcePacketIdentity(packet: Uint8Array, header: MMTPHeader): SourcePacketIdentity | null {\n try {\n const extraction = extractMFUPayloadWithHeader(packet, header)\n if (!extraction) return null\n const identity: SourcePacketIdentity = {\n mpuSequenceNumber: extraction.mpu.mpuSequenceNumber,\n }\n if (extraction.mfuDuHeader) {\n identity.sampleNumber = extraction.mfuDuHeader.sampleNumber\n identity.movieFragmentSequenceNumber = extraction.mfuDuHeader.movieFragmentSequenceNumber\n identity.offset = extraction.mfuDuHeader.offset\n }\n return identity\n } catch {\n return null\n }\n }\n\n /**\n * Feed tallies for this parser. A fresh snapshot per call, not a live view,\n * so a caller can hold one and compare it against a later read.\n *\n * Survives dispose() \u2014 the counters are the parser's own state and are not\n * cleared by teardown, because a wedged receive path is usually read after\n * the fact.\n */\n get feedStats(): Readonly<MmtpParserFeedStats> {\n return {\n fedObjects: this.#fedObjects,\n outcomes: Object.fromEntries(this.#feedOutcomes),\n deferredOutcomes: Object.fromEntries(this.#deferredFeedOutcomes),\n }\n }\n\n /**\n * Outcome token of the most recent feed(), or null before the first call.\n *\n * Exposed alongside `lastFeedOutcomeCount` as two scalars rather than one\n * object because a wrapper reads them on every packet, and feedStats()\n * allocates a fresh snapshot per call.\n */\n get lastFeedOutcome(): MmtpFeedOutcomeKey | null {\n return this.#lastOutcome\n }\n\n /** How many times `lastFeedOutcome` has now been seen. 1 on its first\n * occurrence, which is what a caller logging once per novel outcome needs. */\n get lastFeedOutcomeCount(): number {\n return this.#lastOutcomeCount\n }\n\n /**\n * MFU fragments feed() handed to the reassembler, including rejected ones.\n * A plain scalar a per-packet caller can difference; reading the\n * reassembler's own stats is a wasm crossing on the Rust backend\n * (BLO-36599).\n */\n get reassemblerFragmentsFed(): number {\n return this.#reassemblerFragmentsFed\n }\n\n /** Data units the reassembler returned complete to feed(). */\n get reassemblerDataUnitsReturned(): number {\n return this.#reassemblerDataUnitsReturned\n }\n\n #countOutcome(token: MmtpFeedOutcomeKey): void {\n const count = (this.#feedOutcomes.get(token) ?? 0) + 1\n this.#feedOutcomes.set(token, count)\n this.#lastOutcome = token\n this.#lastOutcomeCount = count\n }\n\n #countDeferredOutcome(reason: MmtpFeedDropReason): void {\n this.#deferredFeedOutcomes.set(\n reason,\n (this.#deferredFeedOutcomes.get(reason) ?? 0) + 1,\n )\n }\n\n /**\n * Count a feed() drop and return null in one expression, so every early\n * return inside feed() states the reason it took instead of collapsing into\n * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.\n */\n #drop(reason: MmtpFeedDropReason): null {\n this.#countOutcome(`drop:${reason}`)\n return null\n }\n\n get reorderDiagnostics(): ReadonlyArray<MmtpReorderStreamDiagnostics> {\n const streams: MmtpReorderStreamDiagnostics[] = []\n for (const { packetId, sequencer } of this.#sequencers.values()) {\n for (const diagnostics of sequencer.diagnostics) streams.push({ packetId, ...diagnostics })\n }\n return streams\n }\n\n /**\n * Reclaim samples abandoned by the sample combiner's protocol deadline.\n *\n * This is deliberately driven by the parser's existing packet/lifecycle\n * cleanup path rather than by another timer. The reassembler timeout is the\n * same catalog/FEC-derived deadline that bounds each constituent MFU.\n */\n cleanupTimeouts(): void {\n const timeoutMs = this.#reassembler.timeoutMs\n if (timeoutMs === null) return\n for (const combiner of this.#sampleCombiners.values()) {\n combiner.cleanupTimeouts(timeoutMs)\n }\n }\n\n /**\n * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.\n * Call this before feed() when you need to extract FEC payload ID and feed\n * symbols to FECManager before MFU extraction.\n * Returns null for malformed packets.\n */\n parseHeader(packet: Uint8Array, options?: ParseHeaderOptions): PacketInfo | null {\n return this.parsePacket(packet, options)?.info ?? null\n }\n\n /**\n * parseHeader() that also keeps the parsed MMTP header, so a caller that\n * goes on to feedParsed() the same packet parses its header exactly once.\n * The MMTP header is parsed once here and the Source FEC Payload ID is read\n * from it; parseHeader() used to parse the header three times for an FEC\n * source packet, and feed() repeated all of it (BLO-36599).\n */\n parsePacket(packet: Uint8Array, options?: ParseHeaderOptions): ParsedMmtpPacket | null {\n try {\n const header = parseMMTPHeader(packet)\n const isRepair = header.packetType === PACKET_TYPE_REPAIR\n const skipFecPayloadId = options?.skipFecPayloadId === true\n const fecPayloadId =\n !skipFecPayloadId && !isRepair ? sourceFecPayloadIdOf(packet, header) : null\n return {\n info: {\n packetId: header.packetId,\n packetType: header.packetType,\n timestamp: header.timestamp,\n timestampUs: mmtpTimestampToMicros(header.timestamp),\n sequenceNumber: header.sequenceNumber,\n rapFlag: header.rapFlag,\n fecType: header.fecType,\n fecPayloadId,\n isRepair,\n },\n header,\n skipFecPayloadId,\n }\n } catch {\n return null\n }\n }\n\n /** Feed a complete MMTP packet. For two-phase use, call parseHeader() first. */\n feed(packet: Uint8Array, options?: ParseHeaderOptions): MmtpParserRecord | null {\n return this.#feedCounted(packet, options, undefined)\n }\n\n /**\n * feed() for a packet this caller already ran through parsePacket(): the\n * header parse is reused instead of repeated. `parsed` must come from\n * parsePacket() of this same, unmodified packet. If it was resolved under a\n * different skipFecPayloadId option, the packet is parsed again.\n */\n feedParsed(\n packet: Uint8Array,\n parsed: ParsedMmtpPacket,\n options?: ParseHeaderOptions,\n ): MmtpParserRecord | null {\n return this.#feedCounted(packet, options, parsed)\n }\n\n #feedCounted(\n packet: Uint8Array,\n options: ParseHeaderOptions | undefined,\n parsed: ParsedMmtpPacket | undefined,\n ): MmtpParserRecord | null {\n this.#fedObjects += 1\n let record: MmtpParserRecord | null\n try {\n record = this.#feed(packet, options, parsed)\n } catch (error) {\n // Count before rethrowing: a throw is an outcome, and leaving it\n // uncounted would silently break the sum-to-fedObjects invariant that\n // makes this tally readable.\n this.#countOutcome('drop:threw')\n throw error\n }\n // Drops are counted at their own return sites via #drop(), which is what\n // preserves the reason. Only successful records are counted here.\n if (record) this.#countOutcome(record.kind)\n return record\n }\n\n #feed(\n packet: Uint8Array,\n options: ParseHeaderOptions | undefined,\n preParsed: ParsedMmtpPacket | undefined,\n ): MmtpParserRecord | null {\n if (this.#disposed) return this.#drop('disposed')\n\n this.cleanupTimeouts()\n\n const parsed =\n preParsed !== undefined &&\n preParsed.skipFecPayloadId === (options?.skipFecPayloadId === true)\n ? preParsed\n : this.parsePacket(packet, options)\n if (!parsed) return this.#drop('header-parse-failed')\n const info = parsed.info\n\n if (info.packetType !== PACKET_TYPE_MPU) {\n return {\n kind: info.isRepair ? 'repair' : 'non-media',\n packet: info,\n byteLength: packet.byteLength,\n }\n }\n\n // \u2500\u2500 FEC source-symbol exposure \u2500\u2500\n // Fire onSourceSymbol BEFORE MFU extraction so the consumer-side FEC\n // pipeline (e.g. FecWorkerClient.feedSource) starts as early as possible.\n // Source-only: parseHeader already gates fecPayloadId on !isRepair.\n if (info.fecPayloadId !== null && this.#sourceSymbolCb) {\n // Strip the 4-byte fec_payload_id trailer per ISO 23008-1 \u00A7C.5.2.\n // Symbol-size zero-padding is the consumer's responsibility \u2014 FEC\n // symbol size is a FEC-config concern, not a parser concern.\n const rawSymbol = packet.subarray(0, packet.length - 4)\n const altaTrailer = extractAltaTrailer(packet)\n const alta = altaTrailer\n ? { auth: altaTrailer.auth, payloadEnd: altaTrailer.signedEnd }\n : undefined\n try {\n this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol, alta)\n } catch {\n // Source-symbol consumer threw \u2014 never block MFU extraction on\n // FEC-pipeline errors. The frame path stays viable; the consumer\n // is responsible for its own error surfacing.\n }\n }\n\n const extraction = extractMFUPayloadWithHeader(packet, parsed.header, {\n skipFecId: options?.skipFecPayloadId,\n })\n if (!extraction) return this.#drop('mfu-extract-failed')\n\n const { mpu, fragmentType, data, mfuDuHeader } = extraction\n if (mpu.timedFlag !== 1) return this.#drop('untimed-mpu')\n const streamKey = this.#streamKey(info.packetId, options?.catalogTrackName)\n\n if (fragmentType === 0) {\n if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)\n return this.#drop('init-unexpected-fragmentation')\n // ISO MMTP MPU metadata may carry an `mmpu` box between the ftyp and\n // moov boxes. That box is valid MMTP metadata but is not a legal\n // top-level MSE initialization box. Normalize at the parser boundary so\n // every container consumer (including MSE and rendition handoff paths)\n // receives append-safe ftyp+moov bytes rather than having to remember\n // this wire-format detail independently.\n const normalizedInit = normalizeMmtpInitSegment(data)\n if (!normalizedInit) return this.#drop('init-normalize-failed')\n const resolver = this.#timingResolver(streamKey, info.packetId, true)\n if (!resolver?.addInitialization(normalizedInit)) return this.#drop('init-timing-refused')\n this.#initCb?.(normalizedInit, info.packetId, options?.catalogTrackName)\n return {\n kind: 'init',\n packet: info,\n data: normalizedInit,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentationIndicator: mpu.fragmentationIndicator,\n fragmentCounter: mpu.fragmentCounter,\n }\n }\n\n if (fragmentType === 1) {\n if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)\n return this.#drop('fragment-unexpected-fragmentation')\n const resolver = this.#timingResolver(streamKey, info.packetId, false)\n if (!resolver) return this.#drop('fragment-no-resolver')\n const pendingBefore = resolver.pendingSampleCount\n const evictedBefore = resolver.evictedSampleCount\n const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples\n const admitted = resolver.addMovieFragment(mpu.mpuSequenceNumber, data, remaining)\n // Sync on BOTH paths: the resolver can displace stale timing and still\n // refuse the fragment in hand, and a global count that missed those\n // freed slots would keep refusing on a budget that is no longer full.\n this.#pendingTimingSamples += resolver.pendingSampleCount - pendingBefore\n this.#evictedTimingSamples += resolver.evictedSampleCount - evictedBefore\n if (!admitted) {\n if (resolver.lastMovieFragmentRejection === 'budget') {\n this.#rejectedMovieFragments++\n }\n return this.#drop('fragment-timing-refused')\n }\n return {\n kind: 'fragment',\n packet: info,\n data,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentationIndicator: mpu.fragmentationIndicator,\n fragmentCounter: mpu.fragmentCounter,\n }\n }\n if (fragmentType !== 2) return this.#drop('unknown-fragment-type')\n\n const resolver = this.#timingResolver(streamKey, info.packetId, false)\n if (!resolver) return this.#drop('mfu-no-resolver')\n if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)\n return this.#drop('mfu-empty-payload')\n if (mpu.fragmentationIndicator === 0 || mpu.fragmentationIndicator === 1) {\n if (!mfuDuHeader || mfuDuHeader.movieFragmentSequenceNumber === 0 ||\n mfuDuHeader.sampleNumber === 0) {\n return this.#drop('mfu-du-header-missing')\n }\n const headTiming = resolver.sampleTiming(\n mpu.mpuSequenceNumber,\n mfuDuHeader.movieFragmentSequenceNumber,\n mfuDuHeader.sampleNumber,\n )\n if (!headTiming) return this.#drop('mfu-sample-timing-missing')\n // A data unit's authored base offset is its position within the sample\n // (moqcast #37): 0 for a whole-sample DU, nonzero for one subsample DU\n // among siblings. Sizes below are therefore relative to that base, not\n // to the sample's start -- comparing a subsample DU against the whole\n // sample's size is what dropped every partitioned 4K/8K frame.\n const offset = mfuDuHeader.offset\n if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)\n return this.#drop('mfu-offset-out-of-range')\n const remaining = headTiming.size - offset\n // FI=0 carries its data unit whole, in a single payload. Only a\n // partitioned sample's FINAL data unit can be shorter than a full data\n // unit -- every earlier one spans exactly 256 payloads and so is always\n // fragmented -- which makes a whole-carried DU exactly the bytes left\n // from its base. At offset 0 this is the pre-amendment check unchanged.\n if (mpu.fragmentationIndicator === 0 && data.byteLength !== remaining)\n return this.#drop('mfu-size-mismatch')\n if (mpu.fragmentationIndicator === 1 && data.byteLength >= remaining)\n return this.#drop('mfu-size-mismatch')\n\n // Publish the authored size before this data unit can complete, so the\n // combiner never has to guess whether an offset-zero DU is a whole\n // sample. Registration can complete a previously buffered sample; its\n // refusal is a side effect of this feed, not this packet's own outcome,\n // so expose it in deferredOutcomes without double-counting outcomes.\n const readyOnRegister = this.#sampleCombinerFor(streamKey).registerAuthoredSize(\n options?.catalogTrackName,\n mpu.mpuSequenceNumber,\n mfuDuHeader.movieFragmentSequenceNumber,\n mfuDuHeader.sampleNumber,\n headTiming.size,\n )\n if (readyOnRegister) {\n const deferred = this.#emitCombinedSample(\n readyOnRegister,\n info,\n resolver,\n options?.recovered === true,\n options?.fecSbn,\n )\n if (deferred.record === undefined) this.#countDeferredOutcome(deferred.reason)\n }\n }\n\n let assembled: ReassembledMFU | null\n this.#reassemblerFragmentsFed++\n try {\n assembled = this.#reassembler.addFragment({\n fragmentationIndicator: mpu.fragmentationIndicator,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentCounter: mpu.fragmentCounter,\n data,\n timestamp: info.timestamp,\n rapFlag: info.rapFlag,\n priority: mfuDuHeader?.priority,\n sampleNumber: mfuDuHeader?.sampleNumber,\n movieFragmentSequenceNumber: mfuDuHeader?.movieFragmentSequenceNumber,\n sampleOffset: mfuDuHeader?.offset,\n packetSequenceNumber: info.sequenceNumber,\n recovered: options?.recovered === true,\n source: options?.source,\n deliveryProvenance: options?.deliveryProvenance,\n catalogTrackName: options?.catalogTrackName,\n packetId: info.packetId,\n })\n } catch (error) {\n if (!isMfuReassemblyError(error)) throw error\n console.warn(\n `[MmtpContainerParser] rejected MFU fragment: code=${error.code} ` +\n `mpu=${mpu.mpuSequenceNumber} fi=${mpu.fragmentationIndicator} ` +\n `counter=${mpu.fragmentCounter}`,\n )\n return {\n kind: 'rejected',\n packet: info,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentationIndicator: mpu.fragmentationIndicator,\n fragmentCounter: mpu.fragmentCounter,\n error: { code: error.code, message: error.message },\n }\n }\n\n if (!assembled) {\n return {\n kind: 'pending',\n packet: info,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentationIndicator: mpu.fragmentationIndicator,\n fragmentCounter: mpu.fragmentCounter,\n }\n }\n this.#reassemblerDataUnitsReturned++\n\n const movieFragmentSequenceNumber = assembled.movieFragmentSequenceNumber\n const sampleNumber = assembled.sampleNumber\n if (movieFragmentSequenceNumber === undefined || sampleNumber === undefined)\n return this.#drop('assembled-identity-missing')\n // Resolve authored timing BEFORE the combiner sees this data unit. An\n // assembled data unit whose sample identity has no authored timing is not\n // a sample this stream declared, so it must be dropped outright -- letting\n // it buffer would occupy a combiner slot and could evict a legitimate\n // partitioned sample waiting on a sibling.\n if (!resolver.sampleTiming(\n assembled.mpuSequenceNumber,\n movieFragmentSequenceNumber,\n sampleNumber,\n )) return this.#drop('assembled-timing-missing')\n if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)\n return this.#drop('assembled-mpu-mismatch')\n\n // One reassembled data unit is not necessarily one whole sample. A\n // partitioned sample completes only once every sibling data unit has\n // arrived and they are byte-adjacent from zero to the authored size; an\n // unpartitioned sample passes straight through with no buffering.\n let combined: CombinedSample | null\n try {\n combined = this.#sampleCombinerFor(streamKey).addMfu(assembled)\n } catch (error) {\n if (!(error instanceof SampleCombineError)) throw error\n console.warn(\n `[MmtpContainerParser] rejected subsample data unit: code=${error.code} ` +\n `mpu=${assembled.mpuSequenceNumber} sample=${sampleNumber} ` +\n `offset=${assembled.sampleOffset ?? 0}`,\n )\n return {\n kind: 'rejected',\n packet: info,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentationIndicator: mpu.fragmentationIndicator,\n fragmentCounter: mpu.fragmentCounter,\n error: { code: error.code, message: error.message },\n }\n }\n if (!combined) {\n return {\n kind: 'pending',\n packet: info,\n mpuSequenceNumber: mpu.mpuSequenceNumber,\n fragmentationIndicator: mpu.fragmentationIndicator,\n fragmentCounter: mpu.fragmentCounter,\n }\n }\n\n const outcome = this.#emitCombinedSample(\n combined,\n info,\n resolver,\n options?.recovered === true,\n options?.fecSbn,\n )\n if (outcome.record !== undefined) return outcome.record\n return this.#drop(outcome.reason)\n }\n\n /**\n * Deliver one combined sample: resolve its authored timing, build frame\n * metadata, retire the timing entry, and route it. Shared by the ordinary\n * completion path and by the rarer completion that falls out of registering\n * an authored size for data units that arrived before it.\n *\n * Reports a refusal as a reason rather than counting it, because the two\n * call sites owe different accounting. On `#feed()`'s tail return the\n * refusal *is* that feed()'s outcome and must be attributed; on the\n * register-completion path it belongs to an earlier sample while this\n * packet's own fragment continues to its own outcome, so counting it there\n * would push `outcomes` past `fedObjects` \u2014 the very invariant the\n * attribution exists to keep readable. Leaving the choice at the call site\n * is what keeps both true.\n */\n #emitCombinedSample(\n combined: CombinedSample,\n info: PacketInfo,\n resolver: IsoBmffTimingResolver,\n recovered: boolean,\n fecSbn: number | undefined,\n ): CombinedSampleOutcome {\n const timing = resolver.sampleTiming(\n combined.mpuSequenceNumber,\n combined.movieFragmentSequenceNumber,\n combined.sampleNumber,\n )\n if (!timing) return { reason: 'combined-timing-missing' }\n // The combiner already completes against the registered authored size;\n // re-checking here keeps the unpartitioned passthrough path fail-closed\n // on the same invariant rather than trusting it by construction.\n if (combined.data.byteLength !== timing.size) return { reason: 'combined-size-mismatch' }\n\n const meta = this.#buildFrameMeta(\n combined,\n info.packetId,\n info.sequenceNumber,\n timing,\n recovered,\n )\n if (!meta) return { reason: 'combined-meta-build-failed' }\n if (fecSbn !== undefined) meta.fecSbn = fecSbn\n if (!resolver.consumeSample(\n combined.mpuSequenceNumber,\n combined.movieFragmentSequenceNumber,\n combined.sampleNumber,\n timing,\n )) return { reason: 'combined-timing-consume-refused' }\n this.#pendingTimingSamples--\n this.routeFrame(combined.data, meta)\n return {\n record: {\n kind: 'frame',\n packet: info,\n data: combined.data,\n meta,\n mpuSequenceNumber: combined.mpuSequenceNumber,\n fragmentCount: combined.fragmentCount,\n rapFlag: combined.rapFlag,\n ...(combined.priority === undefined ? {} : { priority: combined.priority }),\n },\n }\n }\n\n onInit(cb: InitCallback): void {\n this.#initCb = cb\n }\n\n onFrame(cb: FrameCallback): void {\n this.#frameCb = cb\n }\n\n /** Register a per-packet FEC source-symbol callback. Fires for each MMTP\n * source MPU packet that carries a Source FEC Payload ID (ISO 23008-1 \u00A7C.5.2).\n *\n * Consumer responsibilities:\n * - Zero-pad `rawSymbol` to the FEC `symbolSize` if shorter (FEC config is\n * out-of-band \u2014 typically from the CMSF catalog's `fec.symbolSize`).\n * - Decide oversized handling (rawSymbol.length > symbolSize is not FEC-\n * decodable; consumer typically skips that block's source-feed).\n * - Look up the right FEC consumer (e.g. FecWorkerClient) by packetId.\n *\n * Designed for spec-clean reuse: Shaka, upstream moqtail, or any consumer\n * that uses MmtpContainerParser can wire FEC source delivery without\n * pulling in MulticastManager/MmtpRouter/FECManager. */\n onSourceSymbol(cb: SourceSymbolCallback): void {\n this.#sourceSymbolCb = cb\n }\n\n onTrackFrame(packetId: number, cb: FrameCallback): void {\n this.#trackFrameCbs.set(packetId, cb)\n }\n\n setTrack(packetId: number, info: TrackInfo): void {\n this.#validateReassemblyPolicy()\n for (const [key, entry] of this.#sequencers) {\n if (entry.packetId !== packetId) continue\n entry.sequencer.flush()\n this.#sequencers.delete(key)\n }\n this.#fecSequencer?.flushPacket(packetId)\n for (const [key, state] of this.#timingStreams) {\n if (state.packetId === packetId) this.#dropTimingStream(key)\n }\n for (const key of [...this.#sampleCombiners.keys()]) {\n if ((JSON.parse(key) as [number, string | null])[0] === packetId) {\n this.#dropSampleCombiner(key)\n }\n }\n for (const [key, gatedPacketId] of this.#reliableMoqStartupGate) {\n if (gatedPacketId === packetId) this.#reliableMoqStartupGate.delete(key)\n }\n this.#tracks.set(packetId, info)\n }\n\n /** Drop one physical stream's ordering and MFU state for retained replay. */\n resetTrack(packetId: number, catalogTrackName: string): void {\n if (!catalogTrackName) {\n throw new Error('[MmtpContainerParser] catalogTrackName is required for track reset')\n }\n for (const [key, entry] of this.#sequencers) {\n if (key !== this.#streamKey(packetId, catalogTrackName)) continue\n entry.sequencer.discard()\n this.#sequencers.delete(key)\n }\n const streamKey = this.#streamKey(packetId, catalogTrackName)\n this.#fecSequencer?.discardStream(streamKey)\n this.#dropTimingStream(streamKey)\n this.#reliableMoqStartupGate.delete(streamKey)\n this.#reassembler.resetStream(catalogTrackName)\n // Drop half-combined samples too: a partitioned sample whose siblings\n // straddle the reset would otherwise complete against a stale authored\n // size and hand the decoder bytes from two different publisher epochs.\n this.#dropSampleCombiner(streamKey)\n }\n\n /**\n * Retire one packet ID, drop-only: discard every stream of it (reorder and\n * FEC release buffers, authored timing, half-combined samples, startup\n * gates) and its track registration, and reset the MFU reassembler for each\n * catalog stream it carried. Nothing buffered is emitted, as on live\n * dispose. `catalogTrackNames` names the streams the caller routed on this\n * packet ID; the parser adds any it holds state for itself. Reassembly\n * resets are catalog-scoped, as for resetTrack: a stream that never carried\n * a catalog name keeps its reassembler buffers until they time out or are\n * evicted.\n */\n removeTrack(packetId: number, catalogTrackNames: Iterable<string>): void {\n const names = new Set<string>(catalogTrackNames)\n for (const [key, entry] of [...this.#sequencers]) {\n if (entry.packetId !== packetId) continue\n entry.sequencer.discard()\n this.#sequencers.delete(key)\n }\n this.#fecSequencer?.discardPacket(packetId)\n for (const [key, state] of [...this.#timingStreams]) {\n if (state.packetId !== packetId) continue\n const name = (JSON.parse(key) as [number, string | null])[1]\n if (name !== null) names.add(name)\n this.#dropTimingStream(key)\n }\n for (const key of [...this.#sampleCombiners.keys()]) {\n const [keyPacketId, name] = JSON.parse(key) as [number, string | null]\n if (keyPacketId !== packetId) continue\n if (name !== null) names.add(name)\n this.#dropSampleCombiner(key)\n }\n for (const [key, gatedPacketId] of [...this.#reliableMoqStartupGate]) {\n if (gatedPacketId === packetId) this.#reliableMoqStartupGate.delete(key)\n }\n for (const name of names) this.#reassembler.resetStream(name)\n this.#tracks.delete(packetId)\n this.#trackFrameCbs.delete(packetId)\n }\n\n setMfuTimeoutMs(ms: number | null): void {\n if (ms !== null && ms <= 0) throw new Error('[MmtpContainerParser] mfuTimeoutMs must be > 0')\n this.#reassembler.timeoutMs = ms\n }\n\n setReassemblyPolicy(policy: MfuReassemblyPolicy): void {\n const timeoutMs = mfuReassemblyTimeoutMs(policy)\n this.#validateReassemblyPolicy(policy)\n this.#flushSequencers()\n this.#reassemblyPolicy = policy\n this.#reliableMoqStartupGate.clear()\n this.setMfuTimeoutMs(timeoutMs)\n }\n\n setReorderWindow(windowSize: number): void {\n if (!Number.isFinite(windowSize) || windowSize < 0) {\n throw new Error('[MmtpContainerParser] reorderWindow must be a finite number >= 0')\n }\n const nextWindow = Math.ceil(windowSize)\n this.#validateReassemblyPolicy(this.#reassemblyPolicy, nextWindow)\n this.#flushSequencers()\n this.#reorderWindow = nextWindow\n if (this.#reorderWindow <= 0) this.#sequencers.clear()\n }\n\n /** Route an already-assembled frame through the same reorder/callback path\n * used by source packets. FEC recovery uses this to merge recovered frames\n * with direct source frames before the decoder sees them. */\n routeFrame(data: Uint8Array, meta: FrameMeta): void {\n const seq = meta.packetSequenceNumber\n if (this.#fecSequencer && this.#fecGate?.gates(meta.packetId, meta.catalogTrackName)) {\n this.#fecSequencer.push(\n this.#streamKey(meta.packetId, meta.catalogTrackName),\n data,\n meta,\n seq !== undefined && Number.isFinite(seq) ? seq : 0,\n )\n return\n }\n const sequencer = this.#sequencerFor(meta.packetId, meta.trackType, meta.catalogTrackName)\n if (sequencer && seq !== undefined && Number.isFinite(seq)) {\n sequencer.push(data, meta, seq)\n return\n }\n if (this.#reassemblyPolicy?.transport === 'reliable-moq' &&\n meta.trackType === 'video' &&\n !this.#passReliableMoqStartupGate(meta)) {\n return\n }\n this.#emitFrame(data, meta)\n }\n\n /**\n * Claim and return the authored timing for a recovered sample. Recovery does\n * not pass through the ordinary `feed()` completion path, so it must retire\n * the same bounded resolver entry once the router accepts the recovered\n * sample. A missing entry is a fail-closed signal: callers must not replace\n * it with an MMTP send timestamp or cadence guess.\n */\n consumeAuthoredTimingFor(\n packetId: number,\n mpuSequenceNumber: number,\n movieFragmentSequenceNumber: number | undefined,\n sampleNumber: number | undefined,\n catalogTrackName?: string,\n ): AuthoredTiming | null {\n if (movieFragmentSequenceNumber === undefined || sampleNumber === undefined) return null\n const resolver = this.#timingResolver(\n this.#streamKey(packetId, catalogTrackName),\n packetId,\n false,\n )\n const timing = resolver?.sampleTiming(\n mpuSequenceNumber,\n movieFragmentSequenceNumber,\n sampleNumber,\n )\n if (!timing || !resolver || !resolver.consumeSample(\n mpuSequenceNumber,\n movieFragmentSequenceNumber,\n sampleNumber,\n timing,\n )) return null\n this.#pendingTimingSamples--\n if (this.#pendingTimingSamples < 0) {\n throw new Error('[MmtpContainerParser] pending timing sample accounting underflow')\n }\n return {\n decodeTime: timing.decodeTime,\n presentationTime: timing.presentationTime,\n durationTicks: timing.duration,\n mediaTimescale: timing.timescale,\n }\n }\n\n /** Order-independent reliable-moq startup gate: discard delta frames for a\n * stream until its first RAP is observed, without buffering/reordering. */\n #passReliableMoqStartupGate(meta: FrameMeta): boolean {\n const streamKey = this.#streamKey(meta.packetId, meta.catalogTrackName)\n if (meta.sourceDiscontinuity) this.#reliableMoqStartupGate.delete(streamKey)\n if (this.#reliableMoqStartupGate.has(streamKey)) return true\n if (!meta.keyframe) {\n this.#reorderStats.droppedBeforeStartupKeyframe++\n return false\n }\n this.#reliableMoqStartupGate.set(streamKey, meta.packetId)\n return true\n }\n\n /** Emit all ordered frames currently buffered by the parser. Finite-stream\n * consumers may call this before dispose(); live cancellation should not. */\n flush(): void {\n if (this.#disposed) return\n this.#flushSequencers()\n this.#fecSequencer?.flush()\n }\n\n dispose(): void {\n this.#disposed = true\n for (const { sequencer } of this.#sequencers.values()) sequencer.discard()\n this.#sequencers.clear()\n this.#fecSequencer?.discard()\n this.#timingStreams.clear()\n this.#pendingTimingSamples = 0\n this.#reliableMoqStartupGate.clear()\n this.#reassembler.reset()\n this.#frameCb = null\n this.#initCb = null\n this.#trackFrameCbs.clear()\n }\n\n // \u2500\u2500 Private \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 #timingResolver(\n streamKey: string,\n packetId: number,\n create: boolean,\n ): IsoBmffTimingResolver | null {\n const existing = this.#timingStreams.get(streamKey)\n if (existing) return existing.resolver\n if (!create) return null\n const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples)\n this.#timingStreams.set(streamKey, { packetId, resolver })\n return resolver\n }\n\n #dropTimingStream(streamKey: string): void {\n const state = this.#timingStreams.get(streamKey)\n if (!state) return\n this.#timingStreams.delete(streamKey)\n this.#pendingTimingSamples -= state.resolver.pendingSampleCount\n if (this.#pendingTimingSamples < 0) {\n throw new Error('[MmtpContainerParser] pending timing sample accounting underflow')\n }\n }\n\n #validateReassemblyPolicy(\n policy: MfuReassemblyPolicy | null = this.#reassemblyPolicy,\n reorderWindow = this.#reorderWindow,\n ): void {\n if (!policy) return\n mmtpFrameReorderWindowFrames(policy, reorderWindow)\n }\n\n #buildFrameMeta(\n assembled: CombinedSample,\n packetId: number,\n seq: number,\n timing: IsoBmffSampleTiming,\n recovered = false,\n ): FrameMeta | null {\n const { data, rapFlag, priority } = assembled\n\n if (isFmp4Box(data)) return null\n const presentationTimestamp = mediaTicksToMicroseconds(\n timing.presentationTime,\n timing.timescale,\n )\n const decodeTimestamp = mediaTicksToMicroseconds(timing.decodeTime, timing.timescale)\n const duration = mediaTicksToMicroseconds(BigInt(timing.duration), timing.timescale)\n if (presentationTimestamp === null || decodeTimestamp === null || duration === null ||\n duration <= 0) {\n return null\n }\n\n let track = this.#tracks.get(packetId)\n if (!track && this.#defaultTrack) {\n track = this.#defaultTrack\n this.#tracks.set(packetId, track)\n }\n const codec = track?.codec ?? ''\n\n const keyframe = MmtpContainerParser.isKeyframe(data, isMfuKeyframeMetadata(rapFlag, priority), codec)\n\n const meta: FrameMeta = {\n timestamp: presentationTimestamp,\n decodeTimestamp,\n duration,\n decodeTime: timing.decodeTime,\n presentationTime: timing.presentationTime,\n durationTicks: timing.duration,\n mediaTimescale: timing.timescale,\n authoredTiming: {\n decodeTime: timing.decodeTime,\n presentationTime: timing.presentationTime,\n durationTicks: timing.duration,\n mediaTimescale: timing.timescale,\n },\n keyframe,\n packetId,\n trackType: track?.type ?? null,\n packetSequenceNumber: seq,\n ...(assembled.packetSequenceNumbers === undefined\n ? {}\n : { packetSequenceNumbers: assembled.packetSequenceNumbers }),\n ...(assembled.repairedPacketSequenceNumbers === undefined\n ? {}\n : { repairedPacketSequenceNumbers: assembled.repairedPacketSequenceNumbers }),\n ...(assembled.catalogTrackName === undefined\n ? {}\n : { catalogTrackName: assembled.catalogTrackName }),\n ...(assembled.mmtpTimestamp === undefined\n ? {}\n : { mmtpTimestamp: assembled.mmtpTimestamp }),\n mpuSequenceNumber: assembled.mpuSequenceNumber,\n ...(assembled.movieFragmentSequenceNumber === undefined\n ? {}\n : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber }),\n ...(assembled.sampleNumber === undefined ? {} : { sampleNumber: assembled.sampleNumber }),\n fragmentCount: assembled.fragmentCount,\n rapFlag,\n ...(priority === undefined ? {} : { priority }),\n ...(assembled.source === undefined ? {} : { source: assembled.source }),\n deliveryProvenance: assembled.deliveryProvenance,\n }\n if (recovered || (assembled.repairedPacketSequenceNumbers?.length ?? 0) > 0) {\n meta.recovered = true\n }\n\n return meta\n }\n\n #sequencerFor(\n packetId: number,\n _trackType: FrameMeta['trackType'],\n catalogTrackName?: string,\n ): FrameSequencer | null {\n const windowSize = this.#reassemblyPolicy\n ? mmtpFrameReorderWindowFrames(this.#reassemblyPolicy, this.#reorderWindow)\n : this.#reorderWindow\n if (windowSize <= 0) return null\n const streamKey = this.#streamKey(packetId, catalogTrackName)\n let sequencer = this.#sequencers.get(streamKey)?.sequencer\n if (!sequencer) {\n sequencer = new FrameSequencer(windowSize, (data, meta) => {\n this.#emitFrame(data, meta)\n }, (stat, count = 1) => {\n this.#reorderStats[stat] += count\n })\n this.#sequencers.set(streamKey, { packetId, sequencer })\n }\n return sequencer\n }\n\n #flushSequencers(): void {\n for (const { sequencer } of this.#sequencers.values()) sequencer.flush()\n this.#sequencers.clear()\n }\n\n /** Authored presentation timestamp of the last emitted frame, in microseconds. */\n lastFrameTimestamp: number | undefined = undefined\n\n #emitFrame(data: Uint8Array, meta: FrameMeta): void {\n this.lastFrameTimestamp = meta.timestamp\n const trackCb = this.#trackFrameCbs.get(meta.packetId)\n trackCb?.(data, meta)\n this.#frameCb?.(data, meta)\n }\n\n // \u2500\u2500 Static utilities \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 static isKeyframe(data: Uint8Array, rapFlag: boolean, codec = ''): boolean {\n const payloadKeyframe = MmtpContainerParser.#scanForKeyframe(data, codec)\n if (payloadKeyframe !== undefined) return payloadKeyframe\n return rapFlag\n }\n\n static #scanForKeyframe(data: Uint8Array, codec: string): boolean | undefined {\n const c = codec.toLowerCase()\n if (data.length === 0) return undefined\n\n if (c.startsWith('av01')) {\n return scanAv1ObusForKeyframe(data)\n }\n\n if (c.startsWith('vp09') || c.startsWith('vp8')) {\n return (data[0]! & 0x04) === 0\n }\n\n const isHevc = c.startsWith('hev1') || c.startsWith('hvc1')\n if (isHevc) {\n if (data.length < 5) return undefined\n if (startsWithAnnexB(data)) {\n return MmtpContainerParser.#scanAnnexBForKeyframe(data, true)\n }\n return MmtpContainerParser.#scanLengthPrefixedHevcForKeyframe(data)\n }\n\n if (c === '' || c.startsWith('avc')) {\n return classifyH264Keyframe(data, { allowPartialAvcc: true })\n }\n\n return undefined\n }\n\n static #scanLengthPrefixedHevcForKeyframe(data: Uint8Array): boolean | undefined {\n let sawNal = false\n let offset = 0\n while (offset + 4 < data.length) {\n const nalLen =\n (data[offset]! << 24) |\n (data[offset + 1]! << 16) |\n (data[offset + 2]! << 8) |\n data[offset + 3]!\n offset += 4\n if (nalLen <= 0) return sawNal ? false : undefined\n // The router's sync probe may see only the first fragment of a large\n // length-prefixed NAL. The length can exceed this packet, but the NAL\n // header is still enough to classify IRAP (H.265 Table 7-1, 16..=23)\n // and open the sync gate.\n if (offset >= data.length) return sawNal ? false : undefined\n sawNal = true\n const hevcType = (data[offset]! >> 1) & 0x3f\n if (isHevcIrapNalUnitType(hevcType)) return true\n if (offset + nalLen > data.length) break\n offset += nalLen\n }\n return sawNal ? false : undefined\n }\n\n static #scanAnnexBForKeyframe(data: Uint8Array, isHevc: boolean): boolean | undefined {\n let offset = 0\n let sawNal = false\n while (offset < data.length) {\n const start = findAnnexBStart(data, offset)\n if (!start) return sawNal ? false : undefined\n const headerOffset = start.offset + start.length\n if (headerOffset >= data.length) return sawNal ? false : undefined\n sawNal = true\n if (isHevc) {\n if (headerOffset + 1 >= data.length) return sawNal ? false : undefined\n const hevcType = (data[headerOffset]! >> 1) & 0x3f\n if (isHevcIrapNalUnitType(hevcType)) return true\n } else {\n const nalType = data[headerOffset]! & 0x1f\n if (nalType === 5) return true\n }\n offset = headerOffset + 1\n }\n return sawNal ? false : undefined\n }\n}\n\nfunction scanAv1ObusForKeyframe(data: Uint8Array): boolean | undefined {\n let offset = 0\n let sawSequenceHeader = false\n let sawFrame = false\n\n while (offset < data.length) {\n const obu = readAv1Obu(data, offset)\n if (!obu) return sawFrame ? false : undefined\n offset = obu.nextOffset\n\n if (obu.type === 1) {\n sawSequenceHeader = true\n continue\n }\n if (obu.type !== 3 && obu.type !== 6) continue\n\n sawFrame = true\n if (!sawSequenceHeader) {\n continue\n }\n\n const keyframe = readAv1FrameHeaderKeyframe(data.subarray(obu.payloadOffset, obu.payloadEnd))\n if (keyframe !== undefined) return keyframe\n }\n\n return sawFrame ? false : undefined\n}\n\nfunction readAv1Obu(\n data: Uint8Array,\n offset: number,\n): { type: number; payloadOffset: number; payloadEnd: number; nextOffset: number } | null {\n if (offset >= data.length) return null\n const header = data[offset]!\n if ((header & 0x80) !== 0 || (header & 0x01) !== 0) return null\n\n const type = (header >> 3) & 0x0f\n const extensionFlag = (header & 0x04) !== 0\n const hasSizeField = (header & 0x02) !== 0\n let cursor = offset + 1\n if (extensionFlag) cursor += 1\n if (cursor > data.length) return null\n\n let payloadSize = data.length - cursor\n if (hasSizeField) {\n const leb = readLeb128(data, cursor)\n if (!leb) return null\n payloadSize = leb.value\n cursor = leb.nextOffset\n }\n\n const payloadEnd = cursor + payloadSize\n if (payloadEnd > data.length) return null\n return { type, payloadOffset: cursor, payloadEnd, nextOffset: payloadEnd }\n}\n\nfunction readLeb128(data: Uint8Array, offset: number): { value: number; nextOffset: number } | null {\n let value = 0\n for (let i = 0; i < 8; i++) {\n if (offset + i >= data.length) return null\n const byte = data[offset + i]!\n value += (byte & 0x7f) * (2 ** (i * 7))\n if ((byte & 0x80) === 0) return { value, nextOffset: offset + i + 1 }\n }\n return null\n}\n\nfunction readAv1FrameHeaderKeyframe(payload: Uint8Array): boolean | undefined {\n if (payload.length === 0) return undefined\n const first = payload[0]!\n const showExistingFrame = (first & 0x80) !== 0\n if (showExistingFrame) return false\n const frameType = (first >> 5) & 0x03\n return frameType === 0\n}\n\nfunction startsWithAnnexB(data: Uint8Array): boolean {\n return (\n (data.length >= 4 && data[0] === 0 && data[1] === 0 && data[2] === 1) ||\n (data.length >= 5 && data[0] === 0 && data[1] === 0 && data[2] === 0 && data[3] === 1)\n )\n}\n\nfunction findAnnexBStart(data: Uint8Array, offset: number): { offset: number; length: 3 | 4 } | null {\n for (let i = offset; i + 3 <= data.length; i++) {\n if (data[i] !== 0 || data[i + 1] !== 0) continue\n if (data[i + 2] === 1) return { offset: i, length: 3 }\n if (i + 3 < data.length && data[i + 2] === 0 && data[i + 3] === 1) {\n return { offset: i, length: 4 }\n }\n }\n return null\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 | 'rap-spacing-mismatch'\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 }\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 if (!isPositiveFinite(input.framerate)) {\n return { trackKind: 'video', mode: 'all-protected', reason: 'framerate-absent' }\n }\n const framerate = input.framerate\n\n let keyframeInterval: KeyframeInterval\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 } else {\n return { trackKind: 'video', mode: 'all-protected', reason: 'keyframe-cadence-absent' }\n }\n\n const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale)\n if (gopFrames === null) {\n return {\n trackKind: 'video',\n mode: 'all-protected',\n reason: 'keyframe-interval-not-integral',\n }\n }\n\n const frameDurationMs = 1000 / framerate\n const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs)\n if (interleaveUnits >= gopFrames) {\n return { trackKind: 'video', mode: 'all-protected', reason: 'block-spans-gop' }\n }\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 is not `classifying` or the interval is not an exact integer\n * number of media ticks.\n */\nexport function keyframeIntervalMediaTicks(\n geometry: BlockClassifierGeometry,\n mediaTimescale: number,\n): bigint | null {\n if (geometry.trackKind !== 'video' || geometry.mode !== 'classifying') 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// \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 the MPU: 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.\n */\n readonly idx?: number\n /** movie_fragment_sequence_number from the DU header, when present. */\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 idxMin?: number\n idxMax?: 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/** Authored order of two data-unit starts of one MPU. */\nfunction compareDataUnitStarts(\n a: Omit<DataUnitStart, 'sbn'>,\n b: Omit<DataUnitStart, 'sbn'>,\n): number {\n return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset\n}\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`), in\n * one movie fragment (`mpu-multiple-fragments`).\n *\n * P1 and P2 are what make a block's frames contiguous and lie within\n * [idxMax \u2212 D + 1, idxMin + D \u2212 1] of its MPU. What refutes P1 is a pair of\n * source packets whose wire-stated authored order and SBN order disagree:\n * a later MPU in an earlier block, a later data unit of one MPU (by\n * 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 /** MPU \u2192 movie_fragment_sequence_number observed in it. */\n #mpuFragments = new Map<number, number>()\n #lastRap: { mpu: number; presentationTime: bigint; mediaTimescale: number } | 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.#mpuFragments.clear()\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, so the P1\n * ledger starts again.\n */\n noteSourceDiscontinuity(): void {\n this.#clearContiguityLedger()\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\n if (evidence.rap) block.rapSeen = true\n if (evidence.mpu !== undefined) block.mpus.add(evidence.mpu)\n if (evidence.idx !== undefined) {\n block.idxMin = block.idxMin === undefined ? evidence.idx : Math.min(block.idxMin, evidence.idx)\n block.idxMax = block.idxMax === undefined ? evidence.idx : Math.max(block.idxMax, evidence.idx)\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 (evidence.rap && evidence.idx !== undefined && evidence.idx !== 0) {\n this.#mpuBoundsRaps = false\n }\n\n const violation = this.#checkInvariants(sbn, block, evidence)\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 noteReleasedRap(\n mpu: number,\n presentationTime: bigint,\n mediaTimescale: number,\n ): ClassifierChange[] {\n if (this.#geometry.trackKind === 'audio' || this.#mode === 'all-protected') {\n return []\n }\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 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).\n if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {\n return []\n }\n this.#lastRap = { mpu, presentationTime, mediaTimescale }\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 #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 ): 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 (evidence.rap && evidence.idx !== undefined && evidence.idx !== 0) {\n return 'rap-not-mpu-start'\n }\n if (evidence.idx !== undefined && evidence.idx >= 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.idxMin !== undefined &&\n block.idxMax !== undefined &&\n block.idxMax - block.idxMin >= geometry.interleaveUnits\n ) {\n return 'block-wider-than-interleave'\n }\n if (evidence.mpu !== undefined && evidence.movieFragment !== undefined) {\n const fragment = this.#mpuFragments.get(evidence.mpu)\n if (fragment === undefined) {\n this.#mpuFragments.set(evidence.mpu, evidence.movieFragment)\n // One entry per MPU still inside the classification horizon.\n for (const mpu of this.#mpuFragments.keys()) {\n if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu)\n }\n } else if (fragment !== evidence.movieFragment) {\n // sample_number is then a position within a movie fragment, not\n // within the MPU, and the window rule's geometry does not hold.\n return 'mpu-multiple-fragments'\n }\n }\n if (evidence.mpu !== undefined && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {\n return 'block-not-contiguous'\n }\n return null\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.idxMin !== undefined &&\n block.idxMax !== undefined\n ) {\n // A block closes every D media units, so its frames are contiguous and\n // lie in [idxMax \u2212 D + 1, idxMin + D \u2212 1] of MPU m. Index 0 is the only\n // RAP of an MPU and G bounds its length.\n const span = geometry.interleaveUnits - 1\n if (block.idxMax - span >= 1 && block.idxMin + span <= geometry.gopFrames - 1) {\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 /** 0-based sample position within the MPU, when the geometry verifies it. */\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", "/**\n * MmtpRouter's per-stream duplicate ledgers, retained for the stream's FEC\n * horizon (BLO-36599).\n *\n * The router remembers three kinds of wire number per physical stream, so a\n * second copy of a packet is not parsed or delivered twice:\n *\n * - packet_sequence_numbers received on the direct source path, which a\n * recovered FEC block must not deliver again;\n * - packet_sequence_numbers already handed to the track packet callback;\n * - Source FEC Payload IDs (SS_ID) already parsed for playback, which dedup an\n * overlap copy against its multicast twin.\n *\n * Each of these is useful for as long as FECManager can still re-deliver the\n * number's packet, which ends when its FEC block goes terminal; the ledger\n * keeps one further block lifetime of margin. A block's symbols all arrive\n * within its span, the catalog's `interleaveDepthMs` (draft-ramadan-moq-fec\n * \u00A75.1). After its last symbol FECManager makes the block terminal within one\n * block lifetime (the inactivity fail bound plus the D-28 repair grace, the\n * value `blockLifetimeMsForPacket()` returns). FECManager keeps the terminal\n * record longer than that (`terminalRetentionMsForPacket()`, for the in-order\n * release gate), and that record itself counts late symbols as duplicates, so\n * the ledger need not match it. Measured from a number's first arrival that is\n *\n * retention = interleaveDepthMs + blockLifetime + blockLifetime\n *\n * The bound is a time, not a count, on purpose. A count would need the\n * stream's symbol rate, and the catalog does not give one: the producer closes\n * a block after D media units or after K source symbols, whichever comes\n * first, so one span can hold several blocks (every large keyframe does) and K\n * per span is not an upper bound on the rate. The fixed 2000-entry window this\n * replaces held about 4 s of the 467 packet/s AMT stream and about 40 s of a\n * 47 packet/s audio stream; this one holds each stream for its own horizon.\n *\n * The clock is read only when a stream moves to a new FEC block (or for a\n * packet without an FEC coordinate), never per packet, and no timer is armed:\n * the ledgers rotate lazily.\n *\n * A stream whose horizon cannot be derived while FEC still runs (the FEC\n * manager reports no per-stream geometry, or the catalog gives no block span,\n * in which case FECManager falls back to its fail bound and still recovers\n * blocks) is still re-delivered packets by recovery, so it keeps the count\n * window the router kept for every stream before this change: each ledger\n * holds its newest COUNT_BOUNDED_GENERATION to 2 * COUNT_BOUNDED_GENERATION\n * numbers. Only a router without an FEC manager keeps no ledger: nothing\n * re-delivers a packet.\n */\n\n/**\n * Generation length, in numbers, of a ledger whose stream has no derivable FEC\n * horizon. This is not a new bound: it is the window every stream kept before\n * BLO-36599 (trim to the newest 2000 once past 4000), kept for exactly the\n * streams the FEC horizon cannot describe.\n */\nexport const COUNT_BOUNDED_GENERATION = 2000\n\n/**\n * RFC 1982 serial-number order on a 32-bit wire counter (MMTP\n * packet_sequence_number, SS_ID): true when `a` precedes `b`. The counters\n * wrap, so plain `<` would report every wrap as a regression.\n */\nexport function serial32Precedes(a: number, b: number): boolean {\n const distance = (b - a) >>> 0\n return distance !== 0 && distance < 0x80000000\n}\n\n/** The two FECManager values a stream's duplicate retention is derived from. */\nexport interface DuplicateHorizonGeometry {\n /** Catalog `fec.interleaveDepthMs`: the full FEC block span, in ms. */\n readonly blockSpanMs: number\n /**\n * FECManager's `blockLifetimeMsForPacket()`: the longest a block stays open\n * after its last symbol. Its terminal record is kept at least this long.\n */\n readonly blockLifetimeMs: number\n}\n\n/**\n * How long a stream's duplicate ledgers keep a number, or why no FEC horizon\n * is derivable. `'no-fec-manager'`: the router decodes no FEC, so nothing\n * re-delivers a packet and the stream keeps no ledger. `'no-fec-geometry'`:\n * the FEC manager cannot report per-stream geometry. `'no-block-span'`: the\n * stream has no catalog FEC block span (FECManager reports interleaveDepthMs\n * 0, which is also what a stream without FEC reports). FEC may still recover\n * blocks in the last two cases, so they keep count-bounded ledgers.\n */\nexport type DuplicateHorizon =\n | { readonly kind: 'fec-horizon'; readonly retentionMs: number }\n | {\n readonly kind: 'none'\n readonly reason: 'no-fec-manager' | 'no-fec-geometry' | 'no-block-span'\n }\n\nfunction assertPositiveMs(name: keyof DuplicateHorizonGeometry, value: number): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\n `[DuplicateLedger] ${name}=${value}. Derive a positive ${name} from the ` +\n 'stream catalog through FECManager.',\n )\n }\n}\n\n/** Derive a stream's duplicate retention from its FEC geometry; see the module comment. */\nexport function duplicateRetentionMs(geometry: DuplicateHorizonGeometry): number {\n assertPositiveMs('blockSpanMs', geometry.blockSpanMs)\n assertPositiveMs('blockLifetimeMs', geometry.blockLifetimeMs)\n const untilTerminalMs = geometry.blockLifetimeMs\n const terminalRecordMs = geometry.blockLifetimeMs\n return geometry.blockSpanMs + untilTerminalMs + terminalRecordMs\n}\n\n/**\n * A set of wire numbers kept in two generations. Rotating retires the older\n * generation and starts a new one, so a number stays a member from the moment\n * it is added until the second rotation after that: at least one full\n * generation. A number already present keeps its first-arrival generation, as\n * a duplicate must be timed from the original. Additions are dropped while\n * `gate.retaining` is false. While `gate.countBounded` is true the set rotates\n * itself each time its newer generation reaches COUNT_BOUNDED_GENERATION.\n *\n * One Set holds both generations. A number is added once, so the Set's\n * insertion order is generation order and the older generation is exactly its\n * first `#olderCount` members; rotating deletes those in place. Two Sets with\n * a clear() per rotation would reallocate and regrow a Set every generation.\n */\nexport class GenerationalNumberSet {\n readonly #members = new Set<number>()\n #olderCount = 0\n #newerCount = 0\n #rotations = 0\n #floor: number | undefined = undefined\n readonly #gate: { readonly retaining: boolean; readonly countBounded: boolean }\n\n constructor(gate: { readonly retaining: boolean; readonly countBounded: boolean }) {\n this.#gate = gate\n }\n\n has(value: number): boolean {\n return this.#members.has(value)\n }\n\n add(value: number): void {\n if (!this.#gate.retaining || this.#members.has(value)) return\n this.#members.add(value)\n if (++this.#newerCount >= COUNT_BOUNDED_GENERATION && this.#gate.countBounded) this.rotate()\n }\n\n /** Retire the older generation; the current one becomes the older. */\n rotate(): void {\n let retiring = this.#olderCount\n if (retiring > 0) {\n for (const value of this.#members) {\n this.#members.delete(value)\n if (--retiring === 0) break\n }\n }\n this.#olderCount = this.#newerCount\n this.#newerCount = 0\n this.#rotations++\n // Members are only appended between rotations, so the earliest-arrived\n // survivor is fixed until the next rotation; read it once here rather than\n // allocating an iterator per lookup.\n this.#floor = undefined\n for (const value of this.#members) {\n this.#floor = value\n break\n }\n }\n\n clear(): void {\n this.#members.clear()\n this.#olderCount = 0\n this.#newerCount = 0\n this.restartAging()\n }\n\n /**\n * Keep every member but forget how many rotations have passed, so no floor\n * is reported until two more rotations. A stream that starts timing its\n * generations calls this: generations rotated by count say nothing about\n * how long ago their members arrived.\n */\n restartAging(): void {\n this.#rotations = 0\n this.#floor = undefined\n }\n\n /**\n * The earliest-arrived member, once it is known to have arrived at least one\n * full generation ago; `undefined` before that.\n *\n * A rotation is triggered by an arriving packet, which is normally the\n * first member of the new generation (a live stream adds its next packet\n * within one packet interval otherwise). From the second rotation on, the\n * older generation therefore began at a rotation, and its first member\n * arrived about one generation length before now. Before the second\n * rotation the first member may be a number that simply arrived early out of\n * order, so no floor is reported.\n */\n get horizonFloor(): number | undefined {\n if (this.#rotations < 2 || this.#olderCount === 0) return undefined\n return this.#floor\n }\n\n get size(): number {\n return this.#members.size\n }\n}\n\n/**\n * One physical stream's three duplicate ledgers and their shared generation\n * clock. `advance()` runs once per packet (and once per recovered block) before\n * any lookup, `predatesHorizon()` included. It does work only when the packet\n * belongs to a different FEC block than the previous one, or carries no FEC\n * coordinate on a stream with an FEC horizon; everything else is a Set lookup.\n */\nexport class StreamDuplicateLedgers {\n /** packet_sequence_numbers received on the direct source path. */\n readonly sourceSeqs: GenerationalNumberSet\n /** packet_sequence_numbers already handed to the track packet callback. */\n readonly routedSeqs: GenerationalNumberSet\n /** SS_IDs already parsed for playback. */\n readonly parsedSymbols: GenerationalNumberSet\n\n readonly #horizon: () => DuplicateHorizon\n readonly #now: () => number\n #retentionMs: number | null = null\n #countBounded = false\n /** Whether the horizon was read since construction or the last clear(). */\n #horizonRead = false\n #generationStartMs = 0\n #lastSbn: number | undefined = undefined\n\n /**\n * @param horizon resolves the stream's current horizon from its FEC\n * geometry. It is read when the stream moves to a new block, so a catalog\n * change applies from the next block.\n * @param now the clock FECManager's deadlines use.\n */\n constructor(horizon: () => DuplicateHorizon, now: () => number = () => performance.now()) {\n this.#horizon = horizon\n this.#now = now\n this.sourceSeqs = new GenerationalNumberSet(this)\n this.routedSeqs = new GenerationalNumberSet(this)\n this.parsedSymbols = new GenerationalNumberSet(this)\n }\n\n /**\n * Note the FEC block (SBN) of the packet about to be looked up, or\n * `undefined` for a packet without a Source FEC Payload ID. Returns whether\n * the stream keeps ledgers; while it does not, lookups find nothing and\n * additions are dropped. The horizon is read on the first packet after\n * construction or clear(), and again whenever the block changes; a packet\n * without a coordinate never re-reads it, so a stream without FEC\n * coordinates resolves its horizon once, not per packet.\n */\n advance(sbn: number | undefined): boolean {\n if (sbn !== undefined) {\n if (sbn === this.#lastSbn) return this.retaining\n this.#lastSbn = sbn\n } else if (this.#horizonRead) {\n // A packet outside every FEC block (MPU metadata, for one) does not move\n // the stream to a new block, but it still ages timed generations, so a\n // stream that stops carrying FEC coordinates cannot grow its ledgers.\n // Count-bounded ledgers age on their own.\n if (this.#retentionMs !== null) this.#rotateIfDue(this.#now())\n return this.retaining\n }\n this.#horizonRead = true\n const horizon = this.#horizon()\n if (horizon.kind === 'none') {\n if (horizon.reason === 'no-fec-manager') {\n this.#forget()\n } else {\n // FEC still runs, but its horizon is not derivable: keep what the\n // ledgers hold and bound them by count from here on.\n this.#retentionMs = null\n this.#countBounded = true\n }\n return this.retaining\n }\n const nowMs = this.#now()\n this.#countBounded = false\n if (this.#retentionMs === null) {\n this.#retentionMs = horizon.retentionMs\n this.#generationStartMs = nowMs\n this.sourceSeqs.restartAging()\n this.routedSeqs.restartAging()\n this.parsedSymbols.restartAging()\n return true\n }\n this.#retentionMs = horizon.retentionMs\n this.#rotateIfDue(nowMs)\n return true\n }\n\n /**\n * Whether a packet with these wire numbers predates every number the stream\n * has kept for at least one full FEC horizon (BLO-36599).\n *\n * Within one publisher epoch this cannot happen to a usable packet: it\n * would have been sent before a packet that arrived a whole horizon ago, so\n * no FEC block could still recover it and no reorder window could still place\n * it. A publisher that restarts resets packet_sequence_number and SS_ID,\n * and its first packets land exactly here. The evidence is in-band: two\n * wire counters compared against numbers the stream actually received, with\n * the horizon derived from the catalog. No timer is armed and no count\n * threshold is guessed.\n *\n * Limits, by construction: a stream without an FEC horizon (count-bounded\n * ledgers, or none) reports nothing, and so does a stream younger than two\n * timed generations; a restart whose new counters land inside the retained\n * range is not evidence, and its old numbers age out of the ledgers within\n * one horizon.\n */\n predatesHorizon(packetSequenceNumber: number, ssId: number | undefined): boolean {\n if (this.#retentionMs === null) return false\n const seqFloor = this.sourceSeqs.horizonFloor\n if (\n seqFloor !== undefined &&\n serial32Precedes(packetSequenceNumber, seqFloor) &&\n !this.sourceSeqs.has(packetSequenceNumber)\n ) {\n return true\n }\n if (ssId === undefined) return false\n const ssIdFloor = this.parsedSymbols.horizonFloor\n return (\n ssIdFloor !== undefined &&\n serial32Precedes(ssId, ssIdFloor) &&\n !this.parsedSymbols.has(ssId)\n )\n }\n\n /** Whether the stream keeps ledgers, for its FEC horizon or by count. */\n get retaining(): boolean {\n return this.#retentionMs !== null || this.#countBounded\n }\n\n /** Whether the ledgers are bounded by count because no FEC horizon is derivable. */\n get countBounded(): boolean {\n return this.#countBounded\n }\n\n /** Current retention in ms, or null while the stream has no FEC horizon. */\n get retentionMs(): number | null {\n return this.#retentionMs\n }\n\n /** Forget every number (a track reset); the next packet re-derives the horizon. */\n clear(): void {\n this.#forget()\n this.#lastSbn = undefined\n this.#horizonRead = false\n }\n\n #forget(): void {\n this.sourceSeqs.clear()\n this.routedSeqs.clear()\n this.parsedSymbols.clear()\n this.#retentionMs = null\n this.#countBounded = false\n }\n\n #rotateIfDue(nowMs: number): void {\n if (this.#retentionMs === null || nowMs - this.#generationStartMs < this.#retentionMs) return\n this.sourceSeqs.rotate()\n this.routedSeqs.rotate()\n this.parsedSymbols.rotate()\n this.#generationStartMs = nowMs\n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,oBAAoB,uBAAuB,iBAAiB,kBAAkB,YAAY;AAAA,MAC1N;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAMA,gBACE,UACA,MACA,UAAU,OACD;AACT,UAAM,QAAQ,KAAK,aAAa,IAAI,QAAQ,KAAK;AACjD,WAAO,oBAAoB,WAAW,MAAM,SAAS,KAAK;AAAA,EAC5D;AACF;",
|
|
6
|
+
"names": ["MMTP_HEADER_SIZE", "MPU_HEADER_SIZE", "MPU_LENGTH_FIELD_SIZE", "MPU_HEADER_REMAINDER_SIZE", "PACKET_TYPE_MPU", "MMTP_HEADER_SIZE", "view", "MPU_HEADER_SIZE", "view", "MPU_HEADER_REMAINDER_SIZE", "MPU_LENGTH_FIELD_SIZE", "MMTP_HEADER_SIZE", "MPU_HEADER_SIZE", "PACKET_TYPE_MPU", "MPU_HEADER_SIZE", "MMTP_HEADER_SIZE", "MPU_HEADER_SIZE", "PACKET_TYPE_MPU", "MPU_HEADER_REMAINDER_SIZE", "MPU_LENGTH_FIELD_SIZE", "extractAltaTrailer", "runKey", "result", "active", "objectKey", "view", "view", "box", "children", "INT32_MIN", "INT32_MAX", "keyframe", "box", "trex", "isU32", "PACKET_TYPE_MPU", "extractAltaTrailer", "resolver", "serial32Precedes", "dedupedAgainstSource", "droppedBeforeSync", "cb"]
|
|
7
|
+
}
|