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