dvb-si 17.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
//! Time Offset Table — ETSI EN 300 468 §5.2.6.
//!
//! Carried on PID 0x0014 with table_id 0x73. Structure:
//!   5-byte UTC time + descriptor loop + 4-byte CRC32.
//!
//! The TOT is the spec's framing exception: `section_syntax_indicator` SHALL
//! be `0b0` (§5.2.6: "This 1-bit field shall be set to 0b0") yet the section
//! still ends with a CRC_32. Do not route TOT bytes through the generic
//! [`mpeg_ts::section::Section`] short-form path — it would fold the CRC into
//! the payload. Parse with [`TotSection::parse`] directly.

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};

/// table_id for Time Offset Table.
pub const TABLE_ID: u8 = 0x73;
/// Well-known PID on which TOT is carried (same as TDT).
pub const PID: mpeg_ts::pid::Pid = mpeg_ts::pid::Pid::from_const(0x0014);

const HEADER_LEN: usize = 3;
/// Width of the 40-bit `UTC_time` field.
pub const UTC_TIME_LEN: usize = 5;
const DESC_LOOP_LEN_FIELD: usize = 2;
use super::CRC_LEN;

/// Width of the `reserved_descriptors_loop_length` field.
pub const TOT_RESERVED_BITS: u32 = 4;
const MIN_SECTION_LEN: usize = HEADER_LEN + UTC_TIME_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;

/// Byte offset of the descriptor-loop length field.
const DESC_LOOP_LEN_OFFSET: usize = HEADER_LEN + UTC_TIME_LEN;

/// Time Offset Table.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct TotSection<'a> {
    /// Raw 5-byte UTC time (16-bit MJD + 24-bit BCD HHMMSS).
    /// Private — use [`utc_time_decoded`](Self::utc_time_decoded) for
    /// decoded access.
    pub(crate) utc_time_raw: [u8; UTC_TIME_LEN],
    /// Raw descriptor bytes (typically local_time_offset_descriptor tag 0x58).
    /// Descriptor loop. Serializes as the typed descriptor sequence;
    /// `.raw()` yields the wire bytes.
    pub descriptors: DescriptorLoop<'a>,
    /// Header bit fields: `reserved_future_use` and `reserved(2)` of byte 1
    /// (`section_syntax_indicator` is the fixed `0b0` of §5.2.6; default
    /// [`SectionBits::dvb`](super::SectionBits::dvb)). `reserved_b5` is unused.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub bits: super::SectionBits,
    /// `reserved(4)` before `descriptors_loop_length` (`1111`); preserved.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_descriptors_loop_length: ReservedOnes<TOT_RESERVED_BITS>,
}

impl<'a> TotSection<'a> {
    /// Decode the UTC time to a plain date-time struct (no `jiff` feature
    /// required).
    ///
    /// Returns `None` if the date/time fields are out of range. MJD→calendar
    /// conversion per ETSI EN 300 468 Annex C.
    #[must_use]
    pub fn utc_time_decoded(&self) -> Option<broadcast_common::time::MjdBcdDateTime> {
        broadcast_common::time::decode_mjd_bcd(self.utc_time_raw)
    }

    /// Set the UTC time, encoding it from a [`broadcast_common::time::MjdBcdDateTime`].
    ///
    /// # Errors
    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if the date is
    /// outside the representable 16-bit MJD range.
    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(())
    }

    /// Raw 5-byte UTC time field (for round-trip / serialization).
    #[must_use]
    pub fn utc_time_raw(&self) -> [u8; UTC_TIME_LEN] {
        self.utc_time_raw
    }

    /// Construct a `TotSection` from raw wire fields.
    #[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<'_> {
    /// Decode `utc_time_raw` (16-bit MJD + 24-bit BCD UTC) to a UTC datetime.
    ///
    /// Returns `None` if the date/time fields are out of range. MJD→calendar
    /// conversion per ETSI EN 300 468 Annex C.
    #[must_use]
    pub fn utc_time(&self) -> Option<jiff::Timestamp> {
        broadcast_common::time::decode_mjd_bcd_utc(self.utc_time_raw)
    }

    /// Set the UTC time, encoding it into the 40-bit `utc_time` field.
    ///
    /// # Errors
    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if the date is
    /// outside the representable 16-bit MJD range.
    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;
        // §5.2.6: section_syntax_indicator SHALL be 0 for the TOT (despite the
        // trailing CRC_32). 0x70 = SSI(0) | reserved_future_use(1) | reserved(11).
        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);
        // SSI=0 per §5.2.6 (the TOT exception: SSI=0 but CRC present).
        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(&lto);
        let tot = TotSection::parse(&bytes).unwrap();
        assert_eq!(tot.descriptors.raw(), &lto[..]);
    }

    #[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(&lto);
        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 { .. }
        ));
    }

    /// section_length is 12 bits (max 4095 = UTC_TIME_LEN(5) +
    /// DESC_LOOP_LEN_FIELD(2) + descriptors + CRC_LEN(4), so 4084 is the
    /// largest descriptor loop that fits).
    #[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());
    }

    /// A hostile `descriptors_loop_length` larger than the section is rejected
    /// with the exact overrun, never sliced past the buffer (§5.2.6).
    #[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);
        // descriptors_loop_length lives at bytes 8..10; reserved(4) is the high
        // nibble, so 0xFF 0xFF declares 4095.
        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:?}"),
        }
    }

    /// An overrun that stays inside the section's CRC-adjusted end differs from
    /// one that runs clear past the buffer: both are rejected before the slice.
    #[test]
    fn parse_rejects_descriptors_loop_length_just_past_the_section() {
        let desc = vec![0xAAu8; 20];
        let mut bytes = build_tot(&desc);
        // Declare 25 descriptor bytes: d_end = 10 + 25 = 35, one byte past the
        // 34-byte buffer but only one past the CRC-adjusted end (30).
        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:?}"),
        }
    }

    /// A descriptor loop shorter than the section leaves bytes that belong to
    /// no field: a parse would accept them and a serialize drop them, so the
    /// section is rejected.
    #[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(_))
        ));
    }

    /// A descriptor loop that exactly fills the section is accepted.
    #[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());
    }

    /// The field is 4 bits wide, so a wider value is unrepresentable and cannot
    /// spill into the 12-bit descriptors_loop_length below it.
    #[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);
    }
}