@blockcast/mmt-container 2.2.0-main.ea9223dc11de → 2.2.0-main.ec45bee1b9cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +125 -2
  2. package/dist/__tests__/ad-creative-signer.d.ts +11 -0
  3. package/dist/__tests__/ad-creative-signer.d.ts.map +1 -0
  4. package/dist/__tests__/test-utils.d.ts +1 -0
  5. package/dist/__tests__/test-utils.d.ts.map +1 -1
  6. package/dist/ad-beacon.d.ts +39 -0
  7. package/dist/ad-beacon.d.ts.map +1 -0
  8. package/dist/ad-beacon.js +23 -0
  9. package/dist/ad-beacon.js.map +7 -0
  10. package/dist/ad-creative-record.d.ts +65 -0
  11. package/dist/ad-creative-record.d.ts.map +1 -0
  12. package/dist/ad-creative-record.js +2281 -0
  13. package/dist/ad-creative-record.js.map +7 -0
  14. package/dist/ad-creative-timeline.d.ts +103 -0
  15. package/dist/ad-creative-timeline.d.ts.map +1 -0
  16. package/dist/ad-creative-timeline.js +2550 -0
  17. package/dist/ad-creative-timeline.js.map +7 -0
  18. package/dist/block-policy.d.ts +128 -14
  19. package/dist/block-policy.d.ts.map +1 -1
  20. package/dist/block-policy.js +472 -27
  21. package/dist/block-policy.js.map +2 -2
  22. package/dist/browser-runtime.js +1039 -120
  23. package/dist/browser-runtime.js.map +4 -4
  24. package/dist/carp-catalog.d.ts +1 -0
  25. package/dist/carp-catalog.d.ts.map +1 -1
  26. package/dist/carp-catalog.js +34 -0
  27. package/dist/carp-catalog.js.map +4 -4
  28. package/dist/catalog-fec-params.js.map +1 -1
  29. package/dist/catalog-network-source.d.ts +1 -17
  30. package/dist/catalog-network-source.d.ts.map +1 -1
  31. package/dist/catalog-network-source.js +25 -19
  32. package/dist/catalog-network-source.js.map +3 -3
  33. package/dist/cmaf-block-assembler.d.ts +10 -2
  34. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  35. package/dist/cmaf-block-assembler.js +30 -8
  36. package/dist/cmaf-block-assembler.js.map +3 -3
  37. package/dist/codec-utils.d.ts.map +1 -1
  38. package/dist/codec-utils.js +16 -3
  39. package/dist/codec-utils.js.map +2 -2
  40. package/dist/conceal-timeline.d.ts +24 -1
  41. package/dist/conceal-timeline.d.ts.map +1 -1
  42. package/dist/conceal-timeline.js +201 -4
  43. package/dist/conceal-timeline.js.map +3 -3
  44. package/dist/datagram-leg-deadline.d.ts +4 -0
  45. package/dist/datagram-leg-deadline.d.ts.map +1 -1
  46. package/dist/datagram-leg-deadline.js.map +2 -2
  47. package/dist/event-timeline-mmtp.d.ts +17 -0
  48. package/dist/event-timeline-mmtp.d.ts.map +1 -0
  49. package/dist/event-timeline-mmtp.js +3117 -0
  50. package/dist/event-timeline-mmtp.js.map +7 -0
  51. package/dist/fec-manager.d.ts +24 -3
  52. package/dist/fec-manager.d.ts.map +1 -1
  53. package/dist/fec-manager.js +531 -38
  54. package/dist/fec-manager.js.map +2 -2
  55. package/dist/feed-gate.d.ts +114 -0
  56. package/dist/feed-gate.d.ts.map +1 -0
  57. package/dist/feed-gate.js +175 -0
  58. package/dist/feed-gate.js.map +7 -0
  59. package/dist/index.d.ts +3 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +13 -1
  62. package/dist/index.js.map +2 -2
  63. package/dist/iso-bmff-timing.d.ts +16 -0
  64. package/dist/iso-bmff-timing.d.ts.map +1 -1
  65. package/dist/iso-bmff-timing.js +28 -0
  66. package/dist/iso-bmff-timing.js.map +2 -2
  67. package/dist/mfu-reassembler.d.ts +2 -0
  68. package/dist/mfu-reassembler.d.ts.map +1 -1
  69. package/dist/mfu-reassembler.js +4 -2
  70. package/dist/mfu-reassembler.js.map +2 -2
  71. package/dist/mmtp-container-parser.d.ts +12 -0
  72. package/dist/mmtp-container-parser.d.ts.map +1 -1
  73. package/dist/mmtp-container-parser.js +73 -3
  74. package/dist/mmtp-container-parser.js.map +2 -2
  75. package/dist/mmtp-container-parser.no-modules.js +103 -25
  76. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  77. package/dist/mmtp-decode-pipeline.js +73 -3
  78. package/dist/mmtp-decode-pipeline.js.map +2 -2
  79. package/dist/mmtp-router.d.ts +20 -2
  80. package/dist/mmtp-router.d.ts.map +1 -1
  81. package/dist/mmtp-router.js +150 -23
  82. package/dist/mmtp-router.js.map +3 -3
  83. package/dist/multicast-auth-catalog.js.map +1 -1
  84. package/dist/multicast-input.js.map +1 -1
  85. package/dist/multicast-manager.d.ts +23 -2
  86. package/dist/multicast-manager.d.ts.map +1 -1
  87. package/dist/multicast-manager.js +749 -87
  88. package/dist/multicast-manager.js.map +3 -3
  89. package/dist/multicast-transport.d.ts +8 -0
  90. package/dist/multicast-transport.d.ts.map +1 -1
  91. package/dist/multicast-transport.js +56 -23
  92. package/dist/multicast-transport.js.map +2 -2
  93. package/dist/no-modules.js +98 -22
  94. package/dist/no-modules.js.map +4 -4
  95. package/dist/repair-fetch.d.ts +15 -7
  96. package/dist/repair-fetch.d.ts.map +1 -1
  97. package/dist/repair-fetch.js +34 -7
  98. package/dist/repair-fetch.js.map +2 -2
  99. package/dist/wasm-mfu-reassembler.js.map +2 -2
  100. package/dist/wasm-mmtp-container-parser.js +73 -3
  101. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  102. package/package.json +17 -5
  103. package/schemas/catalog.schema.json +7 -2
  104. package/src/ad-beacon.ts +54 -0
  105. package/src/ad-creative-record.ts +276 -0
  106. package/src/ad-creative-timeline.ts +410 -0
  107. package/src/block-policy.ts +673 -42
  108. package/src/carp-catalog.ts +9 -0
  109. package/src/catalog-network-source.ts +3 -37
  110. package/src/cmaf-block-assembler.ts +17 -0
  111. package/src/codec-utils.ts +19 -3
  112. package/src/conceal-timeline.ts +60 -5
  113. package/src/datagram-leg-deadline.ts +4 -0
  114. package/src/event-timeline-mmtp.ts +55 -0
  115. package/src/fec-manager.ts +84 -12
  116. package/src/feed-gate.ts +295 -0
  117. package/src/index.ts +21 -0
  118. package/src/iso-bmff-timing.ts +33 -0
  119. package/src/mfu-reassembler.ts +4 -0
  120. package/src/mmtp-container-parser.ts +51 -5
  121. package/src/mmtp-router.ts +116 -4
  122. package/src/multicast-manager.ts +31 -0
  123. package/src/multicast-transport.ts +27 -2
  124. package/src/repair-fetch.ts +70 -19
  125. package/test-vectors/catalog/README.md +1 -0
  126. package/test-vectors/catalog/negative/event-timeline-empty-event-type.json +41 -0
  127. package/test-vectors/catalog/positive/event-timeline-ad-creative.json +41 -0
  128. package/test-vectors/catalog/positive/event-timeline-wallclock-no-depends.json +38 -0
  129. package/test-vectors/catalog/positive/multicast-event-timeline.json +81 -0
  130. package/test-vectors/catalog/section-codes.json +1 -0
  131. package/test-vectors/frame-needs-v1.json +295 -0
  132. package/test-vectors/repair-policy-v1.json +98 -18
@@ -1374,6 +1374,23 @@ function multicastCatalogIssues(catalog, options = {}) {
1374
1374
  }
1375
1375
  return issues;
1376
1376
  }
1377
+ function catalogAtsc3NetworkSource(networkSource) {
1378
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
1379
+ for (const ns of entries) {
1380
+ if (!isObject(ns))
1381
+ continue;
1382
+ if (ns.type !== "atsc3" || !isIntegerIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER))
1383
+ continue;
1384
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
1385
+ return {
1386
+ frequency: ns.frequency,
1387
+ ...isIntegerIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
1388
+ ...isIntegerIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
1389
+ ...slsUri ? { slsUri } : {}
1390
+ };
1391
+ }
1392
+ return void 0;
1393
+ }
1377
1394
 
1378
1395
  // ../mmt-base/dist/fec-catalog.js
1379
1396
  var DEFAULT_SCHEMES = ["reed-solomon", "raptorq"];
@@ -1983,6 +2000,39 @@ function datagramLegObjectMax(symbolSize) {
1983
2000
  return DATAGRAM_LEG_OBJECT_HEADER + DATAGRAM_LEG_REPAIR_OVERHEAD + symbolSize;
1984
2001
  }
1985
2002
 
2003
+ // ../mmt-base/dist/event-timeline-catalog.js
2004
+ var RIEDL_AD_CREATIVE = "urn:svta:advertising-wg:ad-creative-signaling";
2005
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2006
+ function catalogEventTimelineTracks(catalog, eventTypes) {
2007
+ const tracks = [];
2008
+ const issues = [];
2009
+ const list = isObject2(catalog) && Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
2010
+ const named = new Set(list.filter(isObject2).map((t) => `${String(t["namespace"] ?? "")}\0${String(t["name"])}`));
2011
+ list.forEach((t, index) => {
2012
+ if (!isObject2(t) || t["packaging"] !== "eventtimeline" || typeof t["name"] !== "string")
2013
+ return;
2014
+ const name = t["name"];
2015
+ const issue = (code, field) => {
2016
+ issues.push({ code, path: `$.tracks[${index}].${field}`, name, index });
2017
+ };
2018
+ const eventType = t["eventType"];
2019
+ if (typeof eventType !== "string" || eventType.length === 0)
2020
+ return issue("track_event_type", "eventType");
2021
+ if (t["mimeType"] !== void 0 && t["mimeType"] !== "application/json")
2022
+ return issue("track_event_mime_type", "mimeType");
2023
+ const namespace = String(t["namespace"] ?? "");
2024
+ const depends = t["depends"] ?? [];
2025
+ if (!Array.isArray(depends) || eventType === RIEDL_AD_CREATIVE && depends.length === 0 || !depends.every((d) => typeof d === "string" && d !== name && named.has(`${namespace}\0${d}`))) {
2026
+ return issue("track_event_depends", "depends");
2027
+ }
2028
+ if (eventTypes !== void 0 && !eventTypes.includes(eventType))
2029
+ return;
2030
+ const ns = t["namespace"];
2031
+ tracks.push({ name, ...typeof ns === "string" ? { namespace: ns } : {}, eventType, depends });
2032
+ });
2033
+ return { tracks, issues };
2034
+ }
2035
+
1986
2036
  // src/mfu-reassembler.ts
1987
2037
  function fragmentProvenance(fragment) {
1988
2038
  if (fragment.deliveryProvenance !== void 0) return fragment.deliveryProvenance;
@@ -2233,7 +2283,8 @@ var MFUReassembler = class {
2233
2283
  sampleOffset: fragment.sampleOffset,
2234
2284
  source: fragment.source,
2235
2285
  deliveryProvenance: deliveryProvenanceOf([fragment]),
2236
- catalogTrackName: fragment.catalogTrackName
2286
+ catalogTrackName: fragment.catalogTrackName,
2287
+ itemId: fragment.itemId
2237
2288
  };
2238
2289
  }
2239
2290
  const sequence = fragment.packetSequenceNumber;
@@ -2609,7 +2660,8 @@ var MFUReassembler = class {
2609
2660
  sampleOffset: fragments[0].sampleOffset,
2610
2661
  source: fragments[0].source,
2611
2662
  deliveryProvenance: deliveryProvenanceOf(fragments),
2612
- catalogTrackName: fragments[0].catalogTrackName
2663
+ catalogTrackName: fragments[0].catalogTrackName,
2664
+ itemId: fragments[0].itemId
2613
2665
  };
2614
2666
  }
2615
2667
  #setTimeout(bufferKey, startedAt = Date.now()) {
@@ -5852,7 +5904,7 @@ function splitH264SampleNalUnits(data, options = {}) {
5852
5904
  return { nals, format: nals.length > 0 ? "avcc" : "unknown" };
5853
5905
  }
5854
5906
  function extractHevcParameterSets(keyframe) {
5855
- const nals = isAnnexB(keyframe) ? splitAnnexBNalUnits(keyframe) : splitAvccNalUnits(keyframe);
5907
+ const nals = splitHevcSample(keyframe)?.nals ?? splitAvccNalUnits(keyframe);
5856
5908
  const out = {};
5857
5909
  for (const nal of nals) {
5858
5910
  if (nal.length === 0) continue;
@@ -5913,9 +5965,9 @@ function extractHevcCodecDescription(keyframe) {
5913
5965
  return generateHvcCFromParameterSets(extractHevcParameterSets(keyframe));
5914
5966
  }
5915
5967
  function hevcVclOnly(data) {
5916
- const nals = isAnnexB(data) ? splitAnnexBNalUnits(data) : splitAvccNalUnits(data);
5968
+ const { nals, lengthPrefixed } = splitHevcSample(data) ?? { nals: splitAvccNalUnits(data), lengthPrefixed: true };
5917
5969
  const vcl = nals.filter((n) => n.length > 0 && hevcNalType(n) <= 31);
5918
- if (vcl.length === nals.length && !isAnnexB(data)) return data;
5970
+ if (vcl.length === nals.length && lengthPrefixed) return data;
5919
5971
  let size = 0;
5920
5972
  for (const n of vcl) size += 4 + n.length;
5921
5973
  const out = new Uint8Array(size);
@@ -6968,6 +7020,19 @@ if (void 0) {
6968
7020
  const vclOnly = lp(idr);
6969
7021
  expect(hevcVclOnly(vclOnly)).toBe(vclOnly);
6970
7022
  });
7023
+ test("a first NAL of 256 to 511 bytes is length-prefixed, not an Annex-B start code", () => {
7024
+ for (const nalLength of [255, 256, 511, 512]) {
7025
+ const sei = new Uint8Array(nalLength).fill(255);
7026
+ sei.set([39 << 1, 1]);
7027
+ const keyframe = lp(sei, vps, sps, pps, idr);
7028
+ expect(extractHevcParameterSets(keyframe), `${nalLength}`).toEqual({ vps, sps, pps });
7029
+ expect(hevcVclOnly(keyframe), `${nalLength}`).toEqual(lp(idr));
7030
+ const slice = new Uint8Array(nalLength).fill(255);
7031
+ slice.set([1 << 1, 1]);
7032
+ const vclOnly = lp(slice);
7033
+ expect(hevcVclOnly(vclOnly), `${nalLength}`).toBe(vclOnly);
7034
+ }
7035
+ });
6971
7036
  });
6972
7037
  });
6973
7038
  }
@@ -8822,12 +8887,16 @@ var transportManager = new TransportManager();
8822
8887
  var REGISTRY = /* @__PURE__ */ Symbol.for("@blockcast/mmt-transport/native-provider-registry/v1");
8823
8888
  var USER_AGENT_VERIFIED = /* @__PURE__ */ Symbol.for("@blockcast/mmt-transport/user-agent-verified/v1");
8824
8889
  var INTEGRITY_SCHEME = "manifest-ed25519-2";
8890
+ var RECEIVER_OPEN_TIMEOUT_MS = 1e4;
8825
8891
  var MulticastError = class extends Error {
8826
8892
  code;
8827
- constructor(code, message, cause) {
8893
+ failure;
8894
+ constructor(code, message, cause, failure) {
8828
8895
  super(message, cause === void 0 ? void 0 : { cause });
8829
8896
  this.name = "MulticastError";
8830
8897
  this.code = code;
8898
+ if (failure !== void 0)
8899
+ this.failure = failure;
8831
8900
  }
8832
8901
  };
8833
8902
  function datagramsOf(chunk) {
@@ -8921,20 +8990,37 @@ function createProvider(scope) {
8921
8990
  } catch (error) {
8922
8991
  throw unsupported("MulticastReceiver refused the request", error);
8923
8992
  }
8924
- const opened = rx.opened;
8993
+ const opened = boundedOpen(rx);
8925
8994
  if (gate === null)
8926
8995
  gate = opened.then(() => void 0, () => void 0);
8927
8996
  return openSubscription(rx, opened, options, c.packetIds);
8928
8997
  }
8929
8998
  };
8930
8999
  }
9000
+ function boundedOpen(rx) {
9001
+ return new Promise((resolve, reject) => {
9002
+ const timer = setTimeout(() => {
9003
+ reject(new MulticastError("subscription-failed", "MulticastReceiver did not open in time", void 0, "open-timeout"));
9004
+ void Promise.resolve().then(() => rx.close()).catch(() => void 0);
9005
+ }, RECEIVER_OPEN_TIMEOUT_MS);
9006
+ rx.opened.then((info) => {
9007
+ clearTimeout(timer);
9008
+ resolve(info);
9009
+ }, (error) => {
9010
+ clearTimeout(timer);
9011
+ reject(new MulticastError("subscription-failed", "MulticastReceiver did not open", error, "open-rejected"));
9012
+ });
9013
+ rx.closed.then((value) => {
9014
+ clearTimeout(timer);
9015
+ reject(new MulticastError("subscription-failed", "MulticastReceiver closed before opening", reasonOf(value), "closed-before-data"));
9016
+ }, (error) => {
9017
+ clearTimeout(timer);
9018
+ reject(new MulticastError("subscription-failed", "MulticastReceiver closed before opening", error, "closed-before-data"));
9019
+ });
9020
+ });
9021
+ }
8931
9022
  async function openSubscription(rx, openedPromise, options, packetIds) {
8932
- let opened;
8933
- try {
8934
- opened = await openedPromise;
8935
- } catch (error) {
8936
- throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
8937
- }
9023
+ const opened = await openedPromise;
8938
9024
  if (opened.integrityScheme !== INTEGRITY_SCHEME) {
8939
9025
  await rx.close();
8940
9026
  throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
@@ -8943,6 +9029,7 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8943
9029
  let state = "connected";
8944
9030
  let filter = packetIds?.length ? new Set(packetIds) : null;
8945
9031
  let closing = false;
9032
+ let delivered = false;
8946
9033
  const setState = (next) => {
8947
9034
  if (state === next)
8948
9035
  return;
@@ -8977,6 +9064,7 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8977
9064
  break;
8978
9065
  const packets = [];
8979
9066
  for (const data of datagramsOf(value)) {
9067
+ delivered = true;
8980
9068
  if (filter !== null) {
8981
9069
  const id = readMMTPPacketId2(data);
8982
9070
  if (id === null || !filter.has(id))
@@ -8992,26 +9080,25 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8992
9080
  } catch {
8993
9081
  }
8994
9082
  })();
9083
+ const fail = (code, message, cause) => {
9084
+ events.dispatchEvent(new CustomEvent("error", {
9085
+ detail: new MulticastError(code, message, cause, delivered ? void 0 : "closed-before-data")
9086
+ }));
9087
+ };
8995
9088
  void rx.closed.then((value) => {
8996
9089
  const reason = reasonOf(value);
8997
9090
  if (!closing) {
8998
- if (reason === "consent-withdrawn") {
8999
- events.dispatchEvent(new CustomEvent("error", {
9000
- detail: new MulticastError("origin-not-trusted", "multicast consent withdrawn")
9001
- }));
9002
- } else if (reason === "oversubscribed" || reason === "network") {
9003
- events.dispatchEvent(new CustomEvent("error", {
9004
- detail: new MulticastError("subscription-failed", `MulticastReceiver closed: ${reason}`)
9005
- }));
9006
- }
9091
+ if (reason === "consent-withdrawn")
9092
+ fail("origin-not-trusted", "multicast consent withdrawn");
9093
+ else if (reason === "oversubscribed" || reason === "network") {
9094
+ fail("subscription-failed", `MulticastReceiver closed: ${reason}`);
9095
+ } else if (!delivered)
9096
+ fail("subscription-failed", "MulticastReceiver closed before any datagram", reason);
9007
9097
  }
9008
9098
  setState("closed");
9009
9099
  }, (error) => {
9010
- if (!closing) {
9011
- events.dispatchEvent(new CustomEvent("error", {
9012
- detail: new MulticastError("subscription-failed", "MulticastReceiver failed", error)
9013
- }));
9014
- }
9100
+ if (!closing)
9101
+ fail("subscription-failed", "MulticastReceiver failed", error);
9015
9102
  setState("closed");
9016
9103
  });
9017
9104
  return subscription;
@@ -11086,25 +11173,209 @@ function classifyPacket(mmtpPacket) {
11086
11173
  }
11087
11174
  }
11088
11175
 
11176
+ // src/feed-gate.ts
11177
+ var FRAME_NEEDS_KEYFRAME = 254;
11178
+ var NOTHING_STATED = Object.freeze({ map: false, distance: 0, mayBeNeeded: true });
11179
+ var MAP_KEYFRAME = Object.freeze({ map: true, distance: 0, mayBeNeeded: true });
11180
+ function decodeFrameNeeds(code, keyframe) {
11181
+ if (keyframe) return code === FRAME_NEEDS_KEYFRAME ? MAP_KEYFRAME : NOTHING_STATED;
11182
+ if (!Number.isInteger(code) || code < 1 || code > 126 || code === 63 || code === 64) {
11183
+ return NOTHING_STATED;
11184
+ }
11185
+ return { map: false, distance: code & 63, mayBeNeeded: code > 64 };
11186
+ }
11187
+ function decoderTolerance(codec) {
11188
+ const lower = codec.toLowerCase();
11189
+ return lower.startsWith("avc1") || lower.startsWith("avc3") ? "conceals" : "none";
11190
+ }
11191
+ var VideoFeedGate = class {
11192
+ #inert;
11193
+ /** A statement was false, or a decoder failed on a selective feed: this track is read no more. */
11194
+ #off = false;
11195
+ /** `hold`: reading stopped inside a GOP in which the gate had answered for a hole. */
11196
+ #mode = "unread";
11197
+ #keyMpu = 0;
11198
+ #keyPosition = 0;
11199
+ /** Slot `position & 63` holds the position fed there: the last 64 positions. */
11200
+ #fedAt = new Float64Array(64).fill(-1);
11201
+ /** Frames fed since the keyframe. */
11202
+ #fedCount = 0;
11203
+ /** Place after the keyframe of the last frame fed. */
11204
+ #top = 0;
11205
+ /** Place after the keyframe of the last frame the gate allowed. */
11206
+ #allowed = 0;
11207
+ #withheldInGop = false;
11208
+ #fedAcrossGap = false;
11209
+ /** A decoder may report a failure after the next keyframe went in. */
11210
+ #fedAcrossGapBefore = false;
11211
+ #lastWithheld;
11212
+ #stats = {
11213
+ fedAcrossGap: 0,
11214
+ withheld: 0,
11215
+ selectiveFeedFailures: 0,
11216
+ statementViolations: 0
11217
+ };
11218
+ constructor(options) {
11219
+ this.#inert = options.tolerance !== "none";
11220
+ }
11221
+ /** True while the gate answers from the statements of the current GOP. */
11222
+ get reading() {
11223
+ return this.#mode === "reading";
11224
+ }
11225
+ get stats() {
11226
+ return { ...this.#stats };
11227
+ }
11228
+ /**
11229
+ * May this frame be fed? Records no frame as fed, so a sink may ask twice
11230
+ * about one frame. `unread` for a keyframe, a concealing decoder, a GOP
11231
+ * whose keyframe did not carry 254, and a track switched off. A late or
11232
+ * repeated frame is refused with `withhold` and not counted.
11233
+ */
11234
+ admit(frame) {
11235
+ if (frame.keyframe) return "unread";
11236
+ const needs = frame.needs;
11237
+ if (this.#mode === "reading") {
11238
+ if (needs === void 0 || needs.code > 128) {
11239
+ this.#stopReading();
11240
+ } else {
11241
+ const offset = this.#offset(needs);
11242
+ if (offset < 0) return "withhold";
11243
+ if (offset === 0) return this.#withhold(needs);
11244
+ const { distance } = decodeFrameNeeds(needs.code, false);
11245
+ if (distance > offset) {
11246
+ this.#stats.statementViolations++;
11247
+ this.#off = true;
11248
+ this.#stopReading();
11249
+ } else {
11250
+ const whole = this.#fedCount === offset - 1;
11251
+ const anchor = needs.position - distance >>> 0;
11252
+ const anchorFed = distance === 0 ? whole : distance === offset || this.#fedAt[anchor & 63] === anchor;
11253
+ if (!anchorFed) return this.#withhold(needs);
11254
+ this.#allowed = Math.max(this.#allowed, offset);
11255
+ return "feed";
11256
+ }
11257
+ }
11258
+ }
11259
+ return this.#mode === "hold" ? this.#withhold(needs) : "unread";
11260
+ }
11261
+ /** The sink handed this frame to its decoder or buffer. */
11262
+ fed(frame) {
11263
+ const needs = frame.needs;
11264
+ if (frame.keyframe) {
11265
+ this.#fedAcrossGapBefore = this.#fedAcrossGap;
11266
+ this.#fedAcrossGap = false;
11267
+ this.#clear();
11268
+ if (this.#inert || this.#off || needs === void 0 || !decodeFrameNeeds(needs.code, true).map) return;
11269
+ this.#mode = "reading";
11270
+ this.#keyMpu = needs.mpu;
11271
+ this.#keyPosition = needs.position >>> 0;
11272
+ return;
11273
+ }
11274
+ if (this.#mode !== "reading") return;
11275
+ if (needs === void 0 || needs.code > 128) {
11276
+ this.#stopReading();
11277
+ return;
11278
+ }
11279
+ const offset = this.#offset(needs);
11280
+ if (offset <= 0) return;
11281
+ if (this.#fedCount !== offset - 1) {
11282
+ this.#fedAcrossGap = true;
11283
+ this.#stats.fedAcrossGap++;
11284
+ }
11285
+ const position = needs.position >>> 0;
11286
+ this.#fedAt[position & 63] = position;
11287
+ this.#fedCount++;
11288
+ this.#top = offset;
11289
+ }
11290
+ /** The sink stalled, reset its decoder or emptied its queue: nothing is read before the next keyframe. */
11291
+ requireKeyframe() {
11292
+ this.#clear();
11293
+ }
11294
+ /**
11295
+ * The decoder raised an error or closed. Returns true when a frame had been
11296
+ * fed across a gap: the decoder could not take the selective feed, so no
11297
+ * statement is read on this track again. Either way the reading of this GOP
11298
+ * stops, and the rest of a GOP with a hole the gate answered for is withheld.
11299
+ */
11300
+ onDecoderFailure() {
11301
+ const selective = this.#fedAcrossGap || this.#fedAcrossGapBefore;
11302
+ this.#fedAcrossGap = false;
11303
+ this.#fedAcrossGapBefore = false;
11304
+ if (selective) {
11305
+ this.#stats.selectiveFeedFailures++;
11306
+ this.#off = true;
11307
+ }
11308
+ if (this.#mode === "reading") this.#stopReading();
11309
+ if (this.#mode !== "hold") this.#clear();
11310
+ return selective;
11311
+ }
11312
+ #clear() {
11313
+ this.#mode = "unread";
11314
+ this.#fedAt.fill(-1);
11315
+ this.#fedCount = 0;
11316
+ this.#top = 0;
11317
+ this.#allowed = 0;
11318
+ this.#withheldInGop = false;
11319
+ }
11320
+ /** The frame's place after the keyframe. 0: another MPU. -1: late or repeated, not after the last frame fed. */
11321
+ #offset(needs) {
11322
+ if (needs.mpu !== this.#keyMpu) return 0;
11323
+ const offset = needs.position - this.#keyPosition >>> 0;
11324
+ return offset > this.#top && offset < 2147483648 ? offset : -1;
11325
+ }
11326
+ /**
11327
+ * The sink's own hold never saw a hole the gate answered for: a frame it
11328
+ * withheld, or one it allowed that was not fed. The gate then holds the
11329
+ * rest of that GOP itself.
11330
+ */
11331
+ #stopReading() {
11332
+ this.#mode = this.#withheldInGop || this.#fedCount < this.#allowed ? "hold" : "unread";
11333
+ }
11334
+ #withhold(needs) {
11335
+ this.#withheldInGop = true;
11336
+ const last = this.#lastWithheld;
11337
+ if (needs === void 0 || last === void 0 || needs.mpu !== last.mpu || needs.position !== last.position) {
11338
+ this.#stats.withheld++;
11339
+ }
11340
+ this.#lastWithheld = needs;
11341
+ return "withhold";
11342
+ }
11343
+ };
11344
+
11089
11345
  // src/conceal-timeline.ts
11090
11346
  function videoConcealModeForCodec(codec) {
11091
- const lower = codec.toLowerCase();
11092
- if (lower.startsWith("avc1") || lower.startsWith("avc3")) return "feed-through";
11093
- return "hold-to-rap";
11347
+ return decoderTolerance(codec) === "conceals" ? "feed-through" : "hold-to-rap";
11094
11348
  }
11095
11349
  var U32_MAX = 0xffffffffn;
11096
11350
  var HoldLastTimeline = class {
11097
11351
  #concealMode;
11352
+ #gate;
11098
11353
  #held = null;
11099
11354
  #dropping = false;
11100
11355
  #compositionOffsets = false;
11356
+ /** A sample was withheld and the held frame has not yet been stretched over it. */
11357
+ #skipped = false;
11101
11358
  #stats = { droppedFrames: 0, extendedHolds: 0 };
11102
11359
  constructor(options) {
11103
11360
  this.#concealMode = options.concealMode;
11361
+ this.#gate = new VideoFeedGate({ tolerance: options.tolerance ?? "conceals" });
11104
11362
  }
11105
11363
  get stats() {
11106
11364
  return { ...this.#stats };
11107
11365
  }
11366
+ /** What the feed gate withheld and fed across a gap. */
11367
+ get gateStats() {
11368
+ return this.#gate.stats;
11369
+ }
11370
+ /**
11371
+ * The sink's decoder failed. True when a frame had been fed across a gap: the gate then
11372
+ * reads no statement on this track again. The rest of a GOP in which the gate withheld a
11373
+ * sample or fed one across a gap is not appended. Nothing else changes; to start over,
11374
+ * call {@link reset}.
11375
+ */
11376
+ onDecoderFailure() {
11377
+ return this.#gate.onDecoderFailure();
11378
+ }
11108
11379
  push(sample) {
11109
11380
  if (sample.dts !== sample.pts) this.#compositionOffsets = true;
11110
11381
  if (this.#dropping) {
@@ -11115,7 +11386,16 @@ var HoldLastTimeline = class {
11115
11386
  this.#dropping = false;
11116
11387
  return this.#accept(sample);
11117
11388
  }
11118
- if (this.#dropsUntilRap(sample)) {
11389
+ const gap = sample.gapBefore;
11390
+ const stalls = !sample.keyframe && gap?.trackKind === "video" && gap.action === "stall";
11391
+ const answer = stalls ? "unread" : this.#gate.admit(sample);
11392
+ const selective = answer !== "unread" && !this.#compositionOffsets;
11393
+ if (selective && answer === "withhold") {
11394
+ this.#skipped = true;
11395
+ return [];
11396
+ }
11397
+ const holed = this.#skipped && this.#compositionOffsets && !sample.keyframe;
11398
+ if (answer === "withhold" || holed || !selective && this.#dropsUntilRap(sample)) {
11119
11399
  this.#dropping = true;
11120
11400
  this.#stats.droppedFrames++;
11121
11401
  return this.#compositionOffsets ? this.#releaseHeld() : [];
@@ -11131,8 +11411,12 @@ var HoldLastTimeline = class {
11131
11411
  this.#held = null;
11132
11412
  this.#dropping = false;
11133
11413
  this.#compositionOffsets = false;
11414
+ this.#skipped = false;
11415
+ this.#gate.requireKeyframe();
11134
11416
  }
11135
11417
  #accept(sample) {
11418
+ this.#gate.fed(sample);
11419
+ this.#skipped = false;
11136
11420
  if (this.#compositionOffsets) {
11137
11421
  const out2 = this.#releaseHeld();
11138
11422
  out2.push(this.#emit(sample, sample.duration));
@@ -11485,7 +11769,7 @@ var CmafBlockAssembler = class {
11485
11769
  if (reference < 0) return timestamp;
11486
11770
  return timestamp + Math.round((reference - timestamp) / wrapPeriod) * wrapPeriod;
11487
11771
  }
11488
- #emitSample(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber2, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, synthetic, gapBefore) {
11772
+ #emitSample(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber2, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, synthetic, gapBefore, needs) {
11489
11773
  if (authoredTiming !== void 0 && !this.#config.admitAuthoredTiming) {
11490
11774
  this.#sampleOrderStats.unadmittedAuthoredSamples++;
11491
11775
  return;
@@ -11529,7 +11813,8 @@ var CmafBlockAssembler = class {
11529
11813
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
11530
11814
  ...deliveryProvenance === void 0 ? {} : { deliveryProvenance },
11531
11815
  ...synthetic === void 0 ? {} : { synthetic },
11532
- ...gapBefore === void 0 ? {} : { gapBefore }
11816
+ ...gapBefore === void 0 ? {} : { gapBefore },
11817
+ ...needs === void 0 ? {} : { needs }
11533
11818
  });
11534
11819
  if (sample === null) return;
11535
11820
  if (advancesHorizon && unwrappedTimestamp > this.#lastSourceTs) {
@@ -11755,7 +12040,8 @@ var CmafBlockAssembler = class {
11755
12040
  f.movieFragmentSequenceNumber,
11756
12041
  f.sampleNumber,
11757
12042
  f.synthetic,
11758
- f.gapBefore
12043
+ f.gapBefore,
12044
+ f.needs
11759
12045
  );
11760
12046
  }
11761
12047
  }
@@ -11792,7 +12078,7 @@ var CmafBlockAssembler = class {
11792
12078
  * is guarded by the per-frame `lastEmittedTs` check (also enforced in
11793
12079
  * `#emitPerSample`). The `sbn`/`esi` parameters are kept for the call-site
11794
12080
  * signature but no longer affect routing. */
11795
- addFrame(sbn, esi, data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber2, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, gapBefore) {
12081
+ addFrame(sbn, esi, data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber2, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, gapBefore, needs) {
11796
12082
  void sbn;
11797
12083
  void esi;
11798
12084
  this.#emitStats.addedFrames++;
@@ -11814,7 +12100,8 @@ var CmafBlockAssembler = class {
11814
12100
  movieFragmentSequenceNumber,
11815
12101
  sampleNumber,
11816
12102
  void 0,
11817
- gapBefore
12103
+ gapBefore,
12104
+ needs
11818
12105
  );
11819
12106
  this.#countEmit([{ keyframe }]);
11820
12107
  }
@@ -11855,7 +12142,7 @@ var CmafBlockAssembler = class {
11855
12142
  }
11856
12143
  }
11857
12144
  /** Emit a single frame immediately as a one-sample segment (for oversized packets bypassing FEC). */
11858
- addBypassFrame(data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber2, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, gapBefore) {
12145
+ addBypassFrame(data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber2, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, gapBefore, needs) {
11859
12146
  if (!this.#ordersSamples()) this.#drainRecoveredUpTo(timestamp);
11860
12147
  this.#emitSample(
11861
12148
  data,
@@ -11874,7 +12161,8 @@ var CmafBlockAssembler = class {
11874
12161
  movieFragmentSequenceNumber,
11875
12162
  sampleNumber,
11876
12163
  void 0,
11877
- gapBefore
12164
+ gapBefore,
12165
+ needs
11878
12166
  );
11879
12167
  }
11880
12168
  /** Build and emit init segment from catalog config. */
@@ -11986,7 +12274,8 @@ var CmafBlockAssembler = class {
11986
12274
  frame.movieFragmentSequenceNumber,
11987
12275
  frame.sampleNumber,
11988
12276
  frame.synthetic,
11989
- frame.gapBefore
12277
+ frame.gapBefore,
12278
+ frame.needs
11990
12279
  );
11991
12280
  this.#countEmit([frame]);
11992
12281
  }
@@ -12208,6 +12497,7 @@ function parseProtectedPacket(packetData, hdr, index, bump) {
12208
12497
  sampleNumber: extraction.mfuDuHeader?.sampleNumber,
12209
12498
  movieFragmentSequenceNumber: extraction.mfuDuHeader?.movieFragmentSequenceNumber,
12210
12499
  sampleOffset: extraction.mfuDuHeader?.offset,
12500
+ dependencyCounter: extraction.mfuDuHeader?.dependencyCounter,
12211
12501
  itemId: extraction.itemId ?? void 0
12212
12502
  },
12213
12503
  isKeyframe: isMfuKeyframeMetadata(hdr.rapFlag, extraction.mfuDuHeader?.priority),
@@ -13738,11 +14028,13 @@ function deriveBlockClassifierGeometry(input) {
13738
14028
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
13739
14029
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
13740
14030
  }
14031
+ const groupDuration = isPositiveFinite(input.groupDurationMs) ? { groupDurationMs: input.groupDurationMs } : {};
13741
14032
  const protect = (reason) => ({
13742
14033
  trackKind: "video",
13743
14034
  mode: "all-protected",
13744
14035
  reason,
13745
- ...keyframeInterval === void 0 ? {} : { keyframeInterval }
14036
+ ...keyframeInterval === void 0 ? {} : { keyframeInterval },
14037
+ ...groupDuration
13746
14038
  });
13747
14039
  if (!isPositiveFinite(input.framerate)) return protect("framerate-absent");
13748
14040
  const framerate = input.framerate;
@@ -13758,9 +14050,24 @@ function deriveBlockClassifierGeometry(input) {
13758
14050
  frameDurationMs,
13759
14051
  interleaveUnits,
13760
14052
  gopFrames,
13761
- keyframeInterval
14053
+ keyframeInterval,
14054
+ ...groupDuration
13762
14055
  };
13763
14056
  }
14057
+ function isPositiveSafeInteger(value) {
14058
+ return Number.isSafeInteger(value) && value > 0;
14059
+ }
14060
+ function mpuRuleCatalogReason(geometry2) {
14061
+ const interval = geometry2.keyframeInterval;
14062
+ if (interval === void 0 || !isPositiveSafeInteger(interval.ticks) || !isPositiveSafeInteger(interval.timescale)) {
14063
+ return "keyframe-interval-absent";
14064
+ }
14065
+ const groupMs = geometry2.groupDurationMs;
14066
+ if (!isPositiveFinite(groupMs)) return "group-duration-absent";
14067
+ const { ticks, timescale } = interval;
14068
+ const equal = Number.isSafeInteger(groupMs) ? BigInt(ticks) * 1000n === BigInt(groupMs) * BigInt(timescale) : Math.abs(ticks / timescale * 1e3 - groupMs) <= 2 * Number.EPSILON * groupMs;
14069
+ return equal ? null : "keyframe-interval-not-group-duration";
14070
+ }
13764
14071
  function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13765
14072
  if (geometry2.trackKind !== "video" || geometry2.keyframeInterval === void 0) return null;
13766
14073
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
@@ -13778,6 +14085,25 @@ function keyframeInstantBetween(start, interval, from, to) {
13778
14085
  function compareDataUnitStarts(a, b) {
13779
14086
  return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
13780
14087
  }
14088
+ function firstStartAtOrAfter(starts, sbn) {
14089
+ let lo = 0;
14090
+ let hi = starts.length;
14091
+ while (lo < hi) {
14092
+ const mid = lo + hi >>> 1;
14093
+ if (starts[mid].sbn < sbn) lo = mid + 1;
14094
+ else hi = mid;
14095
+ }
14096
+ return lo;
14097
+ }
14098
+ var ARRIVED_START_MAX = 4096;
14099
+ function nextSampleHeader(headers, at2) {
14100
+ const of = headers[at2];
14101
+ for (let i = at2 + 1; i < headers.length; i++) {
14102
+ const header = headers[i];
14103
+ if (header.movieFragment !== of.movieFragment || header.idx !== of.idx) return header;
14104
+ }
14105
+ return void 0;
14106
+ }
13781
14107
  var LATE_RAP_MAX_MPUS_BACK = 64;
13782
14108
  var UNPLACED = { rapNotMpuStart: false };
13783
14109
  var BlockClassifier = class {
@@ -13802,6 +14128,50 @@ var BlockClassifier = class {
13802
14128
  #mpuSbnSpans = /* @__PURE__ */ new Map();
13803
14129
  #dataUnitStarts = /* @__PURE__ */ new Map();
13804
14130
  #highestMpu = null;
14131
+ /**
14132
+ * The DU headers held, per MPU in authored order, for the MPU rule. Kept in
14133
+ * every mode (the rule needs no catalog cadence) for the same horizon and
14134
+ * the same continuous SBN sequence as the P1 ledger.
14135
+ */
14136
+ #headers = /* @__PURE__ */ new Map();
14137
+ /**
14138
+ * The source packets that arrived, per MPU. The MPU rule asks it whether
14139
+ * every packet between two held DU headers arrived, and where. Same
14140
+ * horizon as the headers.
14141
+ */
14142
+ #arrived = /* @__PURE__ */ new Map();
14143
+ #heldHighestMpu = null;
14144
+ /** Two DU headers of this sequence lay in blocks against their authored order: the MPU rule proves nothing. */
14145
+ #headerOrderRefuted = false;
14146
+ /**
14147
+ * A DU header held carried RAP_flag and was not of its MPU's first sample:
14148
+ * not the first sample of its movie fragment, or in another movie fragment
14149
+ * than the first DU header held of its MPU. This stream puts a RAP inside
14150
+ * an MPU, and neither rule proves anything for the rest of the epoch. It is
14151
+ * the MPU rule's own reading, in every DU-header layout and of rebuilt
14152
+ * headers too. The first case is read on a header of an MPU behind the two
14153
+ * kept as well. `mpuBoundsRaps`, which the stall or conceal decision reads,
14154
+ * is set as before and not from here.
14155
+ */
14156
+ #rapInsideMpu = false;
14157
+ /** What the catalog lacks for the MPU rule, or null when it states a keyframe interval equal to the group duration. */
14158
+ #mpuRuleCatalog = null;
14159
+ /**
14160
+ * The lowest and highest decode time known in an MPU, for the two MPUs of
14161
+ * the highest numbers: those of the samples that held movie fragment
14162
+ * metadata times (noteDecodeTimes). Valid within one MPU sequence, as the
14163
+ * P1 ledger is; if MPU numbers go back with no source discontinuity, the
14164
+ * new ones are not read until then, as their DU headers are not.
14165
+ */
14166
+ #decodeSpans = /* @__PURE__ */ new Map();
14167
+ /**
14168
+ * An MPU held a sample one keyframe interval or more after another by
14169
+ * decode time, so it lasts longer than the interval. A track of an earlier
14170
+ * revision whose interval equals its group duration can hold a further RAP
14171
+ * only in such an MPU: neither rule proves anything for the rest of the
14172
+ * epoch.
14173
+ */
14174
+ #mpuOutlastsInterval = false;
13805
14175
  /**
13806
14176
  * P3 layout, kept for the MPUs within the classification horizon and valid
13807
14177
  * within one continuous SBN sequence (`noteSourceDiscontinuity`).
@@ -13844,6 +14214,20 @@ var BlockClassifier = class {
13844
14214
  get mpuBoundsRaps() {
13845
14215
  return this.#mpuBoundsRaps;
13846
14216
  }
14217
+ /**
14218
+ * Why the MPU rule classes no block on this track now, or null while it
14219
+ * can. A catalog reason is known from the start of the epoch; the others
14220
+ * name what the stream showed. A block the rule would have classed reads
14221
+ * `unknown` under every one of them, and so does one the window rule would
14222
+ * have classed, under every one but `du-headers-out-of-order`.
14223
+ */
14224
+ get mpuRuleOff() {
14225
+ if (this.#mpuRuleCatalog !== null) return this.#mpuRuleCatalog;
14226
+ if (this.#rapInsideMpu) return "rap-inside-mpu";
14227
+ if (this.#mpuOutlastsInterval) return "mpu-longer-than-keyframe-interval";
14228
+ if (!this.#mpuBoundsRaps) return "mpu-bounds-raps-refuted";
14229
+ return this.#headerOrderRefuted ? "du-headers-out-of-order" : null;
14230
+ }
13847
14231
  /** Begin a fresh epoch (catalog change or track reset). */
13848
14232
  reset(geometry2 = this.#geometry) {
13849
14233
  this.#geometry = geometry2;
@@ -13852,6 +14236,9 @@ var BlockClassifier = class {
13852
14236
  this.#clearMpuLayout();
13853
14237
  this.#lastRap = null;
13854
14238
  this.#mpuBoundsRaps = true;
14239
+ this.#rapInsideMpu = false;
14240
+ this.#mpuOutlastsInterval = false;
14241
+ this.#mpuRuleCatalog = geometry2.trackKind === "video" ? mpuRuleCatalogReason(geometry2) : null;
13855
14242
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
13856
14243
  this.#mode = "all-protected";
13857
14244
  this.#reason = geometry2.reason;
@@ -13892,9 +14279,16 @@ var BlockClassifier = class {
13892
14279
  this.#clearMpuLayout();
13893
14280
  this.#lastRap = null;
13894
14281
  }
13895
- /** Register a block that exists without evidence (a vanished block). */
14282
+ /**
14283
+ * Register a block that exists without evidence of its own: a vanished
14284
+ * block, or one only repair symbols state. The DU headers already held
14285
+ * around it class it now (the MPU rule); no later header need come between
14286
+ * them to ask again.
14287
+ */
13896
14288
  touch(sbn) {
13897
- this.#blockFor(sbn);
14289
+ const changes = [];
14290
+ this.#reclassify(sbn, this.#blockFor(sbn), changes);
14291
+ return changes;
13898
14292
  }
13899
14293
  /** Forget a resolved block. */
13900
14294
  forget(sbn) {
@@ -13904,8 +14298,15 @@ var BlockClassifier = class {
13904
14298
  if (this.#geometry.trackKind === "audio") return "audio";
13905
14299
  return this.#blocks.get(sbn)?.cls ?? "unknown";
13906
14300
  }
13907
- /** Record one first-arrival source symbol's evidence for block `sbn`. */
13908
- observe(sbn, evidence) {
14301
+ /**
14302
+ * Record one first-arrival source symbol's evidence for block `sbn`.
14303
+ * `ssId` is its FEC source symbol id (the block's SS_Start plus its ESI,
14304
+ * ISO/IEC 23008-1 C.5.2). The publisher numbers the packets of the FEC
14305
+ * flow with it, one each, so the MPU rule reads from it whether every
14306
+ * packet between two DU headers arrived. Without it the rule's two
14307
+ * exceptions prove nothing.
14308
+ */
14309
+ observe(sbn, evidence, ssId) {
13909
14310
  if (this.#geometry.trackKind === "audio") return [];
13910
14311
  const changes = [];
13911
14312
  const block = this.#blockFor(sbn);
@@ -13917,22 +14318,137 @@ var BlockClassifier = class {
13917
14318
  block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
13918
14319
  block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
13919
14320
  }
13920
- if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
14321
+ if (placement.rapNotMpuStart) this.#refuteMpuBounds(changes);
13921
14322
  const violation = this.#checkInvariants(sbn, block, evidence, placement);
13922
14323
  if (violation !== null) changes.push(...this.#disable(violation));
13923
- const next = this.#classify(block);
13924
- if (next !== block.cls && this.#allowed(block.cls, next)) {
13925
- changes.push({
13926
- kind: "reclassified",
13927
- sbn,
13928
- from: block.cls,
13929
- to: next,
13930
- evidence: this.#evidenceFor(block, next)
13931
- });
13932
- block.cls = next;
14324
+ this.#noteArrived(sbn, evidence.mpu, ssId);
14325
+ const bounds = this.#noteHeader(sbn, evidence, position, ssId, changes);
14326
+ this.#reclassify(sbn, block, changes);
14327
+ if (bounds) this.#reclassifyOthers(sbn, changes);
14328
+ return changes;
14329
+ }
14330
+ /**
14331
+ * A first-arrival source symbol placed in a repair-less span (IsoBlockLocator:
14332
+ * the SS_IDs between two stated blocks whose every repair was lost). A span
14333
+ * is no block: it can hold several producer blocks, so nothing block-scoped
14334
+ * is read from it (no record, P1, P2 or MPU-rule bound) and its blocks stay
14335
+ * unknown. What its DU header says of its MPU (P3) still counts (BLO-57323).
14336
+ */
14337
+ observeInSpan(evidence) {
14338
+ if (this.#geometry.trackKind === "audio") return [];
14339
+ const changes = [];
14340
+ const placement = this.#place(evidence);
14341
+ if (placement.rapNotMpuStart) this.#refuteMpuBounds(changes);
14342
+ const geometry2 = this.#geometry;
14343
+ if (this.#mode === "all-protected" || geometry2.mode !== "classifying") return changes;
14344
+ if (placement.rapNotMpuStart) changes.push(...this.#disable("rap-not-mpu-start"));
14345
+ else if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
14346
+ changes.push(...this.#disable("mpu-longer-than-gop"));
14347
+ } else if (placement.violation !== void 0) changes.push(...this.#disable(placement.violation));
14348
+ return changes;
14349
+ }
14350
+ /**
14351
+ * The DU header of a source packet that a decode rebuilt, in block `sbn`.
14352
+ * It bounds the blocks around that block for the MPU rule as a header that
14353
+ * arrived does: the rule reads the DU headers the receiver holds. The
14354
+ * rebuilt block is whole, so it gets no class and no record, and the
14355
+ * packet is no evidence for P1 or P3, which rest on what arrived: it
14356
+ * supports no class by the window rule, and can only end it. It is not
14357
+ * counted as a packet that arrived either (#arrivedBetween).
14358
+ */
14359
+ observeRecovered(sbn, evidence) {
14360
+ if (this.#geometry.trackKind === "audio") return [];
14361
+ const { mpu, idx, movieFragment } = evidence;
14362
+ if (mpu === void 0 || idx === void 0 || movieFragment === void 0) return [];
14363
+ const changes = [];
14364
+ if (idx !== 0) {
14365
+ this.#multiSampleFragment = true;
14366
+ const geometry2 = this.#geometry;
14367
+ if (this.#fragmentPerFrame && geometry2.trackKind === "video" && geometry2.mode === "classifying") {
14368
+ changes.push(...this.#disable("mpu-multiple-fragments"));
14369
+ }
14370
+ }
14371
+ if (this.#noteHeader(sbn, evidence, this.#positionHeld(mpu, idx, movieFragment), void 0, changes)) {
14372
+ this.#reclassifyOthers(sbn, changes);
13933
14373
  }
13934
14374
  return changes;
13935
14375
  }
14376
+ /**
14377
+ * Decode times the receiver can determine: `first` and `last` are those of
14378
+ * the first and the last sample that one held movie fragment's metadata
14379
+ * (FT=1) times, of MPU `mpu`, in ticks of `mediaTimescale`; a `trun` lists
14380
+ * samples in decode order, so `first` is not after `last`. They are read
14381
+ * for one thing, and only on a track the MPU rule applies to: an MPU with
14382
+ * two samples a keyframe interval or more apart lasts longer than the
14383
+ * interval, so its first sample need not be its only RAP. The rule then
14384
+ * stops for the rest of the epoch, the window rule with it, and every delta
14385
+ * class goes (fec-multicast-01 Block Classification). No class comes from
14386
+ * a decode time. The MPU's first sample is never later than the earliest
14387
+ * one known, so the known span is no longer than the real one.
14388
+ */
14389
+ noteDecodeTimes(mpu, first, last, mediaTimescale) {
14390
+ const changes = [];
14391
+ const geometry2 = this.#geometry;
14392
+ if (geometry2.trackKind !== "video" || this.#mpuRuleCatalog !== null || !isPositiveSafeInteger(mediaTimescale)) {
14393
+ return changes;
14394
+ }
14395
+ const held = this.#decodeSpans.get(mpu);
14396
+ const known = held?.mediaTimescale === mediaTimescale ? held : void 0;
14397
+ let late = false;
14398
+ if (held === void 0 && this.#decodeSpans.size >= 2) {
14399
+ const lowest = Math.min(...this.#decodeSpans.keys());
14400
+ late = mpu < lowest;
14401
+ if (!late) this.#decodeSpans.delete(lowest);
14402
+ }
14403
+ const min = known !== void 0 && known.min < first ? known.min : first;
14404
+ const max = known !== void 0 && known.max > last ? known.max : last;
14405
+ if (!late) this.#decodeSpans.set(mpu, { min, max, mediaTimescale });
14406
+ const { ticks, timescale } = geometry2.keyframeInterval;
14407
+ if ((max - min) * BigInt(timescale) >= BigInt(ticks) * BigInt(mediaTimescale)) {
14408
+ this.#mpuOutlastsInterval = true;
14409
+ this.#withdraw(changes);
14410
+ }
14411
+ return changes;
14412
+ }
14413
+ /** Ask again for every block held but `own`: a new DU header can bound any of them. */
14414
+ #reclassifyOthers(own, changes) {
14415
+ for (const [sbn, block] of this.#blocks) {
14416
+ if (sbn !== own) this.#reclassify(sbn, block, changes);
14417
+ }
14418
+ }
14419
+ /**
14420
+ * Move delta blocks back to unknown: a premise their class stood on is
14421
+ * gone. After DU headers out of block order, what the window rule still
14422
+ * holds for is classed again as its blocks are seen.
14423
+ */
14424
+ #withdraw(changes) {
14425
+ for (const [sbn, block] of this.#blocks) {
14426
+ if (block.cls !== "delta") continue;
14427
+ block.cls = "unknown";
14428
+ changes.push({ kind: "reclassified", sbn, from: "delta", to: "unknown", evidence: "classifier-disabled" });
14429
+ }
14430
+ }
14431
+ /**
14432
+ * An MPU boundary stopped bounding this stream's RAPs: neither rule proves
14433
+ * anything from now on, and every delta class goes.
14434
+ */
14435
+ #refuteMpuBounds(changes) {
14436
+ if (!this.#mpuBoundsRaps) return;
14437
+ this.#mpuBoundsRaps = false;
14438
+ this.#withdraw(changes);
14439
+ }
14440
+ #reclassify(sbn, block, changes) {
14441
+ const next = this.#classify(block, sbn);
14442
+ if (next === block.cls || !this.#allowed(block.cls, next)) return;
14443
+ changes.push({
14444
+ kind: "reclassified",
14445
+ sbn,
14446
+ from: block.cls,
14447
+ to: next,
14448
+ evidence: this.#evidenceFor(block, next)
14449
+ });
14450
+ block.cls = next;
14451
+ }
13936
14452
  /**
13937
14453
  * Record a RAP frame released in order. Released MPU-start RAPs of MPUs m
13938
14454
  * and m+n must be exactly n keyframe intervals apart in the media
@@ -13960,7 +14476,9 @@ var BlockClassifier = class {
13960
14476
  if (presentationTime === previous.presentationTime) return [];
13961
14477
  const interval2 = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13962
14478
  if (interval2 === null || decodeTime === void 0 || previous.decodeTime === void 0 || (decodeTime - previous.decodeTime) % interval2 !== 0n) {
13963
- this.#mpuBoundsRaps = false;
14479
+ const changes = [];
14480
+ this.#refuteMpuBounds(changes);
14481
+ return changes;
13964
14482
  }
13965
14483
  return [];
13966
14484
  }
@@ -14065,6 +14583,18 @@ var BlockClassifier = class {
14065
14583
  ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
14066
14584
  };
14067
14585
  }
14586
+ /**
14587
+ * The MPU position #place gives a DU header, read from the layout the
14588
+ * arrived headers built and recording nothing: where a rebuilt header
14589
+ * stands for the catalog interval's check in the MPU rule.
14590
+ */
14591
+ #positionHeld(mpu, idx, fragment) {
14592
+ if (!this.#fragmentPerFrame || this.#multiSampleFragment) return idx;
14593
+ const anchor = this.#mpus.get(mpu)?.anchor;
14594
+ if (anchor === void 0) return void 0;
14595
+ const offset = fragment - anchor | 0;
14596
+ return offset === 0 || offset > 0 && this.#fragmentsProven ? offset : void 0;
14597
+ }
14068
14598
  /**
14069
14599
  * How many fragments MPU m's anchor `fragment` lies past the start that
14070
14600
  * the anchor received last predicts for MPU m: one frame per fragment and
@@ -14091,6 +14621,11 @@ var BlockClassifier = class {
14091
14621
  this.#mpuSbnSpans.clear();
14092
14622
  this.#dataUnitStarts.clear();
14093
14623
  this.#highestMpu = null;
14624
+ this.#headers.clear();
14625
+ this.#arrived.clear();
14626
+ this.#heldHighestMpu = null;
14627
+ this.#headerOrderRefuted = false;
14628
+ this.#decodeSpans.clear();
14094
14629
  }
14095
14630
  /**
14096
14631
  * P1 check for one source packet of MPU `mpu` in block `sbn`, then record
@@ -14181,18 +14716,218 @@ var BlockClassifier = class {
14181
14716
  }
14182
14717
  return changes;
14183
14718
  }
14184
- #classify(block) {
14719
+ #classify(block, sbn) {
14185
14720
  if (block.rapSeen || block.mpus.size >= 2) return "keyframe";
14186
- if (this.#mode === "all-protected") return "unknown";
14721
+ if (block.cls === "delta") return "delta";
14722
+ if (this.#windowHolds(block) || this.#mpuRuleHolds(block, sbn)) return "delta";
14723
+ return "unknown";
14724
+ }
14725
+ #windowHolds(block) {
14726
+ const off = this.mpuRuleOff;
14727
+ if (this.#mode === "all-protected" || off !== null && off !== "du-headers-out-of-order") return false;
14187
14728
  const geometry2 = this.#geometry;
14188
- if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
14189
- if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
14190
- const span = geometry2.interleaveUnits - 1;
14191
- if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
14192
- return "delta";
14729
+ if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return false;
14730
+ if (block.mpus.size !== 1 || block.positionMin === void 0 || block.positionMax === void 0) {
14731
+ return false;
14732
+ }
14733
+ const span = geometry2.interleaveUnits - 1;
14734
+ return block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1;
14735
+ }
14736
+ /**
14737
+ * Keep the header and arrival ledgers to the two newest MPUs. False for an
14738
+ * MPU behind them, which is not kept: no block still asked lies there, and
14739
+ * the ledgers stay bounded when MPU numbers go back with no source
14740
+ * discontinuity (a restart nothing signalled, or the 2^32 wrap). The rule
14741
+ * is then silent until the next one.
14742
+ */
14743
+ #noteHeldMpu(mpu) {
14744
+ const highest = this.#heldHighestMpu;
14745
+ if (highest !== null && mpu <= highest) return mpu + 1 >= highest;
14746
+ this.#heldHighestMpu = mpu;
14747
+ for (const held of [this.#headers, this.#arrived]) {
14748
+ for (const other of [...held.keys()]) {
14749
+ if (other + 1 < mpu) held.delete(other);
14193
14750
  }
14194
14751
  }
14195
- return "unknown";
14752
+ return true;
14753
+ }
14754
+ /** Record a source packet that arrived as source symbol `ssId`, for #arrivedBetween. */
14755
+ #noteArrived(sbn, mpu, ssId) {
14756
+ if (mpu === void 0 || ssId === void 0 || !this.#noteHeldMpu(mpu)) return;
14757
+ const arrived = this.#arrived.get(mpu);
14758
+ if (arrived === void 0) this.#arrived.set(mpu, { start: /* @__PURE__ */ new Map([[ssId, sbn]]), last: ssId });
14759
+ else {
14760
+ if (arrived.start.size < ARRIVED_START_MAX) arrived.start.set(ssId, sbn);
14761
+ if (ssId > arrived.last) arrived.last = ssId;
14762
+ }
14763
+ }
14764
+ /**
14765
+ * Record a held DU header for the MPU rule; `ssId` is its source symbol id
14766
+ * when it arrived, undefined for one that FEC rebuilt. True when it is new
14767
+ * and in order: the blocks held are then asked again. Blocks follow
14768
+ * authored order (P1), so the first header that lies against it withdraws
14769
+ * every class, and the rule proves nothing for the rest of the sequence.
14770
+ */
14771
+ #noteHeader(sbn, evidence, position, ssId, changes) {
14772
+ const { mpu, idx, movieFragment } = evidence;
14773
+ if (this.#geometry.trackKind !== "video" || mpu === void 0 || idx === void 0 || movieFragment === void 0) {
14774
+ return false;
14775
+ }
14776
+ if (!this.#noteHeldMpu(mpu)) {
14777
+ if (evidence.rap && idx !== 0 && !this.#rapInsideMpu) {
14778
+ this.#rapInsideMpu = true;
14779
+ this.#withdraw(changes);
14780
+ }
14781
+ return false;
14782
+ }
14783
+ const header = {
14784
+ movieFragment,
14785
+ idx,
14786
+ offset: evidence.offset ?? 0,
14787
+ sbn,
14788
+ rap: evidence.rap,
14789
+ ...ssId === void 0 ? {} : { ssId },
14790
+ ...position === void 0 ? {} : { position }
14791
+ };
14792
+ let headers = this.#headers.get(mpu);
14793
+ if (headers === void 0) {
14794
+ headers = [];
14795
+ this.#headers.set(mpu, headers);
14796
+ }
14797
+ let at2 = 0;
14798
+ let end = headers.length;
14799
+ while (at2 < end) {
14800
+ const mid = at2 + end >>> 1;
14801
+ if (compareDataUnitStarts(headers[mid], header) < 0) at2 = mid + 1;
14802
+ else end = mid;
14803
+ }
14804
+ if (at2 < headers.length && compareDataUnitStarts(headers[at2], header) === 0) return false;
14805
+ headers.splice(at2, 0, header);
14806
+ const first = headers[0];
14807
+ if (!this.#rapInsideMpu && (header.rap && header.idx !== 0 || (at2 === 0 ? headers : [header]).some((held) => held.rap && held.movieFragment !== first.movieFragment))) {
14808
+ this.#rapInsideMpu = true;
14809
+ this.#withdraw(changes);
14810
+ }
14811
+ const before = headers[at2 - 1]?.sbn;
14812
+ const after = headers[at2 + 1]?.sbn;
14813
+ if (before !== void 0 && before > sbn || after !== void 0 && after < sbn) {
14814
+ if (!this.#headerOrderRefuted) {
14815
+ this.#headerOrderRefuted = true;
14816
+ this.#withdraw(changes);
14817
+ }
14818
+ return false;
14819
+ }
14820
+ return true;
14821
+ }
14822
+ /**
14823
+ * The MPU rule. L is the DU header held last before the block and U the
14824
+ * one held first after it. Every packet carries its MPU number, and an MPU
14825
+ * holds one RAP: its first sample.
14826
+ *
14827
+ * - R1, L and U in one MPU: the block holds no part of a RAP, provided the
14828
+ * MPU's first sample ended before the block (#firstSampleEndedBefore).
14829
+ * - R2, U in the next MPU: the block may hold the start of that MPU,
14830
+ * unless that start arrived whole (#startArrivedWhole). The block is
14831
+ * then the tail of L's MPU, and R1's proviso decides.
14832
+ * - R3, more than one MPU apart: a whole MPU is gone, its RAP with it.
14833
+ * - R4, no U held yet (or no L): not known. The next DU header asks again.
14834
+ *
14835
+ * It rests on the publisher keeping one RAP to an MPU, which no packet
14836
+ * says. So it classes nothing unless the catalog states a keyframe interval
14837
+ * equal to the group duration, and nothing once the stream showed
14838
+ * otherwise: a RAP inside an MPU (mpuBoundsRaps, or a RAP-flagged DU header
14839
+ * held that is not of its MPU's first sample: #noteHeader), an MPU longer than the
14840
+ * keyframe interval by the decode times known (noteDecodeTimes), or DU
14841
+ * headers against the block order. `mpuRuleOff` names which. `dep_counter`
14842
+ * is not read.
14843
+ */
14844
+ #mpuRuleHolds(block, sbn) {
14845
+ if (this.mpuRuleOff !== null) return false;
14846
+ let lower;
14847
+ let upper;
14848
+ let lowerMpu = 0;
14849
+ let upperMpu = 0;
14850
+ let lowerAt = 0;
14851
+ let upperAt = 0;
14852
+ for (const [mpu, headers] of this.#headers) {
14853
+ const before = firstStartAtOrAfter(headers, sbn) - 1;
14854
+ const after = firstStartAtOrAfter(headers, sbn + 1);
14855
+ const below = headers[before];
14856
+ const above = headers[after];
14857
+ if (below !== void 0 && (lower === void 0 || below.sbn > lower.sbn || below.sbn === lower.sbn && mpu > lowerMpu)) {
14858
+ lower = below;
14859
+ lowerMpu = mpu;
14860
+ lowerAt = before;
14861
+ }
14862
+ if (above !== void 0 && (upper === void 0 || above.sbn < upper.sbn || above.sbn === upper.sbn && mpu < upperMpu)) {
14863
+ upper = above;
14864
+ upperMpu = mpu;
14865
+ upperAt = after;
14866
+ }
14867
+ }
14868
+ if (lower === void 0 || upper === void 0) return false;
14869
+ if (block.mpus.size === 1 && !block.mpus.has(lowerMpu)) return false;
14870
+ if (upperMpu === lowerMpu) {
14871
+ if (upper.rap) return false;
14872
+ const geometry2 = this.#geometry;
14873
+ if (geometry2.trackKind === "video" && geometry2.mode === "classifying" && lower.position !== void 0 && upper.position !== void 0 && Math.floor(upper.position / geometry2.gopFrames) > Math.floor(lower.position / geometry2.gopFrames)) {
14874
+ return false;
14875
+ }
14876
+ } else if (upperMpu !== lowerMpu + 1 || !this.#startArrivedWhole(upperMpu, upperAt)) {
14877
+ return false;
14878
+ }
14879
+ return this.#firstSampleEndedBefore(sbn, lowerMpu, lowerAt);
14880
+ }
14881
+ /**
14882
+ * R1's proviso for block `sbn`, where header `at` of MPU `mpu` is the one
14883
+ * held last before it: no part of the MPU's first sample lies in the
14884
+ * block. A sample start without RAP_flag is not the first sample. Any
14885
+ * other header may be of it (a later data unit of a sample need not repeat
14886
+ * the flag). That sample ended before the block only if every packet from
14887
+ * the header to the next sample's DU header arrived, in earlier blocks.
14888
+ */
14889
+ #firstSampleEndedBefore(sbn, mpu, at2) {
14890
+ const headers = this.#headers.get(mpu);
14891
+ const lower = headers[at2];
14892
+ if (lower.offset === 0 && !lower.rap) return true;
14893
+ const next = nextSampleHeader(headers, at2);
14894
+ return next !== void 0 && this.#arrivedBetween(mpu, lower, next, sbn);
14895
+ }
14896
+ /**
14897
+ * R2's exception: the start of MPU `mpu` arrived whole. Its header `at`,
14898
+ * the DU header held first after the block, is of the MPU's RAP. Every
14899
+ * packet before it arrived, back to the last packet of the MPU before: so
14900
+ * did the MPU and movie fragment metadata sent before the sample. And
14901
+ * every packet after it arrived, up to the next sample's DU header.
14902
+ */
14903
+ #startArrivedWhole(mpu, at2) {
14904
+ const headers = this.#headers.get(mpu);
14905
+ const first = headers[at2];
14906
+ const arrived = this.#arrived.get(mpu);
14907
+ const previous = this.#arrived.get(mpu - 1);
14908
+ if (!first.rap || first.ssId === void 0 || arrived === void 0 || previous === void 0) return false;
14909
+ let ssId = first.ssId - 1;
14910
+ while (arrived.start.has(ssId)) ssId--;
14911
+ if (ssId !== previous.last) return false;
14912
+ const next = nextSampleHeader(headers, at2);
14913
+ return next !== void 0 && this.#arrivedBetween(mpu, first, next);
14914
+ }
14915
+ /**
14916
+ * Whether every packet sent after DU header `from` and before DU header
14917
+ * `to`, both of MPU `mpu`, arrived as a packet of that MPU, each in a block
14918
+ * before `before` when one is given. The source symbol id counts every
14919
+ * packet of the FEC flow, so no id may be missing between the two. Ids are
14920
+ * read as plain numbers, as block starts are: past the 2^32 wrap of the id
14921
+ * nothing is proved.
14922
+ */
14923
+ #arrivedBetween(mpu, from, to, before) {
14924
+ const arrived = this.#arrived.get(mpu);
14925
+ if (arrived === void 0 || from.ssId === void 0 || to.ssId === void 0) return false;
14926
+ for (let ssId = from.ssId + 1; ssId !== to.ssId; ssId++) {
14927
+ const sbn = arrived.start.get(ssId);
14928
+ if (sbn === void 0 || before !== void 0 && sbn >= before) return false;
14929
+ }
14930
+ return true;
14196
14931
  }
14197
14932
  #allowed(from, to) {
14198
14933
  if (from === "keyframe") return false;
@@ -14201,7 +14936,7 @@ var BlockClassifier = class {
14201
14936
  return false;
14202
14937
  }
14203
14938
  #evidenceFor(block, to) {
14204
- if (to === "delta") return "window";
14939
+ if (to === "delta") return this.#windowHolds(block) ? "window" : "mpu-rule";
14205
14940
  return block.rapSeen ? "rap" : "mpu-span";
14206
14941
  }
14207
14942
  };
@@ -15412,6 +16147,33 @@ var FECManager = class _FECManager {
15412
16147
  }
15413
16148
  }
15414
16149
  }
16150
+ /**
16151
+ * The DU header of a source packet that a decode rebuilt in block `sbn`.
16152
+ * It can class the blocks around that block (the MPU rule reads the DU
16153
+ * headers the receiver holds); the rebuilt block itself is resolved.
16154
+ */
16155
+ noteRecoveredSource(sbn, packetId, catalogTrackName, evidence) {
16156
+ const trackConfig = this.#trackConfigs.get(packetId);
16157
+ if (trackConfig === void 0 || !_FECManager.#hasCatalogTiming(trackConfig)) return;
16158
+ this.#applyClassifierChanges(
16159
+ packetId,
16160
+ catalogTrackName,
16161
+ this.#classifierFor(packetId, catalogTrackName).observeRecovered(sbn, evidence)
16162
+ );
16163
+ }
16164
+ /**
16165
+ * Tell the classifier of a block no source symbol of which is held, so the
16166
+ * DU headers around it can class it (the MPU rule reads the headers held
16167
+ * before and after a block's missing symbols; here every one is missing).
16168
+ * A block the classifier has no record of is never classed.
16169
+ */
16170
+ #registerSourcelessBlock(sbn, packetId, catalogTrackName) {
16171
+ this.#applyClassifierChanges(
16172
+ packetId,
16173
+ catalogTrackName,
16174
+ this.#classifierFor(packetId, catalogTrackName).touch(sbn)
16175
+ );
16176
+ }
15415
16177
  /**
15416
16178
  * Freeze a block's class at resolution and drop its classifier state. The
15417
16179
  * frozen class answers every later query (a recovery counted after the
@@ -15579,7 +16341,7 @@ var FECManager = class _FECManager {
15579
16341
  if (this.#blockResolutionFor(key) !== "untracked") return;
15580
16342
  this.#materializedBlocks.add(key);
15581
16343
  if (this.#hasCatalogTimingForPacket(packetId)) {
15582
- this.#classifierFor(packetId, catalogTrackName).touch(sbn);
16344
+ this.#registerSourcelessBlock(sbn, packetId, catalogTrackName);
15583
16345
  }
15584
16346
  this.onBlockVanished?.(sbn, packetId, catalogTrackName);
15585
16347
  if (repairable) {
@@ -17174,6 +17936,16 @@ var FECManager = class _FECManager {
17174
17936
  const classifier = this.#classifierFor(packetId, catalogTrackName);
17175
17937
  return { mode: classifier.mode, reason: classifier.reason };
17176
17938
  }
17939
+ /**
17940
+ * Why the MPU rule classes no block on a video stream now
17941
+ * (`BlockClassifier.mpuRuleOff`): what its catalog does not state, or what
17942
+ * the stream showed. Null while the rule can class a block. Undefined for a
17943
+ * stream with no classifier: one not heard yet, or without catalog timing.
17944
+ */
17945
+ mpuRuleOffFor(packetId, catalogTrackName) {
17946
+ const classifier = this.#classifiers.get(this.#streamKey(packetId, catalogTrackName));
17947
+ return classifier?.geometry.trackKind === "video" ? classifier.mpuRuleOff : void 0;
17948
+ }
17177
17949
  /**
17178
17950
  * Whether an MPU boundary still bounds this stream's RAPs (see
17179
17951
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
@@ -17251,6 +18023,20 @@ var FECManager = class _FECManager {
17251
18023
  )
17252
18024
  );
17253
18025
  }
18026
+ /**
18027
+ * Decode times of the first and last sample that one held movie fragment's
18028
+ * metadata times, in MPU `mpu`. On a video stream the classifier looks
18029
+ * among them for an MPU longer than the catalog keyframe interval, where
18030
+ * the MPU rule stops (`BlockClassifier.noteDecodeTimes`).
18031
+ */
18032
+ noteSampleDecodeTimes(packetId, catalogTrackName, mpu, first, last, mediaTimescale) {
18033
+ if (!this.#hasCatalogTimingForPacket(packetId)) return;
18034
+ this.#applyClassifierChanges(
18035
+ packetId,
18036
+ catalogTrackName,
18037
+ this.#classifierFor(packetId, catalogTrackName).noteDecodeTimes(mpu, first, last, mediaTimescale)
18038
+ );
18039
+ }
17254
18040
  // -----------------------------------------------------------------------
17255
18041
  // Configuration
17256
18042
  // -----------------------------------------------------------------------
@@ -17922,6 +18708,9 @@ var FECManager = class _FECManager {
17922
18708
  if (!repairIds) {
17923
18709
  repairIds = /* @__PURE__ */ new Set();
17924
18710
  this.#blockRepairRsIds.set(blockKey, repairIds);
18711
+ if (!this.#blockSourceCounts.has(blockKey) && this.#hasCatalogTimingForPacket(packetId)) {
18712
+ this.#registerSourcelessBlock(sbn, packetId, catalogTrackName);
18713
+ }
17925
18714
  }
17926
18715
  repairIds.add(rsId);
17927
18716
  if (this.#repairRequestedBlocks.has(blockKey)) {
@@ -18151,12 +18940,13 @@ var FECManager = class _FECManager {
18151
18940
  * classification evidence, and marks the block clean when all of its
18152
18941
  * authored source symbols arrived: the SSB_length a repair symbol declared,
18153
18942
  * otherwise K. `held` marks a source held unplaced since it arrived and
18154
- * placed only now (see #noteSbnSeen).
18943
+ * placed only now (see #noteSbnSeen); `inSpan` one placed in a repair-less
18944
+ * span, which the classifier reads as no block (BLO-57323).
18155
18945
  *
18156
18946
  * Throws for a packetId that was never configured, so a classified block
18157
18947
  * never reads the manager-global K or timeout.
18158
18948
  */
18159
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
18949
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false, inSpan = false) {
18160
18950
  const trackConfig = this.#trackConfigs.get(packetId);
18161
18951
  if (trackConfig === void 0) {
18162
18952
  throw new Error(
@@ -18166,15 +18956,8 @@ var FECManager = class _FECManager {
18166
18956
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
18167
18957
  const k = trackConfig.k;
18168
18958
  if (this.#completedBlocks.has(key)) return;
18169
- this.#noteSbnSeen(
18170
- sbn,
18171
- packetId,
18172
- catalogTrackName,
18173
- "source",
18174
- evidence.packetSequenceNumber,
18175
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
18176
- held
18177
- );
18959
+ const ssId = Number.isInteger(esi) ? sbn + esi >>> 0 : void 0;
18960
+ this.#noteSbnSeen(sbn, packetId, catalogTrackName, "source", evidence.packetSequenceNumber, ssId, held);
18178
18961
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
18179
18962
  if (Number.isInteger(esi) && esi >= authoredLength) {
18180
18963
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -18184,7 +18967,7 @@ var FECManager = class _FECManager {
18184
18967
  this.#applyClassifierChanges(
18185
18968
  packetId,
18186
18969
  catalogTrackName,
18187
- this.#classifierFor(packetId, catalogTrackName).observe(sbn, evidence)
18970
+ inSpan ? this.#classifierFor(packetId, catalogTrackName).observeInSpan(evidence) : this.#classifierFor(packetId, catalogTrackName).observe(sbn, evidence, ssId)
18188
18971
  );
18189
18972
  }
18190
18973
  const count = (this.#blockSourceCounts.get(key) ?? 0) + 1;
@@ -19033,6 +19816,7 @@ var IsoBmffTimingResolver = class {
19033
19816
  #pendingSamples = 0;
19034
19817
  #evictedSamples = 0;
19035
19818
  #lastMovieFragmentRejection = null;
19819
+ #lastMovieFragmentDecodeSpan = null;
19036
19820
  /** True once an FT=0 has bound the track that FT=1 timing is read against. */
19037
19821
  get initialized() {
19038
19822
  return this.#track !== null;
@@ -19053,6 +19837,15 @@ var IsoBmffTimingResolver = class {
19053
19837
  get lastMovieFragmentRejection() {
19054
19838
  return this.#lastMovieFragmentRejection;
19055
19839
  }
19840
+ /**
19841
+ * Decode times of the first and the last sample of the movie fragment that
19842
+ * the most recent `addMovieFragment` parsed, or null when it parsed none. A
19843
+ * `trun` lists samples in decode order, so these bound the fragment. It is
19844
+ * set whether or not the fragment was then admitted: the caller knows that.
19845
+ */
19846
+ get lastMovieFragmentDecodeSpan() {
19847
+ return this.#lastMovieFragmentDecodeSpan;
19848
+ }
19056
19849
  addInitialization(data) {
19057
19850
  const timing = parseIsoBmffInitializationTiming(data);
19058
19851
  if (!timing) return false;
@@ -19069,6 +19862,7 @@ var IsoBmffTimingResolver = class {
19069
19862
  */
19070
19863
  addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
19071
19864
  this.#lastMovieFragmentRejection = null;
19865
+ this.#lastMovieFragmentDecodeSpan = null;
19072
19866
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
19073
19867
  this.#lastMovieFragmentRejection = "invalid";
19074
19868
  return false;
@@ -19086,6 +19880,15 @@ var IsoBmffTimingResolver = class {
19086
19880
  this.#lastMovieFragmentRejection = "invalid";
19087
19881
  return false;
19088
19882
  }
19883
+ const firstSample = parsed.samples[0];
19884
+ const lastSample = parsed.samples[parsed.samples.length - 1];
19885
+ if (firstSample && lastSample) {
19886
+ this.#lastMovieFragmentDecodeSpan = {
19887
+ first: firstSample.decodeTime,
19888
+ last: lastSample.decodeTime,
19889
+ timescale: firstSample.timescale
19890
+ };
19891
+ }
19089
19892
  const key = fragmentKey(mpuSequenceNumber2, parsed.movieFragmentSequenceNumber);
19090
19893
  const existing = this.#fragments.get(key);
19091
19894
  if (existing) {
@@ -19121,6 +19924,14 @@ var IsoBmffTimingResolver = class {
19121
19924
  );
19122
19925
  return samples?.[sampleNumber - 1] ?? null;
19123
19926
  }
19927
+ /**
19928
+ * True when FT=1 declared exactly one sample for this movie fragment,
19929
+ * pending or delivered. False once the fragment is forgotten.
19930
+ */
19931
+ movieFragmentHoldsOneSample(mpuSequenceNumber2, movieFragmentSequenceNumber) {
19932
+ const key = fragmentKey(mpuSequenceNumber2, movieFragmentSequenceNumber);
19933
+ return (this.#fragments.get(key)?.length ?? this.#delivered.get(key)?.sampleCount) === 1;
19934
+ }
19124
19935
  consumeSample(mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber, expected) {
19125
19936
  const samples = this.#fragments.get(
19126
19937
  fragmentKey(mpuSequenceNumber2, movieFragmentSequenceNumber)
@@ -19798,6 +20609,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19798
20609
  this.#reassemblyPolicy = null;
19799
20610
  this.#frameCb = null;
19800
20611
  this.#initCb = null;
20612
+ this.#movieFragmentTimingCb = null;
19801
20613
  this.#sourceSymbolCb = null;
19802
20614
  this.#trackFrameCbs = /* @__PURE__ */ new Map();
19803
20615
  this.#reorderStats = {
@@ -19907,6 +20719,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19907
20719
  #reassemblyPolicy;
19908
20720
  #frameCb;
19909
20721
  #initCb;
20722
+ #movieFragmentTimingCb;
19910
20723
  #sourceSymbolCb;
19911
20724
  #trackFrameCbs;
19912
20725
  #reorderStats;
@@ -20116,6 +20929,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
20116
20929
  identity.sampleNumber = extraction.mfuDuHeader.sampleNumber;
20117
20930
  identity.movieFragmentSequenceNumber = extraction.mfuDuHeader.movieFragmentSequenceNumber;
20118
20931
  identity.offset = extraction.mfuDuHeader.offset;
20932
+ identity.dependencyCounter = extraction.mfuDuHeader.dependencyCounter;
20119
20933
  }
20120
20934
  return identity;
20121
20935
  } catch {
@@ -20346,6 +21160,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
20346
21160
  }
20347
21161
  return this.#drop("fragment-timing-refused");
20348
21162
  }
21163
+ const span = resolver2.lastMovieFragmentDecodeSpan;
21164
+ if (span) {
21165
+ this.#movieFragmentTimingCb?.(
21166
+ info.packetId,
21167
+ options?.catalogTrackName,
21168
+ mpu.mpuSequenceNumber,
21169
+ span.first,
21170
+ span.last,
21171
+ span.timescale
21172
+ );
21173
+ }
20349
21174
  this.#replayAwaitingTiming(streamKey, resolver2);
20350
21175
  return {
20351
21176
  kind: "fragment",
@@ -20561,6 +21386,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
20561
21386
  onInit(cb) {
20562
21387
  this.#initCb = cb;
20563
21388
  }
21389
+ /**
21390
+ * Register a callback for the decode times of each movie fragment (FT=1)
21391
+ * the parser admits, arrived or FEC-recovered: what the receiver can
21392
+ * determine of its samples' decode times, whether or not they arrive.
21393
+ */
21394
+ onMovieFragmentTiming(cb) {
21395
+ this.#movieFragmentTimingCb = cb;
21396
+ }
20564
21397
  onFrame(cb) {
20565
21398
  this.#frameCb = cb;
20566
21399
  }
@@ -20709,6 +21542,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
20709
21542
  hasAuthoredTimingFor(packetId, mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
20710
21543
  return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber) != null;
20711
21544
  }
21545
+ /** Whether FT=1 declared exactly one sample for this movie fragment. False when that is not known. */
21546
+ movieFragmentHoldsOneSample(packetId, mpuSequenceNumber2, movieFragmentSequenceNumber, catalogTrackName) {
21547
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.movieFragmentHoldsOneSample(mpuSequenceNumber2, movieFragmentSequenceNumber) === true;
21548
+ }
20712
21549
  /**
20713
21550
  * Claim and return the authored timing for a recovered sample. Recovery does
20714
21551
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -20779,6 +21616,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
20779
21616
  this.#reassembler.reset();
20780
21617
  this.#frameCb = null;
20781
21618
  this.#initCb = null;
21619
+ this.#movieFragmentTimingCb = null;
20782
21620
  this.#trackFrameCbs.clear();
20783
21621
  }
20784
21622
  // ── Private ─────────────────────────────────────────────────────
@@ -20943,7 +21781,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
20943
21781
  const isHevc = c.startsWith("hev1") || c.startsWith("hvc1");
20944
21782
  if (isHevc) {
20945
21783
  if (data.length < 5) return void 0;
20946
- if (startsWithAnnexB(data)) {
21784
+ if (startsWithAnnexB(data) && !isCompleteAvccSample(data)) {
20947
21785
  return _MmtpContainerParser.#scanAnnexBForKeyframe(data, true);
20948
21786
  }
20949
21787
  return _MmtpContainerParser.#scanLengthPrefixedHevcForKeyframe(data);
@@ -24149,7 +24987,22 @@ function sourceSymbolEvidence(packet, header, rapFlag, packetSequenceNumber) {
24149
24987
  ...identity === null ? {} : { mpu: identity.mpuSequenceNumber },
24150
24988
  ...identity?.sampleNumber !== void 0 && identity.sampleNumber >= 1 ? { idx: identity.sampleNumber - 1 } : {},
24151
24989
  ...identity?.movieFragmentSequenceNumber !== void 0 ? { movieFragment: identity.movieFragmentSequenceNumber } : {},
24152
- ...identity?.offset !== void 0 ? { offset: identity.offset } : {}
24990
+ ...identity?.offset !== void 0 ? { offset: identity.offset } : {},
24991
+ ...identity?.dependencyCounter ? { depCounter: identity.dependencyCounter } : {}
24992
+ };
24993
+ }
24994
+ function recoveredHeaderEvidence(sym) {
24995
+ const { fragment } = sym;
24996
+ if (sym.fragmentType !== 2 || fragment.sampleNumber === void 0 || fragment.sampleNumber < 1 || fragment.movieFragmentSequenceNumber === void 0) {
24997
+ return null;
24998
+ }
24999
+ return {
25000
+ rap: fragment.rapFlag,
25001
+ mpu: fragment.mpuSequenceNumber,
25002
+ idx: fragment.sampleNumber - 1,
25003
+ movieFragment: fragment.movieFragmentSequenceNumber,
25004
+ ...fragment.sampleOffset === void 0 ? {} : { offset: fragment.sampleOffset },
25005
+ ...fragment.dependencyCounter ? { depCounter: fragment.dependencyCounter } : {}
24153
25006
  };
24154
25007
  }
24155
25008
  var MmtpRouter = class {
@@ -24386,9 +25239,23 @@ var MmtpRouter = class {
24386
25239
  this.#diagFor(packetId, catalogTrackName).initSegments++;
24387
25240
  this.#deliverInit(packetId, data, catalogTrackName);
24388
25241
  });
25242
+ this.#parser.onMovieFragmentTiming((packetId, catalogTrackName, mpu, first, last, mediaTimescale) => {
25243
+ this.#fecManager?.noteSampleDecodeTimes?.(packetId, catalogTrackName, mpu, first, last, mediaTimescale);
25244
+ });
24389
25245
  this.#parser.onFrame((data, meta) => this.#routeParsedFrame(data, meta));
24390
25246
  this.#wireFecLifecycle(config?.onBlockFailed);
24391
25247
  }
25248
+ /**
25249
+ * The `needs` field of a video frame whose DU header places it, or nothing.
25250
+ * Fragment numbers count frames in decode order only where each movie
25251
+ * fragment holds one sample, so a frame gets one only when FT=1 said so.
25252
+ */
25253
+ #frameNeeds(isVideo, packetId, catalogTrackName, frame) {
25254
+ const { mpuSequenceNumber: mpu, movieFragmentSequenceNumber: position, priority: code } = frame;
25255
+ if (!isVideo || mpu === void 0 || position === void 0 || code === void 0) return {};
25256
+ if (!this.#parser.movieFragmentHoldsOneSample(packetId, mpu, position, catalogTrackName)) return {};
25257
+ return { needs: { mpu, position, code } };
25258
+ }
24392
25259
  /**
24393
25260
  * Deliver one parser frame: MSE assembly, sync gating, and callback
24394
25261
  * routing. Reads #currentFecInfo, the FEC coordinates of the packet the
@@ -24412,7 +25279,8 @@ var MmtpRouter = class {
24412
25279
  ...meta.mpuSequenceNumber === void 0 ? {} : { mpuSequenceNumber: meta.mpuSequenceNumber },
24413
25280
  ...meta.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: meta.movieFragmentSequenceNumber },
24414
25281
  ...meta.sampleNumber === void 0 ? {} : { sampleNumber: meta.sampleNumber },
24415
- ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
25282
+ ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName },
25283
+ ...this.#frameNeeds(isVideo, packetId, meta.catalogTrackName, meta)
24416
25284
  };
24417
25285
  if (meta.source) frameMeta.source = meta.source;
24418
25286
  if (isVideo && frameMeta.keyframe) {
@@ -24446,7 +25314,8 @@ var MmtpRouter = class {
24446
25314
  ...frameMeta.sampleNumber === void 0 ? {} : { sampleNumber: frameMeta.sampleNumber },
24447
25315
  ...frameMeta.catalogTrackName === void 0 ? {} : { catalogTrackName: frameMeta.catalogTrackName },
24448
25316
  ...frameMeta.deliveryProvenance === void 0 ? {} : { deliveryProvenance: frameMeta.deliveryProvenance },
24449
- ...frameMeta.gapBefore === void 0 ? {} : { gapBefore: frameMeta.gapBefore }
25317
+ ...frameMeta.gapBefore === void 0 ? {} : { gapBefore: frameMeta.gapBefore },
25318
+ ...frameMeta.needs === void 0 ? {} : { needs: frameMeta.needs }
24450
25319
  }]);
24451
25320
  } else if (assembler) {
24452
25321
  const fecInfo = this.#currentFecInfo;
@@ -24467,7 +25336,8 @@ var MmtpRouter = class {
24467
25336
  frameMeta.mmtpTimestamp,
24468
25337
  frameMeta.movieFragmentSequenceNumber,
24469
25338
  frameMeta.sampleNumber,
24470
- frameMeta.gapBefore
25339
+ frameMeta.gapBefore,
25340
+ frameMeta.needs
24471
25341
  );
24472
25342
  } else {
24473
25343
  assembler.addBypassFrame(
@@ -24484,7 +25354,8 @@ var MmtpRouter = class {
24484
25354
  frameMeta.mmtpTimestamp,
24485
25355
  frameMeta.movieFragmentSequenceNumber,
24486
25356
  frameMeta.sampleNumber,
24487
- frameMeta.gapBefore
25357
+ frameMeta.gapBefore,
25358
+ frameMeta.needs
24488
25359
  );
24489
25360
  }
24490
25361
  }
@@ -25929,7 +26800,7 @@ var MmtpRouter = class {
25929
26800
  const blockStart = placement.block.start;
25930
26801
  this.#openAssistBlock(ownerPacketId, catalogTrackName, blockStart, repair.ssbLength);
25931
26802
  if (placement.span !== void 0) {
25932
- this.#replayIsoSources(ownerPacketId, catalogTrackName, placement.span.block.start, placement.span.placed);
26803
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, placement.span.block.start, placement.span.placed, true);
25933
26804
  }
25934
26805
  this.#replayIsoSources(ownerPacketId, catalogTrackName, blockStart, placement.placed);
25935
26806
  if (this.#classifyPacketId(ownerPacketId) === null) return;
@@ -25972,7 +26843,7 @@ var MmtpRouter = class {
25972
26843
  closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
25973
26844
  const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
25974
26845
  for (const span of spans) {
25975
- this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
26846
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed, true);
25976
26847
  }
25977
26848
  }
25978
26849
  /**
@@ -25981,7 +26852,7 @@ var MmtpRouter = class {
25981
26852
  * accounting, block tracking with its own classification evidence, then the
25982
26853
  * decoder. Their media was routed when they arrived.
25983
26854
  */
25984
- #replayIsoSources(ownerPacketId, catalogTrackName, blockStart, placed) {
26855
+ #replayIsoSources(ownerPacketId, catalogTrackName, blockStart, placed, inSpan = false) {
25985
26856
  const fec = this.#fecManager;
25986
26857
  if (!fec) return;
25987
26858
  for (const { ssId, esi, payload } of placed) {
@@ -25995,7 +26866,7 @@ var MmtpRouter = class {
25995
26866
  catalogTrackName
25996
26867
  )) continue;
25997
26868
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
25998
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
26869
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true, inSpan);
25999
26870
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
26000
26871
  }
26001
26872
  if (payload.oversized) continue;
@@ -27662,6 +28533,14 @@ var MmtpRouter = class {
27662
28533
  }
27663
28534
  );
27664
28535
  }
28536
+ if (!overlay && this.#fecManager?.noteRecoveredSource) {
28537
+ for (const sym of result.symbols) {
28538
+ const evidence = recoveredHeaderEvidence(sym);
28539
+ if (evidence !== null) {
28540
+ this.#fecManager.noteRecoveredSource(blockId, ownerPacketId, catalogTrackName, evidence);
28541
+ }
28542
+ }
28543
+ }
27665
28544
  const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
27666
28545
  ownerPacketId,
27667
28546
  sym.fragment.mpuSequenceNumber,
@@ -27733,6 +28612,7 @@ var MmtpRouter = class {
27733
28612
  ...sym.fragment.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber },
27734
28613
  ...sym.fragment.sampleNumber === void 0 ? {} : { sampleNumber: sym.fragment.sampleNumber },
27735
28614
  rapFlag: sym.fragment.rapFlag,
28615
+ ...sym.fragment.priority === void 0 ? {} : { priority: sym.fragment.priority },
27736
28616
  recovered: true,
27737
28617
  deliveryProvenance,
27738
28618
  ...fecSbnOf(sym.index),
@@ -27777,7 +28657,8 @@ var MmtpRouter = class {
27777
28657
  // never touches the reassembler, so it must carry the block-level
27778
28658
  // verdict directly or the sample reaches MSE unattributed.
27779
28659
  deliveryProvenance,
27780
- ...sourceDiscontinuity ? { sourceDiscontinuity: true } : {}
28660
+ ...sourceDiscontinuity ? { sourceDiscontinuity: true } : {},
28661
+ ...this.#frameNeeds(isVideoTrack, ownerPacketId, catalogTrackName, sym.fragment)
27781
28662
  });
27782
28663
  this.#noteEmittedKeyframe(ownerPacketId, keyframe);
27783
28664
  } else {
@@ -27845,6 +28726,7 @@ var MmtpRouter = class {
27845
28726
  ...assembled.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber },
27846
28727
  ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
27847
28728
  rapFlag: assembled.rapFlag,
28729
+ ...assembled.priority === void 0 ? {} : { priority: assembled.priority },
27848
28730
  recovered: true,
27849
28731
  ...assembled.deliveryProvenance === void 0 ? {} : { deliveryProvenance: assembled.deliveryProvenance },
27850
28732
  ...fecSbnOf(sym.index),
@@ -27892,7 +28774,8 @@ var MmtpRouter = class {
27892
28774
  ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
27893
28775
  ...assembled.catalogTrackName === void 0 ? {} : { catalogTrackName: assembled.catalogTrackName },
27894
28776
  deliveryProvenance: assembled.deliveryProvenance,
27895
- ...sourceDiscontinuity ? { sourceDiscontinuity: true } : {}
28777
+ ...sourceDiscontinuity ? { sourceDiscontinuity: true } : {},
28778
+ ...this.#frameNeeds(isVideoTrack, ownerPacketId, recoveredCatalogTrackName, assembled)
27896
28779
  });
27897
28780
  this.#noteEmittedKeyframe(ownerPacketId, keyframe);
27898
28781
  }
@@ -27917,7 +28800,8 @@ var MmtpRouter = class {
27917
28800
  ...frame.catalogTrackName === void 0 ? {} : { catalogTrackName: frame.catalogTrackName },
27918
28801
  recovered: true,
27919
28802
  deliveryProvenance: frame.deliveryProvenance,
27920
- ...frame.sourceDiscontinuity ? { sourceDiscontinuity: true } : {}
28803
+ ...frame.sourceDiscontinuity ? { sourceDiscontinuity: true } : {},
28804
+ ...frame.needs === void 0 ? {} : { needs: frame.needs }
27921
28805
  });
27922
28806
  }
27923
28807
  debugRouter(
@@ -27982,6 +28866,7 @@ var MmtpRouter = class {
27982
28866
  ...sym.fragment.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber },
27983
28867
  ...sym.fragment.sampleNumber === void 0 ? {} : { sampleNumber: sym.fragment.sampleNumber },
27984
28868
  rapFlag: sym.fragment.rapFlag,
28869
+ ...sym.fragment.priority === void 0 ? {} : { priority: sym.fragment.priority },
27985
28870
  recovered: true,
27986
28871
  deliveryProvenance,
27987
28872
  ...fecSbnOf(sym.index),
@@ -28061,6 +28946,7 @@ var MmtpRouter = class {
28061
28946
  ...assembled.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber },
28062
28947
  ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
28063
28948
  rapFlag: assembled.rapFlag,
28949
+ ...assembled.priority === void 0 ? {} : { priority: assembled.priority },
28064
28950
  recovered: true,
28065
28951
  deliveryProvenance,
28066
28952
  ...fecSbnOf(sym.index),
@@ -28404,15 +29290,26 @@ function providerErrorOf(error) {
28404
29290
  let name;
28405
29291
  let message;
28406
29292
  let code;
29293
+ let failure;
29294
+ let causeName;
28407
29295
  try {
28408
29296
  name = fields2.name;
28409
29297
  message = fields2.message;
28410
29298
  code = fields2.code;
29299
+ failure = fields2.failure;
29300
+ const cause = fields2.cause;
29301
+ causeName = typeof cause === "object" && cause !== null ? cause.name : void 0;
28411
29302
  } catch {
28412
29303
  return void 0;
28413
29304
  }
28414
29305
  if (typeof name !== "string" || typeof message !== "string") return void 0;
28415
- return Object.freeze(typeof code === "string" ? { name, message, code } : { name, message });
29306
+ return Object.freeze({
29307
+ name,
29308
+ message,
29309
+ ...typeof code === "string" ? { code } : {},
29310
+ ...typeof failure === "string" ? { failure } : {},
29311
+ ...typeof causeName === "string" ? { causeName } : {}
29312
+ });
28416
29313
  }
28417
29314
  var MAX_TRACKED_DROPPED_PIDS = 16;
28418
29315
  function hasMulticastGateway() {
@@ -29234,25 +30131,6 @@ function catalogAmtNetworkSource(networkSource) {
29234
30131
  }
29235
30132
  return void 0;
29236
30133
  }
29237
- function intIn2(value, min, max) {
29238
- return Number.isInteger(value) && value >= min && value <= max;
29239
- }
29240
- function catalogAtsc3NetworkSource(networkSource) {
29241
- const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
29242
- for (const raw of entries) {
29243
- if (!raw || typeof raw !== "object") continue;
29244
- const ns = raw;
29245
- if (ns.type !== "atsc3" || !intIn2(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
29246
- const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
29247
- return {
29248
- frequency: ns.frequency,
29249
- ...intIn2(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
29250
- ...intIn2(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
29251
- ...slsUri ? { slsUri } : {}
29252
- };
29253
- }
29254
- return void 0;
29255
- }
29256
30134
 
29257
30135
  // src/multicast-manager.ts
29258
30136
  function freezeIngress(tracks, flow) {
@@ -29352,6 +30230,9 @@ var RECLASSIFICATION_EVIDENCE = /* @__PURE__ */ new Set([
29352
30230
  "rap",
29353
30231
  "mpu-span",
29354
30232
  "window",
30233
+ "mpu-rule",
30234
+ // Never emitted now (block-policy.ts); an event recorded earlier still validates.
30235
+ "dependent-run",
29355
30236
  "classifier-disabled"
29356
30237
  ]);
29357
30238
  var CLASSIFIER_MODES = /* @__PURE__ */ new Set(["classifying", "all-protected"]);
@@ -30141,7 +31022,9 @@ var MulticastManager = class {
30141
31022
  interleaveDepthMs,
30142
31023
  timescale: config.timescale,
30143
31024
  keyframeIntervalTicks: config.keyframeIntervalTicks,
30144
- keyframeIntervalMs: config.keyframeIntervalMs
31025
+ keyframeIntervalMs: config.keyframeIntervalMs,
31026
+ // The MPU rule classes a block only where this equals the keyframe interval.
31027
+ groupDurationMs: config.groupDurationMs
30145
31028
  });
30146
31029
  const fecConfig = {
30147
31030
  blockProfile,
@@ -30415,6 +31298,7 @@ var MulticastManager = class {
30415
31298
  // worse behaviour.
30416
31299
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
30417
31300
  amtDiscovery: config.amtDiscovery,
31301
+ atsc3: config.atsc3,
30418
31302
  packetIds: config.packetIds,
30419
31303
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId })),
30420
31304
  ...provenance === void 0 ? {} : { protected: true }
@@ -30568,6 +31452,7 @@ var MulticastManager = class {
30568
31452
  amtRelay: endpoint.amtRelay,
30569
31453
  amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
30570
31454
  amtDiscovery: endpoint.amtDiscovery,
31455
+ atsc3: endpoint.atsc3,
30571
31456
  packetIds: endpoint.packetIds,
30572
31457
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
30573
31458
  // A protected repair group's records ride in band on its port (7.2.3).
@@ -31372,8 +32257,10 @@ var MulticastManager = class {
31372
32257
  const out = {};
31373
32258
  for (const [key, stats] of this.#blockPolicyStats) {
31374
32259
  if (stats.epoch !== this.#fec.epochFor(stats.packetId)) continue;
32260
+ const mpuRuleOff = this.#fec.mpuRuleOffFor(stats.packetId, stats.catalogTrackName ?? void 0);
31375
32261
  out[key] = {
31376
32262
  ...stats,
32263
+ ...mpuRuleOff === void 0 ? {} : { mpuRuleOff },
31377
32264
  repairStops: { ...stats.repairStops },
31378
32265
  lastRepairSkip: stats.lastRepairSkip === null ? null : { ...stats.lastRepairSkip }
31379
32266
  };
@@ -34446,6 +35333,7 @@ function wireRepairFetch(mc, opts) {
34446
35333
  const run = entry.running;
34447
35334
  if (!run) return;
34448
35335
  entry.running = null;
35336
+ if (run.mootTimer !== void 0) clearTimeout(run.mootTimer);
34449
35337
  run.stopped = reason;
34450
35338
  run.controller.abort(reason);
34451
35339
  if (reason === "preempted") releaseHold(entry);
@@ -34459,8 +35347,9 @@ function wireRepairFetch(mc, opts) {
34459
35347
  const moot = (entry) => {
34460
35348
  if (entry.priority !== 0) return false;
34461
35349
  const rttMs = readRtt();
34462
- const sentAt = entry.running?.sentAt ?? performance.now();
34463
- if (rttMs !== null && sentAt + rttMs < entry.playoutDeadlineAt) return false;
35350
+ const now = performance.now();
35351
+ const sentAt = entry.running?.sentAt ?? now;
35352
+ if (rttMs !== null && now < entry.playoutDeadlineAt && sentAt + rttMs < entry.playoutDeadlineAt) return false;
34464
35353
  const last = lastSsId(entry);
34465
35354
  if (last === void 0) return false;
34466
35355
  try {
@@ -34469,6 +35358,31 @@ function wireRepairFetch(mc, opts) {
34469
35358
  return false;
34470
35359
  }
34471
35360
  };
35361
+ const dropMoot = (entry) => {
35362
+ stop(entry, "moot");
35363
+ retire(entry);
35364
+ releaseHold(entry);
35365
+ clearEntry(entry);
35366
+ };
35367
+ const mootAtPlayout = (entry) => {
35368
+ const run = entry.running;
35369
+ if (run === null || run.mootTimer !== void 0 || entry.priority !== 0) return;
35370
+ const last = lastSsId(entry);
35371
+ if (last === void 0) return;
35372
+ try {
35373
+ if (mc.rapCompleteAbove?.(entry.packetId, entry.catalogTrackName, last) !== true) return;
35374
+ } catch {
35375
+ return;
35376
+ }
35377
+ run.mootTimer = setTimeout(() => {
35378
+ run.mootTimer = void 0;
35379
+ if (disposed || entry.running !== run) return;
35380
+ if (performance.now() < entry.playoutDeadlineAt) return mootAtPlayout(entry);
35381
+ if (!moot(entry)) return;
35382
+ dropMoot(entry);
35383
+ dispatch();
35384
+ }, Math.max(0, entry.playoutDeadlineAt - performance.now()));
35385
+ };
34472
35386
  const skip = (entry, reason, rttMs, budgetMs) => {
34473
35387
  retire(entry);
34474
35388
  releaseHold(entry);
@@ -34579,6 +35493,7 @@ function wireRepairFetch(mc, opts) {
34579
35493
  });
34580
35494
  const run = { controller: new AbortController(), sentAt: now, stopped: null };
34581
35495
  entry.running = run;
35496
+ mootAtPlayout(entry);
34582
35497
  if (!entry.range) {
34583
35498
  mc.fecManager.holdBlockForRepair(
34584
35499
  entry.sbn,
@@ -34663,6 +35578,7 @@ function wireRepairFetch(mc, opts) {
34663
35578
  return;
34664
35579
  }
34665
35580
  entry.running = null;
35581
+ if (run.mootTimer !== void 0) clearTimeout(run.mootTimer);
34666
35582
  if (error === void 0) {
34667
35583
  retire(entry);
34668
35584
  if (entry.range || fed === 0 || !decodable(entry)) {
@@ -35089,11 +36005,9 @@ function wireRepairFetch(mc, opts) {
35089
36005
  queueMicrotask(() => {
35090
36006
  if (disposed) return;
35091
36007
  for (const entry of [...entries.values()]) {
35092
- if (entry.packetId !== packetId || !entry.running || !moot(entry)) continue;
35093
- stop(entry, "moot");
35094
- retire(entry);
35095
- releaseHold(entry);
35096
- clearEntry(entry);
36008
+ if (entry.packetId !== packetId || !entry.running) continue;
36009
+ if (moot(entry)) dropMoot(entry);
36010
+ else mootAtPlayout(entry);
35097
36011
  }
35098
36012
  dispatch();
35099
36013
  });
@@ -35146,6 +36060,7 @@ export {
35146
36060
  FEC_INACTIVE_REASONS,
35147
36061
  FEC_SOURCE_INFO_LEN,
35148
36062
  FEC_SS_ID_MAX,
36063
+ FRAME_NEEDS_KEYFRAME,
35149
36064
  FecSourceInfo,
35150
36065
  FecStarvationDetector,
35151
36066
  HEVC_NAL_HEADER_LENGTH,
@@ -35184,6 +36099,7 @@ export {
35184
36099
  TrackSession,
35185
36100
  TrackSourceConflictError,
35186
36101
  TransportPool,
36102
+ VideoFeedGate,
35187
36103
  WasmMfuReassembler,
35188
36104
  annexBToAvcc,
35189
36105
  archiveOrigin,
@@ -35195,6 +36111,7 @@ export {
35195
36111
  catalogAmtNetworkSource,
35196
36112
  catalogAtsc3NetworkSource,
35197
36113
  catalogDeclaresFec,
36114
+ catalogEventTimelineTracks,
35198
36115
  catalogFecInterleaveMs,
35199
36116
  catalogFecMediaUnitsPerSecond,
35200
36117
  catalogGroupDurationMs,
@@ -35216,9 +36133,11 @@ export {
35216
36133
  datagramMfuReassembly,
35217
36134
  decideGap,
35218
36135
  decodeFecSourceInfo,
36136
+ decodeFrameNeeds,
35219
36137
  decodeLocHeader,
35220
36138
  decodeLocTimestamp,
35221
36139
  decodeTimestamp,
36140
+ decoderTolerance,
35222
36141
  deriveBlockClassifierGeometry,
35223
36142
  detectH264Keyframe,
35224
36143
  detectHevcKeyframe,