mpeg-ps 0.5.0

MPEG-2 Program Stream parser — pack header, system header, program stream map (ISO/IEC 13818-1 §2.5).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Program Stream Map — ISO/IEC 13818-1 §2.5.4, Table 2-41.
//!
//! The PSM provides a mapping from `stream_type`/`elementary_stream_id`
//! to descriptors, tied to the Program Stream with a CRC-32 trailer.
//! It uses start-code prefix `0x000001` + `map_stream_id` `0xBC`.

use alloc::vec::Vec;

use crate::error::{Error, Result};
use broadcast_common::{Parse, Serialize, crc32_mpeg2};

/// `packet_start_code_prefix` — `0x000001`.
pub const PACKET_START_CODE_PREFIX: u32 = 0x00_0001;
/// `map_stream_id` — `0xBC`, combined with the prefix forms the PSM start code.
pub const MAP_STREAM_ID: u8 = 0xBC;
/// Combined PSM start code: `0x000001BC`.
pub const PSM_START_CODE: u32 = (PACKET_START_CODE_PREFIX << 8) | MAP_STREAM_ID as u32;

/// Bytes before the map body: prefix(3) + map_stream_id(1) + psm_length(2) = 6.
const PREFIX_LEN: usize = 6;

/// `program_stream_map_length` upper bound (ISO/IEC 13818-1 Table 2-41).
const MAP_LENGTH_MAX: usize = 1018;
/// Bytes after the prefix that are always present: flags(1) + reserved(1) +
/// `program_stream_info_length`(2) + `elementary_stream_map_length`(2).
const FIXED_BODY_LEN: usize = 6;
/// CRC-32 trailer length (Table 2-41).
const CRC_LEN: usize = 4;
/// `stream_type`(1) + `elementary_stream_id`(1) + `ES_info_length`(2).
const ES_ENTRY_HEADER_LEN: usize = 4;
/// Pseudo descriptor carrying `elementary_stream_id_extension` (Table 2-41):
/// tag(1) + length(1) + marker+extension(1).
const PSEUDO_DESCRIPTOR_LEN: usize = 3;
/// `pseudo_descriptor_tag` — Table 2-41 allows any value.
const PSEUDO_DESCRIPTOR_TAG: u8 = 0x00;
/// Marker bit in the `elementary_stream_id_extension` byte (Table 2-41).
const MARKER_BIT: u8 = 0x80;
/// 7-bit `elementary_stream_id_extension`.
const EXTENSION_MASK: u8 = 0x7F;
/// `flags` byte reserved bit 5 — conventionally set (Table 2-41).
const FLAGS_RESERVED_BIT: u8 = 0x20;
/// `program_stream_map_version` width in bits (Table 2-41).
const VERSION_BITS: u32 = 5;
/// Mask of the 5-bit `program_stream_map_version` in the flags byte.
const VERSION_MASK: u8 = 0x1F;

/// An elementary stream descriptor entry with optional stream_id_extension.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EsMapEntry<'a> {
    /// `stream_type` per ISO/IEC 13818-1 Table 2-29.
    pub stream_type: u8,
    /// `elementary_stream_id`.
    pub elementary_stream_id: u8,
    /// If `elementary_stream_id == 0xFD` and `single_extension_stream_flag == 0`,
    /// this holds the `elementary_stream_id_extension`. Otherwise `None`.
    pub stream_id_extension: Option<u8>,
    /// Descriptor bytes for this elementary stream.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub descriptors: &'a [u8],
}

/// A parsed Program Stream Map.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ProgramStreamMap<'a> {
    /// `current_next_indicator` (1 bit).
    pub current_next_indicator: bool,
    /// `single_extension_stream_flag` (1 bit).
    pub single_extension_stream_flag: bool,
    /// `program_stream_map_version` (5 bits).
    pub version: u8,
    /// Descriptors for the program stream itself.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub program_stream_info: &'a [u8],
    /// Per-elementary-stream entries.
    pub elementary_stream_map: Vec<EsMapEntry<'a>>,
    /// The raw CRC-32 value in the trailer (validated on parse).
    pub crc: u32,
}

impl<'a> Parse<'a> for ProgramStreamMap<'a> {
    type Error = Error;

    fn parse(b: &'a [u8]) -> Result<Self> {
        if b.len() < PREFIX_LEN + 2 + 4 {
            // prefix + psm_length(2) + CRC(4) = minimum
            return Err(Error::BufferTooShort {
                need: PREFIX_LEN + 2 + 4,
                have: b.len(),
                what: "program_stream_map",
            });
        }

        // packet_start_code_prefix (3 bytes) + map_stream_id (1 byte)
        let start = u32::from_be_bytes([0, b[0], b[1], b[2]]);
        if start != PACKET_START_CODE_PREFIX {
            return Err(Error::BadMapStreamId(b[3]));
        }
        if b[3] != MAP_STREAM_ID {
            return Err(Error::BadMapStreamId(b[3]));
        }

        let map_length = u16::from_be_bytes([b[4], b[5]]) as usize;
        let crc_end = PREFIX_LEN + map_length + 4;
        if b.len() < crc_end {
            return Err(Error::MapLengthOverflow {
                map_length,
                available: b.len().saturating_sub(PREFIX_LEN),
            });
        }

        // Validate CRC before trusting the parsed content
        let crc_data_end = crc_end - 4;
        let crc_data = &b[0..crc_data_end];
        let stored_crc = u32::from_be_bytes([
            b[crc_data_end],
            b[crc_data_end + 1],
            b[crc_data_end + 2],
            b[crc_data_end + 3],
        ]);
        let computed_crc = crc32_mpeg2::compute(crc_data);
        if computed_crc != stored_crc {
            return Err(Error::BadCrc {
                computed: computed_crc,
                stored: stored_crc,
            });
        }

        // flags byte: current_next(1) | single_extension(1) | reserved(1) | version(5)
        let flags = b[6];
        let current_next_indicator = flags & 0x80 != 0;
        let single_extension_stream_flag = flags & 0x40 != 0;
        let version = flags & VERSION_MASK;

        // reserved byte (7 bits reserved + marker_bit)
        if b[7] & 0x01 == 0 {
            return Err(Error::BadMarker("program_stream_map marker_bit"));
        }

        let program_stream_info_length = u16::from_be_bytes([b[8], b[9]]) as usize;

        let info_start = PREFIX_LEN + 4; // after flags(1)+reserved(1)+prog_info_len(2)
        let info_end = info_start + program_stream_info_length;

        // Table 2-41 order: program_stream_info_length(16), descriptor()×N,
        // THEN elementary_stream_map_length(16) — the length field follows
        // the program descriptor loop, not the reverse (#1050).
        if crc_data_end < info_end + 2 {
            return Err(Error::MapLengthOverflow {
                map_length,
                available: b.len().saturating_sub(PREFIX_LEN),
            });
        }
        let elementary_stream_map_length =
            u16::from_be_bytes([b[info_end], b[info_end + 1]]) as usize;

        let es_start = info_end + 2; // after elementary_stream_map_length(2)
        let es_end = es_start + elementary_stream_map_length;

        if crc_data_end < es_end {
            return Err(Error::MapLengthOverflow {
                map_length,
                available: b.len().saturating_sub(PREFIX_LEN),
            });
        }

        let program_stream_info = &b[info_start..info_end];

        // Parse elementary stream loop
        let es_data = &b[es_start..es_end];
        let elementary_stream_map = parse_es_loop(es_data, single_extension_stream_flag)?;

        Ok(ProgramStreamMap {
            current_next_indicator,
            single_extension_stream_flag,
            version,
            program_stream_info,
            elementary_stream_map,
            crc: stored_crc,
        })
    }
}

fn parse_es_loop(data: &[u8], single_flag: bool) -> Result<Vec<EsMapEntry<'_>>> {
    let mut entries = Vec::new();
    let mut pos = 0;
    while pos + 4 <= data.len() {
        let stream_type = data[pos];
        let elementary_stream_id = data[pos + 1];
        let es_info_length = u16::from_be_bytes([data[pos + 2], data[pos + 3]]) as usize;
        let entry_hdr_end = pos + 4;
        let entry_end = entry_hdr_end + es_info_length;
        if entry_end > data.len() {
            return Err(Error::BufferTooShort {
                need: entry_end,
                have: data.len(),
                what: "elementary_stream_map entry descriptors",
            });
        }

        let (stream_id_extension, descriptors) = if elementary_stream_id == 0xFD && !single_flag {
            // Extension form with pseudo descriptor
            if es_info_length < 3 {
                return Err(Error::BufferTooShort {
                    need: 3,
                    have: es_info_length,
                    what: "pseudo descriptor for stream_id_extension",
                });
            }
            // pseudo_descriptor_tag + pseudo_descriptor_length + marker+extension
            if data[entry_hdr_end + 2] & 0x80 == 0 {
                return Err(Error::BadMarker("elementary_stream_id_extension marker"));
            }
            let ext = data[entry_hdr_end + 2] & 0x7F;
            let desc = &data[entry_hdr_end + 3..entry_end];
            (Some(ext), desc)
        } else {
            let desc = &data[entry_hdr_end..entry_end];
            (None, desc)
        };

        entries.push(EsMapEntry {
            stream_type,
            elementary_stream_id,
            stream_id_extension,
            descriptors,
        });

        pos = entry_end;
    }
    Ok(entries)
}

/// Bytes one elementary-stream entry occupies on the wire:
/// `stream_type(1) + elementary_stream_id(1) + ES_info_length(2)` + the
/// optional 3-byte pseudo descriptor + the descriptor bytes.
fn es_entry_len(e: &EsMapEntry<'_>) -> usize {
    ES_ENTRY_HEADER_LEN
        + if e.stream_id_extension.is_some() {
            PSEUDO_DESCRIPTOR_LEN
        } else {
            0
        }
        + e.descriptors.len()
}

/// Write the elementary-stream loop straight into `out` (exactly the sum of
/// [`es_entry_len`], checked by the caller), no intermediate owned copies
/// (audit r14-MPS-O1).
fn write_es_loop(entries: &[EsMapEntry<'_>], out: &mut [u8]) -> Result<()> {
    let mut at = 0usize;
    for e in entries {
        let entry_len = es_entry_len(e);
        let dst = &mut out[at..at + entry_len];
        dst[0] = e.stream_type;
        dst[1] = e.elementary_stream_id;
        let info_len = entry_len - ES_ENTRY_HEADER_LEN;
        let info_len =
            broadcast_common::len::fit_u16(info_len, "elementary_stream_map.ES_info_length")?;
        dst[2..4].copy_from_slice(&info_len.to_be_bytes());
        let mut c = ES_ENTRY_HEADER_LEN;
        if let Some(ext) = e.stream_id_extension {
            dst[c] = PSEUDO_DESCRIPTOR_TAG;
            // pseudo_descriptor_length: 8-bit field covering the marker+
            // extension byte plus the descriptors. Checked in usize before
            // narrowing — `1 + len as u8` used to overflow at 255 (#1129).
            dst[c + 1] = broadcast_common::len::fit_u8(
                1 + e.descriptors.len(),
                "elementary_stream_map.pseudo_descriptor_length",
            )?;
            dst[c + 2] = MARKER_BIT | (ext & EXTENSION_MASK);
            c += PSEUDO_DESCRIPTOR_LEN;
        }
        dst[c..].copy_from_slice(e.descriptors);
        at += entry_len;
    }
    Ok(())
}

impl Serialize for ProgramStreamMap<'_> {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        let prog_info_len = self.program_stream_info.len();
        let es_loop_len: usize = self.elementary_stream_map.iter().map(es_entry_len).sum();
        // PREFIX_LEN + flags(1) + reserved(1) + prog_info_len(2) + prog_info
        // + es_map_len(2) + es_loop + CRC(4)
        PREFIX_LEN + FIXED_BODY_LEN + prog_info_len + es_loop_len + CRC_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let total = self.serialized_len();
        if buf.len() < total {
            return Err(Error::BufferTooShort {
                need: total,
                have: buf.len(),
                what: "program_stream_map serialize output",
            });
        }

        // packet_start_code_prefix (3 bytes)
        buf[0..3].copy_from_slice(&PACKET_START_CODE_PREFIX.to_be_bytes()[1..]);
        // map_stream_id
        buf[3] = MAP_STREAM_ID;

        let prog_info_len = self.program_stream_info.len();
        let es_loop_len: usize = self.elementary_stream_map.iter().map(es_entry_len).sum();

        // map_length = flags(1) + reserved(1) + prog_info_len(2) + es_loop_len(2) + prog_info + es_loop
        let map_length = FIXED_BODY_LEN + prog_info_len + es_loop_len;
        // program_stream_map_length max is 1018 (0x3FA) per Table 2-41 — checked
        // in usize before any narrowing (#1129).
        if map_length > MAP_LENGTH_MAX {
            return Err(broadcast_common::len::FieldOverflow {
                field: "program_stream_map.program_stream_map_length",
                value: map_length as u64,
                max: MAP_LENGTH_MAX as u64,
            }
            .into());
        }
        let map_length = broadcast_common::len::fit_u16(
            map_length,
            "program_stream_map.program_stream_map_length",
        )?;
        buf[4..6].copy_from_slice(&map_length.to_be_bytes());

        // flags: current_next(1) + single_extension(1) + reserved(1, convention
        // is set) + version(5). W8 (#1119): the reserved bit (bit 5) was
        // always written 0 instead of the conventional 1.
        let version = broadcast_common::len::fit_bits(
            u64::from(self.version),
            VERSION_BITS,
            "program_stream_map.program_stream_map_version",
        )? as u8;
        buf[6] = (u8::from(self.current_next_indicator) << 7)
            | (u8::from(self.single_extension_stream_flag) << 6)
            | FLAGS_RESERVED_BIT
            | version;

        // reserved(7, convention is all set) + marker_bit(1).
        // W8 (#1119): `0x7F | 0x01` is a no-op (`0x7F` already has bit 0
        // set) and leaves the MSB reserved bit `0` instead of the
        // conventional `1` — real encoders write this byte `0xFF`, so this
        // did not round-trip byte-identically against a real capture.
        buf[7] = 0xFF;

        // program_stream_info_length and elementary_stream_map_length are
        // both 16-bit fields; `map_length <= MAP_LENGTH_MAX` above already
        // bounds each of them well under `u16::MAX`, but check explicitly
        // rather than relying on that aggregate bound holding (#1129).
        let prog_info_len_u16 = broadcast_common::len::fit_u16(
            prog_info_len,
            "program_stream_map.program_stream_info_length",
        )?;
        let es_loop_len_u16 = broadcast_common::len::fit_u16(
            es_loop_len,
            "program_stream_map.elementary_stream_map_length",
        )?;
        buf[8..10].copy_from_slice(&prog_info_len_u16.to_be_bytes());

        // program_stream_info descriptors (Table 2-41: the program descriptor
        // loop comes immediately after program_stream_info_length, at byte
        // 10, BEFORE elementary_stream_map_length — #1050)
        buf[10..10 + prog_info_len].copy_from_slice(self.program_stream_info);

        // elementary_stream_map_length, then the elementary stream loop
        let es_len_start = 10 + prog_info_len;
        buf[es_len_start..es_len_start + 2].copy_from_slice(&es_loop_len_u16.to_be_bytes());
        let es_start = es_len_start + 2;
        write_es_loop(
            &self.elementary_stream_map,
            &mut buf[es_start..es_start + es_loop_len],
        )?;

        // CRC-32 over everything before it
        let crc_offset = es_start + es_loop_len;
        let crc = crc32_mpeg2::compute(&buf[0..crc_offset]);
        buf[crc_offset..crc_offset + 4].copy_from_slice(&crc.to_be_bytes());

        Ok(total)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn serialize_rejects_version_over_5_bits() {
        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 0x20,
            program_stream_info: &[],
            elementary_stream_map: vec![],
            crc: 0,
        };
        let mut buf = vec![0u8; 64];
        assert!(matches!(
            psm.serialize_into(&mut buf),
            Err(Error::FieldOverflow(_))
        ));
    }

    /// Build a valid PSM programmatically and verify round-trip.
    #[test]
    fn psm_build_and_round_trip() {
        let entries = vec![EsMapEntry {
            stream_type: 0x02, // MPEG-2 video
            elementary_stream_id: 0xE0,
            stream_id_extension: None,
            descriptors: &[0x0A, 0x04, b'H', b'E', b'L', b'L'], // registration descriptor
        }];

        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 3,
            program_stream_info: &[],
            elementary_stream_map: entries,
            crc: 0, // will be overwritten by serialize
        };

        let mut buf = vec![0u8; psm.serialized_len()];
        psm.serialize_into(&mut buf).unwrap();

        // Parse back
        let parsed = ProgramStreamMap::parse(&buf).unwrap();
        assert!(parsed.current_next_indicator);
        assert!(!parsed.single_extension_stream_flag);
        assert_eq!(parsed.version, 3);
        assert!(parsed.program_stream_info.is_empty());
        assert_eq!(parsed.elementary_stream_map.len(), 1);
        assert_eq!(parsed.elementary_stream_map[0].stream_type, 0x02);
        assert_eq!(parsed.elementary_stream_map[0].elementary_stream_id, 0xE0);
        assert!(
            parsed.elementary_stream_map[0]
                .stream_id_extension
                .is_none()
        );
        assert_eq!(
            parsed.elementary_stream_map[0].descriptors,
            &[0x0A, 0x04, b'H', b'E', b'L', b'L']
        );

        // Byte-exact round-trip
        let mut out2 = vec![0u8; parsed.serialized_len()];
        parsed.serialize_into(&mut out2).unwrap();
        assert_eq!(&out2[..], &buf[..], "byte-exact round-trip mismatch");

        // Mutation test: change version, output must differ
        let psm_mut = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 7,
            program_stream_info: &[],
            elementary_stream_map: vec![EsMapEntry {
                stream_type: 0x02,
                elementary_stream_id: 0xE0,
                stream_id_extension: None,
                descriptors: &[0x0A, 0x04, b'H', b'E', b'L', b'L'],
            }],
            crc: 0,
        };
        let mut out3 = vec![0u8; psm_mut.serialized_len()];
        psm_mut.serialize_into(&mut out3).unwrap();
        assert_ne!(&buf[..], &out3[..]);
    }

    #[test]
    fn psm_with_stream_id_extension() {
        let entries = vec![EsMapEntry {
            stream_type: 0x06, // subtitles
            elementary_stream_id: 0xFD,
            stream_id_extension: Some(0x0F),
            descriptors: &[0x59, 0x02, 0x01, 0x02], // subtitling descriptor
        }];

        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 1,
            program_stream_info: &[],
            elementary_stream_map: entries,
            crc: 0,
        };

        let mut buf = vec![0u8; psm.serialized_len()];
        psm.serialize_into(&mut buf).unwrap();

        let parsed = ProgramStreamMap::parse(&buf).unwrap();
        assert_eq!(parsed.elementary_stream_map.len(), 1);
        assert_eq!(
            parsed.elementary_stream_map[0].stream_id_extension,
            Some(0x0F)
        );
        assert_eq!(
            parsed.elementary_stream_map[0].descriptors,
            &[0x59, 0x02, 0x01, 0x02]
        );

        // Byte-exact round-trip
        let mut out2 = vec![0u8; parsed.serialized_len()];
        parsed.serialize_into(&mut out2).unwrap();
        assert_eq!(&out2[..], &buf[..]);
    }

    /// MPS-W6 (#1129): `pseudo_descriptor_length` is `1 + descriptors.len()`,
    /// written as `1 + (descriptors.len() as u8)` — the cast happened before
    /// the add, so a 255-byte descriptor overflowed the `u8` addition
    /// (panicking in debug, wrapping in release) rather than being checked.
    #[test]
    fn pseudo_descriptor_length_overflow_is_rejected_not_wrapped() {
        let entries = vec![EsMapEntry {
            stream_type: 0x06,
            elementary_stream_id: 0xFD,
            stream_id_extension: Some(0x01),
            descriptors: &[0u8; 255],
        }];
        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 0,
            program_stream_info: &[],
            elementary_stream_map: entries,
            crc: 0,
        };
        let mut buf = vec![0u8; psm.serialized_len()];
        assert!(psm.serialize_into(&mut buf).is_err());
    }

    /// MPS-W6 (#1129): `program_stream_map_length` (spec max 1018, Table
    /// 2-41) was written unchecked with `as u16`.
    #[test]
    fn program_stream_map_length_over_spec_max_is_rejected() {
        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 0,
            program_stream_info: &[0u8; 1019],
            elementary_stream_map: vec![],
            crc: 0,
        };
        let mut buf = vec![0u8; psm.serialized_len()];
        assert!(psm.serialize_into(&mut buf).is_err());
    }

    /// The boundary: exactly the spec max still serializes and round-trips.
    #[test]
    fn program_stream_map_length_at_spec_max_round_trips() {
        // map_length = 6 + prog_info_len + es_loop_len; want map_length == 1018.
        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 0,
            program_stream_info: &[0u8; 1012],
            elementary_stream_map: vec![],
            crc: 0,
        };
        let mut buf = vec![0u8; psm.serialized_len()];
        psm.serialize_into(&mut buf).unwrap();
        let parsed = ProgramStreamMap::parse(&buf).unwrap();
        assert_eq!(parsed.program_stream_info.len(), 1012);
    }

    /// #1050 regression: a conformant PSM with a non-empty program
    /// descriptor loop. TSDuck cannot generate PS, and the committed
    /// ffmpeg fixture (`fixtures/mpeg-ps/ffmpeg-mpeg2-ps.mpg`) carries no
    /// PSM at all (VOB/MPEG-PS from ffmpeg's muxer omits it), so this is
    /// hand-built directly from ISO/IEC 13818-1 Table 2-41's field order —
    /// the oracle: `program_stream_info_length(16)`, `descriptor()×N`,
    /// THEN `elementary_stream_map_length(16)`, `stream_map()×N`, `CRC_32`.
    /// Before the fix, parse took the program loop's first descriptor
    /// bytes (tag=0x05 'C'=0x43 here) as `elementary_stream_map_length`
    /// (0x0543 = 1347), which overflows the buffer and fails with
    /// `MapLengthOverflow` instead of parsing the one ES entry.
    #[test]
    fn psm_with_nonempty_program_descriptor_loop() {
        // One program-level registration descriptor (tag 0x05, len 4, "TEST").
        let prog_descriptor: &[u8] = &[0x05, 0x04, b'T', b'E', b'S', b'T'];
        let entries = vec![EsMapEntry {
            stream_type: 0x02, // MPEG-2 video
            elementary_stream_id: 0xE0,
            stream_id_extension: None,
            descriptors: &[],
        }];

        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 5,
            program_stream_info: prog_descriptor,
            elementary_stream_map: entries,
            crc: 0,
        };

        let mut buf = vec![0u8; psm.serialized_len()];
        psm.serialize_into(&mut buf).unwrap();

        // Table 2-41 byte layout check: the program descriptor loop (6 bytes)
        // sits at buf[10..16], directly after program_stream_info_length;
        // elementary_stream_map_length sits at buf[16..18], AFTER it.
        assert_eq!(&buf[10..16], prog_descriptor);
        let es_map_len = u16::from_be_bytes([buf[16], buf[17]]);
        assert_eq!(es_map_len, 4, "one ES entry: stream_type+id+info_len(0)");

        let parsed = ProgramStreamMap::parse(&buf).unwrap();
        assert_eq!(parsed.program_stream_info, prog_descriptor);
        assert_eq!(parsed.elementary_stream_map.len(), 1);
        assert_eq!(parsed.elementary_stream_map[0].stream_type, 0x02);
        assert_eq!(parsed.elementary_stream_map[0].elementary_stream_id, 0xE0);

        // Byte-exact round-trip
        let mut out2 = vec![0u8; parsed.serialized_len()];
        parsed.serialize_into(&mut out2).unwrap();
        assert_eq!(&out2[..], &buf[..]);
    }

    /// W8 (#1119): reserved bits in the flags byte (bit 5) and the
    /// following reserved+marker byte (bits 7-1) are conventionally `1` —
    /// real encoders write byte 6's reserved bit set and byte 7 as `0xFF`.
    /// The flags byte used to always clear bit 5, and byte 7 was written
    /// `0x7F | 0x01` (a no-op, since `0x7F` already has bit 0 set) instead
    /// of `0xFF`, leaving the MSB reserved bit `0`.
    #[test]
    fn reserved_bits_are_set_by_convention() {
        let psm = ProgramStreamMap {
            current_next_indicator: false,
            single_extension_stream_flag: false,
            version: 0,
            program_stream_info: &[],
            elementary_stream_map: vec![],
            crc: 0,
        };
        let mut buf = vec![0u8; psm.serialized_len()];
        psm.serialize_into(&mut buf).unwrap();
        assert_eq!(
            buf[6], 0x20,
            "flags byte reserved bit (0x20) must be set even with both flags clear"
        );
        assert_eq!(buf[7], 0xFF, "reserved(7)+marker_bit(1) byte must be 0xFF");
    }

    #[test]
    fn psm_bad_crc_rejected() {
        let psm = ProgramStreamMap {
            current_next_indicator: true,
            single_extension_stream_flag: false,
            version: 0,
            program_stream_info: &[],
            elementary_stream_map: vec![],
            crc: 0,
        };
        let mut buf = vec![0u8; psm.serialized_len()];
        psm.serialize_into(&mut buf).unwrap();
        // Corrupt CRC (last 4 bytes)
        let crc_off = buf.len() - 4;
        buf[crc_off] ^= 0xFF;
        assert!(matches!(
            ProgramStreamMap::parse(&buf),
            Err(Error::BadCrc { .. })
        ));
    }
}