Skip to main content

dvb_si/
ts.rs

1//! MPEG-TS packet parser + section reassembler. Feature-gated under `ts`.
2
3use crate::error::{Error, Result};
4
5/// Size of one MPEG-TS packet (ETSI EN 300 468 §3.2, ISO/IEC 13818-1 §2.4.3.2).
6pub const TS_PACKET_SIZE: usize = 188;
7/// Sync byte that every TS packet starts with (ISO/IEC 13818-1 §2.4.3.2).
8pub const TS_SYNC_BYTE: u8 = 0x47;
9/// Upper bound on a single section: `section_length` is 12 bits (max 4095)
10/// plus the 3-byte header = 4098. (Long-form SI caps `section_length` at
11/// 4093 → total 4096, but maximal short-form private sections may reach
12/// 4098; the reassembler accepts the absolute ceiling.)
13const MAX_SECTION_SIZE: usize = 4098;
14
15/// ETSI EN 300 468 §3.2.3: transport header byte 1 bits 7 = tei (Transport Error Indicator).
16const TEI_MASK: u8 = 0x80;
17/// ETSI EN 300 468 §3.2.3: byte 1 bits 6 = pusi (Payload Unit Start Indicator).
18const PUSI_MASK: u8 = 0x40;
19/// ETSI EN 300 468 §3.2.3: byte 1 bits 5..=1 = 13-bit PID (upper 5 bits).
20pub const PID_MASK_HI: u8 = 0x1F;
21/// ETSI EN 300 468 §3.2.3: byte 3 bits 7..=6 = 2-bit scrambling control.
22pub const SCRAMBLING_MASK: u8 = 0xC0;
23/// ETSI EN 300 468 §3.2.3: byte 3 bit 4 = adaptation_field_control (bit 4 = 1 means adaptation present).
24pub const ADAPTATION_FLAG: u8 = 0x20;
25/// ETSI EN 300 468 §3.2.3: byte 3 bit 3 = adaptation_field_control (bit 3 = 1 means payload present).
26pub const PAYLOAD_FLAG: u8 = 0x10;
27/// ETSI EN 300 468 §3.2.3: byte 3 bits 3..=0 = 4-bit continuity_counter.
28pub const CC_MASK: u8 = 0x0F;
29
30/// Parsed TS header — the 4-byte transport header fields.
31#[derive(Clone, Debug, PartialEq, Eq)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize))]
33pub struct TsHeader {
34    /// Transport Error Indicator — set by the demodulator when an
35    /// uncorrectable error is present in the packet.
36    pub tei: bool,
37    /// Payload Unit Start Indicator — first byte of the payload is a new
38    /// PES packet or PSI section header when set.
39    pub pusi: bool,
40    /// 13-bit Packet Identifier.
41    pub pid: u16,
42    /// 2-bit transport_scrambling_control (0 = not scrambled).
43    pub scrambling: u8,
44    /// Adaptation field present flag (adaptation_field_control bit 1).
45    pub has_adaptation: bool,
46    /// Payload present flag (adaptation_field_control bit 0).
47    pub has_payload: bool,
48    /// 4-bit continuity_counter (wraps 0..=15 per PID).
49    pub continuity_counter: u8,
50}
51
52/// Borrowed view into one 188-byte TS packet.
53///
54/// Serde: Serialize-only (re-parse from wire bytes to reconstruct). `raw` is
55/// excluded from the serialized form because it is redundant once the header
56/// has been parsed.
57#[derive(Clone, Debug)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize))]
59pub struct TsPacket<'a> {
60    /// Parsed header fields.
61    pub header: TsHeader,
62    /// Slice into the packet's payload, or `None` when `has_payload == false`
63    /// or the adaptation field consumed the whole packet body.
64    pub payload: Option<&'a [u8]>,
65    /// The raw 188 bytes of the packet — kept for cheap forwarding.
66    #[cfg_attr(feature = "serde", serde(skip))]
67    pub raw: &'a [u8; TS_PACKET_SIZE],
68}
69
70impl TsHeader {
71    /// Parse a 4-byte TS transport header.
72    ///
73    /// Returns `None` if `raw4` is shorter than 4 bytes.
74    pub fn parse(raw4: &[u8]) -> Option<Self> {
75        if raw4.len() < 4 {
76            return None;
77        }
78        let b1 = raw4[1];
79        let b2 = raw4[2];
80        let b3 = raw4[3];
81
82        let tei = (b1 & TEI_MASK) != 0;
83        let pusi = (b1 & PUSI_MASK) != 0;
84        let pid = (((b1 & PID_MASK_HI) as u16) << 8) | (b2 as u16);
85        let scrambling = (b3 & SCRAMBLING_MASK) >> 6;
86        let has_adaptation = (b3 & ADAPTATION_FLAG) != 0;
87        let has_payload = (b3 & PAYLOAD_FLAG) != 0;
88        let continuity_counter = b3 & CC_MASK;
89
90        Some(Self {
91            tei,
92            pusi,
93            pid,
94            scrambling,
95            has_adaptation,
96            has_payload,
97            continuity_counter,
98        })
99    }
100
101    /// Serialize this header into the first 4 bytes of `buf`.
102    ///
103    /// Panics if `buf` is shorter than 4 bytes.
104    pub fn serialize_into(&self, buf: &mut [u8]) {
105        assert!(
106            buf.len() >= 4,
107            "buffer must have at least 4 bytes for TS header"
108        );
109        buf[0] = TS_SYNC_BYTE;
110        buf[1] = 0;
111        if self.tei {
112            buf[1] |= TEI_MASK;
113        }
114        if self.pusi {
115            buf[1] |= PUSI_MASK;
116        }
117        buf[1] |= ((self.pid >> 8) as u8) & PID_MASK_HI;
118        buf[2] = (self.pid & 0xFF) as u8;
119        buf[3] = (self.scrambling << 6) & SCRAMBLING_MASK;
120        if self.has_adaptation {
121            buf[3] |= ADAPTATION_FLAG;
122        }
123        if self.has_payload {
124            buf[3] |= PAYLOAD_FLAG;
125        }
126        buf[3] |= self.continuity_counter & CC_MASK;
127    }
128}
129
130impl<'a> TsPacket<'a> {
131    /// Parse a single 188-byte TS packet from a buffer.
132    ///
133    /// Returns `Err(Error::InvalidSyncByte)` if the first byte is not `0x47`,
134    /// `Err(Error::BufferTooShort)` if fewer than 188 bytes, or `Ok` with
135    /// the parsed packet otherwise.
136    pub fn parse(buf: &'a [u8]) -> Result<Self> {
137        if buf.len() < TS_PACKET_SIZE {
138            return Err(Error::BufferTooShort {
139                need: TS_PACKET_SIZE,
140                have: buf.len(),
141                what: "TsPacket::parse",
142            });
143        }
144        if buf[0] != TS_SYNC_BYTE {
145            return Err(Error::InvalidSyncByte { found: buf[0] });
146        }
147
148        let raw: &[u8; TS_PACKET_SIZE] =
149            buf[..TS_PACKET_SIZE]
150                .try_into()
151                .map_err(|_| Error::BufferTooShort {
152                    need: TS_PACKET_SIZE,
153                    have: buf.len(),
154                    what: "TsPacket::parse (array conversion)",
155                })?;
156
157        let header = TsHeader::parse(&raw[..4])
158            .expect("raw is 188 bytes so first 4 bytes are always present");
159
160        let mut cursor = 4usize;
161        let mut payload = None;
162
163        // Skip adaptation field if present (not parsed in detail — not needed for sections).
164        if header.has_adaptation && cursor < TS_PACKET_SIZE {
165            let af_len = raw[cursor] as usize;
166            cursor += 1 + af_len;
167        }
168
169        if header.has_payload && cursor < TS_PACKET_SIZE {
170            payload = Some(&raw[cursor..]);
171        }
172
173        Ok(TsPacket {
174            header,
175            payload,
176            raw,
177        })
178    }
179}
180
181/// Reassembles PSI/SI sections from TS packets on a single PID.
182///
183/// Feed each TS packet's payload with `feed`. Complete sections are
184/// appended to an internal queue; drain them with `pop_section`.
185#[derive(Default)]
186pub struct SectionReassembler {
187    buf: bytes::BytesMut,
188    expected: usize,
189    ready: std::collections::VecDeque<bytes::Bytes>,
190}
191
192impl SectionReassembler {
193    /// Feed a TS payload and whether its packet had PUSI set.
194    ///
195    /// Extracts complete SI sections into the internal queue. A single call
196    /// can produce zero, one, or **several** sections — a payload may
197    /// concatenate multiple complete sections after the `pointer_field`
198    /// (EN 300 468 §5.1.4; common on EMM PIDs). Drain with a
199    /// `while let Some(s) = r.pop_section()` loop, not a single `if let`.
200    pub fn feed(&mut self, payload: &[u8], pusi: bool) {
201        if pusi {
202            // A PUSI packet whose adaptation field consumed the whole body is
203            // malformed but constructible — drop sync rather than panic.
204            if payload.is_empty() {
205                self.buf.clear();
206                self.expected = 0;
207                return;
208            }
209            let pointer = payload[0] as usize;
210            let start = 1 + pointer;
211            if start >= payload.len() {
212                self.buf.clear();
213                return;
214            }
215            self.buf.clear();
216            let new_data = &payload[start..];
217            if self.buf.len() + new_data.len() > MAX_SECTION_SIZE {
218                self.buf.clear();
219                self.expected = 0;
220                return;
221            }
222            self.buf.extend_from_slice(new_data);
223        } else {
224            if self.buf.is_empty() {
225                return;
226            }
227            if self.buf.len() + payload.len() > MAX_SECTION_SIZE {
228                self.buf.clear();
229                self.expected = 0;
230                return;
231            }
232            self.buf.extend_from_slice(payload);
233        }
234
235        self.drain_complete_sections();
236    }
237
238    /// Queue every complete section the buffer currently holds.
239    ///
240    /// A single TS payload may concatenate multiple complete sections after
241    /// the `pointer_field` (legal per ETSI EN 300 468 §5.1.4 and common on
242    /// EMM PIDs, which pack several short messages into one payload). We must
243    /// keep extracting until the buffer holds only a partial (multi-packet
244    /// spanning) section, which is stashed as `expected` for the next
245    /// continuation. A `0xFF` where a `table_id` is expected marks the rest of
246    /// the payload as stuffing.
247    fn drain_complete_sections(&mut self) {
248        loop {
249            if self.buf.len() < 3 {
250                // Not enough for a section header yet; keep the partial bytes
251                // and wait for the next packet to complete the header.
252                self.expected = 0;
253                break;
254            }
255            if self.buf[0] == 0xFF {
256                // Stuffing where a table_id is expected — payload tail is fill.
257                self.buf.clear();
258                self.expected = 0;
259                break;
260            }
261            let exp = 3 + (((self.buf[1] & 0x0F) as usize) << 8 | self.buf[2] as usize);
262            if self.buf.len() >= exp {
263                // split_to returns the first `exp` bytes as an owned BytesMut,
264                // leaving the remainder in self.buf — cheap (shifts pointers).
265                let section = self.buf.split_to(exp).freeze();
266                self.ready.push_back(section);
267                self.expected = 0;
268            } else {
269                // Partial section spanning into later packets.
270                self.expected = exp;
271                break;
272            }
273        }
274    }
275
276    /// Pop one complete section. Returns `None` when the queue is empty.
277    pub fn pop_section(&mut self) -> Option<bytes::Bytes> {
278        self.ready.pop_front()
279    }
280
281    /// Number of bytes currently buffered (incomplete section).
282    pub fn len(&self) -> usize {
283        self.buf.len()
284    }
285
286    /// True if no bytes are currently buffered.
287    pub fn is_empty(&self) -> bool {
288        self.buf.is_empty()
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    /// Helper: construct a minimal 188-byte TS packet buffer with given header flags and payload.
297    fn make_packet(b1: u8, b2: u8, b3: u8, payload_data: &[u8]) -> [u8; TS_PACKET_SIZE] {
298        let mut pkt = [0u8; TS_PACKET_SIZE];
299        pkt[0] = TS_SYNC_BYTE;
300        pkt[1] = b1;
301        pkt[2] = b2;
302        pkt[3] = b3;
303        let payload_start = 4;
304        let end = (payload_start + payload_data.len()).min(TS_PACKET_SIZE);
305        let len = (end - payload_start).min(payload_data.len());
306        pkt[payload_start..payload_start + len].copy_from_slice(&payload_data[..len]);
307        pkt
308    }
309
310    #[test]
311    fn parse_rejects_non_0x47_sync_byte() {
312        let mut pkt = [0u8; TS_PACKET_SIZE];
313        pkt[0] = 0x46; // wrong sync byte
314        let err = TsPacket::parse(&pkt).unwrap_err();
315        match err {
316            Error::InvalidSyncByte { found } => assert_eq!(found, 0x46),
317            other => panic!("expected InvalidSyncByte, got {other:?}"),
318        }
319    }
320
321    #[test]
322    fn parse_extracts_pid_and_continuity_counter() {
323        // PID = 0x1234 → upper 5 bits = 0x12, lower 8 bits = 0x34
324        // CC = 5 → 0x05
325        // b1 = 0x47 (sync=0, tei=0, pusi=0) | (0x12) = 0x47 & 0xE0 | 0x12 = 0x47 & 0xE0 = 0x40 | 0x12 = 0x52
326        // Actually: b1 bits: [tei:1][pusi:1][pid_hi:5]
327        // pid_hi = 0x12 = 0b00100_10 → bits 5..=1 = 0x12
328        // b1 = 0b00_010010 = 0x12 (no tei, no pusi)
329        let pkt = make_packet(0x12, 0x34, 0x05, &[]);
330        let pkt = TsPacket::parse(&pkt).unwrap();
331        assert_eq!(pkt.header.pid, 0x1234);
332        assert_eq!(pkt.header.continuity_counter, 5);
333    }
334
335    #[test]
336    fn payload_unit_start_indicator_flag_extracted() {
337        // b1 = 0x40 → pusi = true (bit 6 set, no tei, no pid bits)
338        let pkt1 = make_packet(0x40, 0x00, 0x00, &[]);
339        let pkt1 = TsPacket::parse(&pkt1).unwrap();
340        assert!(pkt1.header.pusi);
341
342        // b1 = 0x00 → pusi = false
343        let pkt2 = make_packet(0x00, 0x00, 0x00, &[]);
344        let pkt2 = TsPacket::parse(&pkt2).unwrap();
345        assert!(!pkt2.header.pusi);
346    }
347
348    /// Build a PSI-carrying TS payload: `pointer_field` byte followed by
349    /// (optionally) some tail of a previous section, followed by a fresh
350    /// section. `pointer_field` is the number of bytes of the previous
351    /// section that precede the new one (per ETSI EN 300 468 §5.1.4).
352    fn build_pusi_payload(pointer_field: u8, previous_tail: &[u8], section: &[u8]) -> Vec<u8> {
353        assert_eq!(pointer_field as usize, previous_tail.len());
354        let mut v = Vec::with_capacity(1 + previous_tail.len() + section.len());
355        v.push(pointer_field);
356        v.extend_from_slice(previous_tail);
357        v.extend_from_slice(section);
358        v
359    }
360
361    /// Build a long-form section with the given table_id and body bytes.
362    /// Returns the full section including its 3-byte + 5-byte header and a
363    /// placeholder CRC — for reassembler testing we don't validate the CRC.
364    fn build_section(table_id: u8, body_after_length: &[u8]) -> Vec<u8> {
365        let section_length = body_after_length.len() as u16;
366        let mut v = Vec::with_capacity(3 + section_length as usize);
367        v.push(table_id);
368        // ssi=1, pi=0, reserved=11, length hi 4 bits
369        v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
370        v.push((section_length & 0xFF) as u8);
371        v.extend_from_slice(body_after_length);
372        v
373    }
374
375    // The reassembler tests below feed raw payload slices directly to
376    // `feed()` rather than wrapping them in 188-byte TS packets. This avoids
377    // the TS stuffing-byte tail (0xFF padding) bleeding into the reassembled
378    // section and keeps the assertions exact.
379
380    #[test]
381    fn reassembler_accumulates_multi_packet_section() {
382        // 200-byte section that spans two payload slices.
383        let body = vec![0xAAu8; 197];
384        let section = build_section(0x02, &body);
385        assert_eq!(section.len(), 200);
386
387        let first_chunk = 100;
388        let payload1 = build_pusi_payload(0, &[], &section[..first_chunk]);
389        let payload2 = section[first_chunk..].to_vec();
390
391        let mut reasm = SectionReassembler::default();
392        reasm.feed(&payload1, true);
393        reasm.feed(&payload2, false);
394
395        let out = reasm.pop_section().expect("section should be ready");
396        assert_eq!(out.len(), 200);
397        assert_eq!(out.as_ref(), &section[..]);
398    }
399
400    #[test]
401    fn reassembler_yields_complete_section_once_length_satisfied() {
402        // 1-byte-body section: table_id=0x42, section_length=1, total=4 bytes.
403        let section = build_section(0x42, &[0xAA]);
404        assert_eq!(section.len(), 4);
405        let payload = build_pusi_payload(0, &[], &section);
406
407        let mut reasm = SectionReassembler::default();
408        reasm.feed(&payload, true);
409
410        let out = reasm
411            .pop_section()
412            .expect("single-packet section should pop");
413        assert_eq!(out.as_ref(), &section[..]);
414    }
415
416    #[test]
417    fn reassembler_extracts_all_concatenated_sections_in_one_payload() {
418        // Issue #29: a single PUSI payload packing three complete short
419        // sections after the pointer_field. All three must be queued — the
420        // old `feed` stopped after the first and the rest were silently lost
421        // (the CAS/EMM data-loss bug: SHARED EMMs landing as the 2nd+ section).
422        let s1 = build_section(0x42, &[0x11, 0x22]); // 5 bytes
423        let s2 = build_section(0x46, &[0x33]); // 4 bytes
424        let s3 = build_section(0x4A, &[0x44, 0x55, 0x66]); // 6 bytes
425
426        let mut concat = Vec::new();
427        concat.extend_from_slice(&s1);
428        concat.extend_from_slice(&s2);
429        concat.extend_from_slice(&s3);
430        let payload = build_pusi_payload(0, &[], &concat);
431
432        let mut reasm = SectionReassembler::default();
433        reasm.feed(&payload, true);
434
435        // Consumers must drain with a loop, not a single `if let`.
436        let got: Vec<_> = std::iter::from_fn(|| reasm.pop_section()).collect();
437        assert_eq!(got.len(), 3, "all three concatenated sections must pop");
438        assert_eq!(got[0].as_ref(), &s1[..]);
439        assert_eq!(got[1].as_ref(), &s2[..]);
440        assert_eq!(got[2].as_ref(), &s3[..]);
441    }
442
443    #[test]
444    fn reassembler_stops_at_stuffing_after_concatenated_sections() {
445        // Two sections then 0xFF stuffing fill — the stuffing must not be
446        // mistaken for a section header (0xFF table_id) nor leak into a
447        // section; both real sections still pop.
448        let s1 = build_section(0x42, &[0xAA]); // 4 bytes
449        let s2 = build_section(0x46, &[0xBB, 0xCC]); // 5 bytes
450        let mut concat = Vec::new();
451        concat.extend_from_slice(&s1);
452        concat.extend_from_slice(&s2);
453        concat.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]); // stuffing tail
454        let payload = build_pusi_payload(0, &[], &concat);
455
456        let mut reasm = SectionReassembler::default();
457        reasm.feed(&payload, true);
458
459        let got: Vec<_> = std::iter::from_fn(|| reasm.pop_section()).collect();
460        assert_eq!(got.len(), 2);
461        assert_eq!(got[0].as_ref(), &s1[..]);
462        assert_eq!(got[1].as_ref(), &s2[..]);
463        assert!(
464            reasm.is_empty(),
465            "stuffing tail must be discarded, not buffered"
466        );
467    }
468
469    #[test]
470    fn reassembler_concatenated_then_spanning_tail() {
471        // One complete section followed by the head of a second that spans
472        // into a continuation packet: first pops immediately, second pops
473        // once the continuation arrives.
474        let s1 = build_section(0x42, &[0x01, 0x02]); // 5 bytes
475        let s2 = build_section(0x46, &[0x09u8; 60]); // 63 bytes
476        let split = 30;
477
478        let mut head = Vec::new();
479        head.extend_from_slice(&s1);
480        head.extend_from_slice(&s2[..split]);
481        let payload1 = build_pusi_payload(0, &[], &head);
482        let payload2 = s2[split..].to_vec();
483
484        let mut reasm = SectionReassembler::default();
485        reasm.feed(&payload1, true);
486        let first = reasm.pop_section().expect("first section pops at once");
487        assert_eq!(first.as_ref(), &s1[..]);
488        assert!(reasm.pop_section().is_none(), "second is still partial");
489
490        reasm.feed(&payload2, false);
491        let second = reasm.pop_section().expect("second pops after continuation");
492        assert_eq!(second.as_ref(), &s2[..]);
493    }
494
495    #[test]
496    fn reassembler_discards_on_buffer_overflow() {
497        // Declare section_length larger than a single payload can carry. No
498        // pop happens until continuations arrive; if continuations push the
499        // buffer past MAX_SECTION_SIZE the reassembler must reset, not panic.
500        let mut section = Vec::with_capacity(3 + 4095);
501        section.push(0x00); // table_id
502        section.push(0xB0 | ((4095u16 >> 8) as u8 & 0x0F));
503        section.push(0xFF);
504        section.extend_from_slice(&[0u8; 160]);
505        let payload1 = build_pusi_payload(0, &[], &section);
506
507        let mut reasm = SectionReassembler::default();
508        reasm.feed(&payload1, true);
509        assert!(reasm.pop_section().is_none());
510
511        // Push enough continuation data to cross MAX_SECTION_SIZE.
512        let filler = vec![0u8; 180];
513        for _ in 0..(MAX_SECTION_SIZE / 180 + 1) {
514            reasm.feed(&filler, false);
515        }
516        assert!(
517            reasm.pop_section().is_none(),
518            "no section should pop after overflow reset"
519        );
520
521        // State must be resettable — a fresh valid PUSI section works.
522        let valid_section = build_section(0x00, &[0xAA]);
523        let payload2 = build_pusi_payload(0, &[], &valid_section);
524        reasm.feed(&payload2, true);
525        let out = reasm
526            .pop_section()
527            .expect("fresh section should pop after reset");
528        assert_eq!(out.as_ref(), &valid_section[..]);
529    }
530
531    #[test]
532    fn reassembler_handles_pusi_with_nonzero_pointer_field() {
533        // payload = pointer_field=3, 3 bytes of prior-section tail, then new section.
534        let prior_tail = vec![0x11, 0x22, 0x33];
535        let new_section = build_section(0x02, &[0xBB]);
536        assert_eq!(new_section.len(), 4);
537        let payload = build_pusi_payload(3, &prior_tail, &new_section);
538
539        let mut reasm = SectionReassembler::default();
540        reasm.feed(&payload, true);
541
542        let out = reasm
543            .pop_section()
544            .expect("section after pointer_field skip should pop");
545        assert_eq!(out.as_ref(), &new_section[..]);
546    }
547
548    #[test]
549    fn reassembler_ignores_continuation_before_pusi() {
550        // Feed a non-PUSI payload first (no prior PUSI seen).
551        // SectionReassembler should discard it and stay empty.
552        let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA, 0xBB, 0xCC]);
553
554        let mut reasm = SectionReassembler::default();
555        reasm.feed(&pkt[4..], false); // no PUSI
556
557        assert!(
558            reasm.pop_section().is_none(),
559            "no section should appear without prior PUSI"
560        );
561        assert!(
562            reasm.pop_section().is_none(),
563            "second pop should also be none"
564        );
565    }
566
567    /// A PUSI packet with an empty payload (adaptation field ate the body)
568    /// is malformed but must not panic — it drops sync.
569    #[test]
570    fn reassembler_empty_pusi_payload_does_not_panic() {
571        let mut reasm = SectionReassembler::default();
572        reasm.feed(&[], true);
573        assert!(reasm.pop_section().is_none());
574        // Recovers on the next clean PUSI.
575        let mut payload = vec![0x00u8, 0x72, 0x70, 0x01, 0x00];
576        payload.resize(5, 0);
577        reasm.feed(&payload, true);
578        assert!(reasm.pop_section().is_some());
579    }
580
581    /// A maximal short-form private section (section_length 0xFFF, total
582    /// 4098 bytes) reassembles — the ceiling is 12-bit length + 3-byte
583    /// header, not 4096.
584    #[test]
585    fn reassembler_accepts_maximal_private_section() {
586        let mut section = vec![0x80u8, 0x7F, 0xFF]; // user-private tid, SSI=0, len 0xFFF
587        section.resize(3 + 0xFFF, 0xAB);
588
589        let mut reasm = SectionReassembler::default();
590        // First TS payload: pointer_field 0 then the section start.
591        let mut first = vec![0x00];
592        first.extend_from_slice(&section[..183]);
593        reasm.feed(&first, true);
594        for chunk in section[183..].chunks(184) {
595            reasm.feed(chunk, false);
596        }
597        let out = reasm.pop_section().expect("4098-byte section should pop");
598        assert_eq!(out.len(), 4098);
599        assert_eq!(out.as_ref(), &section[..]);
600    }
601}