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 Sat 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::error::{Error, Result};
9use crate::traits::Table;
10use dvb_common::{Parse, Serialize};
11
12/// table_id value for BAT.
13pub const TABLE_ID: u8 = 0x4A;
14/// Well-known PID on which BAT is carried.
15pub const PID: u16 = 0x0011;
16/// bouquet_name_descriptor tag (ETSI EN 300 468 §6.2.4).
17pub const DESCRIPTOR_TAG_BOUQUET_NAME: u8 = 0x47;
18
19const MIN_HEADER_LEN: usize = 3;
20const EXTENSION_HEADER_LEN: usize = 5;
21/// Bytes after the extension header: reserved(4) + bouquet_descriptors_length(12) = 2 bytes.
22const POST_EXTENSION_LEN: usize = 2;
23const CRC_LEN: usize = 4;
24/// Per-transport-stream header: ts_id(2) + original_network_id(2) + reserved(4) + transport_descriptors_length(12) = 6 bytes.
25const TS_HEADER_LEN: usize = 6;
26
27/// One transport-stream entry inside the BAT transport_stream_loop.
28#[derive(Debug, Clone, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub struct BatTransportStream<'a> {
31    /// transport_stream_id of the described TS.
32    pub transport_stream_id: u16,
33    /// original_network_id of the described TS.
34    pub original_network_id: u16,
35    /// Raw descriptor bytes for this transport stream.
36    #[cfg_attr(feature = "serde", serde(borrow))]
37    pub descriptors: &'a [u8],
38}
39
40/// Bouquet Association Table.
41#[derive(Debug, Clone, PartialEq, Eq)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
43pub struct Bat<'a> {
44    /// Bouquet identifier (table_id_extension at bytes 3-4).
45    pub bouquet_id: u16,
46    /// 5-bit version_number.
47    pub version_number: u8,
48    /// current_next_indicator bit.
49    pub current_next_indicator: bool,
50    /// section_number in the sub-table sequence.
51    pub section_number: u8,
52    /// last_section_number in the sub-table sequence.
53    pub last_section_number: u8,
54    /// Raw bouquet-descriptor bytes (may contain bouquet_name_descriptor 0x47).
55    #[cfg_attr(feature = "serde", serde(borrow))]
56    pub bouquet_descriptors: &'a [u8],
57    /// Transport-stream loop entries in wire order.
58    #[cfg_attr(feature = "serde", serde(borrow))]
59    pub transport_streams: Vec<BatTransportStream<'a>>,
60}
61
62impl<'a> Bat<'a> {
63    /// Walk the bouquet_descriptors looking for the first bouquet_name_descriptor
64    /// (tag 0x47). Returns the decoded UTF-8 name, or `None` if not present.
65    pub fn bouquet_name(&self) -> Option<String> {
66        let mut pos = 0usize;
67        while pos + 2 <= self.bouquet_descriptors.len() {
68            let tag = self.bouquet_descriptors[pos];
69            let len = self.bouquet_descriptors[pos + 1] as usize;
70            let next = pos + 2 + len;
71            if next > self.bouquet_descriptors.len() {
72                break;
73            }
74            if tag == DESCRIPTOR_TAG_BOUQUET_NAME {
75                let name_bytes = &self.bouquet_descriptors[pos + 2..next];
76                return Some(crate::text::decode(name_bytes).into_owned());
77            }
78            pos = next;
79        }
80        None
81    }
82}
83
84impl<'a> Parse<'a> for Bat<'a> {
85    type Error = crate::error::Error;
86    fn parse(bytes: &'a [u8]) -> Result<Self> {
87        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + 2 + CRC_LEN;
88        if bytes.len() < min_len {
89            return Err(Error::BufferTooShort {
90                need: min_len,
91                have: bytes.len(),
92                what: "Bat",
93            });
94        }
95
96        if bytes[0] != TABLE_ID {
97            return Err(Error::UnexpectedTableId {
98                table_id: bytes[0],
99                what: "Bat",
100                expected: &[TABLE_ID],
101            });
102        }
103
104        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
105        let total = MIN_HEADER_LEN + section_length as usize;
106        if bytes.len() < total {
107            return Err(Error::SectionLengthOverflow {
108                declared: section_length as usize,
109                available: bytes.len() - MIN_HEADER_LEN,
110            });
111        }
112
113        // Extension header bytes [3..8]:
114        // bytes[3..5] = bouquet_id (table_id_extension)
115        // bytes[5]    = reserved(2) | version_number(5) | current_next_indicator(1)
116        // bytes[6]    = section_number
117        // bytes[7]    = last_section_number
118        let bouquet_id = u16::from_be_bytes([bytes[3], bytes[4]]);
119        let version_number = (bytes[5] >> 1) & 0x1F;
120        let current_next_indicator = (bytes[5] & 0x01) != 0;
121        let section_number = bytes[6];
122        let last_section_number = bytes[7];
123
124        // bytes[8..10] = reserved(4) | bouquet_descriptors_length(12)
125        let bouquet_descriptors_length = (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
126
127        let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
128        let bouquet_desc_end = bouquet_desc_start + bouquet_descriptors_length;
129
130        if bouquet_desc_end > total - CRC_LEN {
131            return Err(Error::SectionLengthOverflow {
132                declared: bouquet_descriptors_length,
133                available: (total - CRC_LEN).saturating_sub(bouquet_desc_start),
134            });
135        }
136
137        let bouquet_descriptors = &bytes[bouquet_desc_start..bouquet_desc_end];
138
139        // Transport stream loop: starts right after bouquet_descriptors.
140        // First 2 bytes: reserved(4) | transport_stream_loop_length(12).
141        let ts_loop_start = bouquet_desc_end;
142        let ts_loop_end = total - CRC_LEN;
143
144        if ts_loop_end < ts_loop_start + 2 {
145            return Err(Error::BufferTooShort {
146                need: 2,
147                have: ts_loop_end - ts_loop_start,
148                what: "Bat transport_stream_loop length header",
149            });
150        }
151
152        let transport_stream_loop_length =
153            (((bytes[ts_loop_start] & 0x0F) as usize) << 8) | bytes[ts_loop_start + 1] as usize;
154
155        let loop_end = ts_loop_start + 2 + transport_stream_loop_length;
156        if loop_end > ts_loop_end {
157            return Err(Error::SectionLengthOverflow {
158                declared: transport_stream_loop_length,
159                available: ts_loop_end - (ts_loop_start + 2),
160            });
161        }
162
163        let mut transport_streams = Vec::new();
164        let mut pos = ts_loop_start + 2;
165        while pos < loop_end {
166            if pos + TS_HEADER_LEN > loop_end {
167                return Err(Error::BufferTooShort {
168                    need: pos + TS_HEADER_LEN,
169                    have: loop_end,
170                    what: "Bat transport_stream_entry",
171                });
172            }
173
174            let transport_stream_id = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
175            let original_network_id = u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]);
176            let transport_descriptors_length =
177                (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
178
179            let desc_start = pos + TS_HEADER_LEN;
180            let desc_end = desc_start + transport_descriptors_length;
181
182            if desc_end > loop_end {
183                return Err(Error::SectionLengthOverflow {
184                    declared: transport_descriptors_length,
185                    available: loop_end - desc_start,
186                });
187            }
188
189            transport_streams.push(BatTransportStream {
190                transport_stream_id,
191                original_network_id,
192                descriptors: &bytes[desc_start..desc_end],
193            });
194
195            pos = desc_end;
196        }
197
198        // CRC is NOT verified here — crate-wide contract: table parsers trust
199        // their input and CRC validation is the framing layer's job
200        // (`Section::validate_crc`). BAT used to be the lone exception, which
201        // made the family contract inconsistent.
202
203        Ok(Bat {
204            bouquet_id,
205            version_number,
206            current_next_indicator,
207            section_number,
208            last_section_number,
209            bouquet_descriptors,
210            transport_streams,
211        })
212    }
213}
214
215impl Serialize for Bat<'_> {
216    type Error = crate::error::Error;
217    fn serialized_len(&self) -> usize {
218        let bouquet_desc_len = self.bouquet_descriptors.len();
219        let ts_bytes: usize = self
220            .transport_streams
221            .iter()
222            .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
223            .sum();
224        MIN_HEADER_LEN
225            + EXTENSION_HEADER_LEN
226            + POST_EXTENSION_LEN
227            + bouquet_desc_len
228            + 2 // transport_stream_loop_length header
229            + ts_bytes
230            + CRC_LEN
231    }
232
233    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
234        let len = self.serialized_len();
235        if buf.len() < len {
236            return Err(Error::OutputBufferTooSmall {
237                need: len,
238                have: buf.len(),
239            });
240        }
241
242        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
243        buf[0] = TABLE_ID;
244        buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
245        buf[2] = (section_length & 0xFF) as u8;
246
247        // Extension header.
248        buf[3..5].copy_from_slice(&self.bouquet_id.to_be_bytes());
249        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
250        buf[6] = self.section_number;
251        buf[7] = self.last_section_number;
252
253        // Bouquet descriptors length field.
254        let bdl = self.bouquet_descriptors.len() as u16;
255        buf[8] = 0xF0 | ((bdl >> 8) as u8 & 0x0F);
256        buf[9] = (bdl & 0xFF) as u8;
257
258        let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
259        buf[bouquet_desc_start..bouquet_desc_start + self.bouquet_descriptors.len()]
260            .copy_from_slice(self.bouquet_descriptors);
261
262        let ts_loop_start = bouquet_desc_start + self.bouquet_descriptors.len();
263        let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
264        buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
265        buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
266
267        let mut pos = ts_loop_start + 2;
268        for ts in &self.transport_streams {
269            buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
270            buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
271            let tdl = ts.descriptors.len() as u16;
272            buf[pos + 4] = 0xF0 | ((tdl >> 8) as u8 & 0x0F);
273            buf[pos + 5] = (tdl & 0xFF) as u8;
274            let desc_start = pos + TS_HEADER_LEN;
275            buf[desc_start..desc_start + ts.descriptors.len()].copy_from_slice(ts.descriptors);
276            pos = desc_start + ts.descriptors.len();
277        }
278
279        // CRC: compute over everything up to (but not including) the CRC slot.
280        let crc_pos = len - CRC_LEN;
281        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
282        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
283        Ok(len)
284    }
285}
286
287impl<'a> Table<'a> for Bat<'a> {
288    const TABLE_ID: u8 = TABLE_ID;
289    const PID: u16 = PID;
290}
291
292impl<'a> crate::traits::TableDef<'a> for Bat<'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    /// Build a complete BAT section (with valid CRC).
304    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: d,
318            })
319            .collect();
320        let bat = Bat {
321            bouquet_id,
322            version_number: version,
323            current_next_indicator: true,
324            section_number,
325            last_section_number,
326            bouquet_descriptors: 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 = Bat::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 = Bat::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 = Bat::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 = Bat::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        // Non-bouquet-name descriptor (tag 0x40 = network_name, also human-readable).
376        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 = Bat::parse(&bytes).unwrap();
379        assert_eq!(bat.bouquet_name(), None);
380    }
381
382    #[test]
383    fn private_descriptors_preserved_in_bouquet_descriptors() {
384        // Private descriptor tag (>= 0x80). Per anti-instructions, surface as raw bytes.
385        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 = Bat::parse(&bytes).unwrap();
388        assert_eq!(bat.bouquet_descriptors, &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 = Bat::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,
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 = Bat::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 = Bat {
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: &name_desc,
438            transport_streams: vec![
439                BatTransportStream {
440                    transport_stream_id: 0x1234,
441                    original_network_id: 0x0020,
442                    descriptors: &ts_desc,
443                },
444                BatTransportStream {
445                    transport_stream_id: 0x5678,
446                    original_network_id: 0x0020,
447                    descriptors: &[],
448                },
449            ],
450        };
451        let mut buf = vec![0u8; bat.serialized_len()];
452        bat.serialize_into(&mut buf).unwrap();
453        let parsed = Bat::parse(&buf).unwrap();
454        assert_eq!(bat, parsed);
455    }
456
457    /// Crate-wide contract: table parsers do NOT verify CRC — that is the
458    /// framing layer's job (`Section::validate_crc`). A corrupted-CRC BAT
459    /// still parses; callers wanting integrity check the Section first.
460    #[test]
461    fn bat_parse_does_not_verify_crc() {
462        let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
463        bytes[3] ^= 0xFF; // corrupt bouquet_id high byte → CRC now wrong
464        let bat = Bat::parse(&bytes).unwrap();
465        assert_eq!(bat.bouquet_id, 0x0001 ^ 0xFF00);
466    }
467
468    #[test]
469    fn parse_rejects_short_buffer() {
470        let err = Bat::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 = Bat::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 = Bat {
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: &[],
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}