1use crate::descriptors::DescriptorLoop;
8use crate::error::{Error, Result};
9use crate::traits::Table;
10use dvb_common::{Parse, Serialize};
11
12pub const TABLE_ID: u8 = 0x02;
14pub const PID: u16 = 0x0000;
17
18const MIN_HEADER_LEN: usize = 3;
19const EXTENSION_HEADER_LEN: usize = 5;
20const PCR_PID_LEN: usize = 2;
21const PROG_INFO_LEN_BYTES: usize = 2;
22const CRC_LEN: usize = 4;
23const STREAM_HEADER_LEN: usize = 5;
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize))]
28#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
29pub struct PmtStream<'a> {
30 pub stream_type: u8,
32 pub elementary_pid: u16,
34 pub es_info: DescriptorLoop<'a>,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize))]
43#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
44pub struct Pmt<'a> {
45 pub program_number: u16,
47 pub version_number: u8,
49 pub current_next_indicator: bool,
51 pub pcr_pid: u16,
53 pub program_info: DescriptorLoop<'a>,
57 pub streams: Vec<PmtStream<'a>>,
59}
60
61impl<'a> Parse<'a> for Pmt<'a> {
62 type Error = crate::error::Error;
63 fn parse(bytes: &'a [u8]) -> Result<Self> {
64 let min_len =
65 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + PCR_PID_LEN + PROG_INFO_LEN_BYTES + CRC_LEN;
66 if bytes.len() < min_len {
67 return Err(Error::BufferTooShort {
68 need: min_len,
69 have: bytes.len(),
70 what: "Pmt",
71 });
72 }
73 if bytes[0] != TABLE_ID {
74 return Err(Error::UnexpectedTableId {
75 table_id: bytes[0],
76 what: "Pmt",
77 expected: &[TABLE_ID],
78 });
79 }
80
81 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
82 let total = MIN_HEADER_LEN + section_length as usize;
83 if bytes.len() < total {
84 return Err(Error::SectionLengthOverflow {
85 declared: section_length as usize,
86 available: bytes.len() - MIN_HEADER_LEN,
87 });
88 }
89
90 let program_number = u16::from_be_bytes([bytes[3], bytes[4]]);
91 let version_number = (bytes[5] >> 1) & 0x1F;
92 let current_next_indicator = (bytes[5] & 0x01) != 0;
93
94 let pcr_pid = (((bytes[8] & 0x1F) as u16) << 8) | bytes[9] as u16;
95 let program_info_length = (((bytes[10] & 0x0F) as usize) << 8) | bytes[11] as usize;
96
97 let prog_info_start =
98 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + PCR_PID_LEN + PROG_INFO_LEN_BYTES;
99 let prog_info_end = prog_info_start + program_info_length;
100 let stream_loop_end = total - CRC_LEN;
101 if prog_info_end > stream_loop_end {
102 return Err(Error::SectionLengthOverflow {
103 declared: program_info_length,
104 available: stream_loop_end - prog_info_start,
105 });
106 }
107 let program_info = DescriptorLoop::new(&bytes[prog_info_start..prog_info_end]);
108
109 let mut streams = Vec::new();
110 let mut pos = prog_info_end;
111 while pos + STREAM_HEADER_LEN <= stream_loop_end {
112 let stream_type = bytes[pos];
113 let elementary_pid = (((bytes[pos + 1] & 0x1F) as u16) << 8) | bytes[pos + 2] as u16;
114 let es_info_length =
115 (((bytes[pos + 3] & 0x0F) as usize) << 8) | bytes[pos + 4] as usize;
116 let es_start = pos + STREAM_HEADER_LEN;
117 let es_end = es_start + es_info_length;
118 if es_end > stream_loop_end {
119 return Err(Error::SectionLengthOverflow {
120 declared: es_info_length,
121 available: stream_loop_end - es_start,
122 });
123 }
124 streams.push(PmtStream {
125 stream_type,
126 elementary_pid,
127 es_info: DescriptorLoop::new(&bytes[es_start..es_end]),
128 });
129 pos = es_end;
130 }
131
132 Ok(Pmt {
133 program_number,
134 version_number,
135 current_next_indicator,
136 pcr_pid,
137 program_info,
138 streams,
139 })
140 }
141}
142
143impl Serialize for Pmt<'_> {
144 type Error = crate::error::Error;
145 fn serialized_len(&self) -> usize {
146 let streams_bytes: usize = self
147 .streams
148 .iter()
149 .map(|s| STREAM_HEADER_LEN + s.es_info.len())
150 .sum();
151 MIN_HEADER_LEN
152 + EXTENSION_HEADER_LEN
153 + PCR_PID_LEN
154 + PROG_INFO_LEN_BYTES
155 + self.program_info.len()
156 + streams_bytes
157 + CRC_LEN
158 }
159
160 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
161 let len = self.serialized_len();
162 if buf.len() < len {
163 return Err(Error::OutputBufferTooSmall {
164 need: len,
165 have: buf.len(),
166 });
167 }
168
169 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
170 buf[0] = TABLE_ID;
171 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
172 buf[2] = (section_length & 0xFF) as u8;
173 buf[3..5].copy_from_slice(&self.program_number.to_be_bytes());
174 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
175 buf[6] = 0;
176 buf[7] = 0;
177 buf[8] = 0xE0 | ((self.pcr_pid >> 8) as u8 & 0x1F);
178 buf[9] = (self.pcr_pid & 0xFF) as u8;
179 let pil = self.program_info.len() as u16;
180 buf[10] = 0xF0 | ((pil >> 8) as u8 & 0x0F);
181 buf[11] = (pil & 0xFF) as u8;
182
183 let prog_info_start =
184 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + PCR_PID_LEN + PROG_INFO_LEN_BYTES;
185 buf[prog_info_start..prog_info_start + self.program_info.len()]
186 .copy_from_slice(self.program_info.raw());
187
188 let mut pos = prog_info_start + self.program_info.len();
189 for stream in &self.streams {
190 buf[pos] = stream.stream_type;
191 buf[pos + 1] = 0xE0 | ((stream.elementary_pid >> 8) as u8 & 0x1F);
192 buf[pos + 2] = (stream.elementary_pid & 0xFF) as u8;
193 let esl = stream.es_info.len() as u16;
194 buf[pos + 3] = 0xF0 | ((esl >> 8) as u8 & 0x0F);
195 buf[pos + 4] = (esl & 0xFF) as u8;
196 let es_start = pos + STREAM_HEADER_LEN;
197 buf[es_start..es_start + stream.es_info.len()].copy_from_slice(stream.es_info.raw());
198 pos = es_start + stream.es_info.len();
199 }
200
201 let crc_pos = len - CRC_LEN;
202 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
203 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
204 Ok(len)
205 }
206}
207
208impl<'a> Table<'a> for Pmt<'a> {
209 const TABLE_ID: u8 = TABLE_ID;
210 const PID: u16 = PID;
211}
212
213impl<'a> crate::traits::TableDef<'a> for Pmt<'a> {
214 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
215 const NAME: &'static str = "PROGRAM_MAP";
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.raw(), &[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 &[(0x02, 0x102, vec![0x11, 0x22]), (0x1B, 0x103, vec![0x33])],
285 );
286 let pmt = Pmt::parse(&bytes).unwrap();
287 assert_eq!(pmt.streams.len(), 2);
288 assert_eq!(pmt.streams[0].stream_type, 0x02);
289 assert_eq!(pmt.streams[0].elementary_pid, 0x102);
290 assert_eq!(pmt.streams[0].es_info.raw(), &[0x11, 0x22]);
291 assert_eq!(pmt.streams[1].stream_type, 0x1B);
292 assert_eq!(pmt.streams[1].elementary_pid, 0x103);
293 assert_eq!(pmt.streams[1].es_info.raw(), &[0x33]);
294 }
295
296 #[test]
297 fn parse_rejects_wrong_table_id() {
298 let mut bytes = build_pmt(1, 0, 0x100, &[], &[]);
299 bytes[0] = 0x00;
300 let err = Pmt::parse(&bytes).unwrap_err();
301 assert!(matches!(
302 err,
303 Error::UnexpectedTableId { table_id: 0x00, .. }
304 ));
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: DescriptorLoop::new(&[]),
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: DescriptorLoop::new(&prog_info),
340 streams: vec![
341 PmtStream {
342 stream_type: 0x02,
343 elementary_pid: 0x100,
344 es_info: DescriptorLoop::new(&es1),
345 },
346 PmtStream {
347 stream_type: 0x03,
348 elementary_pid: 0x101,
349 es_info: DescriptorLoop::new(&es2),
350 },
351 PmtStream {
352 stream_type: 0x1B,
353 elementary_pid: 0x102,
354 es_info: DescriptorLoop::new(&[]),
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.raw(), &pi[..]);
377 }
378}