1use crate::error::{Error, Result};
8use crate::traits::Table;
9use dvb_common::{Parse, Serialize};
10
11pub const TABLE_ID: u8 = 0x02;
13pub const PID: u16 = 0x0000;
16
17const MIN_HEADER_LEN: usize = 3;
18const EXTENSION_HEADER_LEN: usize = 5;
19const PCR_PID_LEN: usize = 2;
20const PROG_INFO_LEN_BYTES: usize = 2;
21const CRC_LEN: usize = 4;
22const STREAM_HEADER_LEN: usize = 5;
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct PmtStream<'a> {
28 pub stream_type: u8,
30 pub elementary_pid: u16,
32 #[cfg_attr(feature = "serde", serde(borrow))]
34 pub es_info: &'a [u8],
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub struct Pmt<'a> {
41 pub program_number: u16,
43 pub version_number: u8,
45 pub current_next_indicator: bool,
47 pub pcr_pid: u16,
49 #[cfg_attr(feature = "serde", serde(borrow))]
51 pub program_info: &'a [u8],
52 #[cfg_attr(feature = "serde", serde(borrow))]
54 pub streams: Vec<PmtStream<'a>>,
55}
56
57impl<'a> Parse<'a> for Pmt<'a> {
58 type Error = crate::error::Error;
59 fn parse(bytes: &'a [u8]) -> Result<Self> {
60 let min_len =
61 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + PCR_PID_LEN + PROG_INFO_LEN_BYTES + CRC_LEN;
62 if bytes.len() < min_len {
63 return Err(Error::BufferTooShort {
64 need: min_len,
65 have: bytes.len(),
66 what: "Pmt",
67 });
68 }
69 if bytes[0] != TABLE_ID {
70 return Err(Error::UnexpectedTableId {
71 table_id: bytes[0],
72 what: "Pmt",
73 expected: &[TABLE_ID],
74 });
75 }
76
77 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
78 let total = MIN_HEADER_LEN + section_length as usize;
79 if bytes.len() < total {
80 return Err(Error::SectionLengthOverflow {
81 declared: section_length as usize,
82 available: bytes.len() - MIN_HEADER_LEN,
83 });
84 }
85
86 let program_number = u16::from_be_bytes([bytes[3], bytes[4]]);
87 let version_number = (bytes[5] >> 1) & 0x1F;
88 let current_next_indicator = (bytes[5] & 0x01) != 0;
89
90 let pcr_pid = (((bytes[8] & 0x1F) as u16) << 8) | bytes[9] as u16;
91 let program_info_length = (((bytes[10] & 0x0F) as usize) << 8) | bytes[11] as usize;
92
93 let prog_info_start =
94 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + PCR_PID_LEN + PROG_INFO_LEN_BYTES;
95 let prog_info_end = prog_info_start + program_info_length;
96 let stream_loop_end = total - CRC_LEN;
97 if prog_info_end > stream_loop_end {
98 return Err(Error::SectionLengthOverflow {
99 declared: program_info_length,
100 available: stream_loop_end - prog_info_start,
101 });
102 }
103 let program_info = &bytes[prog_info_start..prog_info_end];
104
105 let mut streams = Vec::new();
106 let mut pos = prog_info_end;
107 while pos + STREAM_HEADER_LEN <= stream_loop_end {
108 let stream_type = bytes[pos];
109 let elementary_pid = (((bytes[pos + 1] & 0x1F) as u16) << 8) | bytes[pos + 2] as u16;
110 let es_info_length =
111 (((bytes[pos + 3] & 0x0F) as usize) << 8) | bytes[pos + 4] as usize;
112 let es_start = pos + STREAM_HEADER_LEN;
113 let es_end = es_start + es_info_length;
114 if es_end > stream_loop_end {
115 return Err(Error::SectionLengthOverflow {
116 declared: es_info_length,
117 available: stream_loop_end - es_start,
118 });
119 }
120 streams.push(PmtStream {
121 stream_type,
122 elementary_pid,
123 es_info: &bytes[es_start..es_end],
124 });
125 pos = es_end;
126 }
127
128 Ok(Pmt {
129 program_number,
130 version_number,
131 current_next_indicator,
132 pcr_pid,
133 program_info,
134 streams,
135 })
136 }
137}
138
139impl Serialize for Pmt<'_> {
140 type Error = crate::error::Error;
141 fn serialized_len(&self) -> usize {
142 let streams_bytes: usize = self
143 .streams
144 .iter()
145 .map(|s| STREAM_HEADER_LEN + s.es_info.len())
146 .sum();
147 MIN_HEADER_LEN
148 + EXTENSION_HEADER_LEN
149 + PCR_PID_LEN
150 + PROG_INFO_LEN_BYTES
151 + self.program_info.len()
152 + streams_bytes
153 + CRC_LEN
154 }
155
156 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
157 let len = self.serialized_len();
158 if buf.len() < len {
159 return Err(Error::OutputBufferTooSmall {
160 need: len,
161 have: buf.len(),
162 });
163 }
164
165 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
166 buf[0] = TABLE_ID;
167 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
168 buf[2] = (section_length & 0xFF) as u8;
169 buf[3..5].copy_from_slice(&self.program_number.to_be_bytes());
170 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
171 buf[6] = 0;
172 buf[7] = 0;
173 buf[8] = 0xE0 | ((self.pcr_pid >> 8) as u8 & 0x1F);
174 buf[9] = (self.pcr_pid & 0xFF) as u8;
175 let pil = self.program_info.len() as u16;
176 buf[10] = 0xF0 | ((pil >> 8) as u8 & 0x0F);
177 buf[11] = (pil & 0xFF) as u8;
178
179 let prog_info_start =
180 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + PCR_PID_LEN + PROG_INFO_LEN_BYTES;
181 buf[prog_info_start..prog_info_start + self.program_info.len()]
182 .copy_from_slice(self.program_info);
183
184 let mut pos = prog_info_start + self.program_info.len();
185 for stream in &self.streams {
186 buf[pos] = stream.stream_type;
187 buf[pos + 1] = 0xE0 | ((stream.elementary_pid >> 8) as u8 & 0x1F);
188 buf[pos + 2] = (stream.elementary_pid & 0xFF) as u8;
189 let esl = stream.es_info.len() as u16;
190 buf[pos + 3] = 0xF0 | ((esl >> 8) as u8 & 0x0F);
191 buf[pos + 4] = (esl & 0xFF) as u8;
192 let es_start = pos + STREAM_HEADER_LEN;
193 buf[es_start..es_start + stream.es_info.len()].copy_from_slice(stream.es_info);
194 pos = es_start + stream.es_info.len();
195 }
196
197 let crc_pos = len - CRC_LEN;
198 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
199 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
200 Ok(len)
201 }
202}
203
204impl<'a> Table<'a> for Pmt<'a> {
205 const TABLE_ID: u8 = TABLE_ID;
206 const PID: u16 = PID;
207}
208
209impl<'a> crate::traits::TableDef<'a> for Pmt<'a> {
210 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
211 const NAME: &'static str = "PROGRAM_MAP";
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 fn build_pmt(
220 program_number: u16,
221 version: u8,
222 pcr_pid: u16,
223 program_info: &[u8],
224 streams: &[(u8, u16, Vec<u8>)],
225 ) -> Vec<u8> {
226 let streams_bytes: usize = streams
227 .iter()
228 .map(|(_, _, es)| STREAM_HEADER_LEN + es.len())
229 .sum();
230 let section_length: u16 = (EXTENSION_HEADER_LEN
231 + PCR_PID_LEN
232 + PROG_INFO_LEN_BYTES
233 + program_info.len()
234 + streams_bytes
235 + CRC_LEN) as u16;
236 let mut v = Vec::new();
237 v.push(TABLE_ID);
238 v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
239 v.push((section_length & 0xFF) as u8);
240 v.extend_from_slice(&program_number.to_be_bytes());
241 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
242 v.push(0);
243 v.push(0);
244 v.push(0xE0 | ((pcr_pid >> 8) as u8 & 0x1F));
245 v.push((pcr_pid & 0xFF) as u8);
246 v.push(0xF0 | ((program_info.len() >> 8) as u8 & 0x0F));
247 v.push((program_info.len() & 0xFF) as u8);
248 v.extend_from_slice(program_info);
249 for (stype, pid, es) in streams {
250 v.push(*stype);
251 v.push(0xE0 | ((pid >> 8) as u8 & 0x1F));
252 v.push((pid & 0xFF) as u8);
253 v.push(0xF0 | ((es.len() >> 8) as u8 & 0x0F));
254 v.push((es.len() & 0xFF) as u8);
255 v.extend_from_slice(es);
256 }
257 v.extend_from_slice(&[0, 0, 0, 0]);
258 v
259 }
260
261 #[test]
262 fn parse_extracts_pcr_pid_and_program_info() {
263 let bytes = build_pmt(42, 5, 0x0100, &[0xAA, 0xBB], &[]);
264 let pmt = Pmt::parse(&bytes).unwrap();
265 assert_eq!(pmt.program_number, 42);
266 assert_eq!(pmt.version_number, 5);
267 assert!(pmt.current_next_indicator);
268 assert_eq!(pmt.pcr_pid, 0x0100);
269 assert_eq!(pmt.program_info, &[0xAA, 0xBB]);
270 assert_eq!(pmt.streams.len(), 0);
271 }
272
273 #[test]
274 fn parse_elementary_streams_and_es_info_slices() {
275 let bytes = build_pmt(
276 1,
277 0,
278 0x101,
279 &[],
280 &[(0x02, 0x102, vec![0x11, 0x22]), (0x1B, 0x103, vec![0x33])],
281 );
282 let pmt = Pmt::parse(&bytes).unwrap();
283 assert_eq!(pmt.streams.len(), 2);
284 assert_eq!(pmt.streams[0].stream_type, 0x02);
285 assert_eq!(pmt.streams[0].elementary_pid, 0x102);
286 assert_eq!(pmt.streams[0].es_info, &[0x11, 0x22]);
287 assert_eq!(pmt.streams[1].stream_type, 0x1B);
288 assert_eq!(pmt.streams[1].elementary_pid, 0x103);
289 assert_eq!(pmt.streams[1].es_info, &[0x33]);
290 }
291
292 #[test]
293 fn parse_rejects_wrong_table_id() {
294 let mut bytes = build_pmt(1, 0, 0x100, &[], &[]);
295 bytes[0] = 0x00;
296 let err = Pmt::parse(&bytes).unwrap_err();
297 assert!(matches!(
298 err,
299 Error::UnexpectedTableId { table_id: 0x00, .. }
300 ));
301 }
302
303 #[test]
304 fn parse_rejects_short_buffer() {
305 let err = Pmt::parse(&[0x02, 0x00]).unwrap_err();
306 assert!(matches!(err, Error::BufferTooShort { .. }));
307 }
308
309 #[test]
310 fn serialize_round_trip_empty_program() {
311 let pmt = Pmt {
312 program_number: 1,
313 version_number: 0,
314 current_next_indicator: true,
315 pcr_pid: 0x100,
316 program_info: &[],
317 streams: vec![],
318 };
319 let mut buf = vec![0u8; pmt.serialized_len()];
320 pmt.serialize_into(&mut buf).unwrap();
321 let re = Pmt::parse(&buf).unwrap();
322 assert_eq!(pmt, re);
323 }
324
325 #[test]
326 fn serialize_round_trip_with_streams_and_descriptors() {
327 let prog_info: [u8; 3] = [0x09, 0x01, 0xFF];
328 let es1: [u8; 4] = [0x52, 0x02, 0xAA, 0xBB];
329 let es2: [u8; 2] = [0x0A, 0x00];
330 let pmt = Pmt {
331 program_number: 0xABCD,
332 version_number: 7,
333 current_next_indicator: true,
334 pcr_pid: 0x1F0,
335 program_info: &prog_info,
336 streams: vec![
337 PmtStream {
338 stream_type: 0x02,
339 elementary_pid: 0x100,
340 es_info: &es1,
341 },
342 PmtStream {
343 stream_type: 0x03,
344 elementary_pid: 0x101,
345 es_info: &es2,
346 },
347 PmtStream {
348 stream_type: 0x1B,
349 elementary_pid: 0x102,
350 es_info: &[],
351 },
352 ],
353 };
354 let mut buf = vec![0u8; pmt.serialized_len()];
355 pmt.serialize_into(&mut buf).unwrap();
356 let re = Pmt::parse(&buf).unwrap();
357 assert_eq!(pmt, re);
358 }
359
360 #[test]
361 fn zero_elementary_streams_is_valid() {
362 let bytes = build_pmt(99, 0, 0x0100, &[], &[]);
363 let pmt = Pmt::parse(&bytes).unwrap();
364 assert_eq!(pmt.streams.len(), 0);
365 }
366
367 #[test]
368 fn parse_preserves_raw_program_info_bytes() {
369 let pi = vec![0x09, 0x04, 0x01, 0x02, 0x03, 0x04];
370 let bytes = build_pmt(1, 0, 0x100, &pi, &[]);
371 let pmt = Pmt::parse(&bytes).unwrap();
372 assert_eq!(pmt.program_info, &pi[..]);
373 }
374}