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