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