simulcrypt 0.2.1

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
//! TS packets of a `Service`: the ECM carousel, the current ECM of each of its streams on the
//! stream's `ecm_pid` repeated every `rep_period` of its CAS, and each EMM once on the
//! `EmmgConfig::pid` of its CAS.

use std::{
    collections::VecDeque,
    time::Duration,
};

use bytes::Bytes;
use libmpegts::{
    psi::{
        PsiPacketizer,
        Sections,
    },
    ts::{
        PACKET_SIZE,
        TsPacketMut,
    },
};
use tokio::time::Instant;

use crate::{
    event::{
        DatagramFormat,
        Event,
        StreamInfo,
    },
    simulcrypt::{
        CasRef,
        Inner,
    },
};

/// Repetition period while the ECMG has not set `ECM_rep_period`.
const DEFAULT_REP_PERIOD: Duration = Duration::from_millis(100);

/// PIDs below 0x0020 belong to PSI/SI, 0x1FFF to null packets.
fn carries_ca(pid: u16) -> bool {
    (0x0020 ..= 0x1FFE).contains(&pid)
}

/// One stream on the carousel.
struct Slot {
    cas: CasRef,
    stream_id: u16,
    pid: u16,
    /// The ECM datagram on air.
    ecm: Bytes,
    /// `ecm` packetized on `pid`; the continuity counter is set on every repetition.
    packets: Vec<[u8; PACKET_SIZE]>,
    cc: u8,
    period: Duration,
    due: Instant,
}

pub struct Carousel {
    slots: Vec<Slot>,
}

impl Carousel {
    /// One slot per distinct stream whose `ecm_pid` can carry ECM.
    pub fn new(streams: &[StreamInfo]) -> Self {
        let now = Instant::now();
        let mut slots: Vec<Slot> = Vec::new();
        for info in streams {
            if !carries_ca(info.ecm_pid)
                || slots
                    .iter()
                    .any(|slot| slot.cas == info.cas && slot.stream_id == info.stream_id)
            {
                continue;
            }
            slots.push(Slot {
                cas: info.cas,
                stream_id: info.stream_id,
                pid: info.ecm_pid,
                ecm: Bytes::new(),
                packets: Vec::new(),
                cc: 0,
                period: DEFAULT_REP_PERIOD,
                due: now,
            });
        }
        Self { slots }
    }

    /// When the next slot is due; `None` without slots.
    pub fn next_due(&self) -> Option<Instant> {
        self.slots.iter().map(|slot| slot.due).min()
    }

    /// Queues the ECM of every due slot into `out`. Reads the latest ECM and `rep_period` from the
    /// CAS at each repetition, so an event receiver that lagged past an ECM does not keep an old
    /// one on air. A slot whose CAS was removed leaves the carousel.
    pub fn run(&mut self, inner: &Inner, out: &mut VecDeque<Event>) {
        let now = Instant::now();
        self.slots.retain_mut(|slot| {
            if slot.due > now {
                return true;
            }
            let Ok(entry) = inner.cas_entry(slot.cas) else {
                return false;
            };
            if let Some(params) = entry.params() {
                slot.period = params
                    .rep_period
                    .filter(|period| !period.is_zero())
                    .unwrap_or(DEFAULT_REP_PERIOD);
            }
            if let Some(Event::Ecm { format, data, .. }) = entry.last_ecm(slot.stream_id)
                && data != slot.ecm
            {
                slot.packets = packetize(slot.pid, format, &data);
                slot.ecm = data;
            }
            if !slot.packets.is_empty() {
                out.push_back(Event::Ts(stamp_cc(&slot.packets, &mut slot.cc)));
            }
            // From the schedule, not from `now`: the wakeup latency would stretch every period.
            let next = slot.due + slot.period;
            slot.due = if next > now { next } else { now + slot.period };
            true
        });
    }
}

/// The streams of one CAS in a `Service`, for its EMM.
struct EmmCas {
    cas: CasRef,
    streams: Vec<u16>,
    cc: u8,
}

pub struct EmmPackets {
    cas: Vec<EmmCas>,
}

impl EmmPackets {
    pub fn new(streams: &[StreamInfo]) -> Self {
        let mut cas: Vec<EmmCas> = Vec::new();
        for info in streams {
            match cas.iter_mut().find(|slot| slot.cas == info.cas) {
                Some(slot) if slot.streams.contains(&info.stream_id) => {}
                Some(slot) => slot.streams.push(info.stream_id),
                None => cas.push(EmmCas {
                    cas: info.cas,
                    streams: vec![info.stream_id],
                    cc: 0,
                }),
            }
        }
        Self { cas }
    }

    /// Queues an EMM of the service's streams into `out` as TS packets on the EMM PID of its CAS,
    /// read from the CAS settings at each EMM.
    pub fn push(&mut self, inner: &Inner, event: &Event, out: &mut VecDeque<Event>) {
        let Event::Emm {
            cas,
            stream_id,
            format,
            data,
            ..
        } = event
        else {
            return;
        };
        let Some(slot) = self.cas.iter_mut().find(|slot| slot.cas == *cas) else {
            return;
        };
        let Some((pid, broadcast)) = inner.cas_entry(*cas).ok().and_then(|entry| entry.emm_pid())
        else {
            return;
        };
        // A broadcast EMM comes on every stream of the CAS: one copy is enough.
        let wanted = if broadcast {
            slot.streams[0] == *stream_id
        } else {
            slot.streams.contains(stream_id)
        };
        if !wanted || !carries_ca(pid) {
            return;
        }
        let packets = packetize(pid, *format, data);
        if !packets.is_empty() {
            out.push_back(Event::Ts(stamp_cc(&packets, &mut slot.cc)));
        }
    }
}

/// A datagram as TS packets on `pid`: a section gets PUSI, pointer field 0 and 0xFF stuffing;
/// TS packets keep everything but the PID, a trailing partial packet is dropped.
fn packetize(pid: u16, format: DatagramFormat, data: &[u8]) -> Vec<[u8; PACKET_SIZE]> {
    let mut packets = Vec::new();
    if data.is_empty() {
        return packets;
    }
    match format {
        DatagramFormat::Section => {
            let mut packetizer = PsiPacketizer::new(pid);
            packetizer.set_sections(Sections::from(data));
            let mut packet = [0; PACKET_SIZE];
            while packetizer.next(&mut packet) {
                packets.push(packet);
            }
        }
        DatagramFormat::TsPacket => {
            for chunk in data.chunks_exact(PACKET_SIZE) {
                let mut packet = [0; PACKET_SIZE];
                packet.copy_from_slice(chunk);
                TsPacketMut::from(&mut packet).set_pid(pid);
                packets.push(packet);
            }
        }
    }
    packets
}

fn stamp_cc(packets: &[[u8; PACKET_SIZE]], cc: &mut u8) -> Vec<[u8; PACKET_SIZE]> {
    packets
        .iter()
        .map(|packet| {
            let mut packet = *packet;
            TsPacketMut::from(&mut packet).set_cc(*cc);
            *cc = (*cc + 1) & 0x0F;
            packet
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use libmpegts::ts::TsPacketRef;

    use super::*;

    #[test]
    fn section_gets_pusi_pointer_and_stuffing() {
        let ecm = [0x80, 0x70, 0x02, 0xAB, 0xCD];
        let packets = packetize(0x0100, DatagramFormat::Section, &ecm);
        assert_eq!(packets.len(), 1);
        let packet = TsPacketRef::from(&packets[0]);
        assert_eq!(packet.pid(), 0x0100);
        assert!(packet.is_payload_start());
        let payload = packet.payload().unwrap();
        assert_eq!(payload[0], 0, "pointer field");
        assert_eq!(&payload[1 .. 6], &ecm);
        assert!(payload[6 ..].iter().all(|&byte| byte == 0xFF));
    }

    #[test]
    fn long_section_spans_packets() {
        let mut ecm = vec![0x81, 0x71, 0x2C];
        ecm.resize(3 + 300, 0x55);
        let packets = packetize(0x0101, DatagramFormat::Section, &ecm);
        assert_eq!(packets.len(), 2);
        assert!(!TsPacketRef::from(&packets[1]).is_payload_start());
    }

    #[test]
    fn ts_packets_keep_all_but_the_pid() {
        let mut data = vec![0u8; PACKET_SIZE * 2 + 10];
        for (index, chunk) in data.chunks_exact_mut(PACKET_SIZE).enumerate() {
            chunk[0] = 0x47;
            chunk[1] = 0x5F;
            chunk[2] = 0xFF;
            chunk[3] = 0x10;
            chunk[4] = index as u8;
        }
        let packets = packetize(0x0ABC, DatagramFormat::TsPacket, &data);
        assert_eq!(packets.len(), 2, "trailing partial packet dropped");
        for (index, packet) in packets.iter().enumerate() {
            assert_eq!(TsPacketRef::from(packet).pid(), 0x0ABC);
            assert_eq!(packet[1] & 0xE0, 0x40, "PUSI kept");
            assert_eq!(packet[4], index as u8);
        }
    }

    #[test]
    fn empty_datagram_has_no_packets() {
        assert!(packetize(0x0100, DatagramFormat::Section, &[]).is_empty());
        assert!(packetize(0x0100, DatagramFormat::TsPacket, &[]).is_empty());
    }

    #[test]
    fn cc_runs_across_repetitions_and_wraps() {
        let mut ecm = vec![0x80, 0x70, 0xBD];
        ecm.resize(3 + 189, 0x55);
        let packets = packetize(0x0100, DatagramFormat::Section, &ecm);
        let mut cc = 14;
        let first = stamp_cc(&packets, &mut cc);
        let second = stamp_cc(&packets, &mut cc);
        let ccs: Vec<u8> = first
            .iter()
            .chain(&second)
            .map(|packet| TsPacketRef::from(packet).cc())
            .collect();
        assert_eq!(ccs, [14, 15, 0, 1]);
    }

    #[test]
    fn reserved_pids_and_repeated_streams_get_no_slot() {
        let info = |cas, ecm_pid, stream_id| StreamInfo {
            cas: CasRef::new(cas),
            ecm_pid,
            stream_id,
        };
        let carousel = Carousel::new(&[
            info(0, 0x0000, 1),
            info(0, 0x001F, 2),
            info(0, 0x1FFF, 3),
            info(0, 0x0100, 4),
            info(0, 0x0100, 4),
            info(1, 0x0100, 4),
        ]);
        let slots: Vec<_> = carousel
            .slots
            .iter()
            .map(|slot| (slot.cas, slot.stream_id))
            .collect();
        assert_eq!(slots, [(CasRef::new(0), 4), (CasRef::new(1), 4)]);
    }
}