@blockcast/mmt-container 2.2.0-main.fb5c7dfbe2de → 2.2.0-main.fde7aee36726

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +5 -2
  2. package/dist/block-policy.d.ts +88 -16
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +164 -56
  5. package/dist/block-policy.js.map +3 -3
  6. package/dist/browser-runtime.js +1284 -174
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +40 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +163 -10
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.d.ts +1 -1
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +48 -1
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.js +34 -0
  17. package/dist/catalog-network-source.js.map +3 -3
  18. package/dist/cmaf-block-assembler.js +92 -1
  19. package/dist/cmaf-block-assembler.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +68 -0
  24. package/dist/delivery-catalog.js.map +4 -4
  25. package/dist/delta-fallback-config.js +39 -1
  26. package/dist/delta-fallback-config.js.map +4 -4
  27. package/dist/fec-manager.d.ts +155 -10
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +596 -81
  30. package/dist/fec-manager.js.map +4 -4
  31. package/dist/fec-state.d.ts +17 -5
  32. package/dist/fec-state.d.ts.map +1 -1
  33. package/dist/fec-state.js +41 -1
  34. package/dist/fec-state.js.map +3 -3
  35. package/dist/fec-worker-setup.js +34 -0
  36. package/dist/fec-worker-setup.js.map +3 -3
  37. package/dist/held-layer-admission.js +34 -0
  38. package/dist/held-layer-admission.js.map +3 -3
  39. package/dist/index.d.ts +6 -5
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +9 -1
  42. package/dist/index.js.map +2 -2
  43. package/dist/iso-block-locator.d.ts +16 -0
  44. package/dist/iso-block-locator.d.ts.map +1 -1
  45. package/dist/iso-block-locator.js +62 -0
  46. package/dist/iso-block-locator.js.map +3 -3
  47. package/dist/mfu-reassembler.js +34 -0
  48. package/dist/mfu-reassembler.js.map +3 -3
  49. package/dist/mmtp-container-parser.d.ts +30 -2
  50. package/dist/mmtp-container-parser.d.ts.map +1 -1
  51. package/dist/mmtp-container-parser.js +140 -2
  52. package/dist/mmtp-container-parser.js.map +3 -3
  53. package/dist/mmtp-container-parser.no-modules.js +293 -18
  54. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  55. package/dist/mmtp-decode-pipeline.js +140 -2
  56. package/dist/mmtp-decode-pipeline.js.map +3 -3
  57. package/dist/mmtp-fec-session.js +34 -0
  58. package/dist/mmtp-fec-session.js.map +3 -3
  59. package/dist/mmtp-mode-selection.d.ts +48 -0
  60. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  61. package/dist/mmtp-mode-selection.js +79 -0
  62. package/dist/mmtp-mode-selection.js.map +7 -0
  63. package/dist/mmtp-router.d.ts +66 -8
  64. package/dist/mmtp-router.d.ts.map +1 -1
  65. package/dist/mmtp-router.js +348 -27
  66. package/dist/mmtp-router.js.map +4 -4
  67. package/dist/multicast-auth-catalog.js +42 -2
  68. package/dist/multicast-auth-catalog.js.map +3 -3
  69. package/dist/multicast-input.js +42 -2
  70. package/dist/multicast-input.js.map +3 -3
  71. package/dist/multicast-manager.d.ts +108 -1
  72. package/dist/multicast-manager.d.ts.map +1 -1
  73. package/dist/multicast-manager.js +1067 -138
  74. package/dist/multicast-manager.js.map +4 -4
  75. package/dist/multicast-transport.js +68 -0
  76. package/dist/multicast-transport.js.map +4 -4
  77. package/dist/multicast-unwrap.js +34 -0
  78. package/dist/multicast-unwrap.js.map +3 -3
  79. package/dist/no-modules.d.ts +1 -0
  80. package/dist/no-modules.d.ts.map +1 -1
  81. package/dist/no-modules.js +295 -19
  82. package/dist/no-modules.js.map +4 -4
  83. package/dist/phase14-catalog-override.d.ts +2 -1
  84. package/dist/phase14-catalog-override.d.ts.map +1 -1
  85. package/dist/phase14-catalog-override.js +69 -2
  86. package/dist/phase14-catalog-override.js.map +3 -3
  87. package/dist/repair-fetch.d.ts +2 -0
  88. package/dist/repair-fetch.d.ts.map +1 -1
  89. package/dist/repair-fetch.js +52 -2
  90. package/dist/repair-fetch.js.map +3 -3
  91. package/dist/repair-layer-subscriptions.js +34 -0
  92. package/dist/repair-layer-subscriptions.js.map +3 -3
  93. package/dist/signaling.js +34 -0
  94. package/dist/signaling.js.map +3 -3
  95. package/dist/timestamp-codec.js +34 -0
  96. package/dist/timestamp-codec.js.map +3 -3
  97. package/dist/wasm-mfu-reassembler.js +34 -0
  98. package/dist/wasm-mfu-reassembler.js.map +3 -3
  99. package/dist/wasm-mmtp-container-parser.js +140 -2
  100. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  101. package/package.json +5 -5
  102. package/schemas/catalog.schema.json +2 -2
  103. package/src/block-policy.ts +324 -83
  104. package/src/carp-catalog.ts +165 -5
  105. package/src/catalog-fec-params.ts +1 -0
  106. package/src/codec-utils.ts +121 -1
  107. package/src/fec-manager.ts +534 -41
  108. package/src/fec-state.ts +21 -5
  109. package/src/index.ts +23 -0
  110. package/src/iso-block-locator.ts +34 -0
  111. package/src/mmtp-container-parser.ts +57 -11
  112. package/src/mmtp-mode-selection.ts +80 -0
  113. package/src/mmtp-router.ts +287 -42
  114. package/src/multicast-manager.ts +218 -10
  115. package/src/no-modules.ts +3 -0
  116. package/src/phase14-catalog-override.ts +14 -3
  117. package/src/repair-fetch.ts +27 -2
  118. package/test-vectors/catalog/README.md +36 -2
  119. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  120. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  121. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  122. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  123. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  124. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  125. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  126. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  127. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  128. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  129. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  130. package/test-vectors/catalog/section-codes.json +3 -3
  131. package/test-vectors/catalog-validation.json +266 -7
  132. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -13,7 +13,7 @@ import {
13
13
  MMTP_SIGNALING_PACKET_ID,
14
14
  type FecBlockProfile,
15
15
  } from "@blockcast/mmt-base";
16
- import { multicastEndpointSource } from "@blockcast/mmt-base";
16
+ import { MMTP_SIBLING_RENDITION_FIELDS, isMmtpMode, mmtpSiblingCandidates, multicastEndpointSource } from "@blockcast/mmt-base";
17
17
  import type { EndpointAuthConfig, MulticastAuthConfig } from "./multicast-auth-catalog.js";
18
18
 
19
19
  // ── Track Role (Phase 14, D-02..D-05) ─────────────────────────
@@ -602,6 +602,11 @@ function validateArchive(catalog: Record<string, unknown>): void {
602
602
  export type CmsfCatalog = {
603
603
  version: number;
604
604
  tracks: Record<string, unknown>[];
605
+ /**
606
+ * The mmtp tracks `validateCmsfMmtpCatalog` removed from `tracks`, and why
607
+ * (mmt-02 13.1 / 4.3.1). Absent when it removed none; not enumerable.
608
+ */
609
+ rejectedTracks?: MmtpTrackIssue[];
605
610
  multicast?: Record<string, unknown>;
606
611
  archive?: ArchiveConfig;
607
612
  [key: string]: unknown;
@@ -619,6 +624,8 @@ export type CmsfCatalogErrorCode =
619
624
  | "track_is_live"
620
625
  | "track_codec"
621
626
  | "track_mmtp_mode"
627
+ | "track_mmtp_sibling"
628
+ | "track_delivery_mode_conflict"
622
629
  | "track_presentation_anchor"
623
630
  | "track_init_ref"
624
631
  | "catalog_init_data_list"
@@ -814,10 +821,10 @@ export function validateCmsfMmtpCatalog(
814
821
  // here throws on `fec` or on a repair or symbol track. A -01 single-object
815
822
  // `fec` therefore costs only that track's FEC (BLO-50171).
816
823
  if (packaging === "mmtp") {
817
- // mmt-01 12.1: MUST be "mfu"; a subscriber rejects anything else.
818
- if (track["mmtpMode"] !== "mfu") {
819
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
820
- }
824
+ // mmt-02 13.1: `mmtpMode` is "mfu" or "mfu-datagram"; absent or
825
+ // unknown rejects the track, never the catalog: no throw here,
826
+ // `dropRejectedMmtpTracks` removes it from the result, with the
827
+ // sibling and delivery-mode rejections of 4.3.1.
821
828
  if (!positiveInteger(timescale)) {
822
829
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
823
830
  }
@@ -938,9 +945,162 @@ export function validateCmsfMmtpCatalog(
938
945
 
939
946
  validateArchive(catalog);
940
947
 
948
+ dropRejectedMmtpTracks(catalog);
941
949
  return catalog as CmsfCatalog;
942
950
  }
943
951
 
952
+ // mmt-02 13.1 / 4.3.1: a rejected mmtp track leaves the validated catalog,
953
+ // with the `fec-repair` tracks and endpoint references that name it, so a
954
+ // caller that relies on the validator alone never subscribes it. In place,
955
+ // like the `version` normalization: a caller that keeps its own reference
956
+ // sees the same tracks. A catalog with no rejected track is untouched.
957
+ function dropRejectedMmtpTracks(catalog: Record<string, unknown>): void {
958
+ const rejected = mmtpTrackIssues(catalog);
959
+ if (rejected.length === 0) return;
960
+ const tracks = catalog["tracks"] as unknown[];
961
+ const rejectedIndexes = new Set(rejected.map((issue) => issue.index));
962
+ const nameOf = (track: unknown) => (track as Record<string, unknown> | null)?.["name"];
963
+ const mediaNames = new Set(tracks.filter((_, index) => !rejectedIndexes.has(index)).map(nameOf));
964
+ const kept = tracks.filter((track, index) => {
965
+ if (rejectedIndexes.has(index)) return false;
966
+ const t = track as Record<string, unknown> | null;
967
+ return !(t?.["packaging"] === "fec-repair" && typeof t["source"] === "string" && !mediaNames.has(t["source"]) &&
968
+ rejected.some((issue) => issue.name === t["source"]));
969
+ });
970
+ catalog["tracks"] = kept;
971
+ const keptNames = new Set(kept.map(nameOf));
972
+ const endpoints = (catalog["multicast"] as Record<string, unknown> | undefined)?.["endpoints"];
973
+ if (Array.isArray(endpoints)) {
974
+ for (const endpoint of endpoints as (Record<string, unknown> | null)[]) {
975
+ const refs = endpoint?.["tracks"];
976
+ if (!endpoint || !Array.isArray(refs)) continue;
977
+ // A reference to a dropped track would read as "unknown catalog
978
+ // track" and fail the whole catalog on a second validation.
979
+ endpoint["tracks"] = refs.filter((ref) => keptNames.has(typeof ref === "object" ? nameOf(ref) : ref));
980
+ }
981
+ }
982
+ // Not enumerable: the catalog serializes and schema-validates as before.
983
+ Object.defineProperty(catalog, "rejectedTracks", { value: rejected, enumerable: false, configurable: true, writable: true });
984
+ }
985
+
986
+ /** The mmtp track admission rules of draft-ramadan-moq-mmt-02 13.1 and 4.3.1. */
987
+ export type MmtpTrackIssueCode = "track_mmtp_mode" | "track_mmtp_sibling" | "track_delivery_mode_conflict";
988
+
989
+ export interface MmtpTrackIssue {
990
+ code: MmtpTrackIssueCode;
991
+ /** JSONPath of the offending field. */
992
+ path: string;
993
+ message: string;
994
+ /** The mmtp track a subscriber rejects; every other track stays usable. */
995
+ name: string;
996
+ index: number;
997
+ }
998
+
999
+ /**
1000
+ * Every mmtp track a subscriber rejects, in document order, and why. These
1001
+ * are track-level: `validateCmsfMmtpCatalog` never throws on them, it removes
1002
+ * each named track from the catalog it returns and lists them in
1003
+ * `rejectedTracks`, so one bad track costs nothing else (mmt-02 13.1: "a
1004
+ * subscriber MUST reject a track whose mmtpMode is absent or unknown"). Call
1005
+ * this on a catalog that has not been validated yet. Never throws.
1006
+ *
1007
+ * - `track_mmtp_mode`: `mmtpMode` is absent or neither "mfu" nor "mfu-datagram".
1008
+ * - `track_delivery_mode_conflict`: an "mfu-datagram" track, or a `fec-repair`
1009
+ * track whose `source` it is, declares `deliveryMode: "stream"`; libmmt
1010
+ * would subscribe no repair (`catalogTrackDeliveryMode`) on the one track
1011
+ * whose point is repair.
1012
+ * - `track_mmtp_sibling`: an "mfu-datagram" track equals no "mfu" track on
1013
+ * the whole identity set (namespace, `timescale`,
1014
+ * `presentationAnchorTicks`, group duration and the 13.1 rendition fields,
1015
+ * `MMTP_SIBLING_RENDITION_FIELDS`), or more than one: the two carry one
1016
+ * payload, so one description (mmt-02 4.3.1). Or it shares its "mfu" track
1017
+ * with another "mfu-datagram" track: the catalog does not say which one
1018
+ * mirrors it. A track with a `track_delivery_mode_conflict` is dropped, so
1019
+ * it is not counted as that other track.
1020
+ */
1021
+ export function mmtpTrackIssues(catalog: unknown): MmtpTrackIssue[] {
1022
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) return [];
1023
+ const tracks = (catalog as Record<string, unknown>)["tracks"];
1024
+ if (!Array.isArray(tracks)) return [];
1025
+ const records = tracks.filter(
1026
+ (track): track is Record<string, unknown> => typeof track === "object" && track !== null && !Array.isArray(track),
1027
+ );
1028
+ const issues: MmtpTrackIssue[] = [];
1029
+ // Where an "mfu-datagram" track, or a repair track whose source it is, says deliveryMode "stream".
1030
+ const streamPaths = (track: Record<string, unknown>): string[] => {
1031
+ const name = typeof track["name"] === "string" ? track["name"] : "";
1032
+ return [track, ...records.filter((repair) => repair["packaging"] === "fec-repair" && repair["source"] === name)]
1033
+ .filter((declaring) => declaring["deliveryMode"] === "stream")
1034
+ .map((declaring) => `$.tracks[${tracks.indexOf(declaring)}]`);
1035
+ };
1036
+ // The "mfu" tracks each "mfu-datagram" track could mirror, and for each "mfu"
1037
+ // track with exactly such a match, the datagram tracks that claim it. A track
1038
+ // rejected for its delivery mode is dropped, so it claims none.
1039
+ const candidatesOf = new Map<Record<string, unknown>, Record<string, unknown>[]>();
1040
+ const mirrorsOf = new Map<Record<string, unknown>, Record<string, unknown>[]>();
1041
+ for (const track of records) {
1042
+ if (track["packaging"] !== "mmtp" || track["mmtpMode"] !== "mfu-datagram") continue;
1043
+ const candidates = mmtpSiblingCandidates(records, track);
1044
+ candidatesOf.set(track, candidates);
1045
+ if (candidates.length === 1 && streamPaths(track).length === 0) {
1046
+ mirrorsOf.set(candidates[0]!, [...(mirrorsOf.get(candidates[0]!) ?? []), track]);
1047
+ }
1048
+ }
1049
+ for (const track of records) {
1050
+ const index = tracks.indexOf(track);
1051
+ const path = `$.tracks[${index}]`;
1052
+ const name = typeof track["name"] === "string" ? track["name"] : "";
1053
+ if (track["packaging"] !== "mmtp") continue;
1054
+ const mode = track["mmtpMode"];
1055
+ if (!isMmtpMode(mode)) {
1056
+ issues.push({
1057
+ code: "track_mmtp_mode",
1058
+ path: `${path}.mmtpMode`,
1059
+ message: `mmtpMode must be "mfu" or "mfu-datagram", got ${JSON.stringify(mode)}; a subscriber rejects the track (draft-ramadan-moq-mmt-02 13.1)`,
1060
+ name,
1061
+ index,
1062
+ });
1063
+ continue;
1064
+ }
1065
+ if (mode !== "mfu-datagram") continue;
1066
+ const conflict = (at: string) => issues.push({
1067
+ code: "track_delivery_mode_conflict",
1068
+ path: `${at}.deliveryMode`,
1069
+ message: `"mfu-datagram" track ${JSON.stringify(name)} and its repair tracks are sent as datagrams; deliveryMode "stream" would subscribe no repair (draft-ramadan-moq-mmt-02 4.3.1)`,
1070
+ name,
1071
+ index,
1072
+ });
1073
+ const streams = streamPaths(track);
1074
+ for (const at of streams) conflict(at);
1075
+ const candidates = candidatesOf.get(track) ?? [];
1076
+ // Two datagram tracks that mirror one "mfu" track: pairMmtpSiblings pairs
1077
+ // neither, so each is rejected here and the fallback to "mfu" has a reason.
1078
+ const rivals = candidates.length === 1 && streams.length === 0
1079
+ ? (mirrorsOf.get(candidates[0]!) ?? []).filter((other) => other !== track)
1080
+ : [];
1081
+ if (rivals.length > 0) {
1082
+ issues.push({
1083
+ code: "track_mmtp_sibling",
1084
+ path,
1085
+ message: `"mfu-datagram" track ${JSON.stringify(name)} mirrors "mfu" track ${JSON.stringify(candidates[0]!["name"])}, and so ${rivals.length === 1 ? "does" : "do"} ${rivals.map((rival) => JSON.stringify(rival["name"])).join(", ")}; the catalog does not say which one mirrors it, so a subscriber pairs none (draft-ramadan-moq-mmt-02 4.3.1)`,
1086
+ name,
1087
+ index,
1088
+ });
1089
+ } else if (candidates.length !== 1) {
1090
+ issues.push({
1091
+ code: "track_mmtp_sibling",
1092
+ path,
1093
+ message: candidates.length === 0
1094
+ ? `"mfu-datagram" track ${JSON.stringify(name)} mirrors no "mfu" track of its namespace with the same timescale, presentationAnchorTicks, group duration and rendition fields (${MMTP_SIBLING_RENDITION_FIELDS.join(", ")}), each equal or absent on both (draft-ramadan-moq-mmt-02 4.3.1, 13.1)`
1095
+ : `"mfu-datagram" track ${JSON.stringify(name)} could mirror ${candidates.length} "mfu" tracks (${candidates.map((c) => JSON.stringify(c["name"])).join(", ")}) that carry one description; the pair is ambiguous`,
1096
+ name,
1097
+ index,
1098
+ });
1099
+ }
1100
+ }
1101
+ return issues;
1102
+ }
1103
+
944
1104
  /**
945
1105
  * Resolve a track's group duration to integer ticks using the supplied
946
1106
  * timescale (Hz). Implements mmt-01 §4.4.2:
@@ -37,6 +37,7 @@ export { FEC_BLOCK_PROFILES, isFecBlockProfile, parseFecBlockProfile, type FecBl
37
37
  // Re-exported here, not from index.ts: index's bundle keeps `./*.js` external,
38
38
  // so a direct mmt-base re-export there leaves a dangling `./mmtp.js` import.
39
39
  export {
40
+ runtimeFecCatalogReport,
40
41
  validateFecCatalog,
41
42
  type FecCatalogCode,
42
43
  type FecCatalogInstance,
@@ -1276,9 +1276,21 @@ function isH264IntraSlice(nal: Uint8Array): boolean {
1276
1276
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9
1277
1277
  }
1278
1278
 
1279
+ /**
1280
+ * Escaped bytes after the NAL header that always hold first_mb_in_slice and
1281
+ * slice_type. {@link readUnsignedExpGolomb} reads at most 61 bits per ue(v)
1282
+ * and gives up at the 31st leading zero, so both fields end within 122 bits
1283
+ * (16 bytes) of RBSP. {@link removeEmulationPrevention} drops a 0x03 only
1284
+ * after two kept zero bytes since the last one it dropped, so 32 escaped
1285
+ * bytes unescape to at least 22.
1286
+ */
1287
+ const H264_SLICE_TYPE_ESCAPED_BYTES = 32
1288
+
1279
1289
  function readH264SliceType(nal: Uint8Array): number | null {
1280
1290
  if (nal.length < 2 || (nal[0]! & 0x1f) !== 1) return null
1281
- const rbsp = removeEmulationPrevention(nal.subarray(1))
1291
+ // Unescape the start of the slice header only, not the whole slice: this
1292
+ // runs on every non-IDR frame.
1293
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES))
1282
1294
  const state = { bitOffset: 0 }
1283
1295
  if (readUnsignedExpGolomb(rbsp, state) === null) return null
1284
1296
  return readUnsignedExpGolomb(rbsp, state)
@@ -1705,6 +1717,114 @@ if (import.meta.vitest) {
1705
1717
  })
1706
1718
  })
1707
1719
 
1720
+ describe('readH264SliceType', () => {
1721
+ /** The read as it was before the prefix bound: unescape the whole NAL unit. */
1722
+ const wholeNalSliceType = (nal: Uint8Array): number | null => {
1723
+ if (nal.length < 2 || (nal[0]! & 0x1f) !== 1) return null
1724
+ const rbsp = removeEmulationPrevention(nal.subarray(1))
1725
+ const state = { bitOffset: 0 }
1726
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null
1727
+ return readUnsignedExpGolomb(rbsp, state)
1728
+ }
1729
+ const hex = (text: string) => Uint8Array.from(text.match(/../g)!, (byte) => parseInt(byte, 16))
1730
+ const ue = (value: number) => {
1731
+ const code = (value + 1).toString(2)
1732
+ return '0'.repeat(code.length - 1) + code
1733
+ }
1734
+ /** A nal_unit_type 1 NAL unit from RBSP bits, escaped as an encoder escapes it (H.264 §7.4.1). */
1735
+ const sliceNal = (bits: string): Uint8Array => {
1736
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, '0').match(/.{8}/g)!
1737
+ const nal = [0x01]
1738
+ let zeros = 0
1739
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
1740
+ if (zeros >= 2 && byte <= 0x03) {
1741
+ nal.push(0x03)
1742
+ zeros = 0
1743
+ }
1744
+ nal.push(byte)
1745
+ zeros = byte === 0 ? zeros + 1 : 0
1746
+ }
1747
+ return Uint8Array.from(nal)
1748
+ }
1749
+
1750
+ // x264 core 164 (FFmpeg 6.1.1) slices of testsrc2: 64x48 with open-gop=1:bframes=2:slices=3;
1751
+ // 1280x720 main with bframes=2:slices=4, each carrying an emulation_prevention_three_byte
1752
+ // in its first 32 bytes; and the first 40 bytes of 7680x4320 slices=4 slices, whose
1753
+ // first_mb_in_slice takes up to 33 bits. [name, NAL unit, slice_type, keyframe]
1754
+ const x264Slices: Array<[string, Uint8Array, number | null, boolean]> = [
1755
+ ['64x48 P', hex('419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176'), 5, false],
1756
+ ['64x48 B', hex('419e414212fffeeade283707cb70f7'), 6, false],
1757
+ ['64x48 non-IDR I', hex(
1758
+ '4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66' +
1759
+ '247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39' +
1760
+ 'a527e23eb34c8167fd',
1761
+ ), 7, true],
1762
+ ['1280x720 B, escape at byte 10', hex(
1763
+ '01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e' +
1764
+ '19b75d92170917306190f262fd58268702db2eff86a9651e48',
1765
+ ), 6, false],
1766
+ ['1280x720 P, escape at byte 15', hex(
1767
+ '41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f0' +
1768
+ '2c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e8530' +
1769
+ '2da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3',
1770
+ ), 5, false],
1771
+ ['1280x720 B, escape at byte 22', hex('01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352'), 6, false],
1772
+ ['7680x4320 IDR, first_mb_in_slice 97440', hex(
1773
+ '650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9',
1774
+ ), null, true],
1775
+ ['7680x4320 P, first_mb_in_slice 32640', hex(
1776
+ '410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020',
1777
+ ), 5, false],
1778
+ ['7680x4320 P, first_mb_in_slice 97440', hex(
1779
+ '410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806',
1780
+ ), 5, false],
1781
+ ]
1782
+ // Field values far past what a picture needs, so that escapes fall inside the two fields.
1783
+ const syntheticSlices: Array<[string, Uint8Array, number | null]> = [
1784
+ ['an escape inside first_mb_in_slice', sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
1785
+ ['an escape between the fields', sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
1786
+ ['an escape inside slice_type', sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
1787
+ ['the longest fields, five escapes', sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
1788
+ ['the largest values', sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
1789
+ ['31 leading zeros in first_mb_in_slice', sliceNal(`${'0'.repeat(31)}1`), null],
1790
+ ['31 leading zeros in slice_type', sliceNal(`1${'0'.repeat(31)}1`), null],
1791
+ ['escapes running past the slice header', sliceNal(ue(0) + ue(5) + '0'.repeat(400)), 5],
1792
+ ]
1793
+
1794
+ test('reads the slice_type of real and synthetic slices', () => {
1795
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
1796
+ expect(readH264SliceType(nal), name).toBe(sliceType)
1797
+ }
1798
+ })
1799
+
1800
+ test('matches the whole-NAL unescape at every truncation', () => {
1801
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
1802
+ for (let end = 0; end <= nal.length; end++) {
1803
+ const cut = nal.subarray(0, end)
1804
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut))
1805
+ }
1806
+ }
1807
+ })
1808
+
1809
+ test('matches the whole-NAL unescape on zero-heavy NAL units', () => {
1810
+ const bytes = [0x00, 0x00, 0x00, 0x03, 0x01, 0x02, 0x80, 0xff]
1811
+ let seed = 1
1812
+ const next = () => (seed = (Math.imul(seed, 1103515245) + 12345) >>> 0) >>> 16
1813
+ for (let i = 0; i < 5000; i++) {
1814
+ const nal = new Uint8Array(2 + (next() % 63))
1815
+ nal[0] = 0x41
1816
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length]!
1817
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal))
1818
+ }
1819
+ })
1820
+
1821
+ test('classifies the x264 slices as keyframes or not', () => {
1822
+ for (const [name, nal, , keyframe] of x264Slices) {
1823
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe)
1824
+ }
1825
+ })
1826
+ })
1827
+
1708
1828
  describe('avccToAnnexB', () => {
1709
1829
  test('converts with SPS/PPS on keyframe', () => {
1710
1830
  const avcc = new Uint8Array([0, 0, 0, 3, 0x65, 0xAA, 0xBB])