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