@blockcast/mmt-container 0.4.0-main.404c51bd317c → 0.4.0-main.6302252bfdb3

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 (52) hide show
  1. package/dist/browser-runtime.js +176 -245
  2. package/dist/browser-runtime.js.map +4 -4
  3. package/dist/carp-catalog.js.map +1 -1
  4. package/dist/catalog-fec-params.js.map +1 -1
  5. package/dist/catalog-network-source.js.map +1 -1
  6. package/dist/delivery-catalog.js +81 -223
  7. package/dist/delivery-catalog.js.map +3 -3
  8. package/dist/fec-manager.js.map +1 -1
  9. package/dist/fec-state.js.map +1 -1
  10. package/dist/fec-worker-setup.js.map +1 -1
  11. package/dist/iso-block-locator.js.map +1 -1
  12. package/dist/mfu-reassembler.js +21 -13
  13. package/dist/mfu-reassembler.js.map +2 -2
  14. package/dist/mmtp-container-parser.d.ts.map +1 -1
  15. package/dist/mmtp-container-parser.js +93 -22
  16. package/dist/mmtp-container-parser.js.map +2 -2
  17. package/dist/mmtp-container-parser.no-modules.js +94 -23
  18. package/dist/mmtp-container-parser.no-modules.js.map +2 -2
  19. package/dist/mmtp-decode-pipeline.js +93 -22
  20. package/dist/mmtp-decode-pipeline.js.map +2 -2
  21. package/dist/mmtp-router.js +93 -22
  22. package/dist/mmtp-router.js.map +2 -2
  23. package/dist/multicast-input.js.map +1 -1
  24. package/dist/multicast-manager.d.ts +6 -0
  25. package/dist/multicast-manager.d.ts.map +1 -1
  26. package/dist/multicast-manager.js +176 -245
  27. package/dist/multicast-manager.js.map +4 -4
  28. package/dist/multicast-transport.d.ts +2 -0
  29. package/dist/multicast-transport.d.ts.map +1 -1
  30. package/dist/multicast-transport.js +82 -223
  31. package/dist/multicast-transport.js.map +3 -3
  32. package/dist/multicast-unwrap.js +21 -13
  33. package/dist/multicast-unwrap.js.map +2 -2
  34. package/dist/no-modules.js +93 -22
  35. package/dist/no-modules.js.map +2 -2
  36. package/dist/repair-fetch.js.map +1 -1
  37. package/dist/repair-layers.js.map +1 -1
  38. package/dist/sample-combiner.d.ts +7 -1
  39. package/dist/sample-combiner.d.ts.map +1 -1
  40. package/dist/sample-combiner.js +14 -2
  41. package/dist/sample-combiner.js.map +2 -2
  42. package/dist/signaling.js.map +1 -1
  43. package/dist/timestamp-codec.js +21 -13
  44. package/dist/timestamp-codec.js.map +2 -2
  45. package/dist/wasm-mfu-reassembler.js.map +1 -1
  46. package/dist/wasm-mmtp-container-parser.js +93 -22
  47. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  48. package/package.json +5 -5
  49. package/src/mmtp-container-parser.ts +75 -7
  50. package/src/multicast-manager.ts +7 -0
  51. package/src/multicast-transport.ts +3 -0
  52. package/src/sample-combiner.ts +15 -2
@@ -655,26 +655,30 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
655
655
  const authLength = view2.getUint16(2, false);
656
656
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
657
657
  }
658
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
658
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
659
659
  if (declaredEnd > payload.length)
660
660
  return null;
661
661
  if (options?.skipFecId) {
662
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
662
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
663
663
  }
664
+ const overlay = options?.overlayDeclared === true && rapFlag;
664
665
  if (fecType === 1) {
665
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
666
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
666
667
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
667
668
  return null;
668
669
  }
669
- return { hasFecId: true };
670
+ return { hasFecId: true, hasOverlayFecId: overlay };
670
671
  }
671
- if (fecType !== 0)
672
+ if (fecType !== 0 || overlay)
672
673
  return null;
673
674
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
674
- return { hasFecId: false };
675
+ return { hasFecId: false, hasOverlayFecId: false };
675
676
  }
676
677
  return null;
677
678
  }
679
+ function sourceFecTrailerSize(overlay) {
680
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
681
+ }
678
682
  function extractNALUnit(mmtpPacket) {
679
683
  const extraction = extractMFUPayload(mmtpPacket);
680
684
  if (!extraction)
@@ -733,15 +737,16 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
733
737
  if ("rejection" in layoutResult)
734
738
  return layoutResult;
735
739
  const { layout } = layoutResult;
736
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
740
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
737
741
  if (!trailerLayout) {
738
742
  if (!options?.skipFecId && header.fecType === 1) {
739
743
  const observed = payload.length - layout.dataEnd;
740
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
744
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
745
+ if (observed !== expected) {
741
746
  return {
742
747
  rejection: {
743
748
  gate: "source-fec-payload-id-width-mismatch",
744
- detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
749
+ detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${expected} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
745
750
  }
746
751
  };
747
752
  }
@@ -771,10 +776,13 @@ function extractPlannedMfu(mmtpPacket, result) {
771
776
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
772
777
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
773
778
  const data = payload.subarray(mfuOffset, dataEnd);
774
- const fecPayloadId = trailerLayout.hasFecId ? {
775
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
776
- } : null;
777
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
779
+ const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
780
+ const ssIdAt = (offset) => ({
781
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
782
+ });
783
+ const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
784
+ const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
785
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
778
786
  }
779
787
  function extractTimestamp(mmtpPacket) {
780
788
  const { header } = unwrapMMTP(mmtpPacket);
@@ -3886,8 +3894,14 @@ var SampleCombiner = class {
3886
3894
  /**
3887
3895
  * Add one reassembled data unit. Returns the combined sample once every
3888
3896
  * constituent data unit has arrived and totals the authored size.
3897
+ *
3898
+ * `sampleSize` is the authored size the host resolves for the sample as the
3899
+ * data unit completes. It stands in only when no size was registered, which
3900
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
3901
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
3902
+ * fragments, or one decoded before its source copy arrived.
3889
3903
  */
3890
- addMfu(mfu) {
3904
+ addMfu(mfu, sampleSize) {
3891
3905
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3892
3906
  this.#stats.passthroughSamples++;
3893
3907
  return fromPassthrough(mfu);
@@ -3903,7 +3917,7 @@ var SampleCombiner = class {
3903
3917
  return null;
3904
3918
  }
3905
3919
  const dataLen = mfu.data.byteLength;
3906
- const authoredSize = this.#authoredSizes.get(key);
3920
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
3907
3921
  if (offset === 0 && !this.#pending.has(key)) {
3908
3922
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
3909
3923
  if (passesThrough) {
@@ -4197,6 +4211,12 @@ if (void 0) {
4197
4211
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
4198
4212
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
4199
4213
  });
4214
+ test("a size handed with the data unit completes a sample no head registered", () => {
4215
+ const c = combiner({ requireAuthoredSize: true });
4216
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
4217
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
4218
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
4219
+ });
4200
4220
  test("duplicate offset is rejected", () => {
4201
4221
  const c = combiner();
4202
4222
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -6955,181 +6975,6 @@ var MoqFecAlgorithm;
6955
6975
  MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
6956
6976
  })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
6957
6977
 
6958
- // node_modules/@blockcast/mmt-base/dist/mmtp.js
6959
- var MPU_HEADER_SIZE2 = 8;
6960
- var MPU_LENGTH_FIELD_SIZE2 = 2;
6961
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
6962
- var MMTP_SIGNALING_PACKET_ID2 = 0;
6963
- var MMTP_PACKET_ID_MAX2 = 65535;
6964
-
6965
- // node_modules/@blockcast/mmt-base/dist/net-constants.js
6966
- var DEFAULT_AMT_RELAY_PORT2 = 2268;
6967
-
6968
- // node_modules/@blockcast/mmt-base/dist/ntp-short.js
6969
- var NTP_SHORT_BITS2 = 32;
6970
- var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
6971
- var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
6972
- function isNtpShort(value) {
6973
- return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
6974
- }
6975
- function compareNtpShort(a, b) {
6976
- if (!isNtpShort(a) || !isNtpShort(b)) {
6977
- throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
6978
- }
6979
- if (a === b)
6980
- return "equal";
6981
- const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
6982
- if (forward < NTP_SHORT_HALF_RANGE2)
6983
- return "after";
6984
- if (forward > NTP_SHORT_HALF_RANGE2)
6985
- return "before";
6986
- return "unordered";
6987
- }
6988
-
6989
- // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
6990
- var FEC_BLOCK_PROFILES2 = Object.freeze([
6991
- "iso-ssbg1-v1"
6992
- ]);
6993
-
6994
- // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
6995
- var ALL_ROLES2 = Object.freeze(["video", "audio"]);
6996
-
6997
- // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
6998
- var DRIADDiscovery = class {
6999
- cache = /* @__PURE__ */ new Map();
7000
- cacheExpiry = 3e5;
7001
- // 5 minutes
7002
- /**
7003
- * Discover AMT relays for a multicast source address (RFC 8777)
7004
- *
7005
- * @param source - The multicast source IP address (NOT the group!)
7006
- * @returns Array of discovered AMT relays that can tunnel traffic from this source
7007
- */
7008
- async discoverRelays(source) {
7009
- const cached = this.cache.get(source);
7010
- if (cached) {
7011
- return cached;
7012
- }
7013
- try {
7014
- const reversedSource = source.split(".").reverse().join(".");
7015
- const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
7016
- console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
7017
- const relays = await this.queryDRIADProxy(source);
7018
- if (relays.length > 0) {
7019
- this.cache.set(source, relays);
7020
- setTimeout(() => this.cache.delete(source), this.cacheExpiry);
7021
- }
7022
- return relays;
7023
- } catch (error) {
7024
- console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
7025
- return [];
7026
- }
7027
- }
7028
- /**
7029
- * Query DRIAD proxy service (browser-compatible)
7030
- */
7031
- async queryDRIADProxy(source) {
7032
- const proxyEndpoints = [
7033
- "https://driad.amt.net/api/v1/relays",
7034
- "https://multicast-gateway.cloudflare.com/driad"
7035
- ];
7036
- for (const endpoint of proxyEndpoints) {
7037
- try {
7038
- const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
7039
- method: "GET",
7040
- headers: { Accept: "application/json" },
7041
- signal: AbortSignal.timeout(5e3)
7042
- });
7043
- if (response.ok) {
7044
- const data = await response.json();
7045
- return data.relays || [];
7046
- }
7047
- } catch {
7048
- }
7049
- }
7050
- const dohRelay = await this.queryDNSOverHTTPS(source);
7051
- if (dohRelay) {
7052
- return [dohRelay];
7053
- }
7054
- return [];
7055
- }
7056
- /**
7057
- * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
7058
- */
7059
- async queryDNSOverHTTPS(source) {
7060
- try {
7061
- const reversedSource = source.split(".").reverse().join(".");
7062
- const queryName = `${reversedSource}.amt.in-addr.arpa`;
7063
- const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
7064
- const response = await fetch(dohUrl, {
7065
- headers: { Accept: "application/dns-json" },
7066
- signal: AbortSignal.timeout(3e3)
7067
- });
7068
- if (!response.ok) {
7069
- return null;
7070
- }
7071
- const result = await response.json();
7072
- if (result.Answer && result.Answer.length > 0) {
7073
- return {
7074
- host: result.Answer[0].data,
7075
- port: DEFAULT_AMT_RELAY_PORT2,
7076
- priority: 10,
7077
- weight: 100,
7078
- asn: 0
7079
- };
7080
- }
7081
- return null;
7082
- } catch (error) {
7083
- console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
7084
- return null;
7085
- }
7086
- }
7087
- /**
7088
- * Select best relay based on RTT measurements
7089
- */
7090
- async selectBestRelay(relays) {
7091
- if (relays.length === 0)
7092
- return null;
7093
- const measured = await Promise.all(relays.map(async (relay) => {
7094
- const rtt = await this.measureRTT(relay.host, relay.port);
7095
- return { ...relay, rtt };
7096
- }));
7097
- measured.sort((a, b) => {
7098
- if (a.priority !== b.priority)
7099
- return a.priority - b.priority;
7100
- return (a.rtt || Infinity) - (b.rtt || Infinity);
7101
- });
7102
- console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
7103
- return measured[0];
7104
- }
7105
- async measureRTT(host, _port) {
7106
- const start = performance.now();
7107
- try {
7108
- await fetch(`https://${host}/health`, {
7109
- method: "HEAD",
7110
- signal: AbortSignal.timeout(2e3),
7111
- mode: "no-cors"
7112
- });
7113
- return performance.now() - start;
7114
- } catch {
7115
- return Infinity;
7116
- }
7117
- }
7118
- /**
7119
- * Clear the relay cache
7120
- */
7121
- clearCache() {
7122
- this.cache.clear();
7123
- }
7124
- /**
7125
- * Get cached relays for a source address
7126
- */
7127
- getCached(source) {
7128
- return this.cache.get(source);
7129
- }
7130
- };
7131
- var driadDiscovery = new DRIADDiscovery();
7132
-
7133
6978
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
7134
6979
  function endpointKey(endpoint) {
7135
6980
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -7337,6 +7182,45 @@ var AdaptiveBitrateController = class {
7337
7182
  }
7338
7183
  };
7339
7184
 
7185
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
7186
+ var MPU_HEADER_SIZE2 = 8;
7187
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
7188
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
7189
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
7190
+ var MMTP_PACKET_ID_MAX2 = 65535;
7191
+
7192
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
7193
+ var DEFAULT_AMT_RELAY_PORT2 = 2268;
7194
+
7195
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
7196
+ var NTP_SHORT_BITS2 = 32;
7197
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
7198
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
7199
+ function isNtpShort(value) {
7200
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
7201
+ }
7202
+ function compareNtpShort(a, b) {
7203
+ if (!isNtpShort(a) || !isNtpShort(b)) {
7204
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
7205
+ }
7206
+ if (a === b)
7207
+ return "equal";
7208
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
7209
+ if (forward < NTP_SHORT_HALF_RANGE2)
7210
+ return "after";
7211
+ if (forward > NTP_SHORT_HALF_RANGE2)
7212
+ return "before";
7213
+ return "unordered";
7214
+ }
7215
+
7216
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
7217
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
7218
+ "iso-ssbg1-v1"
7219
+ ]);
7220
+
7221
+ // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
7222
+ var ALL_ROLES2 = Object.freeze(["video", "audio"]);
7223
+
7340
7224
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7341
7225
  var DEFAULT_DWELL_MS = 3e3;
7342
7226
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -7575,7 +7459,8 @@ function toWindowMulticastSubscribeConfig(input) {
7575
7459
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
7576
7460
  };
7577
7461
  const relay = input.amtRelay?.trim();
7578
- const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
7462
+ const driad = !relay && input.amtDiscovery === "driad";
7463
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
7579
7464
  if (!wantsAmt) {
7580
7465
  const native = {
7581
7466
  ...base,
@@ -7585,6 +7470,20 @@ function toWindowMulticastSubscribeConfig(input) {
7585
7470
  return native;
7586
7471
  }
7587
7472
  const relayPort = input.amtRelayPort;
7473
+ if (driad) {
7474
+ if (!base.source)
7475
+ throw new TypeError("AMT DRIAD discovery requires a source address");
7476
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
7477
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
7478
+ }
7479
+ return {
7480
+ ...base,
7481
+ source: base.source,
7482
+ origin: "amt",
7483
+ discovery: "driad",
7484
+ ...relayPort !== void 0 ? { relayPort } : {}
7485
+ };
7486
+ }
7588
7487
  if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
7589
7488
  throw new TypeError("AMT requires a resolved relay and a valid relay port");
7590
7489
  }
@@ -7628,7 +7527,8 @@ function normalizeMulticastEndpoint(endpoint) {
7628
7527
  port: endpoint.port,
7629
7528
  ...endpoint.mode ? { mode: endpoint.mode } : {},
7630
7529
  ...amtRelay ? { amtRelay } : {},
7631
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
7530
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
7531
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
7632
7532
  };
7633
7533
  }
7634
7534
  function multicastEndpointKey(endpoint) {
@@ -7641,7 +7541,9 @@ function multicastEndpointKey(endpoint) {
7641
7541
  normalized.port,
7642
7542
  normalized.mode ?? "auto",
7643
7543
  normalized.amtRelay ?? "",
7644
- normalized.amtRelayPort ?? ""
7544
+ normalized.amtRelayPort ?? "",
7545
+ // A DRIAD join is a different gateway subscription from a native one.
7546
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
7645
7547
  ]);
7646
7548
  }
7647
7549
  function isMulticastTrackPacketId(value) {
@@ -7681,7 +7583,8 @@ var MulticastSubscriptionPool = class {
7681
7583
  port: config.port,
7682
7584
  mode: config.mode,
7683
7585
  amtRelay: config.amtRelay,
7684
- amtRelayPort: config.amtRelayPort
7586
+ amtRelayPort: config.amtRelayPort,
7587
+ amtDiscovery: config.amtDiscovery
7685
7588
  });
7686
7589
  if (!endpoint)
7687
7590
  throw new Error("Invalid multicast endpoint");
@@ -7747,7 +7650,8 @@ var MulticastSubscriptionPool = class {
7747
7650
  port: endpoint.port,
7748
7651
  ...endpoint.mode ? { mode: endpoint.mode } : {},
7749
7652
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
7750
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
7653
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
7654
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
7751
7655
  }));
7752
7656
  const consumers = /* @__PURE__ */ new Map();
7753
7657
  let entry;
@@ -7827,7 +7731,6 @@ var TransportManager = class {
7827
7731
  };
7828
7732
  capabilities = null;
7829
7733
  subscription = null;
7830
- driad = new DRIADDiscovery();
7831
7734
  /** Built by `connect()` from the caller's ladder; there is no built-in one. */
7832
7735
  abr = null;
7833
7736
  multicastOrchestrator = null;
@@ -7877,8 +7780,8 @@ var TransportManager = class {
7877
7780
  nativeIGMP: hasGatewayBytes,
7878
7781
  directSockets: typeof win?.UDPSocket !== "undefined",
7879
7782
  amt: false,
7880
- driad: true,
7881
- // DRIAD uses HTTP proxy, always available
7783
+ driad: hasGatewayBytes,
7784
+ // the gateway runs RFC 8777 discovery
7882
7785
  fecDecode: false
7883
7786
  };
7884
7787
  console.log("[Transport] Capabilities:", this.capabilities);
@@ -7889,7 +7792,7 @@ var TransportManager = class {
7889
7792
  *
7890
7793
  * Promotion hierarchy:
7891
7794
  * 1. window.multicast gateway bytes
7892
- * 2. AMT proxy (specified or discovered via DRIAD)
7795
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
7893
7796
  * 3. MOQ WebTransport (final fallback)
7894
7797
  *
7895
7798
  * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
@@ -7983,7 +7886,7 @@ var TransportManager = class {
7983
7886
  /**
7984
7887
  * Connect via the lowercase window.multicast bytes gateway.
7985
7888
  */
7986
- async connectWindowMulticast(config, generation) {
7889
+ async connectWindowMulticast(config, generation, mode = "multicast") {
7987
7890
  try {
7988
7891
  const gateway = this.getWindowMulticastGateway();
7989
7892
  if (typeof gateway?.subscribe !== "function")
@@ -8018,7 +7921,7 @@ var TransportManager = class {
8018
7921
  }
8019
7922
  };
8020
7923
  this.state = {
8021
- mode: "multicast",
7924
+ mode,
8022
7925
  connected: true,
8023
7926
  group: config.group,
8024
7927
  source: config.source,
@@ -8036,29 +7939,19 @@ var TransportManager = class {
8036
7939
  }
8037
7940
  }
8038
7941
  /**
8039
- * Connect via AMT proxy (with optional DRIAD discovery)
7942
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
7943
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
8040
7944
  */
8041
7945
  async connectAmt(config, generation) {
8042
7946
  try {
8043
- let amtRelay = config.amtRelay;
8044
- if (!amtRelay && config.driadEnabled !== false && config.source) {
8045
- console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
8046
- const relays = await this.driad.discoverRelays(config.source);
8047
- if (generation !== this.connectionGeneration)
8048
- return false;
8049
- const bestRelay = await this.driad.selectBestRelay(relays);
8050
- if (generation !== this.connectionGeneration)
8051
- return false;
8052
- if (bestRelay) {
8053
- amtRelay = bestRelay.host;
8054
- this.state.amtRelay = amtRelay;
8055
- }
8056
- }
8057
- if (!amtRelay) {
7947
+ if (config.amtRelay)
7948
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
7949
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
8058
7950
  console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
8059
7951
  return false;
8060
7952
  }
8061
- return await this.connectAmtProxy(config, amtRelay, generation);
7953
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
7954
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
8062
7955
  } catch (error) {
8063
7956
  console.warn("[Transport] AMT connection failed:", error);
8064
7957
  return false;
@@ -8289,7 +8182,6 @@ var AMTGatewayManager = class {
8289
8182
  subscriptions = /* @__PURE__ */ new Map();
8290
8183
  messageHandler;
8291
8184
  pendingPackets = /* @__PURE__ */ new Map();
8292
- driad = new DRIADDiscovery();
8293
8185
  constructor() {
8294
8186
  this.messageHandler = (event) => {
8295
8187
  const data = event.data;
@@ -8320,26 +8212,12 @@ var AMTGatewayManager = class {
8320
8212
  return keyStr;
8321
8213
  }
8322
8214
  try {
8323
- let relayAddress;
8324
- let discoveryMethod;
8215
+ const relayAddress = config.relayAddress;
8325
8216
  const relayPort = config.relayPort || DEFAULT_AMT_RELAY_PORT2;
8326
- if (config.relayAddress) {
8327
- relayAddress = config.relayAddress;
8328
- discoveryMethod = "manual";
8329
- console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
8330
- } else if (key.source) {
8331
- console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
8332
- const relays = await this.driad.discoverRelays(key.source);
8333
- const bestRelay = await this.driad.selectBestRelay(relays);
8334
- if (!bestRelay) {
8335
- throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
8336
- }
8337
- relayAddress = bestRelay.host;
8338
- discoveryMethod = "driad";
8339
- console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
8340
- } else {
8341
- throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
8217
+ if (!relayAddress) {
8218
+ throw new Error(`AMT relay address required: this manager does no relay discovery. For RFC 8777 DRIAD discovery, join through window.multicast with amtDiscovery: "driad".`);
8342
8219
  }
8220
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
8343
8221
  const subscriptionId = keyStr;
8344
8222
  this.pendingPackets.set(subscriptionId, []);
8345
8223
  const subscription = {
@@ -8350,7 +8228,7 @@ var AMTGatewayManager = class {
8350
8228
  relay: {
8351
8229
  address: relayAddress,
8352
8230
  port: relayPort,
8353
- discoveryMethod,
8231
+ discoveryMethod: "manual",
8354
8232
  discoveredAt: Date.now()
8355
8233
  }
8356
8234
  };
@@ -17401,6 +17279,7 @@ function isFmp4Box(data) {
17401
17279
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
17402
17280
  return FMPU_BOX_TYPES.has(type);
17403
17281
  }
17282
+ var MAX_AWAITING_TIMING_HEADS = 8;
17404
17283
  var MmtpContainerParser = class _MmtpContainerParser {
17405
17284
  constructor(config) {
17406
17285
  this.#tracks = /* @__PURE__ */ new Map();
@@ -17459,6 +17338,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17459
17338
  * reordering into the parser. */
17460
17339
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
17461
17340
  this.#disposed = false;
17341
+ this.#replayingAwaitingTiming = false;
17462
17342
  this.#fedObjects = 0;
17463
17343
  this.#reassemblerFragmentsFed = 0;
17464
17344
  this.#reassemblerDataUnitsReturned = 0;
@@ -17551,6 +17431,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17551
17431
  #reorderStats;
17552
17432
  #reliableMoqStartupGate;
17553
17433
  #disposed;
17434
+ #replayingAwaitingTiming;
17554
17435
  #fedObjects;
17555
17436
  #reassemblerFragmentsFed;
17556
17437
  #reassemblerDataUnitsReturned;
@@ -17800,7 +17681,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
17800
17681
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
17801
17682
  */
17802
17683
  #drop(reason) {
17803
- this.#countOutcome(`drop:${reason}`);
17684
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
17685
+ else this.#countOutcome(`drop:${reason}`);
17804
17686
  return null;
17805
17687
  }
17806
17688
  get reorderDiagnostics() {
@@ -17823,6 +17705,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
17823
17705
  for (const combiner of this.#sampleCombiners.values()) {
17824
17706
  combiner.cleanupTimeouts(timeoutMs);
17825
17707
  }
17708
+ const now = Date.now();
17709
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
17710
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
17711
+ awaitingTiming.shift();
17712
+ }
17713
+ }
17826
17714
  }
17827
17715
  /**
17828
17716
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -17903,7 +17791,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17903
17791
  byteLength: packet.byteLength
17904
17792
  };
17905
17793
  }
17906
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
17794
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
17907
17795
  const rawSymbol = packet.subarray(0, packet.length - 4);
17908
17796
  try {
17909
17797
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -17951,6 +17839,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17951
17839
  }
17952
17840
  return this.#drop("fragment-timing-refused");
17953
17841
  }
17842
+ this.#replayAwaitingTiming(streamKey, resolver2);
17954
17843
  return {
17955
17844
  kind: "fragment",
17956
17845
  packet: info,
@@ -17974,7 +17863,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
17974
17863
  mfuDuHeader.movieFragmentSequenceNumber,
17975
17864
  mfuDuHeader.sampleNumber
17976
17865
  );
17977
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
17866
+ if (!headTiming) {
17867
+ this.#awaitTiming(streamKey, {
17868
+ packet,
17869
+ options,
17870
+ parsed,
17871
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
17872
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
17873
+ sampleNumber: mfuDuHeader.sampleNumber,
17874
+ arrivedAt: Date.now()
17875
+ });
17876
+ return this.#drop("mfu-sample-timing-missing");
17877
+ }
17978
17878
  const offset = mfuDuHeader.offset;
17979
17879
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
17980
17880
  return this.#drop("mfu-offset-out-of-range");
@@ -18050,16 +17950,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
18050
17950
  const sampleNumber = assembled.sampleNumber;
18051
17951
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
18052
17952
  return this.#drop("assembled-identity-missing");
18053
- if (!resolver.sampleTiming(
17953
+ const assembledTiming = resolver.sampleTiming(
18054
17954
  assembled.mpuSequenceNumber,
18055
17955
  movieFragmentSequenceNumber,
18056
17956
  sampleNumber
18057
- )) return this.#drop("assembled-timing-missing");
17957
+ );
17958
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
18058
17959
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
18059
17960
  return this.#drop("assembled-mpu-mismatch");
18060
17961
  let combined;
18061
17962
  try {
18062
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
17963
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
18063
17964
  } catch (error) {
18064
17965
  if (!(error instanceof SampleCombineError)) throw error;
18065
17966
  console.warn(
@@ -18368,9 +18269,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
18368
18269
  if (existing) return existing.resolver;
18369
18270
  if (!create) return null;
18370
18271
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
18371
- this.#timingStreams.set(streamKey, { packetId, resolver });
18272
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
18372
18273
  return resolver;
18373
18274
  }
18275
+ #awaitTiming(streamKey, head) {
18276
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
18277
+ if (!awaitingTiming) return;
18278
+ awaitingTiming.push(head);
18279
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
18280
+ }
18281
+ /**
18282
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
18283
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
18284
+ * FEC path routes a source symbol that already arrived a second time.
18285
+ */
18286
+ #replayAwaitingTiming(streamKey, resolver) {
18287
+ const state = this.#timingStreams.get(streamKey);
18288
+ if (!state || state.awaitingTiming.length === 0) return;
18289
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
18290
+ head.mpuSequenceNumber,
18291
+ head.movieFragmentSequenceNumber,
18292
+ head.sampleNumber
18293
+ ));
18294
+ if (ready.length === 0) return;
18295
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
18296
+ this.#replayingAwaitingTiming = true;
18297
+ try {
18298
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
18299
+ } finally {
18300
+ this.#replayingAwaitingTiming = false;
18301
+ }
18302
+ }
18374
18303
  #dropTimingStream(streamKey) {
18375
18304
  const state = this.#timingStreams.get(streamKey);
18376
18305
  if (!state) return;
@@ -22188,6 +22117,7 @@ var MulticastTransport = class {
22188
22117
  mode: config.mode,
22189
22118
  amtRelay: config.amtRelay,
22190
22119
  amtRelayPort: config.amtRelayPort,
22120
+ amtDiscovery: config.amtDiscovery,
22191
22121
  packetIds: config.packetIds,
22192
22122
  tracks: config.tracks
22193
22123
  });
@@ -24081,6 +24011,7 @@ var MulticastManager = class {
24081
24011
  // through whatever the relay looks like, since dropping it would be the
24082
24012
  // worse behaviour.
24083
24013
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24014
+ amtDiscovery: config.amtDiscovery,
24084
24015
  packetIds: config.packetIds,
24085
24016
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
24086
24017
  };