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], bytes[4]]);
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 transport_stream_id = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
180 let original_network_id = u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]);
181 let transport_descriptors_length =
182 (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
183
184 let desc_start = pos + TS_HEADER_LEN;
185 let desc_end = desc_start + transport_descriptors_length;
186
187 if desc_end > loop_end {
188 return Err(Error::SectionLengthOverflow {
189 declared: transport_descriptors_length,
190 available: loop_end - desc_start,
191 });
192 }
193
194 transport_streams.push(BatTransportStream {
195 transport_stream_id,
196 original_network_id,
197 descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
198 });
199
200 pos = desc_end;
201 }
202
203 Ok(BatSection {
209 bouquet_id,
210 version_number,
211 current_next_indicator,
212 section_number,
213 last_section_number,
214 bouquet_descriptors,
215 transport_streams,
216 })
217 }
218}
219
220impl Serialize for BatSection<'_> {
221 type Error = crate::error::Error;
222 fn serialized_len(&self) -> usize {
223 let bouquet_desc_len = self.bouquet_descriptors.len();
224 let ts_bytes: usize = self
225 .transport_streams
226 .iter()
227 .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
228 .sum();
229 MIN_HEADER_LEN
230 + EXTENSION_HEADER_LEN
231 + POST_EXTENSION_LEN
232 + bouquet_desc_len
233 + 2 + ts_bytes
235 + CRC_LEN
236 }
237
238 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
239 let len = self.serialized_len();
240 if buf.len() < len {
241 return Err(Error::OutputBufferTooSmall {
242 need: len,
243 have: buf.len(),
244 });
245 }
246
247 let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
248 buf[0] = TABLE_ID;
249 buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
250 buf[2] = (section_length & 0xFF) as u8;
251
252 buf[3..5].copy_from_slice(&self.bouquet_id.to_be_bytes());
254 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
255 buf[6] = self.section_number;
256 buf[7] = self.last_section_number;
257
258 let bdl = self.bouquet_descriptors.len() as u16;
260 buf[8] = 0xF0 | ((bdl >> 8) as u8 & 0x0F);
261 buf[9] = (bdl & 0xFF) as u8;
262
263 let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
264 buf[bouquet_desc_start..bouquet_desc_start + self.bouquet_descriptors.len()]
265 .copy_from_slice(self.bouquet_descriptors.raw());
266
267 let ts_loop_start = bouquet_desc_start + self.bouquet_descriptors.len();
268 let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
269 buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
270 buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
271
272 let mut pos = ts_loop_start + 2;
273 for ts in &self.transport_streams {
274 buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
275 buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
276 let tdl = ts.descriptors.len() as u16;
277 buf[pos + 4] = 0xF0 | ((tdl >> 8) as u8 & 0x0F);
278 buf[pos + 5] = (tdl & 0xFF) as u8;
279 let desc_start = pos + TS_HEADER_LEN;
280 buf[desc_start..desc_start + ts.descriptors.len()]
281 .copy_from_slice(ts.descriptors.raw());
282 pos = desc_start + ts.descriptors.len();
283 }
284
285 let crc_pos = len - CRC_LEN;
287 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
288 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
289 Ok(len)
290 }
291}
292impl<'a> crate::traits::TableDef<'a> for BatSection<'a> {
293 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
294 const NAME: &'static str = "BOUQUET_ASSOCIATION";
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300
301 type TestTs = (u16, u16, Vec<u8>);
302
303 fn build_bat(
305 bouquet_id: u16,
306 version: u8,
307 section_number: u8,
308 last_section_number: u8,
309 bouquet_desc: &[u8],
310 transport_streams: &[TestTs],
311 ) -> Vec<u8> {
312 let ts_streams: Vec<BatTransportStream> = transport_streams
313 .iter()
314 .map(|(tsid, onid, d)| BatTransportStream {
315 transport_stream_id: *tsid,
316 original_network_id: *onid,
317 descriptors: DescriptorLoop::new(d),
318 })
319 .collect();
320 let bat = BatSection {
321 bouquet_id,
322 version_number: version,
323 current_next_indicator: true,
324 section_number,
325 last_section_number,
326 bouquet_descriptors: DescriptorLoop::new(bouquet_desc),
327 transport_streams: ts_streams,
328 };
329 let mut buf = vec![0u8; bat.serialized_len()];
330 bat.serialize_into(&mut buf).unwrap();
331 buf
332 }
333
334 #[test]
335 fn parse_extracts_bouquet_id() {
336 let bytes = build_bat(0x1234, 3, 0, 0, &[], &[]);
337 let bat = BatSection::parse(&bytes).unwrap();
338 assert_eq!(bat.bouquet_id, 0x1234);
339 }
340
341 #[test]
342 fn parse_extracts_version_and_cni() {
343 let bytes = build_bat(0x0001, 7, 0, 0, &[], &[]);
344 let bat = BatSection::parse(&bytes).unwrap();
345 assert_eq!(bat.version_number, 7);
346 assert!(bat.current_next_indicator);
347 }
348
349 #[test]
350 fn parse_extracts_section_numbers() {
351 let bytes = build_bat(0x0001, 0, 2, 4, &[], &[]);
352 let bat = BatSection::parse(&bytes).unwrap();
353 assert_eq!(bat.section_number, 2);
354 assert_eq!(bat.last_section_number, 4);
355 }
356
357 #[test]
358 fn bouquet_name_descriptor_extracted() {
359 let name_desc: Vec<u8> = vec![
360 DESCRIPTOR_TAG_BOUQUET_NAME,
361 0x05,
362 b'H',
363 b'E',
364 b'L',
365 b'L',
366 b'O',
367 ];
368 let bytes = build_bat(0x0001, 0, 0, 0, &name_desc, &[]);
369 let bat = BatSection::parse(&bytes).unwrap();
370 assert_eq!(bat.bouquet_name(), Some("HELLO".to_string()));
371 }
372
373 #[test]
374 fn bouquet_name_returns_none_when_no_bouquet_name_descriptor() {
375 let other_desc: Vec<u8> = vec![0x40, 0x03, b'A', b'B', b'C'];
377 let bytes = build_bat(0x0001, 0, 0, 0, &other_desc, &[]);
378 let bat = BatSection::parse(&bytes).unwrap();
379 assert_eq!(bat.bouquet_name(), None);
380 }
381
382 #[test]
383 fn private_descriptors_preserved_in_bouquet_descriptors() {
384 let private_desc: Vec<u8> = vec![0x80, 0x04, 0xDE, 0xAD, 0xBE, 0xEF];
386 let bytes = build_bat(0x0001, 0, 0, 0, &private_desc, &[]);
387 let bat = BatSection::parse(&bytes).unwrap();
388 assert_eq!(bat.bouquet_descriptors.raw(), &private_desc[..]);
389 }
390
391 #[test]
392 fn parse_transport_stream_entries() {
393 let bytes = build_bat(
394 0x0001,
395 0,
396 0,
397 0,
398 &[],
399 &[
400 (
401 0x1234,
402 0x0020,
403 vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05],
404 ),
405 (0x5678, 0x0020, vec![]),
406 ],
407 );
408 let bat = BatSection::parse(&bytes).unwrap();
409 assert_eq!(bat.transport_streams.len(), 2);
410 assert_eq!(bat.transport_streams[0].transport_stream_id, 0x1234);
411 assert_eq!(bat.transport_streams[0].original_network_id, 0x0020);
412 assert_eq!(
413 bat.transport_streams[0].descriptors.raw(),
414 &[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
415 );
416 assert_eq!(bat.transport_streams[1].transport_stream_id, 0x5678);
417 assert_eq!(bat.transport_streams[1].descriptors.len(), 0);
418 }
419
420 #[test]
421 fn bat_with_no_transport_streams_parses_ok() {
422 let bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
423 let bat = BatSection::parse(&bytes).unwrap();
424 assert!(bat.transport_streams.is_empty());
425 }
426
427 #[test]
428 fn serialize_round_trip() {
429 let name_desc: Vec<u8> = vec![DESCRIPTOR_TAG_BOUQUET_NAME, 0x04, b'T', b'E', b'S', b'T'];
430 let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
431 let bat = BatSection {
432 bouquet_id: 0x4242,
433 version_number: 5,
434 current_next_indicator: true,
435 section_number: 1,
436 last_section_number: 2,
437 bouquet_descriptors: DescriptorLoop::new(&name_desc),
438 transport_streams: vec![
439 BatTransportStream {
440 transport_stream_id: 0x1234,
441 original_network_id: 0x0020,
442 descriptors: DescriptorLoop::new(&ts_desc),
443 },
444 BatTransportStream {
445 transport_stream_id: 0x5678,
446 original_network_id: 0x0020,
447 descriptors: DescriptorLoop::new(&[]),
448 },
449 ],
450 };
451 let mut buf = vec![0u8; bat.serialized_len()];
452 bat.serialize_into(&mut buf).unwrap();
453 let parsed = BatSection::parse(&buf).unwrap();
454 assert_eq!(bat, parsed);
455 }
456
457 #[test]
461 fn bat_parse_does_not_verify_crc() {
462 let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
463 bytes[3] ^= 0xFF; let bat = BatSection::parse(&bytes).unwrap();
465 assert_eq!(bat.bouquet_id, 0x0001 ^ 0xFF00);
466 }
467
468 #[test]
469 fn parse_rejects_short_buffer() {
470 let err = BatSection::parse(&[0x4A, 0x00]).unwrap_err();
471 assert!(matches!(err, Error::BufferTooShort { .. }));
472 }
473
474 #[test]
475 fn parse_rejects_wrong_table_id() {
476 let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
477 bytes[0] = 0x00;
478 let err = BatSection::parse(&bytes).unwrap_err();
479 assert!(matches!(
480 err,
481 Error::UnexpectedTableId { table_id: 0x00, .. }
482 ));
483 }
484
485 #[test]
486 fn serialize_too_small_buffer_returns_error() {
487 let bat = BatSection {
488 bouquet_id: 0x0001,
489 version_number: 0,
490 current_next_indicator: true,
491 section_number: 0,
492 last_section_number: 0,
493 bouquet_descriptors: DescriptorLoop::new(&[]),
494 transport_streams: vec![],
495 };
496 let mut buf = vec![0u8; 2];
497 let err = bat.serialize_into(&mut buf).unwrap_err();
498 assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
499 }
500
501 #[test]
502 fn parse_rejects_zero_section_length() {
503 let mut buf = vec![0u8; 64];
504 buf[0] = TABLE_ID;
505 buf[1] = 0xF0;
506 buf[2] = 0x00;
507 for b in &mut buf[3..] {
508 *b = 0xFF;
509 }
510 assert!(matches!(
511 BatSection::parse(&buf).unwrap_err(),
512 Error::SectionLengthOverflow { .. }
513 ));
514 }
515}