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 =
126            (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
127
128        let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
129        let bouquet_desc_end = bouquet_desc_start + bouquet_descriptors_length;
130
131        if bouquet_desc_end > total - CRC_LEN {
132            return Err(Error::SectionLengthOverflow {
133                declared: bouquet_descriptors_length,
134                available: (total - CRC_LEN).saturating_sub(bouquet_desc_start),
135            });
136        }
137
138        let bouquet_descriptors = &bytes[bouquet_desc_start..bouquet_desc_end];
139
140        // Transport stream loop: starts right after bouquet_descriptors.
141        // First 2 bytes: reserved(4) | transport_stream_loop_length(12).
142        let ts_loop_start = bouquet_desc_end;
143        let ts_loop_end = total - CRC_LEN;
144
145        if ts_loop_end < ts_loop_start + 2 {
146            return Err(Error::BufferTooShort {
147                need: 2,
148                have: ts_loop_end - ts_loop_start,
149                what: "Bat transport_stream_loop length header",
150            });
151        }
152
153        let transport_stream_loop_length =
154            (((bytes[ts_loop_start] & 0x0F) as usize) << 8) | bytes[ts_loop_start + 1] as usize;
155
156        let loop_end = ts_loop_start + 2 + transport_stream_loop_length;
157        if loop_end > ts_loop_end {
158            return Err(Error::SectionLengthOverflow {
159                declared: transport_stream_loop_length,
160                available: ts_loop_end - (ts_loop_start + 2),
161            });
162        }
163
164        let mut transport_streams = Vec::new();
165        let mut pos = ts_loop_start + 2;
166        while pos < loop_end {
167            if pos + TS_HEADER_LEN > loop_end {
168                return Err(Error::BufferTooShort {
169                    need: pos + TS_HEADER_LEN,
170                    have: loop_end,
171                    what: "Bat transport_stream_entry",
172                });
173            }
174
175            let transport_stream_id = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
176            let original_network_id = u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]);
177            let transport_descriptors_length =
178                (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
179
180            let desc_start = pos + TS_HEADER_LEN;
181            let desc_end = desc_start + transport_descriptors_length;
182
183            if desc_end > loop_end {
184                return Err(Error::SectionLengthOverflow {
185                    declared: transport_descriptors_length,
186                    available: loop_end - desc_start,
187                });
188            }
189
190            transport_streams.push(BatTransportStream {
191                transport_stream_id,
192                original_network_id,
193                descriptors: &bytes[desc_start..desc_end],
194            });
195
196            pos = desc_end;
197        }
198
199        // CRC is NOT verified here — crate-wide contract: table parsers trust
200        // their input and CRC validation is the framing layer's job
201        // (`Section::validate_crc`). BAT used to be the lone exception, which
202        // made the family contract inconsistent.
203
204        Ok(Bat {
205            bouquet_id,
206            version_number,
207            current_next_indicator,
208            section_number,
209            last_section_number,
210            bouquet_descriptors,
211            transport_streams,
212        })
213    }
214}
215
216impl Serialize for Bat<'_> {
217    type Error = crate::error::Error;
218    fn serialized_len(&self) -> usize {
219        let bouquet_desc_len = self.bouquet_descriptors.len();
220        let ts_bytes: usize = self
221            .transport_streams
222            .iter()
223            .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
224            .sum();
225        MIN_HEADER_LEN
226            + EXTENSION_HEADER_LEN
227            + POST_EXTENSION_LEN
228            + bouquet_desc_len
229            + 2 // transport_stream_loop_length header
230            + ts_bytes
231            + CRC_LEN
232    }
233
234    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
235        let len = self.serialized_len();
236        if buf.len() < len {
237            return Err(Error::OutputBufferTooSmall {
238                need: len,
239                have: buf.len(),
240            });
241        }
242
243        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
244        buf[0] = TABLE_ID;
245        buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
246        buf[2] = (section_length & 0xFF) as u8;
247
248        // Extension header.
249        buf[3..5].copy_from_slice(&self.bouquet_id.to_be_bytes());
250        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
251        buf[6] = self.section_number;
252        buf[7] = self.last_section_number;
253
254        // Bouquet descriptors length field.
255        let bdl = self.bouquet_descriptors.len() as u16;
256        buf[8] = 0xF0 | ((bdl >> 8) as u8 & 0x0F);
257        buf[9] = (bdl & 0xFF) as u8;
258
259        let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
260        buf[bouquet_desc_start..bouquet_desc_start + self.bouquet_descriptors.len()]
261            .copy_from_slice(self.bouquet_descriptors);
262
263        let ts_loop_start = bouquet_desc_start + self.bouquet_descriptors.len();
264        let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
265        buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
266        buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
267
268        let mut pos = ts_loop_start + 2;
269        for ts in &self.transport_streams {
270            buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
271            buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
272            let tdl = ts.descriptors.len() as u16;
273            buf[pos + 4] = 0xF0 | ((tdl >> 8) as u8 & 0x0F);
274            buf[pos + 5] = (tdl & 0xFF) as u8;
275            let desc_start = pos + TS_HEADER_LEN;
276            buf[desc_start..desc_start + ts.descriptors.len()].copy_from_slice(ts.descriptors);
277            pos = desc_start + ts.descriptors.len();
278        }
279
280        // CRC: compute over everything up to (but not including) the CRC slot.
281        let crc_pos = len - CRC_LEN;
282        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
283        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
284        Ok(len)
285    }
286}
287
288impl<'a> Table<'a> for Bat<'a> {
289    const TABLE_ID: u8 = TABLE_ID;
290    const PID: u16 = PID;
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    type TestTs = (u16, u16, Vec<u8>);
298
299    /// Build a complete BAT section (with valid CRC).
300    fn build_bat(
301        bouquet_id: u16,
302        version: u8,
303        section_number: u8,
304        last_section_number: u8,
305        bouquet_desc: &[u8],
306        transport_streams: &[TestTs],
307    ) -> Vec<u8> {
308        let ts_streams: Vec<BatTransportStream> = transport_streams
309            .iter()
310            .map(|(tsid, onid, d)| BatTransportStream {
311                transport_stream_id: *tsid,
312                original_network_id: *onid,
313                descriptors: d,
314            })
315            .collect();
316        let bat = Bat {
317            bouquet_id,
318            version_number: version,
319            current_next_indicator: true,
320            section_number,
321            last_section_number,
322            bouquet_descriptors: bouquet_desc,
323            transport_streams: ts_streams,
324        };
325        let mut buf = vec![0u8; bat.serialized_len()];
326        bat.serialize_into(&mut buf).unwrap();
327        buf
328    }
329
330    #[test]
331    fn parse_extracts_bouquet_id() {
332        let bytes = build_bat(0x1234, 3, 0, 0, &[], &[]);
333        let bat = Bat::parse(&bytes).unwrap();
334        assert_eq!(bat.bouquet_id, 0x1234);
335    }
336
337    #[test]
338    fn parse_extracts_version_and_cni() {
339        let bytes = build_bat(0x0001, 7, 0, 0, &[], &[]);
340        let bat = Bat::parse(&bytes).unwrap();
341        assert_eq!(bat.version_number, 7);
342        assert!(bat.current_next_indicator);
343    }
344
345    #[test]
346    fn parse_extracts_section_numbers() {
347        let bytes = build_bat(0x0001, 0, 2, 4, &[], &[]);
348        let bat = Bat::parse(&bytes).unwrap();
349        assert_eq!(bat.section_number, 2);
350        assert_eq!(bat.last_section_number, 4);
351    }
352
353    #[test]
354    fn bouquet_name_descriptor_extracted() {
355        let name_desc: Vec<u8> = vec![
356            DESCRIPTOR_TAG_BOUQUET_NAME,
357            0x05,
358            b'H',
359            b'E',
360            b'L',
361            b'L',
362            b'O',
363        ];
364        let bytes = build_bat(0x0001, 0, 0, 0, &name_desc, &[]);
365        let bat = Bat::parse(&bytes).unwrap();
366        assert_eq!(bat.bouquet_name(), Some("HELLO".to_string()));
367    }
368
369    #[test]
370    fn bouquet_name_returns_none_when_no_bouquet_name_descriptor() {
371        // Non-bouquet-name descriptor (tag 0x40 = network_name, also human-readable).
372        let other_desc: Vec<u8> = vec![0x40, 0x03, b'A', b'B', b'C'];
373        let bytes = build_bat(0x0001, 0, 0, 0, &other_desc, &[]);
374        let bat = Bat::parse(&bytes).unwrap();
375        assert_eq!(bat.bouquet_name(), None);
376    }
377
378    #[test]
379    fn private_descriptors_preserved_in_bouquet_descriptors() {
380        // Private descriptor tag (>= 0x80). Per anti-instructions, surface as raw bytes.
381        let private_desc: Vec<u8> = vec![0x80, 0x04, 0xDE, 0xAD, 0xBE, 0xEF];
382        let bytes = build_bat(0x0001, 0, 0, 0, &private_desc, &[]);
383        let bat = Bat::parse(&bytes).unwrap();
384        assert_eq!(bat.bouquet_descriptors, &private_desc[..]);
385    }
386
387    #[test]
388    fn parse_transport_stream_entries() {
389        let bytes = build_bat(
390            0x0001,
391            0,
392            0,
393            0,
394            &[],
395            &[
396                (0x1234, 0x0020, vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05]),
397                (0x5678, 0x0020, vec![]),
398            ],
399        );
400        let bat = Bat::parse(&bytes).unwrap();
401        assert_eq!(bat.transport_streams.len(), 2);
402        assert_eq!(bat.transport_streams[0].transport_stream_id, 0x1234);
403        assert_eq!(bat.transport_streams[0].original_network_id, 0x0020);
404        assert_eq!(
405            bat.transport_streams[0].descriptors,
406            &[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
407        );
408        assert_eq!(bat.transport_streams[1].transport_stream_id, 0x5678);
409        assert_eq!(bat.transport_streams[1].descriptors.len(), 0);
410    }
411
412    #[test]
413    fn bat_with_no_transport_streams_parses_ok() {
414        let bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
415        let bat = Bat::parse(&bytes).unwrap();
416        assert!(bat.transport_streams.is_empty());
417    }
418
419    #[test]
420    fn serialize_round_trip() {
421        let name_desc: Vec<u8> = vec![
422            DESCRIPTOR_TAG_BOUQUET_NAME,
423            0x04,
424            b'T',
425            b'E',
426            b'S',
427            b'T',
428        ];
429        let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
430        let bat = Bat {
431            bouquet_id: 0x4242,
432            version_number: 5,
433            current_next_indicator: true,
434            section_number: 1,
435            last_section_number: 2,
436            bouquet_descriptors: &name_desc,
437            transport_streams: vec![
438                BatTransportStream {
439                    transport_stream_id: 0x1234,
440                    original_network_id: 0x0020,
441                    descriptors: &ts_desc,
442                },
443                BatTransportStream {
444                    transport_stream_id: 0x5678,
445                    original_network_id: 0x0020,
446                    descriptors: &[],
447                },
448            ],
449        };
450        let mut buf = vec![0u8; bat.serialized_len()];
451        bat.serialize_into(&mut buf).unwrap();
452        let parsed = Bat::parse(&buf).unwrap();
453        assert_eq!(bat, parsed);
454    }
455
456    /// Crate-wide contract: table parsers do NOT verify CRC — that is the
457    /// framing layer's job (`Section::validate_crc`). A corrupted-CRC BAT
458    /// still parses; callers wanting integrity check the Section first.
459    #[test]
460    fn bat_parse_does_not_verify_crc() {
461        let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
462        bytes[3] ^= 0xFF; // corrupt bouquet_id high byte → CRC now wrong
463        let bat = Bat::parse(&bytes).unwrap();
464        assert_eq!(bat.bouquet_id, 0x0001 ^ 0xFF00);
465    }
466
467    #[test]
468    fn parse_rejects_short_buffer() {
469        let err = Bat::parse(&[0x4A, 0x00]).unwrap_err();
470        assert!(matches!(err, Error::BufferTooShort { .. }));
471    }
472
473    #[test]
474    fn parse_rejects_wrong_table_id() {
475        let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
476        bytes[0] = 0x00;
477        let err = Bat::parse(&bytes).unwrap_err();
478        assert!(matches!(
479            err,
480            Error::UnexpectedTableId { table_id: 0x00, .. }
481        ));
482    }
483
484    #[test]
485    fn serialize_too_small_buffer_returns_error() {
486        let bat = Bat {
487            bouquet_id: 0x0001,
488            version_number: 0,
489            current_next_indicator: true,
490            section_number: 0,
491            last_section_number: 0,
492            bouquet_descriptors: &[],
493            transport_streams: vec![],
494        };
495        let mut buf = vec![0u8; 2];
496        let err = bat.serialize_into(&mut buf).unwrap_err();
497        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
498    }
499}