Skip to main content

dvb_si/tables/
pat.rs

1//! Program Association Table — MPEG-2 ISO/IEC 13818-1 §2.4.4.3.
2//!
3//! PAT is carried on PID 0x0000 with table_id 0x00. It maps
4//! program_number values to the PID on which their PMT is carried.
5//! program_number 0x0000 is special — its PID is the NIT PID.
6
7use crate::error::{Error, Result};
8use dvb_common::{Parse, Serialize};
9
10/// PAT table_id (ISO/IEC 13818-1 Table 2-30).
11pub const TABLE_ID: u8 = 0x00;
12/// PAT well-known PID.
13pub const PID: u16 = 0x0000;
14/// program_number value that carries the NIT PID rather than a PMT PID.
15pub const PROGRAM_NUMBER_NIT: u16 = 0x0000;
16
17const MIN_HEADER_LEN: usize = 3;
18const EXTENSION_HEADER_LEN: usize = 5;
19const CRC_LEN: usize = 4;
20const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;
21const ENTRY_LEN: usize = 4;
22
23/// One entry in the PAT program loop.
24#[derive(Debug, Clone, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize))]
26pub struct PatEntry {
27    /// program_number. 0x0000 means "next PID is the NIT PID".
28    pub program_number: u16,
29    /// PMT PID (or NIT PID when program_number == 0).
30    pub pid: u16,
31}
32
33/// Program Association Table.
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize))]
36pub struct PatSection {
37    /// transport_stream_id from the section header.
38    pub transport_stream_id: u16,
39    /// 5-bit version_number from the section header.
40    pub version_number: u8,
41    /// current_next_indicator bit.
42    pub current_next_indicator: bool,
43    /// section_number in the sub-table sequence.
44    pub section_number: u8,
45    /// last_section_number in the sub-table sequence.
46    pub last_section_number: u8,
47    /// Program entries in wire order.
48    pub entries: Vec<PatEntry>,
49}
50
51impl<'a> Parse<'a> for PatSection {
52    type Error = crate::error::Error;
53    fn parse(bytes: &'a [u8]) -> Result<Self> {
54        if bytes.len() < MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN {
55            return Err(Error::BufferTooShort {
56                need: MIN_HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN,
57                have: bytes.len(),
58                what: "PatSection",
59            });
60        }
61
62        if bytes[0] != TABLE_ID {
63            return Err(Error::UnexpectedTableId {
64                table_id: bytes[0],
65                what: "PatSection",
66                expected: &[TABLE_ID],
67            });
68        }
69
70        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
71        let total = super::check_section_length(
72            bytes.len(),
73            MIN_HEADER_LEN,
74            section_length as usize,
75            MIN_SECTION_LEN,
76        )?;
77
78        let transport_stream_id = u16::from_be_bytes([bytes[3], bytes[4]]);
79        let version_number = (bytes[5] >> 1) & 0x1F;
80        let current_next_indicator = (bytes[5] & 0x01) != 0;
81        let section_number = bytes[6];
82        let last_section_number = bytes[7];
83
84        let end = total - CRC_LEN;
85        let mut entries = Vec::new();
86        let mut pos = 8;
87        while pos < end {
88            if pos + ENTRY_LEN > end {
89                break;
90            }
91            let chunk = &bytes[pos..pos + ENTRY_LEN];
92            let program_number = u16::from_be_bytes([chunk[0], chunk[1]]);
93            let pid = (((chunk[2] & 0x1F) as u16) << 8) | chunk[3] as u16;
94            entries.push(PatEntry {
95                program_number,
96                pid,
97            });
98            pos += ENTRY_LEN;
99        }
100
101        Ok(PatSection {
102            transport_stream_id,
103            version_number,
104            current_next_indicator,
105            section_number,
106            last_section_number,
107            entries,
108        })
109    }
110}
111
112impl Serialize for PatSection {
113    type Error = crate::error::Error;
114    fn serialized_len(&self) -> usize {
115        MIN_HEADER_LEN + EXTENSION_HEADER_LEN + self.entries.len() * ENTRY_LEN + CRC_LEN
116    }
117
118    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
119        let len = self.serialized_len();
120        if buf.len() < len {
121            return Err(Error::OutputBufferTooSmall {
122                need: len,
123                have: buf.len(),
124            });
125        }
126
127        let section_length: u16 =
128            (EXTENSION_HEADER_LEN + self.entries.len() * ENTRY_LEN + CRC_LEN) as u16;
129
130        buf[0] = TABLE_ID;
131        buf[1] = super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F);
132        buf[2] = (section_length & 0xFF) as u8;
133        buf[3..5].copy_from_slice(&self.transport_stream_id.to_be_bytes());
134        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
135        buf[6] = self.section_number;
136        buf[7] = self.last_section_number;
137
138        let mut pos = 8;
139        for entry in &self.entries {
140            buf[pos..pos + 2].copy_from_slice(&entry.program_number.to_be_bytes());
141            buf[pos + 2] = 0xE0 | ((entry.pid >> 8) as u8 & 0x1F);
142            buf[pos + 3] = (entry.pid & 0xFF) as u8;
143            pos += ENTRY_LEN;
144        }
145
146        let crc_pos = len - CRC_LEN;
147        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
148        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
149
150        Ok(len)
151    }
152}
153impl<'a> crate::traits::TableDef<'a> for PatSection {
154    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
155    const NAME: &'static str = "PROGRAM_ASSOCIATION";
156}
157
158impl PatSection {
159    /// Program entries excluding the NIT entry.
160    pub fn programmes(&self) -> impl Iterator<Item = &PatEntry> {
161        self.entries
162            .iter()
163            .filter(|e| e.program_number != PROGRAM_NUMBER_NIT)
164    }
165
166    /// NIT PID if this PAT carries an entry with program_number == 0.
167    pub fn nit_pid(&self) -> Option<u16> {
168        self.entries
169            .iter()
170            .find(|e| e.program_number == PROGRAM_NUMBER_NIT)
171            .map(|e| e.pid)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    /// Build a PAT section with the given entries and a placeholder CRC.
180    fn build_pat(tsid: u16, version: u8, entries: &[(u16, u16)]) -> Vec<u8> {
181        let section_length: u16 =
182            (EXTENSION_HEADER_LEN + entries.len() * ENTRY_LEN + CRC_LEN) as u16;
183        let mut v = Vec::new();
184        v.push(TABLE_ID);
185        v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
186        v.push((section_length & 0xFF) as u8);
187        v.extend_from_slice(&tsid.to_be_bytes());
188        v.push(0xC0 | ((version & 0x1F) << 1) | 0x01); // version, cni=1
189        v.push(0x00); // section_number
190        v.push(0x00); // last_section_number
191        for &(pn, pid) in entries {
192            v.extend_from_slice(&pn.to_be_bytes());
193            v.push(0xE0 | ((pid >> 8) as u8 & 0x1F));
194            v.push((pid & 0xFF) as u8);
195        }
196        v.extend_from_slice(&[0, 0, 0, 0]); // placeholder CRC
197        v
198    }
199
200    #[test]
201    fn parse_empty_pat_zero_programs() {
202        let bytes = build_pat(0x1234, 5, &[]);
203        let pat = PatSection::parse(&bytes).expect("parse");
204        assert_eq!(pat.transport_stream_id, 0x1234);
205        assert_eq!(pat.version_number, 5);
206        assert!(pat.current_next_indicator);
207        assert_eq!(pat.section_number, 0);
208        assert_eq!(pat.last_section_number, 0);
209        assert_eq!(pat.entries.len(), 0);
210    }
211
212    #[test]
213    fn parse_single_program_extracts_pmt_pid() {
214        let bytes = build_pat(1, 0, &[(42, 0x1234)]);
215        let pat = PatSection::parse(&bytes).unwrap();
216        assert_eq!(pat.entries.len(), 1);
217        assert_eq!(pat.entries[0].program_number, 42);
218        assert_eq!(pat.entries[0].pid, 0x1234);
219    }
220
221    #[test]
222    fn parse_many_programs_preserves_order() {
223        let entries: Vec<(u16, u16)> = (1..=10).map(|i| (i, 0x1000 + i)).collect();
224        let bytes = build_pat(1, 0, &entries);
225        let pat = PatSection::parse(&bytes).unwrap();
226        assert_eq!(pat.entries.len(), 10);
227        for (i, e) in pat.entries.iter().enumerate() {
228            assert_eq!(e.program_number, (i + 1) as u16);
229            assert_eq!(e.pid, 0x1000 + (i + 1) as u16);
230        }
231    }
232
233    #[test]
234    fn parse_rejects_wrong_table_id() {
235        let mut bytes = build_pat(1, 0, &[]);
236        bytes[0] = 0x02; // PMT table_id
237        let err = PatSection::parse(&bytes).unwrap_err();
238        assert!(matches!(
239            err,
240            Error::UnexpectedTableId { table_id: 0x02, .. }
241        ));
242    }
243
244    #[test]
245    fn parse_rejects_short_buffer() {
246        let err = PatSection::parse(&[0x00, 0x00]).unwrap_err();
247        assert!(matches!(err, Error::BufferTooShort { .. }));
248    }
249
250    #[test]
251    fn serialize_round_trip_empty() {
252        let pat = PatSection {
253            transport_stream_id: 0x0001,
254            version_number: 0,
255            current_next_indicator: true,
256            section_number: 0,
257            last_section_number: 0,
258            entries: vec![],
259        };
260        let mut buf = vec![0u8; pat.serialized_len()];
261        pat.serialize_into(&mut buf).expect("serialize");
262        let reparsed = PatSection::parse(&buf).expect("reparse");
263        assert_eq!(pat, reparsed);
264    }
265
266    #[test]
267    fn serialize_round_trip_many_programs() {
268        let entries: Vec<PatEntry> = (1..=5)
269            .map(|i| PatEntry {
270                program_number: i,
271                pid: 0x1000 + i,
272            })
273            .collect();
274        let pat = PatSection {
275            transport_stream_id: 0xABCD,
276            version_number: 3,
277            current_next_indicator: true,
278            section_number: 0,
279            last_section_number: 0,
280            entries,
281        };
282        let mut buf = vec![0u8; pat.serialized_len()];
283        pat.serialize_into(&mut buf).unwrap();
284        let reparsed = PatSection::parse(&buf).unwrap();
285        assert_eq!(pat, reparsed);
286    }
287
288    #[test]
289    fn parse_rejects_zero_section_length() {
290        let mut buf = vec![0u8; 64];
291        buf[0] = TABLE_ID;
292        buf[1] = 0xB0;
293        buf[2] = 0x00;
294        for b in &mut buf[3..] {
295            *b = 0xFF;
296        }
297        assert!(matches!(
298            PatSection::parse(&buf).unwrap_err(),
299            Error::SectionLengthOverflow { .. }
300        ));
301    }
302
303    #[test]
304    fn network_pid_entry_identified_by_program_number_0() {
305        let bytes = build_pat(1, 0, &[(0, 0x0010), (1, 0x0100)]);
306        let pat = PatSection::parse(&bytes).unwrap();
307        assert_eq!(pat.nit_pid(), Some(0x0010));
308        assert_eq!(pat.programmes().count(), 1);
309        assert_eq!(pat.programmes().next().unwrap().program_number, 1);
310    }
311}