Skip to main content

dvb_si/tables/
bat.rs

1//! Bouquet Association Table — ETSI EN 300 468 §5.2.2.
2//!
3//! BAT groups services into operator-defined bouquets ("TNT SatSection HD",
4//! "Sky DE Sports", "ORF DIGITAL" etc). Carried on PID 0x0011 with
5//! table_id 0x4A. Structure mirrors NIT: bouquet-level descriptors +
6//! transport_stream loop with per-TS descriptors.
7
8use crate::descriptors::DescriptorLoop;
9use crate::error::{Error, Result};
10use alloc::string::String;
11use alloc::vec::Vec;
12use dvb_common::{Parse, Serialize};
13
14/// table_id value for BAT.
15pub const TABLE_ID: u8 = 0x4A;
16/// Well-known PID on which BAT is carried.
17pub const PID: u16 = 0x0011;
18/// bouquet_name_descriptor tag (ETSI EN 300 468 §6.2.4).
19pub const DESCRIPTOR_TAG_BOUQUET_NAME: u8 = 0x47;
20
21const MIN_HEADER_LEN: usize = 3;
22const EXTENSION_HEADER_LEN: usize = 5;
23/// Bytes after the extension header: reserved(4) + bouquet_descriptors_length(12) = 2 bytes.
24const POST_EXTENSION_LEN: usize = 2;
25const CRC_LEN: usize = 4;
26/// Per-transport-stream header: ts_id(2) + original_network_id(2) + reserved(4) + transport_descriptors_length(12) = 6 bytes.
27const TS_HEADER_LEN: usize = 6;
28const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
29
30/// One transport-stream entry inside the BAT transport_stream_loop.
31#[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    /// transport_stream_id of the described TS.
36    pub transport_stream_id: u16,
37    /// original_network_id of the described TS.
38    pub original_network_id: u16,
39    /// Raw descriptor bytes for this transport stream.
40    /// Per-TS descriptor loop. Serializes as the typed descriptor sequence;
41    /// `.raw()` yields the wire bytes.
42    pub descriptors: DescriptorLoop<'a>,
43}
44
45/// Bouquet Association Table.
46#[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    /// Bouquet identifier (table_id_extension at bytes 3-4).
51    pub bouquet_id: u16,
52    /// 5-bit version_number.
53    pub version_number: u8,
54    /// current_next_indicator bit.
55    pub current_next_indicator: bool,
56    /// section_number in the sub-table sequence.
57    pub section_number: u8,
58    /// last_section_number in the sub-table sequence.
59    pub last_section_number: u8,
60    /// Raw bouquet-descriptor bytes (may contain bouquet_name_descriptor 0x47).
61    /// Bouquet descriptor loop. Serializes as the typed descriptor sequence;
62    /// `.raw()` yields the wire bytes.
63    pub bouquet_descriptors: DescriptorLoop<'a>,
64    /// Transport-stream loop entries in wire order.
65    pub transport_streams: Vec<BatTransportStream<'a>>,
66}
67
68impl<'a> BatSection<'a> {
69    /// Walk the bouquet_descriptors looking for the first bouquet_name_descriptor
70    /// (tag 0x47). Returns the decoded UTF-8 name, or `None` if not present.
71    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        // Extension header bytes [3..8]:
119        // bytes[3..5] = bouquet_id (table_id_extension)
120        // bytes[5]    = reserved(2) | version_number(5) | current_next_indicator(1)
121        // bytes[6]    = section_number
122        // bytes[7]    = last_section_number
123        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        // bytes[8..10] = reserved(4) | bouquet_descriptors_length(12)
130        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        // Transport stream loop: starts right after bouquet_descriptors.
145        // First 2 bytes: reserved(4) | transport_stream_loop_length(12).
146        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        // CRC is NOT verified here — crate-wide contract: table parsers trust
205        // their input and CRC validation is the framing layer's job
206        // (`Section::validate_crc`). BAT used to be the lone exception, which
207        // made the family contract inconsistent.
208
209        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 // transport_stream_loop_length header
235            + 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        // Extension header.
254        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        // Bouquet descriptors length field.
260        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        // CRC: compute over everything up to (but not including) the CRC slot.
287        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    /// Build a complete BAT section (with valid CRC).
305    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        // Non-bouquet-name descriptor (tag 0x40 = network_name, also human-readable).
377        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        // Private descriptor tag (>= 0x80). Per anti-instructions, surface as raw bytes.
386        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    /// Crate-wide contract: table parsers do NOT verify CRC — that is the
459    /// framing layer's job (`Section::validate_crc`). A corrupted-CRC BAT
460    /// still parses; callers wanting integrity check the Section first.
461    #[test]
462    fn bat_parse_does_not_verify_crc() {
463        let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
464        bytes[3] ^= 0xFF; // corrupt bouquet_id high byte → CRC now wrong
465        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}