dvb-si 13.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
//! PDC Descriptor — ETSI EN 300 468 §6.2.30 (tag 0x69, Table 84, PDF p. 97).
//!
//! Programme Delivery Control. Carried inside EIT. Fixed 3-byte body:
//! `reserved_future_use` (4 bits) + `programme_identification_label` (20 bits).
//! The PIL encodes a "day month hour minute" stamp used by VCRs to trigger
//! recording independent of schedule slippage.

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

/// Descriptor tag for PDC_descriptor.
pub const TAG: u8 = 0x69;
/// Length of the header (tag byte + length byte).
pub const HEADER_LEN: usize = 2;
/// Fixed body length: 4 reserved bits + 20-bit PIL = 24 bits = 3 bytes.
pub const BODY_LEN: usize = 3;
/// The programme_identification_label occupies the low 20 bits.
pub const PIL_MASK: u32 = 0x000F_FFFF;
/// Shift of the 4-bit `reserved_future_use` in the 24-bit body.
const RESERVED_SHIFT: u32 = 20;
/// Mask of the 4-bit `reserved_future_use` once shifted down.
const RESERVED_MASK: u8 = 0x0F;
/// Spec default of `reserved_future_use`(4): all ones (EN 300 468
/// V1.4.1-V1.20.1 Table 84; audit `private/specs-verified/dvb/dvb-si/reserved-bits-edition-audit.md`
/// §6.1, class A: stable in every edition).
pub const RESERVED_FUTURE_USE_DEFAULT: u8 = 0x0F;

/// PDC Descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct PdcDescriptor {
    /// `reserved_future_use`(4) ahead of the PIL (4 bits, right-aligned).
    /// Captured on parse and re-emitted verbatim; [`PdcDescriptor::new`]
    /// defaults to [`RESERVED_FUTURE_USE_DEFAULT`].
    pub reserved_future_use: u8,
    /// 20-bit programme_identification_label (day/month/hour/minute packed).
    pub programme_identification_label: u32,
}

impl PdcDescriptor {
    /// Build a descriptor with the spec-default reserved bits (all ones).
    #[must_use]
    pub const fn new(programme_identification_label: u32) -> Self {
        Self {
            reserved_future_use: RESERVED_FUTURE_USE_DEFAULT,
            programme_identification_label,
        }
    }

    /// Day-of-month component of the `programme_identification_label`
    /// (5 bits `[19:15]`, EN 300 468 §6.2.29).
    #[must_use]
    pub fn pil_day(&self) -> u8 {
        ((self.programme_identification_label >> 15) & 0x1F) as u8
    }

    /// Month component (4 bits `[14:11]`).
    #[must_use]
    pub fn pil_month(&self) -> u8 {
        ((self.programme_identification_label >> 11) & 0x0F) as u8
    }

    /// Hour component (5 bits `[10:6]`).
    #[must_use]
    pub fn pil_hour(&self) -> u8 {
        ((self.programme_identification_label >> 6) & 0x1F) as u8
    }

    /// Minute component (6 bits `[5:0]`).
    #[must_use]
    pub fn pil_minute(&self) -> u8 {
        (self.programme_identification_label & 0x3F) as u8
    }

    /// Set the `programme_identification_label` from its day/month/hour/minute
    /// components.
    ///
    /// # Errors
    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if any
    /// component exceeds its bit field (`day` ≤ 31, `month` ≤ 15, `hour` ≤ 31,
    /// `minute` ≤ 63).
    pub fn set_pil(&mut self, day: u8, month: u8, hour: u8, minute: u8) -> crate::Result<()> {
        if day > 0x1F || month > 0x0F || hour > 0x1F || minute > 0x3F {
            return Err(crate::Error::ValueOutOfRange {
                field: "PdcDescriptor::programme_identification_label",
                reason: "a day/month/hour/minute component exceeds its bit field",
            });
        }
        self.programme_identification_label = (u32::from(day) << 15)
            | (u32::from(month) << 11)
            | (u32::from(hour) << 6)
            | u32::from(minute);
        Ok(())
    }
}

impl<'a> Parse<'a> for PdcDescriptor {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "PdcDescriptor",
            "unexpected tag for PDC_descriptor",
        )?;
        if body.len() != BODY_LEN {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "PDC_descriptor length must be exactly 3",
            });
        }
        let raw = (u32::from(body[0]) << 16) | (u32::from(body[1]) << 8) | u32::from(body[2]);
        Ok(Self {
            reserved_future_use: ((raw >> RESERVED_SHIFT) as u8) & RESERVED_MASK,
            programme_identification_label: raw & PIL_MASK,
        })
    }
}

impl Serialize for PdcDescriptor {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        HEADER_LEN + BODY_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        if self.programme_identification_label > PIL_MASK {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "programme_identification_label exceeds 20 bits",
            });
        }
        let len = self.serialized_len();
        need_out(buf, len)?;
        crate::descriptors::write_descriptor_header(buf, TAG, BODY_LEN)?;
        // reserved_future_use(4) preserved from parse (default 1111).
        let raw = (u32::from(broadcast_common::len::fit_mask(
            self.reserved_future_use,
            RESERVED_MASK,
            "reserved_future_use",
        )?) << RESERVED_SHIFT)
            | broadcast_common::len::fit_mask(
                self.programme_identification_label,
                PIL_MASK,
                "programme_identification_label",
            )?;
        buf[HEADER_LEN] = (raw >> 16) as u8;
        buf[HEADER_LEN + 1] = (raw >> 8) as u8;
        buf[HEADER_LEN + 2] = raw as u8;
        Ok(len)
    }
}
impl crate::traits::DescriptorDef<'_> for PdcDescriptor {
    const TAG: u8 = TAG;
    const NAME: &'static str = "PDC";
}

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

    #[test]
    fn parse_extracts_pil() {
        // body 0x0A_BCDE: top nibble reserved (0), PIL = 0x0ABCDE.
        let bytes = [TAG, 3, 0x0A, 0xBC, 0xDE];
        let d = PdcDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.programme_identification_label, 0x0A_BCDE);
    }

    #[test]
    fn parse_captures_reserved_bits() {
        // Top nibble set (reserved) is captured, not rejected, and the PIL is
        // still extracted.
        let bytes = [TAG, 3, 0xFA, 0xBC, 0xDE];
        let d = PdcDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.programme_identification_label, 0x0A_BCDE);
        assert_eq!(d.reserved_future_use, 0x0F);
    }

    /// All 16 reserved nibbles re-serialize byte-identically.
    #[test]
    fn reserved_preserved_for_every_value() {
        for r in 0u8..=0x0F {
            let bytes = [TAG, 3, (r << 4) | 0x0A, 0xBC, 0xDE];
            let d = PdcDescriptor::parse(&bytes).unwrap();
            assert_eq!(d.reserved_future_use, r);
            let mut buf = vec![0u8; d.serialized_len()];
            d.serialize_into(&mut buf).unwrap();
            assert_eq!(buf, bytes);
        }
    }

    #[test]
    fn default_is_spec_value() {
        let d = PdcDescriptor::new(0x0A_BCDE);
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, [TAG, 3, 0xFA, 0xBC, 0xDE]);
    }

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

    #[test]
    fn parse_rejects_wrong_length() {
        assert!(matches!(
            PdcDescriptor::parse(&[TAG, 2, 0, 0]).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_body() {
        assert!(matches!(
            PdcDescriptor::parse(&[TAG, 3, 0, 0]).unwrap_err(),
            Error::BufferTooShort(..)
        ));
    }

    #[test]
    fn serialize_round_trip() {
        let d = PdcDescriptor::new(0x0A_BCDE);
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        // Reserved nibble emitted as 1s.
        assert_eq!(buf, [TAG, 3, 0xFA, 0xBC, 0xDE]);
        assert_eq!(PdcDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn serialize_rejects_too_small_buffer() {
        let d = PdcDescriptor::new(0);
        let mut buf = vec![0u8; 2];
        assert!(matches!(
            d.serialize_into(&mut buf).unwrap_err(),
            Error::OutputBufferTooSmall(..)
        ));
    }

    #[test]
    fn serialize_rejects_over_range_pil() {
        let d = PdcDescriptor::new(0x10_0000);
        let mut buf = vec![0u8; d.serialized_len()];
        assert!(matches!(
            d.serialize_into(&mut buf).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }
}