@blockcast/mmt-base 0.4.0 → 0.4.1-main.2e0aa69d293d

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.
@@ -0,0 +1,350 @@
1
+ /**
2
+ * The draft-ramadan-moq-multicast-01 endpoint and `auth` rules, written once
3
+ * for both sides of the catalog: `validateCmsfMmtpCatalog` in
4
+ * `@blockcast/mmt-container` throws the first issue, and the receivers in
5
+ * `@blockcast/mmt-transport` ignore every endpoint an issue names (all of
6
+ * them when the issue is catalog-level). It lives here because mmt-base is
7
+ * the only package both depend on.
8
+ *
9
+ * Draft: Blockcast/moqcast-draft@fd962fd73d21ed281b60219c11ea61cc9e4e91c4
10
+ * (PR #2 head; normative text equal to 3162ef93), sections 4.1 and 7.2.6.
11
+ */
12
+
13
+ export type MulticastJoinMode = "ssm" | "asm";
14
+
15
+ /** An endpoint's join mode and `S` (4.1): `sourceAddress` on SSM,
16
+ * `auth.senderAddress` on protected ASM, absent on unprotected ASM. */
17
+ export interface MulticastEndpointSource {
18
+ mode: MulticastJoinMode;
19
+ source?: string;
20
+ }
21
+
22
+ export type MulticastCatalogIssueCode =
23
+ | "multicast_auth"
24
+ | "multicast_endpoint"
25
+ | "multicast_endpoint_auth"
26
+ | "multicast_track";
27
+
28
+ export interface MulticastCatalogIssue {
29
+ code: MulticastCatalogIssueCode;
30
+ /** JSONPath of the offending field. */
31
+ path: string;
32
+ message: string;
33
+ /** Endpoint the issue makes a receiver ignore; absent for a catalog-level
34
+ * issue, which leaves the receiver no endpoint at all (7.2.6). */
35
+ endpointIndex?: number;
36
+ }
37
+
38
+ /** Canonical unpadded base64url of exactly 32 octets. */
39
+ export const ED25519_PUBLIC_KEY_BASE64URL = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
40
+
41
+ const UINT32_MAX = 0xffff_ffff;
42
+ const AUTH_MEMBERS = new Set(["scheme", "version", "sig", "keys", "minEpoch"]);
43
+ const KEY_MEMBERS = new Set(["kid", "publicKey", "firstEpoch"]);
44
+ const ENDPOINT_AUTH_MEMBERS = new Set([
45
+ "manifestPort",
46
+ "streamId",
47
+ "senderAddress",
48
+ "maxAuthDelayMs",
49
+ "manifestTimerMs",
50
+ "manifestTrack",
51
+ ]);
52
+
53
+ type JsonObject = Record<string, unknown>;
54
+
55
+ function isObject(value: unknown): value is JsonObject {
56
+ return typeof value === "object" && value !== null && !Array.isArray(value);
57
+ }
58
+
59
+ function isNonEmptyString(value: unknown): value is string {
60
+ return typeof value === "string" && value.trim().length > 0;
61
+ }
62
+
63
+ function isIntegerIn(value: unknown, min: number, max: number): value is number {
64
+ return Number.isSafeInteger(value) && (value as number) >= min && (value as number) <= max;
65
+ }
66
+
67
+ /**
68
+ * Join mode and `S` of one endpoint, or `undefined` when its fields disagree
69
+ * and a receiver must ignore it (4.1). `sourceAddress` alone selects the mode;
70
+ * `protocol` may only restate it, so "amt" and "atsc3" (draft -00) are
71
+ * inconsistent here: a bearer is a `networkSource`, never a protocol.
72
+ */
73
+ export function multicastEndpointSource(endpoint: unknown): MulticastEndpointSource | undefined {
74
+ if (!isObject(endpoint)) return undefined;
75
+ const sourceAddress = endpoint["sourceAddress"];
76
+ if (sourceAddress !== undefined && !isNonEmptyString(sourceAddress)) return undefined;
77
+ const mode: MulticastJoinMode = sourceAddress === undefined ? "asm" : "ssm";
78
+ const protocol = endpoint["protocol"];
79
+ if (protocol !== undefined && protocol !== mode) return undefined;
80
+ const auth = endpoint["auth"];
81
+ const senderAddress = isObject(auth) ? auth["senderAddress"] : undefined;
82
+ if (mode === "ssm") return senderAddress === undefined ? { mode, source: sourceAddress as string } : undefined;
83
+ if (auth === undefined) return { mode };
84
+ return isNonEmptyString(senderAddress) ? { mode, source: senderAddress } : undefined;
85
+ }
86
+
87
+ function authIssues(auth: unknown): MulticastCatalogIssue[] {
88
+ const base = "$.multicast.auth";
89
+ const issue = (path: string, message: string): MulticastCatalogIssue[] => [
90
+ { code: "multicast_auth", path: `${base}${path}`, message },
91
+ ];
92
+ if (!isObject(auth)) return issue("", "auth must be an object");
93
+ const unknown = Object.keys(auth).filter(key => !AUTH_MEMBERS.has(key));
94
+ if (unknown.length > 0) {
95
+ return issue("", `auth has unknown member(s) ${unknown.join(", ")}; draft -01 7.2.6 defines scheme, version, sig, keys and minEpoch`);
96
+ }
97
+ if (auth["scheme"] !== "bc-provenance") return issue(".scheme", 'scheme must be "bc-provenance"');
98
+ if (auth["version"] !== 2) return issue(".version", "version must be 2 (bc-provenance version 2, draft -01 7.2)");
99
+ if (auth["sig"] !== "ed25519") return issue(".sig", 'sig must be "ed25519"');
100
+ const keys = auth["keys"];
101
+ if (!Array.isArray(keys) || keys.length < 1 || keys.length > 4) {
102
+ return issue(".keys", "keys must be an array of one to four {kid, publicKey, firstEpoch} objects");
103
+ }
104
+ const kids = new Set<number>();
105
+ const firstEpochs = new Set<number>();
106
+ for (let index = 0; index < keys.length; index++) {
107
+ const key = keys[index];
108
+ const at = `.keys[${index}]`;
109
+ if (!isObject(key) || Object.keys(key).some(member => !KEY_MEMBERS.has(member))) {
110
+ return issue(at, "a key is exactly {kid, publicKey, firstEpoch}");
111
+ }
112
+ if (!isIntegerIn(key["kid"], 0, UINT32_MAX)) return issue(`${at}.kid`, "kid must be an unsigned 32-bit integer");
113
+ if (typeof key["publicKey"] !== "string" || !ED25519_PUBLIC_KEY_BASE64URL.test(key["publicKey"])) {
114
+ return issue(`${at}.publicKey`, "publicKey must be a 32-octet Ed25519 key in canonical unpadded base64url");
115
+ }
116
+ if (!isIntegerIn(key["firstEpoch"], 0, UINT32_MAX)) {
117
+ return issue(`${at}.firstEpoch`, "firstEpoch must be an unsigned 32-bit integer");
118
+ }
119
+ // A repeated kid or firstEpoch leaves no key set (7.2.6): fail the whole
120
+ // block, never fall back to unauthenticated reception.
121
+ if (kids.has(key["kid"])) return issue(`${at}.kid`, `kid ${key["kid"]} is repeated; the catalog holds no key set`);
122
+ if (firstEpochs.has(key["firstEpoch"])) {
123
+ return issue(`${at}.firstEpoch`, `firstEpoch ${key["firstEpoch"]} is repeated; the catalog holds no key set`);
124
+ }
125
+ kids.add(key["kid"]);
126
+ firstEpochs.add(key["firstEpoch"]);
127
+ }
128
+ if (!isIntegerIn(auth["minEpoch"], 0, UINT32_MAX)) {
129
+ return issue(".minEpoch", "minEpoch must be an unsigned 32-bit integer");
130
+ }
131
+ return [];
132
+ }
133
+
134
+ function endpointAuthIssue(
135
+ endpoint: JsonObject,
136
+ mode: MulticastJoinMode,
137
+ at: string,
138
+ ): { path: string; message: string } | undefined {
139
+ const auth = endpoint["auth"];
140
+ if (!isObject(auth)) return { path: `${at}.auth`, message: "auth must be an object" };
141
+ const unknown = Object.keys(auth).filter(key => !ENDPOINT_AUTH_MEMBERS.has(key));
142
+ if (unknown.length > 0) return { path: `${at}.auth`, message: `auth has unknown member(s) ${unknown.join(", ")}` };
143
+ if (!isIntegerIn(auth["manifestPort"], 1, 65535)) {
144
+ return { path: `${at}.auth.manifestPort`, message: "manifestPort must be an integer from 1 to 65535" };
145
+ }
146
+ if (!isIntegerIn(auth["streamId"], 0, UINT32_MAX)) {
147
+ return { path: `${at}.auth.streamId`, message: "streamId must be an unsigned 32-bit integer" };
148
+ }
149
+ if (mode === "ssm" && auth["senderAddress"] !== undefined) {
150
+ return { path: `${at}.auth.senderAddress`, message: "senderAddress must not appear on an SSM endpoint; S is sourceAddress" };
151
+ }
152
+ if (mode === "asm" && !isNonEmptyString(auth["senderAddress"])) {
153
+ return { path: `${at}.auth.senderAddress`, message: "a protected ASM endpoint requires senderAddress" };
154
+ }
155
+ if (auth["maxAuthDelayMs"] !== undefined && !isIntegerIn(auth["maxAuthDelayMs"], 50, 1000)) {
156
+ return { path: `${at}.auth.maxAuthDelayMs`, message: "maxAuthDelayMs must be an integer from 50 to 1000" };
157
+ }
158
+ if (auth["manifestTimerMs"] !== undefined && !isIntegerIn(auth["manifestTimerMs"], 1, Number.MAX_SAFE_INTEGER)) {
159
+ return { path: `${at}.auth.manifestTimerMs`, message: "manifestTimerMs must be an integer of at least 1" };
160
+ }
161
+ if (auth["manifestTrack"] !== undefined && !isNonEmptyString(auth["manifestTrack"])) {
162
+ return { path: `${at}.auth.manifestTrack`, message: "manifestTrack must be a non-empty string" };
163
+ }
164
+ if (!isIntegerIn(endpoint["bandwidth"], 1, Number.MAX_SAFE_INTEGER)) {
165
+ return { path: `${at}.bandwidth`, message: "a protected endpoint requires bandwidth, which bounds the receiver's hold queues" };
166
+ }
167
+ return undefined;
168
+ }
169
+
170
+ /**
171
+ * Where a catalog object carries the namespace of the catalog track it was
172
+ * read from. A symbol, so it is never wire data and survives object spread;
173
+ * `Symbol.for`, so two bundled copies of this module agree on it.
174
+ */
175
+ export const CATALOG_NAMESPACE: unique symbol = Symbol.for("@blockcast/mmt-base/catalogNamespace");
176
+
177
+ /**
178
+ * `catalog` tagged with the namespace of its catalog track. Every receiver
179
+ * rule that takes the catalog (`multicastCatalogIssues`,
180
+ * `admittedMulticastEndpoints` and the transport selectors built on them)
181
+ * then judges the foreign-namespace rule against it, independent of track
182
+ * order. Tag once, where the catalog track is read.
183
+ */
184
+ export function withCatalogNamespace<T extends object>(catalog: T, namespace: string): T {
185
+ return { ...catalog, [CATALOG_NAMESPACE]: namespace };
186
+ }
187
+
188
+ /**
189
+ * Every draft -01 4.1 / 7.2.6 violation in `catalog.multicast`, in document
190
+ * order. Packet-id, group-address and track-existence rules are not here; the
191
+ * container validator and the receivers already check those.
192
+ *
193
+ * `catalogNamespace` is the namespace of the catalog track, from `options` or else the
194
+ * catalog's `withCatalogNamespace` tag. Without it the
195
+ * foreign-namespace rule can only compare listed tracks with each other: the
196
+ * first listed track's namespace becomes the reference, so which side of a
197
+ * disagreement is dropped depends on order. It still fails closed; pass
198
+ * `catalogNamespace` wherever the catalog track is known.
199
+ */
200
+ export function multicastCatalogIssues(
201
+ catalog: unknown,
202
+ options: { catalogNamespace?: string } = {},
203
+ ): MulticastCatalogIssue[] {
204
+ if (!isObject(catalog)) return [];
205
+ const issues: MulticastCatalogIssue[] = [];
206
+ if ("multicast.auth" in catalog) {
207
+ // Fail closed: a draft -00 publisher meant the flow to be protected, and
208
+ // the key it names verifies nothing in bc-provenance version 2.
209
+ issues.push({
210
+ code: "multicast_auth",
211
+ path: '$["multicast.auth"]',
212
+ message: 'the root "multicast.auth" key is retired; declare auth as multicast.auth (draft -01 7.2.6)',
213
+ });
214
+ }
215
+ const multicast = catalog["multicast"];
216
+ if (!isObject(multicast)) return issues;
217
+ const protectedCatalog = multicast["auth"] !== undefined;
218
+ if (protectedCatalog) issues.push(...authIssues(multicast["auth"]));
219
+ const endpoints = multicast["endpoints"];
220
+ if (!Array.isArray(endpoints)) return issues;
221
+
222
+ const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
223
+ const namespaceOf = new Map<string, unknown>();
224
+ for (const track of tracks) {
225
+ if (isObject(track) && typeof track["name"] === "string") namespaceOf.set(track["name"], track["namespace"]);
226
+ }
227
+ const tagged = (catalog as { [CATALOG_NAMESPACE]?: unknown })[CATALOG_NAMESPACE];
228
+ let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : undefined);
229
+
230
+ const sources: Array<MulticastEndpointSource | undefined> = [];
231
+ for (let index = 0; index < endpoints.length; index++) {
232
+ const endpoint = endpoints[index];
233
+ const at = `$.multicast.endpoints[${index}]`;
234
+ const fail = (code: MulticastCatalogIssueCode, path: string, message: string) => {
235
+ issues.push({ code, path, message, endpointIndex: index });
236
+ };
237
+ sources.push(undefined);
238
+ if (!isObject(endpoint)) {
239
+ fail("multicast_endpoint", at, "endpoint must be an object");
240
+ continue;
241
+ }
242
+ const protocol = endpoint["protocol"];
243
+ if (protocol !== undefined && protocol !== "ssm" && protocol !== "asm") {
244
+ fail("multicast_endpoint", `${at}.protocol`, `protocol must be "ssm" or "asm"; a bearer such as ${JSON.stringify(protocol)} is a networkSource entry (draft -01 4.2)`);
245
+ continue;
246
+ }
247
+ const hasAuth = endpoint["auth"] !== undefined;
248
+ if (protectedCatalog !== hasAuth) {
249
+ fail(
250
+ "multicast_endpoint_auth",
251
+ `${at}.auth`,
252
+ protectedCatalog
253
+ ? "every endpoint requires auth when multicast carries auth; a receiver ignores this endpoint"
254
+ : "auth names no key without multicast.auth; a receiver ignores this endpoint",
255
+ );
256
+ continue;
257
+ }
258
+ const sourceAddress = endpoint["sourceAddress"];
259
+ if (sourceAddress !== undefined && !isNonEmptyString(sourceAddress)) {
260
+ fail("multicast_endpoint", `${at}.sourceAddress`, "sourceAddress must be a non-empty string");
261
+ continue;
262
+ }
263
+ const mode: MulticastJoinMode = sourceAddress === undefined ? "asm" : "ssm";
264
+ if (protocol !== undefined && protocol !== mode) {
265
+ fail("multicast_endpoint", `${at}.protocol`, `protocol ${JSON.stringify(protocol)} disagrees with sourceAddress, which selects ${mode}`);
266
+ continue;
267
+ }
268
+ // The (S, G, port) rule below compares ports with ===, so only an
269
+ // integer may reach it: "5001" and 5001 would otherwise both pass.
270
+ if (!isIntegerIn(endpoint["port"], 1, 65535)) {
271
+ fail("multicast_endpoint", `${at}.port`, "port must be an integer from 1 to 65535");
272
+ continue;
273
+ }
274
+ if (hasAuth) {
275
+ const authIssue = endpointAuthIssue(endpoint, mode, at);
276
+ if (authIssue) {
277
+ fail("multicast_endpoint_auth", authIssue.path, authIssue.message);
278
+ continue;
279
+ }
280
+ }
281
+ sources[index] = multicastEndpointSource(endpoint);
282
+
283
+ const refs = Array.isArray(endpoint["tracks"]) ? endpoint["tracks"] : [];
284
+ for (let refIndex = 0; refIndex < refs.length; refIndex++) {
285
+ const ref = refs[refIndex];
286
+ const name = isObject(ref) ? ref["name"] : ref;
287
+ if (typeof name !== "string") continue;
288
+ const namespace = namespaceOf.get(name);
289
+ if (typeof namespace !== "string") continue;
290
+ referenceNamespace ??= namespace;
291
+ if (namespace !== referenceNamespace) {
292
+ fail("multicast_track", `${at}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} declares namespace ${JSON.stringify(namespace)}, not the catalog track's ${JSON.stringify(referenceNamespace)}`);
293
+ }
294
+ }
295
+ }
296
+
297
+ // One endpoint object per (S, G, port), and a manifestPort that is no port
298
+ // and no other manifestPort of its (S, G) (4.1, 7.2.6). The rule binds the
299
+ // endpoint whose manifestPort clashes; two equal tuples or two equal
300
+ // manifestPorts break it on both sides, so both are named.
301
+ const tupleOf = (index: number) => {
302
+ const endpoint = endpoints[index] as JsonObject;
303
+ const auth = endpoint["auth"];
304
+ return {
305
+ sg: JSON.stringify([sources[index]!.source ?? null, endpoint["groupAddress"]]),
306
+ port: endpoint["port"],
307
+ manifestPort: isObject(auth) ? auth["manifestPort"] : undefined,
308
+ };
309
+ };
310
+ for (let index = 0; index < endpoints.length; index++) {
311
+ if (!sources[index]) continue;
312
+ const own = tupleOf(index);
313
+ const at = `$.multicast.endpoints[${index}]`;
314
+ if (own.manifestPort !== undefined && own.manifestPort === own.port) {
315
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: "manifestPort must differ from the endpoint's own port", endpointIndex: index });
316
+ continue;
317
+ }
318
+ for (let other = 0; other < endpoints.length; other++) {
319
+ if (other === index || !sources[other]) continue;
320
+ const peer = tupleOf(other);
321
+ if (peer.sg !== own.sg) continue;
322
+ if (peer.port === own.port) {
323
+ issues.push({ code: "multicast_endpoint", path: `${at}.port`, message: `(S, G, port) is shared with endpoint ${other}; one endpoint object per multicast tuple`, endpointIndex: index });
324
+ break;
325
+ }
326
+ if (own.manifestPort !== undefined && (own.manifestPort === peer.port || own.manifestPort === peer.manifestPort)) {
327
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: `manifestPort is a port or manifestPort of endpoint ${other} on the same (S, G)`, endpointIndex: index });
328
+ break;
329
+ }
330
+ }
331
+ }
332
+ return issues;
333
+ }
334
+
335
+ /**
336
+ * Indices of the endpoints a receiver may use: none when a catalog-level
337
+ * issue leaves it no key set (7.2.6), otherwise every endpoint no issue
338
+ * names. Other receiver checks (group address, packet ids) still apply.
339
+ */
340
+ export function admittedMulticastEndpoints(
341
+ catalog: unknown,
342
+ options: { catalogNamespace?: string } = {},
343
+ ): ReadonlySet<number> {
344
+ const multicast = isObject(catalog) ? catalog["multicast"] : undefined;
345
+ const endpoints = isObject(multicast) && Array.isArray(multicast["endpoints"]) ? multicast["endpoints"] : [];
346
+ const issues = multicastCatalogIssues(catalog, options);
347
+ if (issues.some(issue => issue.endpointIndex === undefined)) return new Set();
348
+ const ignored = new Set(issues.map(issue => issue.endpointIndex));
349
+ return new Set(endpoints.map((_, index) => index).filter(index => !ignored.has(index)));
350
+ }
package/src/signalling.ts CHANGED
@@ -23,6 +23,8 @@
23
23
  import {
24
24
  ALFEC_MESSAGE_ID,
25
25
  FEC_CODE_RAPTORQ,
26
+ FEC_CODE_REED_SOLOMON,
27
+ MMTP_SIGNALING_PACKET_ID,
26
28
  PACKET_TYPE_SIGNALING,
27
29
  parseMMTPHeader,
28
30
  type MMTPHeader,
@@ -453,100 +455,112 @@ export function parseAlFecMessage(mmtpPacket: Uint8Array): AlFecMessage | null {
453
455
  }
454
456
 
455
457
  /**
456
- * Decoder geometry of one FEC flow under the Blockcast one-stage RaptorQ
457
- * profile: private_field = RaptorQ FEC OTI (RFC 6330 3.3.2-3.3.3, 12 bytes)
458
- * followed by the interleave depth (1 byte).
458
+ * Decoder geometry of one FEC flow's AL-FEC message entry under
459
+ * draft-ramadan-moq-mmt-01 Section 8.3 ("iso-ssbg1-v1"): one Asset, coding
460
+ * byte 0x14, fec_code_id_for_repair_flow 3 (RaptorQ) or 1 (Reed-Solomon),
461
+ * and no OTI (draft-ramadan-moq-mmt-01 Section 7.2). K, T and P come from
462
+ * the entry's own fields; a private field, if present, is ignored.
459
463
  */
460
464
  export interface AlFecRaptorQFlowConfig {
465
+ /** The flow's one Asset packet_id (number_of_assets is 1). */
461
466
  sourcePacketIds: number[]
462
467
  repairFlowId: number
468
+ /** `FEC_CODE_RAPTORQ` (3) or `FEC_CODE_REED_SOLOMON` (1). */
469
+ fecCodeId: number
463
470
  /** Always `SSBG_MODE_1` (`iso-ssbg1-v1`). */
464
471
  ssbgMode: number
465
- /** The coding byte's low bit as signalled (see AlFecFlow.fecPayloadIdMode). */
472
+ /** Always 0: the profile's coding byte is exactly 0x14. */
466
473
  fecPayloadIdMode: 0 | 1
474
+ /** T, from length_of_repair_symbol. */
467
475
  repairSymbolSize: number
476
+ /** K, from maximum_k_for_repair_flow. */
468
477
  maximumK: number
478
+ /** P, from maximum_p_for_repair_flow: the RSB_length total over every published layer. */
469
479
  maximumP: number
470
- interleaveDepth: number
471
- oti: Uint8Array
472
480
  protectionWindowTime: number
473
481
  protectionWindowSize: number
474
482
  }
475
483
 
476
- const RAPTORQ_PRIVATE_FIELD_LENGTH = 13
477
484
  const RAPTORQ_MAX_SOURCE_SYMBOLS = 56_403
478
485
  const REPAIR_SYMBOL_ID_MAX = 0x00ff_ffff
479
-
480
- function canonicalRaptorQOtiK(oti: Uint8Array, repairSymbolSize: number): number | null {
481
- if (oti.length !== 12 || oti[5] !== 0) return null
482
- const transferLength = (oti[0]! * 0x1_0000_0000) +
483
- (((oti[1]! << 24) | (oti[2]! << 16) | (oti[3]! << 8) | oti[4]!) >>> 0)
484
- const symbolSize = (oti[6]! << 8) | oti[7]!
485
- const sourceBlocks = oti[8]!
486
- const subBlocks = (oti[9]! << 8) | oti[10]!
487
- const alignment = oti[11]!
488
- if (!Number.isSafeInteger(transferLength) || transferLength <= 0 ||
489
- symbolSize !== repairSymbolSize || symbolSize === 0 || symbolSize % 8 !== 0 ||
490
- sourceBlocks !== 1 || subBlocks !== 1 || alignment !== 8 ||
491
- transferLength % symbolSize !== 0) {
492
- return null
493
- }
494
- const k = transferLength / symbolSize
495
- return Number.isInteger(k) && k >= 1 && k <= RAPTORQ_MAX_SOURCE_SYMBOLS ? k : null
496
- }
486
+ /** The 12-octet MMTP header plus the 2-octet length of the T - 2 construction (moq-fec-01 Section 7.3). */
487
+ const MIN_REPAIR_SYMBOL_SIZE = 14
488
+ const REED_SOLOMON_MAX_BLOCK = 255
497
489
 
498
490
  /**
499
- * Validate one parsed FEC flow against the Blockcast one-stage RaptorQ
500
- * profile and return its decoder geometry, or null when the flow is outside
501
- * the profile. Nothing is inferred: K comes from the OTI and must equal
502
- * maximum_k_for_repair_flow.
491
+ * Validate one parsed FEC flow against draft-ramadan-moq-mmt-01 Sections 8.3
492
+ * and 12.2 and return its decoder geometry, or null when the entry is
493
+ * outside them. Fail closed on everything else:
494
+ *
495
+ * - coding byte other than 0x14 (one-stage, ssbg_mode1, ffsrpts_flag 0,
496
+ * fec_payload_id_mode 0). 0x15 is fec_payload_id_mode 1 under Amd 1:2025,
497
+ * which "iso-ssbg1-v1" does not describe (moq-fec-01 Section 7.3);
498
+ * - number_of_assets other than 1;
499
+ * - fec_code_id_for_repair_flow other than 3 or 1, the retired Blockcast
500
+ * code 2 included (ISO/IEC 23008-10 Table 1);
501
+ * - T < 14, K = 0, P = 0, K + P - 1 > 2^24 - 1;
502
+ * - RaptorQ: T not a multiple of 8, or K > 56403;
503
+ * - Reed-Solomon: K + P > 255;
504
+ * - repair_flow_id 0 (the signalling flow) or the flow's own packet_id.
503
505
  *
504
- * The profile is `iso-ssbg1-v1`, whose AL-FEC coding byte is 0x14
505
- * (draft-ramadan-moq-fec §7.3; ISO/IEC 23008-1 Table C.3 as replaced by
506
- * Amd 1:2025): one-stage, ssbg_mode1, ffsrpts_flag 0, fec_payload_id_mode 0.
507
- * 0x15 is accepted too: its low bit is fec_payload_id_mode 1 under Amd
508
- * 1:2025 but reserved "1" in the unamended 2023 Table C.3, so a 2023 sender
509
- * of the same profile emits it. No later field depends on the bit, and each
510
- * source packet's FEC_type says whether it carries a Source FEC Payload ID,
511
- * so the bit is reported, not interpreted (BLO-35597 N1). Any other coding
512
- * byte is refused here, though `parseAlFecMessageBody` still reports it:
513
- * ssbg_mode0 (0x10/0x11, the retired `k-padded-v1` wire) carries no length
514
- * field; ffsrpts_flag=1 changes the source/repair packet trailer layout.
506
+ * Checks that span entries (another entry's packet_id, a duplicate
507
+ * repair_flow_id or Asset) are `alFecMessageFlowConfigs`'.
515
508
  */
516
509
  export function alFecRaptorQFlowConfig(flow: AlFecFlow): AlFecRaptorQFlowConfig | null {
517
510
  if (flow.fecCodingStructure !== FEC_CODING_STRUCTURE_ONE_STAGE || flow.repairFlows.length !== 1) return null
518
- if (flow.ssbgMode !== SSBG_MODE_1) return null
519
- if (flow.ffsrptsFlag !== 0) return null
511
+ if (flow.ssbgMode !== SSBG_MODE_1 || flow.ffsrptsFlag !== 0 || flow.fecPayloadIdMode !== 0) return null
512
+ if (flow.packetIds.length !== 1) return null
520
513
  const repair = flow.repairFlows[0]!
521
- if (repair.fecCodeId !== FEC_CODE_RAPTORQ) return null
522
- const privateField = repair.privateField
523
- if (!privateField || privateField.privateFlag !== 1 ||
524
- privateField.data.length !== RAPTORQ_PRIVATE_FIELD_LENGTH) {
525
- return null
526
- }
527
- const oti = privateField.data.slice(0, 12)
528
- const interleaveDepth = privateField.data[12]!
529
- const otiK = canonicalRaptorQOtiK(oti, flow.repairSymbolSize)
530
- if (otiK === null || interleaveDepth === 0) return null
531
- if (repair.maximumK !== otiK || repair.maximumP === 0 ||
532
- repair.maximumK + repair.maximumP - 1 > REPAIR_SYMBOL_ID_MAX) {
514
+ const { fecCodeId, maximumK: k, maximumP: p } = repair
515
+ const t = flow.repairSymbolSize
516
+ if (t < MIN_REPAIR_SYMBOL_SIZE || k < 1 || p < 1 || k + p - 1 > REPAIR_SYMBOL_ID_MAX) return null
517
+ if (fecCodeId === FEC_CODE_RAPTORQ) {
518
+ if (t % 8 !== 0 || k > RAPTORQ_MAX_SOURCE_SYMBOLS) return null
519
+ } else if (fecCodeId === FEC_CODE_REED_SOLOMON) {
520
+ if (k + p > REED_SOLOMON_MAX_BLOCK) return null
521
+ } else {
533
522
  return null
534
523
  }
524
+ if (repair.repairFlowId === MMTP_SIGNALING_PACKET_ID || repair.repairFlowId === flow.packetIds[0]) return null
535
525
  return {
536
526
  sourcePacketIds: [...flow.packetIds],
537
527
  repairFlowId: repair.repairFlowId,
528
+ fecCodeId,
538
529
  ssbgMode: flow.ssbgMode,
539
530
  fecPayloadIdMode: flow.fecPayloadIdMode,
540
- repairSymbolSize: flow.repairSymbolSize,
541
- maximumK: repair.maximumK,
542
- maximumP: repair.maximumP,
543
- interleaveDepth,
544
- oti,
531
+ repairSymbolSize: t,
532
+ maximumK: k,
533
+ maximumP: p,
545
534
  protectionWindowTime: repair.protectionWindowTime,
546
535
  protectionWindowSize: repair.protectionWindowSize,
547
536
  }
548
537
  }
549
538
 
539
+ /**
540
+ * `alFecRaptorQFlowConfig` for every entry of a message, index for index,
541
+ * plus the draft-ramadan-moq-mmt-01 Section 12.2 checks that span entries: an
542
+ * entry whose repair_flow_id is another entry's Asset packet_id, and every
543
+ * entry of two that name one repair_flow_id or list one Asset, is null.
544
+ */
545
+ export function alFecMessageFlowConfigs(message: AlFecMessageBody): (AlFecRaptorQFlowConfig | null)[] {
546
+ const assetCount = new Map<number, number>()
547
+ const repairCount = new Map<number, number>()
548
+ const bump = (map: Map<number, number>, key: number) => map.set(key, (map.get(key) ?? 0) + 1)
549
+ for (const flow of message.flows) {
550
+ for (const id of flow.packetIds) bump(assetCount, id)
551
+ for (const repair of flow.repairFlows) bump(repairCount, repair.repairFlowId)
552
+ }
553
+ return message.flows.map(flow => {
554
+ const config = alFecRaptorQFlowConfig(flow)
555
+ if (!config) return null
556
+ const [asset] = config.sourcePacketIds
557
+ if (assetCount.get(asset!) !== 1 || repairCount.get(config.repairFlowId) !== 1) return null
558
+ // Its own packet_id is already refused, so any count here is another entry's.
559
+ if (assetCount.has(config.repairFlowId)) return null
560
+ return config
561
+ })
562
+ }
563
+
550
564
  // ---------------------------------------------------------------------------
551
565
  // 10.6 — location, asset_id and identifier mapping
552
566
  // ---------------------------------------------------------------------------