dvb-si 13.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
//! Container table section — ETSI TS 102 323 v1.4.1 §7.3.1.4 (table_id 0x75).
//!
//! The container section carries TV-Anytime container data (an MHP object
//! carousel file fragment, after optional compression). Syntax per "Table 20 —
//! Container section" (`private/specs-verified/dvb/dvb-si/`, §7.3.1.4, PDF p. 36):
//!
//! ```text
//! container_section() {
//!   table_id                 8   (0x75)
//!   section_syntax_indicator 1
//!   private_indicator        1
//!   reserved                 2
//!   private_section_length  12
//!   container_id            16   (table_id_extension)
//!   reserved                 2
//!   version_number           5
//!   current_next_indicator   1
//!   section_number           8
//!   last_section_number      8
//!   container_data()        N*8
//!   CRC_32                  32
//! }
//! ```
//!
//! This is a private section (the spec's byte-1 bit 6 is `private_indicator`),
//! so it is handled with the same idiom as [`crate::tables::cit`]. The
//! `container_data` payload is kept as a borrowed raw slice; its internal
//! structure (compression_wrapper / object-carousel fragments) is out of scope.
//!
//! Carriage is signalled via descriptors (no well-known PID), following the
//! [`crate::tables::dsmcc`] precedent of `PID = 0x0000`.

use crate::error::{Error, Result};
use broadcast_common::len::{need_in, need_out};
use broadcast_common::{Parse, Serialize};

/// table_id for the Container table.
pub const TABLE_ID: u8 = 0x75;

// No fixed PID: this table's PID is signalled (PMT / descriptors). A `PID`
// constant of `0x0000` used to sit here, which is the real PAT PID, so a
// caller filtering on it would pick up PAT traffic (audit r02-W15/O12).

/// Bytes 0-2: table_id (1) + flags + private_section_length (2).
const HEADER_LEN: usize = 3;

/// Bytes 3-7: container_id(2) + reserved/version/cni(1) + section_number(1)
/// + last_section_number(1).
const EXTENSION_HEADER_LEN: usize = 5;

use super::CRC_LEN;

/// Minimum total encoded length: header + extension + CRC.
const MIN_LEN: usize = HEADER_LEN + EXTENSION_HEADER_LEN + CRC_LEN;

/// Container table section parser (ETSI TS 102 323 v1.4.1 §7.3.1.4).
///
/// `container_data` borrows the payload region (everything between the extension
/// header and the CRC-32 trailer) without parsing its internal structure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct ContainerSection<'a> {
    /// `section_syntax_indicator` (byte 1 bit 7): `1` for a constructed value,
    /// whatever the wire carried for a parsed one (parse tolerant, serialize
    /// preserves).
    pub section_syntax_indicator: bool,
    /// `private_indicator` bit from byte 1 (this is a private section).
    pub private_indicator: bool,
    /// 16-bit `container_id` (carried in the table_id_extension slot, bytes 3-4).
    pub container_id: u16,
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator` bit.
    pub current_next_indicator: bool,
    /// section_number in the sub-table sequence.
    pub section_number: u8,
    /// last_section_number in the sub-table sequence.
    pub last_section_number: u8,
    /// Raw `container_data` bytes (everything between the extension header and
    /// the CRC-32 trailer). Internal structure is not parsed.
    pub container_data: &'a [u8],
    /// `reserved(2)` in byte 1 bits `[5:4]` (`11`); preserved from the wire.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_b1: u8,
    /// `reserved(2)` in front of `version_number` (`11`); preserved.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_b5: u8,
}

impl<'a> ContainerSection<'a> {
    /// Construct a Container section with the spec `reserved` fill.
    #[must_use]
    pub fn new(
        private_indicator: bool,
        container_id: u16,
        version_number: u8,
        current_next_indicator: bool,
        section_number: u8,
        last_section_number: u8,
        container_data: &'a [u8],
    ) -> Self {
        Self {
            section_syntax_indicator: true,
            private_indicator,
            container_id,
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            container_data,
            reserved_b1: super::RESERVED_2,
            reserved_b5: super::RESERVED_2,
        }
    }
}

impl<'a> Parse<'a> for ContainerSection<'a> {
    type Error = crate::error::Error;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        need_in(bytes, MIN_LEN, "ContainerSection")?;

        if bytes[0] != TABLE_ID {
            return Err(Error::UnexpectedTableId {
                table_id: bytes[0],
                what: "ContainerSection",
                expected: &[TABLE_ID],
            });
        }

        // byte 1 = section_syntax_indicator(1) | private_indicator(1)
        //          | reserved(2) | private_section_length[11:8](4)
        // byte 2 = private_section_length[7:0]
        let section_length = super::section_length_of(bytes);
        let total = super::check_section_length(bytes.len(), HEADER_LEN, section_length, MIN_LEN)?;

        let private_indicator = (bytes[1] & super::SECTION_B1_PRIVATE_INDICATOR) != 0;

        // Extension header (bytes 3..8).
        let container_id = crate::wire::be_u16(bytes, 3, "container")?;
        // byte 5: reserved(2) | version_number(5) | current_next_indicator(1)
        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];

        // container_data: from end of extension header up to (not including) CRC.
        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
        let data_end = total - CRC_LEN;
        let container_data = &bytes[data_start..data_end];

        Ok(ContainerSection {
            section_syntax_indicator: bytes[1] & super::SECTION_B1_SSI != 0,
            private_indicator,
            container_id,
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            container_data,
            reserved_b1: super::b1_reserved_of(bytes[1]),
            reserved_b5: super::b5_reserved_of(bytes[5]),
        })
    }
}

impl Serialize for ContainerSection<'_> {
    type Error = crate::error::Error;

    fn serialized_len(&self) -> usize {
        HEADER_LEN + EXTENSION_HEADER_LEN + self.container_data.len() + CRC_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        need_out(buf, len)?;

        // Byte 0: table_id.
        buf[0] = TABLE_ID;
        // Byte 1: section_syntax_indicator(1)=1 | private_indicator(1)
        //         | reserved(2)=11 | private_section_length[11:8](4).
        buf[1] = super::b1_of(
            self.section_syntax_indicator,
            self.private_indicator,
            self.reserved_b1,
        )?;
        // Byte 2: private_section_length[7:0].
        super::write_section_length(buf, len - HEADER_LEN)?;

        // Extension header.
        buf[3..5].copy_from_slice(&self.container_id.to_be_bytes());
        buf[5] = super::b5_of(
            self.reserved_b5,
            self.version_number,
            self.current_next_indicator,
        )?;
        buf[6] = self.section_number;
        buf[7] = self.last_section_number;

        // container_data.
        let data_start = HEADER_LEN + EXTENSION_HEADER_LEN;
        let data_end = data_start + self.container_data.len();
        buf[data_start..data_end].copy_from_slice(self.container_data);

        // CRC-32 over everything up to (but not including) the CRC slot.
        super::write_crc(buf, data_end);

        Ok(len)
    }
}
impl<'a> crate::traits::TableDef<'a> for ContainerSection<'a> {
    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
    const NAME: &'static str = "CONTAINER";
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a syntactically valid Container section. `container_data` is pasted
    /// verbatim; the CRC slot is filled by the serializer.
    fn build_container(
        container_id: u16,
        version: u8,
        current_next: bool,
        section_number: u8,
        last_section_number: u8,
        container_data: &[u8],
    ) -> Vec<u8> {
        let c = ContainerSection::new(
            true,
            container_id,
            version,
            current_next,
            section_number,
            last_section_number,
            container_data,
        );
        let mut buf = vec![0u8; c.serialized_len()];
        c.serialize_into(&mut buf).unwrap();
        buf
    }

    #[test]
    fn parse_happy_path() {
        let data = [0x00u8, 0xDE, 0xAD, 0xBE, 0xEF];
        let bytes = build_container(0x1234, 7, true, 1, 3, &data);
        let c = ContainerSection::parse(&bytes).unwrap();
        assert!(c.private_indicator);
        assert_eq!(c.container_id, 0x1234);
        assert_eq!(c.version_number, 7);
        assert!(c.current_next_indicator);
        assert_eq!(c.section_number, 1);
        assert_eq!(c.last_section_number, 3);
        assert_eq!(c.container_data, &data[..]);
    }

    #[test]
    fn parse_empty_container_data() {
        let bytes = build_container(0x0000, 0, false, 0, 0, &[]);
        let c = ContainerSection::parse(&bytes).unwrap();
        assert_eq!(c.container_id, 0x0000);
        assert_eq!(c.version_number, 0);
        assert!(!c.current_next_indicator);
        assert!(c.container_data.is_empty());
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
        bytes[0] = 0x70; // not 0x75
        assert!(matches!(
            ContainerSection::parse(&bytes).unwrap_err(),
            Error::UnexpectedTableId { table_id: 0x70, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_buffer() {
        assert!(matches!(
            ContainerSection::parse(&[0x75, 0x80]).unwrap_err(),
            Error::BufferTooShort(..)
        ));
    }

    #[test]
    fn parse_rejects_section_length_overflow() {
        let mut bytes = build_container(0x0001, 0, true, 0, 0, &[]);
        let fake_sl: u16 = (bytes.len() as u16) + 100 - HEADER_LEN as u16;
        bytes[1] = (bytes[1] & 0xF0) | ((fake_sl >> 8) as u8 & 0x0F);
        bytes[2] = (fake_sl & 0xFF) as u8;
        assert!(matches!(
            ContainerSection::parse(&bytes).unwrap_err(),
            Error::SectionLengthOverflow { .. }
        ));
    }

    #[test]
    fn serialize_round_trip() {
        let data = [0x01u8, 0x02, 0x03];
        let original = ContainerSection::new(false, 0xABCD, 15, false, 2, 4, &data);
        let mut buf = vec![0u8; original.serialized_len()];
        original.serialize_into(&mut buf).unwrap();
        assert_eq!(ContainerSection::parse(&buf).unwrap(), original);
    }

    #[test]
    fn serialize_rejects_output_buffer_too_small() {
        let c = ContainerSection::new(false, 0x0001, 0, true, 0, 0, &[]);
        let mut buf = vec![0u8; 2];
        assert!(matches!(
            c.serialize_into(&mut buf).unwrap_err(),
            Error::OutputBufferTooSmall(..)
        ));
    }

    #[test]
    fn table_trait_constants() {
        assert_eq!(TABLE_ID, 0x75);
    }

    #[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!(
            ContainerSection::parse(&buf).unwrap_err(),
            Error::SectionLengthOverflow { .. }
        ));
    }

    /// private_section_length is 12 bits (max 4095 =
    /// EXTENSION_HEADER_LEN(5) + container_data + CRC_LEN(4), so 4086 is
    /// the largest container_data that fits).
    #[test]
    fn serialize_rejects_container_data_exceeding_section_length() {
        let data = vec![0xAAu8; 4087];
        let c = ContainerSection::new(false, 1, 0, true, 0, 0, &data);
        let mut buf = vec![0u8; c.serialized_len()];
        assert!(matches!(
            c.serialize_into(&mut buf).unwrap_err(),
            Error::FieldOverflow(_)
        ));
    }

    #[test]
    fn serialize_accepts_container_data_at_section_length_boundary() {
        let data = vec![0xAAu8; 4086];
        let c = ContainerSection::new(false, 1, 0, true, 0, 0, &data);
        let mut buf = vec![0u8; c.serialized_len()];
        c.serialize_into(&mut buf).expect("boundary fits");
        let reparsed = ContainerSection::parse(&buf).expect("reparse");
        assert_eq!(c, reparsed);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_json_round_trip() {
        // `container_data` is a borrowed `&[u8]` (the rnt/cit idiom), so a
        // deserialize round-trip is not possible — serde encodes a byte slice
        // as a JSON sequence which cannot be re-borrowed. Mirror the borrowed
        // tables by asserting serialization yields valid, field-bearing JSON.
        let data = [0xCAu8, 0xFE];
        let bytes = build_container(0xBEEF, 9, true, 0, 0, &data);
        let c = ContainerSection::parse(&bytes).unwrap();
        let v: serde_json::Value = serde_json::to_value(&c).unwrap();
        assert_eq!(v["container_id"], 0xBEEF);
        assert_eq!(v["version_number"], 9);
        assert_eq!(v["current_next_indicator"], true);
        assert_eq!(v["container_data"], serde_json::json!([0xCA, 0xFE]));
    }
}