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::descriptors::DescriptorLoop;
9use crate::error::{Error, Result};
10use crate::traits::Table;
11use dvb_common::{Parse, Serialize};
12
13/// table_id value for BAT.
14pub const TABLE_ID: u8 = 0x4A;
15/// Well-known PID on which BAT is carried.
16pub const PID: u16 = 0x0011;
17/// bouquet_name_descriptor tag (ETSI EN 300 468 §6.2.4).
18pub const DESCRIPTOR_TAG_BOUQUET_NAME: u8 = 0x47;
19
20const MIN_HEADER_LEN: usize = 3;
21const EXTENSION_HEADER_LEN: usize = 5;
22/// Bytes after the extension header: reserved(4) + bouquet_descriptors_length(12) = 2 bytes.
23const POST_EXTENSION_LEN: usize = 2;
24const CRC_LEN: usize = 4;
25/// Per-transport-stream header: ts_id(2) + original_network_id(2) + reserved(4) + transport_descriptors_length(12) = 6 bytes.
26const TS_HEADER_LEN: usize = 6;
27
28/// One transport-stream entry inside the BAT transport_stream_loop.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize))]
31pub struct BatTransportStream<'a> {
32    /// transport_stream_id of the described TS.
33    pub transport_stream_id: u16,
34    /// original_network_id of the described TS.
35    pub original_network_id: u16,
36    /// Raw descriptor bytes for this transport stream.
37    /// Per-TS descriptor loop. Serializes as the typed descriptor sequence;
38    /// `.raw()` yields the wire bytes.
39    pub descriptors: DescriptorLoop<'a>,
40}
41
42/// Bouquet Association Table.
43#[derive(Debug, Clone, PartialEq, Eq)]
44#[cfg_attr(feature = "serde", derive(serde::Serialize))]
45pub struct Bat<'a> {
46    /// Bouquet identifier (table_id_extension at bytes 3-4).
47    pub bouquet_id: u16,
48    /// 5-bit version_number.
49    pub version_number: u8,
50    /// current_next_indicator bit.
51    pub current_next_indicator: bool,
52    /// section_number in the sub-table sequence.
53    pub section_number: u8,
54    /// last_section_number in the sub-table sequence.
55    pub last_section_number: u8,
56    /// Raw bouquet-descriptor bytes (may contain bouquet_name_descriptor 0x47).
57    /// Bouquet descriptor loop. Serializes as the typed descriptor sequence;
58    /// `.raw()` yields the wire bytes.
59    pub bouquet_descriptors: DescriptorLoop<'a>,
60    /// Transport-stream loop entries in wire order.
61    pub transport_streams: Vec<BatTransportStream<'a>>,
62}
63
64impl<'a> Bat<'a> {
65    /// Walk the bouquet_descriptors looking for the first bouquet_name_descriptor
66    /// (tag 0x47). Returns the decoded UTF-8 name, or `None` if not present.
67    pub fn bouquet_name(&self) -> Option<String> {
68        let mut pos = 0usize;
69        while pos + 2 <= self.bouquet_descriptors.len() {
70            let tag = self.bouquet_descriptors[pos];
71            let len = self.bouquet_descriptors[pos + 1] as usize;
72            let next = pos + 2 + len;
73            if next > self.bouquet_descriptors.len() {
74                break;
75            }
76            if tag == DESCRIPTOR_TAG_BOUQUET_NAME {
77                let name_bytes = &self.bouquet_descriptors[pos + 2..next];
78                return Some(crate::text::decode(name_bytes).into_owned());
79            }
80            pos = next;
81        }
82        None
83    }
84}
85
86impl<'a> Parse<'a> for Bat<'a> {
87    type Error = crate::error::Error;
88    fn parse(bytes: &'a [u8]) -> Result<Self> {
89        let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + 2 + CRC_LEN;
90        if bytes.len() < min_len {
91            return Err(Error::BufferTooShort {
92                need: min_len,
93                have: bytes.len(),
94                what: "Bat",
95            });
96        }
97
98        if bytes[0] != TABLE_ID {
99            return Err(Error::UnexpectedTableId {
100                table_id: bytes[0],
101                what: "Bat",
102                expected: &[TABLE_ID],
103            });
104        }
105
106        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
107        let total = MIN_HEADER_LEN + section_length as usize;
108        if bytes.len() < total {
109            return Err(Error::SectionLengthOverflow {
110                declared: section_length as usize,
111                available: bytes.len() - MIN_HEADER_LEN,
112            });
113        }
114
115        // Extension header bytes [3..8]:
116        // bytes[3..5] = bouquet_id (table_id_extension)
117        // bytes[5]    = reserved(2) | version_number(5) | current_next_indicator(1)
118        // bytes[6]    = section_number
119        // bytes[7]    = last_section_number
120        let bouquet_id = u16::from_be_bytes([bytes[3], bytes[4]]);
121        let version_number = (bytes[5] >> 1) & 0x1F;
122        let current_next_indicator = (bytes[5] & 0x01) != 0;
123        let section_number = bytes[6];
124        let last_section_number = bytes[7];
125
126        // bytes[8..10] = reserved(4) | bouquet_descriptors_length(12)
127        let bouquet_descriptors_length = (((bytes[8] & 0x0F) as usize) << 8) | bytes[9] as usize;
128
129        let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
130        let bouquet_desc_end = bouquet_desc_start + bouquet_descriptors_length;
131
132        if bouquet_desc_end > total - CRC_LEN {
133            return Err(Error::SectionLengthOverflow {
134                declared: bouquet_descriptors_length,
135                available: (total - CRC_LEN).saturating_sub(bouquet_desc_start),
136            });
137        }
138
139        let bouquet_descriptors = DescriptorLoop::new(&bytes[bouquet_desc_start..bouquet_desc_end]);
140
141        // Transport stream loop: starts right after bouquet_descriptors.
142        // First 2 bytes: reserved(4) | transport_stream_loop_length(12).
143        let ts_loop_start = bouquet_desc_end;
144        let ts_loop_end = total - CRC_LEN;
145
146        if ts_loop_end < ts_loop_start + 2 {
147            return Err(Error::BufferTooShort {
148                need: 2,
149                have: ts_loop_end - ts_loop_start,
150                what: "Bat transport_stream_loop length header",
151            });
152        }
153
154        let transport_stream_loop_length =
155            (((bytes[ts_loop_start] & 0x0F) as usize) << 8) | bytes[ts_loop_start + 1] as usize;
156
157        let loop_end = ts_loop_start + 2 + transport_stream_loop_length;
158        if loop_end > ts_loop_end {
159            return Err(Error::SectionLengthOverflow {
160                declared: transport_stream_loop_length,
161                available: ts_loop_end - (ts_loop_start + 2),
162            });
163        }
164
165        let mut transport_streams = Vec::new();
166        let mut pos = ts_loop_start + 2;
167        while pos < loop_end {
168            if pos + TS_HEADER_LEN > loop_end {
169                return Err(Error::BufferTooShort {
170                    need: pos + TS_HEADER_LEN,
171                    have: loop_end,
172                    what: "Bat transport_stream_entry",
173                });
174            }
175
176            let transport_stream_id = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
177            let original_network_id = u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]);
178            let transport_descriptors_length =
179                (((bytes[pos + 4] & 0x0F) as usize) << 8) | bytes[pos + 5] as usize;
180
181            let desc_start = pos + TS_HEADER_LEN;
182            let desc_end = desc_start + transport_descriptors_length;
183
184            if desc_end > loop_end {
185                return Err(Error::SectionLengthOverflow {
186                    declared: transport_descriptors_length,
187                    available: loop_end - desc_start,
188                });
189            }
190
191            transport_streams.push(BatTransportStream {
192                transport_stream_id,
193                original_network_id,
194                descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
195            });
196
197            pos = desc_end;
198        }
199
200        // CRC is NOT verified here — crate-wide contract: table parsers trust
201        // their input and CRC validation is the framing layer's job
202        // (`Section::validate_crc`). BAT used to be the lone exception, which
203        // made the family contract inconsistent.
204
205        Ok(Bat {
206            bouquet_id,
207            version_number,
208            current_next_indicator,
209            section_number,
210            last_section_number,
211            bouquet_descriptors,
212            transport_streams,
213        })
214    }
215}
216
217impl Serialize for Bat<'_> {
218    type Error = crate::error::Error;
219    fn serialized_len(&self) -> usize {
220        let bouquet_desc_len = self.bouquet_descriptors.len();
221        let ts_bytes: usize = self
222            .transport_streams
223            .iter()
224            .map(|ts| TS_HEADER_LEN + ts.descriptors.len())
225            .sum();
226        MIN_HEADER_LEN
227            + EXTENSION_HEADER_LEN
228            + POST_EXTENSION_LEN
229            + bouquet_desc_len
230            + 2 // transport_stream_loop_length header
231            + ts_bytes
232            + CRC_LEN
233    }
234
235    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
236        let len = self.serialized_len();
237        if buf.len() < len {
238            return Err(Error::OutputBufferTooSmall {
239                need: len,
240                have: buf.len(),
241            });
242        }
243
244        let section_length: u16 = (len - MIN_HEADER_LEN) as u16;
245        buf[0] = TABLE_ID;
246        buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
247        buf[2] = (section_length & 0xFF) as u8;
248
249        // Extension header.
250        buf[3..5].copy_from_slice(&self.bouquet_id.to_be_bytes());
251        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
252        buf[6] = self.section_number;
253        buf[7] = self.last_section_number;
254
255        // Bouquet descriptors length field.
256        let bdl = self.bouquet_descriptors.len() as u16;
257        buf[8] = 0xF0 | ((bdl >> 8) as u8 & 0x0F);
258        buf[9] = (bdl & 0xFF) as u8;
259
260        let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
261        buf[bouquet_desc_start..bouquet_desc_start + self.bouquet_descriptors.len()]
262            .copy_from_slice(self.bouquet_descriptors.raw());
263
264        let ts_loop_start = bouquet_desc_start + self.bouquet_descriptors.len();
265        let ts_loop_length: u16 = (len - ts_loop_start - 2 - CRC_LEN) as u16;
266        buf[ts_loop_start] = 0xF0 | ((ts_loop_length >> 8) as u8 & 0x0F);
267        buf[ts_loop_start + 1] = (ts_loop_length & 0xFF) as u8;
268
269        let mut pos = ts_loop_start + 2;
270        for ts in &self.transport_streams {
271            buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
272            buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
273            let tdl = ts.descriptors.len() as u16;
274            buf[pos + 4] = 0xF0 | ((tdl >> 8) as u8 & 0x0F);
275            buf[pos + 5] = (tdl & 0xFF) as u8;
276            let desc_start = pos + TS_HEADER_LEN;
277            buf[desc_start..desc_start + ts.descriptors.len()]
278                .copy_from_slice(ts.descriptors.raw());
279            pos = desc_start + ts.descriptors.len();
280        }
281
282        // CRC: compute over everything up to (but not including) the CRC slot.
283        let crc_pos = len - CRC_LEN;
284        let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
285        buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
286        Ok(len)
287    }
288}
289
290impl<'a> Table<'a> for Bat<'a> {
291    const TABLE_ID: u8 = TABLE_ID;
292    const PID: u16 = PID;
293}
294
295impl<'a> crate::traits::TableDef<'a> for Bat<'a> {
296    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
297    const NAME: &'static str = "BOUQUET_ASSOCIATION";
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    type TestTs = (u16, u16, Vec<u8>);
305
306    /// Build a complete BAT section (with valid CRC).
307    fn build_bat(
308        bouquet_id: u16,
309        version: u8,
310        section_number: u8,
311        last_section_number: u8,
312        bouquet_desc: &[u8],
313        transport_streams: &[TestTs],
314    ) -> Vec<u8> {
315        let ts_streams: Vec<BatTransportStream> = transport_streams
316            .iter()
317            .map(|(tsid, onid, d)| BatTransportStream {
318                transport_stream_id: *tsid,
319                original_network_id: *onid,
320                descriptors: DescriptorLoop::new(d),
321            })
322            .collect();
323        let bat = Bat {
324            bouquet_id,
325            version_number: version,
326            current_next_indicator: true,
327            section_number,
328            last_section_number,
329            bouquet_descriptors: DescriptorLoop::new(bouquet_desc),
330            transport_streams: ts_streams,
331        };
332        let mut buf = vec![0u8; bat.serialized_len()];
333        bat.serialize_into(&mut buf).unwrap();
334        buf
335    }
336
337    #[test]
338    fn parse_extracts_bouquet_id() {
339        let bytes = build_bat(0x1234, 3, 0, 0, &[], &[]);
340        let bat = Bat::parse(&bytes).unwrap();
341        assert_eq!(bat.bouquet_id, 0x1234);
342    }
343
344    #[test]
345    fn parse_extracts_version_and_cni() {
346        let bytes = build_bat(0x0001, 7, 0, 0, &[], &[]);
347        let bat = Bat::parse(&bytes).unwrap();
348        assert_eq!(bat.version_number, 7);
349        assert!(bat.current_next_indicator);
350    }
351
352    #[test]
353    fn parse_extracts_section_numbers() {
354        let bytes = build_bat(0x0001, 0, 2, 4, &[], &[]);
355        let bat = Bat::parse(&bytes).unwrap();
356        assert_eq!(bat.section_number, 2);
357        assert_eq!(bat.last_section_number, 4);
358    }
359
360    #[test]
361    fn bouquet_name_descriptor_extracted() {
362        let name_desc: Vec<u8> = vec![
363            DESCRIPTOR_TAG_BOUQUET_NAME,
364            0x05,
365            b'H',
366            b'E',
367            b'L',
368            b'L',
369            b'O',
370        ];
371        let bytes = build_bat(0x0001, 0, 0, 0, &name_desc, &[]);
372        let bat = Bat::parse(&bytes).unwrap();
373        assert_eq!(bat.bouquet_name(), Some("HELLO".to_string()));
374    }
375
376    #[test]
377    fn bouquet_name_returns_none_when_no_bouquet_name_descriptor() {
378        // Non-bouquet-name descriptor (tag 0x40 = network_name, also human-readable).
379        let other_desc: Vec<u8> = vec![0x40, 0x03, b'A', b'B', b'C'];
380        let bytes = build_bat(0x0001, 0, 0, 0, &other_desc, &[]);
381        let bat = Bat::parse(&bytes).unwrap();
382        assert_eq!(bat.bouquet_name(), None);
383    }
384
385    #[test]
386    fn private_descriptors_preserved_in_bouquet_descriptors() {
387        // Private descriptor tag (>= 0x80). Per anti-instructions, surface as raw bytes.
388        let private_desc: Vec<u8> = vec![0x80, 0x04, 0xDE, 0xAD, 0xBE, 0xEF];
389        let bytes = build_bat(0x0001, 0, 0, 0, &private_desc, &[]);
390        let bat = Bat::parse(&bytes).unwrap();
391        assert_eq!(bat.bouquet_descriptors.raw(), &private_desc[..]);
392    }
393
394    #[test]
395    fn parse_transport_stream_entries() {
396        let bytes = build_bat(
397            0x0001,
398            0,
399            0,
400            0,
401            &[],
402            &[
403                (
404                    0x1234,
405                    0x0020,
406                    vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05],
407                ),
408                (0x5678, 0x0020, vec![]),
409            ],
410        );
411        let bat = Bat::parse(&bytes).unwrap();
412        assert_eq!(bat.transport_streams.len(), 2);
413        assert_eq!(bat.transport_streams[0].transport_stream_id, 0x1234);
414        assert_eq!(bat.transport_streams[0].original_network_id, 0x0020);
415        assert_eq!(
416            bat.transport_streams[0].descriptors.raw(),
417            &[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
418        );
419        assert_eq!(bat.transport_streams[1].transport_stream_id, 0x5678);
420        assert_eq!(bat.transport_streams[1].descriptors.len(), 0);
421    }
422
423    #[test]
424    fn bat_with_no_transport_streams_parses_ok() {
425        let bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
426        let bat = Bat::parse(&bytes).unwrap();
427        assert!(bat.transport_streams.is_empty());
428    }
429
430    #[test]
431    fn serialize_round_trip() {
432        let name_desc: Vec<u8> = vec![DESCRIPTOR_TAG_BOUQUET_NAME, 0x04, b'T', b'E', b'S', b'T'];
433        let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
434        let bat = Bat {
435            bouquet_id: 0x4242,
436            version_number: 5,
437            current_next_indicator: true,
438            section_number: 1,
439            last_section_number: 2,
440            bouquet_descriptors: DescriptorLoop::new(&name_desc),
441            transport_streams: vec![
442                BatTransportStream {
443                    transport_stream_id: 0x1234,
444                    original_network_id: 0x0020,
445                    descriptors: DescriptorLoop::new(&ts_desc),
446                },
447                BatTransportStream {
448                    transport_stream_id: 0x5678,
449                    original_network_id: 0x0020,
450                    descriptors: DescriptorLoop::new(&[]),
451                },
452            ],
453        };
454        let mut buf = vec![0u8; bat.serialized_len()];
455        bat.serialize_into(&mut buf).unwrap();
456        let parsed = Bat::parse(&buf).unwrap();
457        assert_eq!(bat, parsed);
458    }
459
460    /// Crate-wide contract: table parsers do NOT verify CRC — that is the
461    /// framing layer's job (`Section::validate_crc`). A corrupted-CRC BAT
462    /// still parses; callers wanting integrity check the Section first.
463    #[test]
464    fn bat_parse_does_not_verify_crc() {
465        let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
466        bytes[3] ^= 0xFF; // corrupt bouquet_id high byte → CRC now wrong
467        let bat = Bat::parse(&bytes).unwrap();
468        assert_eq!(bat.bouquet_id, 0x0001 ^ 0xFF00);
469    }
470
471    #[test]
472    fn parse_rejects_short_buffer() {
473        let err = Bat::parse(&[0x4A, 0x00]).unwrap_err();
474        assert!(matches!(err, Error::BufferTooShort { .. }));
475    }
476
477    #[test]
478    fn parse_rejects_wrong_table_id() {
479        let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
480        bytes[0] = 0x00;
481        let err = Bat::parse(&bytes).unwrap_err();
482        assert!(matches!(
483            err,
484            Error::UnexpectedTableId { table_id: 0x00, .. }
485        ));
486    }
487
488    #[test]
489    fn serialize_too_small_buffer_returns_error() {
490        let bat = Bat {
491            bouquet_id: 0x0001,
492            version_number: 0,
493            current_next_indicator: true,
494            section_number: 0,
495            last_section_number: 0,
496            bouquet_descriptors: DescriptorLoop::new(&[]),
497            transport_streams: vec![],
498        };
499        let mut buf = vec![0u8; 2];
500        let err = bat.serialize_into(&mut buf).unwrap_err();
501        assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
502    }
503}