Skip to main content

dvb_ci_runtime/
lib.rs

1//! Pure-Rust EN 50221 DVB Common Interface **runtime** — the driver loop over
2//! the [`dvb_ci`] codecs.
3//!
4//! [`dvb_ci`] is `no_std` and owns the *wire* layer (TPDU / SPDU / APDU
5//! parse+serialize, CA_PMT building, CI Plus extensions). This crate adds the
6//! *runtime*: device I/O, the TPDU poll loop, SPDU session management, and the
7//! per-resource state machines that together drive a physical CAM, per
8//! ETSI EN 50221 and TS 101 699.
9//!
10//! # Design
11//!
12//! The whole runtime is written against the [`CaDevice`] trait (the
13//! hardware-abstraction boundary), so it runs against either:
14//! - a real Linux CA device (`/dev/dvb/adapterN/caM`, the `linux` feature), or
15//! - the in-memory [`MockCaDevice`], which makes the state machines testable
16//!   without hardware and enables differential testing against an external
17//!   reference (drive both with the same scripted mock CAM and assert the
18//!   emitted `write`/ioctl byte sequences match).
19//!
20//! Implemented from the EN 50221 specification.
21//!
22//! # What's implemented
23//!
24//! - **Transport** (TPDU, §A.4): `Create_T_C` handshake, empty-`T_Data_Last`
25//!   poll cadence, `T_SB` data-available → `T_RCV`, `T_Data_More/Last`
26//!   reassembly, reply timeout.
27//! - **Session** (SPDU, §7.2): session table; `open_session_request`/response,
28//!   host-initiated `create_session`, `close_session`; `session_number` + APDU
29//!   routing.
30//! - **Resources** (§8): Resource Manager handshake (profile exchange →
31//!   [`Notification::CamReady`], then opens module resources),
32//!   application_information, conditional_access (`ca_pmt`/`ca_pmt_reply`),
33//!   date_time (MJD + BCD), and mmi (surfaces module menus/enquiries as
34//!   [`Notification::Mmi`]).
35//! - **Descramble helper**: [`Driver::descramble`](crate::driver::Driver::descramble)
36//!   / [`HostRequest::Descramble`] runs the full `ca_pmt` query → reply →
37//!   ok_descrambling sequence, CAID-filtered to the CAM's `ca_info`.
38//! - **Devices**: the in-memory [`MockCaDevice`] + [`MockCiDataDevice`], and the
39//!   Linux `/dev/dvb/adapterN/caM` (control) + `ciM` (TS data-plane) devices
40//!   behind the `linux` feature. The data plane ([`CiDataDevice`]) carries the
41//!   scrambled-in / descrambled-out TS for separate-CI hardware.
42//!
43//! - **Diagnostics**: [`RecordingCaDevice`] captures the link in both directions;
44//!   [`trace::decode_frame`]/[`decode_log`](crate::trace::decode_log) annotate a
45//!   capture (TPDU → SPDU → APDU) for live-CAM debugging.
46//!
47//! # Managed CAS layer (#763)
48//!
49//! A single-slot CA orchestration layer sits on top of the raw `ca_pmt` /
50//! `ca_pmt_reply` surface, fed **parsed `dvb-si` structs** (never raw bytes):
51//!
52//! - [`Driver::add_service`](crate::Driver::add_service) /
53//!   [`remove_service`](crate::Driver::remove_service) — build + send the
54//!   `ca_pmt` from a [`dvb_si::tables::pmt::PmtSection`] and track the slot's
55//!   active service set (multi-programme list-management handled internally).
56//! - [`Driver::set_cat`](crate::Driver::set_cat) — feed the CAT; the EMM-PID
57//!   set becomes the CAT's EMM PIDs ∩ the CAM's advertised `ca_info` CAIDs.
58//! - [`Driver::emm_pids`](crate::Driver::emm_pids) /
59//!   [`descramble_pids`](crate::Driver::descramble_pids) /
60//!   [`ca_pids`](crate::Driver::ca_pids) /
61//!   [`required_pids`](crate::Driver::required_pids) — the PIDs to route into
62//!   the `ci0` data plane (EMM ∪ ES ∪ ECM ∪ PCR = `required_pids`).
63//! - [`Driver::set_requery_interval`](crate::Driver::set_requery_interval) — a
64//!   periodic `ca_pmt` re-query (`cmd_id = query`) so a card entitled *after*
65//!   the initial `ca_pmt` still refreshes; a per-programme status transition
66//!   surfaces as an edge-triggered [`Notification::Entitlement`].
67//! - [`CaDescrambler`] — a turnkey wrapper that additionally owns the `ci0`
68//!   [`CiDataDevice`]: `feed_ts` filters a scrambled TS chunk to
69//!   `required_pids()` and returns the descrambled TS. One `CaDescrambler` =
70//!   one CI slot = one TS path (multi-tuner ⇒ one per slot).
71//!
72//! # `ci-probe`
73//!
74//! With the `linux` feature this crate also builds a **`ci-probe`** binary that
75//! discovers and engages an installed CAM: `ci-probe list` / `info` /
76//! `descramble <pmt>` / `mmi`, with `--trace` for an annotated link dump.
77//!
78//! Roadmap: the `host_control` resource and a differential test harness against
79//! an external reference.
80//!
81//! # Example
82//!
83//! Drive a CAM with the [`MockCaDevice`] — the same `Driver` API works against
84//! the real Linux device:
85//!
86//! ```
87//! use std::time::Duration;
88//! use dvb_ci_runtime::{Driver, HotPlug, MockCaDevice, Notification};
89//! use dvb_ci_runtime::dvb_ci::tpdu::tags;
90//!
91//! # fn main() -> std::io::Result<()> {
92//! // Script a module that accepts the transport connection.
93//! let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
94//! let mut driver = Driver::new(dev);
95//!
96//! driver.init()?; // reset + open the transport connection
97//!
98//! // Pump the device: reads frames when readable, otherwise advances the
99//! // EN 50221 poll cadence by the timeout.
100//! for _ in 0..4 {
101//!     driver.pump(Duration::from_millis(100))?;
102//! }
103//!
104//! // Host-facing events (CamReady, ApplicationInfo, CaInfo, Mmi, HotPlug, …)
105//! // surface here — either poll-drained:
106//! for note in driver.take_notifications() {
107//!     match note {
108//!         Notification::CamReady => { /* now safe to send a ca_pmt */ }
109//!         other => { let _ = other; }
110//!     }
111//! }
112//!
113//! // …or, since this crate is sync/sans-IO (no channels), delivered by a
114//! // closure callback per pump — `pump_with` for every notification, or
115//! // `pump_hotplug` to react only to CAM/card hot-plug transitions:
116//! driver.pump_hotplug(Duration::from_millis(100), |hp| match hp {
117//!     HotPlug::CamPresent => { /* CAM (re)inserted — re-send any pending ca_pmt */ }
118//!     HotPlug::CamRemoved => { /* CAM removed — stop descrambling */ }
119//!     _ => {}
120//! })?;
121//! # Ok(())
122//! # }
123//! ```
124
125// The portable core is unsafe-free; only the optional Linux device leaf
126// (`#[allow(unsafe_code)]` in `linux`) uses ioctls, so this is `deny`, not
127// `forbid`.
128#![deny(unsafe_code)]
129#![warn(missing_docs)]
130
131pub mod dataplane;
132pub mod descrambler;
133pub mod device;
134pub mod driver;
135pub mod event;
136pub mod managed;
137pub mod resource;
138pub mod session;
139pub mod stack;
140pub mod trace;
141pub mod transport;
142
143#[cfg(all(feature = "linux", target_os = "linux"))]
144pub mod linux;
145
146pub use dataplane::{CiDataDevice, MockCiDataDevice, TS_PACKET_LEN};
147pub use descrambler::CaDescrambler;
148pub use device::{CaDevice, DeviceOp, LinkEvent, MockCaDevice, RecordingCaDevice, SlotInfo};
149pub use driver::Driver;
150pub use event::{Action, Event, HostRequest, HotPlug, Notification};
151#[cfg(all(feature = "linux", target_os = "linux"))]
152pub use linux::{LinuxCaDevice, LinuxCiDataDevice};
153pub use managed::{CaError, ManagedCa, ManagedService, REQUERY_DEFAULT};
154pub use stack::CiStack;
155
156/// Re-export of the wire-codec crate this runtime drives.
157pub use dvb_ci;