Skip to main content

dvb_ci_runtime/
dataplane.rs

1//! The CI **TS data-plane** device: [`CiDataDevice`].
2//!
3//! Separate-CI hardware (CXD2099-class CI bridges — a PCIe/USB CI card with no
4//! integrated demod) exposes two devices. The **control plane** is the CA device
5//! ([`CaDevice`](crate::device::CaDevice), `caM`): the EN 50221 APDU exchange
6//! (resource manager, sessions, `ca_pmt`). The **data plane** is `ciM`: the host
7//! **writes** the scrambled Transport Stream into it and **reads** the
8//! descrambled TS back out. This module abstracts the data plane the same way
9//! [`CaDevice`](crate::device::CaDevice) abstracts the control plane, so the
10//! host-fed descramble path can be driven by a real device (`linux` feature) or
11//! an in-memory mock.
12//!
13//! All TS I/O is in whole 188-byte packets ([`TS_PACKET_SIZE`]); a non-aligned
14//! buffer is rejected with [`io::ErrorKind::InvalidInput`].
15
16use std::io;
17use std::time::Duration;
18
19/// MPEG-2 TS packet length (ISO/IEC 13818-1): 188 bytes.
20use mpeg_ts::ts::TS_PACKET_SIZE;
21
22/// The TS data-plane device of a separate-CI module (`/dev/dvb/adapterN/ciM`).
23///
24/// The host pushes scrambled TS in with [`write`](Self::write) and pulls the
25/// descrambled TS out with [`read`](Self::read). Implementations:
26/// [`MockCiDataDevice`] (in-memory, for tests + differential harness) and, with
27/// the `linux` feature, a device over `/dev/dvb/.../ci`.
28pub trait CiDataDevice {
29    /// Write scrambled TS to the module. `ts` must be a whole number of
30    /// [`TS_PACKET_SIZE`]-byte packets.
31    ///
32    /// An implementation must never leave a packet half written. When the
33    /// device cannot take all of `ts` (its buffer is full) it returns an
34    /// [`io::ErrorKind::WouldBlock`] error carrying a [`PartialWrite`] — read
35    /// it with [`partial_write_progress`] — whose `written` is the number of
36    /// whole-packet bytes the device did accept, so the caller can resume
37    /// after them (see [`CaDescrambler::feed_ts`](crate::descrambler::CaDescrambler::feed_ts),
38    /// which drains the device and retries the unsent tail).
39    fn write(&mut self, ts: &[u8]) -> io::Result<()>;
40
41    /// Read descrambled TS into `buf` (sized to a multiple of [`TS_PACKET_SIZE`]);
42    /// returns the byte count. `Ok(0)` means none available (non-blocking).
43    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
44
45    /// Wait up to `timeout` for descrambled TS to become readable; `Ok(true)` if
46    /// readable.
47    fn poll(&mut self, timeout: Duration) -> io::Result<bool>;
48}
49
50/// Payload of the [`io::ErrorKind::WouldBlock`] error a [`CiDataDevice::write`]
51/// returns when the device buffer filled before all of the TS was accepted.
52/// Read it back with [`partial_write_progress`].
53#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
54#[error("{device}: device buffer full, {written} of {requested} bytes ({} packets) written", .written / TS_PACKET_SIZE)]
55pub struct PartialWrite {
56    /// Bytes the device accepted — always a whole number of
57    /// [`TS_PACKET_SIZE`]-byte packets (never a torn packet).
58    pub written: usize,
59    /// Bytes the caller asked to write.
60    pub requested: usize,
61    /// The device, for the error message.
62    pub device: String,
63}
64
65/// The whole-packet byte count a [`CiDataDevice::write`] error accepted before
66/// the device filled, or `None` when `err` is not a [`PartialWrite`].
67#[must_use]
68pub fn partial_write_progress(err: &io::Error) -> Option<usize> {
69    err.get_ref()
70        .and_then(|inner| inner.downcast_ref::<PartialWrite>())
71        .map(|p| p.written)
72}
73
74/// Reject a buffer that is not a whole number of TS packets.
75fn check_aligned(len: usize, what: &'static str) -> io::Result<()> {
76    if len.is_multiple_of(TS_PACKET_SIZE) {
77        Ok(())
78    } else {
79        Err(io::Error::new(io::ErrorKind::InvalidInput, what))
80    }
81}
82
83/// In-memory [`CiDataDevice`] for tests and the differential harness.
84///
85/// - `descrambled` is a scripted queue of TS the "module" returns; each
86///   [`read`](CiDataDevice::read) pops one entry (the "scripted descramble").
87/// - every byte the host writes is recorded in `written`, so a test (or a
88///   byte-exact comparison against an external reference) can assert the exact
89///   scrambled TS that was pushed in.
90#[derive(Debug, Default)]
91pub struct MockCiDataDevice {
92    /// Scripted descrambled-TS the module returns to the host (FIFO).
93    pub descrambled: std::collections::VecDeque<Vec<u8>>,
94    /// Scrambled TS the host wrote, in order.
95    pub written: Vec<Vec<u8>>,
96}
97
98impl MockCiDataDevice {
99    /// New mock returning the given descrambled-TS script.
100    #[must_use]
101    pub fn new(descrambled: impl IntoIterator<Item = Vec<u8>>) -> Self {
102        Self {
103            descrambled: descrambled.into_iter().collect(),
104            written: Vec::new(),
105        }
106    }
107
108    /// All scrambled TS the host wrote, concatenated.
109    #[must_use]
110    pub fn written_ts(&self) -> Vec<u8> {
111        self.written.iter().flatten().copied().collect()
112    }
113}
114
115impl CiDataDevice for MockCiDataDevice {
116    fn write(&mut self, ts: &[u8]) -> io::Result<()> {
117        check_aligned(ts.len(), "write not a multiple of 188 bytes")?;
118        self.written.push(ts.to_vec());
119        Ok(())
120    }
121
122    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
123        check_aligned(buf.len(), "read buffer not a multiple of 188 bytes")?;
124        match self.descrambled.pop_front() {
125            Some(ts) => {
126                let n = ts.len().min(buf.len());
127                buf[..n].copy_from_slice(&ts[..n]);
128                Ok(n)
129            }
130            None => Ok(0),
131        }
132    }
133
134    fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
135        Ok(!self.descrambled.is_empty())
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn partial_write_displays_progress_in_bytes_and_packets() {
145        let e = PartialWrite {
146            written: 376,
147            requested: 564,
148            device: "/dev/dvb/adapter0/sec0".to_string(),
149        };
150        assert_eq!(
151            e.to_string(),
152            "/dev/dvb/adapter0/sec0: device buffer full, 376 of 564 bytes (2 packets) written"
153        );
154        assert!(std::error::Error::source(&e).is_none());
155    }
156
157    fn packet(fill: u8) -> Vec<u8> {
158        let mut p = vec![fill; TS_PACKET_SIZE];
159        p[0] = 0x47; // sync byte
160        p
161    }
162
163    #[test]
164    fn mock_records_writes_and_replays_descrambled() {
165        let mut dev = MockCiDataDevice::new([packet(0xAA), packet(0xBB)]);
166        dev.write(&packet(0x11)).unwrap();
167        dev.write(&packet(0x22)).unwrap();
168
169        let mut buf = [0u8; TS_PACKET_SIZE];
170        assert!(dev.poll(Duration::ZERO).unwrap());
171        assert_eq!(dev.read(&mut buf).unwrap(), TS_PACKET_SIZE);
172        assert_eq!(buf[1], 0xAA);
173        assert_eq!(dev.read(&mut buf).unwrap(), TS_PACKET_SIZE);
174        assert_eq!(buf[1], 0xBB);
175        assert_eq!(dev.read(&mut buf).unwrap(), 0); // drained
176        assert!(!dev.poll(Duration::ZERO).unwrap());
177
178        assert_eq!(dev.written_ts().len(), 2 * TS_PACKET_SIZE);
179    }
180
181    #[test]
182    fn partial_write_display_names_device_and_progress() {
183        let err = PartialWrite {
184            written: 188,
185            requested: 376,
186            device: "ci0".to_string(),
187        };
188        let text = err.to_string();
189        assert!(text.contains("ci0"), "{text}");
190        assert!(text.contains("188 of 376"), "{text}");
191        assert!(text.contains("1 packets"), "{text}");
192    }
193
194    #[test]
195    fn rejects_unaligned_io() {
196        let mut dev = MockCiDataDevice::new([]);
197        assert_eq!(
198            dev.write(&[0x47; 100]).unwrap_err().kind(),
199            io::ErrorKind::InvalidInput
200        );
201        let mut buf = [0u8; 100];
202        assert_eq!(
203            dev.read(&mut buf).unwrap_err().kind(),
204            io::ErrorKind::InvalidInput
205        );
206    }
207}