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