dvb-si 12.0.1

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
//! Application Signalling Descriptor — ETSI TS 102 809 V1.3.1 §5.3.5.1, Table 17
//! (tag 0x6F).
//!
//! Carried in the PMT to point at the AIT and enumerate the application types
//! present alongside the AIT version expected. Per ts_102_809_apps.md
//! "Table 17 — Application signalling descriptor syntax" (PDF p. 37) each loop
//! entry is 3 bytes: reserved_future_use(1) + application_type(15), then
//! reserved_future_use(3) + AIT_version_number(5).

use super::descriptor_body;
use crate::error::{Error, Result};
use crate::tables::ait::ApplicationType;
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};

/// Descriptor tag for application_signalling_descriptor.
pub const TAG: u8 = 0x6F;
const HEADER_LEN: usize = 2;
const ENTRY_LEN: usize = 3;

/// Largest representable 15-bit application_type.
const APPLICATION_TYPE_MAX: u16 = 0x7FFF;
/// Largest representable 5-bit AIT_version_number.
const AIT_VERSION_MAX: u8 = 0x1F;

/// Returns the well-known name for an `application_type`, or `None` if the
/// type is not recognised.
///
/// Delegates to [`crate::tables::ait::ApplicationType`] as the single source
/// of truth for application-type naming.  Verified entries from the
/// DVB Services registry.
#[must_use]
pub fn application_type_name(val: u16) -> Option<&'static str> {
    use crate::tables::ait::ApplicationType;
    let ty = ApplicationType::from_u16(val);
    matches!(
        ty,
        ApplicationType::DvbJ
            | ApplicationType::DvbHtml
            | ApplicationType::HbbTv
            | ApplicationType::OipfDae
    )
    .then(|| ty.name())
}

/// Default of the 1-bit `reserved_future_use` before `application_type`:
/// TS 102 809 V1.1.1-V1.3.1 §5.3.3.2 ("all reserved_future_use bits shall be
/// set to 1"). Older MHP editions (TS 101 812 V1.1.1-V1.3.2) have no such bit
/// — `application_type` is 16 bits there — so MHP-era senders write 0 here
/// (audit §3.2); parse keeps whatever the sender wrote.
pub const RESERVED_FUTURE_USE_1_DEFAULT: u8 = 0b1;
/// Default of the 3-bit `reserved_future_use` before `AIT_version_number`
/// (TS 102 809 §5.3.3.2: `1`s).
pub const RESERVED_FUTURE_USE_3_DEFAULT: u8 = 0b111;

/// One application-signalling loop entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ApplicationSignallingEntry {
    /// `reserved_future_use(1)` ahead of `application_type` (TS 102 809
    /// Table 17), captured on parse and re-emitted verbatim. 0 on MHP-era
    /// (TS 101 812) senders, 1 per TS 102 809.
    pub reserved_future_use_1: u8,
    /// `reserved_future_use(3)` ahead of `AIT_version_number` (3 bits,
    /// right-aligned), captured on parse and re-emitted verbatim.
    pub reserved_future_use_3: u8,
    /// 15-bit application_type — reuses [`crate::tables::ait::ApplicationType`]
    /// (ETSI TS 102 809 §5.3.5.1 / DVB Services registry).
    pub application_type: ApplicationType,
    /// 5-bit AIT_version_number this entry refers to.
    pub ait_version_number: u8,
}

impl ApplicationSignallingEntry {
    /// Build an entry with the TS 102 809 default reserved bits (all ones).
    #[must_use]
    pub const fn new(application_type: ApplicationType, ait_version_number: u8) -> Self {
        Self {
            reserved_future_use_1: RESERVED_FUTURE_USE_1_DEFAULT,
            reserved_future_use_3: RESERVED_FUTURE_USE_3_DEFAULT,
            application_type,
            ait_version_number,
        }
    }
}

/// Application Signalling Descriptor.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ApplicationSignallingDescriptor {
    /// Entries in wire order.
    pub entries: Vec<ApplicationSignallingEntry>,
}

impl ApplicationSignallingDescriptor {
    /// Build a descriptor from its loop entries.
    #[must_use]
    pub const fn new(entries: Vec<ApplicationSignallingEntry>) -> Self {
        Self { entries }
    }
}

impl<'a> Parse<'a> for ApplicationSignallingDescriptor {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "ApplicationSignallingDescriptor",
            "unexpected tag for application_signalling_descriptor",
        )?;
        if body.len() % ENTRY_LEN != 0 {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "application_signalling_descriptor length must be a multiple of 3",
            });
        }
        let mut entries = Vec::with_capacity(body.len() / ENTRY_LEN);
        for chunk in body.chunks_exact(ENTRY_LEN) {
            let word = crate::wire::be_u16(chunk, 0, "application_signalling")?;
            let application_type_raw = word & APPLICATION_TYPE_MAX;
            let application_type = ApplicationType::from_u16(application_type_raw);
            let ait_version_number = chunk[2] & AIT_VERSION_MAX;
            entries.push(ApplicationSignallingEntry {
                reserved_future_use_1: (word >> 15) as u8,
                reserved_future_use_3: chunk[2] >> 5,
                application_type,
                ait_version_number,
            });
        }
        Ok(Self { entries })
    }
}

impl Serialize for ApplicationSignallingDescriptor {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        HEADER_LEN + self.entries.len() * ENTRY_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        for e in &self.entries {
            if e.application_type.to_u16() > APPLICATION_TYPE_MAX {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "application_type exceeds 15 bits",
                });
            }
            if e.ait_version_number > AIT_VERSION_MAX {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "ait_version_number exceeds 5 bits",
                });
            }
        }
        if self.entries.len() * ENTRY_LEN > u8::MAX as usize {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "application_signalling_descriptor body exceeds 255 bytes",
            });
        }
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        crate::descriptors::write_descriptor_header(buf, TAG, self.entries.len() * ENTRY_LEN)?;
        let mut pos = HEADER_LEN;
        for e in &self.entries {
            // reserved_future_use(1): preserved from parse, default 1.
            let word = (u16::from(broadcast_common::len::fit_mask(
                e.reserved_future_use_1,
                1,
                "reserved_future_use_1",
            )?) << 15)
                | broadcast_common::len::fit_mask(
                    e.application_type.to_u16(),
                    APPLICATION_TYPE_MAX,
                    "application_type",
                )?;
            buf[pos..pos + 2].copy_from_slice(&word.to_be_bytes());
            // reserved_future_use(3): preserved from parse, default 111.
            buf[pos + 2] = (broadcast_common::len::fit_mask(
                e.reserved_future_use_3,
                0x07,
                "reserved_future_use_3",
            )? << 5)
                | broadcast_common::len::fit_mask(
                    e.ait_version_number,
                    AIT_VERSION_MAX,
                    "ait_version_number",
                )?;
            pos += ENTRY_LEN;
        }
        Ok(len)
    }
}
impl crate::traits::DescriptorDef<'_> for ApplicationSignallingDescriptor {
    const TAG: u8 = TAG;
    const NAME: &'static str = "APPLICATION_SIGNALLING";
}

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

    #[test]
    fn parse_single_entry() {
        // application_type=0x0010 (HbbTV), AIT_version=3, reserved bits set.
        let bytes = [TAG, 3, 0x80, 0x10, 0xE3];
        let d = ApplicationSignallingDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].application_type, ApplicationType::HbbTv);
        assert_eq!(d.entries[0].ait_version_number, 3);
    }

    #[test]
    fn parse_multiple_entries() {
        let bytes = [TAG, 6, 0x00, 0x01, 0x05, 0x7F, 0xFF, 0x1F];
        let d = ApplicationSignallingDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 2);
        assert_eq!(d.entries[0].application_type, ApplicationType::DvbJ);
        assert_eq!(d.entries[0].ait_version_number, 5);
        assert_eq!(
            d.entries[1].application_type,
            ApplicationType::Reserved(0x7FFF)
        );
        assert_eq!(d.entries[1].ait_version_number, 0x1F);
    }

    #[test]
    fn parse_captures_reserved_bits() {
        // top bit of word + top 3 bits of version byte are reserved → captured, not folded into the fields.
        let bytes = [TAG, 3, 0xFF, 0xFF, 0xFF];
        let d = ApplicationSignallingDescriptor::parse(&bytes).unwrap();
        assert_eq!(
            d.entries[0].application_type,
            ApplicationType::Reserved(0x7FFF)
        );
        assert_eq!(d.entries[0].ait_version_number, 0x1F);
        assert_eq!(d.entries[0].reserved_future_use_1, 1);
        assert_eq!(d.entries[0].reserved_future_use_3, 0b111);
    }

    /// Every real-sender reserved-bit combination (MHP-era 0 bit, 000 / 111 in
    /// the version byte) re-serializes byte-identically.
    #[test]
    fn reserved_bits_preserved_for_every_combination() {
        for r1 in 0u8..=1 {
            for r3 in 0u8..=7 {
                let bytes = [TAG, 3, r1 << 7, 0x10, (r3 << 5) | 0x03];
                let d = ApplicationSignallingDescriptor::parse(&bytes).unwrap();
                assert_eq!(d.entries[0].reserved_future_use_1, r1);
                assert_eq!(d.entries[0].reserved_future_use_3, r3);
                let mut buf = vec![0u8; d.serialized_len()];
                d.serialize_into(&mut buf).unwrap();
                assert_eq!(buf, bytes);
            }
        }
    }

    /// A hand-built entry carries the TS 102 809 value (all ones).
    #[test]
    fn default_reserved_bits_are_ones() {
        let d = ApplicationSignallingDescriptor::new(vec![ApplicationSignallingEntry::new(
            ApplicationType::HbbTv,
            3,
        )]);
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, [TAG, 3, 0x80, 0x10, 0xE3]);
    }

    #[test]
    fn application_type_name_verified() {
        assert_eq!(application_type_name(0x0001), Some("DVB-J"));
        assert_eq!(application_type_name(0x0002), Some("DVB-HTML"));
        assert_eq!(application_type_name(0x0010), Some("HbbTV"));
        assert_eq!(application_type_name(0x0011), Some("OIPF DAE"));
    }

    #[test]
    fn application_type_name_removed_entries_return_none() {
        assert_eq!(application_type_name(0x0003), None);
        assert_eq!(application_type_name(0x0004), None);
        assert_eq!(application_type_name(0x0005), None);
        assert_eq!(application_type_name(0x0012), None);
        assert_eq!(application_type_name(0x0013), None);
        assert_eq!(application_type_name(0x0020), None);
    }

    #[test]
    fn application_type_name_unknown() {
        assert_eq!(application_type_name(0x0000), None);
        assert_eq!(application_type_name(0xFFFF), None);
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        assert!(matches!(
            ApplicationSignallingDescriptor::parse(&[0x70, 0]).unwrap_err(),
            Error::InvalidDescriptor { tag: 0x70, .. }
        ));
    }

    #[test]
    fn parse_rejects_length_not_multiple_of_3() {
        let bytes = [TAG, 4, 0, 0, 0, 0];
        assert!(matches!(
            ApplicationSignallingDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { .. }
        ));
    }

    #[test]
    fn empty_descriptor_valid() {
        let bytes = [TAG, 0];
        let d = ApplicationSignallingDescriptor::parse(&bytes).unwrap();
        assert!(d.entries.is_empty());
    }

    #[test]
    fn serialize_round_trip() {
        let d = ApplicationSignallingDescriptor::new(vec![
            ApplicationSignallingEntry::new(ApplicationType::DvbJ, 7),
            ApplicationSignallingEntry::new(ApplicationType::HbbTv, 0),
        ]);
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(ApplicationSignallingDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn serialize_rejects_application_type_over_range() {
        let d = ApplicationSignallingDescriptor::new(vec![ApplicationSignallingEntry::new(
            ApplicationType::Reserved(0x8000),
            0,
        )]);
        let mut buf = vec![0u8; d.serialized_len()];
        assert!(matches!(
            d.serialize_into(&mut buf).unwrap_err(),
            Error::InvalidDescriptor { .. }
        ));
    }

    #[test]
    fn serialize_rejects_ait_version_over_range() {
        let d = ApplicationSignallingDescriptor::new(vec![ApplicationSignallingEntry::new(
            ApplicationType::Reserved(0),
            0x20,
        )]);
        let mut buf = vec![0u8; d.serialized_len()];
        assert!(matches!(
            d.serialize_into(&mut buf).unwrap_err(),
            Error::InvalidDescriptor { .. }
        ));
    }

    #[test]
    fn application_type_known_values_round_trip() {
        // Spot-check that well-known types survive a serialize→parse round-trip.
        for at in [
            ApplicationType::DvbJ,
            ApplicationType::DvbHtml,
            ApplicationType::HbbTv,
            ApplicationType::OipfDae,
            ApplicationType::Reserved(0x0005),
        ] {
            let d =
                ApplicationSignallingDescriptor::new(vec![ApplicationSignallingEntry::new(at, 1)]);
            let mut buf = vec![0u8; d.serialized_len()];
            d.serialize_into(&mut buf).unwrap();
            let re = ApplicationSignallingDescriptor::parse(&buf).unwrap();
            assert_eq!(re, d, "ApplicationType round-trip failed for {at:?}");
        }
    }
}