use crate::descriptors::DescriptorLoop;
use crate::error::{Error, Result};
use broadcast_core::len::{need_in, need_out};
use broadcast_core::reserved::ReservedOnes;
use broadcast_core::{Parse, Serialize};
pub const TABLE_ID: u8 = 0x73;
pub const PID: mpeg_ts::pid::Pid = mpeg_ts::pid::Pid::from_const(0x0014);
const HEADER_LEN: usize = 3;
pub const UTC_TIME_LEN: usize = 5;
const DESC_LOOP_LEN_FIELD: usize = 2;
use super::CRC_LEN;
pub const TOT_RESERVED_BITS: u32 = 4;
const MIN_SECTION_LEN: usize = HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;
const DESC_LOOP_LEN_OFFSET: usize = HEADER_LEN + UTC_TIME_LEN;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct TotSection<'a> {
pub(crate) utc_time_raw: [u8; UTC_TIME_LEN],
pub descriptors: DescriptorLoop<'a>,
#[cfg_attr(feature = "serde", serde(skip))]
pub bits: super::SectionBits,
#[cfg_attr(feature = "serde", serde(skip))]
pub reserved_descriptors_loop_length: ReservedOnes<TOT_RESERVED_BITS>,
}
impl<'a> TotSection<'a> {
#[must_use]
pub fn utc_time_decoded(&self) -> Option<broadcast_common::time::MjdBcdDateTime> {
broadcast_common::time::decode_mjd_bcd(self.utc_time_raw)
}
pub fn set_utc_time_decoded(
&mut self,
dt: broadcast_common::time::MjdBcdDateTime,
) -> Result<()> {
self.utc_time_raw =
broadcast_common::time::encode_mjd_bcd(dt).ok_or(Error::ValueOutOfRange {
field: "TotSection::utc_time",
reason: "date not representable in 16-bit MJD",
})?;
Ok(())
}
#[must_use]
pub fn utc_time_raw(&self) -> [u8; UTC_TIME_LEN] {
self.utc_time_raw
}
#[must_use]
pub fn new(utc_time_raw: [u8; UTC_TIME_LEN], descriptors: DescriptorLoop<'a>) -> Self {
Self {
utc_time_raw,
descriptors,
bits: super::SectionBits::dvb().short_form(),
reserved_descriptors_loop_length: ReservedOnes::FILL,
}
}
}
#[cfg(feature = "jiff")]
impl TotSection<'_> {
#[must_use]
pub fn utc_time(&self) -> Option<jiff::Timestamp> {
broadcast_common::time::decode_mjd_bcd_utc(self.utc_time_raw)
}
pub fn set_utc_time(&mut self, utc_time: jiff::Timestamp) -> Result<()> {
self.utc_time_raw =
broadcast_common::time::encode_mjd_bcd_utc(utc_time).ok_or(Error::ValueOutOfRange {
field: "TotSection::utc_time",
reason: "date not representable in 16-bit MJD",
})?;
Ok(())
}
}
impl<'a> Parse<'a> for TotSection<'a> {
type Error = crate::error::Error;
fn parse(bytes: &'a [u8]) -> Result<Self> {
let min_len = HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;
need_in(bytes, min_len, "TotSection")?;
if bytes[0] != TABLE_ID {
return Err(Error::UnexpectedTableId {
table_id: bytes[0],
what: "TotSection",
expected: &[TABLE_ID],
});
}
let section_length = super::section_length_of(bytes);
let total =
super::check_section_length(bytes.len(), HEADER_LEN, section_length, MIN_SECTION_LEN)?;
let mut utc_time_raw = [0u8; UTC_TIME_LEN];
utc_time_raw.copy_from_slice(&bytes[HEADER_LEN..HEADER_LEN + UTC_TIME_LEN]);
let dl_pos = HEADER_LEN + UTC_TIME_LEN;
let dl = super::desc_loop_len_of(bytes[dl_pos], bytes[dl_pos + 1]);
let d_start = dl_pos + DESC_LOOP_LEN_FIELD;
let d_end = d_start + dl;
if d_end > total - CRC_LEN {
return Err(Error::SectionLengthOverflow {
declared: dl,
available: (total - CRC_LEN).saturating_sub(d_start),
});
}
super::check_loop_reaches_crc(
d_end,
total - CRC_LEN,
"TotSection trailing bytes after descriptor loop",
)?;
Ok(TotSection {
utc_time_raw,
descriptors: DescriptorLoop::new(&bytes[d_start..d_end]),
bits: super::SectionBits::parse(bytes[1], None),
reserved_descriptors_loop_length: ReservedOnes::from_bits(u64::from(
super::len_reserved_of(bytes[dl_pos]),
)),
})
}
}
impl Serialize for TotSection<'_> {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + self.descriptors.len() + CRC_LEN
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let len = self.serialized_len();
need_out(buf, len, "TotSection")?;
buf[0] = TABLE_ID;
buf[1] = self.bits.b1()?;
super::write_section_length(buf, len - HEADER_LEN)?;
buf[HEADER_LEN..HEADER_LEN + UTC_TIME_LEN].copy_from_slice(&self.utc_time_raw);
let dl = broadcast_core::len::fit_bits(
self.descriptors.len() as u64,
super::DESC_LOOP_LEN_BITS,
"descriptors_loop_length",
)?;
super::write_desc_loop_len_r(
&mut buf[DESC_LOOP_LEN_OFFSET..DESC_LOOP_LEN_OFFSET + DESC_LOOP_LEN_FIELD],
dl as usize,
self.reserved_descriptors_loop_length.get() as u8,
)?;
let d_end = DESC_LOOP_LEN_OFFSET + DESC_LOOP_LEN_FIELD + self.descriptors.len();
buf[DESC_LOOP_LEN_OFFSET + DESC_LOOP_LEN_FIELD..d_end]
.copy_from_slice(self.descriptors.raw());
let crc_pos = len - CRC_LEN;
broadcast_common::crc32_mpeg2::seal(buf, crc_pos)?;
Ok(len)
}
}
impl<'a> crate::traits::TableDef<'a> for TotSection<'a> {
const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
const NAME: &'static str = "TIME_OFFSET";
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::{vec, vec::Vec};
fn build_tot(desc: &[u8]) -> Vec<u8> {
let section_length = (UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + desc.len() + CRC_LEN) as u16;
let mut v = Vec::new();
v.push(TABLE_ID);
v.push(0x70 | ((section_length >> 8) as u8 & crate::tables::SECTION_LENGTH_HI_MASK));
v.push((section_length & 0xFF) as u8);
v.extend_from_slice(&[0xE4, 0x09, 0x12, 0x34, 0x56]);
crate::tables::push_desc_loop_len(&mut v, desc.len());
v.extend_from_slice(desc);
let crc = broadcast_common::crc32_mpeg2::compute(&v);
v.extend_from_slice(&crc.to_be_bytes());
v
}
#[test]
fn parse_with_no_descriptors() {
let bytes = build_tot(&[]);
let tot = TotSection::parse(&bytes).unwrap();
assert_eq!(tot.utc_time_raw(), [0xE4, 0x09, 0x12, 0x34, 0x56]);
assert_eq!(tot.descriptors.raw(), &[] as &[u8]);
}
#[test]
fn parse_with_local_time_offset_descriptor() {
let lto = [
0x58u8, 13, b'G', b'B', b'R', 0x02, 0x00, 0x00, 0xE4, 0x09, 0x12, 0x34, 0x56, 0x01,
0x00,
];
let bytes = build_tot(<o);
let tot = TotSection::parse(&bytes).unwrap();
assert_eq!(tot.descriptors.raw(), <o[..]);
}
#[test]
fn parse_rejects_wrong_tag() {
let mut bytes = build_tot(&[]);
bytes[0] = 0x70;
assert!(matches!(
TotSection::parse(&bytes).unwrap_err(),
Error::UnexpectedTableId { table_id: 0x70, .. }
));
}
#[test]
fn serialize_round_trip() {
let lto = [0x58u8, 0];
let bytes = build_tot(<o);
let tot = TotSection::parse(&bytes).unwrap();
let mut buf = vec![0u8; tot.serialized_len()];
tot.serialize_into(&mut buf).unwrap();
assert_eq!(buf, bytes, "TOT byte-identity against hand-built input");
let re = TotSection::parse(&buf).unwrap();
assert_eq!(tot, re);
}
#[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!(
TotSection::parse(&buf).unwrap_err(),
Error::SectionLengthOverflow { .. }
));
}
#[test]
fn serialize_rejects_descriptors_exceeding_section_length() {
let desc = vec![0xAAu8; 4085];
let tot = TotSection::new([0xE4, 0x09, 0x12, 0x34, 0x56], DescriptorLoop::new(&desc));
let mut buf = vec![0u8; tot.serialized_len()];
assert!(matches!(
tot.serialize_into(&mut buf).unwrap_err(),
Error::FieldOverflow(_)
));
}
#[test]
fn serialize_accepts_descriptors_at_section_length_boundary() {
let desc = vec![0xAAu8; 4084];
let tot = TotSection::new([0xE4, 0x09, 0x12, 0x34, 0x56], DescriptorLoop::new(&desc));
let mut buf = vec![0u8; tot.serialized_len()];
tot.serialize_into(&mut buf).expect("boundary fits");
let reparsed = TotSection::parse(&buf).expect("reparse");
assert_eq!(tot.descriptors.raw(), reparsed.descriptors.raw());
}
#[test]
fn parse_rejects_descriptors_loop_length_beyond_section() {
let desc = vec![0xAAu8; 20];
let mut bytes = build_tot(&desc);
assert_eq!(bytes.len(), 34);
bytes[8] = 0xFF;
bytes[9] = 0xFF;
match TotSection::parse(&bytes) {
Err(Error::SectionLengthOverflow {
declared,
available,
}) => {
assert_eq!(declared, 4095);
assert_eq!(available, 20);
}
other => panic!("expected SectionLengthOverflow, got {other:?}"),
}
}
#[test]
fn parse_rejects_descriptors_loop_length_just_past_the_section() {
let desc = vec![0xAAu8; 20];
let mut bytes = build_tot(&desc);
bytes[8] = 0xF0;
bytes[9] = 25;
match TotSection::parse(&bytes) {
Err(Error::SectionLengthOverflow {
declared,
available,
}) => {
assert_eq!(declared, 25);
assert_eq!(available, 20);
}
other => panic!("expected SectionLengthOverflow, got {other:?}"),
}
}
#[test]
fn parse_rejects_bytes_between_the_descriptor_loop_and_the_crc() {
let desc = vec![0xAAu8; 20];
let mut bytes = build_tot(&desc);
bytes[8] = 0xF0;
bytes[9] = 19;
assert!(matches!(
TotSection::parse(&bytes),
Err(Error::BufferTooShort(_))
));
}
#[test]
fn parse_accepts_descriptors_loop_exactly_filling_section() {
let desc = vec![0xAAu8; 20];
let bytes = build_tot(&desc);
let tot = TotSection::parse(&bytes).unwrap();
assert_eq!(tot.descriptors.raw(), desc.as_slice());
}
#[test]
fn reserved_cannot_hold_more_than_four_bits() {
let d = TotSection::new([0, 0, 0, 0, 0], DescriptorLoop::new(&[]));
let d = TotSection {
reserved_descriptors_loop_length: ReservedOnes::from_bits(0x1F),
..d
};
assert_eq!(d.reserved_descriptors_loop_length.get(), 0x0F);
}
}