simulcrypt 0.2.1

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
use std::time::{
    Duration,
    SystemTime,
};

use bytes::Bytes;

use crate::{
    CasRef,
    cw::Parity,
    ecmg::{
        ChannelParams,
        SectionTsPktFlag,
    },
};

/// ECM/EMM datagram format. The crate reports it together with the data, so the application does
/// not have to track `section_TSpkt_flag` itself.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DatagramFormat {
    /// The datagram is a PSI/SI section, TS packetization is up to the application.
    Section,
    /// The datagram is already split into TS packets.
    TsPacket,
}

impl From<SectionTsPktFlag> for DatagramFormat {
    fn from(flag: SectionTsPktFlag) -> Self {
        match flag {
            SectionTsPktFlag::TsPacket => DatagramFormat::TsPacket,
            SectionTsPktFlag::Section | SectionTsPktFlag::Unknown(_) => DatagramFormat::Section,
        }
    }
}

/// One ordered event queue per service. `Clone` is needed to deliver the same event to several
/// `Service`s sharing one CW group.
#[derive(Clone, Debug)]
pub enum Event {
    /// New crypto period: the key for the scrambler.
    Cw {
        /// Crypto period number `cw` is valid for.
        cp_number: u16,
        /// Parity - which CSA slot to update.
        parity: Parity,
        /// The control word.
        cw: [u8; 8],
    },

    /// ECM datagram as the ECMG sent it, for applications that packetize ECM themselves; [`Ts`]
    /// carries the same ECM ready for the stream.
    ///
    /// [`Ts`]: Event::Ts
    Ecm {
        /// CAS channel that sent the datagram.
        cas: CasRef,
        /// Stream the datagram belongs to.
        stream_id: u16,
        /// Crypto period number, if the ECMG sent one.
        cp_number: Option<u16>,
        /// Datagram format.
        format: DatagramFormat,
        /// Raw ECM bytes.
        data: Bytes,
    },

    /// TS packets to insert into the stream: either the ECM carousel, the current ECM of one stream
    /// on its `ecm_pid` repeated every `rep_period` of its CAS (100 ms while the ECMG sets none),
    /// or one EMM on the [`EmmgConfig::pid`](crate::EmmgConfig::pid) of its CAS. The continuity
    /// counter runs per stream for ECM and per CAS for EMM.
    Ts(Vec<[u8; 188]>),

    /// EMM received by the EMMG server from an external EMM generator, as it came; [`Ts`] carries
    /// it ready for the stream when its CAS has an EMM PID.
    ///
    /// [`Ts`]: Event::Ts
    Emm {
        /// CAS channel that received the datagram.
        cas: CasRef,
        /// Stream the datagram belongs to.
        stream_id: u16,
        /// Data identifier from `STREAM_SETUP`.
        data_id: u16,
        /// Data type from `STREAM_SETUP`.
        data_type: u8,
        /// Datagram format.
        format: DatagramFormat,
        /// Raw EMM bytes.
        data: Bytes,
    },

    /// Channel state change: logs and diagnostics.
    State {
        /// Channel whose state changed.
        cas: CasRef,
        /// New state.
        state: CasState,
    },
}

/// State of the ECMG connection of one CAS channel.
#[derive(Clone, Debug)]
pub enum CasState {
    /// Connecting or reconnecting to the ECMG.
    Connecting,
    /// Handshake of the channel and all currently known streams is complete.
    Ready(CasParams),
    /// The ECMG returned an error or the connection failed with an error.
    Error {
        /// Error code, if present in `CHANNEL_ERROR/STREAM_ERROR`.
        code: Option<u16>,
        /// Error description, if one was sent.
        info: Option<String>,
    },
    /// Connection closed, waiting to reconnect.
    Disconnected,
}

/// Parameters negotiated in `CHANNEL_STATUS`. `format` and `rep_period` affect the crate's
/// behavior, the other fields are informational.
#[derive(Clone, Copy, Debug)]
pub struct CasParams {
    /// ECM datagram format on this channel.
    pub format: DatagramFormat,
    /// ECM repetition period recommended by the ECMG, followed by the ECM carousel.
    pub rep_period: Option<Duration>,
    /// Maximum number of streams the ECMG allows on this channel.
    pub max_streams: Option<u16>,
    /// Minimum allowed crypto period duration.
    pub min_cp_duration: Option<Duration>,
    /// How many crypto periods ahead the ECMG wants to receive CWs.
    pub lead_cw: Option<u8>,
    /// How many CWs the ECMG expects in one `CW_PROVISION`.
    pub cw_per_msg: Option<u8>,
    /// Maximum time the ECMG spends building an ECM.
    pub max_comp_time: Option<Duration>,
}

impl CasParams {
    /// Converts on-the-wire units (see [`ChannelParams`]) into [`Duration`].
    pub(super) fn from_wire(section_ts_pkt_flag: SectionTsPktFlag, params: ChannelParams) -> Self {
        Self {
            format: section_ts_pkt_flag.into(),
            rep_period: params
                .rep_period
                .map(|ms| Duration::from_millis(u64::from(ms))),
            max_streams: params.max_streams,
            min_cp_duration: params
                .min_cp_duration
                .map(|hundred_ms| Duration::from_millis(u64::from(hundred_ms) * 100)),
            lead_cw: params.lead_cw,
            cw_per_msg: params.cw_per_msg,
            max_comp_time: params
                .max_comp_time
                .map(|ms| Duration::from_millis(u64::from(ms))),
        }
    }
}

/// Stream assigned by the crate: the CAS, the caller's `ecm_pid` and the actual protocol
/// `stream_id`.
#[derive(Clone, Copy, Debug)]
pub struct StreamInfo {
    /// CAS channel the stream belongs to.
    pub cas: CasRef,
    /// `ecm_pid` this stream was requested with in `ServiceCas`.
    pub ecm_pid: u16,
    /// Actual protocol `stream_id` assigned by the crate.
    pub stream_id: u16,
}

/// State of one CAS channel for diagnostics and monitoring (`Simulcrypt::status`).
#[derive(Clone, Debug)]
pub struct CasStatus {
    /// Channel this entry describes.
    pub cas: CasRef,
    /// Channel name from `CasConfig::name`.
    pub name: String,
    /// Current ECMG connection state.
    pub state: CasState,
    /// Last ECMG error. `state` passes `Error` on its way to a reconnect; this keeps it after the
    /// connection recovers.
    pub last_error: Option<CasError>,
    /// Completed ECMG handshakes since the CAS was registered; more than one means the channel
    /// reconnected.
    pub connects: u64,
    /// Streams currently open on the channel.
    pub streams: Vec<StreamStatus>,
}

/// Last ECMG error of a CAS channel (see [`CasStatus::last_error`]).
#[derive(Clone, Debug)]
pub struct CasError {
    /// Error code from `CHANNEL_ERROR`/`STREAM_ERROR`, if the ECMG sent one.
    pub code: Option<u16>,
    /// Error description.
    pub info: Option<String>,
    /// When the error happened.
    pub at: SystemTime,
}

/// One stream of a CAS channel (see [`CasStatus::streams`]). Counters run since the stream was
/// opened.
#[derive(Clone, Debug)]
pub struct StreamStatus {
    /// Protocol `stream_id`.
    pub stream_id: u16,
    /// `ecm_pid` the stream was opened with in `ServiceCas`.
    pub ecm_pid: u16,
    /// The ECMG accepted the stream on the current connection.
    pub ready: bool,
    /// Crypto period of the CW on air for this stream; `None` before the first CW.
    pub cp_number: Option<u16>,
    /// ECM delivered to services.
    pub ecm: u64,
    /// ECM dropped because they came for a past crypto period.
    pub ecm_stale: u64,
    /// EMM delivered to services, over TCP and UDP.
    pub emm: u64,
}

/// EMMG listener of one port (see `Simulcrypt::emmg_status`).
#[derive(Clone, Debug)]
pub struct EmmgPortStatus {
    /// Listening port.
    pub port: u16,
    /// UDP is bound on the port.
    pub udp: bool,
    /// Open TCP connections from EMM generators.
    pub connections: usize,
    /// UDP datagrams dropped without a reply because they did not parse or resolve to a stream.
    /// Always 0 when `udp` is false.
    pub datagrams_dropped: u64,
}