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