use crate::error::{Error, Result};
use broadcast_common::crc32_mpeg2 as crc;
use broadcast_common::len::{need_in, need_out};
use broadcast_common::{Parse, Serialize};
const MIN_HEADER_LEN: usize = 3;
const LONG_FORM_EXTRA: usize = 5;
const CRC_LEN: usize = 4;
const SSI_MASK: u8 = 0x80;
const PRIVATE_INDICATOR_MASK: u8 = 0x40;
const BYTE1_RESERVED_BITS: u8 = 0x30;
const VERSION_NUMBER_MASK: u8 = 0x1F;
const BYTE5_RESERVED_BITS: u8 = 0xC0;
const CURRENT_NEXT_MASK: u8 = 0x01;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Section<'a> {
pub table_id: u8,
pub section_syntax_indicator: bool,
pub private_indicator: bool,
pub section_length: u16,
pub extension_id: u16,
pub version_number: u8,
pub current_next_indicator: bool,
pub section_number: u8,
pub last_section_number: u8,
pub payload: &'a [u8],
pub crc32: Option<u32>,
}
impl<'a> Section<'a> {
#[inline]
pub fn payload(&self) -> &'a [u8] {
self.payload
}
pub fn validate_crc(&self, raw: &[u8]) -> Result<()> {
let expected = match self.crc32 {
None => return Ok(()), Some(v) => v,
};
need_in(raw, CRC_LEN, "CRC suffix in validate_crc")?;
let covered = &raw[..raw.len() - CRC_LEN];
let computed = crc::compute(covered);
if computed != expected {
return Err(Error::CrcMismatch(broadcast_common::error::CrcMismatch {
what: "section",
computed,
expected,
}));
}
Ok(())
}
}
impl<'a> Parse<'a> for Section<'a> {
type Error = crate::error::Error;
fn parse(bytes: &'a [u8]) -> Result<Self> {
need_in(bytes, MIN_HEADER_LEN, "section header")?;
let table_id = bytes[0];
let section_syntax_indicator = (bytes[1] & SSI_MASK) != 0;
let private_indicator = (bytes[1] & PRIVATE_INDICATOR_MASK) != 0;
let total = crate::ts::section_total_len(bytes)
.expect("bytes.len() >= MIN_HEADER_LEN checked above");
let section_length = (total - MIN_HEADER_LEN) as u16;
if bytes.len() < total {
return Err(Error::SectionLengthOverflow {
declared: total,
available: bytes.len(),
});
}
let section_bytes = &bytes[..total];
if !section_syntax_indicator {
let payload = §ion_bytes[MIN_HEADER_LEN..];
return Ok(Section {
table_id,
section_syntax_indicator,
private_indicator,
section_length,
extension_id: 0,
version_number: 0,
current_next_indicator: false,
section_number: 0,
last_section_number: 0,
payload,
crc32: None,
});
}
let min_long = MIN_HEADER_LEN + LONG_FORM_EXTRA + CRC_LEN;
need_in(
section_bytes,
min_long,
"long-form section extension header + CRC",
)?;
let extension_id = ((bytes[3] as u16) << 8) | (bytes[4] as u16);
let version_number = (bytes[5] >> 1) & VERSION_NUMBER_MASK;
let current_next_indicator = (bytes[5] & CURRENT_NEXT_MASK) != 0;
let section_number = bytes[6];
let last_section_number = bytes[7];
let payload_start = MIN_HEADER_LEN + LONG_FORM_EXTRA;
let payload_end = total - CRC_LEN;
let payload = §ion_bytes[payload_start..payload_end];
let crc_offset = total - CRC_LEN;
let crc32 = Some(
((section_bytes[crc_offset] as u32) << 24)
| ((section_bytes[crc_offset + 1] as u32) << 16)
| ((section_bytes[crc_offset + 2] as u32) << 8)
| (section_bytes[crc_offset + 3] as u32),
);
Ok(Section {
table_id,
section_syntax_indicator,
private_indicator,
section_length,
extension_id,
version_number,
current_next_indicator,
section_number,
last_section_number,
payload,
crc32,
})
}
}
impl Serialize for Section<'_> {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
usize::from(self.section_length) + MIN_HEADER_LEN
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let need = self.serialized_len();
need_out(buf, need)?;
let overhead = if self.section_syntax_indicator {
LONG_FORM_EXTRA + CRC_LEN
} else {
0
};
let expected_payload_len = usize::from(self.section_length).checked_sub(overhead);
if expected_payload_len != Some(self.payload.len()) {
return Err(Error::SectionPayloadLengthMismatch {
section_length: self.section_length,
expected: expected_payload_len.unwrap_or(0),
actual: self.payload.len(),
});
}
buf[0] = self.table_id;
let length_hi = ((self.section_length >> 8) as u8) & crate::ts::SECTION_LENGTH_HI_MASK;
let ssi = u8::from(self.section_syntax_indicator) << 7;
let pi = u8::from(self.private_indicator) << 6;
buf[1] = ssi | pi | BYTE1_RESERVED_BITS | length_hi;
buf[2] = self.section_length.to_be_bytes()[1];
if self.section_syntax_indicator {
buf[3..5].copy_from_slice(&self.extension_id.to_be_bytes());
let version = (self.version_number & VERSION_NUMBER_MASK) << 1;
let cni = u8::from(self.current_next_indicator);
buf[5] = BYTE5_RESERVED_BITS | version | cni;
buf[6] = self.section_number;
buf[7] = self.last_section_number;
let payload_start = MIN_HEADER_LEN + LONG_FORM_EXTRA;
let payload_end = payload_start + self.payload.len();
buf[payload_start..payload_end].copy_from_slice(self.payload);
let crc = self
.crc32
.unwrap_or_else(|| crc::compute(&buf[..payload_end]));
let crc_start = payload_end;
buf[crc_start..crc_start + CRC_LEN].copy_from_slice(&crc.to_be_bytes());
} else {
let payload_end = MIN_HEADER_LEN + self.payload.len();
buf[MIN_HEADER_LEN..payload_end].copy_from_slice(self.payload);
}
Ok(need)
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use alloc::vec::Vec;
use broadcast_common::crc32_mpeg2::compute as crc32;
fn make_long_section(
table_id: u8,
extension_id: u16,
version: u8,
current_next: bool,
section_number: u8,
last_section_number: u8,
payload: &[u8],
) -> Vec<u8> {
let section_length: u16 = (5 + payload.len() + 4) as u16;
let ver_cni = 0xC0u8 | ((version & 0x1F) << 1) | (current_next as u8);
let mut buf: Vec<u8> = vec![
table_id,
0x80 | 0x30 | ((section_length >> 8) as u8 & 0x0F),
(section_length & 0xFF) as u8,
(extension_id >> 8) as u8,
(extension_id & 0xFF) as u8,
ver_cni,
section_number,
last_section_number,
];
buf.extend_from_slice(payload);
let crc = crc32(&buf);
buf.push((crc >> 24) as u8);
buf.push((crc >> 16) as u8);
buf.push((crc >> 8) as u8);
buf.push(crc as u8);
buf
}
#[test]
fn parse_rejects_buffer_shorter_than_3_bytes() {
for bad_len in [0usize, 1, 2] {
let buf = vec![0x00u8; bad_len];
let err = Section::parse(&buf).unwrap_err();
assert!(
matches!(err, Error::BufferTooShort(broadcast_common::error::BufferTooShort { need: 3, have, .. }) if have == bad_len),
"expected BufferTooShort for len={bad_len}, got {err:?}"
);
}
}
#[test]
fn parse_reads_table_id_syntax_indicator_and_length() {
let raw = make_long_section(0x42, 0x1234, 3, true, 0, 0, &[0xAB]);
assert_eq!(raw.len(), 13);
let section = Section::parse(&raw).unwrap();
assert_eq!(section.table_id, 0x42);
assert!(section.section_syntax_indicator);
assert_eq!(section.section_length, 10);
}
#[test]
fn parse_rejects_when_section_length_exceeds_buffer() {
let buf = [
0x00u8, 0x80u8, 100u8, ];
let err = Section::parse(&buf).unwrap_err();
assert!(
matches!(
err,
Error::SectionLengthOverflow {
declared: 103,
available: 3
}
),
"expected SectionLengthOverflow, got {err:?}"
);
}
#[test]
fn parse_reads_extension_id_version_current_next_section_numbers() {
let raw = make_long_section(
0x02, 0xBEEF, 7, true, 2, 5, &[0x00, 0x00], );
let section = Section::parse(&raw).unwrap();
assert_eq!(section.extension_id, 0xBEEF);
assert_eq!(section.version_number, 7);
assert!(section.current_next_indicator);
assert_eq!(section.section_number, 2);
assert_eq!(section.last_section_number, 5);
}
#[test]
fn parse_reads_current_next_indicator_false() {
let raw = make_long_section(
0x02, 0xBEEF, 7, false, 2, 5, &[0x00, 0x00],
);
let section = Section::parse(&raw).unwrap();
assert!(!section.current_next_indicator);
assert_eq!(section.extension_id, 0xBEEF);
assert_eq!(section.version_number, 7);
assert_eq!(section.section_number, 2);
assert_eq!(section.last_section_number, 5);
}
#[test]
fn payload_slice_excludes_header_and_crc() {
let inner_payload = &[0x01u8, 0x02, 0x03, 0x04, 0x05];
let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, inner_payload);
let section = Section::parse(&raw).unwrap();
assert_eq!(section.payload(), inner_payload);
}
#[test]
fn validate_crc_accepts_matching_crc32() {
let raw = make_long_section(0x00, 0x0001, 1, true, 0, 0, &[0xDE, 0xAD, 0xBE, 0xEF]);
let section = Section::parse(&raw).unwrap();
section.validate_crc(&raw).expect("CRC should match");
}
#[test]
fn validate_crc_rejects_flipped_bit() {
let mut raw = make_long_section(0x00, 0x0001, 1, true, 0, 0, &[0xDE, 0xAD, 0xBE, 0xEF]);
raw[8] ^= 0x01;
let section = Section::parse(&raw).unwrap();
let err = section.validate_crc(&raw).unwrap_err();
assert!(
matches!(err, Error::CrcMismatch(..)),
"expected CrcMismatch, got {err:?}"
);
}
#[test]
fn validate_crc_rejects_raw_slice_shorter_than_crc_len() {
let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xDE, 0xAD]);
let section = Section::parse(&raw).unwrap();
let err = section.validate_crc(&[]).unwrap_err();
assert!(
matches!(
err,
Error::BufferTooShort(broadcast_common::error::BufferTooShort {
need: CRC_LEN,
..
})
),
"expected BufferTooShort(need=CRC_LEN), got {err:?}"
);
}
#[test]
fn short_form_section_has_no_crc() {
let buf = [
0x70u8, 0x70u8, 0x05u8, 0xE0, 0x00, 0x00, 0x00, 0x00,
];
let section = Section::parse(&buf).unwrap();
assert!(!section.section_syntax_indicator);
assert!(section.crc32.is_none());
section
.validate_crc(&buf)
.expect("short-form: no CRC to validate");
assert_eq!(section.payload(), &buf[3..]);
}
#[test]
fn serialize_rejects_oversized_payload_for_declared_section_length() {
let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xAA, 0xBB]);
let mut section = Section::parse(&raw).unwrap();
let oversized = vec![0u8; section.payload.len() + 1];
section.payload = &oversized;
let mut buf = vec![0u8; section.serialized_len()];
let err = section.serialize_into(&mut buf).unwrap_err();
assert!(
matches!(err, Error::SectionPayloadLengthMismatch { actual, .. } if actual == oversized.len()),
"expected SectionPayloadLengthMismatch, got {err:?}"
);
}
#[test]
fn serialize_rejects_undersized_payload_for_declared_section_length() {
let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xAA, 0xBB, 0xCC]);
let mut section = Section::parse(&raw).unwrap();
let undersized = &[0xAAu8][..];
section.payload = undersized;
let mut buf = vec![0u8; section.serialized_len() + 16];
let err = section.serialize_into(&mut buf).unwrap_err();
assert!(
matches!(err, Error::SectionPayloadLengthMismatch { actual, .. } if actual == undersized.len()),
"expected SectionPayloadLengthMismatch, got {err:?}"
);
}
#[test]
fn serialize_accepts_consistent_section_round_trip() {
let raw = make_long_section(0x42, 0x0001, 3, true, 1, 2, &[0x01, 0x02, 0x03]);
let section = Section::parse(&raw).unwrap();
let mut buf = vec![0u8; section.serialized_len()];
let n = section.serialize_into(&mut buf).unwrap();
assert_eq!(&buf[..n], raw.as_slice());
}
}