@blockcast/mmt-base 0.1.0

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.
package/src/mmtp.ts ADDED
@@ -0,0 +1,746 @@
1
+ import {
2
+ MMTP_EXT_TYPE_ALTA_AUTH as _LEAF_MMTP_EXT_TYPE_ALTA_AUTH,
3
+ MMTP_EXT_TRAILER_HEADER_SIZE as _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE,
4
+ extractAltaTrailer as _leafExtractAltaTrailer,
5
+ type AltaTrailer as _LeafAltaTrailer,
6
+ } from '@blockcast/mmt-alta-parse'
7
+
8
+ /**
9
+ * @mmt/container - MMTP Parser
10
+ *
11
+ * MMTP (MMT Protocol) packet parser based on ISO/IEC 23008-1:2023 Section 9.2
12
+ *
13
+ * MMTP header format (12 bytes):
14
+ * - Byte 0: V(2) | C(1) | FEC_type(2) | r(1) | X(1) | R(1)
15
+ * - Byte 1: reserved(2) | packet_type(6)
16
+ * - Bytes 2-3: packet_id (big-endian)
17
+ * - Bytes 4-7: timestamp (big-endian, 32-bit)
18
+ * - Bytes 8-11: sequence_number (big-endian)
19
+ *
20
+ * FEC_type values:
21
+ * - 0: No FEC / source packet
22
+ * - 1: FEC mode 0 (source with FEC payload ID)
23
+ * - 2: FEC repair packet mode 0
24
+ * - 3: FEC repair packet mode 1
25
+ *
26
+ * @packageDocumentation
27
+ */
28
+
29
+ export interface MMTPHeader {
30
+ version: number
31
+ /** Packet type: 0x00=MPU, 0x02=Signaling, 0x03=Repair */
32
+ packetType: number
33
+ packetId: number
34
+ timestamp: bigint
35
+ sequenceNumber: number
36
+ payloadLength: number
37
+ fecType: number
38
+ /** C flag: header carries a 32-bit packet_counter. */
39
+ packetCounterFlag: boolean
40
+ packetCounter?: number
41
+ /** X flag: header carries an extension header and value. */
42
+ extensionFlag: boolean
43
+ extension?: { type: number; data: Uint8Array }
44
+ /** Byte offset at which the MMTP payload begins. */
45
+ headerLength: number
46
+ /** Random Access Point flag - indicates keyframe (ISO 23008-1, byte 0 bit 0) */
47
+ rapFlag: boolean
48
+ }
49
+
50
+ export interface MPUHeader {
51
+ mpuSequenceNumber: number
52
+ fragmentationIndicator: number // FI: 0=complete, 1=first, 2=middle, 3=last
53
+ /** 8-bit MPU fragment_counter from byte 3. */
54
+ fragmentCounter: number
55
+ /** T flag: 1=timed media (14-byte MFU DU header), 0=non-timed (4-byte header) */
56
+ timedFlag: number
57
+ /** A flag: aggregated MPU payload. This strict profile requires A=0. */
58
+ aggregationFlag: boolean
59
+ /** MPU payload_length (bytes 0-1): bytes after the length field, including
60
+ * the remaining six MPU-header bytes and all data-unit bytes. */
61
+ payloadLength: number
62
+ }
63
+
64
+ export interface MFUDuHeader {
65
+ movieFragmentSequenceNumber: number
66
+ sampleNumber: number
67
+ offset: number
68
+ priority: number
69
+ dependencyCounter: number
70
+ }
71
+
72
+ export interface MMTPPacket {
73
+ header: MMTPHeader
74
+ payload: Uint8Array
75
+ }
76
+
77
+ export const MMTP_HEADER_SIZE = 12
78
+ export const MPU_HEADER_SIZE = 8
79
+ export const MFU_DU_HEADER_SIZE_TIMED = 14 // T=1: timed media (video/audio samples)
80
+ export const MFU_DU_HEADER_SIZE_NONTIMED = 4 // T=0: non-timed media (item_id only)
81
+
82
+ const MPU_LENGTH_FIELD_SIZE = 2
83
+ const MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE
84
+ const SOURCE_FEC_PAYLOAD_ID_SIZE = 4
85
+
86
+ // MMTP Packet Types (ISO/IEC 23008-1:2023 Section 9.2.2)
87
+ export const PACKET_TYPE_MPU = 0x00
88
+ export const PACKET_TYPE_SIGNALING = 0x02
89
+ export const PACKET_TYPE_REPAIR = 0x03
90
+
91
+ // AL-FEC Signaling Message ID (ISO/IEC 23008-1:2023 Amendment 1:2025)
92
+ export const ALFEC_MESSAGE_ID = 0x0203
93
+
94
+ // FEC Code IDs
95
+ export const FEC_CODE_XOR = 1
96
+ export const FEC_CODE_RAPTORQ = 2
97
+
98
+ /**
99
+ * Parse MMTP header from buffer
100
+ */
101
+ export function parseMMTPHeader(buffer: Uint8Array): MMTPHeader {
102
+ if (buffer.length < MMTP_HEADER_SIZE) {
103
+ throw new Error(`MMTP packet too small: ${buffer.length} bytes`)
104
+ }
105
+
106
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)
107
+
108
+ const version = (buffer[0]! >> 6) & 0x03
109
+ if (version !== 0) {
110
+ throw new Error(`Unsupported MMTP version: ${version}`)
111
+ }
112
+
113
+ // Extract FEC type from byte 0, bits 3-4
114
+ const fecType = (buffer[0]! >> 3) & 0x03
115
+ const packetCounterFlag = (buffer[0]! & 0x20) !== 0
116
+ const extensionFlag = (buffer[0]! & 0x02) !== 0
117
+
118
+ // Extract RAP flag from byte 0, bit 0 (R bit - Random Access Point)
119
+ const rapFlag = (buffer[0]! & 0x01) === 1
120
+
121
+ // ISO/IEC 23008-1:2023 Figure 8 (V=0) places reserved(2) before
122
+ // packet_type(6), so packet_type occupies the low six bits of byte 1.
123
+ const packetType = buffer[1]! & 0x3F
124
+
125
+ let offset = 2
126
+
127
+ // Packet ID (2 bytes, big-endian)
128
+ const packetId = view.getUint16(offset, false)
129
+ offset += 2
130
+
131
+ // Timestamp (4 bytes, big-endian)
132
+ const timestamp = BigInt(view.getUint32(offset, false))
133
+ offset += 4
134
+
135
+ // Sequence number (4 bytes, big-endian)
136
+ const sequenceNumber = view.getUint32(offset, false)
137
+ offset += 4
138
+
139
+ let packetCounter: number | undefined
140
+ if (packetCounterFlag) {
141
+ if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in packet_counter')
142
+ packetCounter = view.getUint32(offset, false)
143
+ offset += 4
144
+ }
145
+
146
+ let extension: { type: number; data: Uint8Array } | undefined
147
+ if (extensionFlag) {
148
+ if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in header extension')
149
+ const type = view.getUint16(offset, false)
150
+ const length = view.getUint16(offset + 2, false)
151
+ offset += 4
152
+ if (offset + length > buffer.length) throw new Error('MMTP packet truncated in header extension value')
153
+ extension = { type, data: buffer.subarray(offset, offset + length) }
154
+ offset += length
155
+ }
156
+
157
+ return {
158
+ version,
159
+ packetType,
160
+ packetId,
161
+ timestamp,
162
+ sequenceNumber,
163
+ payloadLength: buffer.length - offset,
164
+ fecType,
165
+ packetCounterFlag,
166
+ packetCounter,
167
+ extensionFlag,
168
+ extension,
169
+ headerLength: offset,
170
+ rapFlag,
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Unwrap MMTP packet to extract payload
176
+ */
177
+ export function unwrapMMTP(buffer: Uint8Array): MMTPPacket {
178
+ const header = parseMMTPHeader(buffer)
179
+ const payload = buffer.subarray(header.headerLength)
180
+
181
+ return { header, payload }
182
+ }
183
+
184
+ /**
185
+ * Parse MPU header from payload
186
+ * ISO/IEC 23008-1:2023 Section 9.2.3.3
187
+ *
188
+ * MPU Header format (8 bytes) as written by FFmpeg/libmmt:
189
+ * - Bytes 0-1: payload_length (16 bits, big-endian)
190
+ * - Byte 2: FT(4) | T(1) | FI(2) | A(1)
191
+ * - Byte 3: fragment_counter (8 bits)
192
+ * - Bytes 4-7: MPU_sequence_number (32 bits, big-endian)
193
+ */
194
+ export function parseMPUHeader(payload: Uint8Array): MPUHeader {
195
+ if (payload.length < MPU_HEADER_SIZE) {
196
+ throw new Error(`Payload too small for MPU header: ${payload.length} bytes`)
197
+ }
198
+
199
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength)
200
+
201
+ // Bytes 0-1: payload_length (16 bits, big-endian)
202
+ const payloadLength = view.getUint16(0, false)
203
+
204
+ // Byte 2: FT(4) | T(1) | FI(2) | A(1)
205
+ const flagsByte = payload[2]!
206
+ const timedFlag = (flagsByte >> 3) & 0x01
207
+ const fragmentationIndicator = (flagsByte >> 1) & 0x03
208
+ const aggregationFlag = (flagsByte & 0x01) !== 0
209
+
210
+ // Byte 3: fragment_counter (8 bits). The high bit is part of the counter in
211
+ // the current libmmt/FFmpeg writer ABI.
212
+ const fragmentCounter = payload[3]!
213
+
214
+ // Bytes 4-7: MPU_sequence_number (32 bits, big-endian)
215
+ const mpuSequenceNumber = view.getUint32(4, false)
216
+
217
+ return {
218
+ mpuSequenceNumber,
219
+ fragmentationIndicator,
220
+ fragmentCounter,
221
+ timedFlag,
222
+ aggregationFlag,
223
+ payloadLength,
224
+ }
225
+ }
226
+
227
+ export function parseTimedMfuDuHeader(payload: Uint8Array, offset: number): MFUDuHeader | null {
228
+ if (offset < 0 || offset + MFU_DU_HEADER_SIZE_TIMED > payload.length) return null
229
+ const view = new DataView(payload.buffer, payload.byteOffset + offset, MFU_DU_HEADER_SIZE_TIMED)
230
+ return {
231
+ movieFragmentSequenceNumber: view.getUint32(0, false),
232
+ sampleNumber: view.getUint32(4, false),
233
+ offset: view.getUint32(8, false),
234
+ priority: payload[offset + 12]!,
235
+ dependencyCounter: payload[offset + 13]!,
236
+ }
237
+ }
238
+
239
+ interface MfuPayloadLayout {
240
+ hasMfuDuHeader: boolean
241
+ mfuOffset: number
242
+ dataEnd: number
243
+ }
244
+
245
+ function resolveMfuPayloadLayout(
246
+ mpu: MPUHeader,
247
+ fragmentType: number,
248
+ payload: Uint8Array,
249
+ ): MfuPayloadLayout | null {
250
+ if (mpu.payloadLength < MPU_HEADER_REMAINDER_SIZE) return null
251
+
252
+ // ISO/IEC 23008-1 defines payload_length from immediately after its own
253
+ // two-byte field. It therefore includes the remaining six MPU-header bytes.
254
+ const declaredEnd = MPU_LENGTH_FIELD_SIZE + mpu.payloadLength
255
+ if (declaredEnd > payload.length) return null
256
+
257
+ const hasHeader = fragmentType === 2 && mpu.fragmentationIndicator <= 1
258
+ const mfuHeaderSize = mpu.timedFlag ? MFU_DU_HEADER_SIZE_TIMED : MFU_DU_HEADER_SIZE_NONTIMED
259
+ const mfuOffset = MPU_HEADER_SIZE + (hasHeader ? mfuHeaderSize : 0)
260
+ if (mfuOffset >= declaredEnd) return null
261
+
262
+ return {
263
+ hasMfuDuHeader: hasHeader,
264
+ mfuOffset,
265
+ dataEnd: declaredEnd,
266
+ }
267
+ }
268
+
269
+ function isEmptyOrExactAltaTrailer(payload: Uint8Array, start: number, end: number): boolean {
270
+ if (start === end) return true
271
+ if (start < 0 || end > payload.length || start + _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE > end) {
272
+ return false
273
+ }
274
+
275
+ const view = new DataView(
276
+ payload.buffer,
277
+ payload.byteOffset + start,
278
+ end - start,
279
+ )
280
+ if (view.getUint16(0, false) !== _LEAF_MMTP_EXT_TYPE_ALTA_AUTH) return false
281
+
282
+ const authLength = view.getUint16(2, false)
283
+ return start + _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE + authLength === end
284
+ }
285
+
286
+ interface DeclaredTrailerLayout {
287
+ hasFecId: boolean
288
+ }
289
+
290
+ function resolveDeclaredTrailers(
291
+ payload: Uint8Array,
292
+ declaredEnd: number,
293
+ fecType: number,
294
+ options?: { skipFecId?: boolean },
295
+ ): DeclaredTrailerLayout | null {
296
+ if (declaredEnd > payload.length) return null
297
+
298
+ if (options?.skipFecId) {
299
+ return isEmptyOrExactAltaTrailer(payload, declaredEnd, payload.length)
300
+ ? { hasFecId: false }
301
+ : null
302
+ }
303
+
304
+ if (fecType === 1) {
305
+ const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE
306
+ if (fecStart < declaredEnd || !isEmptyOrExactAltaTrailer(payload, declaredEnd, fecStart)) {
307
+ return null
308
+ }
309
+ return { hasFecId: true }
310
+ }
311
+ if (fecType !== 0) return null
312
+
313
+ if (isEmptyOrExactAltaTrailer(payload, declaredEnd, payload.length)) {
314
+ return { hasFecId: false }
315
+ }
316
+
317
+ return null
318
+ }
319
+
320
+ /**
321
+ * Extract NAL unit payload from MMTP packet
322
+ */
323
+ export function extractNALUnit(mmtpPacket: Uint8Array): Uint8Array {
324
+ const extraction = extractMFUPayload(mmtpPacket)
325
+ if (!extraction) throw new Error('Malformed MMTP MPU payload')
326
+ return extraction.data
327
+ }
328
+
329
+ /** Result of extracting MFU payload from an MMTP packet */
330
+ export interface MFUExtraction {
331
+ /** MMTP header fields */
332
+ header: MMTPHeader
333
+ /** MPU header fields */
334
+ mpu: MPUHeader
335
+ /** Fragment type (FT field, 4 bits): 0=metadata, 2=MFU data */
336
+ fragmentType: number
337
+ /** MFU payload data (video/audio bytes, headers stripped, FEC ID excluded) */
338
+ data: Uint8Array
339
+ /** Parsed timed MFU DU header when present, otherwise null */
340
+ mfuDuHeader: MFUDuHeader | null
341
+ /** Non-timed MFU Item_ID when the 4-byte DU header is present. */
342
+ itemId: number | null
343
+ /** Source FEC Payload ID if present (`FEC_type == 1`), or null */
344
+ fecPayloadId: { ssId: number } | null
345
+ }
346
+
347
+ /**
348
+ * Extract MFU payload from a raw MMTP packet.
349
+ *
350
+ * Handles all the byte arithmetic for:
351
+ * - MMTP header (12 bytes)
352
+ * - MPU sub-header (8 bytes, payloadLength field)
353
+ * - MFU DU header (14 bytes timed / 4 bytes non-timed, only for FI ≤ 1)
354
+ * - Source FEC Payload ID (4 bytes at end, only when `FEC_type == 1`)
355
+ *
356
+ * `payloadLength` is the ISO length-after-field value: six remaining MPU-header
357
+ * bytes, then the MFU DU header when present, then media. ALTA and Source FEC
358
+ * trailers are outside that declared span and must consume the exact suffix.
359
+ *
360
+ * @param mmtpPacket Raw MMTP packet (from multicast or MoQ)
361
+ * @param options.skipFecId When true, do NOT subtract the 4-byte Source FEC Payload ID
362
+ * from the payload boundary, even if fecType >= 1 in the MMTP header. Use this for
363
+ * FEC-recovered symbols where the FEC PID was already stripped before WASM decoding
364
+ * but the fecType bits in byte 0 still reflect the original packet (FEC Type=1 per
365
+ * draft-ramadan-moq-mmt-00 §3.1).
366
+ * @returns Extracted MFU data + metadata, or null if packet is too small
367
+ */
368
+ export function extractMFUPayload(
369
+ mmtpPacket: Uint8Array,
370
+ options?: { skipFecId?: boolean },
371
+ ): MFUExtraction | null {
372
+ if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null
373
+
374
+ let header: MMTPHeader
375
+ try {
376
+ header = parseMMTPHeader(mmtpPacket)
377
+ } catch {
378
+ return null
379
+ }
380
+ if (header.packetType !== PACKET_TYPE_MPU) return null
381
+ const payload = mmtpPacket.subarray(header.headerLength)
382
+ if (payload.length < MPU_HEADER_SIZE) return null
383
+ const mpu = parseMPUHeader(payload)
384
+ if (mpu.aggregationFlag) return null
385
+
386
+ // Fragment type from byte 2 upper nibble (not returned by parseMPUHeader)
387
+ const fragmentType = (payload[2]! >> 4) & 0x0f
388
+
389
+ const layout = resolveMfuPayloadLayout(
390
+ mpu,
391
+ fragmentType,
392
+ payload,
393
+ )
394
+ if (!layout) return null
395
+
396
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options)
397
+ if (!trailerLayout) return null
398
+
399
+ const mfuDuHeaderPresent = layout.hasMfuDuHeader
400
+ const mfuOffset = layout.mfuOffset
401
+ const dataEnd = layout.dataEnd
402
+
403
+ if (mfuOffset >= dataEnd) return null
404
+
405
+ const mfuDuHeader =
406
+ mfuDuHeaderPresent && mpu.timedFlag === 1
407
+ ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE)
408
+ : null
409
+ const itemId =
410
+ mfuDuHeaderPresent && mpu.timedFlag === 0
411
+ ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false)
412
+ : null
413
+
414
+ const data = payload.subarray(mfuOffset, dataEnd)
415
+
416
+ const fecPayloadId = trailerLayout.hasFecId
417
+ ? {
418
+ ssId: new DataView(
419
+ mmtpPacket.buffer,
420
+ mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE,
421
+ SOURCE_FEC_PAYLOAD_ID_SIZE,
422
+ ).getUint32(0, false),
423
+ }
424
+ : null
425
+
426
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId }
427
+ }
428
+
429
+ /**
430
+ * Extract timestamp from MMTP packet
431
+ */
432
+ export function extractTimestamp(mmtpPacket: Uint8Array): bigint {
433
+ const { header } = unwrapMMTP(mmtpPacket)
434
+ return header.timestamp
435
+ }
436
+
437
+ /**
438
+ * Check if MMTP packet is an FEC repair packet
439
+ * FEC_type 2 and 3 are repair packets
440
+ */
441
+ export function isFecRepairPacket(mmtpPacket: Uint8Array): boolean {
442
+ if (mmtpPacket.length < 1) return false
443
+ const fecType = (mmtpPacket[0]! >> 3) & 0x03
444
+ return fecType >= 2
445
+ }
446
+
447
+ /**
448
+ * Extract Source FEC Payload ID (SS_ID) from the last 4 bytes of an MMTP
449
+ * source packet per ISO/IEC 23008-1:2023 Section C.5.2 Figure C.10.
450
+ *
451
+ * SS_ID is a flat 32-bit monotonic counter (incremented by 1 per packet
452
+ * for ssbg_mode0 and ssbg_mode1). Block membership and ESI are derived
453
+ * at recovery time from repair packet SS_Start and SSB_length:
454
+ * SBN = floor(SS_ID / K), ESI = SS_ID % K
455
+ * SS_Start = SBN * K (first SS_ID of the block)
456
+ *
457
+ * This matches FFmpeg moqenc_mmt.c, the drafts (draft-ramadan-moq-fec §6.2),
458
+ * and ATSC A/331 §8.1.2.5 which defers to ISO 23008-1 Annex C.
459
+ */
460
+ export function extractFecPayloadId(mmtpPacket: Uint8Array): { ssId: number } | null {
461
+ if (!hasSourceFecPayloadId(mmtpPacket)) return null
462
+ // Flat 4-byte SS_ID: encoder writes block_id * K + symbol_id
463
+ const off = mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE
464
+ const view = new DataView(
465
+ mmtpPacket.buffer,
466
+ mmtpPacket.byteOffset + off,
467
+ SOURCE_FEC_PAYLOAD_ID_SIZE,
468
+ )
469
+ return { ssId: view.getUint32(0, false) }
470
+ }
471
+
472
+ /**
473
+ * Return true when FEC_type=1 and the exact suffix after the ISO-declared MPU
474
+ * payload contains a four-byte Source FEC Payload ID.
475
+ */
476
+ export function hasSourceFecPayloadId(mmtpPacket: Uint8Array): boolean {
477
+ if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return false
478
+
479
+ let header: MMTPHeader
480
+ try {
481
+ header = parseMMTPHeader(mmtpPacket)
482
+ } catch {
483
+ return false
484
+ }
485
+ if (header.packetType !== PACKET_TYPE_MPU) return false
486
+
487
+ const payload = mmtpPacket.subarray(header.headerLength)
488
+ if (payload.length < MPU_HEADER_SIZE) return false
489
+ const mpu = parseMPUHeader(payload)
490
+ if (mpu.payloadLength < MPU_HEADER_REMAINDER_SIZE) return false
491
+ const declaredEnd = MPU_LENGTH_FIELD_SIZE + mpu.payloadLength
492
+ return resolveDeclaredTrailers(payload, declaredEnd, header.fecType)?.hasFecId ?? false
493
+ }
494
+
495
+ /**
496
+ * MMTP header-extension ext_type assigned to the detached ALTA authenticator
497
+ * trailer (Path 2 / 08-07). Carried in an `[ext_type][ext_length][auth]`
498
+ * block appended after the MPU's declared payload bytes, before the 4-byte
499
+ * Source FEC Payload ID. MMTP X-bit stays 0 — non-ALTA MMTP receivers treat
500
+ * the trailer as bytes past `payload_length` and skip it (per ISO 23008-1
501
+ * §9.2.2 "may be discarded without impacting correct processing").
502
+ */
503
+ // Re-export the ALTA trailer helper from the zero-dep leaf package. The leaf
504
+ // owns the implementation so container and FEC consumers share one parser
505
+ // without creating a package cycle.
506
+ export const MMTP_EXT_TYPE_ALTA_AUTH = _LEAF_MMTP_EXT_TYPE_ALTA_AUTH
507
+ export const MMTP_EXT_TRAILER_HEADER_SIZE = _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE
508
+ export type AltaTrailer = _LeafAltaTrailer
509
+ export const extractAltaTrailer = _leafExtractAltaTrailer
510
+
511
+ /** Size of Repair FEC Payload ID per ISO/IEC 23008-1 Section C.5.3 */
512
+ export const REPAIR_FEC_PID_SIZE = 13
513
+
514
+ /** Parse the 13-byte Repair FEC Payload ID after the complete dynamic MMTP header. */
515
+ function readRepairFecPayloadIdFields(mmtpPacket: Uint8Array): {
516
+ packetId: number; ssStart: number; rsbLength: number; rsId: number; ssbLength: number; dataOffset: number
517
+ } | null {
518
+ let header: MMTPHeader
519
+ try {
520
+ header = parseMMTPHeader(mmtpPacket)
521
+ } catch {
522
+ return null
523
+ }
524
+ if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2) return null
525
+
526
+ const off = header.headerLength
527
+ if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE) return null
528
+ const view = new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + off, REPAIR_FEC_PID_SIZE)
529
+ const ssStart = view.getUint32(0, false) // 32 bits
530
+ const rsbLength = (mmtpPacket[off + 4]! << 16) | (mmtpPacket[off + 5]! << 8) | mmtpPacket[off + 6]! // 24 bits
531
+ const rsId = (mmtpPacket[off + 7]! << 16) | (mmtpPacket[off + 8]! << 8) | mmtpPacket[off + 9]! // 24 bits
532
+ const ssbLength = (mmtpPacket[off + 10]! << 16) | (mmtpPacket[off + 11]! << 8) | mmtpPacket[off + 12]! // 24 bits
533
+ return {
534
+ packetId: header.packetId,
535
+ ssStart,
536
+ rsbLength,
537
+ rsId,
538
+ ssbLength,
539
+ dataOffset: off + REPAIR_FEC_PID_SIZE,
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Extract Repair FEC Payload ID from a raw-multicast MMTP repair packet.
545
+ * Per ISO/IEC 23008-1:2023 Section C.5.3 (ssbg_mode0, one-stage, no FFSRP_TS):
546
+ * [MMTP header][SS_Start:4][RSB_length:3][RS_ID:3][SSB_length:3][repair data]
547
+ * OTI is delivered via AL-FEC signaling message (Table C.3), not per-packet.
548
+ *
549
+ * Byte 1 is reserved(2)|packet_type(6) for V=0, so repair type 0x03 is 0x03.
550
+ * Pre-migration high-bits bytes (0x0c) are rejected — no compatibility decode.
551
+ */
552
+ export function extractRepairFecPayloadId(mmtpPacket: Uint8Array): {
553
+ ssStart: number; rsbLength: number; rsId: number; ssbLength: number
554
+ } | null {
555
+ const fields = readRepairFecPayloadIdFields(mmtpPacket)
556
+ if (!fields) return null
557
+ return {
558
+ ssStart: fields.ssStart,
559
+ rsbLength: fields.rsbLength,
560
+ rsId: fields.rsId,
561
+ ssbLength: fields.ssbLength,
562
+ }
563
+ }
564
+
565
+ /** Parsed MoQ repair frame per ISO/IEC 23008-1 Section C.4.3 + C.5.3 */
566
+ export interface MoqRepairFrame {
567
+ /** MMTP packetId (1=video, 2=audio) — for routing to correct FEC decoder */
568
+ packetId: number
569
+ /** SS_Start (32 bits): SS_ID of first source symbol in block */
570
+ ssStart: number
571
+ /** RSB_length (24 bits): number of repair symbols (P) */
572
+ rsbLength: number
573
+ /** RS_ID (24 bits): repair symbol index (0-based) */
574
+ rsId: number
575
+ /** SSB_length (24 bits): number of source symbols (K) */
576
+ ssbLength: number
577
+ /** Repair symbol data after the dynamic MMTP header and 13-byte FEC payload ID. */
578
+ symbolData: Uint8Array
579
+ }
580
+
581
+ /**
582
+ * Parse a MoQ repair frame (ISO/IEC 23008-1 Annex C format).
583
+ *
584
+ * Wire format per ISO 23008-1 §C.4.3 + §C.5.3:
585
+ * MMTP Header: fixed 12 bytes plus C/X optional fields
586
+ * then SS_Start (4 bytes) → block identifier
587
+ * then RSB_length (3 bytes) → P
588
+ * then RS_ID (3 bytes) → ESI = K + RS_ID
589
+ * then SSB_length (3 bytes) → K
590
+ * then Repair Symbol Data (T bytes)
591
+ *
592
+ * @param frame - Raw MoQ repair frame bytes
593
+ * @returns Parsed frame or null if invalid
594
+ */
595
+ export function parseMoqRepairFrame(frame: Uint8Array): MoqRepairFrame | null {
596
+ const repairId = readRepairFecPayloadIdFields(frame)
597
+ if (!repairId) return null
598
+
599
+ const symbolData = frame.subarray(repairId.dataOffset)
600
+ if (
601
+ repairId.rsbLength === 0 ||
602
+ repairId.ssbLength === 0 ||
603
+ repairId.rsId >= repairId.rsbLength ||
604
+ symbolData.length === 0
605
+ ) return null
606
+
607
+ return {
608
+ packetId: repairId.packetId,
609
+ ssStart: repairId.ssStart,
610
+ rsbLength: repairId.rsbLength,
611
+ rsId: repairId.rsId,
612
+ ssbLength: repairId.ssbLength,
613
+ symbolData,
614
+ }
615
+ }
616
+
617
+ /**
618
+ * AL-FEC signaling configuration parsed from ISO/IEC 23008-1:2023 Table C.3 message.
619
+ */
620
+ export interface AlFecConfig {
621
+ fecCodeId: number
622
+ fecPayloadIdMode: 0
623
+ repairSymbolSize: number
624
+ maximumK: number
625
+ maximumP: number
626
+ interleaveDepth: number
627
+ oti: Uint8Array
628
+ }
629
+
630
+ function canonicalRaptorQOtiK(oti: Uint8Array, repairSymbolSize: number): number | null {
631
+ if (oti.length !== 12 || oti[5] !== 0) return null
632
+ const transferLength = (oti[0]! * 0x1_0000_0000) +
633
+ (((oti[1]! << 24) | (oti[2]! << 16) | (oti[3]! << 8) | oti[4]!) >>> 0)
634
+ const symbolSize = (oti[6]! << 8) | oti[7]!
635
+ const sourceBlocks = oti[8]!
636
+ const subBlocks = (oti[9]! << 8) | oti[10]!
637
+ const alignment = oti[11]!
638
+ if (!Number.isSafeInteger(transferLength) || transferLength <= 0 ||
639
+ symbolSize !== repairSymbolSize || symbolSize === 0 || symbolSize % 8 !== 0 ||
640
+ sourceBlocks !== 1 || subBlocks !== 1 || alignment !== 8 ||
641
+ transferLength % symbolSize !== 0) {
642
+ return null
643
+ }
644
+ const k = transferLength / symbolSize
645
+ return Number.isInteger(k) && k >= 1 && k <= 56_403 ? k : null
646
+ }
647
+
648
+ /**
649
+ * Parse AL-FEC signaling message from a full MMTP signaling packet.
650
+ *
651
+ * Wire format (ISO/IEC 23008-1:2023 Table C.3, Amendment 1:2025):
652
+ * [12-byte MMTP header (packet_type=0x02)]
653
+ * message_id(2) = 0x0203
654
+ * version(1)
655
+ * message_length(2) = length of remaining payload
656
+ * flags(1) = fec_flag(1) | private_fec_flag(1) | reserved(6)
657
+ * fec_flow_descriptor:
658
+ * length(2)
659
+ * num_flows(1)
660
+ * per flow:
661
+ * fec_flow_id(1), source_flow_id(1), num_assets(1), packet_ids(2*N),
662
+ * coding_params(1), repair_symbol_size(2),
663
+ * [one-stage]: repair_flow_id(2), fec_code_id(1),
664
+ * [private_fec_flag]: private_header(1){flag(1)|len(7)},
665
+ * current RaptorQ profile OTI(12) + interleave_depth(1)
666
+ * max_k(3), max_p(3), protection_window_time(4), protection_window_size(4)
667
+ *
668
+ * @param mmtpPacket Full MMTP packet including 12-byte header
669
+ * @returns Parsed config or null if not an AL-FEC signaling message
670
+ */
671
+ export function parseAlFecMessage(mmtpPacket: Uint8Array): AlFecConfig | null {
672
+ if (mmtpPacket.length < MMTP_HEADER_SIZE + 9) return null
673
+ let header: MMTPHeader
674
+ try {
675
+ header = parseMMTPHeader(mmtpPacket)
676
+ } catch {
677
+ return null
678
+ }
679
+ if (header.packetType !== PACKET_TYPE_SIGNALING || header.fecType !== 0) return null
680
+ const payload = mmtpPacket.subarray(header.headerLength)
681
+ if (payload.length < 9) return null
682
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength)
683
+ let off = 0
684
+
685
+ const messageId = view.getUint16(off, false); off += 2
686
+ if (messageId !== ALFEC_MESSAGE_ID) return null
687
+ const version = payload[off]!; off += 1
688
+ const messageLength = view.getUint16(off, false); off += 2
689
+ if (version !== 1 || messageLength === 0 || messageLength !== payload.length - off) return null
690
+
691
+ const flags = payload[off]!; off += 1
692
+ const fecFlag = (flags >> 7) & 1
693
+ const privateFecFlag = (flags >> 6) & 1
694
+ if (fecFlag !== 1 || privateFecFlag !== 1 || (flags & 0x3f) !== 0x3f) return null
695
+
696
+ if (off + 2 > payload.length) return null
697
+ const descriptorLength = view.getUint16(off, false); off += 2
698
+ const descriptorEnd = off + descriptorLength
699
+ if (descriptorLength === 0 || descriptorEnd !== payload.length) return null
700
+
701
+ const numFlows = payload[off]!; off += 1
702
+ if (numFlows !== 1 || off + 3 > descriptorEnd) return null
703
+
704
+ off += 2 // fec_flow_id, source_flow_id
705
+ const numAssets = payload[off]!; off += 1
706
+ if (numAssets === 0 || off + (numAssets * 2) > descriptorEnd) return null
707
+ off += numAssets * 2
708
+
709
+ if (off + 3 > descriptorEnd) return null
710
+ const codingParams = payload[off]!; off += 1
711
+ const fecCodingStructure = (codingParams >> 4) & 0x0f
712
+ const ssbgMode = (codingParams >> 2) & 0x03
713
+ const ffsrptsFlag = (codingParams >> 1) & 0x01
714
+ const fecPayloadIdMode = codingParams & 0x01
715
+ if (fecCodingStructure !== 1 || ssbgMode !== 0 || ffsrptsFlag !== 0 || fecPayloadIdMode !== 0) {
716
+ return null
717
+ }
718
+ const repairSymbolSize = view.getUint16(off, false); off += 2
719
+ if (repairSymbolSize === 0 || repairSymbolSize % 8 !== 0) return null
720
+
721
+ if (off + 4 > descriptorEnd) return null
722
+ off += 2 // Amendment 1:2025 replaces Table C.3 with a 16-bit repair_flow_id
723
+ const fecCodeId = payload[off]!; off += 1
724
+ if (fecCodeId !== FEC_CODE_RAPTORQ) return null
725
+ const privateHeader = payload[off]!; off += 1
726
+ const privateFlag = privateHeader >> 7
727
+ const privateFieldLength = privateHeader & 0x7f
728
+ if (privateFlag !== 1 || privateFieldLength !== 13 || off + 13 > descriptorEnd) return null
729
+ const oti = payload.slice(off, off + 12); off += 12
730
+ const interleaveDepth = payload[off]!; off += 1
731
+ const otiK = canonicalRaptorQOtiK(oti, repairSymbolSize)
732
+ if (otiK === null || interleaveDepth === 0) return null
733
+
734
+ if (off + 14 !== descriptorEnd) return null
735
+ const maximumK = (payload[off]! << 16) | (payload[off + 1]! << 8) | payload[off + 2]!
736
+ off += 3
737
+ const maximumP = (payload[off]! << 16) | (payload[off + 1]! << 8) | payload[off + 2]!
738
+ off += 3
739
+ if (maximumK !== otiK || maximumP === 0 || maximumK + maximumP - 1 > 0x00ff_ffff) {
740
+ return null
741
+ }
742
+ off += 8 // protection_window_time, protection_window_size
743
+ if (off !== descriptorEnd) return null
744
+
745
+ return { fecCodeId, fecPayloadIdMode, repairSymbolSize, maximumK, maximumP, interleaveDepth, oti }
746
+ }