dvb-si 13.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
//! Conditional Access Table — ISO/IEC 13818-1 (H.222.0 08/2023) §2.4.4.7.
//!
//! Carried on PID 0x0001 with table_id 0x01. Contains a flat
//! list of CA descriptors (tag 0x09) identifying every CA system
//! in use plus the EMM PID on which Entitlement Management
//! Messages for that system are carried.
//!
//! A single-section table per CAS standard.

use crate::descriptors::DescriptorLoop;
use crate::descriptors::ca::CaDescriptor;
use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};
use mpeg_ts::pid::Pid;

/// CAT table_id (ISO/IEC 13818-1 Table 2-30).
pub const TABLE_ID: u8 = 0x01;
/// CAT well-known PID.
pub const PID: mpeg_ts::pid::Pid = mpeg_ts::pid::Pid::new(0x0001);
/// The 16 reserved bits in place of `table_id_extension` (all ones).
const RESERVED_EXTENSION: u16 = 0xFFFF;

/// One CA descriptor entry from the CAT, in owned form so it
/// outlives the source section bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct CatCaEntry {
    /// CA System ID — the CAID. e.g. 0x0500 Viaccess, 0x0650
    /// Irdeto ORF-ICE, 0x0100 Seca/Mediaguard.
    pub ca_system_id: u16,
    /// EMM PID for this CA system.
    pub ca_pid: Pid,
    /// Optional private data after the standard CA fields.
    pub private_data: Vec<u8>,
}

/// Conditional Access Table.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct CatSection<'a> {
    /// 5-bit version_number from the section header.
    pub version_number: u8,
    /// current_next_indicator bit.
    pub current_next_indicator: bool,
    /// section_number in the sub-table sequence (typically 0 — single-section).
    pub section_number: u8,
    /// last_section_number (typically 0).
    pub last_section_number: u8,
    /// Descriptor loop (byte 8 → CRC), preserved verbatim. ISO/IEC 13818-1
    /// §2.4.4.7 permits descriptors other than CA in this loop; keeping the loop
    /// raw makes parse → serialize identity hold for all of them. Serializes as
    /// the typed descriptor sequence; `.raw()` yields the wire bytes. Use
    /// [`CatSection::ca_descriptors`] for the typed CA (tag 0x09) view.
    pub descriptors: DescriptorLoop<'a>,
    /// Header bit fields (`'0'` after `section_syntax_indicator`, the two
    /// `reserved(2)`; default [`SectionBits::psi`](super::SectionBits::psi)).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub bits: super::SectionBits,
    /// The 16 reserved bits at bytes 3-4 (the `reserved(18)` of `CA_section`,
    /// ISO/IEC 13818-1 §2.4.4.7; all ones = `0xFFFF`), preserved from the wire.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub reserved_extension: u16,
}

impl Default for CatSection<'_> {
    fn default() -> Self {
        Self::new(0, false, 0, 0, DescriptorLoop::default())
    }
}

impl<'a> CatSection<'a> {
    /// Construct a CAT section with the spec `reserved` fill.
    #[must_use]
    pub fn new(
        version_number: u8,
        current_next_indicator: bool,
        section_number: u8,
        last_section_number: u8,
        descriptors: DescriptorLoop<'a>,
    ) -> Self {
        Self {
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
            descriptors,
            bits: super::SectionBits::psi(),
            reserved_extension: RESERVED_EXTENSION,
        }
    }
}

impl CatSection<'_> {
    /// Typed view of the CA descriptors (tag 0x09) in the descriptor loop.
    /// Non-CA descriptors are skipped; a truncated trailing descriptor returns
    /// an error.
    pub fn ca_descriptors(&self) -> Result<Vec<CatCaEntry>> {
        let mut out = Vec::new();
        let mut pos = 0;
        while pos + 2 <= self.descriptors.len() {
            let tag = self.descriptors[pos];
            let length = self.descriptors[pos + 1] as usize;
            let end = pos + 2 + length;
            if end > self.descriptors.len() {
                return Err(Error::BufferTooShort(
                    broadcast_common::error::BufferTooShort {
                        need: end - pos,
                        have: self.descriptors.len() - pos,
                        what: "CatSection ca_descriptors truncated descriptor",
                    },
                ));
            }
            if tag == crate::descriptors::ca::TAG
                && let Ok(ca) = CaDescriptor::parse(&self.descriptors[pos..end])
            {
                out.push(CatCaEntry {
                    ca_system_id: ca.ca_system_id,
                    ca_pid: ca.ca_pid,
                    private_data: ca.private_data.to_vec(),
                });
            }
            pos = end;
        }
        Ok(out)
    }
}

impl<'a> Parse<'a> for CatSection<'a> {
    type Error = Error;

    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let p = super::descriptor_section::parse(bytes, &[TABLE_ID], "CatSection", "cat")?;
        Ok(CatSection {
            version_number: p.version_number,
            current_next_indicator: p.current_next_indicator,
            section_number: p.section_number,
            last_section_number: p.last_section_number,
            descriptors: p.descriptors,
            bits: p.bits,
            reserved_extension: p.table_id_extension,
        })
    }
}

impl Serialize for CatSection<'_> {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        super::descriptor_section::serialized_len(&self.descriptors)
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        super::descriptor_section::serialize_into(
            TABLE_ID,
            &super::descriptor_section::View {
                table_id_extension: self.reserved_extension,
                version_number: self.version_number,
                current_next_indicator: self.current_next_indicator,
                section_number: self.section_number,
                last_section_number: self.last_section_number,
                descriptors: &self.descriptors,
                bits: &self.bits,
            },
            buf,
        )
    }
}
impl<'a> crate::traits::TableDef<'a> for CatSection<'a> {
    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
    const NAME: &'static str = "CONDITIONAL_ACCESS";
}

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

    const EXTENSION_HEADER_LEN: usize = 5;

    /// Build a CAT section with the given CA descriptors and placeholder CRC.
    fn build_cat(version: u8, descriptors: &[u8]) -> Vec<u8> {
        let section_length: u16 =
            (EXTENSION_HEADER_LEN as u16) + descriptors.len() as u16 + (CRC_LEN as u16);
        let mut v = Vec::new();
        v.push(TABLE_ID);
        crate::tables::push_section_header(
            &mut v,
            crate::tables::SECTION_B1_FLAGS_PSI,
            section_length as usize,
        );
        // table_id_extension (reserved for CAT) — typically 0xFFFF in the wild.
        v.extend_from_slice(&[0xFF, 0xFF]);
        v.push(crate::tables::version_byte(version, true));
        v.push(0x00); // section_number
        v.push(0x00); // last_section_number
        v.extend_from_slice(descriptors);
        v.extend_from_slice(&[0, 0, 0, 0]); // placeholder CRC
        v
    }

    fn ca_descriptor(ca_system_id: u16, ca_pid: u16) -> [u8; 6] {
        [
            0x09,
            0x04,
            (ca_system_id >> 8) as u8,
            (ca_system_id & 0xFF) as u8,
            0xE0 | ((ca_pid >> 8) as u8 & 0x1F),
            (ca_pid & 0xFF) as u8,
        ]
    }

    #[test]
    fn parse_empty_cat_zero_descriptors() {
        let bytes = build_cat(5, &[]);
        let cat = CatSection::parse(&bytes).expect("parse");
        assert_eq!(cat.version_number, 5);
        assert!(cat.current_next_indicator);
        assert!(cat.descriptors.is_empty());
        assert_eq!(cat.ca_descriptors().unwrap().len(), 0);
    }

    #[test]
    fn parse_single_ca_descriptor_extracts_caid_and_pid() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        let bytes = build_cat(0, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let cas = cat.ca_descriptors().unwrap();
        assert_eq!(cas.len(), 1);
        assert_eq!(cas[0].ca_system_id, 0x0500);
        assert_eq!(cas[0].ca_pid, Pid::new(0x0050));
        assert!(cas[0].private_data.is_empty());
    }

    #[test]
    fn parse_multiple_ca_descriptors_preserves_order() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
        desc.extend_from_slice(&ca_descriptor(0x0100, 0x0080));
        let bytes = build_cat(2, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let cas = cat.ca_descriptors().unwrap();
        assert_eq!(cas.len(), 3);
        assert_eq!(cas[0].ca_system_id, 0x0500);
        assert_eq!(cas[1].ca_system_id, 0x0650);
        assert_eq!(cas[2].ca_system_id, 0x0100);
        assert_eq!(cas[1].ca_pid, Pid::new(0x0062));
    }

    #[test]
    fn parse_rejects_wrong_table_id() {
        let mut bytes = build_cat(0, &[]);
        bytes[0] = 0x02; // PMT table_id
        let err = CatSection::parse(&bytes).unwrap_err();
        assert!(matches!(
            err,
            Error::UnexpectedTableId { table_id: 0x02, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_buffer() {
        let err = CatSection::parse(&[0x01, 0x00]).unwrap_err();
        assert!(matches!(err, Error::BufferTooShort(..)));
    }

    /// §2.4.4.7 permits non-CA descriptors in the CAT loop: the typed view
    /// skips them, but parse → serialize MUST preserve them byte-for-byte.
    #[test]
    fn non_ca_descriptors_skipped_by_view_but_round_trip() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.extend_from_slice(&[0x12, 0x02, 0xAA, 0xBB]); // unknown tag 0x12, len 2
        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
        let bytes = build_cat(0, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let cas = cat.ca_descriptors().unwrap();
        assert_eq!(cas.len(), 2);
        assert_eq!(cas[0].ca_system_id, 0x0500);
        assert_eq!(cas[1].ca_system_id, 0x0650);
        // The unknown descriptor survives the round trip verbatim.
        assert_eq!(cat.descriptors.raw(), desc);
        let mut buf = vec![0u8; cat.serialized_len()];
        cat.serialize_into(&mut buf).unwrap();
        let re = CatSection::parse(&buf).unwrap();
        assert_eq!(re.descriptors.raw(), desc);
    }

    #[test]
    fn serialize_round_trip() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.extend_from_slice(&ca_descriptor(0x0650, 0x0062));
        let bytes = build_cat(3, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        let mut buf = vec![0u8; cat.serialized_len()];
        cat.serialize_into(&mut buf).unwrap();
        assert_eq!(CatSection::parse(&buf).unwrap(), cat);
    }

    #[test]
    fn table_trait_constants() {
        assert_eq!(TABLE_ID, 0x01);
        assert_eq!(PID.value(), 0x0001);
    }

    /// CAT borrows its descriptor loop (3.0): the loop serializes as the
    /// typed descriptor sequence and the struct is serialize-only. Verify the
    /// CA descriptor decodes inside the JSON.
    #[cfg(feature = "serde")]
    #[test]
    fn serde_json_serializes_typed_loop() {
        let bytes = build_cat(1, &ca_descriptor(0x0500, 0x0050));
        let cat = CatSection::parse(&bytes).unwrap();
        let v = serde_json::to_value(&cat).unwrap();
        let loop_ = v["descriptors"]
            .as_array()
            .expect("typed descriptor sequence");
        assert_eq!(loop_.len(), 1);
        assert_eq!(loop_[0]["ca"]["ca_system_id"], 0x0500);
        assert_eq!(loop_[0]["ca"]["ca_pid"], 0x0050);
    }

    /// section_length is 12 bits (max 4095). A descriptor loop that pushes
    /// the section past that must be rejected, not silently wrapped.
    #[test]
    fn serialize_rejects_descriptor_loop_exceeding_section_length() {
        let raw = vec![0xAAu8; 4091]; // + 9 header/crc bytes > 4095
        let cat = CatSection::new(0, true, 0, 0, DescriptorLoop::from(raw.as_slice()));
        let mut buf = vec![0u8; cat.serialized_len()];
        assert!(matches!(
            cat.serialize_into(&mut buf).unwrap_err(),
            Error::FieldOverflow(_)
        ));
    }

    #[test]
    fn serialize_accepts_descriptor_loop_at_section_length_boundary() {
        // section_length = EXTENSION_HEADER_LEN(5) + loop_len + CRC_LEN(4);
        // 4086 is the largest loop that keeps it at the 12-bit max, 4095.
        let raw = vec![0xAAu8; 4086];
        let cat = CatSection::new(0, true, 0, 0, DescriptorLoop::from(raw.as_slice()));
        let mut buf = vec![0u8; cat.serialized_len()];
        cat.serialize_into(&mut buf).expect("boundary fits");
        let reparsed = CatSection::parse(&buf).expect("reparse");
        assert_eq!(cat.descriptors.raw(), reparsed.descriptors.raw());
    }

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

    #[test]
    fn ca_descriptors_rejects_truncated_descriptor() {
        let mut desc = Vec::new();
        desc.extend_from_slice(&ca_descriptor(0x0500, 0x0050));
        desc.push(0x09);
        desc.push(0x10);
        let bytes = build_cat(0, &desc);
        let cat = CatSection::parse(&bytes).unwrap();
        assert!(matches!(
            cat.ca_descriptors().unwrap_err(),
            Error::BufferTooShort(broadcast_common::error::BufferTooShort {
                what: "CatSection ca_descriptors truncated descriptor",
                ..
            })
        ));
    }
}