1use crate::descriptors::DescriptorLoop;
9use crate::error::{Error, Result};
10use alloc::string::String;
11use alloc::vec::Vec;
12use dvb_common::{Parse, Serialize};
13
14pub const TABLE_ID: u8 = 0x4A;
16pub const PID: u16 = 0x0011;
18pub const DESCRIPTOR_TAG_BOUQUET_NAME: u8 = 0x47;
20
21const MIN_HEADER_LEN: usize = 3;
22const EXTENSION_HEADER_LEN: usize = 5;
23const POST_EXTENSION_LEN: usize = 2;
25const CRC_LEN: usize = 4;
26const TS_HEADER_LEN: usize = 6;
28const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize))]
33#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
34pub struct BatTransportStream<'a> {
35 pub transport_stream_id: u16,
37 pub original_network_id: u16,
39 pub descriptors: DescriptorLoop<'a>,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize))]
48#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
49pub struct BatSection<'a> {
50 pub bouquet_id: u16,
52 pub version_number: u8,
54 pub current_next_indicator: bool,
56 pub section_number: u8,
58 pub last_section_number: u8,
60 pub bouquet_descriptors: DescriptorLoop<'a>,
64 pub transport_streams: Vec<BatTransportStream<'a>>,
66}
67
68impl<'a> BatSection<'a> {
69 pub fn bouquet_name(&self) -> Option<String> {
72 let mut pos = 0usize;
73 while pos + 2 <= self.bouquet_descriptors.len() {
74 let tag = self.bouquet_descriptors[pos];
75 let len = self.bouquet_descriptors[pos + 1] as usize;
76 let next = pos + 2 + len;
77 if next > self.bouquet_descriptors.len() {
78 break;
79 }
80 if tag == DESCRIPTOR_TAG_BOUQUET_NAME {
81 let name_bytes = &self.bouquet_descriptors[pos + 2..next];
82 return Some(crate::text::decode(name_bytes).into_owned());
83 }
84 pos = next;
85 }
86 None
87 }
88}
89
90impl<'a> Parse<'a> for BatSection<'a> {
91 type Error = crate::error::Error;
92 fn parse(bytes: &'a [u8]) -> Result<Self> {
93 let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + 2 + CRC_LEN;
94 if bytes.len() < min_len {
95 return Err(Error::BufferTooShort {
96 need: min_len,
97 have: bytes.len(),
98 what: "BatSection",
99 });
100 }
101
102 if bytes[0] != TABLE_ID {
103 return Err(Error::UnexpectedTableId {
104 table_id: bytes[0],
105 what: "BatSection",
106 expected: &[TABLE_ID],
107 });
108 }
109
110 let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
111 let total = super::check_section_length(
112 bytes.len(),
113 MIN_HEADER_LEN,
114 section_length as usize,
115 MIN_SECTION_LEN,
116 )?;
117
118 let bouquet_id = u16::from_be_bytes(*bytes[3..].first_chunk::<2>().unwrap());
124 let version_number = (bytes[5] >> 1) & 0x1F;
125 let current_next_indicator = (bytes[5] & 0x01) != 0;
126 let section_number = bytes[6];
127 let last_section_number = bytes[7];
128
129 let bouquet_descriptors_length = (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
131
132 let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
133 let bouquet_desc_end = bouquet_desc_start + bouquet_descriptors_length;
134
135 if bouquet_desc_end > total - CRC_LEN {
136 return Err(Error::SectionLengthOverflow {
137 declared: bouquet_descriptors_length,
138 available: (total - CRC_LEN).saturating_sub(bouquet_desc_start),
139 });
140 }
141
142 let bouquet_descriptors = DescriptorLoop::new(&bytes[bouquet_desc_start..bouquet_desc_end]);
143
144 let ts_loop_start = bouquet_desc_end;
147 let ts_loop_end = total - CRC_LEN;
148
149 if ts_loop_end < ts_loop_start + 2 {
150 return Err(Error::BufferTooShort {
151 need: 2,
152 have: ts_loop_end - ts_loop_start,
153 what: "BatSection transport_stream_loop length header",
154 });
155 }
156
157 let transport_stream_loop_length =
158 (((bytes[ts_loop_start] & 0x0F) as usize) << 8) | bytes[ts_loop_start + 1] as usize;
159
160 let loop_end = ts_loop_start + 2 + transport_stream_loop_length;
161 if loop_end > ts_loop_end {
162 return Err(Error::SectionLengthOverflow {
163 declared: transport_stream_loop_length,
164 available: ts_loop_end - (ts_loop_start + 2),
165 });
166 }
167
168 let mut transport_streams = Vec::new();
169 let mut pos = ts_loop_start + 2;
170 while pos < loop_end {
171 if pos + TS_HEADER_LEN > loop_end {
172 return Err(Error::BufferTooShort {
173 need: pos + TS_HEADER_LEN,
174 have: loop_end,
175 what: "BatSection transport_stream_entry",
176 });
177 }
178
179 let hdr = &bytes[pos..pos + TS_HEADER_LEN];
180 let transport_stream_id = u16::from_be_bytes(*hdr[0..].first_chunk::<2>().unwrap());
181 let original_network_id = u16::from_be_bytes(*hdr[2..].first_chunk::<2>().unwrap());
182 let transport_descriptors_length =
183 (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
184
185 let desc_start = pos + TS_HEADER_LEN;
186 let desc_end = desc_start + transport_descriptors_length;
187
188 if desc_end > loop_end {
189 return Err(Error::SectionLengthOverflow {
190 declared: transport_descriptors_length,
191 available: loop_end - desc_start,
192 });
193 }
194
195 transport_streams.push(BatTransportStream {
196 transport_stream_id,
197 original_network_id,
198 descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
199 });
200
201 pos = desc_end;
202 }
203
204 Ok(BatSection {
210 bouquet_id,
211 version_number,
212 current_next_indicator,
213 section_number,
214 last_section_number,
215 bouquet_descriptors,
216 transport_streams,
217 })
218 }
219}
220
221impl Serialize for BatSection<'_> {
222 type Error = crate::error::Error;
223 fn serialized_len(&self) -> usize {
224 let bouquet_desc_len = self.bouquet_descriptors.len();
225 let ts_bytes: usize = self
226 .transport_streams
227 .iter()
228 .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
229 .sum();
230 MIN_HEADER_LEN
231 + EXTENSION_HEADER_LEN
232 + POST_EXTENSION_LEN
233 + bouquet_desc_len
234 + 2 + ts_bytes
236 + CRC_LEN
237 }
238
239 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
240 let len = self.serialized_len();
241 if buf.len() < len {
242 return Err(Error::OutputBufferTooSmall {
243 need: len,
244 have: buf.len(),
245 });
246 }
247
248 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
249 buf[0] = TABLE_ID;
250 buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
251 buf[2] = (section_length & 0xFF) as u8;
252
253 buf[3..5].copy_from_slice(&self.bouquet_id.to_be_bytes());
255 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
256 buf[6] = self.section_number;
257 buf[7] = self.last_section_number;
258
259 let bdl = self.bouquet_descriptors.len() as u16;
261 buf[8] = 0xF0 | ((bdl >> 8) as u8 & 0x0F);
262 buf[9] = (bdl & 0xFF) as u8;
263
264 let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
265 buf[bouquet_desc_start..bouquet_desc_start + self.bouquet_descriptors.len()]
266 .copy_from_slice(self.bouquet_descriptors.raw());
267
268 let ts_loop_start = bouquet_desc_start + self.bouquet_descriptors.len();
269 let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
270 buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
271 buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
272
273 let mut pos = ts_loop_start + 2;
274 for ts in &self.transport_streams {
275 buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
276 buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
277 let tdl = ts.descriptors.len() as u16;
278 buf[pos + 4] = 0xF0 | ((tdl >> 8) as u8 & 0x0F);
279 buf[pos + 5] = (tdl & 0xFF) as u8;
280 let desc_start = pos + TS_HEADER_LEN;
281 buf[desc_start..desc_start + ts.descriptors.len()]
282 .copy_from_slice(ts.descriptors.raw());
283 pos = desc_start + ts.descriptors.len();
284 }
285
286 let crc_pos = len - CRC_LEN;
288 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
289 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
290 Ok(len)
291 }
292}
293impl<'a> crate::traits::TableDef<'a> for BatSection<'a> {
294 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
295 const NAME: &'static str = "BOUQUET_ASSOCIATION";
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 type TestTs = (u16, u16, Vec<u8>);
303
304 fn build_bat(
306 bouquet_id: u16,
307 version: u8,
308 section_number: u8,
309 last_section_number: u8,
310 bouquet_desc: &[u8],
311 transport_streams: &[TestTs],
312 ) -> Vec<u8> {
313 let ts_streams: Vec<BatTransportStream> = transport_streams
314 .iter()
315 .map(|(tsid, onid, d)| BatTransportStream {
316 transport_stream_id: *tsid,
317 original_network_id: *onid,
318 descriptors: DescriptorLoop::new(d),
319 })
320 .collect();
321 let bat = BatSection {
322 bouquet_id,
323 version_number: version,
324 current_next_indicator: true,
325 section_number,
326 last_section_number,
327 bouquet_descriptors: DescriptorLoop::new(bouquet_desc),
328 transport_streams: ts_streams,
329 };
330 let mut buf = vec![0u8; bat.serialized_len()];
331 bat.serialize_into(&mut buf).unwrap();
332 buf
333 }
334
335 #[test]
336 fn parse_extracts_bouquet_id() {
337 let bytes = build_bat(0x1234, 3, 0, 0, &[], &[]);
338 let bat = BatSection::parse(&bytes).unwrap();
339 assert_eq!(bat.bouquet_id, 0x1234);
340 }
341
342 #[test]
343 fn parse_extracts_version_and_cni() {
344 let bytes = build_bat(0x0001, 7, 0, 0, &[], &[]);
345 let bat = BatSection::parse(&bytes).unwrap();
346 assert_eq!(bat.version_number, 7);
347 assert!(bat.current_next_indicator);
348 }
349
350 #[test]
351 fn parse_extracts_section_numbers() {
352 let bytes = build_bat(0x0001, 0, 2, 4, &[], &[]);
353 let bat = BatSection::parse(&bytes).unwrap();
354 assert_eq!(bat.section_number, 2);
355 assert_eq!(bat.last_section_number, 4);
356 }
357
358 #[test]
359 fn bouquet_name_descriptor_extracted() {
360 let name_desc: Vec<u8> = vec![
361 DESCRIPTOR_TAG_BOUQUET_NAME,
362 0x05,
363 b'H',
364 b'E',
365 b'L',
366 b'L',
367 b'O',
368 ];
369 let bytes = build_bat(0x0001, 0, 0, 0, &name_desc, &[]);
370 let bat = BatSection::parse(&bytes).unwrap();
371 assert_eq!(bat.bouquet_name(), Some("HELLO".to_string()));
372 }
373
374 #[test]
375 fn bouquet_name_returns_none_when_no_bouquet_name_descriptor() {
376 let other_desc: Vec<u8> = vec![0x40, 0x03, b'A', b'B', b'C'];
378 let bytes = build_bat(0x0001, 0, 0, 0, &other_desc, &[]);
379 let bat = BatSection::parse(&bytes).unwrap();
380 assert_eq!(bat.bouquet_name(), None);
381 }
382
383 #[test]
384 fn private_descriptors_preserved_in_bouquet_descriptors() {
385 let private_desc: Vec<u8> = vec![0x80, 0x04, 0xDE, 0xAD, 0xBE, 0xEF];
387 let bytes = build_bat(0x0001, 0, 0, 0, &private_desc, &[]);
388 let bat = BatSection::parse(&bytes).unwrap();
389 assert_eq!(bat.bouquet_descriptors.raw(), &private_desc[..]);
390 }
391
392 #[test]
393 fn parse_transport_stream_entries() {
394 let bytes = build_bat(
395 0x0001,
396 0,
397 0,
398 0,
399 &[],
400 &[
401 (
402 0x1234,
403 0x0020,
404 vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05],
405 ),
406 (0x5678, 0x0020, vec![]),
407 ],
408 );
409 let bat = BatSection::parse(&bytes).unwrap();
410 assert_eq!(bat.transport_streams.len(), 2);
411 assert_eq!(bat.transport_streams[0].transport_stream_id, 0x1234);
412 assert_eq!(bat.transport_streams[0].original_network_id, 0x0020);
413 assert_eq!(
414 bat.transport_streams[0].descriptors.raw(),
415 &[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
416 );
417 assert_eq!(bat.transport_streams[1].transport_stream_id, 0x5678);
418 assert_eq!(bat.transport_streams[1].descriptors.len(), 0);
419 }
420
421 #[test]
422 fn bat_with_no_transport_streams_parses_ok() {
423 let bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
424 let bat = BatSection::parse(&bytes).unwrap();
425 assert!(bat.transport_streams.is_empty());
426 }
427
428 #[test]
429 fn serialize_round_trip() {
430 let name_desc: Vec<u8> = vec![DESCRIPTOR_TAG_BOUQUET_NAME, 0x04, b'T', b'E', b'S', b'T'];
431 let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
432 let bat = BatSection {
433 bouquet_id: 0x4242,
434 version_number: 5,
435 current_next_indicator: true,
436 section_number: 1,
437 last_section_number: 2,
438 bouquet_descriptors: DescriptorLoop::new(&name_desc),
439 transport_streams: vec![
440 BatTransportStream {
441 transport_stream_id: 0x1234,
442 original_network_id: 0x0020,
443 descriptors: DescriptorLoop::new(&ts_desc),
444 },
445 BatTransportStream {
446 transport_stream_id: 0x5678,
447 original_network_id: 0x0020,
448 descriptors: DescriptorLoop::new(&[]),
449 },
450 ],
451 };
452 let mut buf = vec![0u8; bat.serialized_len()];
453 bat.serialize_into(&mut buf).unwrap();
454 let parsed = BatSection::parse(&buf).unwrap();
455 assert_eq!(bat, parsed);
456 }
457
458 #[test]
462 fn bat_parse_does_not_verify_crc() {
463 let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
464 bytes[3] ^= 0xFF; let bat = BatSection::parse(&bytes).unwrap();
466 assert_eq!(bat.bouquet_id, 0x0001 ^ 0xFF00);
467 }
468
469 #[test]
470 fn parse_rejects_short_buffer() {
471 let err = BatSection::parse(&[0x4A, 0x00]).unwrap_err();
472 assert!(matches!(err, Error::BufferTooShort { .. }));
473 }
474
475 #[test]
476 fn parse_rejects_wrong_table_id() {
477 let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
478 bytes[0] = 0x00;
479 let err = BatSection::parse(&bytes).unwrap_err();
480 assert!(matches!(
481 err,
482 Error::UnexpectedTableId { table_id: 0x00, .. }
483 ));
484 }
485
486 #[test]
487 fn serialize_too_small_buffer_returns_error() {
488 let bat = BatSection {
489 bouquet_id: 0x0001,
490 version_number: 0,
491 current_next_indicator: true,
492 section_number: 0,
493 last_section_number: 0,
494 bouquet_descriptors: DescriptorLoop::new(&[]),
495 transport_streams: vec![],
496 };
497 let mut buf = vec![0u8; 2];
498 let err = bat.serialize_into(&mut buf).unwrap_err();
499 assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
500 }
501
502 #[test]
503 fn parse_rejects_zero_section_length() {
504 let mut buf = vec![0u8; 64];
505 buf[0] = TABLE_ID;
506 buf[1] = 0xF0;
507 buf[2] = 0x00;
508 for b in &mut buf[3..] {
509 *b = 0xFF;
510 }
511 assert!(matches!(
512 BatSection::parse(&buf).unwrap_err(),
513 Error::SectionLengthOverflow { .. }
514 ));
515 }
516}