mpeg-ts 0.6.2

MPEG-2 Transport Stream framing (ITU-T H.222.0 / ISO/IEC 13818-1): TS packet, adaptation field, PCR, PSI section reassembly + packetisation, resync. no_std.
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
//! Owned 188-byte TS packet with pre-parsed header fields.
//!
//! [`OwnedTsPacket`] complements the zero-copy [`crate::ts::TsPacket`] (which holds
//! a borrowed `&[u8; 188]`) with an **owned** `[u8; 188]` suitable for queuing,
//! cloning, and in-place mutation — e.g. for mux pipelines that must rewrite the
//! continuity counter or splice in a new payload.
//!
//! Header parsing delegates to [`crate::ts::TsHeader::parse`]; no bit-twiddling
//! is duplicated here.

use crate::error::{Error, Result};
use crate::pid::Pid;
use crate::ts::{
    ADAPTATION_FLAG, AF_PCR_FLAG, AdaptationField, AdaptationFieldControl, CC_MASK, PCR_FIELD_LEN,
    Pcr, ScramblingControl, TS_PACKET_SIZE, TS_SYNC_BYTE, TsHeader,
};

/// The 13-bit PID value used for null packets — `0x1FFF`
/// (ISO/IEC 13818-1 §2.4.3.3, Table 2-3).
const NULL_PID: Pid = crate::pid::well_known::NULL;

/// Owned 188-byte TS packet with pre-parsed header fields.
///
/// The raw bytes are stored privately; the parsed flags (`pid`, `pusi`, etc.)
/// are pre-extracted at construction time so hot paths avoid repeated byte
/// masking. The fields are **private** (audit r01-W8, #1074): a public copy
/// of a header field that a caller could assign would silently drift from
/// the bytes that [`raw`](Self::raw) serialises. Read them through the
/// getters; the only mutation entry points are the associated functions that
/// edit a raw `[u8; 188]` (`set_pcr`, `set_continuity_counter`) followed by a
/// re-[`parse`](Self::parse).
///
/// # Payload access
///
/// Use [`payload`](Self::payload) / [`payload_mut`](Self::payload_mut) to obtain
/// a slice that correctly skips the 4-byte header **and** any adaptation field.
///
/// # Building packets
///
/// [`serialize_with_payload`](Self::serialize_with_payload) constructs a plain
/// payload-only packet (no adaptation field) filled with 0xFF stuffing.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct OwnedTsPacket {
    /// The raw 188 bytes (serialized as a byte sequence).
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_raw_bytes"))]
    raw: [u8; TS_PACKET_SIZE],
    /// 13-bit PID extracted from bytes 1–2.
    pid: Pid,
    /// Payload Unit Start Indicator (byte 1 bit 6).
    pusi: bool,
    /// Adaptation field present flag (byte 3 bit 5).
    has_adaptation: bool,
    /// Payload present flag (byte 3 bit 4).
    has_payload: bool,
    /// Transport Error Indicator (byte 1 bit 7).
    tei: bool,
    /// 2-bit transport_scrambling_control (byte 3 bits 7–6).
    scrambling: u8,
    /// 4-bit continuity_counter (byte 3 bits 3–0).
    continuity_counter: u8,
    /// Discontinuity flag: `true` if the adaptation-field `discontinuity_indicator`
    /// was set in the source packet, or if the caller marks this as a
    /// continuity-counter discontinuity boundary. Defaults to `false` on parse.
    pub discontinuity: bool,
}

/// Serialize a `[u8; N]` as a variable-length byte sequence so serde's
/// blanket impls (only up to `[u8; 32]`) are not required.
#[cfg(feature = "serde")]
fn serialize_raw_bytes<S: serde::Serializer>(
    bytes: &[u8; TS_PACKET_SIZE],
    s: S,
) -> core::result::Result<S::Ok, S::Error> {
    use serde::ser::SerializeSeq;
    let mut seq = s.serialize_seq(Some(bytes.len()))?;
    for b in bytes {
        seq.serialize_element(b)?;
    }
    seq.end()
}

impl OwnedTsPacket {
    /// The raw 188 bytes.
    pub fn raw(&self) -> &[u8; TS_PACKET_SIZE] {
        &self.raw
    }

    /// Consume the packet, returning its raw 188 bytes.
    pub fn into_raw(self) -> [u8; TS_PACKET_SIZE] {
        self.raw
    }

    /// 13-bit PID (bytes 1–2).
    pub fn pid(&self) -> Pid {
        self.pid
    }

    /// Payload Unit Start Indicator (byte 1 bit 6).
    pub fn pusi(&self) -> bool {
        self.pusi
    }

    /// Adaptation field present flag (byte 3 bit 5).
    pub fn has_adaptation(&self) -> bool {
        self.has_adaptation
    }

    /// Payload present flag (byte 3 bit 4).
    pub fn has_payload(&self) -> bool {
        self.has_payload
    }

    /// Transport Error Indicator (byte 1 bit 7).
    pub fn tei(&self) -> bool {
        self.tei
    }

    /// Raw 2-bit `transport_scrambling_control` (byte 3 bits 7–6); see
    /// [`scrambling_control`](Self::scrambling_control) for the typed view.
    pub fn scrambling(&self) -> u8 {
        self.scrambling
    }

    /// 4-bit continuity_counter (byte 3 bits 3–0).
    pub fn continuity_counter(&self) -> u8 {
        self.continuity_counter
    }

    /// Parse a 188-byte owned TS packet.
    ///
    /// Returns [`Error::InvalidSyncByte`] if `raw[0] != 0x47`.
    /// Header bit-parsing is delegated to [`TsHeader::parse`].
    /// The `discontinuity` field defaults to `false`; set it manually if needed.
    pub fn parse(raw: [u8; TS_PACKET_SIZE]) -> Result<Self> {
        if raw[0] != TS_SYNC_BYTE {
            return Err(Error::InvalidSyncByte { found: raw[0] });
        }
        let hdr = TsHeader::parse(&raw[..4])?;
        Ok(Self {
            raw,
            pid: hdr.pid,
            pusi: hdr.pusi,
            has_adaptation: hdr.has_adaptation,
            has_payload: hdr.has_payload,
            tei: hdr.tei,
            scrambling: hdr.scrambling,
            continuity_counter: hdr.continuity_counter,
            discontinuity: false,
        })
    }

    /// Typed view of the 2-bit `transport_scrambling_control` field.
    ///
    /// See [`ScramblingControl`] for the spec citation (H.222.0 Table 2-4 +
    /// ETSI TS 100 289 §5.1 Table 1).
    pub fn scrambling_control(&self) -> ScramblingControl {
        ScramblingControl::from_bits(self.scrambling)
    }

    /// Typed view of the `adaptation_field_control` 2-bit field, derived from the
    /// stored `has_adaptation`/`has_payload` booleans.
    ///
    /// See [`AdaptationFieldControl`] for the spec citation (H.222.0 Table 2-5).
    pub fn adaptation_field_control(&self) -> AdaptationFieldControl {
        AdaptationFieldControl::from_flags(self.has_adaptation, self.has_payload)
    }

    /// Return the payload bytes (after the 4-byte header and any adaptation field).
    ///
    /// Returns `None` when [`has_payload`](Self::has_payload) is `false` or the
    /// adaptation field consumed all remaining bytes.
    pub fn payload(&self) -> Option<&[u8]> {
        if !self.has_payload {
            return None;
        }
        let offset = self.payload_offset();
        if offset < TS_PACKET_SIZE {
            Some(&self.raw[offset..])
        } else {
            None
        }
    }

    /// Return a mutable slice of the payload bytes.
    ///
    /// Returns `None` when [`has_payload`](Self::has_payload) is `false` or the
    /// adaptation field consumed all remaining bytes.
    pub fn payload_mut(&mut self) -> Option<&mut [u8]> {
        if !self.has_payload {
            return None;
        }
        let offset = self.payload_offset();
        if offset < TS_PACKET_SIZE {
            Some(&mut self.raw[offset..])
        } else {
            None
        }
    }

    /// Compute the byte offset of the first payload byte inside `raw`.
    ///
    /// The 4-byte header is always present; if `has_adaptation` is set, the next
    /// byte is the adaptation-field length, and the payload starts after those
    /// `1 + af_len` bytes.
    #[inline]
    fn payload_offset(&self) -> usize {
        let mut offset = 4;
        if self.has_adaptation {
            // raw[4] is the adaptation_field_length byte
            let af_len = self.raw[4] as usize;
            offset += 1 + af_len;
        }
        offset
    }

    /// Maximum payload bytes a plain (no-adaptation-field) TS packet can carry:
    /// 188 bytes minus the 4-byte header.
    pub const MAX_PAYLOAD_LEN: usize = TS_PACKET_SIZE - 4;

    /// Build a 188-byte payload-only TS packet (no adaptation field).
    ///
    /// The packet is initialised to `0xFF` (MPEG-TS stuffing), the 4-byte header
    /// is written via [`TsHeader::serialize_into`], then `payload` is copied
    /// starting at byte 4. Any unfilled bytes remain `0xFF`.
    ///
    /// Returns [`Error::PayloadTooLarge`] if `payload` is longer than
    /// [`MAX_PAYLOAD_LEN`](Self::MAX_PAYLOAD_LEN) (184 bytes) — the fixed
    /// per-packet payload capacity would previously be silently truncated
    /// (#1129).
    ///
    /// # Panics
    ///
    /// Never panics — serializing a 4-byte header into a 188-byte buffer cannot
    /// fail.
    pub fn serialize_with_payload(
        pid: Pid,
        pusi: bool,
        cc: u8,
        payload: &[u8],
    ) -> Result<[u8; TS_PACKET_SIZE]> {
        if payload.len() > Self::MAX_PAYLOAD_LEN {
            return Err(Error::PayloadTooLarge {
                len: payload.len(),
                max: Self::MAX_PAYLOAD_LEN,
            });
        }
        let mut pkt = [crate::ts::STUFFING_BYTE; TS_PACKET_SIZE];
        let hdr = TsHeader {
            tei: false,
            pusi,
            pid,
            scrambling: 0,
            has_adaptation: false,
            has_payload: true,
            continuity_counter: cc & CC_MASK,
        };
        // Cannot fail: buf is 188 bytes, need 4.
        hdr.serialize_into(&mut pkt)
            .expect("serialize TsHeader into 188-byte buf");
        pkt[4..4 + payload.len()].copy_from_slice(payload);
        Ok(pkt)
    }

    /// Build a 188-byte null packet (PID `0x1FFF`) with `0xFF`-stuffed payload.
    ///
    /// Null packets carry PID `0x1FFF` and have no meaningful payload
    /// (ISO/IEC 13818-1 §2.4.1). The continuity counter `cc` is masked to 4
    /// bits. Transport scrambling is `00` (not scrambled).
    ///
    /// # Example
    ///
    /// ```
    /// use mpeg_ts::OwnedTsPacket;
    /// use mpeg_ts::ts::{TsPacket, TS_PACKET_SIZE};
    /// let raw = OwnedTsPacket::null_packet(3);
    /// assert_eq!(raw.len(), TS_PACKET_SIZE);
    /// let pkt = TsPacket::parse(&raw).unwrap();
    /// assert_eq!(pkt.header.pid, mpeg_ts::pid::well_known::NULL);
    /// assert_eq!(pkt.header.continuity_counter, 3);
    /// ```
    #[must_use]
    pub fn null_packet(cc: u8) -> [u8; TS_PACKET_SIZE] {
        // Cannot fail: an empty payload never exceeds MAX_PAYLOAD_LEN.
        Self::serialize_with_payload(NULL_PID, false, cc, &[])
            .expect("empty payload always fits a TS packet")
    }

    /// Overwrite the `continuity_counter` field in `packet` without re-parsing.
    ///
    /// Writes the low 4 bits of `cc` into byte 3 bits `[3:0]` in place
    /// (ISO/IEC 13818-1 §2.4.3.3). The other bits of byte 3 are preserved.
    ///
    /// # Example
    ///
    /// ```
    /// use mpeg_ts::OwnedTsPacket;
    /// use mpeg_ts::pid::Pid;
    /// use mpeg_ts::ts::TsPacket;
    /// let mut raw = OwnedTsPacket::serialize_with_payload(Pid::new(0x0100), false, 0, &[]).unwrap();
    /// OwnedTsPacket::set_continuity_counter(&mut raw, 7);
    /// let pkt = TsPacket::parse(&raw).unwrap();
    /// assert_eq!(pkt.header.continuity_counter, 7);
    /// ```
    pub fn set_continuity_counter(packet: &mut [u8; TS_PACKET_SIZE], cc: u8) {
        // Byte 3 bits [3:0] = continuity_counter (ISO/IEC 13818-1 §2.4.3.3).
        packet[3] = (packet[3] & !CC_MASK) | (cc & CC_MASK);
    }

    /// Overwrite the PCR value in an existing adaptation field in `packet`.
    ///
    /// The packet must already have `adaptation_field_control` with adaptation
    /// present (`has_adaptation == true`) and the PCR flag set in the adaptation
    /// field flags byte. This function locates the 6-byte PCR field and
    /// overwrites it with the encoding of `pcr`.
    ///
    /// # Errors
    ///
    /// - [`Error::BufferTooShort`] — the adaptation field does not contain a
    ///   PCR slot (no adaptation field, zero-length field, or PCR flag not set).
    ///
    /// # Example
    ///
    /// ```
    /// use mpeg_ts::ts::{AdaptationField, AF_PCR_FLAG, Pcr, TsPacket,
    ///                    TS_PACKET_SIZE, TS_SYNC_BYTE,
    ///                    ADAPTATION_FLAG, PAYLOAD_FLAG};
    /// use mpeg_ts::OwnedTsPacket;
    ///
    /// // Build a packet that has a PCR slot (adaptation_field_length = 7).
    /// let mut raw = [0xAAu8; TS_PACKET_SIZE];
    /// raw[0] = TS_SYNC_BYTE;
    /// raw[1] = 0x00; raw[2] = 0x64; // PID = 100
    /// raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
    /// raw[4] = 7;  // adaptation_field_length
    /// raw[5] = AF_PCR_FLAG;
    /// raw[6..12].copy_from_slice(&[0u8; 6]);
    ///
    /// let new_pcr = Pcr { base: 10_000, extension: 0 };
    /// OwnedTsPacket::set_pcr(&mut raw, new_pcr).unwrap();
    ///
    /// let pkt = TsPacket::parse(&raw).unwrap();
    /// let af = pkt.adaptation_field().unwrap().unwrap();
    /// assert_eq!(af.pcr, Some(new_pcr));
    /// ```
    pub fn set_pcr(packet: &mut [u8; TS_PACKET_SIZE], pcr: Pcr) -> Result<()> {
        // Byte 3: check adaptation_field_control has adaptation bit set
        // (ADAPTATION_FLAG = bit 5, ISO/IEC 13818-1 §2.4.3.3).
        if packet[3] & ADAPTATION_FLAG == 0 {
            return Err(Error::BufferTooShort {
                need: 6,
                have: 0,
                what: "set_pcr: no adaptation field",
            });
        }
        let af_len = packet[4] as usize;
        // W7 (#1074): the flags byte (1) + PCR field (PCR_FIELD_LEN = 6) must
        // both fit inside `af_len`, not just the flags byte. A malformed
        // adaptation field with `af_len` between 1 and 6 (PCR flag set
        // anyway) previously passed this check and then wrote 6 PCR bytes at
        // a fixed offset — 5 of which land past what `af_len` declares as
        // the adaptation field, i.e. into the payload.
        const REQUIRED_AF_LEN: usize = 1 + PCR_FIELD_LEN;
        if af_len < REQUIRED_AF_LEN {
            return Err(Error::BufferTooShort {
                need: REQUIRED_AF_LEN,
                have: af_len,
                what: "set_pcr: adaptation field too short for flags byte + PCR",
            });
        }
        // Byte 5: adaptation field flags byte (AF_PCR_FLAG = 0x10, §2.4.3.4).
        if packet[5] & AF_PCR_FLAG == 0 {
            return Err(Error::BufferTooShort {
                need: 6,
                have: 0,
                what: "set_pcr: PCR flag not set in adaptation field",
            });
        }
        // PCR occupies the 6 bytes starting at offset 6 (after header + af_len byte + flags byte).
        let pcr_start = 6usize;
        let pcr_end = pcr_start + PCR_FIELD_LEN;
        packet[pcr_start..pcr_end].copy_from_slice(&pcr.to_field_bytes());
        Ok(())
    }

    /// Decode the adaptation field from this packet, if present.
    ///
    /// Returns `None` when no adaptation field is present, and
    /// `Some(Err(..))` when the adaptation field bytes are malformed.
    /// The returned [`AdaptationField`] borrows from `self.raw`.
    pub fn adaptation_field(&self) -> Option<crate::Result<AdaptationField<'_>>> {
        if self.raw[3] & ADAPTATION_FLAG == 0 {
            return None;
        }
        let af_len = self.raw[4] as usize;
        if af_len == 0 || 5 + af_len > TS_PACKET_SIZE {
            return None;
        }
        Some(AdaptationField::parse(&self.raw[5..5 + af_len]))
    }
}

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

    /// The getters decode the header bytes literally (H.222.0 §2.4.3.2): a
    /// hand-built header 0x47 | TEI=1 PUSI=1 prio=0 PID=0x1ABC | scr=0b10
    /// afc=0b01 cc=0xC.
    #[test]
    fn getters_report_the_raw_header_fields() {
        let mut raw = [crate::ts::STUFFING_BYTE; TS_PACKET_SIZE];
        raw[0] = TS_SYNC_BYTE;
        raw[1] = 0b1101_1010; // TEI=1, PUSI=1, priority=0, PID[12:8]=0b11010
        raw[2] = 0xBC;
        raw[3] = 0b1001_1100; // scrambling=0b10, afc=0b01 (payload only), cc=0xC
        let pkt = OwnedTsPacket::parse(raw).unwrap();
        assert!(pkt.tei());
        assert!(pkt.pusi());
        assert_eq!(pkt.pid(), Pid::new(0x1ABC));
        assert_eq!(pkt.scrambling(), 0b10);
        assert!(!pkt.has_adaptation());
        assert!(pkt.has_payload());
        assert_eq!(pkt.continuity_counter(), 0xC);
        assert_eq!(pkt.raw(), &raw);
        assert_eq!(pkt.into_raw(), raw);
    }

    #[test]
    fn owned_round_trip_and_payload_mut() {
        let payload = [0xAAu8; 184];
        let mut pkt = OwnedTsPacket::parse(
            OwnedTsPacket::serialize_with_payload(Pid::new(0x0100), true, 7, &payload).unwrap(),
        )
        .unwrap();
        assert_eq!(pkt.pid(), Pid::new(0x0100));
        assert!(pkt.pusi);
        assert_eq!(pkt.continuity_counter, 7);
        assert_eq!(pkt.payload().unwrap()[..184], payload[..]);
        pkt.payload_mut().unwrap()[0] = 0x55;
        assert_eq!(pkt.payload().unwrap()[0], 0x55);
        // discontinuity defaults to false
        assert!(!pkt.discontinuity);
    }

    /// W9 (#1129): `serialize_with_payload` used to silently truncate a
    /// payload over 184 bytes (`payload.len().min(184)`) instead of
    /// erroring, dropping data with no signal.
    #[test]
    fn oversized_payload_is_rejected_not_truncated() {
        let payload = [0xAAu8; 185];
        assert!(
            OwnedTsPacket::serialize_with_payload(Pid::new(0x0100), true, 0, &payload).is_err()
        );
    }

    /// The boundary: exactly 184 bytes (the fixed payload capacity) still
    /// serializes and round-trips.
    #[test]
    fn max_payload_len_round_trips() {
        let payload = [0xBBu8; OwnedTsPacket::MAX_PAYLOAD_LEN];
        let raw =
            OwnedTsPacket::serialize_with_payload(Pid::new(0x0100), true, 0, &payload).unwrap();
        let pkt = OwnedTsPacket::parse(raw).unwrap();
        assert_eq!(pkt.payload().unwrap(), &payload[..]);
    }

    #[test]
    fn owned_scrambling_control_accessor() {
        let make = |scrambling_bits: u8| -> OwnedTsPacket {
            let mut raw =
                OwnedTsPacket::serialize_with_payload(Pid::new(0x0100), false, 0, &[]).unwrap();
            // byte 3 bits [7:6] = scrambling
            raw[3] = (raw[3] & 0x3F) | (scrambling_bits << 6);
            OwnedTsPacket::parse(raw).unwrap()
        };
        assert_eq!(
            make(0b00).scrambling_control(),
            ScramblingControl::NotScrambled
        );
        assert_eq!(make(0b01).scrambling_control(), ScramblingControl::Reserved);
        assert_eq!(make(0b10).scrambling_control(), ScramblingControl::EvenKey);
        assert_eq!(make(0b11).scrambling_control(), ScramblingControl::OddKey);
    }

    #[test]
    fn owned_adaptation_field_control_accessor() {
        let make = |afc_bits: u8| -> OwnedTsPacket {
            let mut raw = [crate::ts::STUFFING_BYTE; TS_PACKET_SIZE];
            raw[0] = TS_SYNC_BYTE;
            raw[1] = 0x00;
            raw[2] = 0x00;
            raw[3] = (afc_bits << 4) & 0x30;
            if afc_bits & 0b10 != 0 {
                raw[4] = 0; // adaptation_field_length = 0
            }
            OwnedTsPacket::parse(raw).unwrap()
        };
        assert_eq!(
            make(0b00).adaptation_field_control(),
            AdaptationFieldControl::Reserved
        );
        assert_eq!(
            make(0b01).adaptation_field_control(),
            AdaptationFieldControl::PayloadOnly
        );
        assert_eq!(
            make(0b10).adaptation_field_control(),
            AdaptationFieldControl::AdaptationOnly
        );
        assert_eq!(
            make(0b11).adaptation_field_control(),
            AdaptationFieldControl::AdaptationAndPayload
        );
    }

    /// W7 (#1074): `set_pcr` only checked `af_len >= 1` (room for the flags
    /// byte), not `af_len >= 1 + PCR_FIELD_LEN` (room for the PCR itself). A
    /// malformed adaptation field with `af_len` between 1 and 6 but the PCR
    /// flag set anyway let `set_pcr` write its fixed 6-byte PCR field 6 bytes
    /// past the header regardless — spilling into whatever follows the
    /// (too-short) declared adaptation field, i.e. the payload.
    #[test]
    fn set_pcr_rejects_adaptation_field_too_short_for_pcr() {
        let mut raw = [crate::ts::STUFFING_BYTE; TS_PACKET_SIZE];
        raw[0] = TS_SYNC_BYTE;
        raw[1] = 0x00;
        raw[2] = 0x00;
        raw[3] = ADAPTATION_FLAG | crate::ts::PAYLOAD_FLAG;
        raw[4] = 1; // adaptation_field_length: only room for the flags byte
        raw[5] = AF_PCR_FLAG; // PCR flag set anyway (malformed: no room for PCR)
        // raw[6..] is payload (0xFF stuffing here).
        let payload_before = raw[6..].to_vec();

        let pcr = Pcr {
            base: 10_000,
            extension: 0,
        };
        let err = OwnedTsPacket::set_pcr(&mut raw, pcr).unwrap_err();
        assert!(matches!(err, Error::BufferTooShort { .. }));
        assert_eq!(
            &raw[6..],
            payload_before.as_slice(),
            "payload must be untouched"
        );
    }
}