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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/align.d.ts +6 -2
  2. package/dist/align.d.ts.map +1 -1
  3. package/dist/align.js.map +2 -2
  4. package/dist/audio-ring-buffer.js +23 -36
  5. package/dist/audio-ring-buffer.js.map +1 -1
  6. package/dist/browser-runtime.js +6865 -6485
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +3 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +21 -2
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.js +10 -0
  13. package/dist/catalog-fec-params.js.map +4 -4
  14. package/dist/cmaf-block-assembler.d.ts +42 -0
  15. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  16. package/dist/cmaf-block-assembler.js +542 -535
  17. package/dist/cmaf-block-assembler.js.map +2 -2
  18. package/dist/cmaf-group-batcher.js +27 -46
  19. package/dist/cmaf-group-batcher.js.map +2 -2
  20. package/dist/cmcd-producer.js +45 -66
  21. package/dist/cmcd-producer.js.map +1 -1
  22. package/dist/fec-manager.d.ts +13 -1
  23. package/dist/fec-manager.d.ts.map +1 -1
  24. package/dist/fec-manager.js +1151 -871
  25. package/dist/fec-manager.js.map +2 -2
  26. package/dist/fec-starvation-detector.js +25 -40
  27. package/dist/fec-starvation-detector.js.map +1 -1
  28. package/dist/fec-worker-setup.js +242 -225
  29. package/dist/fec-worker-setup.js.map +3 -3
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js.map +2 -2
  33. package/dist/iso-bmff-timing.js +63 -88
  34. package/dist/iso-bmff-timing.js.map +1 -1
  35. package/dist/loc.js +7 -4
  36. package/dist/loc.js.map +1 -1
  37. package/dist/manifest-auth-plan.js +292 -311
  38. package/dist/manifest-auth-plan.js.map +1 -1
  39. package/dist/media-router.d.ts +0 -99
  40. package/dist/media-router.d.ts.map +1 -1
  41. package/dist/media-router.js +270 -504
  42. package/dist/media-router.js.map +3 -3
  43. package/dist/mfu-reassembler.js +597 -607
  44. package/dist/mfu-reassembler.js.map +3 -3
  45. package/dist/mmtp-container-parser.d.ts +37 -0
  46. package/dist/mmtp-container-parser.d.ts.map +1 -1
  47. package/dist/mmtp-container-parser.js +1531 -1522
  48. package/dist/mmtp-container-parser.js.map +3 -3
  49. package/dist/mmtp-container-parser.no-modules.js +179 -102
  50. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  51. package/dist/mmtp-decode-pipeline.js +1641 -1651
  52. package/dist/mmtp-decode-pipeline.js.map +3 -3
  53. package/dist/mmtp-router.d.ts +34 -0
  54. package/dist/mmtp-router.d.ts.map +1 -1
  55. package/dist/mmtp-router.js +3676 -3390
  56. package/dist/mmtp-router.js.map +3 -3
  57. package/dist/mmtp-to-cmaf.d.ts +7 -1
  58. package/dist/mmtp-to-cmaf.d.ts.map +1 -1
  59. package/dist/mmtp-to-cmaf.js +109 -134
  60. package/dist/mmtp-to-cmaf.js.map +2 -2
  61. package/dist/multicast-input.d.ts +7 -35
  62. package/dist/multicast-input.d.ts.map +1 -1
  63. package/dist/multicast-input.js +21 -2
  64. package/dist/multicast-input.js.map +4 -4
  65. package/dist/multicast-manager.d.ts +10 -1
  66. package/dist/multicast-manager.d.ts.map +1 -1
  67. package/dist/multicast-manager.js +5584 -4961
  68. package/dist/multicast-manager.js.map +4 -4
  69. package/dist/multicast-transport.d.ts +7 -0
  70. package/dist/multicast-transport.d.ts.map +1 -1
  71. package/dist/multicast-transport.js +369 -421
  72. package/dist/multicast-transport.js.map +4 -4
  73. package/dist/multicast-unwrap.js +53 -30
  74. package/dist/multicast-unwrap.js.map +2 -2
  75. package/dist/no-modules.js +2096 -2097
  76. package/dist/no-modules.js.map +3 -3
  77. package/dist/sample-combiner.js +118 -139
  78. package/dist/sample-combiner.js.map +1 -1
  79. package/dist/signaling.js.map +2 -2
  80. package/dist/source-auth.js +353 -382
  81. package/dist/source-auth.js.map +1 -1
  82. package/dist/switching-set-alignment.js +14 -29
  83. package/dist/switching-set-alignment.js.map +1 -1
  84. package/dist/timestamp-codec.js +17 -11
  85. package/dist/timestamp-codec.js.map +2 -2
  86. package/dist/track-pipeline-setup.js +105 -125
  87. package/dist/track-pipeline-setup.js.map +1 -1
  88. package/dist/track-pipeline.js +107 -127
  89. package/dist/track-pipeline.js.map +1 -1
  90. package/dist/track-session.d.ts +16 -0
  91. package/dist/track-session.d.ts.map +1 -1
  92. package/dist/track-session.js +230 -243
  93. package/dist/track-session.js.map +2 -2
  94. package/dist/transport-pool.js +24 -38
  95. package/dist/transport-pool.js.map +1 -1
  96. package/dist/wasm-mfu-reassembler.d.ts +6 -1
  97. package/dist/wasm-mfu-reassembler.d.ts.map +1 -1
  98. package/dist/wasm-mfu-reassembler.js +127 -144
  99. package/dist/wasm-mfu-reassembler.js.map +2 -2
  100. package/dist/wasm-mmtp-container-parser.js +1659 -1650
  101. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  102. package/node_modules/@blockcast/fec-worker/README.md +5 -1
  103. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +8 -2
  104. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -1
  105. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +89 -16
  106. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -1
  107. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts +48 -3
  108. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts.map +1 -1
  109. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js +55 -8
  110. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js.map +2 -2
  111. package/node_modules/@blockcast/fec-worker/dist/index.d.ts +1 -1
  112. package/node_modules/@blockcast/fec-worker/dist/index.d.ts.map +1 -1
  113. package/node_modules/@blockcast/fec-worker/dist/index.js.map +1 -1
  114. package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +97 -17
  115. package/node_modules/@blockcast/fec-worker/src/fec-worker-types.ts +46 -2
  116. package/node_modules/@blockcast/fec-worker/src/fec-worker.ts +78 -10
  117. package/node_modules/@blockcast/fec-worker/src/index.ts +2 -0
  118. package/node_modules/@blockcast/mmt-base/README.md +1 -0
  119. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  120. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  121. package/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  122. package/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  123. package/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  124. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/README.md +1 -0
  125. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  126. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  127. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  128. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  129. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  130. package/package.json +7 -6
  131. package/schemas/catalog.schema.json +1 -1
  132. package/src/align.ts +6 -2
  133. package/src/carp-catalog.ts +13 -3
  134. package/src/cmaf-block-assembler.ts +90 -81
  135. package/src/fec-manager.ts +530 -146
  136. package/src/index.ts +2 -2
  137. package/src/media-router.ts +0 -397
  138. package/src/mmtp-container-parser.ts +97 -21
  139. package/src/mmtp-router.ts +302 -125
  140. package/src/mmtp-to-cmaf.ts +21 -7
  141. package/src/multicast-input.ts +23 -3
  142. package/src/multicast-manager.ts +83 -11
  143. package/src/multicast-transport.ts +56 -17
  144. package/src/track-session.ts +16 -0
  145. package/src/wasm-mfu-reassembler.ts +40 -24
  146. package/test-vectors/catalog/README.md +2 -0
  147. package/test-vectors/catalog/negative/multicast-packet-id-signaling.json +26 -0
  148. package/test-vectors/catalog-validation.json +11 -0
@@ -1,20 +1,3 @@
1
- var __typeError = (msg) => {
2
- throw TypeError(msg);
3
- };
4
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
- var __privateWrapper = (obj, member, setter, getter) => ({
10
- set _(value) {
11
- __privateSet(obj, member, value, setter);
12
- },
13
- get _() {
14
- return __privateGet(obj, member, getter);
15
- }
16
- });
17
-
18
1
  // src/mmtp-to-cmaf.ts
19
2
  function box(type, ...children) {
20
3
  let size = 8;
@@ -352,6 +335,7 @@ function buildVideoInitSegment(avcC, width, height, timescale = 1e6, trackId = 1
352
335
  function buildAudioInitSegment(sampleRate, channels, asc, timescale, trackId = 1) {
353
336
  assertTrackId(trackId, "audio trackId");
354
337
  const ts = timescale ?? sampleRate;
338
+ assertTimescale(ts, "audio timescale");
355
339
  if (!asc) {
356
340
  const freqTable = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
357
341
  const fi = freqTable.indexOf(sampleRate);
@@ -1069,35 +1053,31 @@ function scaleAuthoredTiming(timing, targetTimescale) {
1069
1053
  // src/cmaf-block-assembler.ts
1070
1054
  var INT32_MIN2 = -2147483648;
1071
1055
  var INT32_MAX2 = 2147483647;
1072
- var _config, _blocks, _pendingFlush, _pendingRecovered, _sequence, _baseTs, _fillFrame, _lastDecodableAudioFrame, _frameDuration, _lastEmittedTs, _lastSourceTs, _sampleReorderWindow, _sampleOrder, _sampleOrderCapacity, _sampleReorderQueue, _recoveredHorizonTs, _sampleOrderStats, _validateH264Keyframes, _keyframeRejectDumpCount, _armedVideo, _lastEmittedSbn, _CmafBlockAssembler_instances, claimSbnEmission_fn, applyVideoKeyframeGate_fn, normalizeVideoKeyframes_fn, withEffectiveVideoKeyframe_fn, dumpRejectedVideoKeyframe_fn, ordersSamples_fn, unwrapTimestamp_fn, emitSample_fn, emitArrivalOrdered_fn, queueSample_fn, releaseHorizon_fn, sampleIsReleasable_fn, dropPreRapSamples_fn, drainSampleReorder_fn, emitQueuedSample_fn, enforceSampleOrderCapacity_fn, emitSampleNow_fn, writeSampleNow_fn, emitAudioGapFillNowBefore_fn, emitPerSample_fn, _dumpCount, _emitCount, _sampleCount, _keyframeCount, _addFrameCount, _recoveredBlockCount, _completeBlockCount, _failBlockCount, _aggregateTimer, startAggregateTimer_fn, dumpEmit_fn, rebase_fn, normalizeSampleData_fn, enqueueRecovered_fn, drainRecoveredUpTo_fn, flushBlock_fn, flushBlockWithFill_fn;
1073
1056
  var CmafBlockAssembler = class {
1074
1057
  constructor(config) {
1075
- __privateAdd(this, _CmafBlockAssembler_instances);
1076
- __privateAdd(this, _config);
1077
- __privateAdd(this, _blocks, /* @__PURE__ */ new Map());
1078
- __privateAdd(this, _pendingFlush, /* @__PURE__ */ new Set());
1079
- __privateAdd(this, _pendingRecovered, /* @__PURE__ */ new Map());
1080
- __privateAdd(this, _sequence, 1);
1081
- __privateAdd(this, _baseTs, -1);
1082
- __privateAdd(this, _fillFrame);
1083
- __privateAdd(this, _lastDecodableAudioFrame, null);
1084
- __privateAdd(this, _frameDuration);
1085
- __privateAdd(this, _lastEmittedTs, -1);
1086
- __privateAdd(this, _lastSourceTs, -1);
1087
- __privateAdd(this, _sampleReorderWindow, 0);
1088
- __privateAdd(this, _sampleOrder, { mode: "arrival" });
1089
- __privateAdd(this, _sampleOrderCapacity, 0);
1090
- __privateAdd(this, _sampleReorderQueue, []);
1091
- __privateAdd(this, _recoveredHorizonTs, -1);
1092
- __privateAdd(this, _sampleOrderStats, {
1058
+ this.#blocks = /* @__PURE__ */ new Map();
1059
+ this.#pendingFlush = /* @__PURE__ */ new Set();
1060
+ this.#pendingRecovered = /* @__PURE__ */ new Map();
1061
+ this.#sequence = 1;
1062
+ this.#baseTs = -1;
1063
+ this.#lastDecodableAudioFrame = null;
1064
+ this.#lastEmittedTs = -1;
1065
+ this.#lastSourceTs = -1;
1066
+ this.#sampleReorderWindow = 0;
1067
+ this.#sampleOrder = { mode: "arrival" };
1068
+ this.#sampleOrderCapacity = 0;
1069
+ this.#sampleReorderQueue = [];
1070
+ this.#recoveredHorizonTs = -1;
1071
+ this.#sampleOrderStats = {
1093
1072
  staleSamples: 0,
1094
1073
  duplicateSamples: 0,
1095
1074
  preRapDeadlineDrops: 0,
1096
1075
  noRapFlushDrops: 0,
1097
- forcedReleases: 0
1098
- });
1099
- __privateAdd(this, _validateH264Keyframes, false);
1100
- __privateAdd(this, _keyframeRejectDumpCount, 0);
1076
+ forcedReleases: 0,
1077
+ unadmittedAuthoredSamples: 0
1078
+ };
1079
+ this.#validateH264Keyframes = false;
1080
+ this.#keyframeRejectDumpCount = 0;
1101
1081
  /** Callback: emits a complete moof+mdat CMAF segment */
1102
1082
  this.onSegment = null;
1103
1083
  /** Callback: emits a gated/deduped raw sample for callers that already own the MSE timeline. */
@@ -1114,43 +1094,42 @@ var CmafBlockAssembler = class {
1114
1094
  // unconditionally — valid for the codecs supported here (AAC, Opus) where
1115
1095
  // every frame is independently decodable. SBR-only AAC, USAC, or HE-AAC v2
1116
1096
  // with PCE re-entry would need a similar gate.
1117
- __privateAdd(this, _armedVideo, false);
1097
+ this.#armedVideo = false;
1118
1098
  // Legacy SBN emission watermark for the old block-buffered path. Direct
1119
1099
  // source emission is now timestamp-ordered instead; recovered frames are
1120
1100
  // queued by media timestamp so they can fill gaps without racing ahead of
1121
1101
  // source frames.
1122
- __privateAdd(this, _lastEmittedSbn, -1);
1123
- // [BLO-3035-LAYER4-DIAG] Byte-dump for the first 6 video emits + 1Hz
1124
- // aggregate counters that survive the whole run. The counters tell us
1125
- // whether "emits=low" (assembler emits too few segments) or
1126
- // "addFrame=low" (parser delivers too few frames) — which routes the
1127
- // root-cause hunt to assembler vs router vs publisher.
1128
- __privateAdd(this, _dumpCount, 0);
1129
- __privateAdd(this, _emitCount, 0);
1130
- __privateAdd(this, _sampleCount, 0);
1131
- __privateAdd(this, _keyframeCount, 0);
1132
- __privateAdd(this, _addFrameCount, 0);
1133
- __privateAdd(this, _recoveredBlockCount, 0);
1134
- __privateAdd(this, _completeBlockCount, 0);
1135
- __privateAdd(this, _failBlockCount, 0);
1136
- __privateAdd(this, _aggregateTimer, null);
1137
- __privateSet(this, _config, {
1102
+ this.#lastEmittedSbn = -1;
1103
+ // Cumulative emit counters (see emitStats). They replace the BLO-3035 L4
1104
+ // diagnostics, which hashed and hex-dumped every video keyframe and ran a
1105
+ // 1 s setInterval console aggregate on the MSE path (BLO-36599).
1106
+ this.#emitStats = {
1107
+ emits: 0,
1108
+ samples: 0,
1109
+ keyframes: 0,
1110
+ addedFrames: 0,
1111
+ recoveredBlocks: 0,
1112
+ completedBlocks: 0,
1113
+ failedBlocks: 0
1114
+ };
1115
+ this.#config = {
1138
1116
  k: config.k,
1139
1117
  timescale: config.timescale ?? 1e6,
1140
1118
  trackId: config.trackId ?? 1,
1141
- trackType: config.trackType
1142
- });
1119
+ trackType: config.trackType,
1120
+ admitAuthoredTiming: config.admitAuthoredTiming ?? true
1121
+ };
1143
1122
  if (config.fps && config.fps > 0) {
1144
- __privateSet(this, _frameDuration, Math.round(__privateGet(this, _config).timescale / config.fps));
1123
+ this.#frameDuration = Math.round(this.#config.timescale / config.fps);
1145
1124
  } else if (config.trackType === "audio" && config.sampleRate) {
1146
- __privateSet(this, _frameDuration, Math.round(__privateGet(this, _config).timescale * 1024 / config.sampleRate));
1125
+ this.#frameDuration = Math.round(this.#config.timescale * 1024 / config.sampleRate);
1147
1126
  } else {
1148
- __privateSet(this, _frameDuration, 33333);
1127
+ this.#frameDuration = 33333;
1149
1128
  }
1150
1129
  if (config.trackType === "video" && config.avcC && config.width && config.height) {
1151
- __privateSet(this, _fillFrame, generateGreenFillNAL(config.avcC, config.width, config.height));
1130
+ this.#fillFrame = generateGreenFillNAL(config.avcC, config.width, config.height);
1152
1131
  } else {
1153
- __privateSet(this, _fillFrame, new Uint8Array(0));
1132
+ this.#fillFrame = new Uint8Array(0);
1154
1133
  }
1155
1134
  const sampleReorderWindow = config.sampleReorderWindow ?? 0;
1156
1135
  if (!Number.isFinite(sampleReorderWindow) || sampleReorderWindow < 0) {
@@ -1159,10 +1138,10 @@ var CmafBlockAssembler = class {
1159
1138
  if (config.sampleOrder && sampleReorderWindow > 0) {
1160
1139
  throw new Error("[CmafBlockAssembler] configure sampleOrder or sampleReorderWindow, not both");
1161
1140
  }
1162
- __privateSet(this, _sampleReorderWindow, Math.floor(sampleReorderWindow));
1163
- __privateSet(this, _sampleOrder, config.sampleOrder ?? { mode: "arrival" });
1164
- if (__privateGet(this, _sampleOrder).mode === "media-window") {
1165
- const { deliveryWindow, timestampWrapPeriod } = __privateGet(this, _sampleOrder);
1141
+ this.#sampleReorderWindow = Math.floor(sampleReorderWindow);
1142
+ this.#sampleOrder = config.sampleOrder ?? { mode: "arrival" };
1143
+ if (this.#sampleOrder.mode === "media-window") {
1144
+ const { deliveryWindow, timestampWrapPeriod } = this.#sampleOrder;
1166
1145
  if (!Number.isSafeInteger(deliveryWindow) || deliveryWindow <= 0) {
1167
1146
  throw new Error(
1168
1147
  "[CmafBlockAssembler] media-window deliveryWindow must be a positive safe integer"
@@ -1179,25 +1158,339 @@ var CmafBlockAssembler = class {
1179
1158
  "[CmafBlockAssembler] media-window ordering requires catalog-derived media cadence"
1180
1159
  );
1181
1160
  }
1182
- __privateSet(this, _sampleOrderCapacity, Math.ceil(deliveryWindow * samplesPerSecond / __privateGet(this, _config).timescale) + 1);
1161
+ this.#sampleOrderCapacity = Math.ceil(deliveryWindow * samplesPerSecond / this.#config.timescale) + 1;
1183
1162
  }
1184
- __privateSet(this, _validateH264Keyframes, config.trackType === "video" && (!!config.avcC || !config.codec || isH264Codec(config.codec)));
1163
+ this.#validateH264Keyframes = config.trackType === "video" && (!!config.avcC || !config.codec || isH264Codec(config.codec));
1185
1164
  if (config.trackType === "video") {
1186
1165
  console.log(
1187
- `[L4-KF-CONFIG] validate=${__privateGet(this, _validateH264Keyframes)} codec=${config.codec ?? ""} avcC=${config.avcC?.length ?? 0}`
1166
+ `[L4-KF-CONFIG] validate=${this.#validateH264Keyframes} codec=${config.codec ?? ""} avcC=${config.avcC?.length ?? 0}`
1188
1167
  );
1189
1168
  }
1190
1169
  this._videoConfig = config.trackType === "video" && config.avcC ? { avcC: config.avcC, width: config.width ?? 0, height: config.height ?? 0 } : null;
1191
1170
  this._audioConfig = config.trackType === "audio" && config.sampleRate && config.channels ? { sampleRate: config.sampleRate, channels: config.channels, asc: config.asc } : null;
1192
1171
  }
1172
+ #config;
1173
+ #blocks;
1174
+ #pendingFlush;
1175
+ #pendingRecovered;
1176
+ #sequence;
1177
+ #baseTs;
1178
+ #fillFrame;
1179
+ #lastDecodableAudioFrame;
1180
+ #frameDuration;
1181
+ #lastEmittedTs;
1182
+ #lastSourceTs;
1183
+ #sampleReorderWindow;
1184
+ #sampleOrder;
1185
+ #sampleOrderCapacity;
1186
+ #sampleReorderQueue;
1187
+ #recoveredHorizonTs;
1188
+ #sampleOrderStats;
1189
+ #validateH264Keyframes;
1190
+ #keyframeRejectDumpCount;
1191
+ #armedVideo;
1192
+ #lastEmittedSbn;
1193
+ /** Attempt to claim emission for `sbn`. Returns true if `sbn` is past
1194
+ * the watermark (and advances it); false if this sbn has already been
1195
+ * claimed or is older (caller should drop). */
1196
+ #claimSbnEmission(sbn) {
1197
+ if (sbn <= this.#lastEmittedSbn) return false;
1198
+ this.#lastEmittedSbn = sbn;
1199
+ return true;
1200
+ }
1201
+ /** Truncate `frames` to start at the first keyframe for video tracks before
1202
+ * the first emission. Returns the (possibly spliced) frames, or null to
1203
+ * drop the block entirely. Audio + already-armed video: identity. */
1204
+ #applyVideoKeyframeGate(frames) {
1205
+ const keyedFrames = this.#normalizeVideoKeyframes(frames);
1206
+ if (this.#config.trackType !== "video" || this.#armedVideo) return keyedFrames;
1207
+ const firstKfIdx = keyedFrames.findIndex((f) => f.keyframe);
1208
+ if (firstKfIdx < 0) return null;
1209
+ return firstKfIdx === 0 ? keyedFrames : keyedFrames.slice(firstKfIdx);
1210
+ }
1211
+ #normalizeVideoKeyframes(frames) {
1212
+ if (this.#config.trackType !== "video" || !this.#validateH264Keyframes) return frames;
1213
+ return frames.map((frame) => this.#withEffectiveVideoKeyframe(frame));
1214
+ }
1215
+ #withEffectiveVideoKeyframe(frame) {
1216
+ if (this.#config.trackType !== "video" || !this.#validateH264Keyframes) return frame;
1217
+ const keyframe = detectH264Keyframe(frame.data);
1218
+ if (!keyframe) this.#dumpRejectedVideoKeyframe(frame.data, frame.keyframe);
1219
+ return keyframe === frame.keyframe ? frame : { ...frame, keyframe };
1220
+ }
1221
+ #dumpRejectedVideoKeyframe(data, metadataKeyframe) {
1222
+ if (this.#keyframeRejectDumpCount >= 12) return;
1223
+ this.#keyframeRejectDumpCount++;
1224
+ const sample = splitH264SampleNalUnits(data);
1225
+ const nalTypes = describeH264NalTypes(sample.nals);
1226
+ const classify = classifyH264Keyframe(data);
1227
+ const hex = Array.from(data.subarray(0, Math.min(48, data.length))).map((b) => b.toString(16).padStart(2, "0")).join(" ");
1228
+ console.log(
1229
+ `[L4-KF-GATE] reject#${this.#keyframeRejectDumpCount} len=${data.length} metadataKf=${metadataKeyframe} classify=${classify} format=${sample.format} nalTypes=[${nalTypes.join(",")}] first48=[${hex}]`
1230
+ );
1231
+ }
1193
1232
  /** Mark video as already synchronized by an external decoder path.
1194
1233
  * Used by MoQ→multicast MSE continuity when MoQ has already appended a
1195
1234
  * keyframe to the same SourceBuffer timeline before multicast takeover. */
1196
1235
  markVideoSynced() {
1197
- if (__privateGet(this, _config).trackType === "video") __privateSet(this, _armedVideo, true);
1236
+ if (this.#config.trackType === "video") this.#armedVideo = true;
1237
+ }
1238
+ /** Emit each frame as its own single-sample moof+mdat segment. Matches the
1239
+ * case-20 path (`MmtpToCmaf.wrapVideoSample` → `encodeDataSegment`) byte-
1240
+ * for-byte per frame. Working hypothesis (pending Chromium-source
1241
+ * validation against `media/filters/chunk_demuxer.cc`):
1242
+ * `encodeMultiSampleSegment` blobs are accepted by ChunkDemuxer in this
1243
+ * pipeline but only the first sample renders for live, possibly because
1244
+ * the pipeline expects per-frame moof boundaries. Track in BLO-3035.
1245
+ *
1246
+ * Stale-tfdt defense-in-depth: drops any frame whose timestamp is older
1247
+ * than `#lastEmittedTs`. The SBN watermark already prevents out-of-order
1248
+ * FEC-block emissions, but `addBypassFrame` (oversized MFU / no-FEC path)
1249
+ * doesn't touch the watermark — a bypass frame at t=T followed by a FEC
1250
+ * block whose frames precede T would otherwise inject earlier tfdt and
1251
+ * detach the SourceBuffer. */
1252
+ #ordersSamples() {
1253
+ return this.#sampleOrder.mode === "media-window" || this.#sampleReorderWindow > 0;
1254
+ }
1255
+ #unwrapTimestamp(timestamp) {
1256
+ const wrapPeriod = this.#sampleOrder.mode === "media-window" ? this.#sampleOrder.timestampWrapPeriod : void 0;
1257
+ if (!wrapPeriod) return timestamp;
1258
+ const reference = this.#lastSourceTs >= 0 ? this.#lastSourceTs : this.#recoveredHorizonTs >= 0 ? this.#recoveredHorizonTs : this.#lastEmittedTs;
1259
+ if (reference < 0) return timestamp;
1260
+ return timestamp + Math.round((reference - timestamp) / wrapPeriod) * wrapPeriod;
1261
+ }
1262
+ #emitSample(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, synthetic) {
1263
+ if (authoredTiming !== void 0 && !this.#config.admitAuthoredTiming) {
1264
+ this.#sampleOrderStats.unadmittedAuthoredSamples++;
1265
+ return;
1266
+ }
1267
+ const scaledTiming = authoredTiming === void 0 ? null : scaleAuthoredTiming(authoredTiming, this.#config.timescale);
1268
+ if (authoredTiming !== void 0 && scaledTiming === null) return;
1269
+ const authoredTimestamp = scaledTiming?.timestamp ?? timestamp;
1270
+ const authoredDuration = scaledTiming?.duration ?? duration;
1271
+ let compositionTimeOffset;
1272
+ if (authoredTiming !== void 0) {
1273
+ const scaledOffset = scaleAuthoredTicks(
1274
+ authoredTiming.presentationTime - authoredTiming.decodeTime,
1275
+ authoredTiming.mediaTimescale,
1276
+ this.#config.timescale
1277
+ );
1278
+ if (scaledOffset === null) return;
1279
+ const roundedOffset = Math.round(scaledOffset);
1280
+ if (!Number.isSafeInteger(roundedOffset) || roundedOffset < INT32_MIN2 || roundedOffset > INT32_MAX2) return;
1281
+ compositionTimeOffset = roundedOffset;
1282
+ }
1283
+ const unwrappedTimestamp = this.#unwrapTimestamp(authoredTimestamp);
1284
+ if (unwrappedTimestamp <= this.#lastEmittedTs) {
1285
+ this.#sampleOrderStats.staleSamples++;
1286
+ return;
1287
+ }
1288
+ const sample = this.#withEffectiveVideoKeyframe({
1289
+ data,
1290
+ timestamp: unwrappedTimestamp,
1291
+ duration: authoredDuration,
1292
+ keyframe,
1293
+ ...mmtpTimestamp === void 0 ? {} : { mmtpTimestamp },
1294
+ ...compositionTimeOffset === void 0 ? {} : { compositionTimeOffset },
1295
+ advancesHorizon,
1296
+ ...authoredTiming === void 0 ? {} : { authoredTiming },
1297
+ ...packetSequenceNumber === void 0 ? {} : { packetSequenceNumber },
1298
+ ...packetSequenceNumbers === void 0 ? {} : { packetSequenceNumbers },
1299
+ ...repairedPacketSequenceNumbers === void 0 ? {} : { repairedPacketSequenceNumbers },
1300
+ ...mpuSequenceNumber === void 0 ? {} : { mpuSequenceNumber },
1301
+ ...movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber },
1302
+ ...sampleNumber === void 0 ? {} : { sampleNumber },
1303
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName },
1304
+ ...deliveryProvenance === void 0 ? {} : { deliveryProvenance },
1305
+ ...synthetic === void 0 ? {} : { synthetic }
1306
+ });
1307
+ if (advancesHorizon && unwrappedTimestamp > this.#lastSourceTs) {
1308
+ this.#lastSourceTs = unwrappedTimestamp;
1309
+ } else if (!advancesHorizon && unwrappedTimestamp > this.#recoveredHorizonTs) {
1310
+ this.#recoveredHorizonTs = unwrappedTimestamp;
1311
+ }
1312
+ if (this.#ordersSamples()) {
1313
+ this.#queueSample(sample);
1314
+ return;
1315
+ }
1316
+ this.#emitArrivalOrdered(sample);
1317
+ }
1318
+ #emitArrivalOrdered(sample) {
1319
+ if (this.#config.trackType === "video" && !this.#armedVideo && !sample.keyframe) {
1320
+ this.#sampleOrderStats.preRapDeadlineDrops++;
1321
+ return;
1322
+ }
1323
+ this.#emitSampleNow(sample);
1324
+ }
1325
+ #queueSample(sample) {
1326
+ if (this.#sampleReorderQueue.some((s) => s.timestamp === sample.timestamp)) {
1327
+ this.#sampleOrderStats.duplicateSamples++;
1328
+ return;
1329
+ }
1330
+ this.#sampleReorderQueue.push(sample);
1331
+ this.#sampleReorderQueue.sort((a, b) => a.timestamp - b.timestamp);
1332
+ this.#drainSampleReorder(false);
1333
+ this.#enforceSampleOrderCapacity();
1334
+ }
1335
+ #releaseHorizon() {
1336
+ return this.#lastSourceTs >= 0 ? this.#lastSourceTs : this.#recoveredHorizonTs;
1337
+ }
1338
+ #sampleIsReleasable(sample, flushAll) {
1339
+ if (flushAll) return true;
1340
+ if (this.#sampleOrder.mode === "media-window") {
1341
+ const horizon = this.#releaseHorizon();
1342
+ return horizon >= 0 && sample.timestamp < horizon - this.#sampleOrder.deliveryWindow;
1343
+ }
1344
+ return this.#sampleReorderQueue.length > this.#sampleReorderWindow;
1345
+ }
1346
+ #dropPreRapSamples(flushAll) {
1347
+ if (this.#config.trackType !== "video" || this.#armedVideo) return false;
1348
+ const firstRap = this.#sampleReorderQueue.findIndex(
1349
+ (sample) => sample.keyframe && this.#sampleIsReleasable(sample, flushAll)
1350
+ );
1351
+ if (firstRap >= 0) {
1352
+ if (firstRap > 0) {
1353
+ this.#sampleOrderStats.preRapDeadlineDrops += firstRap;
1354
+ this.#sampleReorderQueue.splice(0, firstRap);
1355
+ }
1356
+ return false;
1357
+ }
1358
+ let dropped = 0;
1359
+ while (this.#sampleReorderQueue[0] && this.#sampleIsReleasable(this.#sampleReorderQueue[0], flushAll)) {
1360
+ this.#sampleReorderQueue.shift();
1361
+ dropped++;
1362
+ }
1363
+ if (flushAll) this.#sampleOrderStats.noRapFlushDrops += dropped;
1364
+ else this.#sampleOrderStats.preRapDeadlineDrops += dropped;
1365
+ return dropped > 0;
1366
+ }
1367
+ #drainSampleReorder(flushAll) {
1368
+ while (this.#sampleReorderQueue.length > 0) {
1369
+ if (this.#dropPreRapSamples(flushAll) && this.#sampleReorderQueue.length === 0) return;
1370
+ const sample = this.#sampleReorderQueue[0];
1371
+ if (!sample || !this.#sampleIsReleasable(sample, flushAll)) return;
1372
+ this.#sampleReorderQueue.shift();
1373
+ this.#emitQueuedSample(sample);
1374
+ }
1375
+ }
1376
+ #emitQueuedSample(sample) {
1377
+ const next = this.#sampleReorderQueue.find((s) => s.timestamp > sample.timestamp);
1378
+ const duration = sample.authoredTiming ? sample.duration : next ? next.timestamp - sample.timestamp : sample.duration;
1379
+ this.#emitSampleNow({
1380
+ ...sample,
1381
+ duration: duration > 0 ? duration : sample.authoredTiming ? sample.duration : this.#frameDuration
1382
+ });
1383
+ }
1384
+ #enforceSampleOrderCapacity() {
1385
+ if (this.#sampleOrder.mode !== "media-window") return;
1386
+ while (this.#sampleReorderQueue.length > this.#sampleOrderCapacity) {
1387
+ const sample = this.#sampleReorderQueue.shift();
1388
+ if (!sample) return;
1389
+ this.#sampleOrderStats.forcedReleases++;
1390
+ console.warn(
1391
+ `[CmafBlockAssembler] ${this.#config.trackType} media-window queue exceeded ${this.#sampleOrderCapacity} samples; force-releasing timestamp=${sample.timestamp}`
1392
+ );
1393
+ if (this.#config.trackType === "video" && !this.#armedVideo && !sample.keyframe) {
1394
+ this.#sampleOrderStats.preRapDeadlineDrops++;
1395
+ continue;
1396
+ }
1397
+ this.#emitQueuedSample(sample);
1398
+ }
1399
+ }
1400
+ #emitSampleNow(sample) {
1401
+ if (sample.timestamp <= this.#lastEmittedTs) {
1402
+ this.#sampleOrderStats.staleSamples++;
1403
+ return;
1404
+ }
1405
+ this.#emitAudioGapFillNowBefore(sample.timestamp);
1406
+ this.#writeSampleNow(sample, true);
1407
+ }
1408
+ #writeSampleNow(sample, rememberAudio) {
1409
+ const { timestamp, duration, keyframe } = sample;
1410
+ this.#lastEmittedTs = timestamp;
1411
+ if (this.#config.trackType === "video" && keyframe) this.#armedVideo = true;
1412
+ const data = this.#normalizeSampleData(sample.data);
1413
+ if (this.#config.trackType === "audio" && rememberAudio && data.length > 0) {
1414
+ this.#lastDecodableAudioFrame = data.slice();
1415
+ }
1416
+ if (this.onSample) {
1417
+ this.onSample(data === sample.data ? sample : { ...sample, data });
1418
+ } else {
1419
+ const baseTime = this.#rebase(timestamp);
1420
+ const segment = encodeDataSegment(
1421
+ data,
1422
+ baseTime,
1423
+ duration,
1424
+ keyframe,
1425
+ this.#sequence++,
1426
+ this.#config.trackId,
1427
+ sample.compositionTimeOffset
1428
+ );
1429
+ this.onSegment?.(segment);
1430
+ }
1431
+ }
1432
+ #emitAudioGapFillNowBefore(timestamp) {
1433
+ if (this.#config.trackType !== "audio" || this.#lastEmittedTs < 0 || this.#lastDecodableAudioFrame === null) return;
1434
+ const gap = timestamp - this.#lastEmittedTs;
1435
+ if (gap <= this.#frameDuration * 1.5) return;
1436
+ const missingFrames = Math.max(0, Math.round(gap / this.#frameDuration) - 1);
1437
+ for (let i = 0; i < missingFrames; i++) {
1438
+ const fillTs = this.#lastEmittedTs + this.#frameDuration;
1439
+ this.#writeSampleNow({
1440
+ data: this.#lastDecodableAudioFrame.slice(),
1441
+ timestamp: fillTs,
1442
+ duration: this.#frameDuration,
1443
+ keyframe: true,
1444
+ synthetic: true
1445
+ }, false);
1446
+ }
1447
+ }
1448
+ #emitPerSample(frames, audioDurationOverride, advancesHorizon = false) {
1449
+ for (let i = 0; i < frames.length; i++) {
1450
+ const f = frames[i];
1451
+ let duration;
1452
+ if (this.#config.trackType === "audio") {
1453
+ duration = audioDurationOverride ?? this.#frameDuration;
1454
+ } else if (i < frames.length - 1) {
1455
+ duration = frames[i + 1].timestamp - f.timestamp;
1456
+ } else if (i > 0) {
1457
+ duration = f.timestamp - frames[i - 1].timestamp;
1458
+ } else {
1459
+ duration = audioDurationOverride ?? this.#frameDuration;
1460
+ }
1461
+ if (duration <= 0) duration = audioDurationOverride ?? this.#frameDuration;
1462
+ this.#emitSample(
1463
+ f.data,
1464
+ f.timestamp,
1465
+ duration,
1466
+ f.keyframe,
1467
+ advancesHorizon,
1468
+ f.catalogTrackName,
1469
+ f.mpuSequenceNumber,
1470
+ f.packetSequenceNumber,
1471
+ f.packetSequenceNumbers,
1472
+ f.repairedPacketSequenceNumbers,
1473
+ f.authoredTiming,
1474
+ f.deliveryProvenance,
1475
+ f.mmtpTimestamp,
1476
+ f.movieFragmentSequenceNumber,
1477
+ f.sampleNumber,
1478
+ f.synthetic
1479
+ );
1480
+ }
1481
+ }
1482
+ #emitStats;
1483
+ #countEmit(samples) {
1484
+ this.#emitStats.emits++;
1485
+ this.#emitStats.samples += samples.length;
1486
+ for (const sample of samples) if (sample.keyframe) this.#emitStats.keyframes++;
1198
1487
  }
1199
1488
  get sampleOrderStats() {
1200
- return { ...__privateGet(this, _sampleOrderStats) };
1489
+ return { ...this.#sampleOrderStats };
1490
+ }
1491
+ /** Cumulative emit and block-event counters since construction. */
1492
+ get emitStats() {
1493
+ return { ...this.#emitStats };
1201
1494
  }
1202
1495
  /** Emit a single frame immediately as a one-sample moof+mdat segment.
1203
1496
  *
@@ -1218,57 +1511,87 @@ var CmafBlockAssembler = class {
1218
1511
  addFrame(sbn, esi, data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber) {
1219
1512
  void sbn;
1220
1513
  void esi;
1221
- __privateWrapper(this, _addFrameCount)._++;
1222
- __privateMethod(this, _CmafBlockAssembler_instances, startAggregateTimer_fn).call(this);
1223
- if (!__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) __privateMethod(this, _CmafBlockAssembler_instances, drainRecoveredUpTo_fn).call(this, timestamp);
1224
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, data, timestamp, __privateGet(this, _frameDuration), keyframe, true, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, void 0);
1225
- __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "addFrame-direct", [{ data, timestamp, keyframe }]);
1514
+ this.#emitStats.addedFrames++;
1515
+ if (!this.#ordersSamples()) this.#drainRecoveredUpTo(timestamp);
1516
+ this.#emitSample(
1517
+ data,
1518
+ timestamp,
1519
+ this.#frameDuration,
1520
+ keyframe,
1521
+ true,
1522
+ catalogTrackName,
1523
+ mpuSequenceNumber,
1524
+ packetSequenceNumber,
1525
+ packetSequenceNumbers,
1526
+ repairedPacketSequenceNumbers,
1527
+ authoredTiming,
1528
+ deliveryProvenance,
1529
+ mmtpTimestamp,
1530
+ movieFragmentSequenceNumber,
1531
+ sampleNumber,
1532
+ void 0
1533
+ );
1534
+ this.#countEmit([{ keyframe }]);
1226
1535
  }
1227
1536
  /** Mark a block as complete (all K source symbols received or FEC recovery succeeded).
1228
1537
  * If all frames are already buffered, flushes immediately. Otherwise sets pending-flush. */
1229
1538
  completeBlock(sbn) {
1230
1539
  void sbn;
1231
- __privateWrapper(this, _completeBlockCount)._++;
1232
- __privateMethod(this, _CmafBlockAssembler_instances, startAggregateTimer_fn).call(this);
1540
+ this.#emitStats.completedBlocks++;
1233
1541
  }
1234
1542
  /** Handle block timeout — emit whatever frames we have + fill for missing slots. */
1235
1543
  failBlock(sbn) {
1236
- __privateWrapper(this, _failBlockCount)._++;
1237
- __privateMethod(this, _CmafBlockAssembler_instances, startAggregateTimer_fn).call(this);
1238
- __privateGet(this, _pendingFlush).delete(sbn);
1239
- const block = __privateGet(this, _blocks).get(sbn);
1544
+ this.#emitStats.failedBlocks++;
1545
+ this.#pendingFlush.delete(sbn);
1546
+ const block = this.#blocks.get(sbn);
1240
1547
  if (!block || block.size === 0) {
1241
- __privateGet(this, _blocks).delete(sbn);
1548
+ this.#blocks.delete(sbn);
1242
1549
  return;
1243
1550
  }
1244
- __privateMethod(this, _CmafBlockAssembler_instances, flushBlockWithFill_fn).call(this, sbn);
1551
+ this.#flushBlockWithFill(sbn);
1245
1552
  }
1246
1553
  /** Add all frames from a FEC-recovered block at once and emit immediately. */
1247
1554
  addRecoveredBlock(sbn, frames) {
1248
1555
  void sbn;
1249
- __privateWrapper(this, _recoveredBlockCount)._++;
1250
- __privateMethod(this, _CmafBlockAssembler_instances, startAggregateTimer_fn).call(this);
1251
- __privateGet(this, _pendingFlush).delete(sbn);
1252
- __privateGet(this, _blocks).delete(sbn);
1556
+ this.#emitStats.recoveredBlocks++;
1557
+ this.#pendingFlush.delete(sbn);
1558
+ this.#blocks.delete(sbn);
1253
1559
  if (frames.length === 0) return;
1254
- const normalized = __privateMethod(this, _CmafBlockAssembler_instances, normalizeVideoKeyframes_fn).call(this, frames);
1255
- __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "addRecoveredBlock", normalized, sbn);
1256
- if (__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) {
1257
- __privateMethod(this, _CmafBlockAssembler_instances, emitPerSample_fn).call(this, normalized, void 0, false);
1560
+ const normalized = this.#normalizeVideoKeyframes(frames);
1561
+ this.#countEmit(normalized);
1562
+ if (this.#ordersSamples()) {
1563
+ this.#emitPerSample(normalized, void 0, false);
1258
1564
  return;
1259
1565
  }
1260
- if (__privateGet(this, _lastSourceTs) >= 0) {
1261
- __privateMethod(this, _CmafBlockAssembler_instances, enqueueRecovered_fn).call(this, normalized);
1262
- __privateMethod(this, _CmafBlockAssembler_instances, drainRecoveredUpTo_fn).call(this, __privateGet(this, _lastSourceTs));
1566
+ if (this.#lastSourceTs >= 0) {
1567
+ this.#enqueueRecovered(normalized);
1568
+ this.#drainRecoveredUpTo(this.#lastSourceTs);
1263
1569
  } else {
1264
- const gated = __privateMethod(this, _CmafBlockAssembler_instances, applyVideoKeyframeGate_fn).call(this, normalized);
1265
- if (gated) __privateMethod(this, _CmafBlockAssembler_instances, emitPerSample_fn).call(this, gated, void 0, false);
1570
+ const gated = this.#applyVideoKeyframeGate(normalized);
1571
+ if (gated) this.#emitPerSample(gated, void 0, false);
1266
1572
  }
1267
1573
  }
1268
1574
  /** Emit a single frame immediately as a one-sample segment (for oversized packets bypassing FEC). */
1269
1575
  addBypassFrame(data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber) {
1270
- if (!__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) __privateMethod(this, _CmafBlockAssembler_instances, drainRecoveredUpTo_fn).call(this, timestamp);
1271
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, data, timestamp, __privateGet(this, _frameDuration), keyframe, true, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, void 0);
1576
+ if (!this.#ordersSamples()) this.#drainRecoveredUpTo(timestamp);
1577
+ this.#emitSample(
1578
+ data,
1579
+ timestamp,
1580
+ this.#frameDuration,
1581
+ keyframe,
1582
+ true,
1583
+ catalogTrackName,
1584
+ mpuSequenceNumber,
1585
+ packetSequenceNumber,
1586
+ packetSequenceNumbers,
1587
+ repairedPacketSequenceNumbers,
1588
+ authoredTiming,
1589
+ deliveryProvenance,
1590
+ mmtpTimestamp,
1591
+ movieFragmentSequenceNumber,
1592
+ sampleNumber,
1593
+ void 0
1594
+ );
1272
1595
  }
1273
1596
  /** Build and emit init segment from catalog config. */
1274
1597
  emitInit() {
@@ -1278,476 +1601,160 @@ var CmafBlockAssembler = class {
1278
1601
  this._videoConfig.avcC,
1279
1602
  this._videoConfig.width,
1280
1603
  this._videoConfig.height,
1281
- __privateGet(this, _config).timescale,
1282
- __privateGet(this, _config).trackId
1604
+ this.#config.timescale,
1605
+ this.#config.trackId
1283
1606
  );
1284
1607
  } else if (this._audioConfig) {
1285
1608
  init = buildAudioInitSegment(
1286
1609
  this._audioConfig.sampleRate,
1287
1610
  this._audioConfig.channels,
1288
1611
  this._audioConfig.asc,
1289
- __privateGet(this, _config).timescale,
1290
- __privateGet(this, _config).trackId
1612
+ this.#config.timescale,
1613
+ this.#config.trackId
1291
1614
  );
1292
1615
  }
1293
1616
  if (init) this.onInitSegment?.(init);
1294
1617
  }
1295
1618
  /** Drain all ordered samples at end-of-stream or before reconfiguration. */
1296
1619
  flush() {
1297
- if (__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) {
1298
- __privateMethod(this, _CmafBlockAssembler_instances, drainSampleReorder_fn).call(this, true);
1620
+ if (this.#ordersSamples()) {
1621
+ this.#drainSampleReorder(true);
1299
1622
  return;
1300
1623
  }
1301
- if (__privateGet(this, _pendingRecovered).size === 0) return;
1302
- const frames = [...__privateGet(this, _pendingRecovered).values()].sort((a, b) => a.timestamp - b.timestamp);
1303
- __privateGet(this, _pendingRecovered).clear();
1304
- const gated = __privateMethod(this, _CmafBlockAssembler_instances, applyVideoKeyframeGate_fn).call(this, frames);
1305
- if (gated) __privateMethod(this, _CmafBlockAssembler_instances, emitPerSample_fn).call(this, gated, void 0, false);
1306
- else if (__privateGet(this, _config).trackType === "video") {
1307
- __privateGet(this, _sampleOrderStats).noRapFlushDrops += frames.length;
1624
+ if (this.#pendingRecovered.size === 0) return;
1625
+ const frames = [...this.#pendingRecovered.values()].sort((a, b) => a.timestamp - b.timestamp);
1626
+ this.#pendingRecovered.clear();
1627
+ const gated = this.#applyVideoKeyframeGate(frames);
1628
+ if (gated) this.#emitPerSample(gated, void 0, false);
1629
+ else if (this.#config.trackType === "video") {
1630
+ this.#sampleOrderStats.noRapFlushDrops += frames.length;
1308
1631
  }
1309
1632
  }
1310
1633
  /** Drop all queued state and begin a fresh timestamp epoch. */
1311
1634
  reset() {
1312
- __privateGet(this, _blocks).clear();
1313
- __privateGet(this, _pendingFlush).clear();
1314
- __privateGet(this, _pendingRecovered).clear();
1315
- __privateSet(this, _sequence, 1);
1316
- __privateSet(this, _baseTs, -1);
1317
- __privateSet(this, _lastEmittedTs, -1);
1318
- __privateSet(this, _lastSourceTs, -1);
1319
- __privateSet(this, _recoveredHorizonTs, -1);
1320
- __privateSet(this, _lastDecodableAudioFrame, null);
1321
- __privateSet(this, _armedVideo, false);
1322
- __privateSet(this, _lastEmittedSbn, -1);
1323
- __privateSet(this, _sampleReorderQueue, []);
1635
+ this.#blocks.clear();
1636
+ this.#pendingFlush.clear();
1637
+ this.#pendingRecovered.clear();
1638
+ this.#sequence = 1;
1639
+ this.#baseTs = -1;
1640
+ this.#lastEmittedTs = -1;
1641
+ this.#lastSourceTs = -1;
1642
+ this.#recoveredHorizonTs = -1;
1643
+ this.#lastDecodableAudioFrame = null;
1644
+ this.#armedVideo = false;
1645
+ this.#lastEmittedSbn = -1;
1646
+ this.#sampleReorderQueue = [];
1324
1647
  }
1325
1648
  dispose() {
1326
1649
  this.reset();
1327
1650
  this.onSegment = null;
1328
1651
  this.onSample = null;
1329
1652
  this.onInitSegment = null;
1330
- if (__privateGet(this, _aggregateTimer)) {
1331
- clearInterval(__privateGet(this, _aggregateTimer));
1332
- __privateSet(this, _aggregateTimer, null);
1333
- }
1334
1653
  }
1335
- };
1336
- _config = new WeakMap();
1337
- _blocks = new WeakMap();
1338
- _pendingFlush = new WeakMap();
1339
- _pendingRecovered = new WeakMap();
1340
- _sequence = new WeakMap();
1341
- _baseTs = new WeakMap();
1342
- _fillFrame = new WeakMap();
1343
- _lastDecodableAudioFrame = new WeakMap();
1344
- _frameDuration = new WeakMap();
1345
- _lastEmittedTs = new WeakMap();
1346
- _lastSourceTs = new WeakMap();
1347
- _sampleReorderWindow = new WeakMap();
1348
- _sampleOrder = new WeakMap();
1349
- _sampleOrderCapacity = new WeakMap();
1350
- _sampleReorderQueue = new WeakMap();
1351
- _recoveredHorizonTs = new WeakMap();
1352
- _sampleOrderStats = new WeakMap();
1353
- _validateH264Keyframes = new WeakMap();
1354
- _keyframeRejectDumpCount = new WeakMap();
1355
- _armedVideo = new WeakMap();
1356
- _lastEmittedSbn = new WeakMap();
1357
- _CmafBlockAssembler_instances = new WeakSet();
1358
- /** Attempt to claim emission for `sbn`. Returns true if `sbn` is past
1359
- * the watermark (and advances it); false if this sbn has already been
1360
- * claimed or is older (caller should drop). */
1361
- claimSbnEmission_fn = function(sbn) {
1362
- if (sbn <= __privateGet(this, _lastEmittedSbn)) return false;
1363
- __privateSet(this, _lastEmittedSbn, sbn);
1364
- return true;
1365
- };
1366
- /** Truncate `frames` to start at the first keyframe for video tracks before
1367
- * the first emission. Returns the (possibly spliced) frames, or null to
1368
- * drop the block entirely. Audio + already-armed video: identity. */
1369
- applyVideoKeyframeGate_fn = function(frames) {
1370
- const keyedFrames = __privateMethod(this, _CmafBlockAssembler_instances, normalizeVideoKeyframes_fn).call(this, frames);
1371
- if (__privateGet(this, _config).trackType !== "video" || __privateGet(this, _armedVideo)) return keyedFrames;
1372
- const firstKfIdx = keyedFrames.findIndex((f) => f.keyframe);
1373
- if (firstKfIdx < 0) return null;
1374
- return firstKfIdx === 0 ? keyedFrames : keyedFrames.slice(firstKfIdx);
1375
- };
1376
- normalizeVideoKeyframes_fn = function(frames) {
1377
- if (__privateGet(this, _config).trackType !== "video" || !__privateGet(this, _validateH264Keyframes)) return frames;
1378
- return frames.map((frame) => __privateMethod(this, _CmafBlockAssembler_instances, withEffectiveVideoKeyframe_fn).call(this, frame));
1379
- };
1380
- withEffectiveVideoKeyframe_fn = function(frame) {
1381
- if (__privateGet(this, _config).trackType !== "video" || !__privateGet(this, _validateH264Keyframes)) return frame;
1382
- const keyframe = detectH264Keyframe(frame.data);
1383
- if (!keyframe) __privateMethod(this, _CmafBlockAssembler_instances, dumpRejectedVideoKeyframe_fn).call(this, frame.data, frame.keyframe);
1384
- return keyframe === frame.keyframe ? frame : { ...frame, keyframe };
1385
- };
1386
- dumpRejectedVideoKeyframe_fn = function(data, metadataKeyframe) {
1387
- if (__privateGet(this, _keyframeRejectDumpCount) >= 12) return;
1388
- __privateWrapper(this, _keyframeRejectDumpCount)._++;
1389
- const sample = splitH264SampleNalUnits(data);
1390
- const nalTypes = describeH264NalTypes(sample.nals);
1391
- const classify = classifyH264Keyframe(data);
1392
- const hex = Array.from(data.subarray(0, Math.min(48, data.length))).map((b) => b.toString(16).padStart(2, "0")).join(" ");
1393
- console.log(
1394
- `[L4-KF-GATE] reject#${__privateGet(this, _keyframeRejectDumpCount)} len=${data.length} metadataKf=${metadataKeyframe} classify=${classify} format=${sample.format} nalTypes=[${nalTypes.join(",")}] first48=[${hex}]`
1395
- );
1396
- };
1397
- /** Emit each frame as its own single-sample moof+mdat segment. Matches the
1398
- * case-20 path (`MmtpToCmaf.wrapVideoSample` → `encodeDataSegment`) byte-
1399
- * for-byte per frame. Working hypothesis (pending Chromium-source
1400
- * validation against `media/filters/chunk_demuxer.cc`):
1401
- * `encodeMultiSampleSegment` blobs are accepted by ChunkDemuxer in this
1402
- * pipeline but only the first sample renders for live, possibly because
1403
- * the pipeline expects per-frame moof boundaries. Track in BLO-3035.
1404
- *
1405
- * Stale-tfdt defense-in-depth: drops any frame whose timestamp is older
1406
- * than `#lastEmittedTs`. The SBN watermark already prevents out-of-order
1407
- * FEC-block emissions, but `addBypassFrame` (oversized MFU / no-FEC path)
1408
- * doesn't touch the watermark — a bypass frame at t=T followed by a FEC
1409
- * block whose frames precede T would otherwise inject earlier tfdt and
1410
- * detach the SourceBuffer. */
1411
- ordersSamples_fn = function() {
1412
- return __privateGet(this, _sampleOrder).mode === "media-window" || __privateGet(this, _sampleReorderWindow) > 0;
1413
- };
1414
- unwrapTimestamp_fn = function(timestamp) {
1415
- const wrapPeriod = __privateGet(this, _sampleOrder).mode === "media-window" ? __privateGet(this, _sampleOrder).timestampWrapPeriod : void 0;
1416
- if (!wrapPeriod) return timestamp;
1417
- const reference = __privateGet(this, _lastSourceTs) >= 0 ? __privateGet(this, _lastSourceTs) : __privateGet(this, _recoveredHorizonTs) >= 0 ? __privateGet(this, _recoveredHorizonTs) : __privateGet(this, _lastEmittedTs);
1418
- if (reference < 0) return timestamp;
1419
- return timestamp + Math.round((reference - timestamp) / wrapPeriod) * wrapPeriod;
1420
- };
1421
- emitSample_fn = function(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, synthetic) {
1422
- const scaledTiming = authoredTiming === void 0 ? null : scaleAuthoredTiming(authoredTiming, __privateGet(this, _config).timescale);
1423
- if (authoredTiming !== void 0 && scaledTiming === null) return;
1424
- const authoredTimestamp = scaledTiming?.timestamp ?? timestamp;
1425
- const authoredDuration = scaledTiming?.duration ?? duration;
1426
- let compositionTimeOffset;
1427
- if (authoredTiming !== void 0) {
1428
- const scaledOffset = scaleAuthoredTicks(
1429
- authoredTiming.presentationTime - authoredTiming.decodeTime,
1430
- authoredTiming.mediaTimescale,
1431
- __privateGet(this, _config).timescale
1432
- );
1433
- if (scaledOffset === null) return;
1434
- const roundedOffset = Math.round(scaledOffset);
1435
- if (!Number.isSafeInteger(roundedOffset) || roundedOffset < INT32_MIN2 || roundedOffset > INT32_MAX2) return;
1436
- compositionTimeOffset = roundedOffset;
1654
+ // ── Private ──
1655
+ /** Rebase an absolute timestamp to relative media time (starting near 0). */
1656
+ #rebase(timestamp) {
1657
+ if (this.#baseTs < 0) this.#baseTs = timestamp;
1658
+ return timestamp - this.#baseTs;
1437
1659
  }
1438
- const unwrappedTimestamp = __privateMethod(this, _CmafBlockAssembler_instances, unwrapTimestamp_fn).call(this, authoredTimestamp);
1439
- if (unwrappedTimestamp <= __privateGet(this, _lastEmittedTs)) {
1440
- __privateGet(this, _sampleOrderStats).staleSamples++;
1441
- return;
1442
- }
1443
- const sample = __privateMethod(this, _CmafBlockAssembler_instances, withEffectiveVideoKeyframe_fn).call(this, {
1444
- data,
1445
- timestamp: unwrappedTimestamp,
1446
- duration: authoredDuration,
1447
- keyframe,
1448
- ...mmtpTimestamp === void 0 ? {} : { mmtpTimestamp },
1449
- ...compositionTimeOffset === void 0 ? {} : { compositionTimeOffset },
1450
- advancesHorizon,
1451
- ...authoredTiming === void 0 ? {} : { authoredTiming },
1452
- ...packetSequenceNumber === void 0 ? {} : { packetSequenceNumber },
1453
- ...packetSequenceNumbers === void 0 ? {} : { packetSequenceNumbers },
1454
- ...repairedPacketSequenceNumbers === void 0 ? {} : { repairedPacketSequenceNumbers },
1455
- ...mpuSequenceNumber === void 0 ? {} : { mpuSequenceNumber },
1456
- ...movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber },
1457
- ...sampleNumber === void 0 ? {} : { sampleNumber },
1458
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
1459
- ...deliveryProvenance === void 0 ? {} : { deliveryProvenance },
1460
- ...synthetic === void 0 ? {} : { synthetic }
1461
- });
1462
- if (advancesHorizon && unwrappedTimestamp > __privateGet(this, _lastSourceTs)) {
1463
- __privateSet(this, _lastSourceTs, unwrappedTimestamp);
1464
- } else if (!advancesHorizon && unwrappedTimestamp > __privateGet(this, _recoveredHorizonTs)) {
1465
- __privateSet(this, _recoveredHorizonTs, unwrappedTimestamp);
1660
+ #normalizeSampleData(data) {
1661
+ return this.#config.trackType === "audio" ? normalizeAacSampleForCmaf(data) : data;
1466
1662
  }
1467
- if (__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) {
1468
- __privateMethod(this, _CmafBlockAssembler_instances, queueSample_fn).call(this, sample);
1469
- return;
1470
- }
1471
- __privateMethod(this, _CmafBlockAssembler_instances, emitArrivalOrdered_fn).call(this, sample);
1472
- };
1473
- emitArrivalOrdered_fn = function(sample) {
1474
- if (__privateGet(this, _config).trackType === "video" && !__privateGet(this, _armedVideo) && !sample.keyframe) {
1475
- __privateGet(this, _sampleOrderStats).preRapDeadlineDrops++;
1476
- return;
1477
- }
1478
- __privateMethod(this, _CmafBlockAssembler_instances, emitSampleNow_fn).call(this, sample);
1479
- };
1480
- queueSample_fn = function(sample) {
1481
- if (__privateGet(this, _sampleReorderQueue).some((s) => s.timestamp === sample.timestamp)) {
1482
- __privateGet(this, _sampleOrderStats).duplicateSamples++;
1483
- return;
1484
- }
1485
- __privateGet(this, _sampleReorderQueue).push(sample);
1486
- __privateGet(this, _sampleReorderQueue).sort((a, b) => a.timestamp - b.timestamp);
1487
- __privateMethod(this, _CmafBlockAssembler_instances, drainSampleReorder_fn).call(this, false);
1488
- __privateMethod(this, _CmafBlockAssembler_instances, enforceSampleOrderCapacity_fn).call(this);
1489
- };
1490
- releaseHorizon_fn = function() {
1491
- return __privateGet(this, _lastSourceTs) >= 0 ? __privateGet(this, _lastSourceTs) : __privateGet(this, _recoveredHorizonTs);
1492
- };
1493
- sampleIsReleasable_fn = function(sample, flushAll) {
1494
- if (flushAll) return true;
1495
- if (__privateGet(this, _sampleOrder).mode === "media-window") {
1496
- const horizon = __privateMethod(this, _CmafBlockAssembler_instances, releaseHorizon_fn).call(this);
1497
- return horizon >= 0 && sample.timestamp < horizon - __privateGet(this, _sampleOrder).deliveryWindow;
1498
- }
1499
- return __privateGet(this, _sampleReorderQueue).length > __privateGet(this, _sampleReorderWindow);
1500
- };
1501
- dropPreRapSamples_fn = function(flushAll) {
1502
- if (__privateGet(this, _config).trackType !== "video" || __privateGet(this, _armedVideo)) return false;
1503
- const firstRap = __privateGet(this, _sampleReorderQueue).findIndex(
1504
- (sample) => sample.keyframe && __privateMethod(this, _CmafBlockAssembler_instances, sampleIsReleasable_fn).call(this, sample, flushAll)
1505
- );
1506
- if (firstRap >= 0) {
1507
- if (firstRap > 0) {
1508
- __privateGet(this, _sampleOrderStats).preRapDeadlineDrops += firstRap;
1509
- __privateGet(this, _sampleReorderQueue).splice(0, firstRap);
1663
+ #enqueueRecovered(frames) {
1664
+ for (const frame of frames) {
1665
+ if (this.#lastEmittedTs >= 0 && frame.timestamp <= this.#lastEmittedTs) {
1666
+ this.#sampleOrderStats.staleSamples++;
1667
+ continue;
1668
+ }
1669
+ if (this.#pendingRecovered.has(frame.timestamp)) {
1670
+ this.#sampleOrderStats.duplicateSamples++;
1671
+ continue;
1672
+ }
1673
+ this.#pendingRecovered.set(frame.timestamp, frame);
1510
1674
  }
1511
- return false;
1512
- }
1513
- let dropped = 0;
1514
- while (__privateGet(this, _sampleReorderQueue)[0] && __privateMethod(this, _CmafBlockAssembler_instances, sampleIsReleasable_fn).call(this, __privateGet(this, _sampleReorderQueue)[0], flushAll)) {
1515
- __privateGet(this, _sampleReorderQueue).shift();
1516
- dropped++;
1517
1675
  }
1518
- if (flushAll) __privateGet(this, _sampleOrderStats).noRapFlushDrops += dropped;
1519
- else __privateGet(this, _sampleOrderStats).preRapDeadlineDrops += dropped;
1520
- return dropped > 0;
1521
- };
1522
- drainSampleReorder_fn = function(flushAll) {
1523
- while (__privateGet(this, _sampleReorderQueue).length > 0) {
1524
- if (__privateMethod(this, _CmafBlockAssembler_instances, dropPreRapSamples_fn).call(this, flushAll) && __privateGet(this, _sampleReorderQueue).length === 0) return;
1525
- const sample = __privateGet(this, _sampleReorderQueue)[0];
1526
- if (!sample || !__privateMethod(this, _CmafBlockAssembler_instances, sampleIsReleasable_fn).call(this, sample, flushAll)) return;
1527
- __privateGet(this, _sampleReorderQueue).shift();
1528
- __privateMethod(this, _CmafBlockAssembler_instances, emitQueuedSample_fn).call(this, sample);
1529
- }
1530
- };
1531
- emitQueuedSample_fn = function(sample) {
1532
- const next = __privateGet(this, _sampleReorderQueue).find((s) => s.timestamp > sample.timestamp);
1533
- const duration = sample.authoredTiming ? sample.duration : next ? next.timestamp - sample.timestamp : sample.duration;
1534
- __privateMethod(this, _CmafBlockAssembler_instances, emitSampleNow_fn).call(this, {
1535
- ...sample,
1536
- duration: duration > 0 ? duration : sample.authoredTiming ? sample.duration : __privateGet(this, _frameDuration)
1537
- });
1538
- };
1539
- enforceSampleOrderCapacity_fn = function() {
1540
- if (__privateGet(this, _sampleOrder).mode !== "media-window") return;
1541
- while (__privateGet(this, _sampleReorderQueue).length > __privateGet(this, _sampleOrderCapacity)) {
1542
- const sample = __privateGet(this, _sampleReorderQueue).shift();
1543
- if (!sample) return;
1544
- __privateGet(this, _sampleOrderStats).forcedReleases++;
1545
- console.warn(
1546
- `[CmafBlockAssembler] ${__privateGet(this, _config).trackType} media-window queue exceeded ${__privateGet(this, _sampleOrderCapacity)} samples; force-releasing timestamp=${sample.timestamp}`
1547
- );
1548
- if (__privateGet(this, _config).trackType === "video" && !__privateGet(this, _armedVideo) && !sample.keyframe) {
1549
- __privateGet(this, _sampleOrderStats).preRapDeadlineDrops++;
1550
- continue;
1676
+ #drainRecoveredUpTo(horizonTs) {
1677
+ if (this.#pendingRecovered.size === 0) return;
1678
+ const ready = [...this.#pendingRecovered.values()].filter((frame) => frame.timestamp <= horizonTs).sort((a, b) => a.timestamp - b.timestamp);
1679
+ for (const frame of ready) {
1680
+ this.#pendingRecovered.delete(frame.timestamp);
1681
+ this.#emitSample(
1682
+ frame.data,
1683
+ frame.timestamp,
1684
+ this.#frameDuration,
1685
+ frame.keyframe,
1686
+ false,
1687
+ frame.catalogTrackName,
1688
+ frame.mpuSequenceNumber,
1689
+ frame.packetSequenceNumber,
1690
+ frame.packetSequenceNumbers,
1691
+ frame.repairedPacketSequenceNumbers,
1692
+ frame.authoredTiming,
1693
+ frame.deliveryProvenance,
1694
+ frame.mmtpTimestamp,
1695
+ frame.movieFragmentSequenceNumber,
1696
+ frame.sampleNumber,
1697
+ frame.synthetic
1698
+ );
1699
+ this.#countEmit([frame]);
1551
1700
  }
1552
- __privateMethod(this, _CmafBlockAssembler_instances, emitQueuedSample_fn).call(this, sample);
1553
- }
1554
- };
1555
- emitSampleNow_fn = function(sample) {
1556
- if (sample.timestamp <= __privateGet(this, _lastEmittedTs)) {
1557
- __privateGet(this, _sampleOrderStats).staleSamples++;
1558
- return;
1559
- }
1560
- __privateMethod(this, _CmafBlockAssembler_instances, emitAudioGapFillNowBefore_fn).call(this, sample.timestamp);
1561
- __privateMethod(this, _CmafBlockAssembler_instances, writeSampleNow_fn).call(this, sample, true);
1562
- };
1563
- writeSampleNow_fn = function(sample, rememberAudio) {
1564
- const { timestamp, duration, keyframe } = sample;
1565
- __privateSet(this, _lastEmittedTs, timestamp);
1566
- if (__privateGet(this, _config).trackType === "video" && keyframe) __privateSet(this, _armedVideo, true);
1567
- const data = __privateMethod(this, _CmafBlockAssembler_instances, normalizeSampleData_fn).call(this, sample.data);
1568
- if (__privateGet(this, _config).trackType === "audio" && rememberAudio && data.length > 0) {
1569
- __privateSet(this, _lastDecodableAudioFrame, data.slice());
1570
1701
  }
1571
- if (this.onSample) {
1572
- this.onSample(data === sample.data ? sample : { ...sample, data });
1573
- } else {
1574
- const baseTime = __privateMethod(this, _CmafBlockAssembler_instances, rebase_fn).call(this, timestamp);
1575
- const segment = encodeDataSegment(
1576
- data,
1577
- baseTime,
1578
- duration,
1579
- keyframe,
1580
- __privateWrapper(this, _sequence)._++,
1581
- __privateGet(this, _config).trackId,
1582
- sample.compositionTimeOffset
1583
- );
1584
- this.onSegment?.(segment);
1585
- }
1586
- };
1587
- emitAudioGapFillNowBefore_fn = function(timestamp) {
1588
- if (__privateGet(this, _config).trackType !== "audio" || __privateGet(this, _lastEmittedTs) < 0 || __privateGet(this, _lastDecodableAudioFrame) === null) return;
1589
- const gap = timestamp - __privateGet(this, _lastEmittedTs);
1590
- if (gap <= __privateGet(this, _frameDuration) * 1.5) return;
1591
- const missingFrames = Math.max(0, Math.round(gap / __privateGet(this, _frameDuration)) - 1);
1592
- for (let i = 0; i < missingFrames; i++) {
1593
- const fillTs = __privateGet(this, _lastEmittedTs) + __privateGet(this, _frameDuration);
1594
- __privateMethod(this, _CmafBlockAssembler_instances, writeSampleNow_fn).call(this, {
1595
- data: __privateGet(this, _lastDecodableAudioFrame).slice(),
1596
- timestamp: fillTs,
1597
- duration: __privateGet(this, _frameDuration),
1598
- keyframe: true,
1599
- synthetic: true
1600
- }, false);
1601
- }
1602
- };
1603
- emitPerSample_fn = function(frames, audioDurationOverride, advancesHorizon = false) {
1604
- for (let i = 0; i < frames.length; i++) {
1605
- const f = frames[i];
1606
- let duration;
1607
- if (__privateGet(this, _config).trackType === "audio") {
1608
- duration = audioDurationOverride ?? __privateGet(this, _frameDuration);
1609
- } else if (i < frames.length - 1) {
1610
- duration = frames[i + 1].timestamp - f.timestamp;
1611
- } else if (i > 0) {
1612
- duration = f.timestamp - frames[i - 1].timestamp;
1613
- } else {
1614
- duration = audioDurationOverride ?? __privateGet(this, _frameDuration);
1702
+ /** Flush a block's buffered frames as a multi-sample CMAF segment. */
1703
+ #flushBlock(sbn) {
1704
+ const block = this.#blocks.get(sbn);
1705
+ if (!block || block.size === 0) {
1706
+ this.#blocks.delete(sbn);
1707
+ return;
1615
1708
  }
1616
- if (duration <= 0) duration = audioDurationOverride ?? __privateGet(this, _frameDuration);
1617
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, f.data, f.timestamp, duration, f.keyframe, advancesHorizon, f.catalogTrackName, f.mpuSequenceNumber, f.packetSequenceNumber, f.packetSequenceNumbers, f.repairedPacketSequenceNumbers, f.authoredTiming, f.deliveryProvenance, f.mmtpTimestamp, f.movieFragmentSequenceNumber, f.sampleNumber, f.synthetic);
1709
+ const entries = [...block.entries()].sort((a, b) => a[0] - b[0]);
1710
+ const sortedFrames = entries.map(([, f]) => f);
1711
+ this.#blocks.delete(sbn);
1712
+ if (!this.#claimSbnEmission(sbn)) return;
1713
+ const frames = this.#applyVideoKeyframeGate(sortedFrames);
1714
+ if (!frames) return;
1715
+ this.#countEmit(frames);
1716
+ this.#emitPerSample(frames);
1618
1717
  }
1619
- };
1620
- _dumpCount = new WeakMap();
1621
- _emitCount = new WeakMap();
1622
- _sampleCount = new WeakMap();
1623
- _keyframeCount = new WeakMap();
1624
- _addFrameCount = new WeakMap();
1625
- _recoveredBlockCount = new WeakMap();
1626
- _completeBlockCount = new WeakMap();
1627
- _failBlockCount = new WeakMap();
1628
- _aggregateTimer = new WeakMap();
1629
- startAggregateTimer_fn = function() {
1630
- if (__privateGet(this, _aggregateTimer)) return;
1631
- __privateSet(this, _aggregateTimer, setInterval(() => {
1632
- const order = __privateGet(this, _sampleOrderStats);
1633
- console.log(
1634
- `[L4-AGG-${__privateGet(this, _config).trackType}] emits=${__privateGet(this, _emitCount)} samples=${__privateGet(this, _sampleCount)} kf=${__privateGet(this, _keyframeCount)} addFrame=${__privateGet(this, _addFrameCount)} recovered=${__privateGet(this, _recoveredBlockCount)} complete=${__privateGet(this, _completeBlockCount)} fail=${__privateGet(this, _failBlockCount)} pendingBlocks=${__privateGet(this, _blocks).size} pendingFlushes=${__privateGet(this, _pendingFlush).size} armedVideo=${__privateGet(this, _armedVideo)} forced=${order.forcedReleases} stale=${order.staleSamples} dup=${order.duplicateSamples} preRap=${order.preRapDeadlineDrops} noRap=${order.noRapFlushDrops}`
1635
- );
1636
- __privateSet(this, _emitCount, 0);
1637
- __privateSet(this, _sampleCount, 0);
1638
- __privateSet(this, _keyframeCount, 0);
1639
- __privateSet(this, _addFrameCount, 0);
1640
- __privateSet(this, _recoveredBlockCount, 0);
1641
- __privateSet(this, _completeBlockCount, 0);
1642
- __privateSet(this, _failBlockCount, 0);
1643
- }, 1e3));
1644
- };
1645
- dumpEmit_fn = function(path, samples, sbn) {
1646
- __privateWrapper(this, _emitCount)._++;
1647
- __privateSet(this, _sampleCount, __privateGet(this, _sampleCount) + samples.length);
1648
- __privateSet(this, _keyframeCount, __privateGet(this, _keyframeCount) + samples.filter((s) => s.keyframe).length);
1649
- const anyKf = __privateGet(this, _config).trackType === "video" && samples.some((s) => s.keyframe);
1650
- if (__privateGet(this, _config).trackType !== "video" || __privateGet(this, _dumpCount) >= 6 && !anyKf) return;
1651
- __privateWrapper(this, _dumpCount)._++;
1652
- const s0 = samples[0];
1653
- if (!s0) return;
1654
- const d = s0.data;
1655
- const hex = Array.from(d.subarray(0, Math.min(48, d.length))).map((b) => b.toString(16).padStart(2, "0")).join(" ");
1656
- let h = 5381;
1657
- for (let i = 0; i < d.length; i++) h = h * 33 + d[i] | 0;
1658
- const hash = (h >>> 0).toString(16).padStart(8, "0");
1659
- const ts0 = s0.timestamp ?? -1;
1660
- const tsN = samples[samples.length - 1]?.timestamp ?? -1;
1661
- console.log(
1662
- `[L4-DIAG] EMIT#${__privateGet(this, _dumpCount)} path=${path}${sbn !== void 0 ? ` sbn=${sbn}` : ""} samples=${samples.length} s0.kf=${s0.keyframe} s0.len=${d.length} ts0=${ts0} tsN=${tsN} dur=${tsN - ts0} hash=${hash} first48=[${hex}]`
1663
- );
1664
- };
1665
- // ── Private ──
1666
- /** Rebase an absolute timestamp to relative media time (starting near 0). */
1667
- rebase_fn = function(timestamp) {
1668
- if (__privateGet(this, _baseTs) < 0) __privateSet(this, _baseTs, timestamp);
1669
- return timestamp - __privateGet(this, _baseTs);
1670
- };
1671
- normalizeSampleData_fn = function(data) {
1672
- return __privateGet(this, _config).trackType === "audio" ? normalizeAacSampleForCmaf(data) : data;
1673
- };
1674
- enqueueRecovered_fn = function(frames) {
1675
- for (const frame of frames) {
1676
- if (__privateGet(this, _lastEmittedTs) >= 0 && frame.timestamp <= __privateGet(this, _lastEmittedTs)) {
1677
- __privateGet(this, _sampleOrderStats).staleSamples++;
1678
- continue;
1718
+ /** Flush a block with fill frames for missing ESI slots (FEC timeout path). */
1719
+ #flushBlockWithFill(sbn) {
1720
+ const block = this.#blocks.get(sbn);
1721
+ if (!block) return;
1722
+ const k = this.#config.k;
1723
+ const isVideo = this.#config.trackType === "video";
1724
+ const firstAudioFrame = !isVideo ? [...block.values()].sort((a, b) => a.timestamp - b.timestamp)[0]?.data : void 0;
1725
+ const audioConcealmentFrame = this.#lastDecodableAudioFrame ?? firstAudioFrame;
1726
+ const allFrames = [];
1727
+ let lastRealTs = -1;
1728
+ let firstRealTs = -1;
1729
+ for (const [, f] of block) {
1730
+ if (firstRealTs < 0 || f.timestamp < firstRealTs) firstRealTs = f.timestamp;
1731
+ if (f.timestamp > lastRealTs) lastRealTs = f.timestamp;
1679
1732
  }
1680
- if (__privateGet(this, _pendingRecovered).has(frame.timestamp)) {
1681
- __privateGet(this, _sampleOrderStats).duplicateSamples++;
1682
- continue;
1683
- }
1684
- __privateGet(this, _pendingRecovered).set(frame.timestamp, frame);
1685
- }
1686
- };
1687
- drainRecoveredUpTo_fn = function(horizonTs) {
1688
- if (__privateGet(this, _pendingRecovered).size === 0) return;
1689
- const ready = [...__privateGet(this, _pendingRecovered).values()].filter((frame) => frame.timestamp <= horizonTs).sort((a, b) => a.timestamp - b.timestamp);
1690
- for (const frame of ready) {
1691
- __privateGet(this, _pendingRecovered).delete(frame.timestamp);
1692
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, frame.data, frame.timestamp, __privateGet(this, _frameDuration), frame.keyframe, false, frame.catalogTrackName, frame.mpuSequenceNumber, frame.packetSequenceNumber, frame.packetSequenceNumbers, frame.repairedPacketSequenceNumbers, frame.authoredTiming, frame.deliveryProvenance, frame.mmtpTimestamp, frame.movieFragmentSequenceNumber, frame.sampleNumber, frame.synthetic);
1693
- __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "recovered-drain", [frame]);
1694
- }
1695
- };
1696
- /** Flush a block's buffered frames as a multi-sample CMAF segment. */
1697
- flushBlock_fn = function(sbn) {
1698
- const block = __privateGet(this, _blocks).get(sbn);
1699
- if (!block || block.size === 0) {
1700
- __privateGet(this, _blocks).delete(sbn);
1701
- return;
1702
- }
1703
- const entries = [...block.entries()].sort((a, b) => a[0] - b[0]);
1704
- const sortedFrames = entries.map(([, f]) => f);
1705
- __privateGet(this, _blocks).delete(sbn);
1706
- if (!__privateMethod(this, _CmafBlockAssembler_instances, claimSbnEmission_fn).call(this, sbn)) return;
1707
- const frames = __privateMethod(this, _CmafBlockAssembler_instances, applyVideoKeyframeGate_fn).call(this, sortedFrames);
1708
- if (!frames) return;
1709
- __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "flushBlock", frames, sbn);
1710
- __privateMethod(this, _CmafBlockAssembler_instances, emitPerSample_fn).call(this, frames);
1711
- };
1712
- /** Flush a block with fill frames for missing ESI slots (FEC timeout path). */
1713
- flushBlockWithFill_fn = function(sbn) {
1714
- const block = __privateGet(this, _blocks).get(sbn);
1715
- if (!block) return;
1716
- const k = __privateGet(this, _config).k;
1717
- const isVideo = __privateGet(this, _config).trackType === "video";
1718
- const firstAudioFrame = !isVideo ? [...block.values()].sort((a, b) => a.timestamp - b.timestamp)[0]?.data : void 0;
1719
- const audioConcealmentFrame = __privateGet(this, _lastDecodableAudioFrame) ?? firstAudioFrame;
1720
- const allFrames = [];
1721
- let lastRealTs = -1;
1722
- let firstRealTs = -1;
1723
- for (const [, f] of block) {
1724
- if (firstRealTs < 0 || f.timestamp < firstRealTs) firstRealTs = f.timestamp;
1725
- if (f.timestamp > lastRealTs) lastRealTs = f.timestamp;
1726
- }
1727
- const estimatedBlockDuration = block.size > 1 ? (lastRealTs - firstRealTs) / (block.size - 1) * k : __privateGet(this, _frameDuration) * k;
1728
- for (let esi = 0; esi < k; esi++) {
1729
- const real = block.get(esi);
1730
- if (real) {
1731
- allFrames.push(real);
1732
- } else {
1733
- const interpolatedTs = firstRealTs >= 0 ? firstRealTs + Math.round(esi * estimatedBlockDuration / k) : __privateGet(this, _lastEmittedTs) >= 0 ? __privateGet(this, _lastEmittedTs) + __privateGet(this, _frameDuration) * (esi + 1) : 0;
1734
- allFrames.push({
1735
- // A synthesized AAC access unit is not portable across every
1736
- // AudioSpecificConfig. Repeat known-good encoded audio instead;
1737
- // if this is the first block, use its earliest received sample.
1738
- data: isVideo ? __privateGet(this, _fillFrame) : audioConcealmentFrame?.slice() ?? new Uint8Array(0),
1739
- timestamp: interpolatedTs,
1740
- // Video: first fill is keyframe (IDR). Audio: all fill marked keyframe.
1741
- keyframe: isVideo ? !block.has(0) && esi === 0 : true,
1742
- synthetic: true
1743
- });
1733
+ const estimatedBlockDuration = block.size > 1 ? (lastRealTs - firstRealTs) / (block.size - 1) * k : this.#frameDuration * k;
1734
+ for (let esi = 0; esi < k; esi++) {
1735
+ const real = block.get(esi);
1736
+ if (real) {
1737
+ allFrames.push(real);
1738
+ } else {
1739
+ const interpolatedTs = firstRealTs >= 0 ? firstRealTs + Math.round(esi * estimatedBlockDuration / k) : this.#lastEmittedTs >= 0 ? this.#lastEmittedTs + this.#frameDuration * (esi + 1) : 0;
1740
+ allFrames.push({
1741
+ // A synthesized AAC access unit is not portable across every
1742
+ // AudioSpecificConfig. Repeat known-good encoded audio instead;
1743
+ // if this is the first block, use its earliest received sample.
1744
+ data: isVideo ? this.#fillFrame : audioConcealmentFrame?.slice() ?? new Uint8Array(0),
1745
+ timestamp: interpolatedTs,
1746
+ // Video: first fill is keyframe (IDR). Audio: all fill marked keyframe.
1747
+ keyframe: isVideo ? !block.has(0) && esi === 0 : true,
1748
+ synthetic: true
1749
+ });
1750
+ }
1744
1751
  }
1752
+ this.#blocks.delete(sbn);
1753
+ if (!this.#claimSbnEmission(sbn)) return;
1754
+ const gatedFrames = this.#applyVideoKeyframeGate(allFrames);
1755
+ if (!gatedFrames) return;
1756
+ this.#emitPerSample(gatedFrames);
1745
1757
  }
1746
- __privateGet(this, _blocks).delete(sbn);
1747
- if (!__privateMethod(this, _CmafBlockAssembler_instances, claimSbnEmission_fn).call(this, sbn)) return;
1748
- const gatedFrames = __privateMethod(this, _CmafBlockAssembler_instances, applyVideoKeyframeGate_fn).call(this, allFrames);
1749
- if (!gatedFrames) return;
1750
- __privateMethod(this, _CmafBlockAssembler_instances, emitPerSample_fn).call(this, gatedFrames);
1751
1758
  };
1752
1759
  function isH264Codec(codec) {
1753
1760
  const c = codec?.toLowerCase();