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