@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
  // ../mmt-alta-parse/dist/index.js
19
2
  var MMTP_HEADER_SIZE = 12;
20
3
  var MPU_HEADER_SIZE = 8;
@@ -244,7 +227,7 @@ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
244
227
  }
245
228
  return null;
246
229
  }
247
- function planMfuExtraction(mmtpPacket, options) {
230
+ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
248
231
  if (mmtpPacket.length < MMTP_HEADER_SIZE2 + MPU_HEADER_SIZE2) {
249
232
  return {
250
233
  rejection: {
@@ -254,15 +237,19 @@ function planMfuExtraction(mmtpPacket, options) {
254
237
  };
255
238
  }
256
239
  let header;
257
- try {
258
- header = parseMMTPHeader(mmtpPacket);
259
- } catch (error) {
260
- return {
261
- rejection: {
262
- gate: "mmtp-header-unparseable",
263
- detail: error instanceof Error ? error.message : String(error)
264
- }
265
- };
240
+ if (parsedHeader) {
241
+ header = parsedHeader;
242
+ } else {
243
+ try {
244
+ header = parseMMTPHeader(mmtpPacket);
245
+ } catch (error) {
246
+ return {
247
+ rejection: {
248
+ gate: "mmtp-header-unparseable",
249
+ detail: error instanceof Error ? error.message : String(error)
250
+ }
251
+ };
252
+ }
266
253
  }
267
254
  if (header.packetType !== PACKET_TYPE_MPU2) {
268
255
  return {
@@ -314,8 +301,10 @@ function planMfuExtraction(mmtpPacket, options) {
314
301
  }
315
302
  return { plan: { header, payload, mpu, fragmentType, layout, trailerLayout } };
316
303
  }
317
- function extractMFUPayload(mmtpPacket, options) {
318
- const result = planMfuExtraction(mmtpPacket, options);
304
+ function extractMFUPayloadWithHeader(mmtpPacket, header, options) {
305
+ return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options, header));
306
+ }
307
+ function extractPlannedMfu(mmtpPacket, result) {
319
308
  if ("rejection" in result)
320
309
  return null;
321
310
  const { header, payload, mpu, fragmentType, layout, trailerLayout } = result.plan;
@@ -330,32 +319,24 @@ function extractMFUPayload(mmtpPacket, options) {
330
319
  } : null;
331
320
  return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
332
321
  }
333
- function extractFecPayloadId(mmtpPacket) {
334
- if (!hasSourceFecPayloadId(mmtpPacket))
335
- return null;
336
- const off = mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
337
- const view2 = new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + off, SOURCE_FEC_PAYLOAD_ID_SIZE);
338
- return { ssId: view2.getUint32(0, false) };
339
- }
340
- function hasSourceFecPayloadId(mmtpPacket) {
322
+ function sourceFecPayloadIdOf(mmtpPacket, header) {
341
323
  if (mmtpPacket.length < MMTP_HEADER_SIZE2 + MPU_HEADER_SIZE2)
342
- return false;
343
- let header;
344
- try {
345
- header = parseMMTPHeader(mmtpPacket);
346
- } catch {
347
- return false;
348
- }
324
+ return null;
349
325
  if (header.packetType !== PACKET_TYPE_MPU2)
350
- return false;
326
+ return null;
351
327
  const payload = mmtpPacket.subarray(header.headerLength);
352
328
  if (payload.length < MPU_HEADER_SIZE2)
353
- return false;
354
- const mpu = parseMPUHeader(payload);
355
- if (mpu.payloadLength < MPU_HEADER_REMAINDER_SIZE2)
356
- return false;
357
- const declaredEnd = MPU_LENGTH_FIELD_SIZE2 + mpu.payloadLength;
358
- return resolveDeclaredTrailers(payload, declaredEnd, header.fecType)?.hasFecId ?? false;
329
+ return null;
330
+ const payloadLength = payload[0] << 8 | payload[1];
331
+ if (payloadLength < MPU_HEADER_REMAINDER_SIZE2)
332
+ return null;
333
+ const declaredEnd = MPU_LENGTH_FIELD_SIZE2 + payloadLength;
334
+ if (!resolveDeclaredTrailers(payload, declaredEnd, header.fecType)?.hasFecId)
335
+ return null;
336
+ const off = mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
337
+ return {
338
+ ssId: (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0
339
+ };
359
340
  }
360
341
  var extractAltaTrailer2 = extractAltaTrailer;
361
342
 
@@ -488,21 +469,19 @@ var COMPLETED_ADDRESS_WINDOW_MULTIPLE = 2;
488
469
  function parkedRunHoldsASlot(hasOpenRun, fragmentCount) {
489
470
  return !hasOpenRun && fragmentCount > 0;
490
471
  }
491
- var _buffers, _timeouts, _activeDataUnits, _pendingContinuations, _emitted, _emittedOrder, _completed, _completedOrder, _timeoutMs, _maxBuffered, _nextAdmissionSeq, _MFUReassembler_instances, addAssociatedFragment_fn, parkContinuation_fn, drainPendingContinuations_fn, unopenedParkedRunCount_fn, incompleteRunCount_fn, evictLeastRecentlyAdmitted_fn, releaseSlot_fn, reject_fn, associateDataUnit_fn, tryReassemble_fn, assemble_fn, setTimeout_fn, clearPendingTimeout_fn, armHeadlessPendingTimeout_fn, deletePendingRun_fn, onPendingTimeout_fn, clearTimeout_fn, markEmitted_fn, markCompleted_fn, orderValue_fn, removeActiveDataUnitForBuffer_fn, openRunAt_fn, onTimeout_fn, pendingDebugSamples_fn;
492
472
  var MFUReassembler = class {
493
473
  constructor(options) {
494
- __privateAdd(this, _MFUReassembler_instances);
495
474
  // Fragment buffers and active runs use the authored MFU DU identity.
496
475
  // Continuations may wait in one counter-indexed queue per data-unit address
497
476
  // until FI=1 supplies that identity. The address is transport association
498
477
  // only; the object key stays the intrinsic DU identity.
499
- __privateAdd(this, _buffers, /* @__PURE__ */ new Map());
500
- __privateAdd(this, _timeouts, /* @__PURE__ */ new Map());
501
- __privateAdd(this, _activeDataUnits, /* @__PURE__ */ new Map());
502
- __privateAdd(this, _pendingContinuations, /* @__PURE__ */ new Map());
503
- __privateAdd(this, _emitted, /* @__PURE__ */ new Set());
478
+ this.#buffers = /* @__PURE__ */ new Map();
479
+ this.#timeouts = /* @__PURE__ */ new Map();
480
+ this.#activeDataUnits = /* @__PURE__ */ new Map();
481
+ this.#pendingContinuations = /* @__PURE__ */ new Map();
482
+ this.#emitted = /* @__PURE__ */ new Set();
504
483
  // same sample keys, so FEC-recovered duplicate heads are dropped
505
- __privateAdd(this, _emittedOrder, []);
484
+ this.#emittedOrder = [];
506
485
  // Addresses of emitted data units. A continuation addressed to one of them
507
486
  // is a late copy of a fragment the run already consumed (FEC recovery
508
487
  // supplied it first), so it is rejected as stale rather than parked as a
@@ -512,15 +491,13 @@ var MFUReassembler = class {
512
491
  // completions. (#emitted is a separate, per-engine window: this engine keeps
513
492
  // maxBuffered sample keys where Rust keeps 2x; the completed set does not
514
493
  // derive from it.)
515
- __privateAdd(this, _completed, /* @__PURE__ */ new Set());
516
- __privateAdd(this, _completedOrder, []);
517
- __privateAdd(this, _timeoutMs);
518
- __privateAdd(this, _maxBuffered);
494
+ this.#completed = /* @__PURE__ */ new Set();
495
+ this.#completedOrder = [];
519
496
  /**
520
497
  * Monotonic admission ordinal. Counts slot admissions, never reads a clock,
521
498
  * so eviction order survives on hosts that run `timeoutMs: null`.
522
499
  */
523
- __privateAdd(this, _nextAdmissionSeq, 0);
500
+ this.#nextAdmissionSeq = 0;
524
501
  /** Statistics for debugging */
525
502
  this.stats = {
526
503
  totalFragments: 0,
@@ -537,30 +514,41 @@ var MFUReassembler = class {
537
514
  if (!Number.isInteger(maxBuffered) || maxBuffered <= 0) {
538
515
  throw new Error("[MFUReassembler] maxBuffered must be a positive integer");
539
516
  }
540
- __privateSet(this, _timeoutMs, options.timeoutMs);
541
- __privateSet(this, _maxBuffered, maxBuffered);
542
- }
517
+ this.#timeoutMs = options.timeoutMs;
518
+ this.#maxBuffered = maxBuffered;
519
+ }
520
+ #buffers;
521
+ #timeouts;
522
+ #activeDataUnits;
523
+ #pendingContinuations;
524
+ #emitted;
525
+ #emittedOrder;
526
+ #completed;
527
+ #completedOrder;
528
+ #timeoutMs;
529
+ #maxBuffered;
530
+ #nextAdmissionSeq;
543
531
  /** Update the expiry policy for all retained and future incomplete MFUs. */
544
532
  set timeoutMs(ms) {
545
533
  if (ms !== null && (!Number.isFinite(ms) || ms <= 0)) {
546
534
  throw new Error("[MFUReassembler] timeoutMs must be > 0 (derive from frame duration or FEC config)");
547
535
  }
548
- __privateSet(this, _timeoutMs, ms);
536
+ this.#timeoutMs = ms;
549
537
  const now = Date.now();
550
- for (const [bufferKey, state] of __privateGet(this, _timeouts)) {
538
+ for (const [bufferKey, state] of this.#timeouts) {
551
539
  if (state.timeoutId !== void 0) clearTimeout(state.timeoutId);
552
540
  delete state.timeoutId;
553
541
  if (ms !== null) {
554
- state.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onTimeout_fn).call(this, bufferKey), Math.max(0, state.startedAt + ms - now));
542
+ state.timeoutId = setTimeout(() => this.#onTimeout(bufferKey), Math.max(0, state.startedAt + ms - now));
555
543
  }
556
544
  }
557
- for (const address of __privateGet(this, _pendingContinuations).keys()) {
558
- __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
559
- __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
545
+ for (const address of this.#pendingContinuations.keys()) {
546
+ this.#clearPendingTimeout(address);
547
+ this.#armHeadlessPendingTimeout(address);
560
548
  }
561
549
  }
562
550
  get timeoutMs() {
563
- return __privateGet(this, _timeoutMs);
551
+ return this.#timeoutMs;
564
552
  }
565
553
  /**
566
554
  * Add a fragment and return reassembled MFU if complete
@@ -568,10 +556,10 @@ var MFUReassembler = class {
568
556
  addFragment(fragment) {
569
557
  this.stats.totalFragments++;
570
558
  if (!hasValidFragmentHeader(fragment)) {
571
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "invalid-fragment-state", "invalid MFU fragmentation indicator or counter");
559
+ this.#reject("invalid-fragment-state", "invalid MFU fragmentation indicator or counter");
572
560
  }
573
561
  if (fragment.itemId !== void 0 && hasAnySampleIdentityField(fragment)) {
574
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "conflicting-data-unit-identity", "MFU carries timed and non-timed DU identities");
562
+ this.#reject("conflicting-data-unit-identity", "MFU carries timed and non-timed DU identities");
575
563
  }
576
564
  const { mpuSequenceNumber, fragmentationIndicator } = fragment;
577
565
  if (fragmentationIndicator === 0) {
@@ -579,13 +567,13 @@ var MFUReassembler = class {
579
567
  const hasSampleFields = hasAnySampleIdentityField(fragment);
580
568
  const hasItemIdentity = fragment.itemId !== void 0;
581
569
  if (!sampleIdentity && !hasItemIdentity) {
582
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "missing-data-unit-identity", "complete MFU has no intrinsic DU identity");
570
+ this.#reject("missing-data-unit-identity", "complete MFU has no intrinsic DU identity");
583
571
  }
584
572
  if (hasSampleFields && !sampleIdentity) {
585
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "missing-data-unit-identity", "complete MFU has an incomplete sample identity");
573
+ this.#reject("missing-data-unit-identity", "complete MFU has an incomplete sample identity");
586
574
  }
587
575
  if (hasItemIdentity && !isU32(fragment.itemId)) {
588
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "missing-data-unit-identity", "complete MFU has an invalid Item_ID");
576
+ this.#reject("missing-data-unit-identity", "complete MFU has an invalid Item_ID");
589
577
  }
590
578
  this.stats.reassembledMFUs++;
591
579
  return {
@@ -607,67 +595,516 @@ var MFUReassembler = class {
607
595
  }
608
596
  const sequence = fragment.packetSequenceNumber;
609
597
  if (!isU32(sequence)) {
610
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "missing-packet-sequence", "fragmented MFU has no MMTP packet sequence number");
598
+ this.#reject("missing-packet-sequence", "fragmented MFU has no MMTP packet sequence number");
611
599
  }
612
600
  const address = dataUnitAddress(fragment, sequence);
613
601
  if (fragmentationIndicator !== 1) {
614
- const open = __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address);
602
+ const open = this.#openRunAt(address);
615
603
  if (open === void 0) {
616
- if (__privateGet(this, _completed).has(address)) {
617
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "MFU continuation names a data unit that already completed");
604
+ if (this.#completed.has(address)) {
605
+ this.#reject("fragment-counter-mismatch", "MFU continuation names a data unit that already completed");
618
606
  }
619
- __privateMethod(this, _MFUReassembler_instances, parkContinuation_fn).call(this, address, fragment);
607
+ this.#parkContinuation(address, fragment);
620
608
  return null;
621
609
  }
622
610
  const [runKey2, active] = open;
623
611
  if (active.nextFragmentCounter > fragment.fragmentCounter) {
624
- __privateMethod(this, _MFUReassembler_instances, parkContinuation_fn).call(this, address, fragment);
612
+ this.#parkContinuation(address, fragment);
625
613
  return null;
626
614
  }
627
615
  if (active.nextFragmentCounter < fragment.fragmentCounter) {
628
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "MFU continuation is behind the authored fragment-counter countdown");
616
+ this.#reject("fragment-counter-mismatch", "MFU continuation is behind the authored fragment-counter countdown");
629
617
  }
630
- const result2 = __privateMethod(this, _MFUReassembler_instances, addAssociatedFragment_fn).call(this, fragment, runKey2, address);
618
+ const result2 = this.#addAssociatedFragment(fragment, runKey2, address);
631
619
  if (result2 !== null) return result2;
632
- return __privateMethod(this, _MFUReassembler_instances, drainPendingContinuations_fn).call(this, address, runKey2);
620
+ return this.#drainPendingContinuations(address, runKey2);
633
621
  }
634
622
  const runKey = objectKey(fragment);
635
- if ((hasSampleIdentity(fragment) || isU32(fragment.itemId)) && __privateGet(this, _emitted).has(runKey)) {
623
+ if ((hasSampleIdentity(fragment) || isU32(fragment.itemId)) && this.#emitted.has(runKey)) {
636
624
  return null;
637
625
  }
638
- if (__privateGet(this, _activeDataUnits).has(runKey)) {
639
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "overlapping-data-unit", "fragmented MFU overlaps an active data unit");
626
+ if (this.#activeDataUnits.has(runKey)) {
627
+ this.#reject("overlapping-data-unit", "fragmented MFU overlaps an active data unit");
640
628
  }
641
- if (__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0) {
642
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "overlapping-data-unit", "fragmented MFU opens on an address held by an open data unit");
629
+ if (this.#openRunAt(address) !== void 0) {
630
+ this.#reject("overlapping-data-unit", "fragmented MFU opens on an address held by an open data unit");
643
631
  }
644
- const pending = __privateGet(this, _pendingContinuations).get(address);
632
+ const pending = this.#pendingContinuations.get(address);
645
633
  if (pending !== void 0 && [...pending.fragments.keys()].some((counter) => counter >= fragment.fragmentCounter)) {
646
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "queued continuation counter is not below the authored first-fragment counter");
634
+ this.#reject(
635
+ "fragment-counter-mismatch",
636
+ "queued continuation counter is not below the authored first-fragment counter"
637
+ );
647
638
  }
648
- const result = __privateMethod(this, _MFUReassembler_instances, addAssociatedFragment_fn).call(this, fragment, runKey, address, pending?.startedAt);
649
- __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
639
+ const result = this.#addAssociatedFragment(fragment, runKey, address, pending?.startedAt);
640
+ this.#clearPendingTimeout(address);
650
641
  if (result !== null) return result;
651
- return __privateMethod(this, _MFUReassembler_instances, drainPendingContinuations_fn).call(this, address, runKey);
642
+ return this.#drainPendingContinuations(address, runKey);
643
+ }
644
+ #addAssociatedFragment(fragment, runKey, address, startedAt) {
645
+ const association = this.#associateDataUnit(fragment, runKey, address);
646
+ const { bufferKey, first, terminal } = association;
647
+ let fragments = this.#buffers.get(bufferKey);
648
+ if (first) {
649
+ if (fragments !== void 0) {
650
+ this.#reject("overlapping-data-unit", "intrinsic data-unit buffer already exists");
651
+ }
652
+ fragments = [];
653
+ this.#buffers.set(bufferKey, fragments);
654
+ } else if (fragments === void 0) {
655
+ throw new Error("[MFUReassembler] active data unit has no fragment buffer");
656
+ }
657
+ if (first) this.#setTimeout(bufferKey, startedAt);
658
+ fragments.push(fragment);
659
+ if (!terminal) return null;
660
+ const result = this.#tryReassemble(bufferKey);
661
+ this.#activeDataUnits.delete(runKey);
662
+ if (result === null) {
663
+ this.#clearTimeout(bufferKey);
664
+ this.#buffers.delete(bufferKey);
665
+ this.#reject("incomplete-terminal-fragment", "validated terminal fragment did not complete its data unit");
666
+ }
667
+ this.#markCompleted(address);
668
+ return result;
669
+ }
670
+ #parkContinuation(address, fragment) {
671
+ let pending = this.#pendingContinuations.get(address);
672
+ const open = this.#openRunAt(address);
673
+ const alreadyCharged = open !== void 0 || parkedRunHoldsASlot(open !== void 0, pending?.fragments.size ?? 0);
674
+ if (!alreadyCharged && this.#incompleteRunCount() >= this.#maxBuffered) {
675
+ if (!this.#evictLeastRecentlyAdmitted()) {
676
+ this.#reject("active-data-unit-limit", "active MFU data-unit limit reached");
677
+ }
678
+ }
679
+ let armAfterInsert = false;
680
+ if (pending === void 0) {
681
+ pending = {
682
+ fragments: /* @__PURE__ */ new Map(),
683
+ startedAt: Date.now(),
684
+ admissionSeq: open !== void 0 ? open[1].admissionSeq : this.#nextAdmissionSeq++
685
+ };
686
+ this.#pendingContinuations.set(address, pending);
687
+ armAfterInsert = true;
688
+ } else if (!alreadyCharged) {
689
+ pending.admissionSeq = this.#nextAdmissionSeq++;
690
+ pending.startedAt = Date.now();
691
+ this.#clearPendingTimeout(address);
692
+ armAfterInsert = true;
693
+ }
694
+ if (pending.fragments.has(fragment.fragmentCounter)) {
695
+ this.#reject("fragment-counter-mismatch", "duplicate queued continuation counter would replace retained media");
696
+ }
697
+ pending.fragments.set(fragment.fragmentCounter, fragment);
698
+ if (armAfterInsert) this.#armHeadlessPendingTimeout(address);
699
+ }
700
+ #drainPendingContinuations(address, runKey) {
701
+ while (true) {
702
+ const active = this.#activeDataUnits.get(runKey);
703
+ const pending = this.#pendingContinuations.get(address);
704
+ if (active === void 0) {
705
+ if (pending?.fragments.size === 0) this.#deletePendingRun(address);
706
+ return null;
707
+ }
708
+ const fragment = pending?.fragments.get(active.nextFragmentCounter);
709
+ if (fragment === void 0) {
710
+ if (pending?.fragments.size === 0) this.#deletePendingRun(address);
711
+ return null;
712
+ }
713
+ pending.fragments.delete(active.nextFragmentCounter);
714
+ if (pending.fragments.size === 0) this.#deletePendingRun(address);
715
+ const result = this.#addAssociatedFragment(fragment, runKey, address);
716
+ if (result !== null) {
717
+ return result;
718
+ }
719
+ }
720
+ }
721
+ /** Parked data units that hold a `maxBuffered` slot of their own. Membership
722
+ * is `parkedRunHoldsASlot`, the same rule #evictLeastRecentlyAdmitted offers
723
+ * as candidates, so nothing can be counted here that eviction cannot reclaim.
724
+ *
725
+ * One site, two callers — `#incompleteRunCount` and `pendingCount` — mirroring
726
+ * Rust's `unopened_parked_run_count`, which `incomplete_run_count` and
727
+ * `buffered_count` both delegate to. Both callers used to inline this loop
728
+ * verbatim, so converging the *rule* moved one copy and left the other as the
729
+ * divergence (Ally's review of #400). The rule can no longer drift now that
730
+ * every site routes through `parkedRunHoldsASlot`; keeping the loop itself at
731
+ * one site is what stops the scaffolding drifting the next time this question
732
+ * grows an argument. */
733
+ #unopenedParkedRunCount() {
734
+ let count = 0;
735
+ for (const [address, pending] of this.#pendingContinuations) {
736
+ if (parkedRunHoldsASlot(this.#openRunAt(address) !== void 0, pending.fragments.size)) {
737
+ count++;
738
+ }
739
+ }
740
+ return count;
741
+ }
742
+ /** Every open run plus every headless parked data unit that holds a slot,
743
+ * one slot each. This is the quantity maxBuffered bounds. The parked term is
744
+ * `#unopenedParkedRunCount`, whose membership is `parkedRunHoldsASlot` — the
745
+ * same rule #evictLeastRecentlyAdmitted offers as candidates, so nothing can
746
+ * be counted here that eviction cannot reclaim. */
747
+ #incompleteRunCount() {
748
+ return this.#activeDataUnits.size + this.#unopenedParkedRunCount();
749
+ }
750
+ /**
751
+ * Drop the incomplete data unit admitted longest ago so a newly arriving one
752
+ * can take its slot. Selection is by monotonic admission ordinal, never by
753
+ * wall clock, so this is a bounded-capacity replacement policy and not a
754
+ * timeout: it behaves identically on hosts that never drive `cleanup_timeouts`
755
+ * (`timeoutMs: null`). Only incomplete data units are candidates — a data
756
+ * unit that completed has already left both maps.
757
+ *
758
+ * Returns false only if no slot is charged, which cannot happen at the bound
759
+ * (`maxBuffered` is a positive integer); admission then falls back to the
760
+ * fail-closed `active-data-unit-limit` reject, which stays a stable host code.
761
+ * That holds because the candidate set here is built from the same
762
+ * `parkedRunHoldsASlot` rule `#incompleteRunCount` counts by, so reaching the
763
+ * bound implies at least one candidate. Filtering one and not the other would
764
+ * make the claim false: a queue counted but not offered charges a slot no
765
+ * eviction can reclaim, and the receiver refuses every later data unit
766
+ * permanently.
767
+ */
768
+ #evictLeastRecentlyAdmitted() {
769
+ let victimAddress;
770
+ let victimSeq = Number.POSITIVE_INFINITY;
771
+ for (const [, active] of this.#activeDataUnits) {
772
+ if (active.admissionSeq < victimSeq) {
773
+ victimSeq = active.admissionSeq;
774
+ victimAddress = active.address;
775
+ }
776
+ }
777
+ for (const [address, pending] of this.#pendingContinuations) {
778
+ if (!parkedRunHoldsASlot(this.#openRunAt(address) !== void 0, pending.fragments.size)) {
779
+ continue;
780
+ }
781
+ if (pending.admissionSeq < victimSeq) {
782
+ victimSeq = pending.admissionSeq;
783
+ victimAddress = address;
784
+ }
785
+ }
786
+ if (victimAddress === void 0) return false;
787
+ this.#releaseSlot(victimAddress);
788
+ this.stats.evictedMemoryLimit++;
789
+ return true;
790
+ }
791
+ /**
792
+ * Release every form of state one address holds: its open run, that run's
793
+ * buffered fragments and deadline, and its continuation queue. The address is
794
+ * deliberately not marked completed — the data unit never emitted, so a later
795
+ * fragment of it may open a fresh slot rather than being rejected as stale.
796
+ */
797
+ #releaseSlot(address) {
798
+ const open = this.#openRunAt(address);
799
+ if (open !== void 0) {
800
+ const [runKey, active] = open;
801
+ this.#activeDataUnits.delete(runKey);
802
+ this.#clearTimeout(active.bufferKey);
803
+ this.#buffers.delete(active.bufferKey);
804
+ }
805
+ this.#deletePendingRun(address);
806
+ }
807
+ #reject(code, message) {
808
+ this.stats.rejectedFragments++;
809
+ throw new MfuReassemblyError(code, message);
810
+ }
811
+ #associateDataUnit(fragment, runKey, address) {
812
+ const fi = fragment.fragmentationIndicator;
813
+ if (fi === 1) {
814
+ const parked = this.#pendingContinuations.get(address);
815
+ const inheritsParkedSlot = parkedRunHoldsASlot(
816
+ this.#openRunAt(address) !== void 0,
817
+ parked?.fragments.size ?? 0
818
+ );
819
+ const sampleIdentity = hasSampleIdentity(fragment);
820
+ const hasSampleFields = hasAnySampleIdentityField(fragment);
821
+ const hasItemIdentity = fragment.itemId !== void 0;
822
+ if (sampleIdentity && hasItemIdentity) {
823
+ this.#reject("conflicting-data-unit-identity", "fragmented MFU carries timed and non-timed DU identities");
824
+ }
825
+ if (!sampleIdentity && !hasItemIdentity) {
826
+ this.#reject("missing-data-unit-identity", "first fragment has no intrinsic DU identity");
827
+ }
828
+ if (hasSampleFields && !sampleIdentity) {
829
+ this.#reject("missing-data-unit-identity", "first fragment has an incomplete sample identity");
830
+ }
831
+ if (hasItemIdentity && !isU32(fragment.itemId)) {
832
+ this.#reject("missing-data-unit-identity", "first fragment has an invalid Item_ID");
833
+ }
834
+ const bufferKey = objectKey(fragment);
835
+ if (this.#buffers.has(bufferKey)) {
836
+ this.#reject("overlapping-data-unit", "intrinsic data-unit buffer already exists");
837
+ }
838
+ let sampleEnd = null;
839
+ if (sampleIdentity) {
840
+ sampleEnd = checkedSampleEnd(fragment.sampleOffset, fragment.data.byteLength);
841
+ if (sampleEnd === null) this.#reject("offset-overflow", "sample byte offset overflow");
842
+ }
843
+ if (!inheritsParkedSlot && this.#incompleteRunCount() >= this.#maxBuffered) {
844
+ if (!this.#evictLeastRecentlyAdmitted()) {
845
+ this.#reject("active-data-unit-limit", "active MFU data-unit limit reached");
846
+ }
847
+ }
848
+ const admissionSeq = inheritsParkedSlot ? parked.admissionSeq : this.#nextAdmissionSeq++;
849
+ let active2;
850
+ if (sampleIdentity) {
851
+ active2 = {
852
+ address,
853
+ kind: "sample",
854
+ bufferKey,
855
+ nextFragmentCounter: fragment.fragmentCounter - 1,
856
+ admissionSeq,
857
+ movieFragmentSequenceNumber: fragment.movieFragmentSequenceNumber,
858
+ sampleNumber: fragment.sampleNumber,
859
+ nextOffset: sampleEnd,
860
+ ...fragment.catalogTrackName === void 0 ? {} : { catalogTrackName: fragment.catalogTrackName }
861
+ };
862
+ } else {
863
+ active2 = {
864
+ address,
865
+ kind: "item",
866
+ bufferKey,
867
+ nextFragmentCounter: fragment.fragmentCounter - 1,
868
+ admissionSeq,
869
+ itemId: fragment.itemId,
870
+ ...fragment.catalogTrackName === void 0 ? {} : { catalogTrackName: fragment.catalogTrackName }
871
+ };
872
+ }
873
+ this.#activeDataUnits.set(objectKey(fragment), active2);
874
+ return { bufferKey, first: true, terminal: false };
875
+ }
876
+ const active = this.#activeDataUnits.get(runKey);
877
+ if (active === void 0) {
878
+ throw new Error("[MFUReassembler] continuation was not parked before association");
879
+ }
880
+ if (fragment.fragmentCounter !== active.nextFragmentCounter) {
881
+ this.#reject(
882
+ "fragment-counter-mismatch",
883
+ "MFU continuation does not follow the authored fragment-counter countdown"
884
+ );
885
+ }
886
+ if (active.kind === "sample") {
887
+ if (fragment.itemId !== void 0) {
888
+ this.#reject("data-unit-identity-mismatch", "sample continuation carries an Item_ID");
889
+ }
890
+ if (hasAnySampleIdentityField(fragment) && (!hasSampleIdentity(fragment) || fragment.movieFragmentSequenceNumber !== active.movieFragmentSequenceNumber || fragment.sampleNumber !== active.sampleNumber || fragment.sampleOffset !== active.nextOffset)) {
891
+ this.#reject("data-unit-identity-mismatch", "sample continuation identity does not match");
892
+ }
893
+ const nextOffset = checkedSampleEnd(active.nextOffset, fragment.data.byteLength);
894
+ if (nextOffset === null) this.#reject("offset-overflow", "sample byte offset overflow");
895
+ fragment.movieFragmentSequenceNumber = active.movieFragmentSequenceNumber;
896
+ fragment.sampleNumber = active.sampleNumber;
897
+ fragment.sampleOffset = active.nextOffset;
898
+ if (fi === 2) {
899
+ active.nextOffset = nextOffset;
900
+ active.nextFragmentCounter = fragment.fragmentCounter - 1;
901
+ }
902
+ } else {
903
+ if (hasAnySampleIdentityField(fragment) || fragment.itemId !== void 0 && fragment.itemId !== active.itemId) {
904
+ this.#reject("data-unit-identity-mismatch", "Item_ID continuation identity does not match");
905
+ }
906
+ fragment.itemId = active.itemId;
907
+ if (fi === 2) active.nextFragmentCounter = fragment.fragmentCounter - 1;
908
+ }
909
+ return {
910
+ bufferKey: active.bufferKey,
911
+ first: false,
912
+ terminal: fi === 3
913
+ };
914
+ }
915
+ #tryReassemble(bufferKey) {
916
+ const fragments = this.#buffers.get(bufferKey);
917
+ if (!fragments || fragments.length === 0) {
918
+ return null;
919
+ }
920
+ const sorted = [...fragments].sort((a, b) => this.#orderValue(a) - this.#orderValue(b));
921
+ if (sorted[0].fragmentationIndicator !== 1 || sorted[sorted.length - 1].fragmentationIndicator !== 3) {
922
+ return null;
923
+ }
924
+ if (sorted.slice(1, -1).some((fragment) => fragment.fragmentationIndicator !== 2)) {
925
+ return null;
926
+ }
927
+ for (let i = 1; i < sorted.length; i++) {
928
+ if (this.#orderValue(sorted[i]) !== this.#orderValue(sorted[i - 1]) + 1) {
929
+ return null;
930
+ }
931
+ }
932
+ if (ordersByOffset(sorted)) {
933
+ for (let i = 1; i < sorted.length; i++) {
934
+ const previous = sorted[i - 1];
935
+ if (sorted[i].sampleOffset !== previous.sampleOffset + previous.data.byteLength) {
936
+ return null;
937
+ }
938
+ }
939
+ }
940
+ fragments.splice(0, fragments.length, ...sorted);
941
+ return this.#assemble(bufferKey, fragments);
942
+ }
943
+ #assemble(bufferKey, fragments) {
944
+ const totalSize = fragments.reduce((sum, f) => sum + f.data.length, 0);
945
+ const data = new Uint8Array(totalSize);
946
+ let offset = 0;
947
+ for (const fragment of fragments) {
948
+ data.set(fragment.data, offset);
949
+ offset += fragment.data.length;
950
+ }
951
+ this.#clearTimeout(bufferKey);
952
+ this.#buffers.delete(bufferKey);
953
+ this.#markEmitted(bufferKey);
954
+ this.stats.reassembledMFUs++;
955
+ return {
956
+ mpuSequenceNumber: fragments[0].mpuSequenceNumber,
957
+ packetSequenceNumber: fragments[0].packetSequenceNumber,
958
+ ...assembledPacketSequences(fragments),
959
+ data,
960
+ timestamp: fragments[0].timestamp,
961
+ fragmentCount: fragments.length,
962
+ rapFlag: fragments[0].rapFlag,
963
+ priority: fragments.find((f) => f.priority !== void 0)?.priority,
964
+ sampleNumber: fragments[0].sampleNumber,
965
+ movieFragmentSequenceNumber: fragments[0].movieFragmentSequenceNumber,
966
+ sampleOffset: fragments[0].sampleOffset,
967
+ source: fragments[0].source,
968
+ deliveryProvenance: deliveryProvenanceOf(fragments),
969
+ catalogTrackName: fragments[0].catalogTrackName
970
+ };
971
+ }
972
+ #setTimeout(bufferKey, startedAt = Date.now()) {
973
+ const state = { startedAt };
974
+ if (this.#timeoutMs !== null) {
975
+ state.timeoutId = setTimeout(
976
+ () => this.#onTimeout(bufferKey),
977
+ Math.max(0, startedAt + this.#timeoutMs - Date.now())
978
+ );
979
+ }
980
+ this.#timeouts.set(bufferKey, state);
981
+ }
982
+ #clearPendingTimeout(address) {
983
+ const pending = this.#pendingContinuations.get(address);
984
+ if (pending?.timeoutId !== void 0) clearTimeout(pending.timeoutId);
985
+ if (pending !== void 0) {
986
+ delete pending.timeoutId;
987
+ }
988
+ }
989
+ /**
990
+ * A queue whose run closed without completing is headless again and expires
991
+ * from its own first arrival, exactly as it would had the head never come.
992
+ *
993
+ * An empty queue is not armed: it holds no data unit that could fail to
994
+ * complete, so there is nothing for a deadline to expire. Every arming site
995
+ * reaches this function, which takes that test through `parkedRunHoldsASlot`
996
+ * rather than filtering on the open run alone, which is how this engine
997
+ * reaches Rust's answer: its
998
+ * `next_timeout_at` derives candidate deadlines from the queue's live
999
+ * entries, so an empty queue yields none (BLO-32420).
1000
+ */
1001
+ #armHeadlessPendingTimeout(address) {
1002
+ const pending = this.#pendingContinuations.get(address);
1003
+ if (pending === void 0 || pending.timeoutId !== void 0 || this.#timeoutMs === null) return;
1004
+ if (!parkedRunHoldsASlot(this.#openRunAt(address) !== void 0, pending.fragments.size)) return;
1005
+ pending.timeoutId = setTimeout(
1006
+ () => this.#onPendingTimeout(address),
1007
+ Math.max(0, pending.startedAt + this.#timeoutMs - Date.now())
1008
+ );
1009
+ }
1010
+ #deletePendingRun(address) {
1011
+ this.#clearPendingTimeout(address);
1012
+ this.#pendingContinuations.delete(address);
1013
+ }
1014
+ #onPendingTimeout(address) {
1015
+ const pending = this.#pendingContinuations.get(address);
1016
+ if (pending === void 0) return;
1017
+ if (!parkedRunHoldsASlot(this.#openRunAt(address) !== void 0, pending.fragments.size)) {
1018
+ this.#clearPendingTimeout(address);
1019
+ return;
1020
+ }
1021
+ this.stats.timedOutMFUs++;
1022
+ console.warn(
1023
+ `[MfuReassembler] timeout: run=${address} fragments=${pending.fragments.size} (continuations awaiting first fragment, discarded)`
1024
+ );
1025
+ this.#pendingContinuations.delete(address);
1026
+ }
1027
+ #clearTimeout(bufferKey) {
1028
+ const state = this.#timeouts.get(bufferKey);
1029
+ if (state !== void 0) {
1030
+ if (state.timeoutId !== void 0) clearTimeout(state.timeoutId);
1031
+ this.#timeouts.delete(bufferKey);
1032
+ }
1033
+ }
1034
+ #markEmitted(bufferKey) {
1035
+ if (this.#emitted.has(bufferKey)) return;
1036
+ this.#emitted.add(bufferKey);
1037
+ this.#emittedOrder.push(bufferKey);
1038
+ while (this.#emittedOrder.length > this.#maxBuffered) {
1039
+ const oldest = this.#emittedOrder.shift();
1040
+ if (oldest !== void 0) this.#emitted.delete(oldest);
1041
+ }
1042
+ }
1043
+ #markCompleted(address) {
1044
+ if (this.#completed.has(address)) return;
1045
+ this.#completed.add(address);
1046
+ this.#completedOrder.push(address);
1047
+ const cap = this.#maxBuffered * COMPLETED_ADDRESS_WINDOW_MULTIPLE;
1048
+ while (this.#completedOrder.length > cap) {
1049
+ const oldest = this.#completedOrder.shift();
1050
+ if (oldest !== void 0) this.#completed.delete(oldest);
1051
+ }
1052
+ }
1053
+ #orderValue(fragment) {
1054
+ return fragmentCounterOrder(fragment);
1055
+ }
1056
+ /** Close the run behind an expired buffer. Early arrivals parked under its
1057
+ * address stay, now headless, and expire from their own arrival. */
1058
+ #removeActiveDataUnitForBuffer(bufferKey) {
1059
+ for (const [objectKey2, active] of this.#activeDataUnits) {
1060
+ if (active.bufferKey === bufferKey) {
1061
+ this.#activeDataUnits.delete(objectKey2);
1062
+ this.#armHeadlessPendingTimeout(active.address);
1063
+ }
1064
+ }
1065
+ }
1066
+ /** The one open run holding this address, with its object key. Admission
1067
+ * rejects a second head on an open address, so at most one run can match. */
1068
+ #openRunAt(address) {
1069
+ for (const entry of this.#activeDataUnits) {
1070
+ if (entry[1].address === address) return entry;
1071
+ }
1072
+ return void 0;
1073
+ }
1074
+ #onTimeout(bufferKey) {
1075
+ const fragments = this.#buffers.get(bufferKey);
1076
+ if (!fragments || fragments.length === 0) {
1077
+ this.#buffers.delete(bufferKey);
1078
+ this.#timeouts.delete(bufferKey);
1079
+ this.#removeActiveDataUnitForBuffer(bufferKey);
1080
+ this.stats.timedOutMFUs++;
1081
+ console.warn(`[MfuReassembler] timeout: key=${bufferKey} fragments=0 (no data buffered)`);
1082
+ return;
1083
+ }
1084
+ this.stats.timedOutMFUs++;
1085
+ console.warn(`[MfuReassembler] timeout: key=${bufferKey} fragments=${fragments.length} (partial, discarded)`);
1086
+ this.#buffers.delete(bufferKey);
1087
+ this.#timeouts.delete(bufferKey);
1088
+ this.#removeActiveDataUnitForBuffer(bufferKey);
652
1089
  }
653
1090
  /**
654
1091
  * Flush all buffered fragments
655
1092
  */
656
1093
  flush() {
657
- for (const key of __privateGet(this, _buffers).keys()) {
658
- __privateMethod(this, _MFUReassembler_instances, clearTimeout_fn).call(this, key);
1094
+ for (const key of this.#buffers.keys()) {
1095
+ this.#clearTimeout(key);
659
1096
  }
660
- __privateGet(this, _buffers).clear();
661
- __privateGet(this, _timeouts).clear();
662
- __privateGet(this, _activeDataUnits).clear();
663
- for (const address of __privateGet(this, _pendingContinuations).keys()) {
664
- __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1097
+ this.#buffers.clear();
1098
+ this.#timeouts.clear();
1099
+ this.#activeDataUnits.clear();
1100
+ for (const address of this.#pendingContinuations.keys()) {
1101
+ this.#clearPendingTimeout(address);
665
1102
  }
666
- __privateGet(this, _pendingContinuations).clear();
667
- __privateGet(this, _emitted).clear();
668
- __privateGet(this, _emittedOrder).length = 0;
669
- __privateGet(this, _completed).clear();
670
- __privateGet(this, _completedOrder).length = 0;
1103
+ this.#pendingContinuations.clear();
1104
+ this.#emitted.clear();
1105
+ this.#emittedOrder.length = 0;
1106
+ this.#completed.clear();
1107
+ this.#completedOrder.length = 0;
671
1108
  }
672
1109
  /** Drop one catalog stream's incomplete and dedup state. */
673
1110
  resetStream(catalogTrackName) {
@@ -680,34 +1117,34 @@ var MFUReassembler = class {
680
1117
  }
681
1118
  };
682
1119
  const discarded = /* @__PURE__ */ new Set();
683
- for (const [key, fragments] of __privateGet(this, _buffers)) {
1120
+ for (const [key, fragments] of this.#buffers) {
684
1121
  if (fragments.some((fragment) => fragment.catalogTrackName === catalogTrackName)) {
685
1122
  discarded.add(key);
686
1123
  }
687
1124
  }
688
- for (const [objectKey2, active] of __privateGet(this, _activeDataUnits)) {
1125
+ for (const [objectKey2, active] of this.#activeDataUnits) {
689
1126
  if (active.catalogTrackName === catalogTrackName) {
690
1127
  discarded.add(active.bufferKey);
691
- __privateGet(this, _activeDataUnits).delete(objectKey2);
1128
+ this.#activeDataUnits.delete(objectKey2);
692
1129
  }
693
1130
  }
694
- for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1131
+ for (const [address, pending] of this.#pendingContinuations) {
695
1132
  if ([...pending.fragments.values()].some((fragment) => fragment.catalogTrackName === catalogTrackName) || belongsToStream(address))
696
- __privateMethod(this, _MFUReassembler_instances, deletePendingRun_fn).call(this, address);
1133
+ this.#deletePendingRun(address);
697
1134
  }
698
- for (const key of __privateGet(this, _emitted)) {
1135
+ for (const key of this.#emitted) {
699
1136
  if (belongsToStream(key)) discarded.add(key);
700
1137
  }
701
1138
  for (const key of discarded) {
702
- __privateMethod(this, _MFUReassembler_instances, clearTimeout_fn).call(this, key);
703
- __privateGet(this, _buffers).delete(key);
704
- __privateGet(this, _emitted).delete(key);
1139
+ this.#clearTimeout(key);
1140
+ this.#buffers.delete(key);
1141
+ this.#emitted.delete(key);
705
1142
  }
706
- __privateSet(this, _emittedOrder, __privateGet(this, _emittedOrder).filter((key) => !discarded.has(key)));
707
- for (const address of __privateGet(this, _completed)) {
708
- if (belongsToStream(address)) __privateGet(this, _completed).delete(address);
1143
+ this.#emittedOrder = this.#emittedOrder.filter((key) => !discarded.has(key));
1144
+ for (const address of this.#completed) {
1145
+ if (belongsToStream(address)) this.#completed.delete(address);
709
1146
  }
710
- __privateSet(this, _completedOrder, __privateGet(this, _completedOrder).filter((address) => __privateGet(this, _completed).has(address)));
1147
+ this.#completedOrder = this.#completedOrder.filter((address) => this.#completed.has(address));
711
1148
  }
712
1149
  /** Reset all state — flush buffers and zero stats */
713
1150
  reset() {
@@ -739,533 +1176,78 @@ var MFUReassembler = class {
739
1176
  * routing both through one method makes structural rather than conventional.
740
1177
  */
741
1178
  get pendingCount() {
742
- return __privateGet(this, _buffers).size + __privateMethod(this, _MFUReassembler_instances, unopenedParkedRunCount_fn).call(this);
1179
+ return this.#buffers.size + this.#unopenedParkedRunCount();
743
1180
  }
744
1181
  /**
745
1182
  * Get current buffer status
746
1183
  */
747
1184
  getStatus() {
748
1185
  let pendingFragments = 0;
749
- for (const fragments of __privateGet(this, _buffers).values()) {
1186
+ for (const fragments of this.#buffers.values()) {
750
1187
  pendingFragments += fragments.length;
751
1188
  }
752
- for (const pending of __privateGet(this, _pendingContinuations).values()) {
1189
+ for (const pending of this.#pendingContinuations.values()) {
753
1190
  pendingFragments += pending.fragments.size;
754
1191
  }
755
1192
  return {
756
1193
  bufferedMFUs: this.pendingCount,
757
1194
  pendingFragments,
758
- pendingSamples: __privateMethod(this, _MFUReassembler_instances, pendingDebugSamples_fn).call(this),
1195
+ pendingSamples: this.#pendingDebugSamples(),
759
1196
  stats: { ...this.stats }
760
1197
  };
761
1198
  }
762
- };
763
- _buffers = new WeakMap();
764
- _timeouts = new WeakMap();
765
- _activeDataUnits = new WeakMap();
766
- _pendingContinuations = new WeakMap();
767
- _emitted = new WeakMap();
768
- _emittedOrder = new WeakMap();
769
- _completed = new WeakMap();
770
- _completedOrder = new WeakMap();
771
- _timeoutMs = new WeakMap();
772
- _maxBuffered = new WeakMap();
773
- _nextAdmissionSeq = new WeakMap();
774
- _MFUReassembler_instances = new WeakSet();
775
- addAssociatedFragment_fn = function(fragment, runKey, address, startedAt) {
776
- const association = __privateMethod(this, _MFUReassembler_instances, associateDataUnit_fn).call(this, fragment, runKey, address);
777
- const { bufferKey, first, terminal } = association;
778
- let fragments = __privateGet(this, _buffers).get(bufferKey);
779
- if (first) {
780
- if (fragments !== void 0) {
781
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "overlapping-data-unit", "intrinsic data-unit buffer already exists");
782
- }
783
- fragments = [];
784
- __privateGet(this, _buffers).set(bufferKey, fragments);
785
- } else if (fragments === void 0) {
786
- throw new Error("[MFUReassembler] active data unit has no fragment buffer");
787
- }
788
- if (first) __privateMethod(this, _MFUReassembler_instances, setTimeout_fn).call(this, bufferKey, startedAt);
789
- fragments.push(fragment);
790
- if (!terminal) return null;
791
- const result = __privateMethod(this, _MFUReassembler_instances, tryReassemble_fn).call(this, bufferKey);
792
- __privateGet(this, _activeDataUnits).delete(runKey);
793
- if (result === null) {
794
- __privateMethod(this, _MFUReassembler_instances, clearTimeout_fn).call(this, bufferKey);
795
- __privateGet(this, _buffers).delete(bufferKey);
796
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "incomplete-terminal-fragment", "validated terminal fragment did not complete its data unit");
797
- }
798
- __privateMethod(this, _MFUReassembler_instances, markCompleted_fn).call(this, address);
799
- return result;
800
- };
801
- parkContinuation_fn = function(address, fragment) {
802
- let pending = __privateGet(this, _pendingContinuations).get(address);
803
- const open = __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address);
804
- const alreadyCharged = open !== void 0 || parkedRunHoldsASlot(open !== void 0, pending?.fragments.size ?? 0);
805
- if (!alreadyCharged && __privateMethod(this, _MFUReassembler_instances, incompleteRunCount_fn).call(this) >= __privateGet(this, _maxBuffered)) {
806
- if (!__privateMethod(this, _MFUReassembler_instances, evictLeastRecentlyAdmitted_fn).call(this)) {
807
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "active-data-unit-limit", "active MFU data-unit limit reached");
808
- }
809
- }
810
- let armAfterInsert = false;
811
- if (pending === void 0) {
812
- pending = {
813
- fragments: /* @__PURE__ */ new Map(),
814
- startedAt: Date.now(),
815
- admissionSeq: open !== void 0 ? open[1].admissionSeq : __privateWrapper(this, _nextAdmissionSeq)._++
816
- };
817
- __privateGet(this, _pendingContinuations).set(address, pending);
818
- armAfterInsert = true;
819
- } else if (!alreadyCharged) {
820
- pending.admissionSeq = __privateWrapper(this, _nextAdmissionSeq)._++;
821
- pending.startedAt = Date.now();
822
- __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
823
- armAfterInsert = true;
824
- }
825
- if (pending.fragments.has(fragment.fragmentCounter)) {
826
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "duplicate queued continuation counter would replace retained media");
827
- }
828
- pending.fragments.set(fragment.fragmentCounter, fragment);
829
- if (armAfterInsert) __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
830
- };
831
- drainPendingContinuations_fn = function(address, runKey) {
832
- while (true) {
833
- const active = __privateGet(this, _activeDataUnits).get(runKey);
834
- const pending = __privateGet(this, _pendingContinuations).get(address);
835
- if (active === void 0) {
836
- if (pending?.fragments.size === 0) __privateMethod(this, _MFUReassembler_instances, deletePendingRun_fn).call(this, address);
837
- return null;
838
- }
839
- const fragment = pending?.fragments.get(active.nextFragmentCounter);
840
- if (fragment === void 0) {
841
- if (pending?.fragments.size === 0) __privateMethod(this, _MFUReassembler_instances, deletePendingRun_fn).call(this, address);
842
- return null;
843
- }
844
- pending.fragments.delete(active.nextFragmentCounter);
845
- if (pending.fragments.size === 0) __privateMethod(this, _MFUReassembler_instances, deletePendingRun_fn).call(this, address);
846
- const result = __privateMethod(this, _MFUReassembler_instances, addAssociatedFragment_fn).call(this, fragment, runKey, address);
847
- if (result !== null) {
848
- return result;
849
- }
850
- }
851
- };
852
- /** Parked data units that hold a `maxBuffered` slot of their own. Membership
853
- * is `parkedRunHoldsASlot`, the same rule #evictLeastRecentlyAdmitted offers
854
- * as candidates, so nothing can be counted here that eviction cannot reclaim.
855
- *
856
- * One site, two callers — `#incompleteRunCount` and `pendingCount` — mirroring
857
- * Rust's `unopened_parked_run_count`, which `incomplete_run_count` and
858
- * `buffered_count` both delegate to. Both callers used to inline this loop
859
- * verbatim, so converging the *rule* moved one copy and left the other as the
860
- * divergence (Ally's review of #400). The rule can no longer drift now that
861
- * every site routes through `parkedRunHoldsASlot`; keeping the loop itself at
862
- * one site is what stops the scaffolding drifting the next time this question
863
- * grows an argument. */
864
- unopenedParkedRunCount_fn = function() {
865
- let count = 0;
866
- for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
867
- if (parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
868
- count++;
869
- }
870
- }
871
- return count;
872
- };
873
- /** Every open run plus every headless parked data unit that holds a slot,
874
- * one slot each. This is the quantity maxBuffered bounds. The parked term is
875
- * `#unopenedParkedRunCount`, whose membership is `parkedRunHoldsASlot` — the
876
- * same rule #evictLeastRecentlyAdmitted offers as candidates, so nothing can
877
- * be counted here that eviction cannot reclaim. */
878
- incompleteRunCount_fn = function() {
879
- return __privateGet(this, _activeDataUnits).size + __privateMethod(this, _MFUReassembler_instances, unopenedParkedRunCount_fn).call(this);
880
- };
881
- /**
882
- * Drop the incomplete data unit admitted longest ago so a newly arriving one
883
- * can take its slot. Selection is by monotonic admission ordinal, never by
884
- * wall clock, so this is a bounded-capacity replacement policy and not a
885
- * timeout: it behaves identically on hosts that never drive `cleanup_timeouts`
886
- * (`timeoutMs: null`). Only incomplete data units are candidates — a data
887
- * unit that completed has already left both maps.
888
- *
889
- * Returns false only if no slot is charged, which cannot happen at the bound
890
- * (`maxBuffered` is a positive integer); admission then falls back to the
891
- * fail-closed `active-data-unit-limit` reject, which stays a stable host code.
892
- * That holds because the candidate set here is built from the same
893
- * `parkedRunHoldsASlot` rule `#incompleteRunCount` counts by, so reaching the
894
- * bound implies at least one candidate. Filtering one and not the other would
895
- * make the claim false: a queue counted but not offered charges a slot no
896
- * eviction can reclaim, and the receiver refuses every later data unit
897
- * permanently.
898
- */
899
- evictLeastRecentlyAdmitted_fn = function() {
900
- let victimAddress;
901
- let victimSeq = Number.POSITIVE_INFINITY;
902
- for (const [, active] of __privateGet(this, _activeDataUnits)) {
903
- if (active.admissionSeq < victimSeq) {
904
- victimSeq = active.admissionSeq;
905
- victimAddress = active.address;
906
- }
907
- }
908
- for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
909
- if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
910
- continue;
911
- }
912
- if (pending.admissionSeq < victimSeq) {
913
- victimSeq = pending.admissionSeq;
914
- victimAddress = address;
915
- }
916
- }
917
- if (victimAddress === void 0) return false;
918
- __privateMethod(this, _MFUReassembler_instances, releaseSlot_fn).call(this, victimAddress);
919
- this.stats.evictedMemoryLimit++;
920
- return true;
921
- };
922
- /**
923
- * Release every form of state one address holds: its open run, that run's
924
- * buffered fragments and deadline, and its continuation queue. The address is
925
- * deliberately not marked completed — the data unit never emitted, so a later
926
- * fragment of it may open a fresh slot rather than being rejected as stale.
927
- */
928
- releaseSlot_fn = function(address) {
929
- const open = __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address);
930
- if (open !== void 0) {
931
- const [runKey, active] = open;
932
- __privateGet(this, _activeDataUnits).delete(runKey);
933
- __privateMethod(this, _MFUReassembler_instances, clearTimeout_fn).call(this, active.bufferKey);
934
- __privateGet(this, _buffers).delete(active.bufferKey);
935
- }
936
- __privateMethod(this, _MFUReassembler_instances, deletePendingRun_fn).call(this, address);
937
- };
938
- reject_fn = function(code, message) {
939
- this.stats.rejectedFragments++;
940
- throw new MfuReassemblyError(code, message);
941
- };
942
- associateDataUnit_fn = function(fragment, runKey, address) {
943
- const fi = fragment.fragmentationIndicator;
944
- if (fi === 1) {
945
- const parked = __privateGet(this, _pendingContinuations).get(address);
946
- const inheritsParkedSlot = parkedRunHoldsASlot(
947
- __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0,
948
- parked?.fragments.size ?? 0
949
- );
950
- const sampleIdentity = hasSampleIdentity(fragment);
951
- const hasSampleFields = hasAnySampleIdentityField(fragment);
952
- const hasItemIdentity = fragment.itemId !== void 0;
953
- if (sampleIdentity && hasItemIdentity) {
954
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "conflicting-data-unit-identity", "fragmented MFU carries timed and non-timed DU identities");
955
- }
956
- if (!sampleIdentity && !hasItemIdentity) {
957
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "missing-data-unit-identity", "first fragment has no intrinsic DU identity");
958
- }
959
- if (hasSampleFields && !sampleIdentity) {
960
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "missing-data-unit-identity", "first fragment has an incomplete sample identity");
961
- }
962
- if (hasItemIdentity && !isU32(fragment.itemId)) {
963
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "missing-data-unit-identity", "first fragment has an invalid Item_ID");
964
- }
965
- const bufferKey = objectKey(fragment);
966
- if (__privateGet(this, _buffers).has(bufferKey)) {
967
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "overlapping-data-unit", "intrinsic data-unit buffer already exists");
968
- }
969
- let sampleEnd = null;
970
- if (sampleIdentity) {
971
- sampleEnd = checkedSampleEnd(fragment.sampleOffset, fragment.data.byteLength);
972
- if (sampleEnd === null) __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "offset-overflow", "sample byte offset overflow");
973
- }
974
- if (!inheritsParkedSlot && __privateMethod(this, _MFUReassembler_instances, incompleteRunCount_fn).call(this) >= __privateGet(this, _maxBuffered)) {
975
- if (!__privateMethod(this, _MFUReassembler_instances, evictLeastRecentlyAdmitted_fn).call(this)) {
976
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "active-data-unit-limit", "active MFU data-unit limit reached");
1199
+ #pendingDebugSamples() {
1200
+ const out = [];
1201
+ for (const [key, fragments] of this.#buffers) {
1202
+ if (fragments.length === 0) continue;
1203
+ const sorted = [...fragments].sort((a, b) => this.#orderValue(a) - this.#orderValue(b));
1204
+ const fiCounts = [0, 0, 0, 0];
1205
+ let minCounter = Infinity;
1206
+ let maxCounter = -Infinity;
1207
+ let minOffset = Infinity;
1208
+ let maxOffset = -Infinity;
1209
+ for (const fragment of sorted) {
1210
+ fiCounts[fragment.fragmentationIndicator] = (fiCounts[fragment.fragmentationIndicator] ?? 0) + 1;
1211
+ minCounter = Math.min(minCounter, fragment.fragmentCounter);
1212
+ maxCounter = Math.max(maxCounter, fragment.fragmentCounter);
1213
+ if (typeof fragment.sampleOffset === "number") {
1214
+ minOffset = Math.min(minOffset, fragment.sampleOffset);
1215
+ maxOffset = Math.max(maxOffset, fragment.sampleOffset);
1216
+ }
977
1217
  }
978
- }
979
- const admissionSeq = inheritsParkedSlot ? parked.admissionSeq : __privateWrapper(this, _nextAdmissionSeq)._++;
980
- let active2;
981
- if (sampleIdentity) {
982
- active2 = {
983
- address,
984
- kind: "sample",
985
- bufferKey,
986
- nextFragmentCounter: fragment.fragmentCounter - 1,
987
- admissionSeq,
988
- movieFragmentSequenceNumber: fragment.movieFragmentSequenceNumber,
989
- sampleNumber: fragment.sampleNumber,
990
- nextOffset: sampleEnd,
991
- ...fragment.catalogTrackName === void 0 ? {} : { catalogTrackName: fragment.catalogTrackName }
992
- };
993
- } else {
994
- active2 = {
995
- address,
996
- kind: "item",
997
- bufferKey,
998
- nextFragmentCounter: fragment.fragmentCounter - 1,
999
- admissionSeq,
1000
- itemId: fragment.itemId,
1001
- ...fragment.catalogTrackName === void 0 ? {} : { catalogTrackName: fragment.catalogTrackName }
1218
+ const point = (fragment) => ({
1219
+ fi: fragment.fragmentationIndicator,
1220
+ counter: fragment.fragmentCounter,
1221
+ order: this.#orderValue(fragment),
1222
+ ...typeof fragment.packetSequenceNumber === "number" ? { seq: fragment.packetSequenceNumber } : {},
1223
+ ...typeof fragment.sampleOffset === "number" ? { offset: fragment.sampleOffset } : {}
1224
+ });
1225
+ const summary = {
1226
+ key,
1227
+ fragments: sorted.length,
1228
+ fi0: fiCounts[0] ?? 0,
1229
+ fi1: fiCounts[1] ?? 0,
1230
+ fi2: fiCounts[2] ?? 0,
1231
+ fi3: fiCounts[3] ?? 0,
1232
+ firstFi: sorted[0].fragmentationIndicator,
1233
+ lastFi: sorted[sorted.length - 1].fragmentationIndicator,
1234
+ firstOrder: this.#orderValue(sorted[0]),
1235
+ lastOrder: this.#orderValue(sorted[sorted.length - 1]),
1236
+ minCounter,
1237
+ maxCounter,
1238
+ movieFragmentSequenceNumber: sorted.find((f) => f.movieFragmentSequenceNumber !== void 0)?.movieFragmentSequenceNumber,
1239
+ sampleNumber: sorted.find((f) => f.sampleNumber !== void 0)?.sampleNumber,
1240
+ mpuSequenceNumber: sorted[0].mpuSequenceNumber,
1241
+ sortedHead: sorted.slice(0, 6).map(point),
1242
+ sortedTail: sorted.slice(-6).map(point)
1002
1243
  };
1244
+ if (minOffset !== Infinity) summary.minOffset = minOffset;
1245
+ if (maxOffset !== -Infinity) summary.maxOffset = maxOffset;
1246
+ out.push(summary);
1247
+ if (out.length >= 12) break;
1003
1248
  }
1004
- __privateGet(this, _activeDataUnits).set(objectKey(fragment), active2);
1005
- return { bufferKey, first: true, terminal: false };
1006
- }
1007
- const active = __privateGet(this, _activeDataUnits).get(runKey);
1008
- if (active === void 0) {
1009
- throw new Error("[MFUReassembler] continuation was not parked before association");
1010
- }
1011
- if (fragment.fragmentCounter !== active.nextFragmentCounter) {
1012
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "MFU continuation does not follow the authored fragment-counter countdown");
1013
- }
1014
- if (active.kind === "sample") {
1015
- if (fragment.itemId !== void 0) {
1016
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "data-unit-identity-mismatch", "sample continuation carries an Item_ID");
1017
- }
1018
- if (hasAnySampleIdentityField(fragment) && (!hasSampleIdentity(fragment) || fragment.movieFragmentSequenceNumber !== active.movieFragmentSequenceNumber || fragment.sampleNumber !== active.sampleNumber || fragment.sampleOffset !== active.nextOffset)) {
1019
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "data-unit-identity-mismatch", "sample continuation identity does not match");
1020
- }
1021
- const nextOffset = checkedSampleEnd(active.nextOffset, fragment.data.byteLength);
1022
- if (nextOffset === null) __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "offset-overflow", "sample byte offset overflow");
1023
- fragment.movieFragmentSequenceNumber = active.movieFragmentSequenceNumber;
1024
- fragment.sampleNumber = active.sampleNumber;
1025
- fragment.sampleOffset = active.nextOffset;
1026
- if (fi === 2) {
1027
- active.nextOffset = nextOffset;
1028
- active.nextFragmentCounter = fragment.fragmentCounter - 1;
1029
- }
1030
- } else {
1031
- if (hasAnySampleIdentityField(fragment) || fragment.itemId !== void 0 && fragment.itemId !== active.itemId) {
1032
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "data-unit-identity-mismatch", "Item_ID continuation identity does not match");
1033
- }
1034
- fragment.itemId = active.itemId;
1035
- if (fi === 2) active.nextFragmentCounter = fragment.fragmentCounter - 1;
1036
- }
1037
- return {
1038
- bufferKey: active.bufferKey,
1039
- first: false,
1040
- terminal: fi === 3
1041
- };
1042
- };
1043
- tryReassemble_fn = function(bufferKey) {
1044
- const fragments = __privateGet(this, _buffers).get(bufferKey);
1045
- if (!fragments || fragments.length === 0) {
1046
- return null;
1047
- }
1048
- const sorted = [...fragments].sort((a, b) => __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, a) - __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, b));
1049
- if (sorted[0].fragmentationIndicator !== 1 || sorted[sorted.length - 1].fragmentationIndicator !== 3) {
1050
- return null;
1051
- }
1052
- if (sorted.slice(1, -1).some((fragment) => fragment.fragmentationIndicator !== 2)) {
1053
- return null;
1054
- }
1055
- for (let i = 1; i < sorted.length; i++) {
1056
- if (__privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, sorted[i]) !== __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, sorted[i - 1]) + 1) {
1057
- return null;
1058
- }
1059
- }
1060
- if (ordersByOffset(sorted)) {
1061
- for (let i = 1; i < sorted.length; i++) {
1062
- const previous = sorted[i - 1];
1063
- if (sorted[i].sampleOffset !== previous.sampleOffset + previous.data.byteLength) {
1064
- return null;
1065
- }
1066
- }
1067
- }
1068
- fragments.splice(0, fragments.length, ...sorted);
1069
- return __privateMethod(this, _MFUReassembler_instances, assemble_fn).call(this, bufferKey, fragments);
1070
- };
1071
- assemble_fn = function(bufferKey, fragments) {
1072
- const totalSize = fragments.reduce((sum, f) => sum + f.data.length, 0);
1073
- const data = new Uint8Array(totalSize);
1074
- let offset = 0;
1075
- for (const fragment of fragments) {
1076
- data.set(fragment.data, offset);
1077
- offset += fragment.data.length;
1078
- }
1079
- __privateMethod(this, _MFUReassembler_instances, clearTimeout_fn).call(this, bufferKey);
1080
- __privateGet(this, _buffers).delete(bufferKey);
1081
- __privateMethod(this, _MFUReassembler_instances, markEmitted_fn).call(this, bufferKey);
1082
- this.stats.reassembledMFUs++;
1083
- return {
1084
- mpuSequenceNumber: fragments[0].mpuSequenceNumber,
1085
- packetSequenceNumber: fragments[0].packetSequenceNumber,
1086
- ...assembledPacketSequences(fragments),
1087
- data,
1088
- timestamp: fragments[0].timestamp,
1089
- fragmentCount: fragments.length,
1090
- rapFlag: fragments[0].rapFlag,
1091
- priority: fragments.find((f) => f.priority !== void 0)?.priority,
1092
- sampleNumber: fragments[0].sampleNumber,
1093
- movieFragmentSequenceNumber: fragments[0].movieFragmentSequenceNumber,
1094
- sampleOffset: fragments[0].sampleOffset,
1095
- source: fragments[0].source,
1096
- deliveryProvenance: deliveryProvenanceOf(fragments),
1097
- catalogTrackName: fragments[0].catalogTrackName
1098
- };
1099
- };
1100
- setTimeout_fn = function(bufferKey, startedAt = Date.now()) {
1101
- const state = { startedAt };
1102
- if (__privateGet(this, _timeoutMs) !== null) {
1103
- state.timeoutId = setTimeout(
1104
- () => __privateMethod(this, _MFUReassembler_instances, onTimeout_fn).call(this, bufferKey),
1105
- Math.max(0, startedAt + __privateGet(this, _timeoutMs) - Date.now())
1106
- );
1107
- }
1108
- __privateGet(this, _timeouts).set(bufferKey, state);
1109
- };
1110
- clearPendingTimeout_fn = function(address) {
1111
- const pending = __privateGet(this, _pendingContinuations).get(address);
1112
- if (pending?.timeoutId !== void 0) clearTimeout(pending.timeoutId);
1113
- if (pending !== void 0) {
1114
- delete pending.timeoutId;
1115
- }
1116
- };
1117
- /**
1118
- * A queue whose run closed without completing is headless again and expires
1119
- * from its own first arrival, exactly as it would had the head never come.
1120
- *
1121
- * An empty queue is not armed: it holds no data unit that could fail to
1122
- * complete, so there is nothing for a deadline to expire. Every arming site
1123
- * reaches this function, which takes that test through `parkedRunHoldsASlot`
1124
- * rather than filtering on the open run alone, which is how this engine
1125
- * reaches Rust's answer: its
1126
- * `next_timeout_at` derives candidate deadlines from the queue's live
1127
- * entries, so an empty queue yields none (BLO-32420).
1128
- */
1129
- armHeadlessPendingTimeout_fn = function(address) {
1130
- const pending = __privateGet(this, _pendingContinuations).get(address);
1131
- if (pending === void 0 || pending.timeoutId !== void 0 || __privateGet(this, _timeoutMs) === null) return;
1132
- if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) return;
1133
- pending.timeoutId = setTimeout(
1134
- () => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address),
1135
- Math.max(0, pending.startedAt + __privateGet(this, _timeoutMs) - Date.now())
1136
- );
1137
- };
1138
- deletePendingRun_fn = function(address) {
1139
- __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1140
- __privateGet(this, _pendingContinuations).delete(address);
1141
- };
1142
- onPendingTimeout_fn = function(address) {
1143
- const pending = __privateGet(this, _pendingContinuations).get(address);
1144
- if (pending === void 0) return;
1145
- if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1146
- __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1147
- return;
1148
- }
1149
- this.stats.timedOutMFUs++;
1150
- console.warn(
1151
- `[MfuReassembler] timeout: run=${address} fragments=${pending.fragments.size} (continuations awaiting first fragment, discarded)`
1152
- );
1153
- __privateGet(this, _pendingContinuations).delete(address);
1154
- };
1155
- clearTimeout_fn = function(bufferKey) {
1156
- const state = __privateGet(this, _timeouts).get(bufferKey);
1157
- if (state !== void 0) {
1158
- if (state.timeoutId !== void 0) clearTimeout(state.timeoutId);
1159
- __privateGet(this, _timeouts).delete(bufferKey);
1160
- }
1161
- };
1162
- markEmitted_fn = function(bufferKey) {
1163
- if (__privateGet(this, _emitted).has(bufferKey)) return;
1164
- __privateGet(this, _emitted).add(bufferKey);
1165
- __privateGet(this, _emittedOrder).push(bufferKey);
1166
- while (__privateGet(this, _emittedOrder).length > __privateGet(this, _maxBuffered)) {
1167
- const oldest = __privateGet(this, _emittedOrder).shift();
1168
- if (oldest !== void 0) __privateGet(this, _emitted).delete(oldest);
1169
- }
1170
- };
1171
- markCompleted_fn = function(address) {
1172
- if (__privateGet(this, _completed).has(address)) return;
1173
- __privateGet(this, _completed).add(address);
1174
- __privateGet(this, _completedOrder).push(address);
1175
- const cap = __privateGet(this, _maxBuffered) * COMPLETED_ADDRESS_WINDOW_MULTIPLE;
1176
- while (__privateGet(this, _completedOrder).length > cap) {
1177
- const oldest = __privateGet(this, _completedOrder).shift();
1178
- if (oldest !== void 0) __privateGet(this, _completed).delete(oldest);
1179
- }
1180
- };
1181
- orderValue_fn = function(fragment) {
1182
- return fragmentCounterOrder(fragment);
1183
- };
1184
- /** Close the run behind an expired buffer. Early arrivals parked under its
1185
- * address stay, now headless, and expire from their own arrival. */
1186
- removeActiveDataUnitForBuffer_fn = function(bufferKey) {
1187
- for (const [objectKey2, active] of __privateGet(this, _activeDataUnits)) {
1188
- if (active.bufferKey === bufferKey) {
1189
- __privateGet(this, _activeDataUnits).delete(objectKey2);
1190
- __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, active.address);
1191
- }
1192
- }
1193
- };
1194
- /** The one open run holding this address, with its object key. Admission
1195
- * rejects a second head on an open address, so at most one run can match. */
1196
- openRunAt_fn = function(address) {
1197
- for (const entry of __privateGet(this, _activeDataUnits)) {
1198
- if (entry[1].address === address) return entry;
1199
- }
1200
- return void 0;
1201
- };
1202
- onTimeout_fn = function(bufferKey) {
1203
- const fragments = __privateGet(this, _buffers).get(bufferKey);
1204
- if (!fragments || fragments.length === 0) {
1205
- __privateGet(this, _buffers).delete(bufferKey);
1206
- __privateGet(this, _timeouts).delete(bufferKey);
1207
- __privateMethod(this, _MFUReassembler_instances, removeActiveDataUnitForBuffer_fn).call(this, bufferKey);
1208
- this.stats.timedOutMFUs++;
1209
- console.warn(`[MfuReassembler] timeout: key=${bufferKey} fragments=0 (no data buffered)`);
1210
- return;
1211
- }
1212
- this.stats.timedOutMFUs++;
1213
- console.warn(`[MfuReassembler] timeout: key=${bufferKey} fragments=${fragments.length} (partial, discarded)`);
1214
- __privateGet(this, _buffers).delete(bufferKey);
1215
- __privateGet(this, _timeouts).delete(bufferKey);
1216
- __privateMethod(this, _MFUReassembler_instances, removeActiveDataUnitForBuffer_fn).call(this, bufferKey);
1217
- };
1218
- pendingDebugSamples_fn = function() {
1219
- const out = [];
1220
- for (const [key, fragments] of __privateGet(this, _buffers)) {
1221
- if (fragments.length === 0) continue;
1222
- const sorted = [...fragments].sort((a, b) => __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, a) - __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, b));
1223
- const fiCounts = [0, 0, 0, 0];
1224
- let minCounter = Infinity;
1225
- let maxCounter = -Infinity;
1226
- let minOffset = Infinity;
1227
- let maxOffset = -Infinity;
1228
- for (const fragment of sorted) {
1229
- fiCounts[fragment.fragmentationIndicator] = (fiCounts[fragment.fragmentationIndicator] ?? 0) + 1;
1230
- minCounter = Math.min(minCounter, fragment.fragmentCounter);
1231
- maxCounter = Math.max(maxCounter, fragment.fragmentCounter);
1232
- if (typeof fragment.sampleOffset === "number") {
1233
- minOffset = Math.min(minOffset, fragment.sampleOffset);
1234
- maxOffset = Math.max(maxOffset, fragment.sampleOffset);
1235
- }
1236
- }
1237
- const point = (fragment) => ({
1238
- fi: fragment.fragmentationIndicator,
1239
- counter: fragment.fragmentCounter,
1240
- order: __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, fragment),
1241
- ...typeof fragment.packetSequenceNumber === "number" ? { seq: fragment.packetSequenceNumber } : {},
1242
- ...typeof fragment.sampleOffset === "number" ? { offset: fragment.sampleOffset } : {}
1243
- });
1244
- const summary = {
1245
- key,
1246
- fragments: sorted.length,
1247
- fi0: fiCounts[0] ?? 0,
1248
- fi1: fiCounts[1] ?? 0,
1249
- fi2: fiCounts[2] ?? 0,
1250
- fi3: fiCounts[3] ?? 0,
1251
- firstFi: sorted[0].fragmentationIndicator,
1252
- lastFi: sorted[sorted.length - 1].fragmentationIndicator,
1253
- firstOrder: __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, sorted[0]),
1254
- lastOrder: __privateMethod(this, _MFUReassembler_instances, orderValue_fn).call(this, sorted[sorted.length - 1]),
1255
- minCounter,
1256
- maxCounter,
1257
- movieFragmentSequenceNumber: sorted.find((f) => f.movieFragmentSequenceNumber !== void 0)?.movieFragmentSequenceNumber,
1258
- sampleNumber: sorted.find((f) => f.sampleNumber !== void 0)?.sampleNumber,
1259
- mpuSequenceNumber: sorted[0].mpuSequenceNumber,
1260
- sortedHead: sorted.slice(0, 6).map(point),
1261
- sortedTail: sorted.slice(-6).map(point)
1262
- };
1263
- if (minOffset !== Infinity) summary.minOffset = minOffset;
1264
- if (maxOffset !== -Infinity) summary.maxOffset = maxOffset;
1265
- out.push(summary);
1266
- if (out.length >= 12) break;
1249
+ return out;
1267
1250
  }
1268
- return out;
1269
1251
  };
1270
1252
  if (void 0) {
1271
1253
  const { describe, test, expect, vi } = void 0;
@@ -3134,29 +3116,27 @@ var SampleCombineError = class extends Error {
3134
3116
  this.name = "SampleCombineError";
3135
3117
  }
3136
3118
  };
3137
- var _maxBuffered2, _requireAuthoredSize, _maxSegmentsPerSample, _onAbandon, _authoredSizes, _pending, _retired, _stats, _SampleCombiner_instances, abandon_fn, tryComplete_fn, retire_fn, evictOldestPending_fn;
3138
3119
  var SampleCombiner = class {
3120
+ #maxBuffered;
3121
+ #requireAuthoredSize;
3122
+ #maxSegmentsPerSample;
3123
+ #onAbandon;
3124
+ #authoredSizes = /* @__PURE__ */ new Map();
3125
+ /** Map iteration is insertion-ordered, so the first key is the oldest. */
3126
+ #pending = /* @__PURE__ */ new Map();
3127
+ /**
3128
+ * Bounded, insertion-ordered set of recently-completed sample keys, so a
3129
+ * late duplicate or FEC-recovered retransmission is dropped rather than
3130
+ * re-emitted or misread as a fresh whole sample.
3131
+ */
3132
+ #retired = /* @__PURE__ */ new Set();
3133
+ #stats = {
3134
+ combinedSamples: 0,
3135
+ passthroughSamples: 0,
3136
+ timedOutSamples: 0,
3137
+ evictedSamples: 0
3138
+ };
3139
3139
  constructor(options) {
3140
- __privateAdd(this, _SampleCombiner_instances);
3141
- __privateAdd(this, _maxBuffered2);
3142
- __privateAdd(this, _requireAuthoredSize);
3143
- __privateAdd(this, _maxSegmentsPerSample);
3144
- __privateAdd(this, _onAbandon);
3145
- __privateAdd(this, _authoredSizes, /* @__PURE__ */ new Map());
3146
- /** Map iteration is insertion-ordered, so the first key is the oldest. */
3147
- __privateAdd(this, _pending, /* @__PURE__ */ new Map());
3148
- /**
3149
- * Bounded, insertion-ordered set of recently-completed sample keys, so a
3150
- * late duplicate or FEC-recovered retransmission is dropped rather than
3151
- * re-emitted or misread as a fresh whole sample.
3152
- */
3153
- __privateAdd(this, _retired, /* @__PURE__ */ new Set());
3154
- __privateAdd(this, _stats, {
3155
- combinedSamples: 0,
3156
- passthroughSamples: 0,
3157
- timedOutSamples: 0,
3158
- evictedSamples: 0
3159
- });
3160
3140
  const { maxBuffered, requireAuthoredSize, maxSegmentsPerSample, onAbandon } = options;
3161
3141
  if (!Number.isInteger(maxBuffered) || maxBuffered <= 0) {
3162
3142
  throw new Error("[SampleCombiner] maxBuffered must be a positive integer");
@@ -3164,10 +3144,14 @@ var SampleCombiner = class {
3164
3144
  if (!Number.isInteger(maxSegmentsPerSample) || maxSegmentsPerSample <= 0) {
3165
3145
  throw new Error("[SampleCombiner] maxSegmentsPerSample must be a positive integer");
3166
3146
  }
3167
- __privateSet(this, _maxBuffered2, maxBuffered);
3168
- __privateSet(this, _requireAuthoredSize, requireAuthoredSize);
3169
- __privateSet(this, _maxSegmentsPerSample, maxSegmentsPerSample);
3170
- __privateSet(this, _onAbandon, onAbandon);
3147
+ this.#maxBuffered = maxBuffered;
3148
+ this.#requireAuthoredSize = requireAuthoredSize;
3149
+ this.#maxSegmentsPerSample = maxSegmentsPerSample;
3150
+ this.#onAbandon = onAbandon;
3151
+ }
3152
+ /** Report one abandoned sample to the owner of any state keyed on it. */
3153
+ #abandon(key) {
3154
+ this.#onAbandon?.(identityOfKey(key));
3171
3155
  }
3172
3156
  /**
3173
3157
  * Register the authored sample size from the host's own FT=1 parse. Per
@@ -3194,9 +3178,9 @@ var SampleCombiner = class {
3194
3178
  */
3195
3179
  registerAuthoredSize(catalogTrackName, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, size) {
3196
3180
  const key = sampleKey(catalogTrackName, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber);
3197
- __privateGet(this, _retired).delete(key);
3198
- __privateGet(this, _authoredSizes).set(key, size);
3199
- return __privateMethod(this, _SampleCombiner_instances, tryComplete_fn).call(this, key, size);
3181
+ this.#retired.delete(key);
3182
+ this.#authoredSizes.set(key, size);
3183
+ return this.#tryComplete(key, size);
3200
3184
  }
3201
3185
  /**
3202
3186
  * Add one reassembled data unit. Returns the combined sample once every
@@ -3204,7 +3188,7 @@ var SampleCombiner = class {
3204
3188
  */
3205
3189
  addMfu(mfu) {
3206
3190
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3207
- __privateGet(this, _stats).passthroughSamples++;
3191
+ this.#stats.passthroughSamples++;
3208
3192
  return fromPassthrough(mfu);
3209
3193
  }
3210
3194
  const offset = mfu.sampleOffset ?? 0;
@@ -3214,16 +3198,16 @@ var SampleCombiner = class {
3214
3198
  mfu.movieFragmentSequenceNumber,
3215
3199
  mfu.sampleNumber
3216
3200
  );
3217
- if (__privateGet(this, _retired).has(key)) {
3201
+ if (this.#retired.has(key)) {
3218
3202
  return null;
3219
3203
  }
3220
3204
  const dataLen = mfu.data.byteLength;
3221
- const authoredSize = __privateGet(this, _authoredSizes).get(key);
3222
- if (offset === 0 && !__privateGet(this, _pending).has(key)) {
3223
- const passesThrough = authoredSize === void 0 ? !__privateGet(this, _requireAuthoredSize) : dataLen === authoredSize;
3205
+ const authoredSize = this.#authoredSizes.get(key);
3206
+ if (offset === 0 && !this.#pending.has(key)) {
3207
+ const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
3224
3208
  if (passesThrough) {
3225
- __privateGet(this, _stats).passthroughSamples++;
3226
- __privateMethod(this, _SampleCombiner_instances, retire_fn).call(this, key);
3209
+ this.#stats.passthroughSamples++;
3210
+ this.#retire(key);
3227
3211
  return fromPassthrough(mfu);
3228
3212
  }
3229
3213
  }
@@ -3234,7 +3218,7 @@ var SampleCombiner = class {
3234
3218
  "combined subsample data would exceed the registered authored sample size"
3235
3219
  );
3236
3220
  }
3237
- const existing = __privateGet(this, _pending).get(key);
3221
+ const existing = this.#pending.get(key);
3238
3222
  if (existing !== void 0) {
3239
3223
  if (existing.segments.has(offset)) {
3240
3224
  throw new SampleCombineError(
@@ -3242,7 +3226,7 @@ var SampleCombiner = class {
3242
3226
  "subsample data unit duplicates an offset already held for this sample"
3243
3227
  );
3244
3228
  }
3245
- if (existing.segments.size >= __privateGet(this, _maxSegmentsPerSample)) {
3229
+ if (existing.segments.size >= this.#maxSegmentsPerSample) {
3246
3230
  throw new SampleCombineError(
3247
3231
  "too-many-subsample-segments",
3248
3232
  "a sample already holds the maximum number of subsample data units"
@@ -3260,13 +3244,69 @@ var SampleCombiner = class {
3260
3244
  }
3261
3245
  let pending = existing;
3262
3246
  if (pending === void 0) {
3263
- if (__privateGet(this, _pending).size >= __privateGet(this, _maxBuffered2)) __privateMethod(this, _SampleCombiner_instances, evictOldestPending_fn).call(this);
3247
+ if (this.#pending.size >= this.#maxBuffered) this.#evictOldestPending();
3264
3248
  pending = { segments: /* @__PURE__ */ new Map(), startedAt: Date.now() };
3265
- __privateGet(this, _pending).set(key, pending);
3249
+ this.#pending.set(key, pending);
3266
3250
  }
3267
3251
  pending.segments.set(offset, mfu);
3268
3252
  if (authoredSize === void 0) return null;
3269
- return __privateMethod(this, _SampleCombiner_instances, tryComplete_fn).call(this, key, authoredSize);
3253
+ return this.#tryComplete(key, authoredSize);
3254
+ }
3255
+ /**
3256
+ * Emit the sample when its held data units are byte-adjacent from zero and
3257
+ * total `size`. Completion is a protocol event, never a timer.
3258
+ */
3259
+ #tryComplete(key, size) {
3260
+ const pending = this.#pending.get(key);
3261
+ if (pending === void 0) return null;
3262
+ let expected = 0;
3263
+ const sortedOffsets = [...pending.segments.keys()].sort((a, b) => a - b);
3264
+ for (const segOffset of sortedOffsets) {
3265
+ if (segOffset !== expected) return null;
3266
+ expected += pending.segments.get(segOffset).data.byteLength;
3267
+ }
3268
+ if (expected !== size) return null;
3269
+ this.#pending.delete(key);
3270
+ this.#stats.combinedSamples++;
3271
+ this.#retire(key);
3272
+ return fromSegments(pending.segments, sortedOffsets);
3273
+ }
3274
+ /**
3275
+ * Retire a sample's key: free its registered authored size and remember the
3276
+ * key in a bounded recency set. Called on every path that removes a sample
3277
+ * -- completion, passthrough, eviction, and timeout -- so `#authoredSizes`
3278
+ * cannot accumulate entries for samples that never complete, and so a later
3279
+ * data unit for a discarded sample is dropped rather than starting a fresh
3280
+ * buffer or being misread as a whole sample.
3281
+ *
3282
+ * The recency set holds `maxBuffered` keys. A duplicate delayed by more
3283
+ * than that many retirements escapes it; on a reliable path there is no
3284
+ * such duplicate, and on a lossy path the per-data-unit deadline in
3285
+ * {@link MFUReassembler} bounds the delay well inside this window.
3286
+ */
3287
+ #retire(key) {
3288
+ this.#authoredSizes.delete(key);
3289
+ this.#retired.add(key);
3290
+ while (this.#retired.size > this.#maxBuffered) {
3291
+ const oldest = this.#retired.values().next().value;
3292
+ if (oldest === void 0) break;
3293
+ this.#retired.delete(oldest);
3294
+ }
3295
+ }
3296
+ /**
3297
+ * Discard the oldest pending sample by insertion order. This is the only
3298
+ * backstop against one FEC-lost subsample data unit wedging
3299
+ * {@link SampleCombiner.addMfu} for every future sample once `maxBuffered`
3300
+ * is reached, for a host that never drives
3301
+ * {@link SampleCombiner.cleanupTimeouts}.
3302
+ */
3303
+ #evictOldestPending() {
3304
+ const oldest = this.#pending.keys().next().value;
3305
+ if (oldest === void 0) return;
3306
+ this.#pending.delete(oldest);
3307
+ this.#stats.evictedSamples++;
3308
+ this.#retire(oldest);
3309
+ this.#abandon(oldest);
3270
3310
  }
3271
3311
  /**
3272
3312
  * Discard samples whose oldest held segment has waited past `timeoutMs`.
@@ -3277,19 +3317,19 @@ var SampleCombiner = class {
3277
3317
  */
3278
3318
  cleanupTimeouts(timeoutMs) {
3279
3319
  const now = Date.now();
3280
- for (const [key, pending] of [...__privateGet(this, _pending)]) {
3320
+ for (const [key, pending] of [...this.#pending]) {
3281
3321
  if (now - pending.startedAt > timeoutMs) {
3282
- __privateGet(this, _pending).delete(key);
3283
- __privateGet(this, _stats).timedOutSamples++;
3284
- __privateMethod(this, _SampleCombiner_instances, retire_fn).call(this, key);
3285
- __privateMethod(this, _SampleCombiner_instances, abandon_fn).call(this, key);
3322
+ this.#pending.delete(key);
3323
+ this.#stats.timedOutSamples++;
3324
+ this.#retire(key);
3325
+ this.#abandon(key);
3286
3326
  }
3287
3327
  }
3288
3328
  }
3289
3329
  flush() {
3290
- __privateGet(this, _pending).clear();
3291
- __privateGet(this, _authoredSizes).clear();
3292
- __privateGet(this, _retired).clear();
3330
+ this.#pending.clear();
3331
+ this.#authoredSizes.clear();
3332
+ this.#retired.clear();
3293
3333
  }
3294
3334
  /**
3295
3335
  * Drop one stream's in-flight, registered-size, and retired state while
@@ -3297,21 +3337,21 @@ var SampleCombiner = class {
3297
3337
  * {@link MFUReassembler.resetStream}).
3298
3338
  */
3299
3339
  resetStream(catalogTrackName) {
3300
- for (const key of __privateGet(this, _pending).keys()) {
3301
- if (trackNameOfKey(key) === catalogTrackName) __privateGet(this, _pending).delete(key);
3340
+ for (const key of this.#pending.keys()) {
3341
+ if (trackNameOfKey(key) === catalogTrackName) this.#pending.delete(key);
3302
3342
  }
3303
- for (const key of __privateGet(this, _authoredSizes).keys()) {
3304
- if (trackNameOfKey(key) === catalogTrackName) __privateGet(this, _authoredSizes).delete(key);
3343
+ for (const key of this.#authoredSizes.keys()) {
3344
+ if (trackNameOfKey(key) === catalogTrackName) this.#authoredSizes.delete(key);
3305
3345
  }
3306
- for (const key of __privateGet(this, _retired)) {
3307
- if (trackNameOfKey(key) === catalogTrackName) __privateGet(this, _retired).delete(key);
3346
+ for (const key of this.#retired) {
3347
+ if (trackNameOfKey(key) === catalogTrackName) this.#retired.delete(key);
3308
3348
  }
3309
3349
  }
3310
3350
  get stats() {
3311
- return { ...__privateGet(this, _stats) };
3351
+ return { ...this.#stats };
3312
3352
  }
3313
3353
  get pendingCount() {
3314
- return __privateGet(this, _pending).size;
3354
+ return this.#pending.size;
3315
3355
  }
3316
3356
  /**
3317
3357
  * Registered authored sizes still held. Diagnostic only: it exists so tests
@@ -3319,83 +3359,13 @@ var SampleCombiner = class {
3319
3359
  * unbounded one is invisible from `pendingCount` alone.
3320
3360
  */
3321
3361
  get debugAuthoredSizeCount() {
3322
- return __privateGet(this, _authoredSizes).size;
3362
+ return this.#authoredSizes.size;
3323
3363
  }
3324
3364
  /** Retired keys still remembered. Diagnostic only, bounded by `maxBuffered`. */
3325
3365
  get debugRetiredCount() {
3326
- return __privateGet(this, _retired).size;
3327
- }
3328
- };
3329
- _maxBuffered2 = new WeakMap();
3330
- _requireAuthoredSize = new WeakMap();
3331
- _maxSegmentsPerSample = new WeakMap();
3332
- _onAbandon = new WeakMap();
3333
- _authoredSizes = new WeakMap();
3334
- _pending = new WeakMap();
3335
- _retired = new WeakMap();
3336
- _stats = new WeakMap();
3337
- _SampleCombiner_instances = new WeakSet();
3338
- /** Report one abandoned sample to the owner of any state keyed on it. */
3339
- abandon_fn = function(key) {
3340
- var _a;
3341
- (_a = __privateGet(this, _onAbandon)) == null ? void 0 : _a.call(this, identityOfKey(key));
3342
- };
3343
- /**
3344
- * Emit the sample when its held data units are byte-adjacent from zero and
3345
- * total `size`. Completion is a protocol event, never a timer.
3346
- */
3347
- tryComplete_fn = function(key, size) {
3348
- const pending = __privateGet(this, _pending).get(key);
3349
- if (pending === void 0) return null;
3350
- let expected = 0;
3351
- const sortedOffsets = [...pending.segments.keys()].sort((a, b) => a - b);
3352
- for (const segOffset of sortedOffsets) {
3353
- if (segOffset !== expected) return null;
3354
- expected += pending.segments.get(segOffset).data.byteLength;
3355
- }
3356
- if (expected !== size) return null;
3357
- __privateGet(this, _pending).delete(key);
3358
- __privateGet(this, _stats).combinedSamples++;
3359
- __privateMethod(this, _SampleCombiner_instances, retire_fn).call(this, key);
3360
- return fromSegments(pending.segments, sortedOffsets);
3361
- };
3362
- /**
3363
- * Retire a sample's key: free its registered authored size and remember the
3364
- * key in a bounded recency set. Called on every path that removes a sample
3365
- * -- completion, passthrough, eviction, and timeout -- so `#authoredSizes`
3366
- * cannot accumulate entries for samples that never complete, and so a later
3367
- * data unit for a discarded sample is dropped rather than starting a fresh
3368
- * buffer or being misread as a whole sample.
3369
- *
3370
- * The recency set holds `maxBuffered` keys. A duplicate delayed by more
3371
- * than that many retirements escapes it; on a reliable path there is no
3372
- * such duplicate, and on a lossy path the per-data-unit deadline in
3373
- * {@link MFUReassembler} bounds the delay well inside this window.
3374
- */
3375
- retire_fn = function(key) {
3376
- __privateGet(this, _authoredSizes).delete(key);
3377
- __privateGet(this, _retired).add(key);
3378
- while (__privateGet(this, _retired).size > __privateGet(this, _maxBuffered2)) {
3379
- const oldest = __privateGet(this, _retired).values().next().value;
3380
- if (oldest === void 0) break;
3381
- __privateGet(this, _retired).delete(oldest);
3366
+ return this.#retired.size;
3382
3367
  }
3383
3368
  };
3384
- /**
3385
- * Discard the oldest pending sample by insertion order. This is the only
3386
- * backstop against one FEC-lost subsample data unit wedging
3387
- * {@link SampleCombiner.addMfu} for every future sample once `maxBuffered`
3388
- * is reached, for a host that never drives
3389
- * {@link SampleCombiner.cleanupTimeouts}.
3390
- */
3391
- evictOldestPending_fn = function() {
3392
- const oldest = __privateGet(this, _pending).keys().next().value;
3393
- if (oldest === void 0) return;
3394
- __privateGet(this, _pending).delete(oldest);
3395
- __privateGet(this, _stats).evictedSamples++;
3396
- __privateMethod(this, _SampleCombiner_instances, retire_fn).call(this, oldest);
3397
- __privateMethod(this, _SampleCombiner_instances, abandon_fn).call(this, oldest);
3398
- };
3399
3369
  function fromPassthrough(mfu) {
3400
3370
  return {
3401
3371
  mpuSequenceNumber: mfu.mpuSequenceNumber,
@@ -3432,10 +3402,10 @@ function fromSegments(segments, sortedOffsets) {
3432
3402
  writeOffset += seg.data.byteLength;
3433
3403
  fragmentCount += seg.fragmentCount;
3434
3404
  if (seg.packetSequenceNumbers !== void 0) {
3435
- (packetSequenceNumbers ?? (packetSequenceNumbers = [])).push(...seg.packetSequenceNumbers);
3405
+ (packetSequenceNumbers ??= []).push(...seg.packetSequenceNumbers);
3436
3406
  }
3437
3407
  if (seg.repairedPacketSequenceNumbers !== void 0) {
3438
- (repairedPacketSequenceNumbers ?? (repairedPacketSequenceNumbers = [])).push(...seg.repairedPacketSequenceNumbers);
3408
+ (repairedPacketSequenceNumbers ??= []).push(...seg.repairedPacketSequenceNumbers);
3439
3409
  }
3440
3410
  if (first === void 0) first = seg;
3441
3411
  }
@@ -4814,22 +4784,20 @@ function sameTrack(a, b) {
4814
4784
  function sameSample(a, b) {
4815
4785
  return a.decodeTime === b.decodeTime && a.presentationTime === b.presentationTime && a.duration === b.duration && a.timescale === b.timescale && a.size === b.size && a.bytePosition === b.bytePosition;
4816
4786
  }
4817
- var _track, _fragments, _pendingSamples, _evictedSamples, _lastMovieFragmentRejection, _IsoBmffTimingResolver_instances, evictOldestFragment_fn, clearSlot_fn;
4818
4787
  var IsoBmffTimingResolver = class {
4819
4788
  constructor(maxPendingSamples) {
4820
4789
  this.maxPendingSamples = maxPendingSamples;
4821
- __privateAdd(this, _IsoBmffTimingResolver_instances);
4822
- __privateAdd(this, _track, null);
4823
- __privateAdd(this, _fragments, /* @__PURE__ */ new Map());
4824
- __privateAdd(this, _pendingSamples, 0);
4825
- __privateAdd(this, _evictedSamples, 0);
4826
- __privateAdd(this, _lastMovieFragmentRejection, null);
4827
4790
  if (!Number.isInteger(maxPendingSamples) || maxPendingSamples <= 0) {
4828
4791
  throw new Error("[IsoBmffTimingResolver] maxPendingSamples must be a positive integer");
4829
4792
  }
4830
4793
  }
4794
+ #track = null;
4795
+ #fragments = /* @__PURE__ */ new Map();
4796
+ #pendingSamples = 0;
4797
+ #evictedSamples = 0;
4798
+ #lastMovieFragmentRejection = null;
4831
4799
  get pendingSampleCount() {
4832
- return __privateGet(this, _pendingSamples);
4800
+ return this.#pendingSamples;
4833
4801
  }
4834
4802
  /**
4835
4803
  * Slots reclaimed by window displacement rather than by delivery or
@@ -4838,77 +4806,77 @@ var IsoBmffTimingResolver = class {
4838
4806
  * different failures with different owners, and one number cannot say which.
4839
4807
  */
4840
4808
  get evictedSampleCount() {
4841
- return __privateGet(this, _evictedSamples);
4809
+ return this.#evictedSamples;
4842
4810
  }
4843
4811
  /** Typed reason for the most recent rejected movie fragment. */
4844
4812
  get lastMovieFragmentRejection() {
4845
- return __privateGet(this, _lastMovieFragmentRejection);
4813
+ return this.#lastMovieFragmentRejection;
4846
4814
  }
4847
4815
  addInitialization(data) {
4848
4816
  const timing = parseIsoBmffInitializationTiming(data);
4849
4817
  if (!timing) return false;
4850
- if (__privateGet(this, _track)) return sameTrack(__privateGet(this, _track), timing);
4851
- __privateSet(this, _track, timing);
4818
+ if (this.#track) return sameTrack(this.#track, timing);
4819
+ this.#track = timing;
4852
4820
  return true;
4853
4821
  }
4854
4822
  addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
4855
- __privateSet(this, _lastMovieFragmentRejection, null);
4823
+ this.#lastMovieFragmentRejection = null;
4856
4824
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
4857
- __privateSet(this, _lastMovieFragmentRejection, "invalid");
4825
+ this.#lastMovieFragmentRejection = "invalid";
4858
4826
  return false;
4859
4827
  }
4860
- if (!__privateGet(this, _track) || !isU322(mpuSequenceNumber)) {
4861
- __privateSet(this, _lastMovieFragmentRejection, "invalid");
4828
+ if (!this.#track || !isU322(mpuSequenceNumber)) {
4829
+ this.#lastMovieFragmentRejection = "invalid";
4862
4830
  return false;
4863
4831
  }
4864
4832
  const parsed = parseIsoBmffMovieFragmentTiming(
4865
4833
  data,
4866
- __privateGet(this, _track),
4834
+ this.#track,
4867
4835
  this.maxPendingSamples
4868
4836
  );
4869
4837
  if (!parsed) {
4870
- __privateSet(this, _lastMovieFragmentRejection, "invalid");
4838
+ this.#lastMovieFragmentRejection = "invalid";
4871
4839
  return false;
4872
4840
  }
4873
4841
  const key = fragmentKey(mpuSequenceNumber, parsed.movieFragmentSequenceNumber);
4874
- const existing = __privateGet(this, _fragments).get(key);
4842
+ const existing = this.#fragments.get(key);
4875
4843
  if (existing) {
4876
4844
  return existing.length === parsed.samples.length && existing.every(
4877
4845
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
4878
4846
  );
4879
4847
  }
4880
4848
  let freed = 0;
4881
- while (__privateGet(this, _fragments).size > 0 && (__privateGet(this, _pendingSamples) + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
4882
- freed += __privateMethod(this, _IsoBmffTimingResolver_instances, evictOldestFragment_fn).call(this);
4849
+ while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
4850
+ freed += this.#evictOldestFragment();
4883
4851
  }
4884
4852
  if (parsed.samples.length - freed > additionalSampleLimit) {
4885
- __privateSet(this, _lastMovieFragmentRejection, "budget");
4853
+ this.#lastMovieFragmentRejection = "budget";
4886
4854
  return false;
4887
4855
  }
4888
- if (__privateGet(this, _pendingSamples) + parsed.samples.length > this.maxPendingSamples) {
4889
- __privateSet(this, _lastMovieFragmentRejection, "budget");
4856
+ if (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples) {
4857
+ this.#lastMovieFragmentRejection = "budget";
4890
4858
  return false;
4891
4859
  }
4892
- __privateGet(this, _fragments).set(key, [...parsed.samples]);
4893
- __privateSet(this, _pendingSamples, __privateGet(this, _pendingSamples) + parsed.samples.length);
4860
+ this.#fragments.set(key, [...parsed.samples]);
4861
+ this.#pendingSamples += parsed.samples.length;
4894
4862
  return true;
4895
4863
  }
4896
4864
  sampleTiming(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) {
4897
4865
  if (!isU322(mpuSequenceNumber) || !isU322(movieFragmentSequenceNumber) || movieFragmentSequenceNumber === 0 || !isU322(sampleNumber) || sampleNumber === 0) {
4898
4866
  return null;
4899
4867
  }
4900
- const samples = __privateGet(this, _fragments).get(
4868
+ const samples = this.#fragments.get(
4901
4869
  fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber)
4902
4870
  );
4903
4871
  return samples?.[sampleNumber - 1] ?? null;
4904
4872
  }
4905
4873
  consumeSample(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, expected) {
4906
- const samples = __privateGet(this, _fragments).get(
4874
+ const samples = this.#fragments.get(
4907
4875
  fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber)
4908
4876
  );
4909
4877
  const sample = samples?.[sampleNumber - 1];
4910
4878
  if (!sample || !sameSample(sample, expected)) return false;
4911
- return __privateMethod(this, _IsoBmffTimingResolver_instances, clearSlot_fn).call(this, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber);
4879
+ return this.#clearSlot(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber);
4912
4880
  }
4913
4881
  /**
4914
4882
  * Free the budget slot of a sample that will never be delivered.
@@ -4931,51 +4899,45 @@ var IsoBmffTimingResolver = class {
4931
4899
  * was already freed, so a double release cannot drive the count negative.
4932
4900
  */
4933
4901
  releaseSample(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) {
4934
- return __privateMethod(this, _IsoBmffTimingResolver_instances, clearSlot_fn).call(this, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber);
4902
+ return this.#clearSlot(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber);
4935
4903
  }
4936
- reset() {
4937
- __privateSet(this, _track, null);
4938
- __privateGet(this, _fragments).clear();
4939
- __privateSet(this, _pendingSamples, 0);
4904
+ /**
4905
+ * Drop the oldest pending fragment whole and return the slots it held.
4906
+ *
4907
+ * Oldest is insertion order, which for a moof stream is arrival order, so
4908
+ * this is the least-recently-declared timing -- the entries least likely to
4909
+ * still have data units in flight.
4910
+ */
4911
+ #evictOldestFragment() {
4912
+ const oldest = this.#fragments.keys().next().value;
4913
+ if (oldest === void 0) return 0;
4914
+ const samples = this.#fragments.get(oldest);
4915
+ let live = 0;
4916
+ for (const sample of samples) if (sample !== null) live++;
4917
+ this.#fragments.delete(oldest);
4918
+ this.#pendingSamples -= live;
4919
+ this.#evictedSamples += live;
4920
+ return live;
4921
+ }
4922
+ /** Null one slot, decrement the budget, and drop the fragment when empty. */
4923
+ #clearSlot(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) {
4924
+ if (!isU322(mpuSequenceNumber) || !isU322(movieFragmentSequenceNumber) || movieFragmentSequenceNumber === 0 || !isU322(sampleNumber) || sampleNumber === 0) {
4925
+ return false;
4926
+ }
4927
+ const key = fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber);
4928
+ const samples = this.#fragments.get(key);
4929
+ const index = sampleNumber - 1;
4930
+ if (!samples || !samples[index]) return false;
4931
+ samples[index] = null;
4932
+ this.#pendingSamples--;
4933
+ if (samples.every((value) => value === null)) this.#fragments.delete(key);
4934
+ return true;
4940
4935
  }
4941
- };
4942
- _track = new WeakMap();
4943
- _fragments = new WeakMap();
4944
- _pendingSamples = new WeakMap();
4945
- _evictedSamples = new WeakMap();
4946
- _lastMovieFragmentRejection = new WeakMap();
4947
- _IsoBmffTimingResolver_instances = new WeakSet();
4948
- /**
4949
- * Drop the oldest pending fragment whole and return the slots it held.
4950
- *
4951
- * Oldest is insertion order, which for a moof stream is arrival order, so
4952
- * this is the least-recently-declared timing -- the entries least likely to
4953
- * still have data units in flight.
4954
- */
4955
- evictOldestFragment_fn = function() {
4956
- const oldest = __privateGet(this, _fragments).keys().next().value;
4957
- if (oldest === void 0) return 0;
4958
- const samples = __privateGet(this, _fragments).get(oldest);
4959
- let live = 0;
4960
- for (const sample of samples) if (sample !== null) live++;
4961
- __privateGet(this, _fragments).delete(oldest);
4962
- __privateSet(this, _pendingSamples, __privateGet(this, _pendingSamples) - live);
4963
- __privateSet(this, _evictedSamples, __privateGet(this, _evictedSamples) + live);
4964
- return live;
4965
- };
4966
- /** Null one slot, decrement the budget, and drop the fragment when empty. */
4967
- clearSlot_fn = function(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) {
4968
- if (!isU322(mpuSequenceNumber) || !isU322(movieFragmentSequenceNumber) || movieFragmentSequenceNumber === 0 || !isU322(sampleNumber) || sampleNumber === 0) {
4969
- return false;
4936
+ reset() {
4937
+ this.#track = null;
4938
+ this.#fragments.clear();
4939
+ this.#pendingSamples = 0;
4970
4940
  }
4971
- const key = fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber);
4972
- const samples = __privateGet(this, _fragments).get(key);
4973
- const index = sampleNumber - 1;
4974
- if (!samples || !samples[index]) return false;
4975
- samples[index] = null;
4976
- __privateWrapper(this, _pendingSamples)._--;
4977
- if (samples.every((value) => value === null)) __privateGet(this, _fragments).delete(key);
4978
- return true;
4979
4941
  };
4980
4942
  function fragmentKey(mpuSequenceNumber, movieFragmentSequenceNumber) {
4981
4943
  return `${mpuSequenceNumber}:${movieFragmentSequenceNumber}`;
@@ -5030,41 +4992,39 @@ function compareFrameOrder(a, b) {
5030
4992
  const sampleDelta = (a.meta.sampleNumber ?? 0) - (b.meta.sampleNumber ?? 0);
5031
4993
  return sampleDelta !== 0 ? sampleDelta : serialSequenceDelta(a.seq, b.seq);
5032
4994
  }
5033
- var _streams, _windowSize, _emit, _recordStat, _FrameSequencer_instances, streamFor_fn, flushHead_fn, isStale_fn, emitFrame_fn;
5034
4995
  var FrameSequencer = class {
4996
+ #streams = /* @__PURE__ */ new Map();
4997
+ #windowSize;
4998
+ #emit;
4999
+ #recordStat;
5035
5000
  constructor(windowSize, emit, recordStat = () => {
5036
5001
  }) {
5037
- __privateAdd(this, _FrameSequencer_instances);
5038
- __privateAdd(this, _streams, /* @__PURE__ */ new Map());
5039
- __privateAdd(this, _windowSize);
5040
- __privateAdd(this, _emit);
5041
- __privateAdd(this, _recordStat);
5042
- __privateSet(this, _windowSize, windowSize);
5043
- __privateSet(this, _emit, emit);
5044
- __privateSet(this, _recordStat, recordStat);
5002
+ this.#windowSize = windowSize;
5003
+ this.#emit = emit;
5004
+ this.#recordStat = recordStat;
5045
5005
  }
5046
5006
  push(data, meta, seq) {
5047
- if (__privateGet(this, _windowSize) <= 0) {
5048
- __privateGet(this, _emit).call(this, data, meta);
5007
+ if (this.#windowSize <= 0) {
5008
+ this.#emit(data, meta);
5049
5009
  return;
5050
5010
  }
5051
5011
  const frame = { data, meta: { ...meta }, seq };
5052
- const stream = __privateMethod(this, _FrameSequencer_instances, streamFor_fn).call(this, meta.packetId);
5012
+ const stream = this.#streamFor(meta.packetId);
5053
5013
  if (meta.sourceDiscontinuity) {
5054
- __privateGet(this, _recordStat).call(this, "publisherResets");
5055
- __privateGet(this, _recordStat).call(this, "droppedOnPublisherReset", stream.buf.length);
5014
+ this.#recordStat("publisherResets");
5015
+ this.#recordStat("droppedOnPublisherReset", stream.buf.length);
5056
5016
  stream.buf = [];
5057
5017
  stream.lastEmitted = null;
5058
5018
  frame.meta.sourceDiscontinuity = true;
5059
5019
  }
5060
- if (__privateMethod(this, _FrameSequencer_instances, isStale_fn).call(this, stream, frame)) {
5061
- __privateGet(this, _recordStat).call(this, "droppedStale");
5020
+ if (this.#isStale(stream, frame)) {
5021
+ this.#recordStat("droppedStale");
5062
5022
  return;
5063
5023
  }
5064
5024
  if (meta.keyframe && stream.lastEmitted === null) {
5065
- __privateGet(this, _recordStat).call(this, "droppedBeforeStartupKeyframe", stream.buf.length);
5025
+ this.#recordStat("droppedBeforeStartupKeyframe", stream.buf.length);
5066
5026
  stream.buf = [];
5067
- __privateMethod(this, _FrameSequencer_instances, emitFrame_fn).call(this, stream, frame);
5027
+ this.#emitFrame(stream, frame);
5068
5028
  return;
5069
5029
  }
5070
5030
  let lo = 0, hi = stream.buf.length;
@@ -5074,21 +5034,21 @@ var FrameSequencer = class {
5074
5034
  else hi = mid;
5075
5035
  }
5076
5036
  stream.buf.splice(lo, 0, frame);
5077
- while (stream.buf.length > __privateGet(this, _windowSize)) __privateMethod(this, _FrameSequencer_instances, flushHead_fn).call(this, stream);
5037
+ while (stream.buf.length > this.#windowSize) this.#flushHead(stream);
5078
5038
  }
5079
5039
  flush() {
5080
- for (const packetId of [...__privateGet(this, _streams).keys()].sort((a, b) => a - b)) {
5081
- const stream = __privateGet(this, _streams).get(packetId);
5082
- while (stream && stream.buf.length > 0) __privateMethod(this, _FrameSequencer_instances, flushHead_fn).call(this, stream);
5040
+ for (const packetId of [...this.#streams.keys()].sort((a, b) => a - b)) {
5041
+ const stream = this.#streams.get(packetId);
5042
+ while (stream && stream.buf.length > 0) this.#flushHead(stream);
5083
5043
  }
5084
5044
  }
5085
5045
  get buffered() {
5086
5046
  let total = 0;
5087
- for (const stream of __privateGet(this, _streams).values()) total += stream.buf.length;
5047
+ for (const stream of this.#streams.values()) total += stream.buf.length;
5088
5048
  return total;
5089
5049
  }
5090
5050
  get diagnostics() {
5091
- return [...__privateGet(this, _streams).values()].map((stream) => ({
5051
+ return [...this.#streams.values()].map((stream) => ({
5092
5052
  bufferedFrames: stream.buf.length,
5093
5053
  lastEmitted: stream.lastEmitted ? reorderFrameDiagnostics(stream.lastEmitted) : null,
5094
5054
  startupKeyframe: null,
@@ -5098,42 +5058,37 @@ var FrameSequencer = class {
5098
5058
  }));
5099
5059
  }
5100
5060
  discard() {
5101
- for (const stream of __privateGet(this, _streams).values()) {
5102
- __privateGet(this, _recordStat).call(this, "droppedOnLiveDispose", stream.buf.length);
5061
+ for (const stream of this.#streams.values()) {
5062
+ this.#recordStat("droppedOnLiveDispose", stream.buf.length);
5103
5063
  stream.buf = [];
5104
5064
  }
5105
- __privateGet(this, _streams).clear();
5065
+ this.#streams.clear();
5106
5066
  }
5107
- };
5108
- _streams = new WeakMap();
5109
- _windowSize = new WeakMap();
5110
- _emit = new WeakMap();
5111
- _recordStat = new WeakMap();
5112
- _FrameSequencer_instances = new WeakSet();
5113
- streamFor_fn = function(packetId) {
5114
- let stream = __privateGet(this, _streams).get(packetId);
5115
- if (!stream) {
5116
- stream = { buf: [], lastEmitted: null };
5117
- __privateGet(this, _streams).set(packetId, stream);
5118
- }
5119
- return stream;
5120
- };
5121
- flushHead_fn = function(stream) {
5122
- const f = stream.buf.shift();
5123
- if (!f) return false;
5124
- return __privateMethod(this, _FrameSequencer_instances, emitFrame_fn).call(this, stream, f);
5125
- };
5126
- isStale_fn = function(stream, frame) {
5127
- return stream.lastEmitted !== null && compareFrameOrder(frame, stream.lastEmitted) <= 0;
5128
- };
5129
- emitFrame_fn = function(stream, frame) {
5130
- if (__privateMethod(this, _FrameSequencer_instances, isStale_fn).call(this, stream, frame)) {
5131
- __privateGet(this, _recordStat).call(this, "droppedStale");
5132
- return false;
5067
+ #streamFor(packetId) {
5068
+ let stream = this.#streams.get(packetId);
5069
+ if (!stream) {
5070
+ stream = { buf: [], lastEmitted: null };
5071
+ this.#streams.set(packetId, stream);
5072
+ }
5073
+ return stream;
5074
+ }
5075
+ #flushHead(stream) {
5076
+ const f = stream.buf.shift();
5077
+ if (!f) return false;
5078
+ return this.#emitFrame(stream, f);
5079
+ }
5080
+ #isStale(stream, frame) {
5081
+ return stream.lastEmitted !== null && compareFrameOrder(frame, stream.lastEmitted) <= 0;
5082
+ }
5083
+ #emitFrame(stream, frame) {
5084
+ if (this.#isStale(stream, frame)) {
5085
+ this.#recordStat("droppedStale");
5086
+ return false;
5087
+ }
5088
+ stream.lastEmitted = frame;
5089
+ this.#emit(frame.data, frame.meta);
5090
+ return true;
5133
5091
  }
5134
- stream.lastEmitted = frame;
5135
- __privateGet(this, _emit).call(this, frame.data, frame.meta);
5136
- return true;
5137
5092
  };
5138
5093
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
5139
5094
  function isFmp4Box(data) {
@@ -5141,13 +5096,10 @@ function isFmp4Box(data) {
5141
5096
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
5142
5097
  return FMPU_BOX_TYPES.has(type);
5143
5098
  }
5144
- var _tracks, _defaultTrack, _reassembler, _sampleCombiners, _sampleCombinerOptions, _retiredSampleCombinerStats, _timingStreams, _maxPendingTimingSamples, _pendingTimingSamples, _reclaimedTimingSamples, _evictedTimingSamples, _rejectedMovieFragments, _sequencers, _reorderWindow, _reassemblyPolicy, _frameCb, _initCb, _sourceSymbolCb, _trackFrameCbs, _reorderStats, _reliableMoqStartupGate, _disposed, _fedObjects, _feedOutcomes, _deferredFeedOutcomes, _lastOutcome, _lastOutcomeCount, _MmtpContainerParser_instances, streamKey_fn, sampleCombinerFor_fn, releaseTimingSlot_fn, dropSampleCombiner_fn, countOutcome_fn, countDeferredOutcome_fn, drop_fn, feed_fn, emitCombinedSample_fn, passReliableMoqStartupGate_fn, timingResolver_fn, dropTimingStream_fn, validateReassemblyPolicy_fn, buildFrameMeta_fn, sequencerFor_fn, flushSequencers_fn, emitFrame_fn2, _MmtpContainerParser_static, scanForKeyframe_fn, scanLengthPrefixedHevcForKeyframe_fn, scanAnnexBForKeyframe_fn;
5145
- var _MmtpContainerParser = class _MmtpContainerParser {
5099
+ var MmtpContainerParser = class _MmtpContainerParser {
5146
5100
  constructor(config) {
5147
- __privateAdd(this, _MmtpContainerParser_instances);
5148
- __privateAdd(this, _tracks, /* @__PURE__ */ new Map());
5149
- __privateAdd(this, _defaultTrack, null);
5150
- __privateAdd(this, _reassembler);
5101
+ this.#tracks = /* @__PURE__ */ new Map();
5102
+ this.#defaultTrack = null;
5151
5103
  /**
5152
5104
  * Combines subsample data units back into whole samples (moqcast #37), one
5153
5105
  * combiner per parser stream. Per-stream is required, not an optimization:
@@ -5161,30 +5113,28 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5161
5113
  * exceeds one data unit's 256-payload capacity (~327 KB here, routinely
5162
5114
  * exceeded by 4K/8K intra frames).
5163
5115
  */
5164
- __privateAdd(this, _sampleCombiners, /* @__PURE__ */ new Map());
5165
- __privateAdd(this, _sampleCombinerOptions);
5116
+ this.#sampleCombiners = /* @__PURE__ */ new Map();
5166
5117
  /** Counters folded in from combiners dropped by a track reset, so the
5167
5118
  * totals below stay monotonic across a publisher change. */
5168
- __privateAdd(this, _retiredSampleCombinerStats, {
5119
+ this.#retiredSampleCombinerStats = {
5169
5120
  combinedSamples: 0,
5170
5121
  passthroughSamples: 0,
5171
5122
  timedOutSamples: 0,
5172
5123
  evictedSamples: 0
5173
- });
5174
- __privateAdd(this, _timingStreams, /* @__PURE__ */ new Map());
5175
- __privateAdd(this, _maxPendingTimingSamples);
5176
- __privateAdd(this, _pendingTimingSamples, 0);
5177
- __privateAdd(this, _reclaimedTimingSamples, 0);
5178
- __privateAdd(this, _evictedTimingSamples, 0);
5179
- __privateAdd(this, _rejectedMovieFragments, 0);
5180
- __privateAdd(this, _sequencers, /* @__PURE__ */ new Map());
5181
- __privateAdd(this, _reorderWindow, 0);
5182
- __privateAdd(this, _reassemblyPolicy, null);
5183
- __privateAdd(this, _frameCb, null);
5184
- __privateAdd(this, _initCb, null);
5185
- __privateAdd(this, _sourceSymbolCb, null);
5186
- __privateAdd(this, _trackFrameCbs, /* @__PURE__ */ new Map());
5187
- __privateAdd(this, _reorderStats, {
5124
+ };
5125
+ this.#timingStreams = /* @__PURE__ */ new Map();
5126
+ this.#pendingTimingSamples = 0;
5127
+ this.#reclaimedTimingSamples = 0;
5128
+ this.#evictedTimingSamples = 0;
5129
+ this.#rejectedMovieFragments = 0;
5130
+ this.#sequencers = /* @__PURE__ */ new Map();
5131
+ this.#reorderWindow = 0;
5132
+ this.#reassemblyPolicy = null;
5133
+ this.#frameCb = null;
5134
+ this.#initCb = null;
5135
+ this.#sourceSymbolCb = null;
5136
+ this.#trackFrameCbs = /* @__PURE__ */ new Map();
5137
+ this.#reorderStats = {
5188
5138
  droppedBeforeStartupKeyframe: 0,
5189
5139
  droppedIncompleteStartupInterval: 0,
5190
5140
  droppedStale: 0,
@@ -5192,7 +5142,7 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5192
5142
  droppedOnLiveDispose: 0,
5193
5143
  publisherResets: 0,
5194
5144
  droppedOnPublisherReset: 0
5195
- });
5145
+ };
5196
5146
  /** Streams (keyed by physical parser stream, value is packetId) that have
5197
5147
  * observed their first RAP under a reliable-moq policy. Reliable MoQ
5198
5148
  * resolves to a zero parser reorder window (transport ordering is
@@ -5200,13 +5150,15 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5200
5150
  * never runs; this map preserves an order-independent "discard delta
5201
5151
  * frames before the first RAP" gate for that path without reintroducing
5202
5152
  * reordering into the parser. */
5203
- __privateAdd(this, _reliableMoqStartupGate, /* @__PURE__ */ new Map());
5204
- __privateAdd(this, _disposed, false);
5205
- __privateAdd(this, _fedObjects, 0);
5206
- __privateAdd(this, _feedOutcomes, /* @__PURE__ */ new Map());
5207
- __privateAdd(this, _deferredFeedOutcomes, /* @__PURE__ */ new Map());
5208
- __privateAdd(this, _lastOutcome, null);
5209
- __privateAdd(this, _lastOutcomeCount, 0);
5153
+ this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
5154
+ this.#disposed = false;
5155
+ this.#fedObjects = 0;
5156
+ this.#reassemblerFragmentsFed = 0;
5157
+ this.#reassemblerDataUnitsReturned = 0;
5158
+ this.#feedOutcomes = /* @__PURE__ */ new Map();
5159
+ this.#deferredFeedOutcomes = /* @__PURE__ */ new Map();
5160
+ this.#lastOutcome = null;
5161
+ this.#lastOutcomeCount = 0;
5210
5162
  /** Authored presentation timestamp of the last emitted frame, in microseconds. */
5211
5163
  this.lastFrameTimestamp = void 0;
5212
5164
  if (config?.reassemblyPolicy && config.mfuTimeoutMs !== void 0) {
@@ -5229,25 +5181,25 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5229
5181
  if (!Number.isInteger(maxPendingTimingSamples) || maxPendingTimingSamples <= 0) {
5230
5182
  throw new Error("[MmtpContainerParser] maxBufferedMfus must be a positive integer");
5231
5183
  }
5232
- __privateSet(this, _maxPendingTimingSamples, maxPendingTimingSamples);
5184
+ this.#maxPendingTimingSamples = maxPendingTimingSamples;
5233
5185
  const maxSubsampleSegments = config?.maxSubsampleSegments ?? 16;
5234
5186
  if (!Number.isInteger(maxSubsampleSegments) || maxSubsampleSegments <= 0) {
5235
5187
  throw new Error("[MmtpContainerParser] maxSubsampleSegments must be a positive integer");
5236
5188
  }
5237
- __privateSet(this, _reassemblyPolicy, reassemblyPolicy);
5189
+ this.#reassemblyPolicy = reassemblyPolicy;
5238
5190
  if (config?.reassembler) {
5239
- __privateSet(this, _reassembler, config.reassembler);
5191
+ this.#reassembler = config.reassembler;
5240
5192
  if (requestedMfuTimeout !== void 0) {
5241
- __privateGet(this, _reassembler).timeoutMs = requestedMfuTimeout;
5193
+ this.#reassembler.timeoutMs = requestedMfuTimeout;
5242
5194
  }
5243
5195
  } else {
5244
- __privateSet(this, _reassembler, new MFUReassembler({
5196
+ this.#reassembler = new MFUReassembler({
5245
5197
  timeoutMs: requestedMfuTimeout === void 0 ? 1e3 : requestedMfuTimeout,
5246
5198
  ...config?.maxBufferedMfus === void 0 ? {} : { maxBuffered: config.maxBufferedMfus }
5247
- }));
5199
+ });
5248
5200
  }
5249
- __privateSet(this, _reorderWindow, normalizedReorderWindow);
5250
- __privateSet(this, _sampleCombinerOptions, {
5201
+ this.#reorderWindow = normalizedReorderWindow;
5202
+ this.#sampleCombinerOptions = {
5251
5203
  maxBuffered: maxPendingTimingSamples,
5252
5204
  // The parser resolves every timed sample's authored size from FT=1
5253
5205
  // before its data units reach the combiner, so "no size yet" always
@@ -5257,16 +5209,99 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5257
5209
  // partitioned sample instead of completing it.
5258
5210
  requireAuthoredSize: true,
5259
5211
  maxSegmentsPerSample: maxSubsampleSegments
5260
- });
5261
- __privateSet(this, _defaultTrack, config?.defaultTrack ?? null);
5262
- if (__privateGet(this, _defaultTrack)) __privateMethod(this, _MmtpContainerParser_instances, validateReassemblyPolicy_fn).call(this);
5212
+ };
5213
+ this.#defaultTrack = config?.defaultTrack ?? null;
5214
+ if (this.#defaultTrack) this.#validateReassemblyPolicy();
5263
5215
  if (config?.tracks) {
5264
5216
  for (const [id, info] of config.tracks) {
5265
- __privateMethod(this, _MmtpContainerParser_instances, validateReassemblyPolicy_fn).call(this);
5266
- __privateGet(this, _tracks).set(id, info);
5217
+ this.#validateReassemblyPolicy();
5218
+ this.#tracks.set(id, info);
5267
5219
  }
5268
5220
  }
5269
5221
  }
5222
+ #tracks;
5223
+ #defaultTrack;
5224
+ #reassembler;
5225
+ #sampleCombiners;
5226
+ #sampleCombinerOptions;
5227
+ #retiredSampleCombinerStats;
5228
+ #timingStreams;
5229
+ #maxPendingTimingSamples;
5230
+ #pendingTimingSamples;
5231
+ #reclaimedTimingSamples;
5232
+ #evictedTimingSamples;
5233
+ #rejectedMovieFragments;
5234
+ #sequencers;
5235
+ #reorderWindow;
5236
+ #reassemblyPolicy;
5237
+ #frameCb;
5238
+ #initCb;
5239
+ #sourceSymbolCb;
5240
+ #trackFrameCbs;
5241
+ #reorderStats;
5242
+ #reliableMoqStartupGate;
5243
+ #disposed;
5244
+ #fedObjects;
5245
+ #reassemblerFragmentsFed;
5246
+ #reassemblerDataUnitsReturned;
5247
+ #feedOutcomes;
5248
+ #deferredFeedOutcomes;
5249
+ #lastOutcome;
5250
+ #lastOutcomeCount;
5251
+ #streamKey(packetId, catalogTrackName) {
5252
+ return JSON.stringify([packetId, catalogTrackName ?? null]);
5253
+ }
5254
+ #sampleCombinerFor(streamKey) {
5255
+ let combiner = this.#sampleCombiners.get(streamKey);
5256
+ if (combiner === void 0) {
5257
+ combiner = new SampleCombiner({
5258
+ ...this.#sampleCombinerOptions,
5259
+ onAbandon: (sample) => this.#releaseTimingSlot(streamKey, sample)
5260
+ });
5261
+ this.#sampleCombiners.set(streamKey, combiner);
5262
+ }
5263
+ return combiner;
5264
+ }
5265
+ /**
5266
+ * Return the timing budget slot of a sample the combiner abandoned.
5267
+ *
5268
+ * Without this, `#pendingTimingSamples` is charged for every sample a moof
5269
+ * declares but credited only when that sample is delivered, so each sample
5270
+ * lost to eviction or timeout burns a slot until the window displaces it.
5271
+ * Window displacement bounds that leak but only reclaims the OLDEST entries;
5272
+ * this path returns a slot the moment the combiner knows the sample is gone,
5273
+ * which keeps the live window as wide as the stream actually needs.
5274
+ *
5275
+ * The parser total is decremented only when the resolver reports it
5276
+ * actually freed a slot, so a resolver already dropped by a track reset, or
5277
+ * a sample released twice, cannot drive the accounting negative.
5278
+ */
5279
+ #releaseTimingSlot(streamKey, sample) {
5280
+ const resolver = this.#timingStreams.get(streamKey)?.resolver;
5281
+ if (!resolver) return;
5282
+ if (!resolver.releaseSample(
5283
+ sample.mpuSequenceNumber,
5284
+ sample.movieFragmentSequenceNumber,
5285
+ sample.sampleNumber
5286
+ )) return;
5287
+ this.#pendingTimingSamples--;
5288
+ this.#reclaimedTimingSamples++;
5289
+ if (this.#pendingTimingSamples < 0) {
5290
+ throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
5291
+ }
5292
+ }
5293
+ /** Drop one stream's combiner, folding its counters into the retained
5294
+ * totals so a reset cannot make the exposed stats run backwards. */
5295
+ #dropSampleCombiner(streamKey) {
5296
+ const combiner = this.#sampleCombiners.get(streamKey);
5297
+ if (combiner === void 0) return;
5298
+ const stats = combiner.stats;
5299
+ this.#retiredSampleCombinerStats.combinedSamples += stats.combinedSamples;
5300
+ this.#retiredSampleCombinerStats.passthroughSamples += stats.passthroughSamples;
5301
+ this.#retiredSampleCombinerStats.timedOutSamples += stats.timedOutSamples;
5302
+ this.#retiredSampleCombinerStats.evictedSamples += stats.evictedSamples;
5303
+ this.#sampleCombiners.delete(streamKey);
5304
+ }
5270
5305
  /** The MFU reassembler that buffers fragmented MFUs fed via feed().
5271
5306
  * Exposed so a co-operating FEC-recovery layer (MmtpRouter) feeds recovered
5272
5307
  * fragments into the SAME reassembler: a frame split between source-received
@@ -5274,7 +5309,7 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5274
5309
  * Before this was shared, recovered video symbols reported "0 emitted,
5275
5310
  * pending-reassembly=N" because they landed in a separate instance. */
5276
5311
  get reassembler() {
5277
- return __privateGet(this, _reassembler);
5312
+ return this.#reassembler;
5278
5313
  }
5279
5314
  /**
5280
5315
  * Subsample-combining counters (moqcast #37). `combinedSamples` counts
@@ -5285,8 +5320,8 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5285
5320
  * large-frame playback — never parse the console for it.
5286
5321
  */
5287
5322
  get sampleCombinerStats() {
5288
- const total = { ...__privateGet(this, _retiredSampleCombinerStats) };
5289
- for (const combiner of __privateGet(this, _sampleCombiners).values()) {
5323
+ const total = { ...this.#retiredSampleCombinerStats };
5324
+ for (const combiner of this.#sampleCombiners.values()) {
5290
5325
  const stats = combiner.stats;
5291
5326
  total.combinedSamples += stats.combinedSamples;
5292
5327
  total.passthroughSamples += stats.passthroughSamples;
@@ -5306,17 +5341,17 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5306
5341
  */
5307
5342
  get timingBudgetStats() {
5308
5343
  return {
5309
- pending: __privateGet(this, _pendingTimingSamples),
5310
- capacity: __privateGet(this, _maxPendingTimingSamples),
5311
- reclaimed: __privateGet(this, _reclaimedTimingSamples),
5312
- evicted: __privateGet(this, _evictedTimingSamples),
5313
- rejectedMovieFragments: __privateGet(this, _rejectedMovieFragments)
5344
+ pending: this.#pendingTimingSamples,
5345
+ capacity: this.#maxPendingTimingSamples,
5346
+ reclaimed: this.#reclaimedTimingSamples,
5347
+ evicted: this.#evictedTimingSamples,
5348
+ rejectedMovieFragments: this.#rejectedMovieFragments
5314
5349
  };
5315
5350
  }
5316
5351
  get reorderStats() {
5317
5352
  let bufferedFrames = 0;
5318
- for (const { sequencer } of __privateGet(this, _sequencers).values()) bufferedFrames += sequencer.buffered;
5319
- return { ...__privateGet(this, _reorderStats), bufferedFrames };
5353
+ for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
5354
+ return { ...this.#reorderStats, bufferedFrames };
5320
5355
  }
5321
5356
  /**
5322
5357
  * Feed tallies for this parser. A fresh snapshot per call, not a live view,
@@ -5328,9 +5363,9 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5328
5363
  */
5329
5364
  get feedStats() {
5330
5365
  return {
5331
- fedObjects: __privateGet(this, _fedObjects),
5332
- outcomes: Object.fromEntries(__privateGet(this, _feedOutcomes)),
5333
- deferredOutcomes: Object.fromEntries(__privateGet(this, _deferredFeedOutcomes))
5366
+ fedObjects: this.#fedObjects,
5367
+ outcomes: Object.fromEntries(this.#feedOutcomes),
5368
+ deferredOutcomes: Object.fromEntries(this.#deferredFeedOutcomes)
5334
5369
  };
5335
5370
  }
5336
5371
  /**
@@ -5341,16 +5376,50 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5341
5376
  * allocates a fresh snapshot per call.
5342
5377
  */
5343
5378
  get lastFeedOutcome() {
5344
- return __privateGet(this, _lastOutcome);
5379
+ return this.#lastOutcome;
5345
5380
  }
5346
5381
  /** How many times `lastFeedOutcome` has now been seen. 1 on its first
5347
5382
  * occurrence, which is what a caller logging once per novel outcome needs. */
5348
5383
  get lastFeedOutcomeCount() {
5349
- return __privateGet(this, _lastOutcomeCount);
5384
+ return this.#lastOutcomeCount;
5385
+ }
5386
+ /**
5387
+ * MFU fragments feed() handed to the reassembler, including rejected ones.
5388
+ * A plain scalar a per-packet caller can difference; reading the
5389
+ * reassembler's own stats is a wasm crossing on the Rust backend
5390
+ * (BLO-36599).
5391
+ */
5392
+ get reassemblerFragmentsFed() {
5393
+ return this.#reassemblerFragmentsFed;
5394
+ }
5395
+ /** Data units the reassembler returned complete to feed(). */
5396
+ get reassemblerDataUnitsReturned() {
5397
+ return this.#reassemblerDataUnitsReturned;
5398
+ }
5399
+ #countOutcome(token) {
5400
+ const count = (this.#feedOutcomes.get(token) ?? 0) + 1;
5401
+ this.#feedOutcomes.set(token, count);
5402
+ this.#lastOutcome = token;
5403
+ this.#lastOutcomeCount = count;
5404
+ }
5405
+ #countDeferredOutcome(reason) {
5406
+ this.#deferredFeedOutcomes.set(
5407
+ reason,
5408
+ (this.#deferredFeedOutcomes.get(reason) ?? 0) + 1
5409
+ );
5410
+ }
5411
+ /**
5412
+ * Count a feed() drop and return null in one expression, so every early
5413
+ * return inside feed() states the reason it took instead of collapsing into
5414
+ * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
5415
+ */
5416
+ #drop(reason) {
5417
+ this.#countOutcome(`drop:${reason}`);
5418
+ return null;
5350
5419
  }
5351
5420
  get reorderDiagnostics() {
5352
5421
  const streams = [];
5353
- for (const { packetId, sequencer } of __privateGet(this, _sequencers).values()) {
5422
+ for (const { packetId, sequencer } of this.#sequencers.values()) {
5354
5423
  for (const diagnostics of sequencer.diagnostics) streams.push({ packetId, ...diagnostics });
5355
5424
  }
5356
5425
  return streams;
@@ -5363,9 +5432,9 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5363
5432
  * same catalog/FEC-derived deadline that bounds each constituent MFU.
5364
5433
  */
5365
5434
  cleanupTimeouts() {
5366
- const timeoutMs = __privateGet(this, _reassembler).timeoutMs;
5435
+ const timeoutMs = this.#reassembler.timeoutMs;
5367
5436
  if (timeoutMs === null) return;
5368
- for (const combiner of __privateGet(this, _sampleCombiners).values()) {
5437
+ for (const combiner of this.#sampleCombiners.values()) {
5369
5438
  combiner.cleanupTimeouts(timeoutMs);
5370
5439
  }
5371
5440
  }
@@ -5376,20 +5445,35 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5376
5445
  * Returns null for malformed packets.
5377
5446
  */
5378
5447
  parseHeader(packet, options) {
5448
+ return this.parsePacket(packet, options)?.info ?? null;
5449
+ }
5450
+ /**
5451
+ * parseHeader() that also keeps the parsed MMTP header, so a caller that
5452
+ * goes on to feedParsed() the same packet parses its header exactly once.
5453
+ * The MMTP header is parsed once here and the Source FEC Payload ID is read
5454
+ * from it; parseHeader() used to parse the header three times for an FEC
5455
+ * source packet, and feed() repeated all of it (BLO-36599).
5456
+ */
5457
+ parsePacket(packet, options) {
5379
5458
  try {
5380
5459
  const header = parseMMTPHeader(packet);
5381
5460
  const isRepair = header.packetType === PACKET_TYPE_REPAIR;
5382
- const fecPayloadId = !options?.skipFecPayloadId && !isRepair && hasSourceFecPayloadId(packet) ? extractFecPayloadId(packet) : null;
5461
+ const skipFecPayloadId = options?.skipFecPayloadId === true;
5462
+ const fecPayloadId = !skipFecPayloadId && !isRepair ? sourceFecPayloadIdOf(packet, header) : null;
5383
5463
  return {
5384
- packetId: header.packetId,
5385
- packetType: header.packetType,
5386
- timestamp: header.timestamp,
5387
- timestampUs: mmtpTimestampToMicros(header.timestamp),
5388
- sequenceNumber: header.sequenceNumber,
5389
- rapFlag: header.rapFlag,
5390
- fecType: header.fecType,
5391
- fecPayloadId,
5392
- isRepair
5464
+ info: {
5465
+ packetId: header.packetId,
5466
+ packetType: header.packetType,
5467
+ timestamp: header.timestamp,
5468
+ timestampUs: mmtpTimestampToMicros(header.timestamp),
5469
+ sequenceNumber: header.sequenceNumber,
5470
+ rapFlag: header.rapFlag,
5471
+ fecType: header.fecType,
5472
+ fecPayloadId,
5473
+ isRepair
5474
+ },
5475
+ header,
5476
+ skipFecPayloadId
5393
5477
  };
5394
5478
  } catch {
5395
5479
  return null;
@@ -5397,22 +5481,289 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5397
5481
  }
5398
5482
  /** Feed a complete MMTP packet. For two-phase use, call parseHeader() first. */
5399
5483
  feed(packet, options) {
5400
- __privateSet(this, _fedObjects, __privateGet(this, _fedObjects) + 1);
5484
+ return this.#feedCounted(packet, options, void 0);
5485
+ }
5486
+ /**
5487
+ * feed() for a packet this caller already ran through parsePacket(): the
5488
+ * header parse is reused instead of repeated. `parsed` must come from
5489
+ * parsePacket() of this same, unmodified packet. If it was resolved under a
5490
+ * different skipFecPayloadId option, the packet is parsed again.
5491
+ */
5492
+ feedParsed(packet, parsed, options) {
5493
+ return this.#feedCounted(packet, options, parsed);
5494
+ }
5495
+ #feedCounted(packet, options, parsed) {
5496
+ this.#fedObjects += 1;
5401
5497
  let record;
5402
5498
  try {
5403
- record = __privateMethod(this, _MmtpContainerParser_instances, feed_fn).call(this, packet, options);
5499
+ record = this.#feed(packet, options, parsed);
5404
5500
  } catch (error) {
5405
- __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, "drop:threw");
5501
+ this.#countOutcome("drop:threw");
5406
5502
  throw error;
5407
5503
  }
5408
- if (record) __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, record.kind);
5504
+ if (record) this.#countOutcome(record.kind);
5409
5505
  return record;
5410
5506
  }
5507
+ #feed(packet, options, preParsed) {
5508
+ if (this.#disposed) return this.#drop("disposed");
5509
+ this.cleanupTimeouts();
5510
+ const parsed = preParsed !== void 0 && preParsed.skipFecPayloadId === (options?.skipFecPayloadId === true) ? preParsed : this.parsePacket(packet, options);
5511
+ if (!parsed) return this.#drop("header-parse-failed");
5512
+ const info = parsed.info;
5513
+ if (info.packetType !== PACKET_TYPE_MPU2) {
5514
+ return {
5515
+ kind: info.isRepair ? "repair" : "non-media",
5516
+ packet: info,
5517
+ byteLength: packet.byteLength
5518
+ };
5519
+ }
5520
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
5521
+ const rawSymbol = packet.subarray(0, packet.length - 4);
5522
+ const altaTrailer = extractAltaTrailer2(packet);
5523
+ const alta = altaTrailer ? { auth: altaTrailer.auth, payloadEnd: altaTrailer.signedEnd } : void 0;
5524
+ try {
5525
+ this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol, alta);
5526
+ } catch {
5527
+ }
5528
+ }
5529
+ const extraction = extractMFUPayloadWithHeader(packet, parsed.header, {
5530
+ skipFecId: options?.skipFecPayloadId
5531
+ });
5532
+ if (!extraction) return this.#drop("mfu-extract-failed");
5533
+ const { mpu, fragmentType, data, mfuDuHeader } = extraction;
5534
+ if (mpu.timedFlag !== 1) return this.#drop("untimed-mpu");
5535
+ const streamKey = this.#streamKey(info.packetId, options?.catalogTrackName);
5536
+ if (fragmentType === 0) {
5537
+ if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
5538
+ return this.#drop("init-unexpected-fragmentation");
5539
+ const normalizedInit = normalizeMmtpInitSegment(data);
5540
+ if (!normalizedInit) return this.#drop("init-normalize-failed");
5541
+ const resolver2 = this.#timingResolver(streamKey, info.packetId, true);
5542
+ if (!resolver2?.addInitialization(normalizedInit)) return this.#drop("init-timing-refused");
5543
+ this.#initCb?.(normalizedInit, info.packetId, options?.catalogTrackName);
5544
+ return {
5545
+ kind: "init",
5546
+ packet: info,
5547
+ data: normalizedInit,
5548
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
5549
+ fragmentationIndicator: mpu.fragmentationIndicator,
5550
+ fragmentCounter: mpu.fragmentCounter
5551
+ };
5552
+ }
5553
+ if (fragmentType === 1) {
5554
+ if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
5555
+ return this.#drop("fragment-unexpected-fragmentation");
5556
+ const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
5557
+ if (!resolver2) return this.#drop("fragment-no-resolver");
5558
+ const pendingBefore = resolver2.pendingSampleCount;
5559
+ const evictedBefore = resolver2.evictedSampleCount;
5560
+ const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
5561
+ const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
5562
+ this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
5563
+ this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
5564
+ if (!admitted) {
5565
+ if (resolver2.lastMovieFragmentRejection === "budget") {
5566
+ this.#rejectedMovieFragments++;
5567
+ }
5568
+ return this.#drop("fragment-timing-refused");
5569
+ }
5570
+ return {
5571
+ kind: "fragment",
5572
+ packet: info,
5573
+ data,
5574
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
5575
+ fragmentationIndicator: mpu.fragmentationIndicator,
5576
+ fragmentCounter: mpu.fragmentCounter
5577
+ };
5578
+ }
5579
+ if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
5580
+ const resolver = this.#timingResolver(streamKey, info.packetId, false);
5581
+ if (!resolver) return this.#drop("mfu-no-resolver");
5582
+ if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
5583
+ return this.#drop("mfu-empty-payload");
5584
+ if (mpu.fragmentationIndicator === 0 || mpu.fragmentationIndicator === 1) {
5585
+ if (!mfuDuHeader || mfuDuHeader.movieFragmentSequenceNumber === 0 || mfuDuHeader.sampleNumber === 0) {
5586
+ return this.#drop("mfu-du-header-missing");
5587
+ }
5588
+ const headTiming = resolver.sampleTiming(
5589
+ mpu.mpuSequenceNumber,
5590
+ mfuDuHeader.movieFragmentSequenceNumber,
5591
+ mfuDuHeader.sampleNumber
5592
+ );
5593
+ if (!headTiming) return this.#drop("mfu-sample-timing-missing");
5594
+ const offset = mfuDuHeader.offset;
5595
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
5596
+ return this.#drop("mfu-offset-out-of-range");
5597
+ const remaining = headTiming.size - offset;
5598
+ if (mpu.fragmentationIndicator === 0 && data.byteLength !== remaining)
5599
+ return this.#drop("mfu-size-mismatch");
5600
+ if (mpu.fragmentationIndicator === 1 && data.byteLength >= remaining)
5601
+ return this.#drop("mfu-size-mismatch");
5602
+ const readyOnRegister = this.#sampleCombinerFor(streamKey).registerAuthoredSize(
5603
+ options?.catalogTrackName,
5604
+ mpu.mpuSequenceNumber,
5605
+ mfuDuHeader.movieFragmentSequenceNumber,
5606
+ mfuDuHeader.sampleNumber,
5607
+ headTiming.size
5608
+ );
5609
+ if (readyOnRegister) {
5610
+ const deferred = this.#emitCombinedSample(
5611
+ readyOnRegister,
5612
+ info,
5613
+ resolver,
5614
+ options?.recovered === true
5615
+ );
5616
+ if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
5617
+ }
5618
+ }
5619
+ let assembled;
5620
+ this.#reassemblerFragmentsFed++;
5621
+ try {
5622
+ assembled = this.#reassembler.addFragment({
5623
+ fragmentationIndicator: mpu.fragmentationIndicator,
5624
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
5625
+ fragmentCounter: mpu.fragmentCounter,
5626
+ data,
5627
+ timestamp: info.timestamp,
5628
+ rapFlag: info.rapFlag,
5629
+ priority: mfuDuHeader?.priority,
5630
+ sampleNumber: mfuDuHeader?.sampleNumber,
5631
+ movieFragmentSequenceNumber: mfuDuHeader?.movieFragmentSequenceNumber,
5632
+ sampleOffset: mfuDuHeader?.offset,
5633
+ packetSequenceNumber: info.sequenceNumber,
5634
+ recovered: options?.recovered === true,
5635
+ source: options?.source,
5636
+ deliveryProvenance: options?.deliveryProvenance,
5637
+ catalogTrackName: options?.catalogTrackName,
5638
+ packetId: info.packetId
5639
+ });
5640
+ } catch (error) {
5641
+ if (!isMfuReassemblyError(error)) throw error;
5642
+ console.warn(
5643
+ `[MmtpContainerParser] rejected MFU fragment: code=${error.code} mpu=${mpu.mpuSequenceNumber} fi=${mpu.fragmentationIndicator} counter=${mpu.fragmentCounter}`
5644
+ );
5645
+ return {
5646
+ kind: "rejected",
5647
+ packet: info,
5648
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
5649
+ fragmentationIndicator: mpu.fragmentationIndicator,
5650
+ fragmentCounter: mpu.fragmentCounter,
5651
+ error: { code: error.code, message: error.message }
5652
+ };
5653
+ }
5654
+ if (!assembled) {
5655
+ return {
5656
+ kind: "pending",
5657
+ packet: info,
5658
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
5659
+ fragmentationIndicator: mpu.fragmentationIndicator,
5660
+ fragmentCounter: mpu.fragmentCounter
5661
+ };
5662
+ }
5663
+ this.#reassemblerDataUnitsReturned++;
5664
+ const movieFragmentSequenceNumber = assembled.movieFragmentSequenceNumber;
5665
+ const sampleNumber = assembled.sampleNumber;
5666
+ if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
5667
+ return this.#drop("assembled-identity-missing");
5668
+ if (!resolver.sampleTiming(
5669
+ assembled.mpuSequenceNumber,
5670
+ movieFragmentSequenceNumber,
5671
+ sampleNumber
5672
+ )) return this.#drop("assembled-timing-missing");
5673
+ if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
5674
+ return this.#drop("assembled-mpu-mismatch");
5675
+ let combined;
5676
+ try {
5677
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
5678
+ } catch (error) {
5679
+ if (!(error instanceof SampleCombineError)) throw error;
5680
+ console.warn(
5681
+ `[MmtpContainerParser] rejected subsample data unit: code=${error.code} mpu=${assembled.mpuSequenceNumber} sample=${sampleNumber} offset=${assembled.sampleOffset ?? 0}`
5682
+ );
5683
+ return {
5684
+ kind: "rejected",
5685
+ packet: info,
5686
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
5687
+ fragmentationIndicator: mpu.fragmentationIndicator,
5688
+ fragmentCounter: mpu.fragmentCounter,
5689
+ error: { code: error.code, message: error.message }
5690
+ };
5691
+ }
5692
+ if (!combined) {
5693
+ return {
5694
+ kind: "pending",
5695
+ packet: info,
5696
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
5697
+ fragmentationIndicator: mpu.fragmentationIndicator,
5698
+ fragmentCounter: mpu.fragmentCounter
5699
+ };
5700
+ }
5701
+ const outcome = this.#emitCombinedSample(
5702
+ combined,
5703
+ info,
5704
+ resolver,
5705
+ options?.recovered === true
5706
+ );
5707
+ if (outcome.record !== void 0) return outcome.record;
5708
+ return this.#drop(outcome.reason);
5709
+ }
5710
+ /**
5711
+ * Deliver one combined sample: resolve its authored timing, build frame
5712
+ * metadata, retire the timing entry, and route it. Shared by the ordinary
5713
+ * completion path and by the rarer completion that falls out of registering
5714
+ * an authored size for data units that arrived before it.
5715
+ *
5716
+ * Reports a refusal as a reason rather than counting it, because the two
5717
+ * call sites owe different accounting. On `#feed()`'s tail return the
5718
+ * refusal *is* that feed()'s outcome and must be attributed; on the
5719
+ * register-completion path it belongs to an earlier sample while this
5720
+ * packet's own fragment continues to its own outcome, so counting it there
5721
+ * would push `outcomes` past `fedObjects` — the very invariant the
5722
+ * attribution exists to keep readable. Leaving the choice at the call site
5723
+ * is what keeps both true.
5724
+ */
5725
+ #emitCombinedSample(combined, info, resolver, recovered) {
5726
+ const timing = resolver.sampleTiming(
5727
+ combined.mpuSequenceNumber,
5728
+ combined.movieFragmentSequenceNumber,
5729
+ combined.sampleNumber
5730
+ );
5731
+ if (!timing) return { reason: "combined-timing-missing" };
5732
+ if (combined.data.byteLength !== timing.size) return { reason: "combined-size-mismatch" };
5733
+ const meta = this.#buildFrameMeta(
5734
+ combined,
5735
+ info.packetId,
5736
+ info.sequenceNumber,
5737
+ timing,
5738
+ recovered
5739
+ );
5740
+ if (!meta) return { reason: "combined-meta-build-failed" };
5741
+ if (!resolver.consumeSample(
5742
+ combined.mpuSequenceNumber,
5743
+ combined.movieFragmentSequenceNumber,
5744
+ combined.sampleNumber,
5745
+ timing
5746
+ )) return { reason: "combined-timing-consume-refused" };
5747
+ this.#pendingTimingSamples--;
5748
+ this.routeFrame(combined.data, meta);
5749
+ return {
5750
+ record: {
5751
+ kind: "frame",
5752
+ packet: info,
5753
+ data: combined.data,
5754
+ meta,
5755
+ mpuSequenceNumber: combined.mpuSequenceNumber,
5756
+ fragmentCount: combined.fragmentCount,
5757
+ rapFlag: combined.rapFlag,
5758
+ ...combined.priority === void 0 ? {} : { priority: combined.priority }
5759
+ }
5760
+ };
5761
+ }
5411
5762
  onInit(cb) {
5412
- __privateSet(this, _initCb, cb);
5763
+ this.#initCb = cb;
5413
5764
  }
5414
5765
  onFrame(cb) {
5415
- __privateSet(this, _frameCb, cb);
5766
+ this.#frameCb = cb;
5416
5767
  }
5417
5768
  /** Register a per-packet FEC source-symbol callback. Fires for each MMTP
5418
5769
  * source MPU packet that carries a Source FEC Payload ID (ISO 23008-1 §C.5.2).
@@ -5428,57 +5779,57 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5428
5779
  * that uses MmtpContainerParser can wire FEC source delivery without
5429
5780
  * pulling in MulticastManager/MmtpRouter/FECManager. */
5430
5781
  onSourceSymbol(cb) {
5431
- __privateSet(this, _sourceSymbolCb, cb);
5782
+ this.#sourceSymbolCb = cb;
5432
5783
  }
5433
5784
  onTrackFrame(packetId, cb) {
5434
- __privateGet(this, _trackFrameCbs).set(packetId, cb);
5785
+ this.#trackFrameCbs.set(packetId, cb);
5435
5786
  }
5436
5787
  setTrack(packetId, info) {
5437
- __privateMethod(this, _MmtpContainerParser_instances, validateReassemblyPolicy_fn).call(this);
5438
- for (const [key, entry] of __privateGet(this, _sequencers)) {
5788
+ this.#validateReassemblyPolicy();
5789
+ for (const [key, entry] of this.#sequencers) {
5439
5790
  if (entry.packetId !== packetId) continue;
5440
5791
  entry.sequencer.flush();
5441
- __privateGet(this, _sequencers).delete(key);
5792
+ this.#sequencers.delete(key);
5442
5793
  }
5443
- for (const [key, state] of __privateGet(this, _timingStreams)) {
5444
- if (state.packetId === packetId) __privateMethod(this, _MmtpContainerParser_instances, dropTimingStream_fn).call(this, key);
5794
+ for (const [key, state] of this.#timingStreams) {
5795
+ if (state.packetId === packetId) this.#dropTimingStream(key);
5445
5796
  }
5446
- for (const key of [...__privateGet(this, _sampleCombiners).keys()]) {
5797
+ for (const key of [...this.#sampleCombiners.keys()]) {
5447
5798
  if (JSON.parse(key)[0] === packetId) {
5448
- __privateMethod(this, _MmtpContainerParser_instances, dropSampleCombiner_fn).call(this, key);
5799
+ this.#dropSampleCombiner(key);
5449
5800
  }
5450
5801
  }
5451
- for (const [key, gatedPacketId] of __privateGet(this, _reliableMoqStartupGate)) {
5452
- if (gatedPacketId === packetId) __privateGet(this, _reliableMoqStartupGate).delete(key);
5802
+ for (const [key, gatedPacketId] of this.#reliableMoqStartupGate) {
5803
+ if (gatedPacketId === packetId) this.#reliableMoqStartupGate.delete(key);
5453
5804
  }
5454
- __privateGet(this, _tracks).set(packetId, info);
5805
+ this.#tracks.set(packetId, info);
5455
5806
  }
5456
5807
  /** Drop one physical stream's ordering and MFU state for retained replay. */
5457
5808
  resetTrack(packetId, catalogTrackName) {
5458
5809
  if (!catalogTrackName) {
5459
5810
  throw new Error("[MmtpContainerParser] catalogTrackName is required for track reset");
5460
5811
  }
5461
- for (const [key, entry] of __privateGet(this, _sequencers)) {
5462
- if (key !== __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn).call(this, packetId, catalogTrackName)) continue;
5812
+ for (const [key, entry] of this.#sequencers) {
5813
+ if (key !== this.#streamKey(packetId, catalogTrackName)) continue;
5463
5814
  entry.sequencer.discard();
5464
- __privateGet(this, _sequencers).delete(key);
5815
+ this.#sequencers.delete(key);
5465
5816
  }
5466
- const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn).call(this, packetId, catalogTrackName);
5467
- __privateMethod(this, _MmtpContainerParser_instances, dropTimingStream_fn).call(this, streamKey);
5468
- __privateGet(this, _reliableMoqStartupGate).delete(streamKey);
5469
- __privateGet(this, _reassembler).resetStream(catalogTrackName);
5470
- __privateMethod(this, _MmtpContainerParser_instances, dropSampleCombiner_fn).call(this, streamKey);
5817
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
5818
+ this.#dropTimingStream(streamKey);
5819
+ this.#reliableMoqStartupGate.delete(streamKey);
5820
+ this.#reassembler.resetStream(catalogTrackName);
5821
+ this.#dropSampleCombiner(streamKey);
5471
5822
  }
5472
5823
  setMfuTimeoutMs(ms) {
5473
5824
  if (ms !== null && ms <= 0) throw new Error("[MmtpContainerParser] mfuTimeoutMs must be > 0");
5474
- __privateGet(this, _reassembler).timeoutMs = ms;
5825
+ this.#reassembler.timeoutMs = ms;
5475
5826
  }
5476
5827
  setReassemblyPolicy(policy) {
5477
5828
  const timeoutMs = mfuReassemblyTimeoutMs(policy);
5478
- __privateMethod(this, _MmtpContainerParser_instances, validateReassemblyPolicy_fn).call(this, policy);
5479
- __privateMethod(this, _MmtpContainerParser_instances, flushSequencers_fn).call(this);
5480
- __privateSet(this, _reassemblyPolicy, policy);
5481
- __privateGet(this, _reliableMoqStartupGate).clear();
5829
+ this.#validateReassemblyPolicy(policy);
5830
+ this.#flushSequencers();
5831
+ this.#reassemblyPolicy = policy;
5832
+ this.#reliableMoqStartupGate.clear();
5482
5833
  this.setMfuTimeoutMs(timeoutMs);
5483
5834
  }
5484
5835
  setReorderWindow(windowSize) {
@@ -5486,25 +5837,25 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5486
5837
  throw new Error("[MmtpContainerParser] reorderWindow must be a finite number >= 0");
5487
5838
  }
5488
5839
  const nextWindow = Math.ceil(windowSize);
5489
- __privateMethod(this, _MmtpContainerParser_instances, validateReassemblyPolicy_fn).call(this, __privateGet(this, _reassemblyPolicy), nextWindow);
5490
- __privateMethod(this, _MmtpContainerParser_instances, flushSequencers_fn).call(this);
5491
- __privateSet(this, _reorderWindow, nextWindow);
5492
- if (__privateGet(this, _reorderWindow) <= 0) __privateGet(this, _sequencers).clear();
5840
+ this.#validateReassemblyPolicy(this.#reassemblyPolicy, nextWindow);
5841
+ this.#flushSequencers();
5842
+ this.#reorderWindow = nextWindow;
5843
+ if (this.#reorderWindow <= 0) this.#sequencers.clear();
5493
5844
  }
5494
5845
  /** Route an already-assembled frame through the same reorder/callback path
5495
5846
  * used by source packets. FEC recovery uses this to merge recovered frames
5496
5847
  * with direct source frames before the decoder sees them. */
5497
5848
  routeFrame(data, meta) {
5498
5849
  const seq = meta.packetSequenceNumber;
5499
- const sequencer = __privateMethod(this, _MmtpContainerParser_instances, sequencerFor_fn).call(this, meta.packetId, meta.trackType, meta.catalogTrackName);
5850
+ const sequencer = this.#sequencerFor(meta.packetId, meta.trackType, meta.catalogTrackName);
5500
5851
  if (sequencer && seq !== void 0 && Number.isFinite(seq)) {
5501
5852
  sequencer.push(data, meta, seq);
5502
5853
  return;
5503
5854
  }
5504
- if (__privateGet(this, _reassemblyPolicy)?.transport === "reliable-moq" && meta.trackType === "video" && !__privateMethod(this, _MmtpContainerParser_instances, passReliableMoqStartupGate_fn).call(this, meta)) {
5855
+ if (this.#reassemblyPolicy?.transport === "reliable-moq" && meta.trackType === "video" && !this.#passReliableMoqStartupGate(meta)) {
5505
5856
  return;
5506
5857
  }
5507
- __privateMethod(this, _MmtpContainerParser_instances, emitFrame_fn2).call(this, data, meta);
5858
+ this.#emitFrame(data, meta);
5508
5859
  }
5509
5860
  /**
5510
5861
  * Claim and return the authored timing for a recovered sample. Recovery does
@@ -5515,7 +5866,11 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5515
5866
  */
5516
5867
  consumeAuthoredTimingFor(packetId, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
5517
5868
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0) return null;
5518
- const resolver = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn).call(this, packetId, catalogTrackName), packetId, false);
5869
+ const resolver = this.#timingResolver(
5870
+ this.#streamKey(packetId, catalogTrackName),
5871
+ packetId,
5872
+ false
5873
+ );
5519
5874
  const timing = resolver?.sampleTiming(
5520
5875
  mpuSequenceNumber,
5521
5876
  movieFragmentSequenceNumber,
@@ -5527,8 +5882,8 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5527
5882
  sampleNumber,
5528
5883
  timing
5529
5884
  )) return null;
5530
- __privateWrapper(this, _pendingTimingSamples)._--;
5531
- if (__privateGet(this, _pendingTimingSamples) < 0) {
5885
+ this.#pendingTimingSamples--;
5886
+ if (this.#pendingTimingSamples < 0) {
5532
5887
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
5533
5888
  }
5534
5889
  return {
@@ -5538,551 +5893,205 @@ var _MmtpContainerParser = class _MmtpContainerParser {
5538
5893
  mediaTimescale: timing.timescale
5539
5894
  };
5540
5895
  }
5896
+ /** Order-independent reliable-moq startup gate: discard delta frames for a
5897
+ * stream until its first RAP is observed, without buffering/reordering. */
5898
+ #passReliableMoqStartupGate(meta) {
5899
+ const streamKey = this.#streamKey(meta.packetId, meta.catalogTrackName);
5900
+ if (meta.sourceDiscontinuity) this.#reliableMoqStartupGate.delete(streamKey);
5901
+ if (this.#reliableMoqStartupGate.has(streamKey)) return true;
5902
+ if (!meta.keyframe) {
5903
+ this.#reorderStats.droppedBeforeStartupKeyframe++;
5904
+ return false;
5905
+ }
5906
+ this.#reliableMoqStartupGate.set(streamKey, meta.packetId);
5907
+ return true;
5908
+ }
5541
5909
  /** Emit all ordered frames currently buffered by the parser. Finite-stream
5542
5910
  * consumers may call this before dispose(); live cancellation should not. */
5543
5911
  flush() {
5544
- if (__privateGet(this, _disposed)) return;
5545
- __privateMethod(this, _MmtpContainerParser_instances, flushSequencers_fn).call(this);
5912
+ if (this.#disposed) return;
5913
+ this.#flushSequencers();
5546
5914
  }
5547
5915
  dispose() {
5548
- __privateSet(this, _disposed, true);
5549
- for (const { sequencer } of __privateGet(this, _sequencers).values()) sequencer.discard();
5550
- __privateGet(this, _sequencers).clear();
5551
- __privateGet(this, _timingStreams).clear();
5552
- __privateSet(this, _pendingTimingSamples, 0);
5553
- __privateGet(this, _reliableMoqStartupGate).clear();
5554
- __privateGet(this, _reassembler).reset();
5555
- __privateSet(this, _frameCb, null);
5556
- __privateSet(this, _initCb, null);
5557
- __privateGet(this, _trackFrameCbs).clear();
5558
- }
5559
- // ── Static utilities ──────────────────────────────────────────
5560
- static isKeyframe(data, rapFlag, codec = "") {
5561
- var _a;
5562
- const payloadKeyframe = __privateMethod(_a = _MmtpContainerParser, _MmtpContainerParser_static, scanForKeyframe_fn).call(_a, data, codec);
5563
- if (payloadKeyframe !== void 0) return payloadKeyframe;
5564
- return rapFlag;
5565
- }
5566
- };
5567
- _tracks = new WeakMap();
5568
- _defaultTrack = new WeakMap();
5569
- _reassembler = new WeakMap();
5570
- _sampleCombiners = new WeakMap();
5571
- _sampleCombinerOptions = new WeakMap();
5572
- _retiredSampleCombinerStats = new WeakMap();
5573
- _timingStreams = new WeakMap();
5574
- _maxPendingTimingSamples = new WeakMap();
5575
- _pendingTimingSamples = new WeakMap();
5576
- _reclaimedTimingSamples = new WeakMap();
5577
- _evictedTimingSamples = new WeakMap();
5578
- _rejectedMovieFragments = new WeakMap();
5579
- _sequencers = new WeakMap();
5580
- _reorderWindow = new WeakMap();
5581
- _reassemblyPolicy = new WeakMap();
5582
- _frameCb = new WeakMap();
5583
- _initCb = new WeakMap();
5584
- _sourceSymbolCb = new WeakMap();
5585
- _trackFrameCbs = new WeakMap();
5586
- _reorderStats = new WeakMap();
5587
- _reliableMoqStartupGate = new WeakMap();
5588
- _disposed = new WeakMap();
5589
- _fedObjects = new WeakMap();
5590
- _feedOutcomes = new WeakMap();
5591
- _deferredFeedOutcomes = new WeakMap();
5592
- _lastOutcome = new WeakMap();
5593
- _lastOutcomeCount = new WeakMap();
5594
- _MmtpContainerParser_instances = new WeakSet();
5595
- streamKey_fn = function(packetId, catalogTrackName) {
5596
- return JSON.stringify([packetId, catalogTrackName ?? null]);
5597
- };
5598
- sampleCombinerFor_fn = function(streamKey) {
5599
- let combiner = __privateGet(this, _sampleCombiners).get(streamKey);
5600
- if (combiner === void 0) {
5601
- combiner = new SampleCombiner({
5602
- ...__privateGet(this, _sampleCombinerOptions),
5603
- onAbandon: (sample) => __privateMethod(this, _MmtpContainerParser_instances, releaseTimingSlot_fn).call(this, streamKey, sample)
5604
- });
5605
- __privateGet(this, _sampleCombiners).set(streamKey, combiner);
5606
- }
5607
- return combiner;
5608
- };
5609
- /**
5610
- * Return the timing budget slot of a sample the combiner abandoned.
5611
- *
5612
- * Without this, `#pendingTimingSamples` is charged for every sample a moof
5613
- * declares but credited only when that sample is delivered, so each sample
5614
- * lost to eviction or timeout burns a slot until the window displaces it.
5615
- * Window displacement bounds that leak but only reclaims the OLDEST entries;
5616
- * this path returns a slot the moment the combiner knows the sample is gone,
5617
- * which keeps the live window as wide as the stream actually needs.
5618
- *
5619
- * The parser total is decremented only when the resolver reports it
5620
- * actually freed a slot, so a resolver already dropped by a track reset, or
5621
- * a sample released twice, cannot drive the accounting negative.
5622
- */
5623
- releaseTimingSlot_fn = function(streamKey, sample) {
5624
- const resolver = __privateGet(this, _timingStreams).get(streamKey)?.resolver;
5625
- if (!resolver) return;
5626
- if (!resolver.releaseSample(
5627
- sample.mpuSequenceNumber,
5628
- sample.movieFragmentSequenceNumber,
5629
- sample.sampleNumber
5630
- )) return;
5631
- __privateWrapper(this, _pendingTimingSamples)._--;
5632
- __privateWrapper(this, _reclaimedTimingSamples)._++;
5633
- if (__privateGet(this, _pendingTimingSamples) < 0) {
5634
- throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
5635
- }
5636
- };
5637
- /** Drop one stream's combiner, folding its counters into the retained
5638
- * totals so a reset cannot make the exposed stats run backwards. */
5639
- dropSampleCombiner_fn = function(streamKey) {
5640
- const combiner = __privateGet(this, _sampleCombiners).get(streamKey);
5641
- if (combiner === void 0) return;
5642
- const stats = combiner.stats;
5643
- __privateGet(this, _retiredSampleCombinerStats).combinedSamples += stats.combinedSamples;
5644
- __privateGet(this, _retiredSampleCombinerStats).passthroughSamples += stats.passthroughSamples;
5645
- __privateGet(this, _retiredSampleCombinerStats).timedOutSamples += stats.timedOutSamples;
5646
- __privateGet(this, _retiredSampleCombinerStats).evictedSamples += stats.evictedSamples;
5647
- __privateGet(this, _sampleCombiners).delete(streamKey);
5648
- };
5649
- countOutcome_fn = function(token) {
5650
- const count = (__privateGet(this, _feedOutcomes).get(token) ?? 0) + 1;
5651
- __privateGet(this, _feedOutcomes).set(token, count);
5652
- __privateSet(this, _lastOutcome, token);
5653
- __privateSet(this, _lastOutcomeCount, count);
5654
- };
5655
- countDeferredOutcome_fn = function(reason) {
5656
- __privateGet(this, _deferredFeedOutcomes).set(
5657
- reason,
5658
- (__privateGet(this, _deferredFeedOutcomes).get(reason) ?? 0) + 1
5659
- );
5660
- };
5661
- /**
5662
- * Count a feed() drop and return null in one expression, so every early
5663
- * return inside feed() states the reason it took instead of collapsing into
5664
- * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
5665
- */
5666
- drop_fn = function(reason) {
5667
- __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, `drop:${reason}`);
5668
- return null;
5669
- };
5670
- feed_fn = function(packet, options) {
5671
- var _a;
5672
- if (__privateGet(this, _disposed)) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "disposed");
5673
- this.cleanupTimeouts();
5674
- const info = this.parseHeader(packet, options);
5675
- if (!info) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "header-parse-failed");
5676
- if (info.packetType !== PACKET_TYPE_MPU2) {
5677
- return {
5678
- kind: info.isRepair ? "repair" : "non-media",
5679
- packet: info,
5680
- byteLength: packet.byteLength
5681
- };
5682
- }
5683
- if (info.fecPayloadId !== null && __privateGet(this, _sourceSymbolCb)) {
5684
- const rawSymbol = packet.subarray(0, packet.length - 4);
5685
- const altaTrailer = extractAltaTrailer2(packet);
5686
- const alta = altaTrailer ? { auth: altaTrailer.auth, payloadEnd: altaTrailer.signedEnd } : void 0;
5687
- try {
5688
- __privateGet(this, _sourceSymbolCb).call(this, info.packetId, info.fecPayloadId.ssId, rawSymbol, alta);
5689
- } catch {
5916
+ this.#disposed = true;
5917
+ for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
5918
+ this.#sequencers.clear();
5919
+ this.#timingStreams.clear();
5920
+ this.#pendingTimingSamples = 0;
5921
+ this.#reliableMoqStartupGate.clear();
5922
+ this.#reassembler.reset();
5923
+ this.#frameCb = null;
5924
+ this.#initCb = null;
5925
+ this.#trackFrameCbs.clear();
5926
+ }
5927
+ // ── Private ─────────────────────────────────────────────────────
5928
+ #timingResolver(streamKey, packetId, create) {
5929
+ const existing = this.#timingStreams.get(streamKey);
5930
+ if (existing) return existing.resolver;
5931
+ if (!create) return null;
5932
+ const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
5933
+ this.#timingStreams.set(streamKey, { packetId, resolver });
5934
+ return resolver;
5935
+ }
5936
+ #dropTimingStream(streamKey) {
5937
+ const state = this.#timingStreams.get(streamKey);
5938
+ if (!state) return;
5939
+ this.#timingStreams.delete(streamKey);
5940
+ this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
5941
+ if (this.#pendingTimingSamples < 0) {
5942
+ throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
5690
5943
  }
5691
5944
  }
5692
- const extraction = extractMFUPayload(packet, {
5693
- skipFecId: options?.skipFecPayloadId
5694
- });
5695
- if (!extraction) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-extract-failed");
5696
- const { mpu, fragmentType, data, mfuDuHeader } = extraction;
5697
- if (mpu.timedFlag !== 1) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "untimed-mpu");
5698
- const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn).call(this, info.packetId, options?.catalogTrackName);
5699
- if (fragmentType === 0) {
5700
- if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
5701
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "init-unexpected-fragmentation");
5702
- const normalizedInit = normalizeMmtpInitSegment(data);
5703
- if (!normalizedInit) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "init-normalize-failed");
5704
- const resolver2 = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, true);
5705
- if (!resolver2?.addInitialization(normalizedInit)) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "init-timing-refused");
5706
- (_a = __privateGet(this, _initCb)) == null ? void 0 : _a.call(this, normalizedInit, info.packetId, options?.catalogTrackName);
5707
- return {
5708
- kind: "init",
5709
- packet: info,
5710
- data: normalizedInit,
5711
- mpuSequenceNumber: mpu.mpuSequenceNumber,
5712
- fragmentationIndicator: mpu.fragmentationIndicator,
5713
- fragmentCounter: mpu.fragmentCounter
5714
- };
5945
+ #validateReassemblyPolicy(policy = this.#reassemblyPolicy, reorderWindow = this.#reorderWindow) {
5946
+ if (!policy) return;
5947
+ mmtpFrameReorderWindowFrames(policy, reorderWindow);
5715
5948
  }
5716
- if (fragmentType === 1) {
5717
- if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
5718
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-unexpected-fragmentation");
5719
- const resolver2 = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, false);
5720
- if (!resolver2) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-no-resolver");
5721
- const pendingBefore = resolver2.pendingSampleCount;
5722
- const evictedBefore = resolver2.evictedSampleCount;
5723
- const remaining = __privateGet(this, _maxPendingTimingSamples) - __privateGet(this, _pendingTimingSamples);
5724
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
5725
- __privateSet(this, _pendingTimingSamples, __privateGet(this, _pendingTimingSamples) + (resolver2.pendingSampleCount - pendingBefore));
5726
- __privateSet(this, _evictedTimingSamples, __privateGet(this, _evictedTimingSamples) + (resolver2.evictedSampleCount - evictedBefore));
5727
- if (!admitted) {
5728
- if (resolver2.lastMovieFragmentRejection === "budget") {
5729
- __privateWrapper(this, _rejectedMovieFragments)._++;
5730
- }
5731
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-timing-refused");
5732
- }
5733
- return {
5734
- kind: "fragment",
5735
- packet: info,
5736
- data,
5737
- mpuSequenceNumber: mpu.mpuSequenceNumber,
5738
- fragmentationIndicator: mpu.fragmentationIndicator,
5739
- fragmentCounter: mpu.fragmentCounter
5740
- };
5741
- }
5742
- if (fragmentType !== 2) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "unknown-fragment-type");
5743
- const resolver = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, false);
5744
- if (!resolver) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-no-resolver");
5745
- if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
5746
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-empty-payload");
5747
- if (mpu.fragmentationIndicator === 0 || mpu.fragmentationIndicator === 1) {
5748
- if (!mfuDuHeader || mfuDuHeader.movieFragmentSequenceNumber === 0 || mfuDuHeader.sampleNumber === 0) {
5749
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-du-header-missing");
5750
- }
5751
- const headTiming = resolver.sampleTiming(
5752
- mpu.mpuSequenceNumber,
5753
- mfuDuHeader.movieFragmentSequenceNumber,
5754
- mfuDuHeader.sampleNumber
5949
+ #buildFrameMeta(assembled, packetId, seq, timing, recovered = false) {
5950
+ const { data, rapFlag, priority } = assembled;
5951
+ if (isFmp4Box(data)) return null;
5952
+ const presentationTimestamp = mediaTicksToMicroseconds(
5953
+ timing.presentationTime,
5954
+ timing.timescale
5755
5955
  );
5756
- if (!headTiming) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-sample-timing-missing");
5757
- const offset = mfuDuHeader.offset;
5758
- if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
5759
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-offset-out-of-range");
5760
- const remaining = headTiming.size - offset;
5761
- if (mpu.fragmentationIndicator === 0 && data.byteLength !== remaining)
5762
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-size-mismatch");
5763
- if (mpu.fragmentationIndicator === 1 && data.byteLength >= remaining)
5764
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-size-mismatch");
5765
- const readyOnRegister = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).registerAuthoredSize(
5766
- options?.catalogTrackName,
5767
- mpu.mpuSequenceNumber,
5768
- mfuDuHeader.movieFragmentSequenceNumber,
5769
- mfuDuHeader.sampleNumber,
5770
- headTiming.size
5771
- );
5772
- if (readyOnRegister) {
5773
- const deferred = __privateMethod(this, _MmtpContainerParser_instances, emitCombinedSample_fn).call(this, readyOnRegister, info, resolver, options?.recovered === true);
5774
- if (deferred.record === void 0) __privateMethod(this, _MmtpContainerParser_instances, countDeferredOutcome_fn).call(this, deferred.reason);
5956
+ const decodeTimestamp = mediaTicksToMicroseconds(timing.decodeTime, timing.timescale);
5957
+ const duration = mediaTicksToMicroseconds(BigInt(timing.duration), timing.timescale);
5958
+ if (presentationTimestamp === null || decodeTimestamp === null || duration === null || duration <= 0) {
5959
+ return null;
5775
5960
  }
5776
- }
5777
- let assembled;
5778
- try {
5779
- assembled = __privateGet(this, _reassembler).addFragment({
5780
- fragmentationIndicator: mpu.fragmentationIndicator,
5781
- mpuSequenceNumber: mpu.mpuSequenceNumber,
5782
- fragmentCounter: mpu.fragmentCounter,
5783
- data,
5784
- timestamp: info.timestamp,
5785
- rapFlag: info.rapFlag,
5786
- priority: mfuDuHeader?.priority,
5787
- sampleNumber: mfuDuHeader?.sampleNumber,
5788
- movieFragmentSequenceNumber: mfuDuHeader?.movieFragmentSequenceNumber,
5789
- sampleOffset: mfuDuHeader?.offset,
5790
- packetSequenceNumber: info.sequenceNumber,
5791
- recovered: options?.recovered === true,
5792
- source: options?.source,
5793
- deliveryProvenance: options?.deliveryProvenance,
5794
- catalogTrackName: options?.catalogTrackName,
5795
- packetId: info.packetId
5796
- });
5797
- } catch (error) {
5798
- if (!isMfuReassemblyError(error)) throw error;
5799
- console.warn(
5800
- `[MmtpContainerParser] rejected MFU fragment: code=${error.code} mpu=${mpu.mpuSequenceNumber} fi=${mpu.fragmentationIndicator} counter=${mpu.fragmentCounter}`
5801
- );
5802
- return {
5803
- kind: "rejected",
5804
- packet: info,
5805
- mpuSequenceNumber: mpu.mpuSequenceNumber,
5806
- fragmentationIndicator: mpu.fragmentationIndicator,
5807
- fragmentCounter: mpu.fragmentCounter,
5808
- error: { code: error.code, message: error.message }
5809
- };
5810
- }
5811
- if (!assembled) {
5812
- return {
5813
- kind: "pending",
5814
- packet: info,
5815
- mpuSequenceNumber: mpu.mpuSequenceNumber,
5816
- fragmentationIndicator: mpu.fragmentationIndicator,
5817
- fragmentCounter: mpu.fragmentCounter
5818
- };
5819
- }
5820
- const movieFragmentSequenceNumber = assembled.movieFragmentSequenceNumber;
5821
- const sampleNumber = assembled.sampleNumber;
5822
- if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
5823
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-identity-missing");
5824
- if (!resolver.sampleTiming(
5825
- assembled.mpuSequenceNumber,
5826
- movieFragmentSequenceNumber,
5827
- sampleNumber
5828
- )) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-timing-missing");
5829
- if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
5830
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-mpu-mismatch");
5831
- let combined;
5832
- try {
5833
- combined = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).addMfu(assembled);
5834
- } catch (error) {
5835
- if (!(error instanceof SampleCombineError)) throw error;
5836
- console.warn(
5837
- `[MmtpContainerParser] rejected subsample data unit: code=${error.code} mpu=${assembled.mpuSequenceNumber} sample=${sampleNumber} offset=${assembled.sampleOffset ?? 0}`
5838
- );
5839
- return {
5840
- kind: "rejected",
5841
- packet: info,
5842
- mpuSequenceNumber: mpu.mpuSequenceNumber,
5843
- fragmentationIndicator: mpu.fragmentationIndicator,
5844
- fragmentCounter: mpu.fragmentCounter,
5845
- error: { code: error.code, message: error.message }
5846
- };
5847
- }
5848
- if (!combined) {
5849
- return {
5850
- kind: "pending",
5851
- packet: info,
5852
- mpuSequenceNumber: mpu.mpuSequenceNumber,
5853
- fragmentationIndicator: mpu.fragmentationIndicator,
5854
- fragmentCounter: mpu.fragmentCounter
5855
- };
5856
- }
5857
- const outcome = __privateMethod(this, _MmtpContainerParser_instances, emitCombinedSample_fn).call(this, combined, info, resolver, options?.recovered === true);
5858
- if (outcome.record !== void 0) return outcome.record;
5859
- return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, outcome.reason);
5860
- };
5861
- /**
5862
- * Deliver one combined sample: resolve its authored timing, build frame
5863
- * metadata, retire the timing entry, and route it. Shared by the ordinary
5864
- * completion path and by the rarer completion that falls out of registering
5865
- * an authored size for data units that arrived before it.
5866
- *
5867
- * Reports a refusal as a reason rather than counting it, because the two
5868
- * call sites owe different accounting. On `#feed()`'s tail return the
5869
- * refusal *is* that feed()'s outcome and must be attributed; on the
5870
- * register-completion path it belongs to an earlier sample while this
5871
- * packet's own fragment continues to its own outcome, so counting it there
5872
- * would push `outcomes` past `fedObjects` — the very invariant the
5873
- * attribution exists to keep readable. Leaving the choice at the call site
5874
- * is what keeps both true.
5875
- */
5876
- emitCombinedSample_fn = function(combined, info, resolver, recovered) {
5877
- const timing = resolver.sampleTiming(
5878
- combined.mpuSequenceNumber,
5879
- combined.movieFragmentSequenceNumber,
5880
- combined.sampleNumber
5881
- );
5882
- if (!timing) return { reason: "combined-timing-missing" };
5883
- if (combined.data.byteLength !== timing.size) return { reason: "combined-size-mismatch" };
5884
- const meta = __privateMethod(this, _MmtpContainerParser_instances, buildFrameMeta_fn).call(this, combined, info.packetId, info.sequenceNumber, timing, recovered);
5885
- if (!meta) return { reason: "combined-meta-build-failed" };
5886
- if (!resolver.consumeSample(
5887
- combined.mpuSequenceNumber,
5888
- combined.movieFragmentSequenceNumber,
5889
- combined.sampleNumber,
5890
- timing
5891
- )) return { reason: "combined-timing-consume-refused" };
5892
- __privateWrapper(this, _pendingTimingSamples)._--;
5893
- this.routeFrame(combined.data, meta);
5894
- return {
5895
- record: {
5896
- kind: "frame",
5897
- packet: info,
5898
- data: combined.data,
5899
- meta,
5900
- mpuSequenceNumber: combined.mpuSequenceNumber,
5901
- fragmentCount: combined.fragmentCount,
5902
- rapFlag: combined.rapFlag,
5903
- ...combined.priority === void 0 ? {} : { priority: combined.priority }
5961
+ let track = this.#tracks.get(packetId);
5962
+ if (!track && this.#defaultTrack) {
5963
+ track = this.#defaultTrack;
5964
+ this.#tracks.set(packetId, track);
5904
5965
  }
5905
- };
5906
- };
5907
- /** Order-independent reliable-moq startup gate: discard delta frames for a
5908
- * stream until its first RAP is observed, without buffering/reordering. */
5909
- passReliableMoqStartupGate_fn = function(meta) {
5910
- const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn).call(this, meta.packetId, meta.catalogTrackName);
5911
- if (meta.sourceDiscontinuity) __privateGet(this, _reliableMoqStartupGate).delete(streamKey);
5912
- if (__privateGet(this, _reliableMoqStartupGate).has(streamKey)) return true;
5913
- if (!meta.keyframe) {
5914
- __privateGet(this, _reorderStats).droppedBeforeStartupKeyframe++;
5915
- return false;
5916
- }
5917
- __privateGet(this, _reliableMoqStartupGate).set(streamKey, meta.packetId);
5918
- return true;
5919
- };
5920
- // ── Private ─────────────────────────────────────────────────────
5921
- timingResolver_fn = function(streamKey, packetId, create) {
5922
- const existing = __privateGet(this, _timingStreams).get(streamKey);
5923
- if (existing) return existing.resolver;
5924
- if (!create) return null;
5925
- const resolver = new IsoBmffTimingResolver(__privateGet(this, _maxPendingTimingSamples));
5926
- __privateGet(this, _timingStreams).set(streamKey, { packetId, resolver });
5927
- return resolver;
5928
- };
5929
- dropTimingStream_fn = function(streamKey) {
5930
- const state = __privateGet(this, _timingStreams).get(streamKey);
5931
- if (!state) return;
5932
- __privateGet(this, _timingStreams).delete(streamKey);
5933
- __privateSet(this, _pendingTimingSamples, __privateGet(this, _pendingTimingSamples) - state.resolver.pendingSampleCount);
5934
- if (__privateGet(this, _pendingTimingSamples) < 0) {
5935
- throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
5936
- }
5937
- };
5938
- validateReassemblyPolicy_fn = function(policy = __privateGet(this, _reassemblyPolicy), reorderWindow = __privateGet(this, _reorderWindow)) {
5939
- if (!policy) return;
5940
- mmtpFrameReorderWindowFrames(policy, reorderWindow);
5941
- };
5942
- buildFrameMeta_fn = function(assembled, packetId, seq, timing, recovered = false) {
5943
- const { data, rapFlag, priority } = assembled;
5944
- if (isFmp4Box(data)) return null;
5945
- const presentationTimestamp = mediaTicksToMicroseconds(
5946
- timing.presentationTime,
5947
- timing.timescale
5948
- );
5949
- const decodeTimestamp = mediaTicksToMicroseconds(timing.decodeTime, timing.timescale);
5950
- const duration = mediaTicksToMicroseconds(BigInt(timing.duration), timing.timescale);
5951
- if (presentationTimestamp === null || decodeTimestamp === null || duration === null || duration <= 0) {
5952
- return null;
5953
- }
5954
- let track = __privateGet(this, _tracks).get(packetId);
5955
- if (!track && __privateGet(this, _defaultTrack)) {
5956
- track = __privateGet(this, _defaultTrack);
5957
- __privateGet(this, _tracks).set(packetId, track);
5958
- }
5959
- const codec = track?.codec ?? "";
5960
- const keyframe = _MmtpContainerParser.isKeyframe(data, isMfuKeyframeMetadata(rapFlag, priority), codec);
5961
- const meta = {
5962
- timestamp: presentationTimestamp,
5963
- decodeTimestamp,
5964
- duration,
5965
- decodeTime: timing.decodeTime,
5966
- presentationTime: timing.presentationTime,
5967
- durationTicks: timing.duration,
5968
- mediaTimescale: timing.timescale,
5969
- authoredTiming: {
5966
+ const codec = track?.codec ?? "";
5967
+ const keyframe = _MmtpContainerParser.isKeyframe(data, isMfuKeyframeMetadata(rapFlag, priority), codec);
5968
+ const meta = {
5969
+ timestamp: presentationTimestamp,
5970
+ decodeTimestamp,
5971
+ duration,
5970
5972
  decodeTime: timing.decodeTime,
5971
5973
  presentationTime: timing.presentationTime,
5972
5974
  durationTicks: timing.duration,
5973
- mediaTimescale: timing.timescale
5974
- },
5975
- keyframe,
5976
- packetId,
5977
- trackType: track?.type ?? null,
5978
- packetSequenceNumber: seq,
5979
- ...assembled.packetSequenceNumbers === void 0 ? {} : { packetSequenceNumbers: assembled.packetSequenceNumbers },
5980
- ...assembled.repairedPacketSequenceNumbers === void 0 ? {} : { repairedPacketSequenceNumbers: assembled.repairedPacketSequenceNumbers },
5981
- ...assembled.catalogTrackName === void 0 ? {} : { catalogTrackName: assembled.catalogTrackName },
5982
- ...assembled.mmtpTimestamp === void 0 ? {} : { mmtpTimestamp: assembled.mmtpTimestamp },
5983
- mpuSequenceNumber: assembled.mpuSequenceNumber,
5984
- ...assembled.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber },
5985
- ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
5986
- fragmentCount: assembled.fragmentCount,
5987
- rapFlag,
5988
- ...priority === void 0 ? {} : { priority },
5989
- ...assembled.source === void 0 ? {} : { source: assembled.source },
5990
- deliveryProvenance: assembled.deliveryProvenance
5991
- };
5992
- if (recovered || (assembled.repairedPacketSequenceNumbers?.length ?? 0) > 0) {
5993
- meta.recovered = true;
5975
+ mediaTimescale: timing.timescale,
5976
+ authoredTiming: {
5977
+ decodeTime: timing.decodeTime,
5978
+ presentationTime: timing.presentationTime,
5979
+ durationTicks: timing.duration,
5980
+ mediaTimescale: timing.timescale
5981
+ },
5982
+ keyframe,
5983
+ packetId,
5984
+ trackType: track?.type ?? null,
5985
+ packetSequenceNumber: seq,
5986
+ ...assembled.packetSequenceNumbers === void 0 ? {} : { packetSequenceNumbers: assembled.packetSequenceNumbers },
5987
+ ...assembled.repairedPacketSequenceNumbers === void 0 ? {} : { repairedPacketSequenceNumbers: assembled.repairedPacketSequenceNumbers },
5988
+ ...assembled.catalogTrackName === void 0 ? {} : { catalogTrackName: assembled.catalogTrackName },
5989
+ ...assembled.mmtpTimestamp === void 0 ? {} : { mmtpTimestamp: assembled.mmtpTimestamp },
5990
+ mpuSequenceNumber: assembled.mpuSequenceNumber,
5991
+ ...assembled.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber },
5992
+ ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
5993
+ fragmentCount: assembled.fragmentCount,
5994
+ rapFlag,
5995
+ ...priority === void 0 ? {} : { priority },
5996
+ ...assembled.source === void 0 ? {} : { source: assembled.source },
5997
+ deliveryProvenance: assembled.deliveryProvenance
5998
+ };
5999
+ if (recovered || (assembled.repairedPacketSequenceNumbers?.length ?? 0) > 0) {
6000
+ meta.recovered = true;
6001
+ }
6002
+ return meta;
6003
+ }
6004
+ #sequencerFor(packetId, _trackType, catalogTrackName) {
6005
+ const windowSize = this.#reassemblyPolicy ? mmtpFrameReorderWindowFrames(this.#reassemblyPolicy, this.#reorderWindow) : this.#reorderWindow;
6006
+ if (windowSize <= 0) return null;
6007
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
6008
+ let sequencer = this.#sequencers.get(streamKey)?.sequencer;
6009
+ if (!sequencer) {
6010
+ sequencer = new FrameSequencer(windowSize, (data, meta) => {
6011
+ this.#emitFrame(data, meta);
6012
+ }, (stat, count = 1) => {
6013
+ this.#reorderStats[stat] += count;
6014
+ });
6015
+ this.#sequencers.set(streamKey, { packetId, sequencer });
6016
+ }
6017
+ return sequencer;
5994
6018
  }
5995
- return meta;
5996
- };
5997
- sequencerFor_fn = function(packetId, _trackType2, catalogTrackName) {
5998
- const windowSize = __privateGet(this, _reassemblyPolicy) ? mmtpFrameReorderWindowFrames(__privateGet(this, _reassemblyPolicy), __privateGet(this, _reorderWindow)) : __privateGet(this, _reorderWindow);
5999
- if (windowSize <= 0) return null;
6000
- const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn).call(this, packetId, catalogTrackName);
6001
- let sequencer = __privateGet(this, _sequencers).get(streamKey)?.sequencer;
6002
- if (!sequencer) {
6003
- sequencer = new FrameSequencer(windowSize, (data, meta) => {
6004
- __privateMethod(this, _MmtpContainerParser_instances, emitFrame_fn2).call(this, data, meta);
6005
- }, (stat, count = 1) => {
6006
- __privateGet(this, _reorderStats)[stat] += count;
6007
- });
6008
- __privateGet(this, _sequencers).set(streamKey, { packetId, sequencer });
6019
+ #flushSequencers() {
6020
+ for (const { sequencer } of this.#sequencers.values()) sequencer.flush();
6021
+ this.#sequencers.clear();
6009
6022
  }
6010
- return sequencer;
6011
- };
6012
- flushSequencers_fn = function() {
6013
- for (const { sequencer } of __privateGet(this, _sequencers).values()) sequencer.flush();
6014
- __privateGet(this, _sequencers).clear();
6015
- };
6016
- emitFrame_fn2 = function(data, meta) {
6017
- var _a;
6018
- this.lastFrameTimestamp = meta.timestamp;
6019
- const trackCb = __privateGet(this, _trackFrameCbs).get(meta.packetId);
6020
- trackCb?.(data, meta);
6021
- (_a = __privateGet(this, _frameCb)) == null ? void 0 : _a.call(this, data, meta);
6022
- };
6023
- _MmtpContainerParser_static = new WeakSet();
6024
- scanForKeyframe_fn = function(data, codec) {
6025
- var _a, _b;
6026
- const c = codec.toLowerCase();
6027
- if (data.length === 0) return void 0;
6028
- if (c.startsWith("av01")) {
6029
- return scanAv1ObusForKeyframe(data);
6023
+ #emitFrame(data, meta) {
6024
+ this.lastFrameTimestamp = meta.timestamp;
6025
+ const trackCb = this.#trackFrameCbs.get(meta.packetId);
6026
+ trackCb?.(data, meta);
6027
+ this.#frameCb?.(data, meta);
6030
6028
  }
6031
- if (c.startsWith("vp09") || c.startsWith("vp8")) {
6032
- return (data[0] & 4) === 0;
6029
+ // ── Static utilities ──────────────────────────────────────────
6030
+ static isKeyframe(data, rapFlag, codec = "") {
6031
+ const payloadKeyframe = _MmtpContainerParser.#scanForKeyframe(data, codec);
6032
+ if (payloadKeyframe !== void 0) return payloadKeyframe;
6033
+ return rapFlag;
6033
6034
  }
6034
- const isHevc = c.startsWith("hev1") || c.startsWith("hvc1");
6035
- if (isHevc) {
6036
- if (data.length < 5) return void 0;
6037
- if (startsWithAnnexB(data)) {
6038
- return __privateMethod(_a = _MmtpContainerParser, _MmtpContainerParser_static, scanAnnexBForKeyframe_fn).call(_a, data, true);
6035
+ static #scanForKeyframe(data, codec) {
6036
+ const c = codec.toLowerCase();
6037
+ if (data.length === 0) return void 0;
6038
+ if (c.startsWith("av01")) {
6039
+ return scanAv1ObusForKeyframe(data);
6039
6040
  }
6040
- return __privateMethod(_b = _MmtpContainerParser, _MmtpContainerParser_static, scanLengthPrefixedHevcForKeyframe_fn).call(_b, data);
6041
- }
6042
- if (c === "" || c.startsWith("avc")) {
6043
- return classifyH264Keyframe(data, { allowPartialAvcc: true });
6044
- }
6045
- return void 0;
6046
- };
6047
- scanLengthPrefixedHevcForKeyframe_fn = function(data) {
6048
- let sawNal = false;
6049
- let offset = 0;
6050
- while (offset + 4 < data.length) {
6051
- const nalLen = data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
6052
- offset += 4;
6053
- if (nalLen <= 0) return sawNal ? false : void 0;
6054
- if (offset >= data.length) return sawNal ? false : void 0;
6055
- sawNal = true;
6056
- const hevcType = data[offset] >> 1 & 63;
6057
- if (hevcType >= 16 && hevcType <= 21) return true;
6058
- if (offset + nalLen > data.length) break;
6059
- offset += nalLen;
6060
- }
6061
- return sawNal ? false : void 0;
6062
- };
6063
- scanAnnexBForKeyframe_fn = function(data, isHevc) {
6064
- let offset = 0;
6065
- let sawNal = false;
6066
- while (offset < data.length) {
6067
- const start = findAnnexBStart(data, offset);
6068
- if (!start) return sawNal ? false : void 0;
6069
- const headerOffset = start.offset + start.length;
6070
- if (headerOffset >= data.length) return sawNal ? false : void 0;
6071
- sawNal = true;
6041
+ if (c.startsWith("vp09") || c.startsWith("vp8")) {
6042
+ return (data[0] & 4) === 0;
6043
+ }
6044
+ const isHevc = c.startsWith("hev1") || c.startsWith("hvc1");
6072
6045
  if (isHevc) {
6073
- if (headerOffset + 1 >= data.length) return sawNal ? false : void 0;
6074
- const hevcType = data[headerOffset] >> 1 & 63;
6046
+ if (data.length < 5) return void 0;
6047
+ if (startsWithAnnexB(data)) {
6048
+ return _MmtpContainerParser.#scanAnnexBForKeyframe(data, true);
6049
+ }
6050
+ return _MmtpContainerParser.#scanLengthPrefixedHevcForKeyframe(data);
6051
+ }
6052
+ if (c === "" || c.startsWith("avc")) {
6053
+ return classifyH264Keyframe(data, { allowPartialAvcc: true });
6054
+ }
6055
+ return void 0;
6056
+ }
6057
+ static #scanLengthPrefixedHevcForKeyframe(data) {
6058
+ let sawNal = false;
6059
+ let offset = 0;
6060
+ while (offset + 4 < data.length) {
6061
+ const nalLen = data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
6062
+ offset += 4;
6063
+ if (nalLen <= 0) return sawNal ? false : void 0;
6064
+ if (offset >= data.length) return sawNal ? false : void 0;
6065
+ sawNal = true;
6066
+ const hevcType = data[offset] >> 1 & 63;
6075
6067
  if (hevcType >= 16 && hevcType <= 21) return true;
6076
- } else {
6077
- const nalType = data[headerOffset] & 31;
6078
- if (nalType === 5) return true;
6068
+ if (offset + nalLen > data.length) break;
6069
+ offset += nalLen;
6070
+ }
6071
+ return sawNal ? false : void 0;
6072
+ }
6073
+ static #scanAnnexBForKeyframe(data, isHevc) {
6074
+ let offset = 0;
6075
+ let sawNal = false;
6076
+ while (offset < data.length) {
6077
+ const start = findAnnexBStart(data, offset);
6078
+ if (!start) return sawNal ? false : void 0;
6079
+ const headerOffset = start.offset + start.length;
6080
+ if (headerOffset >= data.length) return sawNal ? false : void 0;
6081
+ sawNal = true;
6082
+ if (isHevc) {
6083
+ if (headerOffset + 1 >= data.length) return sawNal ? false : void 0;
6084
+ const hevcType = data[headerOffset] >> 1 & 63;
6085
+ if (hevcType >= 16 && hevcType <= 21) return true;
6086
+ } else {
6087
+ const nalType = data[headerOffset] & 31;
6088
+ if (nalType === 5) return true;
6089
+ }
6090
+ offset = headerOffset + 1;
6079
6091
  }
6080
- offset = headerOffset + 1;
6092
+ return sawNal ? false : void 0;
6081
6093
  }
6082
- return sawNal ? false : void 0;
6083
6094
  };
6084
- __privateAdd(_MmtpContainerParser, _MmtpContainerParser_static);
6085
- var MmtpContainerParser = _MmtpContainerParser;
6086
6095
  function scanAv1ObusForKeyframe(data) {
6087
6096
  let offset = 0;
6088
6097
  let sawSequenceHeader = false;
@@ -6159,49 +6168,45 @@ function findAnnexBStart(data, offset) {
6159
6168
  }
6160
6169
 
6161
6170
  // src/mmtp-decode-pipeline.ts
6162
- var _parser, _fecClient, _frameCb2, _initCb2, _needsKeyframe, _codec, _trackType, _gateDropped, _gateEmitted, _fedObjects2, _warnedNoParser, _feedOutcomes2, _MmtpDecodePipeline_instances, tag_fn, gatedEmit_fn;
6163
6171
  var MmtpDecodePipeline = class {
6164
- constructor() {
6165
- __privateAdd(this, _MmtpDecodePipeline_instances);
6166
- __privateAdd(this, _parser, null);
6167
- __privateAdd(this, _fecClient, null);
6168
- __privateAdd(this, _frameCb2, null);
6169
- __privateAdd(this, _initCb2, null);
6170
- __privateAdd(this, _needsKeyframe, false);
6171
- __privateAdd(this, _codec, null);
6172
- /** Set together with #codec at configure(). Also the diagnostic label: a
6173
- * player builds one pipeline per track, and codec alone does not say which
6174
- * role a line belongs to at a glance. */
6175
- __privateAdd(this, _trackType, null);
6176
- /** Diagnostic counters. The keyframe gate drops silently, so a parser that
6177
- * never marks a frame as a keyframe stalls the whole pipeline with no
6178
- * output anywhere: frames are fed, frames are parsed, and nothing is
6179
- * emitted. Bounded logging only — these gate nothing. */
6180
- __privateAdd(this, _gateDropped, 0);
6181
- __privateAdd(this, _gateEmitted, 0);
6182
- __privateAdd(this, _fedObjects2, 0);
6183
- /** Warned-once latch for feeds arriving with no parser. Kept separate from
6184
- * #fedObjects so that counter stays a pure monotonic count. */
6185
- __privateAdd(this, _warnedNoParser, false);
6186
- /** Histogram of feed() outcomes. feed() already reports which of its ~7 exit
6187
- * paths a packet took, via its return value — but the call below discards it,
6188
- * so a packet that fails header parse, fails MFU extraction, or accumulates
6189
- * forever as an unreassembled fragment is indistinguishable from one that
6190
- * produced a frame. Tally the kinds instead of guessing. */
6191
- __privateAdd(this, _feedOutcomes2, /* @__PURE__ */ new Map());
6192
- }
6172
+ #parser = null;
6173
+ #fecClient = null;
6174
+ #frameCb = null;
6175
+ #initCb = null;
6176
+ #needsKeyframe = false;
6177
+ #codec = null;
6178
+ /** Set together with #codec at configure(). Also the diagnostic label: a
6179
+ * player builds one pipeline per track, and codec alone does not say which
6180
+ * role a line belongs to at a glance. */
6181
+ #trackType = null;
6182
+ /** Diagnostic counters. The keyframe gate drops silently, so a parser that
6183
+ * never marks a frame as a keyframe stalls the whole pipeline with no
6184
+ * output anywhere: frames are fed, frames are parsed, and nothing is
6185
+ * emitted. Bounded logging only — these gate nothing. */
6186
+ #gateDropped = 0;
6187
+ #gateEmitted = 0;
6188
+ #fedObjects = 0;
6189
+ /** Warned-once latch for feeds arriving with no parser. Kept separate from
6190
+ * #fedObjects so that counter stays a pure monotonic count. */
6191
+ #warnedNoParser = false;
6192
+ /** Histogram of feed() outcomes. feed() already reports which of its ~7 exit
6193
+ * paths a packet took, via its return value — but the call below discards it,
6194
+ * so a packet that fails header parse, fails MFU extraction, or accumulates
6195
+ * forever as an unreassembled fragment is indistinguishable from one that
6196
+ * produced a frame. Tally the kinds instead of guessing. */
6197
+ #feedOutcomes = /* @__PURE__ */ new Map();
6193
6198
  /** Configure the inner parser. Call before feedMoqObject(). */
6194
6199
  configure(config) {
6195
- __privateGet(this, _parser)?.flush();
6196
- __privateGet(this, _parser)?.dispose();
6197
- __privateSet(this, _fedObjects2, 0);
6198
- __privateSet(this, _gateDropped, 0);
6199
- __privateSet(this, _gateEmitted, 0);
6200
- __privateGet(this, _feedOutcomes2).clear();
6201
- __privateSet(this, _warnedNoParser, false);
6202
- __privateSet(this, _codec, config.codec);
6200
+ this.#parser?.flush();
6201
+ this.#parser?.dispose();
6202
+ this.#fedObjects = 0;
6203
+ this.#gateDropped = 0;
6204
+ this.#gateEmitted = 0;
6205
+ this.#feedOutcomes.clear();
6206
+ this.#warnedNoParser = false;
6207
+ this.#codec = config.codec;
6203
6208
  const trackType = isVideoCodec(config.codec) ? "video" : "audio";
6204
- __privateSet(this, _trackType, trackType);
6209
+ this.#trackType = trackType;
6205
6210
  const trackInfo = {
6206
6211
  type: trackType,
6207
6212
  codec: config.codec,
@@ -6212,7 +6217,7 @@ var MmtpDecodePipeline = class {
6212
6217
  if (config.packetId != null) {
6213
6218
  tracks.set(config.packetId, trackInfo);
6214
6219
  }
6215
- __privateSet(this, _parser, new MmtpContainerParser({
6220
+ this.#parser = new MmtpContainerParser({
6216
6221
  tracks,
6217
6222
  reorderWindow: config.reorderWindow ?? 0,
6218
6223
  mfuTimeoutMs: config.mfuTimeoutMs,
@@ -6220,30 +6225,29 @@ var MmtpDecodePipeline = class {
6220
6225
  reassembler: config.reassembler,
6221
6226
  maxBufferedMfus: config.maxBufferedMfus,
6222
6227
  defaultTrack: trackInfo
6223
- }));
6224
- __privateGet(this, _parser).onFrame((data, meta) => {
6225
- __privateMethod(this, _MmtpDecodePipeline_instances, gatedEmit_fn).call(this, data, meta);
6226
6228
  });
6227
- __privateGet(this, _parser).onInit((data, packetId) => {
6228
- var _a;
6229
- (_a = __privateGet(this, _initCb2)) == null ? void 0 : _a.call(this, data, packetId);
6229
+ this.#parser.onFrame((data, meta) => {
6230
+ this.#gatedEmit(data, meta);
6231
+ });
6232
+ this.#parser.onInit((data, packetId) => {
6233
+ this.#initCb?.(data, packetId);
6230
6234
  });
6231
6235
  }
6232
6236
  /** Inject a FEC client for source symbol feeding on the MoQ path. */
6233
6237
  setFecClient(client) {
6234
- __privateSet(this, _fecClient, client);
6238
+ this.#fecClient = client;
6235
6239
  }
6236
6240
  /** Register frame output callback. */
6237
6241
  onFrame(cb) {
6238
- __privateSet(this, _frameCb2, cb);
6242
+ this.#frameCb = cb;
6239
6243
  }
6240
6244
  /** Register init segment callback. */
6241
6245
  onInit(cb) {
6242
- __privateSet(this, _initCb2, cb);
6246
+ this.#initCb = cb;
6243
6247
  }
6244
6248
  /** Current shared-parser ordering/drop telemetry. */
6245
6249
  get reorderStats() {
6246
- return __privateGet(this, _parser)?.reorderStats ?? null;
6250
+ return this.#parser?.reorderStats ?? null;
6247
6251
  }
6248
6252
  /**
6249
6253
  * Feed tallies for this track. A fresh snapshot per call, not a live view.
@@ -6255,53 +6259,59 @@ var MmtpDecodePipeline = class {
6255
6259
  */
6256
6260
  get feedStats() {
6257
6261
  return {
6258
- trackType: __privateGet(this, _trackType),
6259
- codec: __privateGet(this, _codec),
6260
- fedObjects: __privateGet(this, _fedObjects2),
6261
- emitted: __privateGet(this, _gateEmitted),
6262
- gateDropped: __privateGet(this, _gateDropped),
6263
- outcomes: Object.fromEntries(__privateGet(this, _feedOutcomes2))
6262
+ trackType: this.#trackType,
6263
+ codec: this.#codec,
6264
+ fedObjects: this.#fedObjects,
6265
+ emitted: this.#gateEmitted,
6266
+ gateDropped: this.#gateDropped,
6267
+ outcomes: Object.fromEntries(this.#feedOutcomes)
6264
6268
  };
6265
6269
  }
6270
+ /** Identity prefix for diagnostics: one pipeline per track means two
6271
+ * instances write to the same console, and unlabelled lines interleave into
6272
+ * a single unreadable stream. */
6273
+ #tag() {
6274
+ return `track=${this.#trackType ?? "unconfigured"} codec=${this.#codec ?? "none"}`;
6275
+ }
6266
6276
  /**
6267
6277
  * Feed a raw MoQ object payload (one MMTP packet per MoQ object).
6268
6278
  * Optionally feeds source symbols to FEC client before parsing.
6269
6279
  */
6270
6280
  feedMoqObject(packet) {
6271
- if (!__privateGet(this, _parser)) {
6272
- if (!__privateGet(this, _warnedNoParser)) {
6273
- __privateSet(this, _warnedNoParser, true);
6274
- console.warn(`[mmtp-pipeline] feedMoqObject called with NO PARSER configured ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} \u2014 packet dropped`);
6281
+ if (!this.#parser) {
6282
+ if (!this.#warnedNoParser) {
6283
+ this.#warnedNoParser = true;
6284
+ console.warn(`[mmtp-pipeline] feedMoqObject called with NO PARSER configured ${this.#tag()} \u2014 packet dropped`);
6275
6285
  }
6276
6286
  return;
6277
6287
  }
6278
- __privateSet(this, _fedObjects2, __privateGet(this, _fedObjects2) + 1);
6279
- if (__privateGet(this, _fedObjects2) === 1) {
6280
- console.log(`[mmtp-pipeline] first object fed ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${packet.length}`);
6288
+ this.#fedObjects += 1;
6289
+ if (this.#fedObjects === 1) {
6290
+ console.log(`[mmtp-pipeline] first object fed ${this.#tag()} bytes=${packet.length}`);
6281
6291
  }
6282
6292
  let outcomeKind = "threw";
6283
6293
  try {
6284
- if (__privateGet(this, _fecClient)?.addSourceSymbol) {
6285
- const info = __privateGet(this, _parser).parseHeader(packet);
6294
+ if (this.#fecClient?.addSourceSymbol) {
6295
+ const info = this.#parser.parseHeader(packet);
6286
6296
  if (info?.fecPayloadId) {
6287
- __privateGet(this, _fecClient).addSourceSymbol(info.fecPayloadId.ssId, packet);
6297
+ this.#fecClient.addSourceSymbol(info.fecPayloadId.ssId, packet);
6288
6298
  }
6289
6299
  }
6290
- const record = __privateGet(this, _parser).feed(packet);
6300
+ const record = this.#parser.feed(packet);
6291
6301
  outcomeKind = record?.kind ?? "null(parse-or-extract-failed)";
6292
6302
  } finally {
6293
- const seen = (__privateGet(this, _feedOutcomes2).get(outcomeKind) ?? 0) + 1;
6294
- __privateGet(this, _feedOutcomes2).set(outcomeKind, seen);
6303
+ const seen = (this.#feedOutcomes.get(outcomeKind) ?? 0) + 1;
6304
+ this.#feedOutcomes.set(outcomeKind, seen);
6295
6305
  if (seen === 1) {
6296
6306
  console.log(
6297
- `[mmtp-pipeline] feed outcome FIRST '${outcomeKind}' ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} at object #${__privateGet(this, _fedObjects2)} bytes=${packet.length}`
6307
+ `[mmtp-pipeline] feed outcome FIRST '${outcomeKind}' ${this.#tag()} at object #${this.#fedObjects} bytes=${packet.length}`
6298
6308
  );
6299
6309
  }
6300
6310
  }
6301
- if (__privateGet(this, _fedObjects2) % 200 === 0) {
6302
- const hist = [...__privateGet(this, _feedOutcomes2)].map(([k, v]) => `${k}=${v}`).join(" ");
6311
+ if (this.#fedObjects % 200 === 0) {
6312
+ const hist = [...this.#feedOutcomes].map(([k, v]) => `${k}=${v}`).join(" ");
6303
6313
  console.log(
6304
- `[mmtp-pipeline] feed histogram ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} @${__privateGet(this, _fedObjects2)}: ${hist} | emitted=${__privateGet(this, _gateEmitted)} gateDropped=${__privateGet(this, _gateDropped)}`
6314
+ `[mmtp-pipeline] feed histogram ${this.#tag()} @${this.#fedObjects}: ${hist} | emitted=${this.#gateEmitted} gateDropped=${this.#gateDropped}`
6305
6315
  );
6306
6316
  }
6307
6317
  }
@@ -6324,85 +6334,65 @@ var MmtpDecodePipeline = class {
6324
6334
  // Same derivation as configure(), read from the field it set rather than
6325
6335
  // recomputed. Pre-configure the parser is null and routeFrame below is a
6326
6336
  // no-op, so the fallback is unreachable in practice.
6327
- trackType: __privateGet(this, _trackType) ?? "audio",
6337
+ trackType: this.#trackType ?? "audio",
6328
6338
  packetSequenceNumber: meta.packetSequenceNumber
6329
6339
  };
6330
6340
  if (meta.sourceDiscontinuity) frameMeta.sourceDiscontinuity = true;
6331
6341
  if (meta.recovered) frameMeta.recovered = true;
6332
6342
  if (meta.deliveryProvenance !== void 0)
6333
6343
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
6334
- __privateGet(this, _parser)?.routeFrame(data, frameMeta);
6344
+ this.#parser?.routeFrame(data, frameMeta);
6335
6345
  }
6336
6346
  /** Request keyframe — gates output until a keyframe arrives. */
6337
6347
  requestKeyframe() {
6338
- __privateSet(this, _needsKeyframe, true);
6348
+ this.#needsKeyframe = true;
6339
6349
  }
6340
6350
  /** Emit buffered ordered frames. Finite consumers call this before dispose(). */
6341
6351
  flush() {
6342
- __privateGet(this, _parser)?.flush();
6352
+ this.#parser?.flush();
6343
6353
  }
6344
6354
  /** Clean up the pipeline. Finite inputs pass flush=true at EOS; live
6345
6355
  * cancellation keeps the default drop-only teardown behavior. */
6346
6356
  dispose(options = {}) {
6347
- const droppedBefore = __privateGet(this, _parser)?.reorderStats.droppedOnLiveDispose ?? 0;
6348
- if (options.flush) __privateGet(this, _parser)?.flush();
6349
- __privateGet(this, _parser)?.dispose();
6350
- const droppedFrames = (__privateGet(this, _parser)?.reorderStats.droppedOnLiveDispose ?? droppedBefore) - droppedBefore;
6357
+ const droppedBefore = this.#parser?.reorderStats.droppedOnLiveDispose ?? 0;
6358
+ if (options.flush) this.#parser?.flush();
6359
+ this.#parser?.dispose();
6360
+ const droppedFrames = (this.#parser?.reorderStats.droppedOnLiveDispose ?? droppedBefore) - droppedBefore;
6351
6361
  if (droppedFrames > 0) {
6352
6362
  console.warn(
6353
- `[MmtpDecodePipeline] live dispose ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
6363
+ `[MmtpDecodePipeline] live dispose ${this.#tag()} dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
6354
6364
  );
6355
6365
  }
6356
- __privateSet(this, _parser, null);
6357
- __privateSet(this, _frameCb2, null);
6358
- __privateSet(this, _initCb2, null);
6359
- __privateSet(this, _fecClient, null);
6360
- }
6361
- };
6362
- _parser = new WeakMap();
6363
- _fecClient = new WeakMap();
6364
- _frameCb2 = new WeakMap();
6365
- _initCb2 = new WeakMap();
6366
- _needsKeyframe = new WeakMap();
6367
- _codec = new WeakMap();
6368
- _trackType = new WeakMap();
6369
- _gateDropped = new WeakMap();
6370
- _gateEmitted = new WeakMap();
6371
- _fedObjects2 = new WeakMap();
6372
- _warnedNoParser = new WeakMap();
6373
- _feedOutcomes2 = new WeakMap();
6374
- _MmtpDecodePipeline_instances = new WeakSet();
6375
- /** Identity prefix for diagnostics: one pipeline per track means two
6376
- * instances write to the same console, and unlabelled lines interleave into
6377
- * a single unreadable stream. */
6378
- tag_fn = function() {
6379
- return `track=${__privateGet(this, _trackType) ?? "unconfigured"} codec=${__privateGet(this, _codec) ?? "none"}`;
6380
- };
6381
- gatedEmit_fn = function(data, meta) {
6382
- var _a;
6383
- let sourceDiscontinuity = false;
6384
- if (__privateGet(this, _needsKeyframe)) {
6385
- if (!meta.keyframe) {
6386
- __privateSet(this, _gateDropped, __privateGet(this, _gateDropped) + 1);
6387
- if (__privateGet(this, _gateDropped) <= 3 || __privateGet(this, _gateDropped) % 200 === 0) {
6388
- console.warn(
6389
- `[mmtp-pipeline] keyframe gate DROP #${__privateGet(this, _gateDropped)} ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${data.length} fed=${__privateGet(this, _fedObjects2)} emitted=${__privateGet(this, _gateEmitted)}`
6390
- );
6366
+ this.#parser = null;
6367
+ this.#frameCb = null;
6368
+ this.#initCb = null;
6369
+ this.#fecClient = null;
6370
+ }
6371
+ #gatedEmit(data, meta) {
6372
+ let sourceDiscontinuity = false;
6373
+ if (this.#needsKeyframe) {
6374
+ if (!meta.keyframe) {
6375
+ this.#gateDropped += 1;
6376
+ if (this.#gateDropped <= 3 || this.#gateDropped % 200 === 0) {
6377
+ console.warn(
6378
+ `[mmtp-pipeline] keyframe gate DROP #${this.#gateDropped} ${this.#tag()} bytes=${data.length} fed=${this.#fedObjects} emitted=${this.#gateEmitted}`
6379
+ );
6380
+ }
6381
+ return;
6391
6382
  }
6392
- return;
6383
+ this.#needsKeyframe = false;
6384
+ sourceDiscontinuity = true;
6385
+ console.log(
6386
+ `[mmtp-pipeline] keyframe gate OPENED ${this.#tag()} after ${this.#gateDropped} drops, fed=${this.#fedObjects}`
6387
+ );
6393
6388
  }
6394
- __privateSet(this, _needsKeyframe, false);
6395
- sourceDiscontinuity = true;
6396
- console.log(
6397
- `[mmtp-pipeline] keyframe gate OPENED ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} after ${__privateGet(this, _gateDropped)} drops, fed=${__privateGet(this, _fedObjects2)}`
6398
- );
6399
- }
6400
- __privateSet(this, _gateEmitted, __privateGet(this, _gateEmitted) + 1);
6401
- if (__privateGet(this, _gateEmitted) === 1) {
6402
- console.log(`[mmtp-pipeline] first frame emitted ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${data.length}`);
6389
+ this.#gateEmitted += 1;
6390
+ if (this.#gateEmitted === 1) {
6391
+ console.log(`[mmtp-pipeline] first frame emitted ${this.#tag()} bytes=${data.length}`);
6392
+ }
6393
+ const outMeta = sourceDiscontinuity ? { ...meta, sourceDiscontinuity: true } : meta;
6394
+ this.#frameCb?.(data, outMeta);
6403
6395
  }
6404
- const outMeta = sourceDiscontinuity ? { ...meta, sourceDiscontinuity: true } : meta;
6405
- (_a = __privateGet(this, _frameCb2)) == null ? void 0 : _a.call(this, data, outMeta);
6406
6396
  };
6407
6397
  function isVideoCodec(codec) {
6408
6398
  return codec.startsWith("avc") || codec.startsWith("hev1") || codec.startsWith("hvc1") || codec.startsWith("av01") || codec.startsWith("vp09") || codec.startsWith("vp8");