use crate::descriptors::DescriptorLoop;
use crate::error::{Error, Result};
use alloc::string::String;
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};
pub const TABLE_ID: u8 = 0x4A;
pub const PID: mpeg_ts::pid::Pid = mpeg_ts::pid::Pid::new(0x0011);
pub const DESCRIPTOR_TAG_BOUQUET_NAME: u8 = 0x47;
const MIN_HEADER_LEN: usize = 3;
const EXTENSION_HEADER_LEN: usize = 5;
const POST_EXTENSION_LEN: usize = 2;
use super::CRC_LEN;
const TS_HEADER_LEN: usize = 6;
const MIN_SECTION_LEN: usize = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + CRC_LEN;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct BatTransportStream<'a> {
pub transport_stream_id: u16,
pub original_network_id: u16,
pub descriptors: DescriptorLoop<'a>,
#[cfg_attr(feature = "serde", serde(skip))]
pub reserved_future_use: u8,
}
impl<'a> BatTransportStream<'a> {
#[must_use]
pub fn new(
transport_stream_id: u16,
original_network_id: u16,
descriptors: DescriptorLoop<'a>,
) -> Self {
Self {
transport_stream_id,
original_network_id,
descriptors,
reserved_future_use: super::RESERVED_4,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct BatSection<'a> {
pub bouquet_id: u16,
pub version_number: u8,
pub current_next_indicator: bool,
pub section_number: u8,
pub last_section_number: u8,
pub bouquet_descriptors: DescriptorLoop<'a>,
pub transport_streams: Vec<BatTransportStream<'a>>,
#[cfg_attr(feature = "serde", serde(skip))]
pub bits: super::SectionBits,
#[cfg_attr(feature = "serde", serde(skip))]
pub reserved_bouquet_descriptors_length: u8,
#[cfg_attr(feature = "serde", serde(skip))]
pub reserved_transport_stream_loop_length: u8,
}
impl<'a> BatSection<'a> {
#[must_use]
pub fn new(
bouquet_id: u16,
version_number: u8,
current_next_indicator: bool,
section_number: u8,
last_section_number: u8,
bouquet_descriptors: DescriptorLoop<'a>,
transport_streams: Vec<BatTransportStream<'a>>,
) -> Self {
Self {
bouquet_id,
version_number,
current_next_indicator,
section_number,
last_section_number,
bouquet_descriptors,
transport_streams,
bits: super::SectionBits::dvb(),
reserved_bouquet_descriptors_length: super::RESERVED_4,
reserved_transport_stream_loop_length: super::RESERVED_4,
}
}
}
impl BatSection<'_> {
pub fn bouquet_name(&self) -> Option<String> {
let mut pos = 0usize;
while pos + 2 <= self.bouquet_descriptors.len() {
let tag = self.bouquet_descriptors[pos];
let len = self.bouquet_descriptors[pos + 1] as usize;
let next = pos + 2 + len;
if next > self.bouquet_descriptors.len() {
break;
}
if tag == DESCRIPTOR_TAG_BOUQUET_NAME {
let name_bytes = &self.bouquet_descriptors[pos + 2..next];
return Some(crate::text::decode(name_bytes).into_owned());
}
pos = next;
}
None
}
}
impl<'a> Parse<'a> for BatSection<'a> {
type Error = crate::error::Error;
fn parse(bytes: &'a [u8]) -> Result<Self> {
let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN + 2 + CRC_LEN;
if bytes.len() < min_len {
return Err(Error::BufferTooShort {
need: min_len,
have: bytes.len(),
what: "BatSection",
});
}
if bytes[0] != TABLE_ID {
return Err(Error::UnexpectedTableId {
table_id: bytes[0],
what: "BatSection",
expected: &[TABLE_ID],
});
}
let section_length = super::section_length_of(bytes);
let total = super::check_section_length(
bytes.len(),
MIN_HEADER_LEN,
section_length,
MIN_SECTION_LEN,
)?;
let bouquet_id = crate::wire::be_u16(bytes, 3, "bat")?;
let version_number = super::version_number_of(bytes[5]);
let current_next_indicator = super::current_next_of(bytes[5]);
let section_number = bytes[6];
let last_section_number = bytes[7];
let bouquet_descriptors_length = super::desc_loop_len_of(bytes[8], bytes[9]);
let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
let bouquet_desc_end = bouquet_desc_start + bouquet_descriptors_length;
if bouquet_desc_end > total - CRC_LEN {
return Err(Error::SectionLengthOverflow {
declared: bouquet_descriptors_length,
available: (total - CRC_LEN).saturating_sub(bouquet_desc_start),
});
}
let bouquet_descriptors = DescriptorLoop::new(&bytes[bouquet_desc_start..bouquet_desc_end]);
let ts_loop_start = bouquet_desc_end;
let ts_loop_end = total - CRC_LEN;
if ts_loop_end < ts_loop_start + 2 {
return Err(Error::BufferTooShort {
need: 2,
have: ts_loop_end - ts_loop_start,
what: "BatSection transport_stream_loop length header",
});
}
let transport_stream_loop_length =
super::desc_loop_len_of(bytes[ts_loop_start], bytes[ts_loop_start + 1]);
let loop_end = ts_loop_start + 2 + transport_stream_loop_length;
if loop_end > ts_loop_end {
return Err(Error::SectionLengthOverflow {
declared: transport_stream_loop_length,
available: ts_loop_end - (ts_loop_start + 2),
});
}
super::check_loop_reaches_crc(
loop_end,
ts_loop_end,
"BatSection trailing bytes after transport stream loop",
)?;
let mut transport_streams = Vec::new();
let mut pos = ts_loop_start + 2;
while pos < loop_end {
if pos + TS_HEADER_LEN > loop_end {
return Err(Error::BufferTooShort {
need: pos + TS_HEADER_LEN,
have: loop_end,
what: "BatSection transport_stream_entry",
});
}
let hdr = &bytes[pos..pos + TS_HEADER_LEN];
let transport_stream_id = crate::wire::be_u16(hdr, 0, "bat")?;
let original_network_id = crate::wire::be_u16(hdr, 2, "bat")?;
let transport_descriptors_length =
super::desc_loop_len_of(bytes[pos + 4], bytes[pos + 5]);
let desc_start = pos + TS_HEADER_LEN;
let desc_end = desc_start + transport_descriptors_length;
if desc_end > loop_end {
return Err(Error::SectionLengthOverflow {
declared: transport_descriptors_length,
available: loop_end - desc_start,
});
}
transport_streams.push(BatTransportStream {
transport_stream_id,
original_network_id,
descriptors: DescriptorLoop::new(&bytes[desc_start..desc_end]),
reserved_future_use: super::len_reserved_of(bytes[pos + 4]),
});
pos = desc_end;
}
Ok(BatSection {
bouquet_id,
version_number,
current_next_indicator,
section_number,
last_section_number,
bouquet_descriptors,
transport_streams,
bits: super::SectionBits::parse(bytes[1], Some(bytes[5])),
reserved_bouquet_descriptors_length: super::len_reserved_of(bytes[8]),
reserved_transport_stream_loop_length: super::len_reserved_of(bytes[ts_loop_start]),
})
}
}
impl Serialize for BatSection<'_> {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
let bouquet_desc_len = self.bouquet_descriptors.len();
let ts_bytes: usize = self
.transport_streams
.iter()
.map(|ts| TS_HEADER_LEN + ts.descriptors.len())
.sum();
MIN_HEADER_LEN
+ EXTENSION_HEADER_LEN
+ POST_EXTENSION_LEN
+ bouquet_desc_len
+ 2 + ts_bytes
+ CRC_LEN
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let len = self.serialized_len();
if buf.len() < len {
return Err(Error::OutputBufferTooSmall {
need: len,
have: buf.len(),
});
}
buf[0] = TABLE_ID;
buf[1] = self.bits.b1()?;
super::write_section_length(buf, len - MIN_HEADER_LEN)?;
buf[3..5].copy_from_slice(&self.bouquet_id.to_be_bytes());
buf[5] = self
.bits
.b5(self.version_number, self.current_next_indicator)?;
buf[6] = self.section_number;
buf[7] = self.last_section_number;
let bdl = broadcast_common::len::fit_bits(
self.bouquet_descriptors.len() as u64,
12,
"bouquet_descriptors_length",
)?;
super::write_desc_loop_len_r(
&mut buf[8..10],
bdl as usize,
self.reserved_bouquet_descriptors_length,
)?;
let bouquet_desc_start = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + POST_EXTENSION_LEN;
buf[bouquet_desc_start..bouquet_desc_start + self.bouquet_descriptors.len()]
.copy_from_slice(self.bouquet_descriptors.raw());
let ts_loop_start = bouquet_desc_start + self.bouquet_descriptors.len();
let ts_loop_length = broadcast_common::len::fit_bits(
(len - ts_loop_start - 2 - CRC_LEN) as u64,
12,
"transport_stream_loop_length",
)?;
super::write_desc_loop_len_r(
&mut buf[ts_loop_start..ts_loop_start + 2],
ts_loop_length as usize,
self.reserved_transport_stream_loop_length,
)?;
let mut pos = ts_loop_start + 2;
for ts in &self.transport_streams {
buf[pos..pos + 2].copy_from_slice(&ts.transport_stream_id.to_be_bytes());
buf[pos + 2..pos + 4].copy_from_slice(&ts.original_network_id.to_be_bytes());
let tdl = broadcast_common::len::fit_bits(
ts.descriptors.len() as u64,
12,
"transport_descriptors_length",
)?;
super::write_desc_loop_len_r(
&mut buf[pos + 4..pos + 6],
tdl as usize,
ts.reserved_future_use,
)?;
let desc_start = pos + TS_HEADER_LEN;
buf[desc_start..desc_start + ts.descriptors.len()]
.copy_from_slice(ts.descriptors.raw());
pos = desc_start + ts.descriptors.len();
}
let crc_pos = len - CRC_LEN;
super::write_crc(buf, crc_pos);
Ok(len)
}
}
impl<'a> crate::traits::TableDef<'a> for BatSection<'a> {
const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
const NAME: &'static str = "BOUQUET_ASSOCIATION";
}
#[cfg(test)]
mod tests {
use super::*;
type TestTs = (u16, u16, Vec<u8>);
fn build_bat(
bouquet_id: u16,
version: u8,
section_number: u8,
last_section_number: u8,
bouquet_desc: &[u8],
transport_streams: &[TestTs],
) -> Vec<u8> {
let ts_streams: Vec<BatTransportStream> = transport_streams
.iter()
.map(|(tsid, onid, d)| BatTransportStream::new(*tsid, *onid, DescriptorLoop::new(d)))
.collect();
let bat = BatSection::new(
bouquet_id,
version,
true,
section_number,
last_section_number,
DescriptorLoop::new(bouquet_desc),
ts_streams,
);
let mut buf = vec![0u8; bat.serialized_len()];
bat.serialize_into(&mut buf).unwrap();
buf
}
#[test]
fn parse_extracts_bouquet_id() {
let bytes = build_bat(0x1234, 3, 0, 0, &[], &[]);
let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.bouquet_id, 0x1234);
}
#[test]
fn parse_extracts_version_and_cni() {
let bytes = build_bat(0x0001, 7, 0, 0, &[], &[]);
let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.version_number, 7);
assert!(bat.current_next_indicator);
}
#[test]
fn parse_extracts_section_numbers() {
let bytes = build_bat(0x0001, 0, 2, 4, &[], &[]);
let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.section_number, 2);
assert_eq!(bat.last_section_number, 4);
}
#[test]
fn bouquet_name_descriptor_extracted() {
let name_desc: Vec<u8> = vec![
DESCRIPTOR_TAG_BOUQUET_NAME,
0x05,
b'H',
b'E',
b'L',
b'L',
b'O',
];
let bytes = build_bat(0x0001, 0, 0, 0, &name_desc, &[]);
let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.bouquet_name(), Some("HELLO".to_string()));
}
#[test]
fn bouquet_name_returns_none_when_no_bouquet_name_descriptor() {
let other_desc: Vec<u8> = vec![0x40, 0x03, b'A', b'B', b'C'];
let bytes = build_bat(0x0001, 0, 0, 0, &other_desc, &[]);
let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.bouquet_name(), None);
}
#[test]
fn private_descriptors_preserved_in_bouquet_descriptors() {
let private_desc: Vec<u8> = vec![0x80, 0x04, 0xDE, 0xAD, 0xBE, 0xEF];
let bytes = build_bat(0x0001, 0, 0, 0, &private_desc, &[]);
let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.bouquet_descriptors.raw(), &private_desc[..]);
}
#[test]
fn parse_transport_stream_entries() {
let bytes = build_bat(
0x0001,
0,
0,
0,
&[],
&[
(
0x1234,
0x0020,
vec![0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05],
),
(0x5678, 0x0020, vec![]),
],
);
let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.transport_streams.len(), 2);
assert_eq!(bat.transport_streams[0].transport_stream_id, 0x1234);
assert_eq!(bat.transport_streams[0].original_network_id, 0x0020);
assert_eq!(
bat.transport_streams[0].descriptors.raw(),
&[0x43, 0x07, 0x0B, 0xB8, 0x00, 0x02, 0x00, 0x05][..]
);
assert_eq!(bat.transport_streams[1].transport_stream_id, 0x5678);
assert_eq!(bat.transport_streams[1].descriptors.len(), 0);
}
#[test]
fn bat_with_no_transport_streams_parses_ok() {
let bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
let bat = BatSection::parse(&bytes).unwrap();
assert!(bat.transport_streams.is_empty());
}
#[test]
fn serialize_round_trip() {
let name_desc: Vec<u8> = vec![DESCRIPTOR_TAG_BOUQUET_NAME, 0x04, b'T', b'E', b'S', b'T'];
let ts_desc: [u8; 3] = [0x43, 0x01, 0x01];
let bat = BatSection::new(
0x4242,
5,
true,
1,
2,
DescriptorLoop::new(&name_desc),
vec![
BatTransportStream::new(0x1234, 0x0020, DescriptorLoop::new(&ts_desc)),
BatTransportStream::new(0x5678, 0x0020, DescriptorLoop::new(&[])),
],
);
let mut buf = vec![0u8; bat.serialized_len()];
bat.serialize_into(&mut buf).unwrap();
let parsed = BatSection::parse(&buf).unwrap();
assert_eq!(bat, parsed);
}
#[test]
fn bat_parse_does_not_verify_crc() {
let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
bytes[3] ^= 0xFF; let bat = BatSection::parse(&bytes).unwrap();
assert_eq!(bat.bouquet_id, 0x0001 ^ 0xFF00);
}
#[test]
fn parse_rejects_short_buffer() {
let err = BatSection::parse(&[0x4A, 0x00]).unwrap_err();
assert!(matches!(err, Error::BufferTooShort { .. }));
}
#[test]
fn parse_rejects_wrong_table_id() {
let mut bytes = build_bat(0x0001, 0, 0, 0, &[], &[]);
bytes[0] = 0x00;
let err = BatSection::parse(&bytes).unwrap_err();
assert!(matches!(
err,
Error::UnexpectedTableId { table_id: 0x00, .. }
));
}
#[test]
fn serialize_too_small_buffer_returns_error() {
let bat = BatSection::new(0x0001, 0, true, 0, 0, DescriptorLoop::new(&[]), vec![]);
let mut buf = vec![0u8; 2];
let err = bat.serialize_into(&mut buf).unwrap_err();
assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
}
#[test]
fn parse_rejects_zero_section_length() {
let mut buf = vec![0u8; 64];
buf[0] = TABLE_ID;
buf[1] = 0xF0;
buf[2] = 0x00;
for b in &mut buf[3..] {
*b = 0xFF;
}
assert!(matches!(
BatSection::parse(&buf).unwrap_err(),
Error::SectionLengthOverflow { .. }
));
}
#[test]
fn serialize_rejects_bouquet_descriptors_exceeding_section_length() {
let desc = vec![0xAAu8; 4083];
let bat = BatSection::new(1, 0, true, 0, 0, DescriptorLoop::new(&desc), vec![]);
let mut buf = vec![0u8; bat.serialized_len()];
assert!(matches!(
bat.serialize_into(&mut buf).unwrap_err(),
Error::FieldOverflow(_)
));
}
#[test]
fn serialize_accepts_bouquet_descriptors_at_section_length_boundary() {
let desc = vec![0xAAu8; 4082];
let bat = BatSection::new(1, 0, true, 0, 0, DescriptorLoop::new(&desc), vec![]);
let mut buf = vec![0u8; bat.serialized_len()];
bat.serialize_into(&mut buf).expect("boundary fits");
let reparsed = BatSection::parse(&buf).expect("reparse");
assert_eq!(
bat.bouquet_descriptors.raw(),
reparsed.bouquet_descriptors.raw()
);
}
}