Skip to main content

simulcrypt/
event.rs

1use std::time::{
2    Duration,
3    SystemTime,
4};
5
6use bytes::Bytes;
7
8use crate::{
9    CasRef,
10    cw::Parity,
11    ecmg::{
12        ChannelParams,
13        SectionTsPktFlag,
14    },
15};
16
17/// ECM/EMM datagram format. The crate reports it together with the data, so the application does
18/// not have to track `section_TSpkt_flag` itself.
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub enum DatagramFormat {
21    /// The datagram is a PSI/SI section, TS packetization is up to the application.
22    Section,
23    /// The datagram is already split into TS packets.
24    TsPacket,
25}
26
27impl From<SectionTsPktFlag> for DatagramFormat {
28    fn from(flag: SectionTsPktFlag) -> Self {
29        match flag {
30            SectionTsPktFlag::TsPacket => DatagramFormat::TsPacket,
31            SectionTsPktFlag::Section | SectionTsPktFlag::Unknown(_) => DatagramFormat::Section,
32        }
33    }
34}
35
36/// One ordered event queue per service. `Clone` is needed to deliver the same event to several
37/// `Service`s sharing one CW group.
38#[derive(Clone, Debug)]
39pub enum Event {
40    /// New crypto period: the key for the scrambler.
41    Cw {
42        /// Crypto period number `cw` is valid for.
43        cp_number: u16,
44        /// Parity - which CSA slot to update.
45        parity: Parity,
46        /// The control word.
47        cw: [u8; 8],
48    },
49
50    /// ECM datagram as the ECMG sent it, for applications that packetize ECM themselves; [`Ts`]
51    /// carries the same ECM ready for the stream.
52    ///
53    /// [`Ts`]: Event::Ts
54    Ecm {
55        /// CAS channel that sent the datagram.
56        cas: CasRef,
57        /// Stream the datagram belongs to.
58        stream_id: u16,
59        /// Crypto period number, if the ECMG sent one.
60        cp_number: Option<u16>,
61        /// Datagram format.
62        format: DatagramFormat,
63        /// Raw ECM bytes.
64        data: Bytes,
65    },
66
67    /// TS packets to insert into the stream: either the ECM carousel, the current ECM of one stream
68    /// on its `ecm_pid` repeated every `rep_period` of its CAS (100 ms while the ECMG sets none),
69    /// or one EMM on the [`EmmgConfig::pid`](crate::EmmgConfig::pid) of its CAS. The continuity
70    /// counter runs per stream for ECM and per CAS for EMM.
71    Ts(Vec<[u8; 188]>),
72
73    /// EMM received by the EMMG server from an external EMM generator, as it came; [`Ts`] carries
74    /// it ready for the stream when its CAS has an EMM PID.
75    ///
76    /// [`Ts`]: Event::Ts
77    Emm {
78        /// CAS channel that received the datagram.
79        cas: CasRef,
80        /// Stream the datagram belongs to.
81        stream_id: u16,
82        /// Data identifier from `STREAM_SETUP`.
83        data_id: u16,
84        /// Data type from `STREAM_SETUP`.
85        data_type: u8,
86        /// Datagram format.
87        format: DatagramFormat,
88        /// Raw EMM bytes.
89        data: Bytes,
90    },
91
92    /// Channel state change: logs and diagnostics.
93    State {
94        /// Channel whose state changed.
95        cas: CasRef,
96        /// New state.
97        state: CasState,
98    },
99}
100
101/// State of the ECMG connection of one CAS channel.
102#[derive(Clone, Debug)]
103pub enum CasState {
104    /// Connecting or reconnecting to the ECMG.
105    Connecting,
106    /// Handshake of the channel and all currently known streams is complete.
107    Ready(CasParams),
108    /// The ECMG returned an error or the connection failed with an error.
109    Error {
110        /// Error code, if present in `CHANNEL_ERROR/STREAM_ERROR`.
111        code: Option<u16>,
112        /// Error description, if one was sent.
113        info: Option<String>,
114    },
115    /// Connection closed, waiting to reconnect.
116    Disconnected,
117}
118
119/// Parameters negotiated in `CHANNEL_STATUS`. `format` and `rep_period` affect the crate's
120/// behavior, the other fields are informational.
121#[derive(Clone, Copy, Debug)]
122pub struct CasParams {
123    /// ECM datagram format on this channel.
124    pub format: DatagramFormat,
125    /// ECM repetition period recommended by the ECMG, followed by the ECM carousel.
126    pub rep_period: Option<Duration>,
127    /// Maximum number of streams the ECMG allows on this channel.
128    pub max_streams: Option<u16>,
129    /// Minimum allowed crypto period duration.
130    pub min_cp_duration: Option<Duration>,
131    /// How many crypto periods ahead the ECMG wants to receive CWs.
132    pub lead_cw: Option<u8>,
133    /// How many CWs the ECMG expects in one `CW_PROVISION`.
134    pub cw_per_msg: Option<u8>,
135    /// Maximum time the ECMG spends building an ECM.
136    pub max_comp_time: Option<Duration>,
137}
138
139impl CasParams {
140    /// Converts on-the-wire units (see [`ChannelParams`]) into [`Duration`].
141    pub(super) fn from_wire(section_ts_pkt_flag: SectionTsPktFlag, params: ChannelParams) -> Self {
142        Self {
143            format: section_ts_pkt_flag.into(),
144            rep_period: params
145                .rep_period
146                .map(|ms| Duration::from_millis(u64::from(ms))),
147            max_streams: params.max_streams,
148            min_cp_duration: params
149                .min_cp_duration
150                .map(|hundred_ms| Duration::from_millis(u64::from(hundred_ms) * 100)),
151            lead_cw: params.lead_cw,
152            cw_per_msg: params.cw_per_msg,
153            max_comp_time: params
154                .max_comp_time
155                .map(|ms| Duration::from_millis(u64::from(ms))),
156        }
157    }
158}
159
160/// Stream assigned by the crate: the CAS, the caller's `ecm_pid` and the actual protocol
161/// `stream_id`.
162#[derive(Clone, Copy, Debug)]
163pub struct StreamInfo {
164    /// CAS channel the stream belongs to.
165    pub cas: CasRef,
166    /// `ecm_pid` this stream was requested with in `ServiceCas`.
167    pub ecm_pid: u16,
168    /// Actual protocol `stream_id` assigned by the crate.
169    pub stream_id: u16,
170}
171
172/// State of one CAS channel for diagnostics and monitoring (`Simulcrypt::status`).
173#[derive(Clone, Debug)]
174pub struct CasStatus {
175    /// Channel this entry describes.
176    pub cas: CasRef,
177    /// Channel name from `CasConfig::name`.
178    pub name: String,
179    /// Current ECMG connection state.
180    pub state: CasState,
181    /// Last ECMG error. `state` passes `Error` on its way to a reconnect; this keeps it after the
182    /// connection recovers.
183    pub last_error: Option<CasError>,
184    /// Completed ECMG handshakes since the CAS was registered; more than one means the channel
185    /// reconnected.
186    pub connects: u64,
187    /// Streams currently open on the channel.
188    pub streams: Vec<StreamStatus>,
189}
190
191/// Last ECMG error of a CAS channel (see [`CasStatus::last_error`]).
192#[derive(Clone, Debug)]
193pub struct CasError {
194    /// Error code from `CHANNEL_ERROR`/`STREAM_ERROR`, if the ECMG sent one.
195    pub code: Option<u16>,
196    /// Error description.
197    pub info: Option<String>,
198    /// When the error happened.
199    pub at: SystemTime,
200}
201
202/// One stream of a CAS channel (see [`CasStatus::streams`]). Counters run since the stream was
203/// opened.
204#[derive(Clone, Debug)]
205pub struct StreamStatus {
206    /// Protocol `stream_id`.
207    pub stream_id: u16,
208    /// `ecm_pid` the stream was opened with in `ServiceCas`.
209    pub ecm_pid: u16,
210    /// The ECMG accepted the stream on the current connection.
211    pub ready: bool,
212    /// Crypto period of the CW on air for this stream; `None` before the first CW.
213    pub cp_number: Option<u16>,
214    /// ECM delivered to services.
215    pub ecm: u64,
216    /// ECM dropped because they came for a past crypto period.
217    pub ecm_stale: u64,
218    /// EMM delivered to services, over TCP and UDP.
219    pub emm: u64,
220}
221
222/// EMMG listener of one port (see `Simulcrypt::emmg_status`).
223#[derive(Clone, Debug)]
224pub struct EmmgPortStatus {
225    /// Listening port.
226    pub port: u16,
227    /// UDP is bound on the port.
228    pub udp: bool,
229    /// Open TCP connections from EMM generators.
230    pub connections: usize,
231    /// UDP datagrams dropped without a reply because they did not parse or resolve to a stream.
232    /// Always 0 when `udp` is false.
233    pub datagrams_dropped: u64,
234}