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 or one section (the queue is for future-proofing
197    /// where one feed might yield multiple sections).
198    pub fn feed(&mut self, payload: &[u8], pusi: bool) {
199        if pusi {
200            // A PUSI packet whose adaptation field consumed the whole body is
201            // malformed but constructible — drop sync rather than panic.
202            if payload.is_empty() {
203                self.buf.clear();
204                self.expected = 0;
205                return;
206            }
207            let pointer = payload[0] as usize;
208            let start = 1 + pointer;
209            if start >= payload.len() {
210                self.buf.clear();
211                return;
212            }
213            self.buf.clear();
214            let new_data = &payload[start..];
215            if self.buf.len() + new_data.len() > MAX_SECTION_SIZE {
216                self.buf.clear();
217                self.expected = 0;
218                return;
219            }
220            self.buf.extend_from_slice(new_data);
221            if self.buf.len() >= 3 {
222                self.expected = 3 + (((self.buf[1] & 0x0F) as usize) << 8 | self.buf[2] as usize);
223            }
224        } else {
225            if self.buf.is_empty() {
226                return;
227            }
228            if self.buf.len() + payload.len() > MAX_SECTION_SIZE {
229                self.buf.clear();
230                self.expected = 0;
231                return;
232            }
233            self.buf.extend_from_slice(payload);
234        }
235
236        if self.expected > 0 && self.buf.len() >= self.expected {
237            // split_to returns the first `expected` bytes as an owned BytesMut,
238            // leaving the remaining bytes in self.buf — cheap (shifts pointers).
239            let section = self.buf.split_to(self.expected).freeze();
240            self.ready.push_back(section);
241            self.expected = 0;
242        }
243    }
244
245    /// Pop one complete section. Returns `None` when the queue is empty.
246    pub fn pop_section(&mut self) -> Option<bytes::Bytes> {
247        self.ready.pop_front()
248    }
249
250    /// Number of bytes currently buffered (incomplete section).
251    pub fn len(&self) -> usize {
252        self.buf.len()
253    }
254
255    /// True if no bytes are currently buffered.
256    pub fn is_empty(&self) -> bool {
257        self.buf.is_empty()
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    /// Helper: construct a minimal 188-byte TS packet buffer with given header flags and payload.
266    fn make_packet(b1: u8, b2: u8, b3: u8, payload_data: &[u8]) -> [u8; TS_PACKET_SIZE] {
267        let mut pkt = [0u8; TS_PACKET_SIZE];
268        pkt[0] = TS_SYNC_BYTE;
269        pkt[1] = b1;
270        pkt[2] = b2;
271        pkt[3] = b3;
272        let payload_start = 4;
273        let end = (payload_start + payload_data.len()).min(TS_PACKET_SIZE);
274        let len = (end - payload_start).min(payload_data.len());
275        pkt[payload_start..payload_start + len].copy_from_slice(&payload_data[..len]);
276        pkt
277    }
278
279    #[test]
280    fn parse_rejects_non_0x47_sync_byte() {
281        let mut pkt = [0u8; TS_PACKET_SIZE];
282        pkt[0] = 0x46; // wrong sync byte
283        let err = TsPacket::parse(&pkt).unwrap_err();
284        match err {
285            Error::InvalidSyncByte { found } => assert_eq!(found, 0x46),
286            other => panic!("expected InvalidSyncByte, got {other:?}"),
287        }
288    }
289
290    #[test]
291    fn parse_extracts_pid_and_continuity_counter() {
292        // PID = 0x1234 → upper 5 bits = 0x12, lower 8 bits = 0x34
293        // CC = 5 → 0x05
294        // b1 = 0x47 (sync=0, tei=0, pusi=0) | (0x12) = 0x47 & 0xE0 | 0x12 = 0x47 & 0xE0 = 0x40 | 0x12 = 0x52
295        // Actually: b1 bits: [tei:1][pusi:1][pid_hi:5]
296        // pid_hi = 0x12 = 0b00100_10 → bits 5..=1 = 0x12
297        // b1 = 0b00_010010 = 0x12 (no tei, no pusi)
298        let pkt = make_packet(0x12, 0x34, 0x05, &[]);
299        let pkt = TsPacket::parse(&pkt).unwrap();
300        assert_eq!(pkt.header.pid, 0x1234);
301        assert_eq!(pkt.header.continuity_counter, 5);
302    }
303
304    #[test]
305    fn payload_unit_start_indicator_flag_extracted() {
306        // b1 = 0x40 → pusi = true (bit 6 set, no tei, no pid bits)
307        let pkt1 = make_packet(0x40, 0x00, 0x00, &[]);
308        let pkt1 = TsPacket::parse(&pkt1).unwrap();
309        assert!(pkt1.header.pusi);
310
311        // b1 = 0x00 → pusi = false
312        let pkt2 = make_packet(0x00, 0x00, 0x00, &[]);
313        let pkt2 = TsPacket::parse(&pkt2).unwrap();
314        assert!(!pkt2.header.pusi);
315    }
316
317    /// Build a PSI-carrying TS payload: `pointer_field` byte followed by
318    /// (optionally) some tail of a previous section, followed by a fresh
319    /// section. `pointer_field` is the number of bytes of the previous
320    /// section that precede the new one (per ETSI EN 300 468 §5.1.4).
321    fn build_pusi_payload(pointer_field: u8, previous_tail: &[u8], section: &[u8]) -> Vec<u8> {
322        assert_eq!(pointer_field as usize, previous_tail.len());
323        let mut v = Vec::with_capacity(1 + previous_tail.len() + section.len());
324        v.push(pointer_field);
325        v.extend_from_slice(previous_tail);
326        v.extend_from_slice(section);
327        v
328    }
329
330    /// Build a long-form section with the given table_id and body bytes.
331    /// Returns the full section including its 3-byte + 5-byte header and a
332    /// placeholder CRC — for reassembler testing we don't validate the CRC.
333    fn build_section(table_id: u8, body_after_length: &[u8]) -> Vec<u8> {
334        let section_length = body_after_length.len() as u16;
335        let mut v = Vec::with_capacity(3 + section_length as usize);
336        v.push(table_id);
337        // ssi=1, pi=0, reserved=11, length hi 4 bits
338        v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
339        v.push((section_length & 0xFF) as u8);
340        v.extend_from_slice(body_after_length);
341        v
342    }
343
344    // The reassembler tests below feed raw payload slices directly to
345    // `feed()` rather than wrapping them in 188-byte TS packets. This avoids
346    // the TS stuffing-byte tail (0xFF padding) bleeding into the reassembled
347    // section and keeps the assertions exact.
348
349    #[test]
350    fn reassembler_accumulates_multi_packet_section() {
351        // 200-byte section that spans two payload slices.
352        let body = vec![0xAAu8; 197];
353        let section = build_section(0x02, &body);
354        assert_eq!(section.len(), 200);
355
356        let first_chunk = 100;
357        let payload1 = build_pusi_payload(0, &[], &section[..first_chunk]);
358        let payload2 = section[first_chunk..].to_vec();
359
360        let mut reasm = SectionReassembler::default();
361        reasm.feed(&payload1, true);
362        reasm.feed(&payload2, false);
363
364        let out = reasm.pop_section().expect("section should be ready");
365        assert_eq!(out.len(), 200);
366        assert_eq!(out.as_ref(), &section[..]);
367    }
368
369    #[test]
370    fn reassembler_yields_complete_section_once_length_satisfied() {
371        // 1-byte-body section: table_id=0x42, section_length=1, total=4 bytes.
372        let section = build_section(0x42, &[0xAA]);
373        assert_eq!(section.len(), 4);
374        let payload = build_pusi_payload(0, &[], &section);
375
376        let mut reasm = SectionReassembler::default();
377        reasm.feed(&payload, true);
378
379        let out = reasm
380            .pop_section()
381            .expect("single-packet section should pop");
382        assert_eq!(out.as_ref(), &section[..]);
383    }
384
385    #[test]
386    fn reassembler_discards_on_buffer_overflow() {
387        // Declare section_length larger than a single payload can carry. No
388        // pop happens until continuations arrive; if continuations push the
389        // buffer past MAX_SECTION_SIZE the reassembler must reset, not panic.
390        let mut section = Vec::with_capacity(3 + 4095);
391        section.push(0x00); // table_id
392        section.push(0xB0 | ((4095u16 >> 8) as u8 & 0x0F));
393        section.push(0xFF);
394        section.extend_from_slice(&[0u8; 160]);
395        let payload1 = build_pusi_payload(0, &[], &section);
396
397        let mut reasm = SectionReassembler::default();
398        reasm.feed(&payload1, true);
399        assert!(reasm.pop_section().is_none());
400
401        // Push enough continuation data to cross MAX_SECTION_SIZE.
402        let filler = vec![0u8; 180];
403        for _ in 0..(MAX_SECTION_SIZE / 180 + 1) {
404            reasm.feed(&filler, false);
405        }
406        assert!(
407            reasm.pop_section().is_none(),
408            "no section should pop after overflow reset"
409        );
410
411        // State must be resettable — a fresh valid PUSI section works.
412        let valid_section = build_section(0x00, &[0xAA]);
413        let payload2 = build_pusi_payload(0, &[], &valid_section);
414        reasm.feed(&payload2, true);
415        let out = reasm
416            .pop_section()
417            .expect("fresh section should pop after reset");
418        assert_eq!(out.as_ref(), &valid_section[..]);
419    }
420
421    #[test]
422    fn reassembler_handles_pusi_with_nonzero_pointer_field() {
423        // payload = pointer_field=3, 3 bytes of prior-section tail, then new section.
424        let prior_tail = vec![0x11, 0x22, 0x33];
425        let new_section = build_section(0x02, &[0xBB]);
426        assert_eq!(new_section.len(), 4);
427        let payload = build_pusi_payload(3, &prior_tail, &new_section);
428
429        let mut reasm = SectionReassembler::default();
430        reasm.feed(&payload, true);
431
432        let out = reasm
433            .pop_section()
434            .expect("section after pointer_field skip should pop");
435        assert_eq!(out.as_ref(), &new_section[..]);
436    }
437
438    #[test]
439    fn reassembler_ignores_continuation_before_pusi() {
440        // Feed a non-PUSI payload first (no prior PUSI seen).
441        // SectionReassembler should discard it and stay empty.
442        let pkt = make_packet(0x00, 0x00, PAYLOAD_FLAG, &[0xAA, 0xBB, 0xCC]);
443
444        let mut reasm = SectionReassembler::default();
445        reasm.feed(&pkt[4..], false); // no PUSI
446
447        assert!(
448            reasm.pop_section().is_none(),
449            "no section should appear without prior PUSI"
450        );
451        assert!(
452            reasm.pop_section().is_none(),
453            "second pop should also be none"
454        );
455    }
456
457    /// A PUSI packet with an empty payload (adaptation field ate the body)
458    /// is malformed but must not panic — it drops sync.
459    #[test]
460    fn reassembler_empty_pusi_payload_does_not_panic() {
461        let mut reasm = SectionReassembler::default();
462        reasm.feed(&[], true);
463        assert!(reasm.pop_section().is_none());
464        // Recovers on the next clean PUSI.
465        let mut payload = vec![0x00u8, 0x72, 0x70, 0x01, 0x00];
466        payload.resize(5, 0);
467        reasm.feed(&payload, true);
468        assert!(reasm.pop_section().is_some());
469    }
470
471    /// A maximal short-form private section (section_length 0xFFF, total
472    /// 4098 bytes) reassembles — the ceiling is 12-bit length + 3-byte
473    /// header, not 4096.
474    #[test]
475    fn reassembler_accepts_maximal_private_section() {
476        let mut section = vec![0x80u8, 0x7F, 0xFF]; // user-private tid, SSI=0, len 0xFFF
477        section.resize(3 + 0xFFF, 0xAB);
478
479        let mut reasm = SectionReassembler::default();
480        // First TS payload: pointer_field 0 then the section start.
481        let mut first = vec![0x00];
482        first.extend_from_slice(&section[..183]);
483        reasm.feed(&first, true);
484        for chunk in section[183..].chunks(184) {
485            reasm.feed(chunk, false);
486        }
487        let out = reasm.pop_section().expect("4098-byte section should pop");
488        assert_eq!(out.len(), 4098);
489        assert_eq!(out.as_ref(), &section[..]);
490    }
491}