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