1use crate::descriptors::DescriptorLoop;
8use crate::error::{Error, Result};
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 MIN_SECTION_LEN: usize =
23 MIN_HEADER_LEN + EXTENSION_HEADER_LEN + PCR_PID_LEN + PROG_INFO_LEN_BYTES + CRC_LEN;
24const STREAM_HEADER_LEN: usize = 5;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize))]
29#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
30pub struct PmtStream<'a> {
31 pub stream_type: u8,
33 pub elementary_pid: u16,
35 pub es_info: DescriptorLoop<'a>,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43#[cfg_attr(feature = "serde", derive(serde::Serialize))]
44#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
45pub struct PmtSection<'a> {
46 pub program_number: u16,
48 pub version_number: u8,
50 pub current_next_indicator: bool,
52 pub pcr_pid: u16,
54 pub program_info: DescriptorLoop<'a>,
58 pub streams: Vec<PmtStream<'a>>,
60}
61
62impl<'a> Parse<'a> for PmtSection<'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: "PmtSection",
72 });
73 }
74 if bytes[0] != TABLE_ID {
75 return Err(Error::UnexpectedTableId {
76 table_id: bytes[0],
77 what: "PmtSection",
78 expected: &[TABLE_ID],
79 });
80 }
81
82 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
83 let total = super::check_section_length(
84 bytes.len(),
85 MIN_HEADER_LEN,
86 section_length as usize,
87 MIN_SECTION_LEN,
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.saturating_sub(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.saturating_sub(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(PmtSection {
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 PmtSection<'_> {
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] = super::SECTION_B1_FLAGS_PSI | ((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}
207impl<'a> crate::traits::TableDef<'a> for PmtSection<'a> {
208 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
209 const NAME: &'static str = "PROGRAM_MAP";
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 fn build_pmt(
218 program_number: u16,
219 version: u8,
220 pcr_pid: u16,
221 program_info: &[u8],
222 streams: &[(u8, u16, Vec<u8>)],
223 ) -> Vec<u8> {
224 let streams_bytes: usize = streams
225 .iter()
226 .map(|(_, _, es)| STREAM_HEADER_LEN + es.len())
227 .sum();
228 let section_length: u16 = (EXTENSION_HEADER_LEN
229 + PCR_PID_LEN
230 + PROG_INFO_LEN_BYTES
231 + program_info.len()
232 + streams_bytes
233 + CRC_LEN) as u16;
234 let mut v = Vec::new();
235 v.push(TABLE_ID);
236 v.push(super::super::SECTION_B1_FLAGS_PSI | ((section_length >> 8) as u8 & 0x0F));
237 v.push((section_length & 0xFF) as u8);
238 v.extend_from_slice(&program_number.to_be_bytes());
239 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
240 v.push(0);
241 v.push(0);
242 v.push(0xE0 | ((pcr_pid >> 8) as u8 & 0x1F));
243 v.push((pcr_pid & 0xFF) as u8);
244 v.push(0xF0 | ((program_info.len() >> 8) as u8 & 0x0F));
245 v.push((program_info.len() & 0xFF) as u8);
246 v.extend_from_slice(program_info);
247 for (stype, pid, es) in streams {
248 v.push(*stype);
249 v.push(0xE0 | ((pid >> 8) as u8 & 0x1F));
250 v.push((pid & 0xFF) as u8);
251 v.push(0xF0 | ((es.len() >> 8) as u8 & 0x0F));
252 v.push((es.len() & 0xFF) as u8);
253 v.extend_from_slice(es);
254 }
255 v.extend_from_slice(&[0, 0, 0, 0]);
256 v
257 }
258
259 #[test]
260 fn parse_extracts_pcr_pid_and_program_info() {
261 let bytes = build_pmt(42, 5, 0x0100, &[0xAA, 0xBB], &[]);
262 let pmt = PmtSection::parse(&bytes).unwrap();
263 assert_eq!(pmt.program_number, 42);
264 assert_eq!(pmt.version_number, 5);
265 assert!(pmt.current_next_indicator);
266 assert_eq!(pmt.pcr_pid, 0x0100);
267 assert_eq!(pmt.program_info.raw(), &[0xAA, 0xBB]);
268 assert_eq!(pmt.streams.len(), 0);
269 }
270
271 #[test]
272 fn parse_elementary_streams_and_es_info_slices() {
273 let bytes = build_pmt(
274 1,
275 0,
276 0x101,
277 &[],
278 &[(0x02, 0x102, vec![0x11, 0x22]), (0x1B, 0x103, vec![0x33])],
279 );
280 let pmt = PmtSection::parse(&bytes).unwrap();
281 assert_eq!(pmt.streams.len(), 2);
282 assert_eq!(pmt.streams[0].stream_type, 0x02);
283 assert_eq!(pmt.streams[0].elementary_pid, 0x102);
284 assert_eq!(pmt.streams[0].es_info.raw(), &[0x11, 0x22]);
285 assert_eq!(pmt.streams[1].stream_type, 0x1B);
286 assert_eq!(pmt.streams[1].elementary_pid, 0x103);
287 assert_eq!(pmt.streams[1].es_info.raw(), &[0x33]);
288 }
289
290 #[test]
291 fn parse_rejects_wrong_table_id() {
292 let mut bytes = build_pmt(1, 0, 0x100, &[], &[]);
293 bytes[0] = 0x00;
294 let err = PmtSection::parse(&bytes).unwrap_err();
295 assert!(matches!(
296 err,
297 Error::UnexpectedTableId { table_id: 0x00, .. }
298 ));
299 }
300
301 #[test]
302 fn parse_rejects_short_buffer() {
303 let err = PmtSection::parse(&[0x02, 0x00]).unwrap_err();
304 assert!(matches!(err, Error::BufferTooShort { .. }));
305 }
306
307 #[test]
308 fn serialize_round_trip_empty_program() {
309 let pmt = PmtSection {
310 program_number: 1,
311 version_number: 0,
312 current_next_indicator: true,
313 pcr_pid: 0x100,
314 program_info: DescriptorLoop::new(&[]),
315 streams: vec![],
316 };
317 let mut buf = vec![0u8; pmt.serialized_len()];
318 pmt.serialize_into(&mut buf).unwrap();
319 let re = PmtSection::parse(&buf).unwrap();
320 assert_eq!(pmt, re);
321 }
322
323 #[test]
324 fn serialize_round_trip_with_streams_and_descriptors() {
325 let prog_info: [u8; 3] = [0x09, 0x01, 0xFF];
326 let es1: [u8; 4] = [0x52, 0x02, 0xAA, 0xBB];
327 let es2: [u8; 2] = [0x0A, 0x00];
328 let pmt = PmtSection {
329 program_number: 0xABCD,
330 version_number: 7,
331 current_next_indicator: true,
332 pcr_pid: 0x1F0,
333 program_info: DescriptorLoop::new(&prog_info),
334 streams: vec![
335 PmtStream {
336 stream_type: 0x02,
337 elementary_pid: 0x100,
338 es_info: DescriptorLoop::new(&es1),
339 },
340 PmtStream {
341 stream_type: 0x03,
342 elementary_pid: 0x101,
343 es_info: DescriptorLoop::new(&es2),
344 },
345 PmtStream {
346 stream_type: 0x1B,
347 elementary_pid: 0x102,
348 es_info: DescriptorLoop::new(&[]),
349 },
350 ],
351 };
352 let mut buf = vec![0u8; pmt.serialized_len()];
353 pmt.serialize_into(&mut buf).unwrap();
354 let re = PmtSection::parse(&buf).unwrap();
355 assert_eq!(pmt, re);
356 }
357
358 #[test]
359 fn zero_elementary_streams_is_valid() {
360 let bytes = build_pmt(99, 0, 0x0100, &[], &[]);
361 let pmt = PmtSection::parse(&bytes).unwrap();
362 assert_eq!(pmt.streams.len(), 0);
363 }
364
365 #[test]
366 fn parse_preserves_raw_program_info_bytes() {
367 let pi = vec![0x09, 0x04, 0x01, 0x02, 0x03, 0x04];
368 let bytes = build_pmt(1, 0, 0x100, &pi, &[]);
369 let pmt = PmtSection::parse(&bytes).unwrap();
370 assert_eq!(pmt.program_info.raw(), &pi[..]);
371 }
372
373 #[test]
374 fn parse_rejects_zero_section_length() {
375 let mut buf = vec![0u8; 64];
376 buf[0] = TABLE_ID;
377 buf[1] = 0xF0;
378 buf[2] = 0x00;
379 for b in &mut buf[3..] {
380 *b = 0xFF;
381 }
382 assert!(matches!(
383 PmtSection::parse(&buf).unwrap_err(),
384 Error::SectionLengthOverflow { .. }
385 ));
386 }
387}