Skip to main content

mpeg_ts/
ts.rs

1//! MPEG-TS packet parser and section reassembler — ITU-T H.222.0 §2.4 (= ISO/IEC 13818-1).
2
3use crate::error::{Error, Result};
4use crate::pid::Pid;
5use broadcast_core::len::{need_in, need_out};
6
7/// Size of one MPEG-TS packet (ETSI EN 300 468 §3.2, ISO/IEC 13818-1 §2.4.3.2).
8pub const TS_PACKET_SIZE: usize = 188;
9/// Sync byte that every TS packet starts with (ISO/IEC 13818-1 §2.4.3.3).
10pub const TS_SYNC_BYTE: u8 = 0x47;
11/// TS packets carried in one datagram over IP: 7 whole 188-byte packets
12/// (1316 bytes), the largest whole-packet multiple that fits a datagram of a
13/// 1500-byte Ethernet MTU — the TS-over-UDP payload size the RTP payload
14/// conventions describe. A sender that ignored this and wrote a whole muxed
15/// frame per datagram had every frame over about 1.3 kB dropped for
16/// exceeding the receiver's MTU-sized cap.
17pub const TS_PACKETS_PER_DATAGRAM: usize = 7;
18/// Bytes of TS carried in one datagram over IP: [`TS_PACKETS_PER_DATAGRAM`]
19/// whole packets.
20pub const TS_BYTES_PER_DATAGRAM: usize = TS_PACKETS_PER_DATAGRAM * TS_PACKET_SIZE;
21/// Upper bound on a single section: `section_length` is 12 bits (max 4095)
22/// plus the 3-byte header = 4098. (Long-form SI caps `section_length` at
23/// 4093 → total 4096, but maximal short-form private sections may reach
24/// 4098; the reassembler accepts the absolute ceiling.)
25const MAX_SECTION_SIZE: usize = 4098;
26/// Bytes before the `section_length` payload: `table_id` (1) + the two bytes
27/// carrying the syntax/RFU flags and the 12-bit `section_length`
28/// (ISO/IEC 13818-1 §2.4.4.1).
29const SECTION_HEADER_LEN: usize = 3;
30/// Byte offsets within the 3-byte section header (ISO/IEC 13818-1 §2.4.4.1).
31const SECTION_TABLE_ID_OFFSET: usize = 0;
32const SECTION_FLAGS_OFFSET: usize = SECTION_TABLE_ID_OFFSET + 1;
33const SECTION_LENGTH_LO_OFFSET: usize = SECTION_FLAGS_OFFSET + 1;
34/// Mask for the 4 most-significant `section_length` bits in a section's second
35/// byte (ISO/IEC 13818-1 §2.4.4.1 — `section_length` is 12 bits). Shared with
36/// the packetiser in `mux.rs`.
37pub(crate) const SECTION_LENGTH_HI_MASK: u8 = 0x0F;
38
39/// MPEG-2 stuffing byte (ISO/IEC 13818-1 §2.4.4.1: `0xFF` fill after the last section in a payload; also the packet fill value).
40pub(crate) const STUFFING_BYTE: u8 = 0xFF;
41
42/// Bit shift that places the high byte of a 16-bit field in position.
43const HIGH_BYTE_SHIFT: u32 = 8;
44
45/// Decode the 12-bit `section_length` field from a section's first 3 bytes
46/// (byte 1 bits 3-0 hi, byte 2 lo) and return the section's **total** size:
47/// `section_length + SECTION_HEADER_LEN`, the 3-byte common header plus every
48/// declared byte after it (ISO/IEC 13818-1 §2.4.4.1). Returns `None` if
49/// `bytes` has fewer than `SECTION_HEADER_LEN` bytes.
50///
51/// W14 (#1074): this decode used to be written out separately in four places
52/// (twice in this file, once in `mux.rs`, once in `section.rs`).
53pub(crate) fn section_total_len(bytes: &[u8]) -> Option<usize> {
54    if bytes.len() < SECTION_HEADER_LEN {
55        return None;
56    }
57    let section_length = ((bytes[SECTION_FLAGS_OFFSET] & SECTION_LENGTH_HI_MASK) as usize)
58        << HIGH_BYTE_SHIFT
59        | bytes[SECTION_LENGTH_LO_OFFSET] as usize;
60    Some(SECTION_HEADER_LEN + section_length)
61}
62
63/// 2-bit `transport_scrambling_control` field — ITU-T H.222.0 (08/2023) Table 2-4
64/// (defines only `00` = not scrambled); DVB assigns `01`/`10`/`11` in ETSI TS 100 289
65/// V1.1.1 §5.1 Table 1 (reserved, even CW, odd CW).
66///
67/// MPEG-2 leaves `01`/`10`/`11` as user-defined; DVB's common-scrambling convention
68/// assigns `10` = even control word, `11` = odd control word, `01` = reserved for future
69/// DVB use. The field lives in the TS header and is never applied to the header itself —
70/// only to the packet payload.
71#[non_exhaustive]
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize))]
74pub enum ScramblingControl {
75    /// `00` — not scrambled. The only MPEG-2-defined value (H.222.0 Table 2-4).
76    NotScrambled,
77    /// `01` — reserved for future DVB use (ETSI TS 100 289 V1.1.1 §5.1 Table 1).
78    Reserved,
79    /// `10` — TS packet payload scrambled with the **even** control word
80    /// (DVB common scrambling, ETSI TS 100 289 V1.1.1 §5.1 Table 1).
81    EvenKey,
82    /// `11` — TS packet payload scrambled with the **odd** control word
83    /// (DVB common scrambling, ETSI TS 100 289 V1.1.1 §5.1 Table 1).
84    OddKey,
85}
86
87impl ScramblingControl {
88    /// Decode from the 2-bit `transport_scrambling_control` value (masked to `[1:0]`).
89    pub fn from_bits(bits: u8) -> Self {
90        match bits & SCRAMBLING_BITS {
91            0b00 => Self::NotScrambled,
92            0b01 => Self::Reserved,
93            0b10 => Self::EvenKey,
94            _ => Self::OddKey,
95        }
96    }
97
98    /// Encode as the 2-bit `transport_scrambling_control` field value (`[1:0]`).
99    ///
100    /// The returned byte is in the range `0x00`–`0x03`; the caller shifts it
101    /// into position within the TS header byte 3 (H.222.0 Table 2-4).
102    pub fn to_bits(self) -> u8 {
103        match self {
104            Self::NotScrambled => 0b00,
105            Self::Reserved => 0b01,
106            Self::EvenKey => 0b10,
107            Self::OddKey => 0b11,
108        }
109    }
110
111    /// Short label for this value, per the #204 convention.
112    pub fn name(&self) -> &'static str {
113        match self {
114            Self::NotScrambled => "not_scrambled",
115            Self::Reserved => "reserved",
116            Self::EvenKey => "even_key",
117            Self::OddKey => "odd_key",
118        }
119    }
120}
121
122broadcast_core::impl_spec_display!(ScramblingControl);
123
124/// 2-bit `adaptation_field_control` field — ITU-T H.222.0 (08/2023) Table 2-5.
125///
126/// Decoders shall discard packets with value `00` (`Reserved`). Null packets use `01`
127/// (`PayloadOnly`). [`TsHeader::adaptation_field_control`] carries the value;
128/// [`TsHeader::has_adaptation`] / [`TsHeader::has_payload`] answer the two flag
129/// questions.
130#[non_exhaustive]
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132#[cfg_attr(feature = "serde", derive(serde::Serialize))]
133pub enum AdaptationFieldControl {
134    /// `00` — reserved for future use; decoders shall discard (H.222.0 Table 2-5).
135    Reserved,
136    /// `01` — no adaptation_field, payload only (H.222.0 Table 2-5).
137    PayloadOnly,
138    /// `10` — adaptation_field only, no payload (H.222.0 Table 2-5).
139    AdaptationOnly,
140    /// `11` — adaptation_field followed by payload (H.222.0 Table 2-5).
141    AdaptationAndPayload,
142}
143
144impl AdaptationFieldControl {
145    /// Convert the two decoded boolean flags into the field's value.
146    pub fn from_flags(has_adaptation: bool, has_payload: bool) -> Self {
147        match (has_adaptation, has_payload) {
148            (false, false) => Self::Reserved,
149            (false, true) => Self::PayloadOnly,
150            (true, false) => Self::AdaptationOnly,
151            (true, true) => Self::AdaptationAndPayload,
152        }
153    }
154
155    /// The `(has_adaptation, has_payload)` flag pair; the inverse of
156    /// [`from_flags`](Self::from_flags).
157    pub fn to_flags(self) -> (bool, bool) {
158        match self {
159            Self::Reserved => (false, false),
160            Self::PayloadOnly => (false, true),
161            Self::AdaptationOnly => (true, false),
162            Self::AdaptationAndPayload => (true, true),
163        }
164    }
165
166    /// Encode as the 2-bit `adaptation_field_control` field value (`[1:0]`).
167    ///
168    /// Bit 1 = adaptation present, bit 0 = payload present (H.222.0 Table 2-5).
169    /// The returned byte is in the range `0x00`–`0x03`; the caller shifts it
170    /// into bits `[5:4]` of TS header byte 3.
171    pub fn to_bits(self) -> u8 {
172        match self {
173            Self::Reserved => 0b00,
174            Self::PayloadOnly => 0b01,
175            Self::AdaptationOnly => 0b10,
176            Self::AdaptationAndPayload => 0b11,
177        }
178    }
179
180    /// Short label for this value, per the #204 convention.
181    pub fn name(&self) -> &'static str {
182        match self {
183            Self::Reserved => "reserved",
184            Self::PayloadOnly => "payload_only",
185            Self::AdaptationOnly => "adaptation_only",
186            Self::AdaptationAndPayload => "adaptation_and_payload",
187        }
188    }
189}
190
191broadcast_core::impl_spec_display!(AdaptationFieldControl);
192
193/// ISO/IEC 13818-1 §2.4.3.3: transport header byte 1 bit 7 = tei (Transport Error Indicator).
194const TEI_MASK: u8 = 0x80;
195/// ISO/IEC 13818-1 §2.4.3.3: byte 1 bit 6 = pusi (Payload Unit Start Indicator).
196const PUSI_MASK: u8 = 0x40;
197/// ISO/IEC 13818-1 §2.4.3.3: byte 1 bits `[4:0]` = 13-bit PID (upper 5 bits).
198pub const PID_MASK_HI: u8 = 0x1F;
199/// ISO/IEC 13818-1 §2.4.3.3: byte 3 bits `[7:6]` = 2-bit scrambling control.
200pub const SCRAMBLING_MASK: u8 = 0xC0;
201/// Shift of the 2-bit `transport_scrambling_control` in header byte 3.
202const SCRAMBLING_SHIFT: u32 = 6;
203/// Width mask of the 2-bit `transport_scrambling_control` value.
204const SCRAMBLING_BITS: u8 = SCRAMBLING_MASK >> SCRAMBLING_SHIFT;
205/// Shift of the 2-bit `adaptation_field_control` in header byte 3.
206const ADAPTATION_SHIFT: u32 = 4;
207/// Width mask of the 2-bit `adaptation_field_control` value.
208const ADAPTATION_CONTROL_MASK: u8 = 0b11;
209/// ISO/IEC 13818-1 §2.4.3.3: byte 3 bit 5 = adaptation_field_control (bit 5 = 1 means adaptation present).
210pub const ADAPTATION_FLAG: u8 = 0x20;
211/// ISO/IEC 13818-1 §2.4.3.3: byte 3 bit 4 = adaptation_field_control (bit 4 = 1 means payload present).
212pub const PAYLOAD_FLAG: u8 = 0x10;
213/// ISO/IEC 13818-1 §2.4.3.3: byte 3 bits `[3:0]` = 4-bit continuity_counter.
214pub const CC_MASK: u8 = 0x0F;
215
216/// Byte offset of the `tei`/`pusi`/PID-high-byte byte in the 4-byte TS header
217/// (ISO/IEC 13818-1 §2.4.3.3).
218const TEI_PUSI_PID_HI_OFFSET: usize = 1;
219/// Byte offset of the PID low byte in the 4-byte TS header.
220const PID_LO_OFFSET: usize = 2;
221/// Byte offset of the `transport_scrambling_control`/`adaptation_field_control`/
222/// `continuity_counter` byte in the 4-byte TS header.
223pub(crate) const SCRAMBLING_AFC_CC_OFFSET: usize = 3;
224
225/// The 4-bit `continuity_counter` field (ISO/IEC 13818-1 §2.4.3.3).
226///
227/// Wraps modulo 16 per PID; only packets that carry a payload increment it.
228/// The value is always `0..=15`, so an out-of-range counter cannot be written
229/// into a header.
230#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
231#[cfg_attr(feature = "serde", derive(serde::Serialize))]
232#[cfg_attr(feature = "serde", serde(transparent))]
233pub struct ContinuityCounter(u8);
234
235impl ContinuityCounter {
236    /// The counter value that starts a stream (`0`).
237    pub const ZERO: Self = Self(0);
238
239    /// The counter after `self`: `(self + 1) mod 16`.
240    #[must_use]
241    pub const fn next(self) -> Self {
242        Self((self.0 + 1) % COUNT_MODULUS)
243    }
244
245    /// The raw 4-bit value (`0..=15`).
246    #[must_use]
247    pub const fn value(self) -> u8 {
248        self.0
249    }
250
251    /// The forward distance from `from` to `self`, `(self - from) mod 16`:
252    /// `1` for an in-order step, `0` for a duplicate, `2` for one lost
253    /// packet, wrapping correctly from 15 to 0.
254    #[must_use]
255    pub const fn forward_distance_from(self, from: Self) -> u8 {
256        (self.0 + COUNT_MODULUS - from.0) % COUNT_MODULUS
257    }
258
259    /// Construct from a raw value, rejecting anything wider than 4 bits.
260    ///
261    /// # Errors
262    /// [`ContinuityCounterOutOfRange`] when `value > 15`.
263    pub const fn try_new(value: u8) -> core::result::Result<Self, ContinuityCounterOutOfRange> {
264        if value > CC_MASK {
265            Err(ContinuityCounterOutOfRange { value })
266        } else {
267            Ok(Self(value))
268        }
269    }
270
271    /// Construct from the low 4 bits of `value`, **deliberately** discarding
272    /// the rest: the explicit name for extracting the field out of header
273    /// byte 3 (ISO/IEC 13818-1 §2.4.3.3, bits `[3:0]`).
274    #[must_use]
275    pub const fn from_wire_masked(value: u8) -> Self {
276        Self(value & CC_MASK)
277    }
278}
279
280/// The modulus of the 4-bit `continuity_counter` (ISO/IEC 13818-1 §2.4.3.3).
281const COUNT_MODULUS: u8 = CC_MASK + 1;
282
283impl From<ContinuityCounter> for u8 {
284    fn from(cc: ContinuityCounter) -> Self {
285        cc.0
286    }
287}
288
289impl TryFrom<u8> for ContinuityCounter {
290    type Error = ContinuityCounterOutOfRange;
291    fn try_from(value: u8) -> core::result::Result<Self, Self::Error> {
292        Self::try_new(value)
293    }
294}
295
296impl core::fmt::Debug for ContinuityCounter {
297    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
298        write!(f, "ContinuityCounter({})", self.0)
299    }
300}
301
302impl core::fmt::Display for ContinuityCounter {
303    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
304        write!(f, "{}", self.0)
305    }
306}
307
308/// A value that does not fit the 4-bit `continuity_counter` field
309/// (ISO/IEC 13818-1 §2.4.3.3).
310#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
311#[error("continuity_counter {value} exceeds the 4-bit range 0..=15")]
312#[non_exhaustive]
313pub struct ContinuityCounterOutOfRange {
314    /// The rejected value.
315    pub value: u8,
316}
317
318/// Parsed TS header — the 4-byte transport header fields.
319#[derive(Clone, Debug, PartialEq, Eq)]
320#[cfg_attr(feature = "serde", derive(serde::Serialize))]
321pub struct TsHeader {
322    /// Transport Error Indicator — set by the demodulator when an
323    /// uncorrectable error is present in the packet.
324    pub tei: bool,
325    /// Payload Unit Start Indicator — first byte of the payload is a new
326    /// PES packet or PSI section header when set.
327    pub pusi: bool,
328    /// 13-bit Packet Identifier.
329    pub pid: Pid,
330    /// 2-bit `transport_scrambling_control` (ISO/IEC 13818-1 Table 2-4; DVB
331    /// assigns `01`/`10`/`11`, see [`ScramblingControl`]).
332    pub scrambling: ScramblingControl,
333    /// 2-bit `adaptation_field_control` (ISO/IEC 13818-1 Table 2-5): whether
334    /// the adaptation field and/or the payload follow the header.
335    ///
336    /// The enum, not a pair of flags: the reserved `00` state is a named
337    /// variant and swapping the two flags is no longer possible.
338    #[cfg_attr(feature = "serde", serde(rename = "adaptation"))]
339    pub adaptation_field_control: AdaptationFieldControl,
340    /// 4-bit `continuity_counter` (wraps 0..=15 per PID).
341    pub continuity_counter: ContinuityCounter,
342}
343
344/// Borrowed view into one 188-byte TS packet.
345///
346/// Serde: Serialize-only (re-parse from wire bytes to reconstruct). `raw` is
347/// excluded from the serialized form because it is redundant once the header
348/// has been parsed.
349#[derive(Clone, Debug)]
350#[cfg_attr(feature = "serde", derive(serde::Serialize))]
351pub struct TsPacket<'a> {
352    /// Parsed header fields.
353    pub header: TsHeader,
354    /// Slice into the packet's payload, or `None` when there is no payload
355    /// (`adaptation_field_control` has its payload bit clear) or the
356    /// adaptation field consumed the whole packet body.
357    pub payload: Option<&'a [u8]>,
358    /// The adaptation-field bytes (after the length byte). Internal capture
359    /// feeding [`adaptation_field`](Self::adaptation_field); not public.
360    #[cfg_attr(feature = "serde", serde(skip))]
361    adaptation: Option<&'a [u8]>,
362    /// The raw 188 bytes of the packet — kept for cheap forwarding.
363    #[cfg_attr(feature = "serde", serde(skip))]
364    pub raw: &'a [u8; TS_PACKET_SIZE],
365}
366
367impl TsHeader {
368    /// Parse a 4-byte TS transport header.
369    pub fn parse(raw4: &[u8]) -> Result<Self> {
370        need_in(raw4, TsHeader::serialized_len(), "TsHeader")?;
371        let b1 = raw4[TEI_PUSI_PID_HI_OFFSET];
372        let b2 = raw4[PID_LO_OFFSET];
373        let b3 = raw4[SCRAMBLING_AFC_CC_OFFSET];
374
375        let tei = (b1 & TEI_MASK) != 0;
376        let pusi = (b1 & PUSI_MASK) != 0;
377        let pid =
378            Pid::from_wire_masked((u16::from(b1 & PID_MASK_HI) << HIGH_BYTE_SHIFT) | u16::from(b2));
379        let has_adaptation = (b3 & ADAPTATION_FLAG) != 0;
380        let has_payload = (b3 & PAYLOAD_FLAG) != 0;
381
382        Ok(Self {
383            tei,
384            pusi,
385            pid,
386            scrambling: ScramblingControl::from_bits(b3 >> SCRAMBLING_SHIFT),
387            adaptation_field_control: AdaptationFieldControl::from_flags(
388                has_adaptation,
389                has_payload,
390            ),
391            continuity_counter: ContinuityCounter::from_wire_masked(b3),
392        })
393    }
394
395    /// Number of bytes written by [`serialize_into`](Self::serialize_into).
396    pub const fn serialized_len() -> usize {
397        4
398    }
399
400    /// The 4 header bytes, infallibly encoded.
401    #[must_use]
402    pub fn to_bytes(&self) -> [u8; 4] {
403        let mut b = [0u8; 4];
404        b[0] = TS_SYNC_BYTE;
405        if self.tei {
406            b[1] |= TEI_MASK;
407        }
408        if self.pusi {
409            b[1] |= PUSI_MASK;
410        }
411        let pid = self.pid.value();
412        b[TEI_PUSI_PID_HI_OFFSET] |= ((pid >> HIGH_BYTE_SHIFT) as u8) & PID_MASK_HI;
413        b[PID_LO_OFFSET] = pid.to_be_bytes()[1];
414        b[SCRAMBLING_AFC_CC_OFFSET] = (self.scrambling.to_bits() << SCRAMBLING_SHIFT)
415            | ((self.adaptation_field_control.to_bits() & ADAPTATION_CONTROL_MASK)
416                << ADAPTATION_SHIFT)
417            | self.continuity_counter.value();
418        b
419    }
420
421    /// Serialize this header into the first 4 bytes of `buf`.
422    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
423        need_out(buf, TsHeader::serialized_len(), "TsHeader")?;
424        buf[..TsHeader::serialized_len()].copy_from_slice(&self.to_bytes());
425        Ok(TsHeader::serialized_len())
426    }
427
428    /// Whether an adaptation field follows the header
429    /// (`adaptation_field_control` bit 1, ISO/IEC 13818-1 Table 2-5).
430    pub fn has_adaptation(&self) -> bool {
431        self.adaptation_field_control.to_flags().0
432    }
433
434    /// Whether a payload follows the header/adaptation field
435    /// (`adaptation_field_control` bit 0, ISO/IEC 13818-1 Table 2-5).
436    pub fn has_payload(&self) -> bool {
437        self.adaptation_field_control.to_flags().1
438    }
439}
440
441impl<'a> broadcast_core::Parse<'a> for TsHeader {
442    type Error = Error;
443
444    fn parse(bytes: &'a [u8]) -> Result<Self> {
445        TsHeader::parse(bytes)
446    }
447}
448
449impl broadcast_core::Serialize for TsHeader {
450    type Error = Error;
451
452    fn serialized_len(&self) -> usize {
453        TsHeader::serialized_len()
454    }
455
456    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
457        TsHeader::serialize_into(self, buf)
458    }
459}
460
461/// Byte range of the adaptation field's **body** (flags byte through the end
462/// of the declared field) within a raw TS packet — ISO/IEC 13818-1 §2.4.3.4.
463///
464/// Returns `None` when `has_adaptation` is false, when the packet is too short
465/// to carry the length byte, when `adaptation_field_length` is zero, or when
466/// the declared field would run past the end of `pkt`. This is the single
467/// adaptation-field locator: `TsPacket::parse`, `extract_ts_payload`,
468/// `OwnedTsPacket::adaptation_field` and the clock-reference lookup all derive
469/// the field's position from it.
470pub(crate) fn adaptation_field_body_range(
471    pkt: &[u8],
472    has_adaptation: bool,
473) -> Option<core::ops::Range<usize>> {
474    if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
475        return None;
476    }
477    let af_len = pkt[AF_LEN_BYTE] as usize;
478    if af_len == 0 {
479        return None;
480    }
481    let start = AF_FLAGS_BYTE;
482    let end = start + af_len;
483    if end > pkt.len() {
484        return None;
485    }
486    Some(start..end)
487}
488
489/// Bytes to skip from byte 4 (right after the 4-byte header) to reach the
490/// payload: `0` when there is no adaptation field, else
491/// `1 + adaptation_field_length` (the length byte itself, plus its declared
492/// body) — ISO/IEC 13818-1 §2.4.3.4. Derived from
493/// [`adaptation_field_body_range`], the one adaptation-field locator.
494fn adaptation_field_skip(pkt: &[u8], has_adaptation: bool) -> usize {
495    if !has_adaptation || pkt.len() <= AF_LEN_BYTE {
496        return 0;
497    }
498    1 + pkt[AF_LEN_BYTE] as usize
499}
500
501/// Outcome of locating a clock-reference (PCR or OPCR) field within a raw TS
502/// packet — ISO/IEC 13818-1 §2.4.3.4. [`clock_reference_slot`] is the one
503/// locator `set_pcr`/`set_opcr` (`owned.rs`) and the duplicate-detection PCR
504/// exemption (`ts_dup.rs`) both use.
505pub(crate) enum ClockReferenceSlot {
506    /// The field's 6-byte byte range within the packet.
507    Field(core::ops::Range<usize>),
508    /// No adaptation field, or a zero-length one.
509    NoAdaptationField,
510    /// The adaptation field is shorter than the flags byte plus the field.
511    TooShort {
512        /// Bytes the field needs (`flags byte + fields before it + 6`).
513        need: usize,
514        /// `adaptation_field_length` the packet declares.
515        have: usize,
516    },
517    /// The adaptation field's flags byte does not set this field's flag.
518    FlagClear,
519    /// The declared field runs past the end of `pkt` (a truncated capture).
520    Truncated {
521        /// Bytes the field needs to reach its end.
522        need: usize,
523        /// Bytes actually available.
524        have: usize,
525    },
526}
527
528/// Locate the `PCR` (`flag == AF_PCR_FLAG`) or `OPCR` (`flag == AF_OPCR_FLAG`)
529/// field within `pkt`, accounting for the flags byte and the field order
530/// (PCR precedes OPCR, each 6 bytes) — ISO/IEC 13818-1 §2.4.3.4/§2.4.3.5.
531pub(crate) fn clock_reference_slot(pkt: &[u8], flag: u8) -> ClockReferenceSlot {
532    if pkt.len() <= AF_LEN_BYTE || pkt[SCRAMBLING_AFC_CC_OFFSET] & ADAPTATION_FLAG == 0 {
533        return ClockReferenceSlot::NoAdaptationField;
534    }
535    let af_len = pkt[AF_LEN_BYTE] as usize;
536    if af_len == 0 {
537        return ClockReferenceSlot::NoAdaptationField;
538    }
539    // Flags byte (1) + every clock-reference field preceding `flag` + the
540    // field itself. Only PCR and OPCR exist, PCR first.
541    let preceding = if flag == AF_OPCR_FLAG {
542        PCR_FIELD_LEN
543    } else {
544        0
545    };
546    let need = 1 + preceding + PCR_FIELD_LEN;
547    if af_len < need {
548        return ClockReferenceSlot::TooShort { need, have: af_len };
549    }
550    if pkt.len() <= AF_FLAGS_BYTE || pkt[AF_FLAGS_BYTE] & flag == 0 {
551        return ClockReferenceSlot::FlagClear;
552    }
553    let start = CLOCK_REFERENCE_START + preceding;
554    let end = start + PCR_FIELD_LEN;
555    if end > pkt.len() {
556        return ClockReferenceSlot::Truncated {
557            need: end,
558            have: pkt.len(),
559        };
560    }
561    ClockReferenceSlot::Field(start..end)
562}
563
564/// Byte range of the payload within a 188-byte TS packet, or `None` when the
565/// packet carries none (`adaptation_field_control` without the payload bit,
566/// or an adaptation field that fills the packet). Lets a caller that must
567/// write into its own buffer find the payload without a second walk of the
568/// adaptation field.
569#[must_use]
570pub fn payload_range(raw: &[u8; TS_PACKET_SIZE]) -> Option<core::ops::Range<usize>> {
571    let header = TsHeader::parse(&raw[..TsHeader::serialized_len()]).ok()?;
572    if !header.has_payload() {
573        return None;
574    }
575    let start = TsHeader::serialized_len() + adaptation_field_skip(raw, header.has_adaptation());
576    (start < TS_PACKET_SIZE).then_some(start..TS_PACKET_SIZE)
577}
578
579impl<'a> TsPacket<'a> {
580    /// Parse a single 188-byte TS packet from a buffer.
581    ///
582    /// Returns `Err(Error::InvalidSync)` if the first byte is not `0x47`,
583    /// `Err(Error::BufferTooShort)` if fewer than 188 bytes, or `Ok` with
584    /// the parsed packet otherwise.
585    pub fn parse(buf: &'a [u8]) -> Result<Self> {
586        need_in(buf, TS_PACKET_SIZE, "TsPacket")?;
587        if buf[0] != TS_SYNC_BYTE {
588            return Err(Error::InvalidSync(broadcast_core::error::InvalidSync::new(
589                "TS sync byte",
590                u32::from(TS_SYNC_BYTE),
591                u32::from(buf[0]),
592            )));
593        }
594
595        let raw: &[u8; TS_PACKET_SIZE] = buf[..TS_PACKET_SIZE].try_into().map_err(|_| {
596            Error::BufferTooShort(broadcast_core::error::BufferTooShort::new(
597                TS_PACKET_SIZE,
598                buf.len(),
599                "TsPacket::parse (array conversion)",
600            ))
601        })?;
602
603        let header = TsHeader::parse(&raw[..TsHeader::serialized_len()])?;
604
605        let mut payload = None;
606
607        // Capture the adaptation field if present, then skip it (the section
608        // path does not need it; decode lazily via `adaptation_field`).
609        //
610        // W6 (#1074): `adaptation_field_length` is only valid up to 183 (the
611        // 183 bytes remaining after the 4-byte header + this length byte,
612        // ISO/IEC 13818-1 §2.4.3.4). An oversized value used to be silently
613        // `.min()`-truncated to a shorter slice here, while
614        // `OwnedTsPacket::adaptation_field` rejected the same bytes as `None`
615        // — two views of one wire format disagreeing on a malformed AF.
616        // Reject (this crate's existing policy in `owned.rs`) rather than
617        // truncate: leave `adaptation` as `None` for an over-long field, same
618        // as `OwnedTsPacket`.
619        let adaptation = adaptation_field_body_range(raw, header.has_adaptation()).map(|r| &raw[r]);
620        if let Some(range) = payload_range(raw) {
621            payload = Some(&raw[range]);
622        }
623
624        Ok(TsPacket {
625            header,
626            payload,
627            adaptation,
628            raw,
629        })
630    }
631
632    /// Decode the adaptation field, if present.
633    ///
634    /// Returns `None` when the packet carries no adaptation field, and
635    /// `Some(Err(..))` when a present field is truncated. Layout per
636    /// ISO/IEC 13818-1:2007 §2.4.3.4 (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/transport_packet.md`).
637    pub fn adaptation_field(&self) -> Option<crate::Result<AdaptationField<'a>>> {
638        self.adaptation.map(AdaptationField::parse)
639    }
640}
641
642// Adaptation-field flag bits, byte 0 (ISO/IEC 13818-1:2007 §2.4.3.4).
643/// `discontinuity_indicator` bit of the adaptation-field flags byte (§2.4.3.5).
644pub const AF_DISCONTINUITY: u8 = 0x80;
645pub(crate) const AF_RANDOM_ACCESS: u8 = 0x40;
646pub(crate) const AF_ES_PRIORITY: u8 = 0x20;
647/// PCR present flag (bit 4 of adaptation field flags byte — §2.4.3.4).
648pub const AF_PCR_FLAG: u8 = 0x10;
649pub(crate) const AF_OPCR_FLAG: u8 = 0x08;
650pub(crate) const AF_SPLICING_FLAG: u8 = 0x04;
651pub(crate) const AF_TRANSPORT_PRIVATE_DATA_FLAG: u8 = 0x02;
652pub(crate) const AF_EXTENSION_FLAG: u8 = 0x01;
653/// PCR field byte 4 bits 6-1: six reserved bits, all set to `1`
654/// (ISO/IEC 13818-1 §2.4.3.5).
655pub(crate) const PCR_RESERVED_BITS: u8 = 0x7E;
656/// Number of reserved bits beside the PCR/OPCR base bits (six).
657const PCR_RESERVED_BITS_COUNT: u32 = 6;
658/// The 6 reserved bits sit at bits 6-1 of PCR byte 4.
659pub(crate) const PCR_RESERVED_SHIFT: u32 = 1;
660/// Byte offset of the reserved bits inside the 6-byte PCR/OPCR field.
661pub(crate) const PCR_RESERVED_BYTE_OFFSET: usize = 4;
662/// 6-bit value of those reserved bits per the spec convention (all `1`).
663const PCR_RESERVED_VALUE: u8 = 0x3F;
664/// Encoded PCR / OPCR field width: 33-bit base + 6 reserved + 9-bit extension.
665pub(crate) const PCR_FIELD_LEN: usize = 6;
666/// Mask of one packed byte of the PCR/OPCR field.
667const PCR_FIELD_BYTE_MASK: u64 = 0xFF;
668/// Bit shifts of the packed 33-bit PCR/OPCR base within the 6-byte field
669/// (ISO/IEC 13818-1 §2.4.3.5).
670const PCR_BASE_SHIFT_HI: u32 = 25;
671const PCR_BASE_SHIFT_HI_MID: u32 = 17;
672const PCR_BASE_SHIFT_LO_MID: u32 = 9;
673const PCR_BASE_SHIFT_LO: u32 = 1;
674/// Bit shift of the base's least-significant bit inside the reserved-bits byte.
675const PCR_BASE_LSB_SHIFT: u32 = 7;
676/// Mask of the base's least-significant bit.
677const PCR_BASE_LSB_MASK: u64 = 0x01;
678/// Bit shift of the extension's most-significant bit inside the reserved-bits
679/// byte.
680const PCR_EXTENSION_HI_SHIFT: u32 = 8;
681/// Mask of the extension's most-significant bit.
682const PCR_EXTENSION_HI_MASK: u8 = 0x01;
683
684/// Byte offset of `adaptation_field_length` within a raw TS packet —
685/// ISO/IEC 13818-1 §2.4.3.4.
686pub(crate) const AF_LEN_BYTE: usize = 4;
687/// Byte offset of the adaptation-field flags byte, immediately after
688/// `adaptation_field_length` — ISO/IEC 13818-1 §2.4.3.4 Table 2-6.
689pub(crate) const AF_FLAGS_BYTE: usize = 5;
690/// Byte offset of the first clock-reference (PCR/OPCR) byte, immediately
691/// after the flags byte — ISO/IEC 13818-1 §2.4.3.4.
692pub(crate) const CLOCK_REFERENCE_START: usize = AF_FLAGS_BYTE + 1;
693
694/// Program Clock Reference (ISO/IEC 13818-1:2007 §2.4.3.5): a 33-bit base on a
695/// 90 kHz clock plus a 9-bit extension on a 27 MHz clock.
696///
697/// Constructing is strict: [`from_parts`](Self::from_parts) / [`from_27mhz`](Self::from_27mhz)
698/// reject parts that do not name a position on the 27 MHz clock, and
699/// [`clock`](Self::clock) hands back the validated
700/// [`broadcast_common::clock33::Clock27`] shared with the ESCR and the
701/// program-stream SCR. Parsing is lossless: the wire extension is 9 bits, so a
702/// real capture can carry `300..=511`, which this type keeps exactly as written
703/// and re-serializes byte-identically; [`to_clock27`](Self::to_clock27) is the
704/// checked view that reports such a value as
705/// [`Error::ClockOutOfRange`].
706#[derive(Clone, Copy, Debug, PartialEq, Eq)]
707#[cfg_attr(feature = "serde", derive(serde::Serialize))]
708pub struct Pcr(broadcast_common::clock33::Clock27);
709
710impl Pcr {
711    /// Construct from the two wire parts, checking both widths.
712    ///
713    /// # Errors
714    /// [`Error::ClockOutOfRange`] when `base >= 2^33` or `extension >= 300`.
715    pub fn from_parts(base: u64, extension: u16) -> Result<Self> {
716        Ok(Self(broadcast_common::clock33::Clock27::from_parts(
717            base, extension,
718        )?))
719    }
720
721    /// Construct from an absolute 27 MHz clock value, clamping nothing.
722    ///
723    /// # Errors
724    /// [`Error::ClockOutOfRange`] when `ticks >= 2^33 * 300`.
725    pub fn from_27mhz(ticks: u64) -> Result<Self> {
726        Ok(Self(broadcast_common::clock33::Clock27::from_27mhz(ticks)?))
727    }
728
729    /// The validated 27 MHz value.
730    ///
731    /// # Errors
732    /// [`Error::ClockOutOfRange`] for a parsed PCR whose extension is at or
733    /// above 300 (off the 27 MHz clock).
734    pub fn to_clock27(self) -> Result<broadcast_common::clock33::Clock27> {
735        Ok(self.0.to_clock27()?)
736    }
737
738    /// The underlying value, kept exactly as the wire carried it (see the
739    /// type's docs on the lossless parse).
740    #[must_use]
741    pub const fn clock(self) -> broadcast_common::clock33::Clock27 {
742        self.0
743    }
744
745    /// 33-bit base (90 kHz units).
746    #[must_use]
747    pub const fn base(self) -> u64 {
748        self.0.base.ticks()
749    }
750
751    /// 9-bit extension as carried: `0..=299` on the 27 MHz clock, `300..=511`
752    /// for a parsed value off it (see [`to_clock27`](Self::to_clock27)).
753    #[must_use]
754    pub const fn extension(self) -> u16 {
755        self.0.ext
756    }
757
758    /// Full PCR value on the 27 MHz clock: `base * 300 + extension`.
759    ///
760    /// ISO/IEC 13818-1:2007 §2.4.3.5: PCR = `PCR_base * 300 + PCR_ext`. For a
761    /// parsed value whose extension is at or above 300 this is not a time on
762    /// the clock; check [`to_clock27`](Self::to_clock27) first.
763    #[must_use]
764    pub fn as_27mhz(self) -> u64 {
765        self.0.ticks()
766    }
767
768    /// Encode as the exact 6-byte PCR/OPCR field used in the adaptation field
769    /// (ISO/IEC 13818-1:2007 §2.4.3.5).
770    ///
771    /// Wire layout (big-endian, 48 bits):
772    /// `[base[32:25]][base[24:17]][base[16:9]][base[8:1]][base[0] | 6×reserved(1) | ext[8]][ext[7:0]]`
773    ///
774    /// The 6 reserved bits are set to `1` as per the spec's "reserved" convention.
775    /// Exact inverse of the private `parse` function, including an off-clock
776    /// extension a parsed value kept.
777    #[must_use]
778    pub fn to_field_bytes(self) -> [u8; PCR_FIELD_LEN] {
779        let b = self.0.base.ticks();
780        let e = u64::from(self.0.ext);
781        [
782            ((b >> PCR_BASE_SHIFT_HI) & PCR_FIELD_BYTE_MASK) as u8,
783            ((b >> PCR_BASE_SHIFT_HI_MID) & PCR_FIELD_BYTE_MASK) as u8,
784            ((b >> PCR_BASE_SHIFT_LO_MID) & PCR_FIELD_BYTE_MASK) as u8,
785            ((b >> PCR_BASE_SHIFT_LO) & PCR_FIELD_BYTE_MASK) as u8,
786            // byte 4: base[0] in bit 7, bits 6-1 = reserved (set to 1), ext[8] in bit 0.
787            (((b & PCR_BASE_LSB_MASK) as u8) << PCR_BASE_LSB_SHIFT)
788                | PCR_RESERVED_BITS
789                | ((e >> PCR_EXTENSION_HI_SHIFT) as u8 & PCR_EXTENSION_HI_MASK),
790            (e & PCR_FIELD_BYTE_MASK) as u8,
791        ]
792    }
793
794    /// The 6-byte PCR/OPCR field, keeping the 6 `reserved` bits a captured
795    /// packet already carries in `reserved`.
796    ///
797    /// # Errors
798    ///
799    /// [`Error::FieldOverflow`] when `reserved` is wider than the 6-bit field.
800    pub fn to_field_bytes_with_reserved(self, reserved: u8) -> Result<[u8; PCR_FIELD_LEN]> {
801        let mut field = self.to_field_bytes();
802        set_pcr_reserved(&mut field, reserved)?;
803        Ok(field)
804    }
805
806    /// Decode six PCR/OPCR field bytes (`buf[from..from + 6]`).
807    ///
808    /// Lossless for every field the wire can carry: the 9-bit extension is kept
809    /// as read (`0..=511`) so the packet round-trips byte-identically, and a
810    /// value off the 27 MHz clock is reported by
811    /// [`to_clock27`](Self::to_clock27), not here.
812    pub(crate) fn parse(buf: &[u8], from: usize) -> Result<Self> {
813        let end = from + PCR_FIELD_LEN;
814        let b: &[u8; PCR_FIELD_LEN] =
815            buf.get(from..end)
816                .and_then(|s| s.try_into().ok())
817                .ok_or(Error::BufferTooShort(
818                    broadcast_core::error::BufferTooShort::new(
819                        end,
820                        buf.len(),
821                        "adaptation_field PCR",
822                    ),
823                ))?;
824        let [b0, b1, b2, b3, b4, b5] = *b;
825        let base = (u64::from(b0) << PCR_BASE_SHIFT_HI)
826            | (u64::from(b1) << PCR_BASE_SHIFT_HI_MID)
827            | (u64::from(b2) << PCR_BASE_SHIFT_LO_MID)
828            | (u64::from(b3) << PCR_BASE_SHIFT_LO)
829            | (u64::from(b4) >> PCR_BASE_LSB_SHIFT);
830        let extension =
831            (u16::from(b4 & PCR_EXTENSION_HI_MASK) << PCR_EXTENSION_HI_SHIFT) | u16::from(b5);
832        Ok(Self(broadcast_common::clock33::Clock27::from_wire_parts(
833            base, extension,
834        )))
835    }
836}
837
838// ── Adaptation-field extension sub-structures (ISO/IEC 13818-1 §2.4.3.5) ──────
839
840/// `legal_time_window` field within the adaptation-field extension
841/// (ISO/IEC 13818-1:2007 §2.4.3.5, `ltw_flag == 1`).
842///
843/// Wire layout: `ltw_valid_flag(1) | ltw_offset(15)` = 2 bytes.
844#[derive(Clone, Copy, Debug, PartialEq, Eq)]
845#[cfg_attr(feature = "serde", derive(serde::Serialize))]
846pub struct Ltw {
847    /// LTW offset valid flag.
848    pub ltw_valid_flag: bool,
849    /// Offset from the PCR to the start of the legal time window, in
850    /// 27 MHz clock ticks (ISO/IEC 13818-1 §2.4.3.5); meaningful only when
851    /// `ltw_valid_flag` is set.
852    pub ltw_offset: LtwOffset,
853}
854
855/// A 15-bit `ltw_offset` (ISO/IEC 13818-1 §2.4.3.5), the lower bound of the
856/// legal time window.
857///
858/// Construction checks the wire width, so a value that does not fit cannot
859/// reach the serializer and become a different valid offset.
860#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
861#[cfg_attr(feature = "serde", derive(serde::Serialize))]
862#[cfg_attr(feature = "serde", serde(transparent))]
863pub struct LtwOffset(u16);
864
865/// Number of bits in the `ltw_offset` wire field (ISO/IEC 13818-1 Table 2-6).
866const LTW_OFFSET_BITS: u32 = 15;
867
868impl LtwOffset {
869    /// The largest offset the 15-bit wire field carries.
870    pub const MAX: Self = Self((1 << LTW_OFFSET_BITS) - 1);
871
872    /// A zero offset.
873    pub const ZERO: Self = Self(0);
874
875    /// Wrap a value, or [`Error::FieldOverflow`] if it does not fit 15 bits.
876    pub fn new(value: u16) -> Result<Self> {
877        let fitted =
878            broadcast_core::len::fit_bits(u64::from(value), LTW_OFFSET_BITS, "ltw_offset")?;
879        Ok(Self(fitted as u16))
880    }
881
882    /// Parse the `ltw_offset` field as written on the wire.
883    ///
884    /// The masked value is at most 15 bits, so the narrowing conversion is
885    /// lossless.
886    #[must_use]
887    pub(crate) fn from_wire_masked(high: u8, low: u8) -> Self {
888        Self((u16::from(high & LTW_OFFSET_HI_MASK) << HIGH_BYTE_SHIFT) | u16::from(low))
889    }
890
891    /// The offset value.
892    #[must_use]
893    pub fn get(self) -> u16 {
894        self.0
895    }
896}
897
898impl From<LtwOffset> for u16 {
899    fn from(value: LtwOffset) -> Self {
900        value.0
901    }
902}
903
904impl core::fmt::Display for LtwOffset {
905    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
906        write!(f, "{}", self.0)
907    }
908}
909
910/// `seamless_splice` field within the adaptation-field extension
911/// (ISO/IEC 13818-1:2007 §2.4.3.5, `seamless_splice_flag == 1`).
912///
913/// Wire layout: 5 bytes — `splice_type(4) | DTS_next_AU[32:30](3) | marker(1) |
914/// DTS_next_AU[29:15](15) | marker(1) | DTS_next_AU[14:0](15) | marker(1)`.
915/// The DTS field uses the same marker-bit encoding as PTS/DTS in PES headers.
916///
917/// `#[non_exhaustive]`: build with [`SeamlessSplice::new`].
918#[non_exhaustive]
919#[derive(Clone, Copy, Debug, PartialEq, Eq)]
920#[cfg_attr(feature = "serde", derive(serde::Serialize))]
921pub struct SeamlessSplice {
922    /// 4-bit `splice_type`.
923    pub splice_type: u8,
924    /// 33-bit `DTS_next_AU` (90 kHz decoding time of the next splice unit).
925    pub dts_next_au: u64,
926    /// The three `marker_bit`s of `DTS_next_AU` (Table 2-6), packed as
927    /// `0b<byte0><byte2><byte4>`; the spec fixes them to `1` (`0b111`), but a
928    /// real stream (TSDuck `test-147.ts`) carries `0`, so they are kept for a
929    /// byte-exact round trip.
930    pub marker_bits: u8,
931}
932
933/// Bits in the `splice_type` nibble (`DTS_next_AU` field, Table 2-6).
934const SPLICE_TYPE_BITS: u32 = 4;
935/// Bits in `DTS_next_AU` (a 33-bit decoding time, as in a PES PTS/DTS field).
936const DTS_NEXT_AU_BITS: u32 = 33;
937/// Bits in the three `marker_bit`s of `DTS_next_AU`.
938const SPLICE_MARKER_BITS: u32 = 3;
939
940impl SeamlessSplice {
941    /// A seamless-splice field with spec-conformant marker bits (all `1`).
942    #[must_use]
943    pub const fn new(splice_type: u8, dts_next_au: u64) -> Self {
944        Self {
945            splice_type,
946            dts_next_au,
947            marker_bits: SPLICE_MARKERS_VALUE,
948        }
949    }
950
951    /// The number of bits the `DTS_next_AU` wire field carries.
952    pub const DTS_NEXT_AU_BITS: u32 = DTS_NEXT_AU_BITS;
953
954    /// Parse the 5-byte `DTS_next_AU` field as written on the wire.
955    #[must_use]
956    pub(crate) fn from_marked_field(field: &[u8; DTS_NEXT_AU_FIELD_LEN]) -> Self {
957        let m = broadcast_common::clock33::unpack_marked(field);
958        Self {
959            splice_type: m.prefix,
960            dts_next_au: m.timestamp,
961            marker_bits: m.markers,
962        }
963    }
964
965    /// The 5 `DTS_next_AU` field bytes, or [`Error::FieldOverflow`] when a
966    /// field does not fit its wire width.
967    pub fn to_marked_field(&self) -> Result<[u8; DTS_NEXT_AU_FIELD_LEN]> {
968        broadcast_core::len::fit_bits(
969            u64::from(self.splice_type),
970            SPLICE_TYPE_BITS,
971            "seamless_splice.splice_type",
972        )?;
973        broadcast_core::len::fit_bits(
974            self.dts_next_au,
975            DTS_NEXT_AU_BITS,
976            "seamless_splice.DTS_next_AU",
977        )?;
978        broadcast_core::len::fit_bits(
979            u64::from(self.marker_bits),
980            SPLICE_MARKER_BITS,
981            "seamless_splice.marker_bit",
982        )?;
983        Ok(broadcast_common::clock33::pack_marked_with(
984            self.dts_next_au,
985            self.splice_type,
986            self.marker_bits,
987        ))
988    }
989}
990
991// W15 (#1074): named flag/mask bits for the adaptation-field extension's
992// flags byte and its LTW/piecewise-rate sub-fields (ISO/IEC 13818-1 §2.4.3.5).
993/// All three `DTS_next_AU` `marker_bit`s set (`0b111`).
994const SPLICE_MARKERS_VALUE: u8 = 0x07;
995const AFE_LTW_FLAG: u8 = 0x80;
996const AFE_PIECEWISE_RATE_FLAG: u8 = 0x40;
997const AFE_SEAMLESS_SPLICE_FLAG: u8 = 0x20;
998/// `ltw_valid_flag` (1 bit) + `ltw_offset` high 7 bits share byte 0 of the LTW field.
999const LTW_OFFSET_HI_MASK: u8 = 0x7F;
1000/// 2 reserved bits (set to `1` on serialize) + `piecewise_rate` high 6 bits.
1001const PIECEWISE_RATE_HI_MASK: u8 = 0x3F;
1002/// `af_descriptor_not_present_flag` (Table 2-6; a reserved bit pre-2012).
1003const AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG: u8 = 0x10;
1004/// The 4 `reserved` bits of the extension flags byte.
1005const AFE_RESERVED_FLAGS_MASK: u8 = 0x0F;
1006/// Spec-convention value of those reserved bits (all `1`).
1007const AFE_RESERVED_FLAGS_VALUE: u8 = 0x0F;
1008/// The 2 `reserved` bits sit in the top of the first `piecewise_rate` byte.
1009const PIECEWISE_RATE_RESERVED_SHIFT: u32 = 6;
1010/// Spec-convention value of the 2 `reserved` bits (`'11'`).
1011const PIECEWISE_RATE_RESERVED_VALUE: u8 = 0x03;
1012/// Number of bits in the `piecewise_rate` wire field (ISO/IEC 13818-1 Table 2-6).
1013const PIECEWISE_RATE_BITS: u32 = 22;
1014/// Wire width of the `ltw_offset` field in the adaptation-field extension
1015/// (ISO/IEC 13818-1 Table 2-6).
1016const LTW_FIELD_LEN: usize = 2;
1017/// Wire width of the `piecewise_rate` field in the adaptation-field extension.
1018const PIECEWISE_RATE_FIELD_LEN: usize = 3;
1019/// Byte offsets of the `piecewise_rate` field's high, middle and low bytes.
1020const PIECEWISE_RATE_HI_OFFSET: usize = 0;
1021const PIECEWISE_RATE_MID_OFFSET: usize = PIECEWISE_RATE_HI_OFFSET + 1;
1022const PIECEWISE_RATE_LO_OFFSET: usize = PIECEWISE_RATE_MID_OFFSET + 1;
1023/// Bit shift of the `piecewise_rate` high byte within its 3-byte field.
1024const PIECEWISE_RATE_HI_SHIFT: u32 = 16;
1025/// Width in bytes of the `seamless_splice` `DTS_next_AU` field (ISO/IEC
1026/// 13818-1 §2.4.3.5, Table 2-6).
1027pub const DTS_NEXT_AU_FIELD_LEN: usize = 5;
1028/// Length of the `adaptation_field_extension_length` byte plus the extension
1029/// flags byte.
1030const AFE_PREFIX_LEN: usize = 2;
1031
1032/// Adaptation-field extension (ISO/IEC 13818-1 Table 2-6 / §2.4.3.5,
1033/// `adaptation_field_extension_flag == 1`).
1034///
1035/// Wire layout after `adaptation_field_extension_length`: `ltw_flag(1) |
1036/// piecewise_rate_flag(1) | seamless_splice_flag(1) |
1037/// af_descriptor_not_present_flag(1) | reserved(4)`, then the gated `ltw`,
1038/// `piecewise_rate` (`reserved(2) | rate(22)`) and `seamless_splice` fields,
1039/// then the remainder of the extension: `af_descriptor()` loop when
1040/// `af_descriptor_not_present_flag == 0`, otherwise `reserved` bytes.
1041///
1042/// Every bit the wire carries is kept in a typed field so parse -> serialize
1043/// is byte-exact; the only bits not preserved are the spec-mandated `1`
1044/// `marker_bit`s inside `DTS_next_AU`. The reserved nibble plus
1045/// `af_descriptor_not_present_flag` were one 5-bit `reserved` field in the
1046/// 1995/2000 editions, so a legacy stream (all five bits `1`) reads as
1047/// `af_descriptor_not_present_flag == true`.
1048///
1049/// `#[non_exhaustive]`: build with [`AdaptationFieldExtension::new`] and set
1050/// fields, so further additions are not a breaking change again.
1051#[non_exhaustive]
1052#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1053#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1054pub struct AdaptationFieldExtension<'a> {
1055    /// LTW (legal time window), if `ltw_flag` is set.
1056    pub ltw: Option<Ltw>,
1057    /// 22-bit piecewise rate, if `piecewise_rate_flag` is set.
1058    pub piecewise_rate: Option<PiecewiseRate>,
1059    /// The 2 `reserved` bits preceding `piecewise_rate` (spec convention
1060    /// `0b11`); only written when `piecewise_rate` is `Some`.
1061    pub piecewise_rate_reserved: u8,
1062    /// Seamless splice info, if `seamless_splice_flag` is set.
1063    pub seamless_splice: Option<SeamlessSplice>,
1064    /// `af_descriptor_not_present_flag`: `true` means the bytes in
1065    /// [`trailing`](Self::trailing) are `reserved`, `false` means they are an
1066    /// `af_descriptor()` loop (ISO/IEC 13818-1 Table 2-6).
1067    pub af_descriptor_not_present_flag: bool,
1068    /// The 4 `reserved` bits of the flags byte (spec convention `0b1111`).
1069    pub reserved_flags: u8,
1070    /// Bytes after the optional fields up to the end of
1071    /// `adaptation_field_extension_length`: an opaque `af_descriptor()` loop
1072    /// (flag `false`) or `reserved` bytes (flag `true`) per Table 2-6.
1073    pub trailing: &'a [u8],
1074}
1075
1076impl Default for AdaptationFieldExtension<'_> {
1077    fn default() -> Self {
1078        Self::new()
1079    }
1080}
1081
1082/// A 22-bit `piecewise_rate` (ISO/IEC 13818-1 §2.4.3.5), the bit rate of the
1083/// stream between two characters with a legal time window.
1084///
1085/// Construction checks the wire width, so a value that does not fit cannot
1086/// reach the serializer and become a different valid rate.
1087#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1088#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1089#[cfg_attr(feature = "serde", serde(transparent))]
1090pub struct PiecewiseRate(u32);
1091
1092impl PiecewiseRate {
1093    /// The largest rate the 22-bit wire field carries.
1094    pub const MAX: Self = Self((1 << PIECEWISE_RATE_BITS) - 1);
1095
1096    /// Wrap a value, or [`Error::FieldOverflow`] if it does not fit 22 bits.
1097    pub fn new(value: u32) -> Result<Self> {
1098        let fitted =
1099            broadcast_core::len::fit_bits(u64::from(value), PIECEWISE_RATE_BITS, "piecewise_rate")?;
1100        Ok(Self(fitted as u32))
1101    }
1102
1103    /// Parse the `piecewise_rate` field as written on the wire.
1104    ///
1105    /// The masked value is at most 22 bits, so the narrowing conversion is
1106    /// lossless.
1107    #[must_use]
1108    pub(crate) fn from_wire_masked(high: u8, mid: u8, low: u8) -> Self {
1109        Self(
1110            (u32::from(high & PIECEWISE_RATE_HI_MASK) << PIECEWISE_RATE_HI_SHIFT)
1111                | (u32::from(mid) << HIGH_BYTE_SHIFT)
1112                | u32::from(low),
1113        )
1114    }
1115
1116    /// The rate value.
1117    #[must_use]
1118    pub fn get(self) -> u32 {
1119        self.0
1120    }
1121}
1122
1123impl From<PiecewiseRate> for u32 {
1124    fn from(value: PiecewiseRate) -> Self {
1125        value.0
1126    }
1127}
1128
1129impl core::fmt::Display for PiecewiseRate {
1130    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1131        write!(f, "{}", self.0)
1132    }
1133}
1134
1135impl<'a> AdaptationFieldExtension<'a> {
1136    /// An extension with no optional fields, spec-convention reserved bits
1137    /// (all `1`), `af_descriptor_not_present_flag` set and no trailing bytes.
1138    #[must_use]
1139    pub const fn new() -> Self {
1140        Self {
1141            ltw: None,
1142            piecewise_rate: None,
1143            piecewise_rate_reserved: PIECEWISE_RATE_RESERVED_VALUE,
1144            seamless_splice: None,
1145            af_descriptor_not_present_flag: true,
1146            reserved_flags: AFE_RESERVED_FLAGS_VALUE,
1147            trailing: &[],
1148        }
1149    }
1150
1151    /// Parse the adaptation-field extension starting at `data[0]`
1152    /// (the `adaptation_field_extension_length` byte).
1153    fn parse(data: &'a [u8]) -> Result<Self> {
1154        need_in(data, 1, "adaptation_field_extension_length")?;
1155        let ext_len = data[0] as usize;
1156        // At least 1 byte (the flags byte) must be present inside the extension.
1157        if data.len() < 1 + ext_len || ext_len < 1 {
1158            return Err(Error::BufferTooShort(
1159                broadcast_core::error::BufferTooShort::new(
1160                    2.max(1 + ext_len),
1161                    data.len(),
1162                    "adaptation_field_extension body",
1163                ),
1164            ));
1165        }
1166        let ext = &data[1..1 + ext_len]; // extension bytes, starts with flags byte
1167        let flags = ext[0];
1168        let mut cursor = 1usize;
1169
1170        let ltw = if flags & AFE_LTW_FLAG != 0 {
1171            need_in(ext, cursor + LTW_FIELD_LEN, "ltw_offset")?;
1172            let w0 = ext[cursor];
1173            let w1 = ext[cursor + 1];
1174            cursor += LTW_FIELD_LEN;
1175            Some(Ltw {
1176                ltw_valid_flag: (w0 & AFE_LTW_FLAG) != 0,
1177                ltw_offset: LtwOffset::from_wire_masked(w0, w1),
1178            })
1179        } else {
1180            None
1181        };
1182
1183        let mut piecewise_rate_reserved = PIECEWISE_RATE_RESERVED_VALUE;
1184        let piecewise_rate = if flags & AFE_PIECEWISE_RATE_FLAG != 0 {
1185            need_in(ext, cursor + PIECEWISE_RATE_FIELD_LEN, "piecewise_rate")?;
1186            piecewise_rate_reserved = ext[cursor] >> PIECEWISE_RATE_RESERVED_SHIFT;
1187            let r = PiecewiseRate::from_wire_masked(
1188                ext[cursor + PIECEWISE_RATE_HI_OFFSET],
1189                ext[cursor + PIECEWISE_RATE_MID_OFFSET],
1190                ext[cursor + PIECEWISE_RATE_LO_OFFSET],
1191            );
1192            cursor += PIECEWISE_RATE_FIELD_LEN;
1193            Some(r)
1194        } else {
1195            None
1196        };
1197
1198        // seamless_splice: 5 bytes with splice_type(4) + DTS_next_AU in PTS-field encoding
1199        let seamless_splice = if flags & AFE_SEAMLESS_SPLICE_FLAG != 0 {
1200            need_in(
1201                ext,
1202                cursor + DTS_NEXT_AU_FIELD_LEN,
1203                "seamless_splice DTS_next_AU",
1204            )?;
1205            let mut field = [0_u8; DTS_NEXT_AU_FIELD_LEN];
1206            field.copy_from_slice(&ext[cursor..cursor + DTS_NEXT_AU_FIELD_LEN]);
1207            // DTS_next_AU uses the same 5-byte marker-bit encoding as PTS/DTS,
1208            // with `splice_type` in the prefix nibble.
1209            let splice = SeamlessSplice::from_marked_field(&field);
1210            cursor += DTS_NEXT_AU_FIELD_LEN;
1211            Some(splice)
1212        } else {
1213            None
1214        };
1215
1216        Ok(AdaptationFieldExtension {
1217            ltw,
1218            piecewise_rate,
1219            piecewise_rate_reserved,
1220            seamless_splice,
1221            af_descriptor_not_present_flag: flags & AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG != 0,
1222            reserved_flags: flags & AFE_RESERVED_FLAGS_MASK,
1223            trailing: &ext[cursor..],
1224        })
1225    }
1226
1227    /// Number of bytes written by [`serialize_into`](Self::serialize_into),
1228    /// **including** the leading `adaptation_field_extension_length` byte.
1229    #[must_use]
1230    pub fn serialized_len(&self) -> usize {
1231        let body = 1 // flags byte
1232            + self.ltw.map_or(0, |_| LTW_FIELD_LEN)
1233            + self.piecewise_rate.map_or(0, |_| PIECEWISE_RATE_FIELD_LEN)
1234            + self.seamless_splice.map_or(0, |_| DTS_NEXT_AU_FIELD_LEN)
1235            + self.trailing.len();
1236        1 + body // + length byte itself
1237    }
1238
1239    /// Serialize into `buf` (includes the `adaptation_field_extension_length` byte).
1240    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1241        let need = self.serialized_len();
1242        need_out(buf, need, "AdaptationFieldExtension")?;
1243        buf[0] = broadcast_core::len::fit_u8(need - 1, "adaptation_field_extension_length")?;
1244
1245        let mut flags = broadcast_core::len::fit_mask(
1246            self.reserved_flags,
1247            AFE_RESERVED_FLAGS_MASK,
1248            "adaptation_field_extension.reserved",
1249        )?;
1250        if self.ltw.is_some() {
1251            flags |= AFE_LTW_FLAG;
1252        }
1253        if self.piecewise_rate.is_some() {
1254            flags |= AFE_PIECEWISE_RATE_FLAG;
1255        }
1256        if self.seamless_splice.is_some() {
1257            flags |= AFE_SEAMLESS_SPLICE_FLAG;
1258        }
1259        if self.af_descriptor_not_present_flag {
1260            flags |= AFE_AF_DESCRIPTOR_NOT_PRESENT_FLAG;
1261        }
1262        buf[1] = flags;
1263        let mut cursor = AFE_PREFIX_LEN;
1264
1265        if let Some(ltw) = self.ltw {
1266            let ltw_valid = if ltw.ltw_valid_flag { AFE_LTW_FLAG } else { 0 };
1267            let offset = broadcast_core::len::fit_bits(
1268                u64::from(ltw.ltw_offset.get()),
1269                LTW_OFFSET_BITS,
1270                "ltw_offset",
1271            )?;
1272            buf[cursor] = ltw_valid | ((offset >> HIGH_BYTE_SHIFT) as u8 & LTW_OFFSET_HI_MASK);
1273            buf[cursor + 1] = offset as u8;
1274            cursor += LTW_FIELD_LEN;
1275        }
1276        if let Some(rate) = self.piecewise_rate {
1277            let rate = broadcast_core::len::fit_bits(
1278                u64::from(rate.get()),
1279                PIECEWISE_RATE_BITS,
1280                "piecewise_rate",
1281            )?;
1282            // reserved(2) | 22-bit rate (ISO/IEC 13818-1 Table 2-6).
1283            buf[cursor] = (broadcast_core::len::fit_mask(
1284                self.piecewise_rate_reserved,
1285                PIECEWISE_RATE_RESERVED_VALUE,
1286                "piecewise_rate.reserved",
1287            )? << PIECEWISE_RATE_RESERVED_SHIFT)
1288                | ((rate >> PIECEWISE_RATE_HI_SHIFT) as u8 & PIECEWISE_RATE_HI_MASK);
1289            buf[cursor + 1] = (rate >> HIGH_BYTE_SHIFT) as u8;
1290            buf[cursor + PIECEWISE_RATE_LO_OFFSET] = rate as u8;
1291            cursor += PIECEWISE_RATE_FIELD_LEN;
1292        }
1293        if let Some(ss) = self.seamless_splice {
1294            // byte 0: splice_type(4) | DTS[32:30](3) | marker(1) ... (5 bytes)
1295            buf[cursor..cursor + DTS_NEXT_AU_FIELD_LEN].copy_from_slice(&ss.to_marked_field()?);
1296            cursor += DTS_NEXT_AU_FIELD_LEN;
1297        }
1298        buf[cursor..cursor + self.trailing.len()].copy_from_slice(self.trailing);
1299        cursor += self.trailing.len();
1300        Ok(cursor)
1301    }
1302}
1303
1304/// Decoded adaptation field — full §2.4.3.4 layout including transport-private
1305/// data and the adaptation-field extension sub-structure.
1306///
1307/// The `transport_private_data` slice borrows from the original packet buffer
1308/// (it is genuinely opaque caller-defined bytes per the spec — `&[u8]` is the
1309/// correct public type). All other fields are fully typed.
1310///
1311/// ISO/IEC 13818-1:2007 §2.4.3.4.
1312#[non_exhaustive]
1313#[derive(Clone, Debug, PartialEq, Eq)]
1314#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1315pub struct AdaptationField<'a> {
1316    /// A timing/continuity discontinuity starts at this packet.
1317    pub discontinuity_indicator: bool,
1318    /// This packet is a random-access point.
1319    pub random_access_indicator: bool,
1320    /// Elementary-stream priority hint.
1321    pub elementary_stream_priority_indicator: bool,
1322    /// Program Clock Reference, present iff the PCR flag is set.
1323    pub pcr: Option<Pcr>,
1324    /// Original PCR, present iff the OPCR flag is set.
1325    pub opcr: Option<Pcr>,
1326    /// Splice countdown (packets until the splice point), iff the flag is set.
1327    pub splice_countdown: Option<i8>,
1328    /// Opaque transport-private data (caller-defined; `&[u8]` is spec-correct here).
1329    ///
1330    /// Present iff `transport_private_data_flag` is set in the flags byte
1331    /// (ISO/IEC 13818-1:2007 §2.4.3.4).
1332    pub transport_private_data: Option<&'a [u8]>,
1333    /// Typed adaptation-field extension sub-structure, if the flag is set.
1334    pub extension: Option<AdaptationFieldExtension<'a>>,
1335    /// The 6 `reserved` bits between `program_clock_reference_base` and
1336    /// `program_clock_reference_extension` of the PCR (Table 2-6; spec
1337    /// convention `0b111111`). Real streams (e.g. TSDuck's `test-002.ts`)
1338    /// carry `0`, so the value is kept for a byte-exact round trip. Only
1339    /// meaningful when `pcr` is `Some`.
1340    pub pcr_reserved: u8,
1341    /// The 6 `reserved` bits of the OPCR (same layout as `pcr_reserved`).
1342    pub opcr_reserved: u8,
1343    /// The stuffing bytes that pad the adaptation-field body out to its
1344    /// declared `adaptation_field_length` (ISO/IEC 13818-1 Table 2-6 —
1345    /// "stuffing_byte: fixed 8-bit value `0xFF`").
1346    ///
1347    /// Real encoders pad the adaptation field so the packet payload begins at a
1348    /// fixed offset; these bytes are part of the wire image. They are kept
1349    /// verbatim (not just counted) so a non-`0xFF` filler from a
1350    /// non-conforming encoder also round-trips byte-for-byte. Use `&[]` when
1351    /// constructing an adaptation field with no stuffing.
1352    pub stuffing: &'a [u8],
1353}
1354
1355impl Default for AdaptationField<'_> {
1356    fn default() -> Self {
1357        Self::new()
1358    }
1359}
1360
1361/// Overwrite the 6 reserved bits of an encoded PCR/OPCR field.
1362pub(crate) fn set_pcr_reserved(field: &mut [u8], reserved: u8) -> Result<()> {
1363    let reserved = broadcast_core::len::fit_bits(
1364        u64::from(reserved),
1365        PCR_RESERVED_BITS_COUNT,
1366        "pcr_reserved",
1367    )?;
1368    field[PCR_RESERVED_BYTE_OFFSET] = (field[PCR_RESERVED_BYTE_OFFSET] & !PCR_RESERVED_BITS)
1369        | (((reserved as u8) << PCR_RESERVED_SHIFT) & PCR_RESERVED_BITS);
1370    Ok(())
1371}
1372
1373impl<'a> AdaptationField<'a> {
1374    /// An adaptation field with every flag clear, no optional fields, no
1375    /// stuffing and spec-convention reserved bits (all `1`). Set fields on the
1376    /// result (the struct is `#[non_exhaustive]`).
1377    #[must_use]
1378    pub const fn new() -> Self {
1379        Self {
1380            discontinuity_indicator: false,
1381            random_access_indicator: false,
1382            elementary_stream_priority_indicator: false,
1383            pcr: None,
1384            opcr: None,
1385            splice_countdown: None,
1386            transport_private_data: None,
1387            extension: None,
1388            pcr_reserved: PCR_RESERVED_VALUE,
1389            opcr_reserved: PCR_RESERVED_VALUE,
1390            stuffing: &[],
1391        }
1392    }
1393
1394    /// Parse the adaptation-field bytes (those following the length byte).
1395    ///
1396    /// `af` must be exactly the adaptation-field body bytes: the slice starts
1397    /// at the **flags byte** (byte 0 of `af`), i.e. the bytes AFTER the
1398    /// `adaptation_field_length` byte itself. This matches how
1399    /// `TsPacket::parse` captures and hands them off.
1400    pub(crate) fn parse(af: &'a [u8]) -> Result<Self> {
1401        let flags = *af.first().ok_or(Error::BufferTooShort(
1402            broadcast_core::error::BufferTooShort::new(1, 0, "adaptation_field flags"),
1403        ))?;
1404        let mut cursor = 1usize;
1405
1406        let mut pcr_reserved = PCR_RESERVED_VALUE;
1407        let mut opcr_reserved = PCR_RESERVED_VALUE;
1408        let pcr = if flags & AF_PCR_FLAG != 0 {
1409            let p = Pcr::parse(af, cursor)?;
1410            pcr_reserved =
1411                (af[cursor + PCR_RESERVED_BYTE_OFFSET] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1412            cursor += PCR_FIELD_LEN;
1413            Some(p)
1414        } else {
1415            None
1416        };
1417        let opcr = if flags & AF_OPCR_FLAG != 0 {
1418            let p = Pcr::parse(af, cursor)?;
1419            opcr_reserved =
1420                (af[cursor + PCR_RESERVED_BYTE_OFFSET] & PCR_RESERVED_BITS) >> PCR_RESERVED_SHIFT;
1421            cursor += PCR_FIELD_LEN;
1422            Some(p)
1423        } else {
1424            None
1425        };
1426        let splice_countdown = if flags & AF_SPLICING_FLAG != 0 {
1427            let b = *af.get(cursor).ok_or(Error::BufferTooShort(
1428                broadcast_core::error::BufferTooShort::new(
1429                    cursor + 1,
1430                    af.len(),
1431                    "adaptation_field splice_countdown",
1432                ),
1433            ))?;
1434            cursor += 1;
1435            Some(b as i8)
1436        } else {
1437            None
1438        };
1439
1440        // transport_private_data (ISO/IEC 13818-1 §2.4.3.4):
1441        // transport_private_data_length(8) + transport_private_data_byte * N
1442        let transport_private_data = if flags & AF_TRANSPORT_PRIVATE_DATA_FLAG != 0 {
1443            let tpd_len = *af.get(cursor).ok_or(Error::BufferTooShort(
1444                broadcast_core::error::BufferTooShort::new(
1445                    cursor + 1,
1446                    af.len(),
1447                    "transport_private_data_length",
1448                ),
1449            ))? as usize;
1450            cursor += 1;
1451            let end = cursor + tpd_len;
1452            let slice = af.get(cursor..end).ok_or(Error::BufferTooShort(
1453                broadcast_core::error::BufferTooShort::new(end, af.len(), "transport_private_data"),
1454            ))?;
1455            cursor = end;
1456            Some(slice)
1457        } else {
1458            None
1459        };
1460
1461        // adaptation_field_extension (ISO/IEC 13818-1 §2.4.3.5):
1462        let extension = if flags & AF_EXTENSION_FLAG != 0 {
1463            let ext_data = af.get(cursor..).ok_or(Error::BufferTooShort(
1464                broadcast_core::error::BufferTooShort::new(
1465                    cursor + 1,
1466                    af.len(),
1467                    "adaptation_field_extension",
1468                ),
1469            ))?;
1470            let ext = AdaptationFieldExtension::parse(ext_data)?;
1471            // advance cursor past the extension (ext_data[0] = length byte)
1472            if !ext_data.is_empty() {
1473                let _ext_len = ext_data[0] as usize;
1474                cursor += 1 + _ext_len;
1475            }
1476            Some(ext)
1477        } else {
1478            None
1479        };
1480
1481        // Any bytes after the last present field, up to `adaptation_field_length`
1482        // (= `af.len()`), are `0xFF` stuffing (ISO/IEC 13818-1:2007 §2.4.3.4).
1483        // Record the count so serialization reproduces the body byte-for-byte.
1484        let stuffing = af.get(cursor..).unwrap_or(&[]);
1485
1486        Ok(AdaptationField {
1487            discontinuity_indicator: flags & AF_DISCONTINUITY != 0,
1488            random_access_indicator: flags & AF_RANDOM_ACCESS != 0,
1489            elementary_stream_priority_indicator: flags & AF_ES_PRIORITY != 0,
1490            pcr,
1491            opcr,
1492            splice_countdown,
1493            transport_private_data,
1494            extension,
1495            pcr_reserved,
1496            opcr_reserved,
1497            stuffing,
1498        })
1499    }
1500
1501    /// Number of bytes written by [`serialize_into`](Self::serialize_into).
1502    ///
1503    /// This is the body length **excluding** the leading `adaptation_field_length`
1504    /// byte — it is the value carried in that length byte itself
1505    /// (ISO/IEC 13818-1:2007 §2.4.3.4).
1506    #[must_use]
1507    pub fn serialized_len(&self) -> usize {
1508        let mut n = 1usize; // flags byte
1509        if self.pcr.is_some() {
1510            n += PCR_FIELD_LEN;
1511        }
1512        if self.opcr.is_some() {
1513            n += PCR_FIELD_LEN;
1514        }
1515        if self.splice_countdown.is_some() {
1516            n += 1;
1517        }
1518        if let Some(tpd) = self.transport_private_data {
1519            n += 1 + tpd.len(); // length byte + data
1520        }
1521        if let Some(ref ext) = self.extension {
1522            n += ext.serialized_len();
1523        }
1524        n += self.stuffing.len();
1525        n
1526    }
1527
1528    /// Serialize the adaptation field into `buf`.
1529    ///
1530    /// Writes the **body** bytes — the flags byte plus optional fields in the
1531    /// order specified by ISO/IEC 13818-1:2007 §2.4.3.4. The
1532    /// `adaptation_field_length` byte itself is **not** written here; the caller
1533    /// must prepend it (it equals `serialized_len()`).
1534    ///
1535    /// Returns the number of bytes written on success, or
1536    /// [`Error::OutputBufferTooSmall`] if `buf` is shorter than
1537    /// `serialized_len()`.
1538    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
1539        let need = self.serialized_len();
1540        need_out(buf, need, "AdaptationField")?;
1541
1542        // Byte 0: flags (ISO/IEC 13818-1:2007 §2.4.3.4).
1543        let mut flags = 0u8;
1544        if self.discontinuity_indicator {
1545            flags |= AF_DISCONTINUITY;
1546        }
1547        if self.random_access_indicator {
1548            flags |= AF_RANDOM_ACCESS;
1549        }
1550        if self.elementary_stream_priority_indicator {
1551            flags |= AF_ES_PRIORITY;
1552        }
1553        if self.pcr.is_some() {
1554            flags |= AF_PCR_FLAG;
1555        }
1556        if self.opcr.is_some() {
1557            flags |= AF_OPCR_FLAG;
1558        }
1559        if self.splice_countdown.is_some() {
1560            flags |= AF_SPLICING_FLAG;
1561        }
1562        if self.transport_private_data.is_some() {
1563            flags |= AF_TRANSPORT_PRIVATE_DATA_FLAG;
1564        }
1565        if self.extension.is_some() {
1566            flags |= AF_EXTENSION_FLAG;
1567        }
1568        buf[0] = flags;
1569
1570        let mut cursor = 1usize;
1571        if let Some(pcr) = self.pcr {
1572            buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&pcr.to_field_bytes());
1573            set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.pcr_reserved)?;
1574            cursor += PCR_FIELD_LEN;
1575        }
1576        if let Some(opcr) = self.opcr {
1577            buf[cursor..cursor + PCR_FIELD_LEN].copy_from_slice(&opcr.to_field_bytes());
1578            set_pcr_reserved(&mut buf[cursor..cursor + PCR_FIELD_LEN], self.opcr_reserved)?;
1579            cursor += PCR_FIELD_LEN;
1580        }
1581        if let Some(sc) = self.splice_countdown {
1582            buf[cursor] = sc as u8;
1583            cursor += 1;
1584        }
1585        if let Some(tpd) = self.transport_private_data {
1586            buf[cursor] = broadcast_core::len::fit_u8(
1587                tpd.len(),
1588                "adaptation_field.transport_private_data_length",
1589            )?;
1590            cursor += 1;
1591            buf[cursor..cursor + tpd.len()].copy_from_slice(tpd);
1592            cursor += tpd.len();
1593        }
1594        if let Some(ref ext) = self.extension {
1595            let written = ext.serialize_into(&mut buf[cursor..])?;
1596            cursor += written;
1597        }
1598
1599        // Trailing `0xFF` stuffing (ISO/IEC 13818-1:2007 §2.4.3.4), reproducing
1600        // the padding the encoder used to fill `adaptation_field_length`.
1601        buf[cursor..cursor + self.stuffing.len()].copy_from_slice(self.stuffing);
1602        cursor += self.stuffing.len();
1603
1604        Ok(cursor)
1605    }
1606}
1607
1608/// How a PSI/SI section is delimited: `table_id`, then flags and a 12-bit
1609/// `section_length` (ISO/IEC 13818-1 §2.4.4); `0xFF` where a `table_id` is
1610/// expected is stuffing.
1611struct SectionFraming;
1612
1613impl crate::unit::Framing for SectionFraming {
1614    fn length(&self, buf: &[u8]) -> crate::unit::UnitLength {
1615        match section_total_len(buf) {
1616            None => crate::unit::UnitLength::NeedMore,
1617            Some(_) if buf[0] == STUFFING_BYTE => crate::unit::UnitLength::Stuffing,
1618            Some(total) => crate::unit::UnitLength::Total(total),
1619        }
1620    }
1621}
1622
1623/// Reassembles PSI/SI sections from TS packets on a single PID.
1624///
1625/// Feed each TS packet's payload with `feed`. Complete sections are
1626/// appended to an internal queue; drain them with `pop_section`. A
1627/// [`crate::unit::UnitReassembler`] with the PSI framing and options.
1628pub struct SectionReassembler {
1629    inner: alloc::boxed::Box<crate::unit::UnitReassembler<SectionFraming>>,
1630}
1631
1632impl Default for SectionReassembler {
1633    fn default() -> Self {
1634        Self {
1635            inner: alloc::boxed::Box::new(crate::unit::UnitReassembler::new(
1636                SectionFraming,
1637                crate::unit::UnitOptions::new(
1638                    crate::unit::AfterContinuation::DiscardRest,
1639                    crate::unit::PointerCheck::Authoritative,
1640                    crate::unit::Duplicates::ContinuationOnly,
1641                    core::num::NonZeroUsize::MIN.saturating_add(MAX_SECTION_SIZE - 1),
1642                ),
1643            )),
1644        }
1645    }
1646}
1647
1648impl SectionReassembler {
1649    /// Feed a TS payload and whether its packet had PUSI set.
1650    ///
1651    /// Extracts complete SI sections into the internal queue. A single call
1652    /// can produce zero, one, or **several** sections — a payload may
1653    /// concatenate multiple complete sections after the `pointer_field`
1654    /// (EN 300 468 §5.1.4; common on EMM PIDs). Drain with a
1655    /// `while let Some(s) = r.pop_section()` loop, not a single `if let`.
1656    pub fn feed(&mut self, payload: &[u8], pusi: bool) {
1657        let _ = self.inner.feed(payload, pusi, None);
1658    }
1659
1660    /// Like [`feed`](Self::feed), additionally taking the packet's
1661    /// `continuity_counter` so a legally retransmitted packet is discarded
1662    /// rather than appended twice.
1663    ///
1664    /// ISO/IEC 13818-1 §2.4.3.3 (`continuity_counter` semantics, see
1665    /// `private/specs-verified/mpeg/mpeg-ts/tables/h222_0/transport_packet.md`)
1666    /// permits a packet to be repeated once with the same counter; a
1667    /// continuation packet whose counter and payload repeat the previous one
1668    /// is dropped. Call this
1669    /// for payload-bearing packets only: the counter does not advance on
1670    /// packets without payload. `discontinuity` is the packet's
1671    /// adaptation-field `discontinuity_indicator` (ISO/IEC 13818-1 §2.4.3.5):
1672    /// when it is set an unchanged continuity counter is legal and the packet
1673    /// is not a duplicate.
1674    pub fn feed_with_continuity(
1675        &mut self,
1676        payload: &[u8],
1677        pusi: bool,
1678        continuity_counter: ContinuityCounter,
1679        discontinuity: bool,
1680    ) {
1681        let _ = self.inner.feed(
1682            payload,
1683            pusi,
1684            Some(crate::unit::Continuity::new(
1685                continuity_counter,
1686                discontinuity,
1687            )),
1688        );
1689    }
1690
1691    /// Pop one complete section. Returns `None` when the queue is empty.
1692    pub fn pop_section(&mut self) -> Option<bytes::Bytes> {
1693        self.inner.pop()
1694    }
1695
1696    /// Number of bytes currently buffered (incomplete section).
1697    pub fn len(&self) -> usize {
1698        self.inner.len()
1699    }
1700
1701    /// True if no bytes are currently buffered.
1702    pub fn is_empty(&self) -> bool {
1703        self.inner.is_empty()
1704    }
1705}
1706
1707/// Iterate over all valid TS packets in a byte buffer.
1708///
1709/// Slices `buf` into 188-byte chunks (using [`slice::chunks_exact`]) and yields
1710/// each chunk for which [`TsPacket::parse`] succeeds. Chunks with a bad sync byte
1711/// (`!= 0x47`) or insufficient length are silently skipped — use
1712/// [`crate::resync::TsResync`] for byte-stream resynchronisation before calling
1713/// this when byte alignment is not guaranteed.
1714///
1715/// # Example
1716///
1717/// ```no_run
1718/// # use mpeg_ts::ts::iter_packets;
1719/// # let data: &[u8] = &[];
1720/// for pkt in iter_packets(data) {
1721///     println!("PID: 0x{:04X}", pkt.header.pid);
1722/// }
1723/// ```
1724pub fn iter_packets(buf: &[u8]) -> impl Iterator<Item = TsPacket<'_>> {
1725    buf.chunks_exact(TS_PACKET_SIZE)
1726        .filter_map(|chunk| TsPacket::parse(chunk).ok())
1727}
1728
1729/// Extract the payload bytes from a raw 188-byte TS packet slice.
1730///
1731/// Returns `None` when:
1732/// - `pkt` is fewer than 4 bytes,
1733/// - `adaptation_field_control` is `00` (reserved) or `10` (adaptation only), or
1734/// - the adaptation field length would place the payload start past the packet end.
1735///
1736/// No sync-byte check is performed — the caller is responsible for ensuring the
1737/// slice is properly aligned. Spec: ITU-T H.222.0 (08/2023) §2.4.3.3 Table 2-5.
1738pub fn extract_ts_payload(pkt: &[u8]) -> Option<&[u8]> {
1739    if pkt.len() < TsHeader::serialized_len() {
1740        return None;
1741    }
1742    let header = TsHeader::parse(&pkt[..TsHeader::serialized_len()]).ok()?;
1743    if !header.has_payload() {
1744        return None;
1745    }
1746    let cursor = TsHeader::serialized_len() + adaptation_field_skip(pkt, header.has_adaptation());
1747    if cursor < pkt.len() {
1748        Some(&pkt[cursor..])
1749    } else {
1750        None
1751    }
1752}
1753
1754#[cfg(test)]
1755mod tests {
1756    use super::*;
1757
1758    #[test]
1759    fn payload_range_never_panics_for_any_adaptation_field_length() {
1760        for control in 0u8..=3 {
1761            for length in 0u8..=u8::MAX {
1762                let mut raw = [0xFFu8; TS_PACKET_SIZE];
1763                raw[0] = TS_SYNC_BYTE;
1764                raw[1] = 0;
1765                raw[2] = 0;
1766                raw[3] = control << 4;
1767                raw[4] = length;
1768                if let Some(range) = payload_range(&raw) {
1769                    assert!(range.start < range.end && range.end <= TS_PACKET_SIZE);
1770                }
1771            }
1772        }
1773    }
1774
1775    #[test]
1776    fn payload_range_follows_adaptation_field_control() {
1777        let mut raw = [0u8; TS_PACKET_SIZE];
1778        raw[0] = TS_SYNC_BYTE;
1779        raw[3] = 0x10;
1780        assert_eq!(payload_range(&raw), Some(4..TS_PACKET_SIZE));
1781        raw[3] = 0x20;
1782        assert_eq!(payload_range(&raw), None);
1783        raw[3] = 0x30;
1784        raw[4] = 7;
1785        assert_eq!(payload_range(&raw), Some(12..TS_PACKET_SIZE));
1786        raw[4] = 183;
1787        assert_eq!(payload_range(&raw), None);
1788        raw[4] = 0;
1789        assert_eq!(payload_range(&raw), Some(5..TS_PACKET_SIZE));
1790        raw[3] = 0x00;
1791        assert_eq!(payload_range(&raw), None);
1792    }
1793
1794    #[test]
1795    fn payload_range_agrees_with_the_parsed_payload() {
1796        let mut raw = [0x55u8; TS_PACKET_SIZE];
1797        raw[0] = TS_SYNC_BYTE;
1798        for control in [0x10u8, 0x20, 0x30] {
1799            for af_len in [0u8, 1, 50, 182, 183, 184, 255] {
1800                raw[3] = control;
1801                raw[4] = af_len;
1802                let parsed = TsPacket::parse(&raw).expect("sync byte present");
1803                let expected = parsed
1804                    .payload
1805                    .map(|p| TS_PACKET_SIZE - p.len()..TS_PACKET_SIZE);
1806                assert_eq!(payload_range(&raw), expected, "{control:#x}/{af_len}");
1807            }
1808        }
1809    }
1810
1811    fn cc(v: u8) -> ContinuityCounter {
1812        ContinuityCounter::try_new(v).expect("4-bit counter")
1813    }
1814    use alloc::string::ToString;
1815    use alloc::vec;
1816    use alloc::vec::Vec;
1817
1818    /// Helper: construct a minimal 188-byte TS packet buffer with given header flags and payload.
1819    fn make_packet(b1: u8, b2: u8, b3: u8, payload_data: &[u8]) -> [u8; TS_PACKET_SIZE] {
1820        let mut pkt = [0u8; TS_PACKET_SIZE];
1821        pkt[0] = TS_SYNC_BYTE;
1822        pkt[1] = b1;
1823        pkt[2] = b2;
1824        pkt[3] = b3;
1825        let payload_start = 4;
1826        let end = (payload_start + payload_data.len()).min(TS_PACKET_SIZE);
1827        let len = (end - payload_start).min(payload_data.len());
1828        pkt[payload_start..payload_start + len].copy_from_slice(&payload_data[..len]);
1829        pkt
1830    }
1831
1832    #[test]
1833    fn parse_rejects_non_0x47_sync_byte() {
1834        let mut pkt = [0u8; TS_PACKET_SIZE];
1835        pkt[0] = 0x46; // wrong sync byte
1836        let err = TsPacket::parse(&pkt).unwrap_err();
1837        match err {
1838            Error::InvalidSync(e) => assert_eq!(e.found, 0x46),
1839            other => panic!("expected InvalidSyncByte, got {other:?}"),
1840        }
1841    }
1842
1843    #[test]
1844    fn ts_header_round_trip() {
1845        // struct → serialize → parse must reproduce the header (the project's
1846        // symmetric Parse/Serialize invariant) across flag/field combinations.
1847        let cases = [
1848            TsHeader {
1849                tei: false,
1850                pusi: true,
1851                pid: Pid::from_const(0x0000),
1852                scrambling: ScramblingControl::NotScrambled,
1853                adaptation_field_control: AdaptationFieldControl::PayloadOnly,
1854                continuity_counter: ContinuityCounter::ZERO,
1855            },
1856            TsHeader {
1857                tei: true,
1858                pusi: false,
1859                pid: Pid::from_const(0x1FFF),
1860                scrambling: ScramblingControl::OddKey,
1861                adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
1862                continuity_counter: ContinuityCounter::try_new(0x0F).expect("4-bit counter"),
1863            },
1864            TsHeader {
1865                tei: false,
1866                pusi: false,
1867                pid: Pid::from_const(0x0100),
1868                scrambling: ScramblingControl::EvenKey,
1869                adaptation_field_control: AdaptationFieldControl::AdaptationOnly,
1870                continuity_counter: ContinuityCounter::try_new(7).expect("4-bit counter"),
1871            },
1872        ];
1873        for h in cases {
1874            let mut buf = [0u8; 4];
1875            assert_eq!(h.serialize_into(&mut buf).unwrap(), 4);
1876            assert_eq!(TsHeader::parse(&buf).unwrap(), h, "round-trip mismatch");
1877        }
1878    }
1879
1880    #[test]
1881    fn parse_extracts_pid_and_continuity_counter() {
1882        // PID = 0x1234 → upper 5 bits = 0x12, lower 8 bits = 0x34
1883        // CC = 5 → 0x05
1884        // b1 bits: [tei:1][pusi:1][pid_hi:5]
1885        // pid_hi = 0x12 = 0b00100_10 → bits 5..=1 = 0x12
1886        // b1 = 0b00_010010 = 0x12 (no tei, no pusi)
1887        let pkt = make_packet(0x12, 0x34, 0x05, &[]);
1888        let pkt = TsPacket::parse(&pkt).unwrap();
1889        assert_eq!(pkt.header.pid, Pid::from_const(0x1234));
1890        assert_eq!(pkt.header.continuity_counter.value(), 5);
1891    }
1892
1893    #[test]
1894    fn payload_unit_start_indicator_flag_extracted() {
1895        // b1 = 0x40 → pusi = true (bit 6 set, no tei, no pid bits)
1896        let pkt1 = make_packet(0x40, 0x00, 0x00, &[]);
1897        let pkt1 = TsPacket::parse(&pkt1).unwrap();
1898        assert!(pkt1.header.pusi);
1899
1900        // b1 = 0x00 → pusi = false
1901        let pkt2 = make_packet(0x00, 0x00, 0x00, &[]);
1902        let pkt2 = TsPacket::parse(&pkt2).unwrap();
1903        assert!(!pkt2.header.pusi);
1904    }
1905
1906    /// Build a PSI-carrying TS payload: `pointer_field` byte followed by
1907    /// (optionally) some tail of a previous section, followed by a fresh
1908    /// section. `pointer_field` is the number of bytes of the previous
1909    /// section that precede the new one (per ETSI EN 300 468 §5.1.4).
1910    fn build_pusi_payload(pointer_field: u8, previous_tail: &[u8], section: &[u8]) -> Vec<u8> {
1911        assert_eq!(pointer_field as usize, previous_tail.len());
1912        let mut v = Vec::with_capacity(1 + previous_tail.len() + section.len());
1913        v.push(pointer_field);
1914        v.extend_from_slice(previous_tail);
1915        v.extend_from_slice(section);
1916        v
1917    }
1918
1919    // The reassembler tests below feed raw payload slices directly to
1920    // `feed()` rather than wrapping them in 188-byte TS packets. This avoids
1921    // the TS stuffing-byte tail (0xFF padding) bleeding into the reassembled
1922    // section and keeps the assertions exact.
1923
1924    #[test]
1925    fn reassembler_accumulates_multi_packet_section() {
1926        // 200-byte section that spans two payload slices.
1927        let body = vec![0xAAu8; 197];
1928        let section = test_fixtures::psi::short_section(0x02, &body);
1929        assert_eq!(section.len(), 200);
1930
1931        let first_chunk = 100;
1932        let payload1 = build_pusi_payload(0, &[], &section[..first_chunk]);
1933        let payload2 = section[first_chunk..].to_vec();
1934
1935        let mut reasm = SectionReassembler::default();
1936        reasm.feed(&payload1, true);
1937        reasm.feed(&payload2, false);
1938
1939        let out = reasm.pop_section().expect("section should be ready");
1940        assert_eq!(out.len(), 200);
1941        assert_eq!(out.as_ref(), &section[..]);
1942    }
1943
1944    #[test]
1945    fn reassembler_yields_complete_section_once_length_satisfied() {
1946        // 1-byte-body section: table_id=0x42, section_length=1, total=4 bytes.
1947        let section = test_fixtures::psi::short_section(0x42, &[0xAA]);
1948        assert_eq!(section.len(), 4);
1949        let payload = build_pusi_payload(0, &[], &section);
1950
1951        let mut reasm = SectionReassembler::default();
1952        reasm.feed(&payload, true);
1953
1954        let out = reasm
1955            .pop_section()
1956            .expect("single-packet section should pop");
1957        assert_eq!(out.as_ref(), &section[..]);
1958    }
1959
1960    /// A 12-bit `section_length` declaring the maximum may not make the
1961    /// reassembler hold or reserve more than the bytes actually fed: the
1962    /// buffer grows one fed payload at a time, capped by `MAX_SECTION_SIZE`.
1963    #[test]
1964    fn a_maximum_section_length_holds_only_the_bytes_supplied() {
1965        // table_id, section_syntax_indicator=1, section_length=0xFFF.
1966        let head = [0x00u8, 0xB0, 0xFF, 0x00, 0x00];
1967        let payload = build_pusi_payload(0, &[], &head);
1968        let mut reasm = SectionReassembler::default();
1969        reasm.feed(&payload, true);
1970        assert_eq!(reasm.len(), head.len(), "only the bytes fed");
1971        assert!(reasm.pop_section().is_none(), "the section is incomplete");
1972
1973        let continuation = [0xAAu8; 16];
1974        reasm.feed(&continuation, false);
1975        assert_eq!(reasm.len(), head.len() + continuation.len());
1976        assert!(reasm.len() <= MAX_SECTION_SIZE);
1977    }
1978
1979    #[test]
1980    fn reassembler_extracts_all_concatenated_sections_in_one_payload() {
1981        // Issue #29: a single PUSI payload packing three complete short
1982        // sections after the pointer_field. All three must be queued — the
1983        // old `feed` stopped after the first and the rest were silently lost
1984        // (the CAS/EMM data-loss bug: SHARED EMMs landing as the 2nd+ section).
1985        let s1 = test_fixtures::psi::short_section(0x42, &[0x11, 0x22]); // 5 bytes
1986        let s2 = test_fixtures::psi::short_section(0x46, &[0x33]); // 4 bytes
1987        let s3 = test_fixtures::psi::short_section(0x4A, &[0x44, 0x55, 0x66]); // 6 bytes
1988
1989        let mut concat = Vec::new();
1990        concat.extend_from_slice(&s1);
1991        concat.extend_from_slice(&s2);
1992        concat.extend_from_slice(&s3);
1993        let payload = build_pusi_payload(0, &[], &concat);
1994
1995        let mut reasm = SectionReassembler::default();
1996        reasm.feed(&payload, true);
1997
1998        // Consumers must drain with a loop, not a single `if let`.
1999        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2000        assert_eq!(got.len(), 3, "all three concatenated sections must pop");
2001        assert_eq!(got[0].as_ref(), &s1[..]);
2002        assert_eq!(got[1].as_ref(), &s2[..]);
2003        assert_eq!(got[2].as_ref(), &s3[..]);
2004    }
2005
2006    #[test]
2007    fn reassembler_stops_at_stuffing_after_concatenated_sections() {
2008        // Two sections then 0xFF stuffing fill — the stuffing must not be
2009        // mistaken for a section header (0xFF table_id) nor leak into a
2010        // section; both real sections still pop.
2011        let s1 = test_fixtures::psi::short_section(0x42, &[0xAA]); // 4 bytes
2012        let s2 = test_fixtures::psi::short_section(0x46, &[0xBB, 0xCC]); // 5 bytes
2013        let mut concat = Vec::new();
2014        concat.extend_from_slice(&s1);
2015        concat.extend_from_slice(&s2);
2016        concat.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]); // stuffing tail
2017        let payload = build_pusi_payload(0, &[], &concat);
2018
2019        let mut reasm = SectionReassembler::default();
2020        reasm.feed(&payload, true);
2021
2022        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2023        assert_eq!(got.len(), 2);
2024        assert_eq!(got[0].as_ref(), &s1[..]);
2025        assert_eq!(got[1].as_ref(), &s2[..]);
2026        assert!(
2027            reasm.is_empty(),
2028            "stuffing tail must be discarded, not buffered"
2029        );
2030    }
2031
2032    #[test]
2033    fn reassembler_concatenated_then_spanning_tail() {
2034        // One complete section followed by the head of a second that spans
2035        // into a continuation packet: first pops immediately, second pops
2036        // once the continuation arrives.
2037        let s1 = test_fixtures::psi::short_section(0x42, &[0x01, 0x02]); // 5 bytes
2038        let s2 = test_fixtures::psi::short_section(0x46, &[0x09u8; 60]); // 63 bytes
2039        let split = 30;
2040
2041        let mut head = Vec::new();
2042        head.extend_from_slice(&s1);
2043        head.extend_from_slice(&s2[..split]);
2044        let payload1 = build_pusi_payload(0, &[], &head);
2045        let payload2 = s2[split..].to_vec();
2046
2047        let mut reasm = SectionReassembler::default();
2048        reasm.feed(&payload1, true);
2049        let first = reasm.pop_section().expect("first section pops at once");
2050        assert_eq!(first.as_ref(), &s1[..]);
2051        assert!(reasm.pop_section().is_none(), "second is still partial");
2052
2053        reasm.feed(&payload2, false);
2054        let second = reasm.pop_section().expect("second pops after continuation");
2055        assert_eq!(second.as_ref(), &s2[..]);
2056    }
2057
2058    #[test]
2059    fn reassembler_completes_section_spanning_into_pusi_packet() {
2060        // Issue #29 (second case): a section starts late in packet A and spills
2061        // into packet B, but B is itself PUSI=1 because new sections begin in it.
2062        // B's pointer_field = the count of leading tail bytes belonging to the
2063        // section from A. Those bytes MUST complete A's section before new
2064        // sections start. 3.1.1 cleared buf + skipped them → the spanning
2065        // section was lost (the SHARED EMM the smartcard needed).
2066        let spanning = test_fixtures::psi::short_section(0x42, &[0x5Au8; 62]); // 65 bytes
2067        let head = 41;
2068        let tail = &spanning[head..]; // 24 bytes — lands in packet B
2069        assert_eq!(tail.len(), 24);
2070
2071        // New section that begins in packet B after the spanning tail.
2072        let next = test_fixtures::psi::short_section(0x46, &[0x77, 0x88]); // 5 bytes
2073
2074        // Packet A (PUSI): pointer 0, then the 41-byte head (incomplete).
2075        let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2076        // Packet B (PUSI): pointer = 24 (tail of A's section), then `next`.
2077        let payload_b = build_pusi_payload(24, tail, &next);
2078
2079        let mut reasm = SectionReassembler::default();
2080        reasm.feed(&payload_a, true);
2081        assert!(reasm.pop_section().is_none(), "head alone is incomplete");
2082
2083        reasm.feed(&payload_b, true);
2084        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
2085        assert_eq!(got.len(), 2, "spanning section + new section must both pop");
2086        assert_eq!(
2087            got[0].as_ref(),
2088            &spanning[..],
2089            "spanning section completed from B's pointer tail"
2090        );
2091        assert_eq!(got[1].as_ref(), &next[..]);
2092    }
2093
2094    #[test]
2095    fn reassembler_pusi_pointer_spans_whole_payload() {
2096        // A section spans into a PUSI packet whose pointer covers the ENTIRE
2097        // remaining payload (no new section starts here) — the tail must be
2098        // appended and the section completed once the count is satisfied.
2099        let spanning = test_fixtures::psi::short_section(0x42, &[0x33u8; 40]); // 43 bytes
2100        let head = 20;
2101        let payload_a = build_pusi_payload(0, &[], &spanning[..head]);
2102        let tail = &spanning[head..]; // 23 bytes — exactly the rest of payload B
2103
2104        let mut reasm = SectionReassembler::default();
2105        reasm.feed(&payload_a, true);
2106        // Packet B: pointer = 23 = all remaining bytes; no new section follows.
2107        reasm.feed(&build_pusi_payload_pointer_spanning_all(tail), true);
2108
2109        let out = reasm.pop_section().expect("spanning section completes");
2110        assert_eq!(out.as_ref(), &spanning[..]);
2111        assert!(reasm.pop_section().is_none());
2112    }
2113
2114    /// Build a PUSI payload whose `pointer_field` equals the whole tail (so the
2115    /// pointer spans to the end of the payload and no new section starts).
2116    fn build_pusi_payload_pointer_spanning_all(tail: &[u8]) -> Vec<u8> {
2117        let mut v = Vec::with_capacity(1 + tail.len());
2118        v.push(tail.len() as u8);
2119        v.extend_from_slice(tail);
2120        v
2121    }
2122
2123    #[test]
2124    fn reassembler_discards_a_retransmitted_continuation_packet() {
2125        let mut section = vec![0x4Eu8, 0xB0, 0x00];
2126        section.resize(300, 0x5A);
2127        section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2128        section[2] = ((300 - 3) & 0xFF) as u8;
2129        let mut first = vec![0x00u8];
2130        first.extend_from_slice(&section[..183]);
2131
2132        let mut reasm = SectionReassembler::default();
2133        reasm.feed_with_continuity(&first, true, cc(0), false);
2134        reasm.feed_with_continuity(&section[183..250], false, cc(1), false);
2135        reasm.feed_with_continuity(&section[183..250], false, cc(1), false);
2136        reasm.feed_with_continuity(&section[250..], false, cc(2), false);
2137
2138        let out = reasm.pop_section().expect("section survives the duplicate");
2139        assert_eq!(out.as_ref(), &section[..]);
2140        assert!(reasm.pop_section().is_none());
2141    }
2142
2143    #[test]
2144    fn a_packet_after_a_discontinuity_with_an_unchanged_counter_is_not_a_duplicate() {
2145        let mut section = vec![0x4Eu8, 0xB0, 0x00];
2146        section.resize(300, 0x5A);
2147        section[1] = 0xB0 | (((300 - 3) >> 8) as u8);
2148        section[2] = ((300 - 3) & 0xFF) as u8;
2149        let mut first = vec![0x00u8];
2150        first.extend_from_slice(&section[..183]);
2151
2152        let mut reasm = SectionReassembler::default();
2153        reasm.feed_with_continuity(&first, true, cc(0), false);
2154        reasm.feed_with_continuity(&section[183..250], false, cc(0), true);
2155        reasm.feed_with_continuity(&section[250..], false, cc(1), false);
2156
2157        let out = reasm
2158            .pop_section()
2159            .expect("section survives the discontinuity");
2160        assert_eq!(out.as_ref(), &section[..]);
2161        assert!(reasm.pop_section().is_none());
2162    }
2163
2164    #[test]
2165    fn reassembler_completes_max_length_section_and_stays_usable() {
2166        // A section declaring the maximum `section_length` (0xFFF → 4098 bytes
2167        // total). The 12-bit length structurally caps the buffer at
2168        // MAX_SECTION_SIZE, so there is no unbounded growth — and (unlike the
2169        // pre-#148 guard, which discarded once buf+payload crossed the cap) a
2170        // valid max-length section completes at its declared length.
2171        let mut section = Vec::with_capacity(MAX_SECTION_SIZE);
2172        section.push(0x00); // table_id
2173        section.push(0xB0 | ((4095u16 >> 8) as u8 & 0x0F));
2174        section.push(0xFF); // section_length = 0xFFF
2175        section.resize(MAX_SECTION_SIZE, 0u8);
2176        assert_eq!(section.len(), MAX_SECTION_SIZE);
2177
2178        let mut reasm = SectionReassembler::default();
2179        let mut first = vec![0x00u8]; // pointer_field 0
2180        first.extend_from_slice(&section[..183]);
2181        reasm.feed(&first, true);
2182        assert!(
2183            reasm.pop_section().is_none(),
2184            "incomplete until the declared length arrives"
2185        );
2186
2187        for chunk in section[183..].chunks(184) {
2188            reasm.feed(chunk, false);
2189        }
2190        let out = reasm
2191            .pop_section()
2192            .expect("max-length section completes at its declared length");
2193        assert_eq!(out.len(), MAX_SECTION_SIZE);
2194        assert_eq!(out.as_ref(), &section[..]);
2195        assert!(reasm.is_empty());
2196
2197        // Extra trailing continuation data after completion is ignored (the
2198        // buffer is empty, so a non-PUSI payload is dropped) — no panic, no
2199        // spurious section.
2200        reasm.feed(&[0u8; 184], false);
2201        assert!(reasm.pop_section().is_none());
2202
2203        // State must be resettable — a fresh valid PUSI section works.
2204        let valid_section = test_fixtures::psi::short_section(0x00, &[0xAA]);
2205        let payload2 = build_pusi_payload(0, &[], &valid_section);
2206        reasm.feed(&payload2, true);
2207        let out = reasm
2208            .pop_section()
2209            .expect("fresh section should pop after reset");
2210        assert_eq!(out.as_ref(), &valid_section[..]);
2211    }
2212
2213    #[test]
2214    fn reassembler_handles_pusi_with_nonzero_pointer_field() {
2215        // payload = pointer_field=3, 3 bytes of prior-section tail, then new section.
2216        let prior_tail = vec![0x11, 0x22, 0x33];
2217        let new_section = test_fixtures::psi::short_section(0x02, &[0xBB]);
2218        assert_eq!(new_section.len(), 4);
2219        let payload = build_pusi_payload(3, &prior_tail, &new_section);
2220
2221        let mut reasm = SectionReassembler::default();
2222        reasm.feed(&payload, true);
2223
2224        let out = reasm
2225            .pop_section()
2226            .expect("section after pointer_field skip should pop");
2227        assert_eq!(out.as_ref(), &new_section[..]);
2228    }
2229
2230    #[test]
2231    fn reassembler_ignores_continuation_before_pusi() {
2232        // Feed a non-PUSI payload first (no prior PUSI seen).
2233        // SectionReassembler should discard it and stay empty.
2234        let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA, 0xBB, 0xCC]);
2235
2236        let mut reasm = SectionReassembler::default();
2237        reasm.feed(&pkt[4..], false); // no PUSI
2238
2239        assert!(
2240            reasm.pop_section().is_none(),
2241            "no section should appear without prior PUSI"
2242        );
2243        assert!(
2244            reasm.pop_section().is_none(),
2245            "second pop should also be none"
2246        );
2247    }
2248
2249    /// A PUSI packet with an empty payload (adaptation field ate the body)
2250    /// is malformed but must not panic — it drops sync.
2251    #[test]
2252    fn reassembler_empty_pusi_payload_does_not_panic() {
2253        let mut reasm = SectionReassembler::default();
2254        reasm.feed(&[], true);
2255        assert!(reasm.pop_section().is_none());
2256        // Recovers on the next clean PUSI.
2257        let payload = vec![0x00u8, 0x72, 0x70, 0x01, 0x00];
2258        reasm.feed(&payload, true);
2259        assert!(reasm.pop_section().is_some());
2260    }
2261
2262    /// A maximal short-form private section (section_length 0xFFF, total
2263    /// 4098 bytes) reassembles — the ceiling is 12-bit length + 3-byte
2264    /// header, not 4096.
2265    #[test]
2266    fn reassembler_accepts_maximal_private_section() {
2267        let mut section = vec![0x80u8, 0x7F, 0xFF]; // user-private tid, SSI=0, len 0xFFF
2268        section.resize(3 + 0xFFF, 0xAB);
2269
2270        let mut reasm = SectionReassembler::default();
2271        // First TS payload: pointer_field 0 then the section start.
2272        let mut first = vec![0x00];
2273        first.extend_from_slice(&section[..183]);
2274        reasm.feed(&first, true);
2275        for chunk in section[183..].chunks(184) {
2276            reasm.feed(chunk, false);
2277        }
2278        let out = reasm.pop_section().expect("4098-byte section should pop");
2279        assert_eq!(out.len(), 4098);
2280        assert_eq!(out.as_ref(), &section[..]);
2281    }
2282
2283    /// Issue #148: a near-maximal section whose final continuation packet
2284    /// carries the section tail followed by `0xFF` **stuffing** must still
2285    /// complete. The old overflow guard counted the trailing stuffing toward
2286    /// `MAX_SECTION_SIZE` and dropped the section.
2287    #[test]
2288    fn reassembler_completes_large_section_with_trailing_stuffing() {
2289        let body = vec![0x5Au8; 4096 - 3];
2290        let section = test_fixtures::psi::short_section(0x50, &body); // 4096 bytes total
2291        assert_eq!(section.len(), 4096);
2292
2293        let mut reasm = SectionReassembler::default();
2294        // First payload (PUSI): pointer_field 0 + first 183 section bytes.
2295        let mut first = vec![0x00u8];
2296        first.extend_from_slice(&section[..183]);
2297        reasm.feed(&first, true);
2298
2299        // Continuation payloads of a full 184 bytes each; the final one is
2300        // padded with 0xFF stuffing to a complete 184-byte payload, exactly as
2301        // a real TS packet would carry it.
2302        let mut pos = 183usize;
2303        while pos < section.len() {
2304            let take = (section.len() - pos).min(184);
2305            let mut payload = section[pos..pos + take].to_vec();
2306            if take < 184 {
2307                payload.resize(184, 0xFF); // stuffing
2308            }
2309            reasm.feed(&payload, false);
2310            pos += take;
2311        }
2312
2313        let out = reasm
2314            .pop_section()
2315            .expect("4096-byte section must complete despite trailing stuffing (#148)");
2316        assert_eq!(out.len(), 4096);
2317        assert_eq!(out.as_ref(), &section[..]);
2318        assert!(reasm.is_empty(), "stuffing tail must be discarded");
2319    }
2320
2321    // ── adaptation field / PCR (ISO/IEC 13818-1 §2.4.3.4–2.4.3.5) ──
2322
2323    #[test]
2324    fn pcr_as_27mhz_known_value() {
2325        assert_eq!(
2326            Pcr::from_parts(10_000, 0).expect("in range").as_27mhz(),
2327            3_000_000
2328        );
2329        // base*300 + extension: 1*300 + 100 = 400.
2330        assert_eq!(Pcr::from_parts(1, 100).expect("in range").as_27mhz(), 400);
2331    }
2332
2333    #[test]
2334    fn pcr_decode_from_bytes() {
2335        // 6-byte PCR encoding base=10000, extension=0 (reserved bits set).
2336        let af = [0x10u8, 0x00, 0x00, 0x13, 0x88, 0x7E, 0x00];
2337        let pcr = Pcr::parse(&af, 1).expect("6 bytes present");
2338        assert_eq!(pcr, Pcr::from_parts(10_000, 0).expect("in range"));
2339        assert_eq!((pcr.base(), pcr.extension()), (10_000, 0));
2340        assert_eq!(pcr.as_27mhz(), 3_000_000);
2341    }
2342
2343    #[test]
2344    fn adaptation_field_flags_and_pcr() {
2345        let mut raw = [0xAAu8; TS_PACKET_SIZE];
2346        raw[0] = TS_SYNC_BYTE;
2347        raw[1] = 0x01; // pid 0x0100
2348        raw[2] = 0x00;
2349        raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2350        raw[4] = 7; // adaptation_field_length: 1 flags + 6 PCR
2351        raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
2352        raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2353        // raw[12..] stays 0xAA = payload.
2354
2355        let pkt = TsPacket::parse(&raw).expect("valid packet");
2356        let af = pkt
2357            .adaptation_field()
2358            .expect("has adaptation field")
2359            .expect("adaptation field parses");
2360        assert!(af.discontinuity_indicator);
2361        assert!(!af.random_access_indicator);
2362        assert_eq!(af.pcr, Some(Pcr::from_parts(10_000, 0).expect("in range")));
2363        assert_eq!(af.pcr.unwrap().as_27mhz(), 3_000_000);
2364        assert!(af.opcr.is_none());
2365        assert!(af.splice_countdown.is_none());
2366        // Payload begins right after the adaptation field (cursor 4+1+7=12).
2367        let payload = pkt.payload.expect("payload present");
2368        assert_eq!(payload.len(), TS_PACKET_SIZE - 12);
2369        assert_eq!(payload[0], 0xAA);
2370    }
2371
2372    /// The one clock-reference locator agrees with the packet layout for both
2373    /// PCR and OPCR, and never reports a field the adaptation field does not
2374    /// actually reach. Pre-dedupe `ts_dup.rs` handled only PCR and `owned.rs`
2375    /// walked flags with its own bit-walk; a shared locator must give both
2376    /// callers the same answer for an OPCR that follows a PCR.
2377    #[test]
2378    fn clock_reference_slot_locates_pcr_then_opcr_and_rejects_unreached_fields() {
2379        let mut raw = [0xAAu8; TS_PACKET_SIZE];
2380        raw[0] = TS_SYNC_BYTE;
2381        raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2382        raw[4] = (1 + 2 * PCR_FIELD_LEN) as u8; // flags + PCR + OPCR
2383        raw[5] = AF_PCR_FLAG | AF_OPCR_FLAG;
2384
2385        // PCR occupies the first 6 bytes after the flags byte, OPCR the next.
2386        assert!(matches!(
2387            clock_reference_slot(&raw, AF_PCR_FLAG),
2388            ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START..CLOCK_REFERENCE_START + PCR_FIELD_LEN)
2389        ));
2390        assert!(matches!(
2391            clock_reference_slot(&raw, AF_OPCR_FLAG),
2392            ClockReferenceSlot::Field(r) if r == (CLOCK_REFERENCE_START + PCR_FIELD_LEN..CLOCK_REFERENCE_START + 2 * PCR_FIELD_LEN)
2393        ));
2394
2395        // A field-only adaptation field (af_len == 1 + 6) reaches PCR but not
2396        // OPCR: the OPCR flag claims a field the declared length cannot hold.
2397        raw[4] = (1 + PCR_FIELD_LEN) as u8;
2398        assert!(matches!(
2399            clock_reference_slot(&raw, AF_OPCR_FLAG),
2400            ClockReferenceSlot::TooShort { need, have }
2401                if need == 1 + 2 * PCR_FIELD_LEN && have == 1 + PCR_FIELD_LEN
2402        ));
2403
2404        // No adaptation field at all.
2405        let payload_only = {
2406            let mut p = raw;
2407            p[3] = PAYLOAD_FLAG;
2408            p
2409        };
2410        assert!(matches!(
2411            clock_reference_slot(&payload_only, AF_PCR_FLAG),
2412            ClockReferenceSlot::NoAdaptationField
2413        ));
2414
2415        // Flag clear on a packet with enough adaptation field to hold it.
2416        raw[4] = (1 + PCR_FIELD_LEN) as u8;
2417        raw[5] = AF_OPCR_FLAG;
2418        assert!(matches!(
2419            clock_reference_slot(&raw, AF_PCR_FLAG),
2420            ClockReferenceSlot::FlagClear
2421        ));
2422
2423        // A slice truncated before the declared field ends reports the field
2424        // as unreachable, not a `Field` that runs past the buffer (the old
2425        // `ts_dup` copy checked `end > pkt.len()`; the locator must too).
2426        raw[5] = AF_PCR_FLAG;
2427        let truncated = &raw[..8];
2428        assert!(matches!(
2429            clock_reference_slot(truncated, AF_PCR_FLAG),
2430            ClockReferenceSlot::Truncated { need, have } if need == 12 && have == 8
2431        ));
2432    }
2433
2434    #[test]
2435    fn oversized_adaptation_field_length_is_rejected_not_truncated() {
2436        // W6 (#1074): `adaptation_field_length` (raw[4]) can only be 0..=183
2437        // (5 + af_len <= 188). 200 doesn't fit; pre-fix, `TsPacket::parse`
2438        // `.min()`-truncated the slice to whatever bytes remained instead of
2439        // rejecting it, disagreeing with `OwnedTsPacket::adaptation_field`
2440        // (which already returned `None` for the same bytes).
2441        let mut raw = [0xAAu8; TS_PACKET_SIZE];
2442        raw[0] = TS_SYNC_BYTE;
2443        raw[1] = 0x01;
2444        raw[2] = 0x00;
2445        raw[3] = ADAPTATION_FLAG; // no payload flag: has_payload = false
2446        raw[4] = 200; // adaptation_field_length: does not fit in 188 bytes
2447
2448        let pkt = TsPacket::parse(&raw).expect("header + af_len byte still parse");
2449        assert!(
2450            pkt.adaptation_field().is_none(),
2451            "an over-long adaptation field must be rejected, not truncated"
2452        );
2453        assert!(pkt.payload.is_none());
2454
2455        // Cross-check against the owned view, which already rejected this.
2456        let owned = crate::owned::OwnedTsPacket::parse(raw).unwrap();
2457        assert!(owned.adaptation_field().is_none());
2458    }
2459
2460    #[test]
2461    fn no_adaptation_returns_none() {
2462        let mut raw = [0x00u8; TS_PACKET_SIZE];
2463        raw[0] = TS_SYNC_BYTE;
2464        raw[1] = 0x01;
2465        raw[3] = PAYLOAD_FLAG; // payload only
2466        let pkt = TsPacket::parse(&raw).expect("valid");
2467        assert!(pkt.adaptation_field().is_none());
2468        assert!(pkt.adaptation.is_none());
2469    }
2470
2471    #[test]
2472    fn adaptation_field_splice_countdown_negative() {
2473        let mut raw = [0xAAu8; TS_PACKET_SIZE];
2474        raw[0] = TS_SYNC_BYTE;
2475        raw[1] = 0x01;
2476        raw[2] = 0x00;
2477        raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
2478        raw[4] = 2; // 1 flags + 1 splice_countdown
2479        raw[5] = AF_SPLICING_FLAG;
2480        raw[6] = 0xFB; // -5 as i8
2481        let pkt = TsPacket::parse(&raw).expect("valid");
2482        let af = pkt.adaptation_field().unwrap().unwrap();
2483        assert_eq!(af.splice_countdown, Some(-5));
2484        assert!(af.pcr.is_none());
2485    }
2486
2487    // ── ScramblingControl / AdaptationFieldControl enums ──
2488
2489    #[test]
2490    fn scrambling_control_all_values() {
2491        assert_eq!(
2492            ScramblingControl::from_bits(0b00),
2493            ScramblingControl::NotScrambled
2494        );
2495        assert_eq!(
2496            ScramblingControl::from_bits(0b01),
2497            ScramblingControl::Reserved
2498        );
2499        assert_eq!(
2500            ScramblingControl::from_bits(0b10),
2501            ScramblingControl::EvenKey
2502        );
2503        assert_eq!(
2504            ScramblingControl::from_bits(0b11),
2505            ScramblingControl::OddKey
2506        );
2507        // name() labels
2508        assert_eq!(ScramblingControl::NotScrambled.name(), "not_scrambled");
2509        assert_eq!(ScramblingControl::Reserved.name(), "reserved");
2510        assert_eq!(ScramblingControl::EvenKey.name(), "even_key");
2511        assert_eq!(ScramblingControl::OddKey.name(), "odd_key");
2512        // Display delegates to name()
2513        assert_eq!(ScramblingControl::NotScrambled.to_string(), "not_scrambled");
2514        assert_eq!(ScramblingControl::OddKey.to_string(), "odd_key");
2515        // Masking: only low 2 bits matter
2516        assert_eq!(
2517            ScramblingControl::from_bits(0xFF),
2518            ScramblingControl::OddKey
2519        );
2520    }
2521
2522    #[test]
2523    fn adaptation_field_control_all_values() {
2524        assert_eq!(
2525            AdaptationFieldControl::from_flags(false, false),
2526            AdaptationFieldControl::Reserved
2527        );
2528        assert_eq!(
2529            AdaptationFieldControl::from_flags(false, true),
2530            AdaptationFieldControl::PayloadOnly
2531        );
2532        assert_eq!(
2533            AdaptationFieldControl::from_flags(true, false),
2534            AdaptationFieldControl::AdaptationOnly
2535        );
2536        assert_eq!(
2537            AdaptationFieldControl::from_flags(true, true),
2538            AdaptationFieldControl::AdaptationAndPayload
2539        );
2540        // name()
2541        assert_eq!(AdaptationFieldControl::Reserved.name(), "reserved");
2542        assert_eq!(AdaptationFieldControl::PayloadOnly.name(), "payload_only");
2543        assert_eq!(
2544            AdaptationFieldControl::AdaptationOnly.name(),
2545            "adaptation_only"
2546        );
2547        assert_eq!(
2548            AdaptationFieldControl::AdaptationAndPayload.name(),
2549            "adaptation_and_payload"
2550        );
2551        // Display
2552        assert_eq!(
2553            AdaptationFieldControl::PayloadOnly.to_string(),
2554            "payload_only"
2555        );
2556    }
2557
2558    #[test]
2559    fn ts_header_field_types_carry_the_decoded_values() {
2560        let hdr = TsHeader {
2561            tei: false,
2562            pusi: false,
2563            pid: Pid::from_const(0x0100),
2564            scrambling: ScramblingControl::EvenKey,
2565            adaptation_field_control: AdaptationFieldControl::PayloadOnly,
2566            continuity_counter: ContinuityCounter::ZERO,
2567        };
2568        assert_eq!(hdr.scrambling, ScramblingControl::EvenKey);
2569        assert_eq!(
2570            hdr.adaptation_field_control,
2571            AdaptationFieldControl::PayloadOnly
2572        );
2573        assert!(hdr.has_payload());
2574        assert!(!hdr.has_adaptation());
2575
2576        let hdr_both = TsHeader {
2577            adaptation_field_control: AdaptationFieldControl::AdaptationAndPayload,
2578            ..hdr
2579        };
2580        assert_eq!(
2581            hdr_both.adaptation_field_control,
2582            AdaptationFieldControl::AdaptationAndPayload
2583        );
2584        assert!(hdr_both.has_adaptation() && hdr_both.has_payload());
2585    }
2586
2587    #[test]
2588    fn reserved_adaptation_field_control_is_preserved_through_parse_and_serialize() {
2589        // `00` is already a named variant; a header carrying it round-trips
2590        // instead of collapsing into a pair of false flags.
2591        let bytes = [TS_SYNC_BYTE, 0x00, 0x00, 0x05];
2592        let hdr = TsHeader::parse(&bytes).expect("parse");
2593        assert_eq!(
2594            hdr.adaptation_field_control,
2595            AdaptationFieldControl::Reserved
2596        );
2597        assert!(!hdr.has_adaptation() && !hdr.has_payload());
2598        let mut out = [0u8; 4];
2599        hdr.serialize_into(&mut out).expect("serialize");
2600        assert_eq!(out, bytes);
2601    }
2602
2603    // ── iter_packets / extract_ts_payload helpers ──
2604
2605    #[test]
2606    fn iter_packets_yields_valid_and_skips_bad_sync() {
2607        // Two valid packets back-to-back, then one bad-sync packet.
2608        let pkt1 = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA; 10]);
2609        let pkt2 = make_packet(0x40, 0x64, PAYLOAD_FLAG, &[0xBB; 10]);
2610        let mut bad = [0u8; TS_PACKET_SIZE];
2611        bad[0] = 0x00; // bad sync byte
2612
2613        let mut buf = Vec::new();
2614        buf.extend_from_slice(&pkt1);
2615        buf.extend_from_slice(&pkt2);
2616        buf.extend_from_slice(&bad);
2617
2618        let pkts: Vec<_> = super::iter_packets(&buf).collect();
2619        assert_eq!(pkts.len(), 2, "bad sync packet must be skipped");
2620        assert_eq!(pkts[0].header.pid, Pid::from_const(0x0000));
2621        assert_eq!(pkts[1].header.pid, Pid::from_const(0x0064));
2622    }
2623
2624    #[test]
2625    fn extract_ts_payload_payload_only() {
2626        let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xABu8; 10]);
2627        let p = super::extract_ts_payload(&pkt).expect("payload present");
2628        assert_eq!(p[0], 0xAB);
2629        assert_eq!(p.len(), TS_PACKET_SIZE - 4);
2630    }
2631
2632    #[test]
2633    fn extract_ts_payload_adaptation_only_returns_none() {
2634        let pkt = make_packet(0x00, 0x00, ADAPTATION_FLAG, &[]);
2635        assert!(super::extract_ts_payload(&pkt).is_none());
2636    }
2637
2638    // ── Pcr write-side ──────────────────────────────────────────────────────
2639
2640    /// `from_27mhz(v).as_27mhz() == v` for representative values
2641    /// (ISO/IEC 13818-1:2007 §2.4.3.5).
2642    #[test]
2643    fn pcr_from_27mhz_round_trips() {
2644        for &ticks in &[0u64, 1, 300, 27_000_000, u64::from(u32::MAX), 8_589_934_591] {
2645            let pcr = Pcr::from_27mhz(ticks).expect("in range");
2646            assert_eq!(pcr.as_27mhz(), ticks, "ticks={ticks}");
2647        }
2648    }
2649
2650    /// `to_field_bytes` → `parse` → same `Pcr` (field-bytes round-trip).
2651    ///
2652    /// The extension cases stop at 299: the 9-bit wire field can carry
2653    /// `300..=511`, but those cannot name a 27 MHz position, and
2654    /// `pcr_wire_extension_at_or_above_300_is_rejected` pins that.
2655    #[test]
2656    fn pcr_to_field_bytes_round_trips_parse() {
2657        let cases = [
2658            Pcr::from_parts(0, 0).expect("in range"),
2659            Pcr::from_parts(10_000, 0).expect("in range"),
2660            Pcr::from_parts(1, 100).expect("in range"),
2661            Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range"),
2662        ];
2663        for pcr in cases {
2664            let bytes = pcr.to_field_bytes();
2665            // Prefix the 6 bytes with a dummy flags byte so the offset is 1,
2666            // matching the parse() calling convention inside AdaptationField::parse.
2667            let mut af = [0u8; 7];
2668            af[1..7].copy_from_slice(&bytes);
2669            let decoded = Pcr::parse(&af, 1).expect("parse round-trip");
2670            assert_eq!(decoded, pcr, "round-trip failed for {pcr:?}");
2671        }
2672    }
2673
2674    /// A full-width PCR survives the wire codec byte-exactly.
2675    #[test]
2676    fn pcr_full_width_extension_round_trips_the_field() {
2677        let pcr = Pcr::from_parts(0x1_FFFF_FFFF, 299).expect("in range");
2678        // byte 4: base[0] = 1 (bit 7), reserved 6 bits (0x7E), ext[8] = 1 (bit 0).
2679        assert_eq!(pcr.to_field_bytes(), [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x2B]);
2680        assert_eq!(Pcr::parse(&pcr.to_field_bytes(), 0).expect("parse"), pcr);
2681        assert_eq!(
2682            pcr.as_27mhz(),
2683            broadcast_common::clock33::PCR_WRAP_27MHZ - 1
2684        );
2685    }
2686
2687    /// The 9-bit wire extension can encode 300..=511, which is off the 27 MHz
2688    /// clock. Parsing keeps it (lossless round trip) and the checked view
2689    /// reports it, so a real capture still parses and re-serializes.
2690    #[test]
2691    fn pcr_off_clock_wire_extension_parses_losslessly_and_reports() {
2692        let mut bytes = Pcr::from_parts(5, 0).expect("in range").to_field_bytes();
2693        bytes[4] |= 0x01; // extension bit 8
2694        bytes[5] = 0x2C; // extension = 0x12C = 300
2695        let pcr = Pcr::parse(&bytes, 0).expect("a wire-legal field parses");
2696        assert_eq!((pcr.base(), pcr.extension()), (5, 300));
2697        assert_eq!(
2698            pcr.to_field_bytes(),
2699            bytes,
2700            "re-serializes byte-identically"
2701        );
2702        assert!(!pcr.clock().is_valid());
2703        assert!(matches!(
2704            pcr.to_clock27(),
2705            Err(Error::ClockOutOfRange(
2706                broadcast_common::clock33::ClockOutOfRange {
2707                    field: "27 MHz extension",
2708                    value: 300,
2709                    ..
2710                }
2711            ))
2712        ));
2713        // Every extension the 9-bit field can carry survives the codec.
2714        for ext in 0u16..512 {
2715            let mut bytes = Pcr::from_parts(0x1_2345_6789 & ((1 << 33) - 1), 0)
2716                .expect("in range")
2717                .to_field_bytes();
2718            bytes[4] = (bytes[4] & !0x01) | ((ext >> 8) as u8 & 0x01);
2719            bytes[5] = (ext & 0xFF) as u8;
2720            let decoded = Pcr::parse(&bytes, 0).expect("extension is 9 bits on the wire");
2721            assert_eq!(decoded.extension(), ext);
2722            assert_eq!(decoded.to_field_bytes(), bytes);
2723            assert_eq!(decoded.to_clock27().is_ok(), ext < 300);
2724        }
2725    }
2726
2727    /// Known vector from ts.rs existing test — base=10000, extension=0 produces
2728    /// the 6-byte encoding `[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]`.
2729    #[test]
2730    fn pcr_to_field_bytes_known_vector() {
2731        let pcr = Pcr::from_parts(10_000, 0).expect("in range");
2732        let bytes = pcr.to_field_bytes();
2733        assert_eq!(bytes, [0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2734    }
2735
2736    // ── ScramblingControl to_bits ───────────────────────────────────────────
2737
2738    #[test]
2739    fn scrambling_control_to_bits_inverse_of_from_bits() {
2740        for bits in 0u8..=3 {
2741            let sc = ScramblingControl::from_bits(bits);
2742            assert_eq!(sc.to_bits(), bits, "to_bits() != from_bits() for {bits}");
2743        }
2744    }
2745
2746    // ── AdaptationFieldControl to_bits / to_flags ──────────────────────────
2747
2748    #[test]
2749    fn adaptation_field_control_to_bits_inverse_of_from_flags() {
2750        let cases = [
2751            (false, false, 0b00u8),
2752            (false, true, 0b01),
2753            (true, false, 0b10),
2754            (true, true, 0b11),
2755        ];
2756        for (has_af, has_pl, expected_bits) in cases {
2757            let afc = AdaptationFieldControl::from_flags(has_af, has_pl);
2758            assert_eq!(afc.to_bits(), expected_bits);
2759            assert_eq!(afc.to_flags(), (has_af, has_pl));
2760        }
2761    }
2762
2763    // ── AdaptationField serialize_into ─────────────────────────────────────
2764
2765    /// Build an adaptation field with PCR, serialize → parse → verify equal.
2766    #[test]
2767    fn adaptation_field_serialize_round_trip_with_pcr() {
2768        let original = AdaptationField {
2769            discontinuity_indicator: true,
2770            random_access_indicator: false,
2771            elementary_stream_priority_indicator: false,
2772            pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2773            opcr: None,
2774            splice_countdown: None,
2775            transport_private_data: None,
2776            extension: None,
2777            stuffing: &[],
2778            pcr_reserved: PCR_RESERVED_VALUE,
2779            opcr_reserved: PCR_RESERVED_VALUE,
2780        };
2781        let len = original.serialized_len();
2782        assert_eq!(len, 7); // 1 flags + 6 PCR
2783        let mut buf = vec![0u8; len];
2784        let written = original.serialize_into(&mut buf).expect("serialize");
2785        assert_eq!(written, len);
2786        let decoded = AdaptationField::parse(&buf).expect("parse round-trip");
2787        assert_eq!(decoded, original);
2788    }
2789
2790    /// W10 (#1129): `transport_private_data_length` is an 8-bit field but
2791    /// used to be written with `tpd.len() as u8`, wrapping to a short length
2792    /// while the full data was still copied after it.
2793    #[test]
2794    fn transport_private_data_over_255_bytes_rejected_not_wrapped() {
2795        let data = vec![0u8; 256];
2796        let af = AdaptationField {
2797            discontinuity_indicator: false,
2798            random_access_indicator: false,
2799            elementary_stream_priority_indicator: false,
2800            pcr: None,
2801            opcr: None,
2802            splice_countdown: None,
2803            transport_private_data: Some(&data),
2804            extension: None,
2805            stuffing: &[],
2806            pcr_reserved: PCR_RESERVED_VALUE,
2807            opcr_reserved: PCR_RESERVED_VALUE,
2808        };
2809        let mut buf = vec![0u8; af.serialized_len()];
2810        assert!(matches!(
2811            &(af.serialize_into(&mut buf)),
2812            Err(crate::error::Error::FieldOverflow(_))
2813        ));
2814    }
2815
2816    /// Known-bytes test: flags=0x30 (discontinuity + PCR), known PCR vector.
2817    #[test]
2818    fn adaptation_field_serialize_produces_known_bytes() {
2819        // Matches the packet in ts.rs `adaptation_field_flags_and_pcr` test:
2820        // raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG = 0x90
2821        // raw[6..12] = [0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]
2822        let af = AdaptationField {
2823            discontinuity_indicator: true,
2824            random_access_indicator: false,
2825            elementary_stream_priority_indicator: false,
2826            pcr: Some(Pcr::from_parts(10_000, 0).expect("in range")),
2827            opcr: None,
2828            splice_countdown: None,
2829            transport_private_data: None,
2830            extension: None,
2831            stuffing: &[],
2832            pcr_reserved: PCR_RESERVED_VALUE,
2833            opcr_reserved: PCR_RESERVED_VALUE,
2834        };
2835        let mut buf = [0u8; 7];
2836        af.serialize_into(&mut buf).unwrap();
2837        assert_eq!(buf[0], AF_DISCONTINUITY | AF_PCR_FLAG);
2838        assert_eq!(&buf[1..7], &[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
2839    }
2840
2841    /// Serialize → parse round-trip for AdaptationField with OPCR + splice_countdown.
2842    #[test]
2843    fn adaptation_field_serialize_round_trip_opcr_and_splice() {
2844        let original = AdaptationField {
2845            discontinuity_indicator: false,
2846            random_access_indicator: true,
2847            elementary_stream_priority_indicator: true,
2848            pcr: Some(Pcr::from_parts(1, 100).expect("in range")),
2849            opcr: Some(Pcr::from_parts(999, 5).expect("in range")),
2850            splice_countdown: Some(-3),
2851            transport_private_data: None,
2852            extension: None,
2853            stuffing: &[],
2854            pcr_reserved: PCR_RESERVED_VALUE,
2855            opcr_reserved: PCR_RESERVED_VALUE,
2856        };
2857        let len = original.serialized_len();
2858        assert_eq!(len, 1 + 6 + 6 + 1); // flags + PCR + OPCR + splice
2859        let mut buf = vec![0u8; len];
2860        original.serialize_into(&mut buf).unwrap();
2861        let decoded = AdaptationField::parse(&buf).expect("parse");
2862        assert_eq!(decoded, original);
2863    }
2864
2865    /// Flags-only AdaptationField (no PCR/OPCR/splice).
2866    #[test]
2867    fn adaptation_field_serialize_flags_only() {
2868        let af = AdaptationField {
2869            discontinuity_indicator: false,
2870            random_access_indicator: true,
2871            elementary_stream_priority_indicator: false,
2872            pcr: None,
2873            opcr: None,
2874            splice_countdown: None,
2875            transport_private_data: None,
2876            extension: None,
2877            stuffing: &[],
2878            pcr_reserved: PCR_RESERVED_VALUE,
2879            opcr_reserved: PCR_RESERVED_VALUE,
2880        };
2881        assert_eq!(af.serialized_len(), 1);
2882        let mut buf = [0u8; 1];
2883        af.serialize_into(&mut buf).unwrap();
2884        assert_eq!(buf[0], AF_RANDOM_ACCESS);
2885        let decoded = AdaptationField::parse(&buf).unwrap();
2886        assert_eq!(decoded, af);
2887    }
2888
2889    /// OutputBufferTooSmall returned when buffer is too short.
2890    #[test]
2891    fn adaptation_field_serialize_rejects_small_buffer() {
2892        let af = AdaptationField {
2893            discontinuity_indicator: false,
2894            random_access_indicator: false,
2895            elementary_stream_priority_indicator: false,
2896            pcr: Some(Pcr::from_parts(0, 0).expect("in range")),
2897            opcr: None,
2898            splice_countdown: None,
2899            transport_private_data: None,
2900            extension: None,
2901            stuffing: &[],
2902            pcr_reserved: PCR_RESERVED_VALUE,
2903            opcr_reserved: PCR_RESERVED_VALUE,
2904        };
2905        let mut buf = [0u8; 3]; // need 7
2906        assert!(matches!(
2907            af.serialize_into(&mut buf),
2908            Err(Error::OutputBufferTooSmall(..))
2909        ));
2910    }
2911
2912    // ── AdaptationFieldExtension (§2.4.3.5) ────────────────────────────────
2913
2914    /// Round-trip LTW field.
2915    #[test]
2916    fn adaptation_field_extension_ltw_round_trip() {
2917        let ext = AdaptationFieldExtension {
2918            ltw: Some(Ltw {
2919                ltw_valid_flag: true,
2920                ltw_offset: LtwOffset::new(0x1234).expect("in range"),
2921            }),
2922            piecewise_rate: None,
2923            seamless_splice: None,
2924            ..AdaptationFieldExtension::new()
2925        };
2926        let mut buf = vec![0u8; ext.serialized_len()];
2927        ext.serialize_into(&mut buf).unwrap();
2928        // Parse via AdaptationField (extension is the last field)
2929        // Build a full AdaptationField with only the extension set.
2930        let af = AdaptationField {
2931            discontinuity_indicator: false,
2932            random_access_indicator: false,
2933            elementary_stream_priority_indicator: false,
2934            pcr: None,
2935            opcr: None,
2936            splice_countdown: None,
2937            transport_private_data: None,
2938            extension: Some(ext),
2939            stuffing: &[],
2940            pcr_reserved: PCR_RESERVED_VALUE,
2941            opcr_reserved: PCR_RESERVED_VALUE,
2942        };
2943        let len = af.serialized_len();
2944        let mut abuf = vec![0u8; len];
2945        af.serialize_into(&mut abuf).unwrap();
2946        let decoded = AdaptationField::parse(&abuf).unwrap();
2947        assert_eq!(decoded.extension, Some(ext));
2948    }
2949
2950    /// Round-trip piecewise_rate field.
2951    #[test]
2952    fn adaptation_field_extension_piecewise_rate_round_trip() {
2953        let af = AdaptationField {
2954            discontinuity_indicator: false,
2955            random_access_indicator: false,
2956            elementary_stream_priority_indicator: false,
2957            pcr: None,
2958            opcr: None,
2959            splice_countdown: None,
2960            transport_private_data: None,
2961            extension: Some(AdaptationFieldExtension {
2962                ltw: None,
2963                piecewise_rate: Some(PiecewiseRate::MAX),
2964                seamless_splice: None,
2965                ..AdaptationFieldExtension::new()
2966            }),
2967            stuffing: &[],
2968            pcr_reserved: PCR_RESERVED_VALUE,
2969            opcr_reserved: PCR_RESERVED_VALUE,
2970        };
2971        let mut buf = vec![0u8; af.serialized_len()];
2972        af.serialize_into(&mut buf).unwrap();
2973        let decoded = AdaptationField::parse(&buf).unwrap();
2974        assert_eq!(
2975            decoded.extension.unwrap().piecewise_rate,
2976            Some(PiecewiseRate::MAX)
2977        );
2978    }
2979
2980    /// Round-trip seamless_splice field.
2981    #[test]
2982    fn adaptation_field_extension_seamless_splice_round_trip() {
2983        let af = AdaptationField {
2984            discontinuity_indicator: false,
2985            random_access_indicator: false,
2986            elementary_stream_priority_indicator: false,
2987            pcr: None,
2988            opcr: None,
2989            splice_countdown: None,
2990            transport_private_data: None,
2991            extension: Some(AdaptationFieldExtension {
2992                ltw: None,
2993                piecewise_rate: None,
2994                seamless_splice: Some(SeamlessSplice::new(0xA, 0x1_2345_6789)),
2995                ..AdaptationFieldExtension::new()
2996            }),
2997            stuffing: &[],
2998            pcr_reserved: PCR_RESERVED_VALUE,
2999            opcr_reserved: PCR_RESERVED_VALUE,
3000        };
3001        let mut buf = vec![0u8; af.serialized_len()];
3002        af.serialize_into(&mut buf).unwrap();
3003        let decoded = AdaptationField::parse(&buf).unwrap();
3004        let ss = decoded.extension.unwrap().seamless_splice.unwrap();
3005        assert_eq!(ss.splice_type, 0xA);
3006        assert_eq!(ss.dts_next_au, 0x1_2345_6789);
3007    }
3008
3009    /// A `DTS_next_AU` wider than 33 bits or a `splice_type` wider than the
3010    /// nibble used to be reduced modulo the field width and written as a
3011    /// different, valid-looking value.
3012    #[test]
3013    fn adaptation_field_extension_seamless_splice_rejects_over_range_fields() {
3014        let mut ss = SeamlessSplice::new(0xA, 0x1_2345_6789);
3015        ss.dts_next_au = 1 << SeamlessSplice::DTS_NEXT_AU_BITS;
3016        assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
3017        ss.dts_next_au = (1 << SeamlessSplice::DTS_NEXT_AU_BITS) - 1;
3018        assert!(ss.to_marked_field().is_ok());
3019
3020        let mut ss = SeamlessSplice::new(0x10, 0x1_2345_6789);
3021        assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
3022        ss.splice_type = 0x0F;
3023        ss.marker_bits = SPLICE_MARKERS_VALUE + 1;
3024        assert!(matches!(ss.to_marked_field(), Err(Error::FieldOverflow(_))));
3025        ss.marker_bits = SPLICE_MARKERS_VALUE;
3026        assert!(ss.to_marked_field().is_ok());
3027    }
3028
3029    /// `ltw_offset` and `piecewise_rate` used to be written with their wire
3030    /// masks, so an over-range value became a different valid value; the
3031    /// bounded newtypes refuse it at construction and the serializer rechecks.
3032    #[test]
3033    fn adaptation_field_extension_rejects_over_range_ltw_and_rate() {
3034        assert!(matches!(
3035            LtwOffset::new(0x8000),
3036            Err(Error::FieldOverflow(_))
3037        ));
3038        assert_eq!(LtwOffset::new(LtwOffset::MAX.get()), Ok(LtwOffset::MAX));
3039        assert!(matches!(
3040            PiecewiseRate::new(0x40_0000),
3041            Err(Error::FieldOverflow(_))
3042        ));
3043        assert_eq!(PiecewiseRate::new(0x3F_FFFF), Ok(PiecewiseRate::MAX));
3044
3045        let mut ext = AdaptationFieldExtension::new();
3046        ext.ltw = Some(Ltw {
3047            ltw_valid_flag: true,
3048            ltw_offset: LtwOffset::MAX,
3049        });
3050        ext.piecewise_rate = Some(PiecewiseRate::MAX);
3051        let mut buf = vec![0u8; ext.serialized_len()];
3052        ext.serialize_into(&mut buf).unwrap();
3053        assert_eq!(buf[1..3], [0xDF, 0xFF]);
3054        assert_eq!(buf[3..6], [0xFF, 0xFF, 0xFF]);
3055        assert_eq!(AdaptationFieldExtension::parse(&buf).unwrap(), ext);
3056    }
3057
3058    /// An over-range `pcr_reserved` used to be shifted into the PCR base bits
3059    /// (writing a different clock value) instead of being rejected.
3060    #[test]
3061    fn adaptation_field_serialize_rejects_over_range_reserved_bits() {
3062        let mut af = AdaptationField::new();
3063        af.pcr = Some(Pcr::from_parts(0, 0).expect("in range"));
3064        let mut ok = [0u8; 7];
3065        af.serialize_into(&mut ok).unwrap();
3066        assert_eq!(&ok[1..6], &[0x00, 0x00, 0x00, 0x00, 0x7E]);
3067
3068        af.pcr_reserved = PCR_RESERVED_VALUE + 1;
3069        let mut buf = [0u8; 7];
3070        assert!(matches!(
3071            af.serialize_into(&mut buf),
3072            Err(Error::FieldOverflow(_))
3073        ));
3074    }
3075
3076    /// Round-trip with transport_private_data.
3077    #[test]
3078    fn adaptation_field_transport_private_data_round_trip() {
3079        let tpd = [0xDE, 0xAD, 0xBE, 0xEF];
3080        let af = AdaptationField {
3081            discontinuity_indicator: false,
3082            random_access_indicator: false,
3083            elementary_stream_priority_indicator: false,
3084            pcr: None,
3085            opcr: None,
3086            splice_countdown: None,
3087            transport_private_data: Some(&tpd),
3088            extension: None,
3089            stuffing: &[],
3090            pcr_reserved: PCR_RESERVED_VALUE,
3091            opcr_reserved: PCR_RESERVED_VALUE,
3092        };
3093        let mut buf = vec![0u8; af.serialized_len()];
3094        af.serialize_into(&mut buf).unwrap();
3095        let decoded = AdaptationField::parse(&buf).unwrap();
3096        assert_eq!(decoded.transport_private_data, Some(tpd.as_slice()));
3097    }
3098
3099    /// PCR + `0xFF` stuffing round-trips byte-identical, and the stuffing is
3100    /// re-emitted as `0xFF` (ISO/IEC 13818-1:2007 §2.4.3.4).
3101    #[test]
3102    fn adaptation_field_stuffing_round_trip() {
3103        let af = AdaptationField {
3104            discontinuity_indicator: false,
3105            random_access_indicator: false,
3106            elementary_stream_priority_indicator: false,
3107            pcr: Some(Pcr::from_parts(12_345, 7).expect("in range")),
3108            opcr: None,
3109            splice_countdown: None,
3110            transport_private_data: None,
3111            extension: None,
3112            stuffing: &[0xFF; 20],
3113            pcr_reserved: PCR_RESERVED_VALUE,
3114            opcr_reserved: PCR_RESERVED_VALUE,
3115        };
3116        // 1 flags + 6 PCR + 20 stuffing.
3117        assert_eq!(af.serialized_len(), 27);
3118        let mut buf = vec![0u8; af.serialized_len()];
3119        af.serialize_into(&mut buf).unwrap();
3120        // Trailing bytes are 0xFF stuffing.
3121        assert!(buf[7..27].iter().all(|&b| b == 0xFF));
3122        let decoded = AdaptationField::parse(&buf).unwrap();
3123        assert_eq!(decoded.stuffing.len(), 20);
3124        assert_eq!(decoded, af);
3125        // Pure stuffing (flags-only body padded out) also round-trips.
3126        let pure = AdaptationField {
3127            discontinuity_indicator: false,
3128            random_access_indicator: false,
3129            elementary_stream_priority_indicator: false,
3130            pcr: None,
3131            opcr: None,
3132            splice_countdown: None,
3133            transport_private_data: None,
3134            extension: None,
3135            stuffing: &[0xFF; 5],
3136            pcr_reserved: PCR_RESERVED_VALUE,
3137            opcr_reserved: PCR_RESERVED_VALUE,
3138        };
3139        let mut pbuf = vec![0u8; pure.serialized_len()];
3140        pure.serialize_into(&mut pbuf).unwrap();
3141        assert_eq!(pbuf, vec![0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
3142        assert_eq!(AdaptationField::parse(&pbuf).unwrap(), pure);
3143    }
3144
3145    /// All optional fields together: PCR + splice + TPD + extension.
3146    #[test]
3147    fn adaptation_field_all_fields_round_trip() {
3148        let tpd = [0x01u8, 0x02, 0x03];
3149        let af = AdaptationField {
3150            discontinuity_indicator: true,
3151            random_access_indicator: false,
3152            elementary_stream_priority_indicator: false,
3153            pcr: Some(Pcr::from_parts(90_000, 50).expect("in range")),
3154            opcr: None,
3155            splice_countdown: Some(10),
3156            transport_private_data: Some(&tpd),
3157            extension: Some(AdaptationFieldExtension {
3158                ltw: Some(Ltw {
3159                    ltw_valid_flag: false,
3160                    ltw_offset: LtwOffset::new(500).expect("in range"),
3161                }),
3162                piecewise_rate: Some(PiecewiseRate::new(12345).expect("in range")),
3163                seamless_splice: None,
3164                ..AdaptationFieldExtension::new()
3165            }),
3166            stuffing: &[],
3167            pcr_reserved: PCR_RESERVED_VALUE,
3168            opcr_reserved: PCR_RESERVED_VALUE,
3169        };
3170        let len = af.serialized_len();
3171        let mut buf = vec![0u8; len];
3172        af.serialize_into(&mut buf).unwrap();
3173        let decoded = AdaptationField::parse(&buf).unwrap();
3174        assert_eq!(decoded.pcr, af.pcr);
3175        assert_eq!(decoded.splice_countdown, af.splice_countdown);
3176        assert_eq!(decoded.transport_private_data, af.transport_private_data);
3177        assert_eq!(decoded.extension, af.extension);
3178        assert!(decoded.discontinuity_indicator);
3179    }
3180
3181    /// Full round-trip: build a packet with PCR in adaptation field, parse
3182    /// it, re-serialize the adaptation field, re-parse, assert PCR matches.
3183    #[test]
3184    fn adaptation_field_serialize_from_real_packet_bytes() {
3185        // Replicate the raw packet from `adaptation_field_flags_and_pcr`.
3186        let mut raw = [0xAAu8; TS_PACKET_SIZE];
3187        raw[0] = TS_SYNC_BYTE;
3188        raw[1] = 0x01;
3189        raw[2] = 0x00;
3190        raw[3] = ADAPTATION_FLAG | PAYLOAD_FLAG;
3191        raw[4] = 7;
3192        raw[5] = AF_DISCONTINUITY | AF_PCR_FLAG;
3193        raw[6..12].copy_from_slice(&[0x00, 0x00, 0x13, 0x88, 0x7E, 0x00]);
3194
3195        let pkt = TsPacket::parse(&raw).unwrap();
3196        let af = pkt.adaptation_field().unwrap().unwrap();
3197
3198        // Re-serialize.
3199        let mut ser = vec![0u8; af.serialized_len()];
3200        af.serialize_into(&mut ser).unwrap();
3201        let decoded = AdaptationField::parse(&ser).unwrap();
3202        assert_eq!(
3203            decoded.pcr,
3204            Some(Pcr::from_parts(10_000, 0).expect("in range"))
3205        );
3206        assert!(decoded.discontinuity_indicator);
3207    }
3208}