Skip to main content

dvb_ci_runtime/
driver.rs

1//! The driver — the one place I/O happens. It pumps a [`CaDevice`] against the
2//! sans-IO [`CiStack`]: reads frames in, executes the stack's [`Action`]s
3//! (writes/ioctls) out, tracks the requested poll timer, and collects
4//! [`Notification`]s for the host application.
5
6use mpeg_ts::pid::Pid;
7use std::collections::{BTreeSet, VecDeque};
8use std::io;
9use std::time::{Duration, Instant};
10
11use broadcast_core::Serialize;
12use dvb_ci::builder::{build_ca_pmt, build_ca_pmt_for_caids};
13use dvb_ci::objects::ca_pmt::{CaPmtCmdId, CaPmtListManagement};
14use dvb_si::tables::cat::CatSection;
15use dvb_si::tables::pmt::PmtSection;
16
17use broadcast_core::Parse;
18
19use crate::device::{CaDevice, MAX_CA_FRAME, SlotInfo};
20use crate::event::{Action, Event, HostRequest, HotPlug, MmiEvent, Notification};
21use crate::managed::{self, CaError, ManagedCa};
22use crate::stack::{CiStack, StackBounds};
23
24/// Substrings (case-insensitive) in MMI menu/list/enquiry text that
25/// heuristically indicate the smart card is absent. **Best-effort**: EN 50221
26/// defines no card-detect signal, so this is free-text sniffing of real CAM
27/// MMI copy, not a spec-defined mechanism.
28const MMI_CARD_ABSENT_KEYWORDS: &[&str] = &[
29    "no card",
30    "insert card",
31    "insert smart card",
32    "card removed",
33    "please insert",
34];
35
36/// Substrings (case-insensitive) in MMI menu/list/enquiry text that
37/// heuristically indicate a valid smart card is present (entitlements
38/// readable). **Best-effort**, same caveat as
39/// [`MMI_CARD_ABSENT_KEYWORDS`].
40const MMI_CARD_PRESENT_KEYWORDS: &[&str] = &["entitlement", "card valid", "subscription active"];
41
42/// The numbers a [`Driver`] runs on. The crate supplies none of them.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct DriverBounds {
45    /// The protocol stack's bounds.
46    pub stack: StackBounds,
47    /// Most [`Notification`]s buffered before the driver discards the oldest.
48    ///
49    /// A CAM that keeps sending malformed frames produces one notification per frame, and a host
50    /// that only ever calls [`Driver::pump`] never drains the queue, so it needs a bound. The
51    /// oldest entry is dropped first and every drop is counted in
52    /// [`Driver::notifications_dropped`].
53    pub max_pending_notifications: usize,
54    /// How long past the fixed post-`CA_RESET` settle window the first write to a still
55    /// initialising slot keeps being retried. The kernel's `dvb_ca_en50221_io_write` answers
56    /// `EINVAL` until the slot reaches its `RUNNING` state, and how long the CAM takes to get
57    /// there after a reset varies.
58    pub slot_ready_grace: Duration,
59    /// Pause between retries of a write the slot refused with `EINVAL`.
60    pub slot_retry: Duration,
61}
62
63/// Clock source for [`Driver::pump`]'s elapsed-time measurement (r10-W-21).
64/// A boxed closure (not a bare `fn` pointer) so a test's [`Driver::with_clock`]
65/// can capture mutable state to simulate a jump of arbitrary size in one call,
66/// which real wall-clock time cannot do deterministically.
67type Clock = Box<dyn Fn() -> Instant>;
68
69fn default_clock() -> Clock {
70    Box::new(Instant::now)
71}
72
73/// Drives a [`CaDevice`] with the [`CiStack`].
74pub struct Driver<D: CaDevice> {
75    device: D,
76    bounds: DriverBounds,
77    stack: CiStack,
78    notifications: VecDeque<Notification>,
79    /// Notifications discarded by the [`DriverBounds::max_pending_notifications`] bound.
80    notifications_dropped: u64,
81    /// Delay the stack last asked to be polled after (`None` = none pending).
82    next_timer: Option<Duration>,
83    /// Read buffer for one link-layer frame.
84    buf: Vec<u8>,
85    /// Last observed slot status (Part A hot-plug edge detection, #726).
86    /// `None` means no [`SlotInfo`] has been observed yet — the first
87    /// observation only establishes the baseline; it never itself fires
88    /// [`Notification::HotPlug`] carrying [`HotPlug::CamPresent`]/
89    /// [`CamRemoved`](HotPlug::CamRemoved), so `Driver::init` on an
90    /// already-inserted module doesn't spuriously re-drive its own handshake.
91    last_slot: Option<SlotInfo>,
92    /// Last `ca_info` CAID set seen for the current module (Part B card
93    /// inference, best-effort). `None` = not seen yet (baseline only).
94    last_caids: Option<BTreeSet<u16>>,
95    /// Last `ca_pmt_reply` `descrambling_ok` seen for the current module
96    /// (Part B card inference, best-effort). `None` = not seen yet.
97    last_descrambling_ok: Option<bool>,
98    /// Card state last inferred from MMI text (`Some(true)` present,
99    /// `Some(false)` absent, `None` = no card keyword seen yet): the keyword
100    /// heuristic only reports a card *transition*, so a CAM that re-sends
101    /// the same "insert card" menu does not repeat the notification (audit
102    /// r10-O-13).
103    last_mmi_card_present: Option<bool>,
104    /// The slot's managed CAS-layer state (#763 Layer 1) — active services
105    /// built via [`add_service`](Self::add_service).
106    managed: ManagedCa,
107    /// Wall-clock time of the start of the previous [`Self::pump`] call
108    /// (r10-W-21). `None` before the first call — that call's `timeout`
109    /// argument is used as-is, since there is no previous call to measure
110    /// from.
111    last_pump: Option<Instant>,
112    /// Clock source for [`Self::pump`] — see [`Clock`]/[`Self::with_clock`].
113    clock: Clock,
114    /// r10-W-20: a re-query-tick serialization failure recorded for later
115    /// reporting (a corrupt service must not silently swallow the healthy
116    /// services' resend); drained with priority on the next tick.
117    requery_pending: Option<CaError>,
118    /// r10-O-10: deadline until which the slot is settling after a
119    /// `CA_RESET` ([`CaDevice::reset_settle`]); no transport traffic is sent
120    /// or read before it. `None` = not settling.
121    settle_until: Option<Instant>,
122    /// Link-layer writes the stack emitted after the reset (the `Create_T_C`),
123    /// held back until `settle_until` passes.
124    deferred_writes: Vec<Vec<u8>>,
125    /// Until when a post-reset write that fails `EINVAL` ("slot not RUNNING
126    /// yet") is retried instead of reported: the reset instant + the settle
127    /// window + [`DriverBounds::slot_ready_grace`]. `None` = no retry window (no reset
128    /// settle, e.g. a mock device).
129    slot_ready_deadline: Option<Instant>,
130}
131
132impl<D: CaDevice> Driver<D> {
133    /// New driver over `device`, single transport connection, running on the caller's `bounds`.
134    #[must_use]
135    pub fn new(device: D, bounds: DriverBounds) -> Self {
136        Self {
137            device,
138            bounds,
139            stack: CiStack::new(bounds.stack),
140            notifications: VecDeque::new(),
141            notifications_dropped: 0,
142            next_timer: None,
143            buf: vec![0u8; MAX_CA_FRAME],
144            last_slot: None,
145            last_caids: None,
146            last_descrambling_ok: None,
147            last_mmi_card_present: None,
148            managed: ManagedCa::new(),
149            last_pump: None,
150            clock: default_clock(),
151            requery_pending: None,
152            settle_until: None,
153            deferred_writes: Vec::new(),
154            slot_ready_deadline: None,
155        }
156    }
157
158    /// Override [`Self::pump`]'s clock source (r10-W-21) — `Instant::now`
159    /// by default. A test uses this to simulate an arbitrary elapsed jump
160    /// deterministically, in place of a real sleep.
161    #[must_use]
162    pub fn with_clock(mut self, clock: impl Fn() -> Instant + 'static) -> Self {
163        self.clock = Box::new(clock);
164        self
165    }
166
167    /// The slot's managed CAS-layer state (#763 Layer 1) — the active
168    /// service set built via [`add_service`](Self::add_service).
169    pub fn managed_ca(&self) -> &ManagedCa {
170        &self.managed
171    }
172
173    /// Borrow the underlying device (e.g. to inspect a mock's recorded ops).
174    pub fn device(&self) -> &D {
175        &self.device
176    }
177
178    /// Mutably borrow the underlying device (e.g. to script a mock's inbound
179    /// frames between pumps).
180    pub fn device_mut(&mut self) -> &mut D {
181        &mut self.device
182    }
183
184    /// The poll delay the stack most recently requested, if any.
185    pub fn next_timer(&self) -> Option<Duration> {
186        self.next_timer
187    }
188
189    /// Drain the notifications collected so far.
190    pub fn take_notifications(&mut self) -> Vec<Notification> {
191        self.notifications.drain(..).collect()
192    }
193
194    /// How many notifications have been discarded by the
195    /// [`DriverBounds::max_pending_notifications`] bound over this driver's lifetime — a
196    /// non-zero value means a host that does not drain
197    /// [`take_notifications`](Self::take_notifications) (or use
198    /// [`pump_with`](Self::pump_with)) missed that many of the oldest ones.
199    pub fn notifications_dropped(&self) -> u64 {
200        self.notifications_dropped
201    }
202
203    /// Queue one notification, discarding the oldest buffered one when the
204    /// [`DriverBounds::max_pending_notifications`] bound is reached.
205    fn push_notification(&mut self, n: Notification) {
206        if self.notifications.len() >= self.bounds.max_pending_notifications {
207            self.notifications.pop_front();
208            self.notifications_dropped += 1;
209        }
210        self.notifications.push_back(n);
211    }
212
213    /// Bring the interface up (reset + open the transport connection).
214    pub fn init(&mut self) -> io::Result<()> {
215        let actions = self.stack.handle(Event::Host(HostRequest::Init));
216        self.run(actions)
217    }
218
219    /// Request the module descramble the services in `ca_pmt` (a serialized
220    /// `ca_pmt` APDU body, e.g. from `dvb_ci::build_ca_pmt`).
221    pub fn send_ca_pmt(&mut self, ca_pmt: &[u8]) -> io::Result<()> {
222        let actions = self
223            .stack
224            .handle(Event::Host(HostRequest::SendCaPmt(ca_pmt)));
225        self.run(actions)
226    }
227
228    fn send_ca_pmt_checked(&mut self, ca_pmt: &[u8]) -> Result<(), CaError> {
229        let before = self.notifications.len();
230        let dropped_before = self.notifications_dropped;
231        self.send_ca_pmt(ca_pmt)?;
232        let start = before.saturating_sub((self.notifications_dropped - dropped_before) as usize);
233        let refusal = self.notifications.range(start..).find_map(|n| match n {
234            Notification::Error { detail } => Some(detail.clone()),
235            _ => None,
236        });
237        refusal.map_or(Ok(()), |detail| Err(CaError::NotSent { detail }))
238    }
239
240    /// Descramble the services in a PMT section: the stack filters the PMT's
241    /// `CA_descriptor`s to the CAM's advertised CAIDs and sends a `ca_pmt`
242    /// (`list_management = only`, `cmd_id = ok_descrambling`). The outcome
243    /// surfaces as [`Notification::CaPmtReply`]. Call after the CAM is ready and
244    /// its `ca_info` has been received (otherwise no CAID filter is applied).
245    pub fn descramble(&mut self, pmt_section: &[u8]) -> io::Result<()> {
246        let actions = self
247            .stack
248            .handle(Event::Host(HostRequest::Descramble(pmt_section)));
249        self.run(actions)
250    }
251
252    /// Descramble a set of programmes in one CA-PMT list (`first`/`more`/`last`),
253    /// replacing any previously selected set. Each element is a raw PMT section.
254    pub fn descramble_programs(&mut self, pmt_sections: &[&[u8]]) -> io::Result<()> {
255        let actions = self
256            .stack
257            .handle(Event::Host(HostRequest::DescramblePrograms(pmt_sections)));
258        self.run(actions)
259    }
260
261    /// Add one programme to the descrambled set (`list_management = add`) without
262    /// re-listing the others — for a capacity manager adding a viewer's service.
263    pub fn add_program(&mut self, pmt_section: &[u8]) -> io::Result<()> {
264        let actions = self
265            .stack
266            .handle(Event::Host(HostRequest::AddProgram(pmt_section)));
267        self.run(actions)
268    }
269
270    /// Remove one programme from the descrambled set (`list_management = update`,
271    /// `cmd_id = not_selected`) — tells the CAM to stop descrambling it.
272    pub fn remove_program(&mut self, pmt_section: &[u8]) -> io::Result<()> {
273        let actions = self
274            .stack
275            .handle(Event::Host(HostRequest::RemoveProgram(pmt_section)));
276        self.run(actions)
277    }
278
279    /// Build the `ca_pmt` projection of `pmt`, CAID-filtered to the CAM's
280    /// advertised `ca_info` CAIDs once known (#1067): a CICAM rejects a
281    /// `ca_pmt` carrying a `CA_descriptor` for a `CA_system_id` it does not
282    /// support, declining even the streams it could descramble
283    /// (`dvb_ci::builder::build_ca_pmt_for_caids`'s own doc). Shared by
284    /// [`add_service`](Self::add_service) and the entitlement re-query timer
285    /// ([`requery_tick`](Self::requery_tick)) so both apply the same filter
286    /// the raw [`descramble`](Self::descramble) path already does
287    /// (`CiStack::build_ca_pmt_bytes`). Falls back to every `CA_descriptor`
288    /// unfiltered before any `ca_info` has been observed, matching that same
289    /// fallback.
290    fn build_ca_pmt_filtered(
291        &self,
292        pmt: &PmtSection<'_>,
293        list_management: CaPmtListManagement,
294        cmd_id: CaPmtCmdId,
295    ) -> dvb_ci::builder::CaPmtBuilt {
296        let cam_caids = self.managed.cam_caids();
297        if cam_caids.is_empty() {
298            build_ca_pmt(pmt, list_management, cmd_id)
299        } else {
300            let allowed: Vec<u16> = cam_caids.iter().copied().collect();
301            build_ca_pmt_for_caids(pmt, &allowed, list_management, cmd_id)
302        }
303    }
304
305    /// Shared build + serialize half of [`add_service`](Self::add_service) and
306    /// [`update_service`](Self::update_service): validates the `CA_descriptor`
307    /// presence, builds the CAID-filtered `ca_pmt` (`try_to_bytes` first, so an
308    /// unencodable PMT is rejected before any state is touched or anything is
309    /// sent), and re-serializes the raw PMT bytes. Returns `(built_ca_pmt_bytes,
310    /// pmt_raw_bytes)`. Sending and recording are the caller's responsibility
311    /// so each entry point keeps its own `list_management` and managed-set
312    /// semantics.
313    fn build_service_bytes(
314        &self,
315        pmt: &PmtSection<'_>,
316        list_management: CaPmtListManagement,
317        cmd_id: CaPmtCmdId,
318    ) -> Result<(Vec<u8>, Vec<u8>), CaError> {
319        if !managed::pmt_has_ca(pmt) {
320            return Err(CaError::NoCaDescriptor {
321                program_number: pmt.program_number,
322            });
323        }
324        // r10-W-20: `try_to_bytes`, not `to_bytes`.
325        let built_bytes = self
326            .build_ca_pmt_filtered(pmt, list_management, cmd_id)
327            .to_bytes()?;
328        let mut pmt_raw = vec![0u8; pmt.serialized_len()];
329        let n = pmt.serialize_into(&mut pmt_raw)?;
330        pmt_raw.truncate(n);
331        Ok((built_bytes, pmt_raw))
332    }
333
334    /// Build + send the `ca_pmt` for `pmt` (via
335    /// [`dvb_ci::builder::build_ca_pmt`], ETSI EN 50221 §8.4.3.4 Table 25) and
336    /// track it in the slot's managed active-service set (#763 Layer 1).
337    /// Additive alongside the raw [`send_ca_pmt`](Self::send_ca_pmt) and the
338    /// existing multi-programme API
339    /// ([`descramble_programs`](Self::descramble_programs)/
340    /// [`add_program`](Self::add_program)).
341    ///
342    /// `list_management` (EN 50221 Table 25) is auto-selected from the tracked
343    /// set: `Only` when this is the first service added to an empty managed
344    /// set, `Add` when joining an already-active set. (Contrast the raw
345    /// [`add_program`](Self::add_program), which always sends `Add` and leaves
346    /// list-management sequencing to the caller.)
347    ///
348    /// # Errors
349    /// [`CaError::NoCaDescriptor`] if `pmt` carries no `CA_descriptor`
350    /// (ISO/IEC 13818-1 §2.6.16, tag `0x09`) at programme or
351    /// elementary-stream level — there would be nothing for the CAM to
352    /// descramble. [`CaError::Io`] if sending the built `ca_pmt` fails.
353    /// [`CaError::NotSent`] if the stack could not hand it to the CAM (no open
354    /// CA session, inactive connection, full queue); nothing is recorded.
355    pub fn add_service(&mut self, pmt: &PmtSection<'_>) -> Result<(), CaError> {
356        let list_management = if self.managed.is_empty() {
357            CaPmtListManagement::Only
358        } else {
359            CaPmtListManagement::Add
360        };
361        let cmd_id = CaPmtCmdId::OkDescrambling;
362        let (built_bytes, pmt_raw) = self.build_service_bytes(pmt, list_management, cmd_id)?;
363        self.send_ca_pmt_checked(&built_bytes)?;
364        self.managed.record(
365            pmt.program_number,
366            managed::service_of(pmt, cmd_id, built_bytes, pmt_raw),
367        );
368        Ok(())
369    }
370
371    /// Update (re-send) the `ca_pmt` for a programme already in the managed
372    /// set, using `ca_pmt_list_management = update` (ETSI EN 50221 §8.4.3.4
373    /// Table 25, `ca_pmt_list_management` value `0x05` "update"). EN 50221
374    /// p. 31: "the CA PMT of a programme already in the list is sent again
375    /// because the version_number or the current_next_indicator has changed.
376    /// ... Since the list management commands act only at the programme level,
377    /// any changes at the elementary stream level in an existing programme
378    /// must be signalled by an 'update' command with the complete elementary
379    /// stream list re-sent." The same page notes that re-sending `add` for an
380    /// already-existing programme is already equivalent to `update`, so
381    /// [`add_service`](Self::add_service) remains spec-conforming; this method
382    /// exists as the explicit, clearer entry point for that case.
383    ///
384    /// The stored service record is **replaced** with the new PMT bytes, so
385    /// later [`remove_service`](Self::remove_service) and the periodic
386    /// re-query use the new PMT.
387    ///
388    /// # Errors
389    /// [`CaError::NotManaged`] if `pmt.program_number` is not currently
390    /// managed. [`CaError::NoCaDescriptor`] if `pmt` carries no
391    /// `CA_descriptor` (ISO/IEC 13818-1 §2.6.16, tag `0x09`) — the stored
392    /// record is left unchanged. [`CaError::Serialize`] if the projected
393    /// `ca_pmt` has no valid wire encoding — the record is left unchanged and
394    /// nothing is sent. [`CaError::Io`] if sending the built `ca_pmt` fails.
395    pub fn update_service(&mut self, pmt: &PmtSection<'_>) -> Result<(), CaError> {
396        if !self.managed.services().contains_key(&pmt.program_number) {
397            return Err(CaError::NotManaged {
398                program_number: pmt.program_number,
399            });
400        }
401        let list_management = CaPmtListManagement::Update;
402        let cmd_id = CaPmtCmdId::OkDescrambling;
403        let (built_bytes, pmt_raw) = self.build_service_bytes(pmt, list_management, cmd_id)?;
404        self.send_ca_pmt_checked(&built_bytes)?;
405        self.managed.record(
406            pmt.program_number,
407            managed::service_of(pmt, cmd_id, built_bytes, pmt_raw),
408        );
409        Ok(())
410    }
411
412    /// Stop descrambling a previously-added service (#763 Task 6): sends the
413    /// removal `ca_pmt` (`list_management = update`, `cmd_id = not_selected`,
414    /// EN 50221 §8.4.3.4 Table 25) via the existing
415    /// [`remove_program`](Self::remove_program) path — re-driving it with the
416    /// raw PMT bytes stashed at [`add_service`](Self::add_service) time — then
417    /// drops the service from the managed set.
418    ///
419    /// Removing a `program_number` that isn't currently tracked (never
420    /// `add_service`'d, or already removed) is a **no-op**, not an error:
421    /// [`CaError`] has no not-found arm, and `remove_service` is idempotent.
422    ///
423    /// # Errors
424    /// [`CaError::Io`] if sending the removal `ca_pmt` fails.
425    pub fn remove_service(&mut self, program_number: u16) -> Result<(), CaError> {
426        let raw = self
427            .managed
428            .services()
429            .get(&program_number)
430            .map(|s| s.pmt_raw.clone());
431        let Some(raw) = raw else {
432            return Ok(());
433        };
434        self.remove_program(&raw)?;
435        self.managed.remove(program_number);
436        Ok(())
437    }
438
439    /// Set the entitlement re-query cadence (#763 Task 5): every
440    /// `interval`, the driver re-sends each actively-managed service's
441    /// `ca_pmt` as a `list_management = update` pair — `cmd_id = query`
442    /// immediately followed by `cmd_id = ok_descrambling` — see
443    /// `requery_tick` for why both, #1032. `Duration::ZERO` disables
444    /// re-query. **Opt-in**: defaults to [`managed::REQUERY_DEFAULT`]
445    /// (`Duration::ZERO`) at construction (the periodic re-query is hardware-verified
446    /// on an entitled AlphaCrypt module since #1032, but stays opt-in).
447    pub fn set_requery_interval(&mut self, interval: Duration) {
448        self.managed.set_requery_interval(interval);
449    }
450
451    /// Feed a freshly-parsed CAT (ISO/IEC 13818-1 §2.4.4.7) to the managed
452    /// CAS-layer state: extracts its `CA_descriptor`s (ISO/IEC 13818-1 §2.6.16,
453    /// CAID → EMM PID) and recomputes [`emm_pids`](Self::emm_pids) against
454    /// the CAM's advertised CAIDs (last `Notification::CaInfo`, captured
455    /// automatically as it arrives — see [`pump`](Self::pump)).
456    ///
457    /// Calling this before any `ca_info` has been observed is **not** an
458    /// error: [`emm_pids`](Self::emm_pids) stays empty until the CAM
459    /// advertises its CAIDs, then recomputes against the CAT stored here —
460    /// `set_cat` need not be re-called once `ca_info` arrives.
461    ///
462    /// # Errors
463    /// [`CaError::Cat`] if the CAT's descriptor loop carries a truncated
464    /// `CA_descriptor`.
465    pub fn set_cat(&mut self, cat: &CatSection<'_>) -> Result<(), CaError> {
466        let entries = cat.ca_descriptors().map_err(CaError::Cat)?;
467        self.managed.set_cat(&entries);
468        Ok(())
469    }
470
471    /// The EMM PIDs to route into `ci0` — the last [`set_cat`](Self::set_cat)'s
472    /// list of `(CAID, EMM PID)` entries (a CAID may have several) intersected with the CAM's advertised CAIDs (#763
473    /// Task 4).
474    #[must_use]
475    pub fn emm_pids(&self) -> &[Pid] {
476        self.managed.emm_pids()
477    }
478
479    /// The PIDs to route into `ci0` for descrambling — the union of every
480    /// actively-managed service's elementary-stream PIDs (#763 Task 4).
481    #[must_use]
482    pub fn descramble_pids(&self) -> &[Pid] {
483        self.managed.descramble_pids()
484    }
485
486    /// The union of every actively-managed service's `CA_PID`s (ECM PIDs —
487    /// ISO/IEC 13818-1 §2.6.16 `CA_descriptor` `CA_PID`, programme + ES level
488    /// combined) — the control-word channel, without which the module has ES
489    /// to descramble but no control words to do it with (#763 Task 7).
490    #[must_use]
491    pub fn ca_pids(&self) -> &[Pid] {
492        self.managed.ca_pids()
493    }
494
495    /// `descramble_pids() ∪ ca_pids() ∪ emm_pids() ∪ PCR ∪ CAT` — every PID class
496    /// this slot needs on `ci0` (ES to descramble ∪ ECM for control words ∪
497    /// EMM for entitlements ∪ each active service's PCR PID — ISO/IEC
498    /// 13818-1 §2.4.4.9 — so the descrambled TS keeps its clock reference
499    /// even when the PCR rides a dedicated PID). #763 Task 7's turnkey
500    /// [`CaDescrambler`](crate::descrambler::CaDescrambler) filters its
501    /// `feed_ts` input to exactly this set.
502    #[must_use]
503    pub fn required_pids(&self) -> Vec<Pid> {
504        self.managed.required_pids()
505    }
506
507    /// Answer an MMI menu/list by 1-based `choice_ref` (0 = back/cancel).
508    pub fn mmi_menu_answer(&mut self, choice_ref: u8) -> io::Result<()> {
509        let actions = self
510            .stack
511            .handle(Event::Host(HostRequest::MmiMenuAnswer(choice_ref)));
512        self.run(actions)
513    }
514
515    /// Answer an MMI enquiry with the user's input (EN 300 468 Annex A bytes).
516    pub fn mmi_enquiry_answer(&mut self, text: &[u8]) -> io::Result<()> {
517        let actions = self
518            .stack
519            .handle(Event::Host(HostRequest::MmiEnquiryAnswer(text)));
520        self.run(actions)
521    }
522
523    /// Abort the current MMI dialogue (`answ` with `answ_id = cancel`).
524    pub fn mmi_cancel(&mut self) -> io::Result<()> {
525        let actions = self.stack.handle(Event::Host(HostRequest::MmiCancel));
526        self.run(actions)
527    }
528
529    /// Ask the module to open its MMI menu (`enter_menu`) — e.g. to read card /
530    /// entitlement info from the module's own menus.
531    pub fn enter_menu(&mut self) -> io::Result<()> {
532        let actions = self.stack.handle(Event::Host(HostRequest::EnterMenu));
533        self.run(actions)
534    }
535
536    /// One pump step: if the device is readable within `timeout`, read a frame
537    /// and feed it; otherwise advance the stack's timers by `timeout` (driving
538    /// the poll cadence). Returns whether a frame was processed.
539    ///
540    /// Also samples [`SlotInfo`] once per call (the DVB-CA slot has no
541    /// interrupt/event of its own; `CA_GET_SLOT_INFO` is a poll) so a hot-plug
542    /// edge is caught between reads — see [`Notification::HotPlug`] carrying
543    /// [`HotPlug::CamPresent`]/[`CamRemoved`](HotPlug::CamRemoved) (#726).
544    pub fn pump(&mut self, timeout: Duration) -> io::Result<bool> {
545        // r10-W-21: advance the stack's timers by the REAL wall-clock time
546        // since the previous call, not by `timeout` — `timeout` is only how
547        // long THIS call's `poll` was willing to wait; the actual elapsed
548        // time can be far less (poll returns as soon as the device is
549        // readable, or a signal interrupts it early) or far more (the
550        // caller's own loop didn't call `pump` again promptly). Using
551        // `timeout` as if it were the measurement let the reply-timeout/poll
552        // cadence drift out of sync with real time in either direction.
553        // `None` (first call) has no previous point to measure from, so
554        // `timeout` is used as a reasonable initial estimate, same as before.
555        let now = (self.clock)();
556        let measured = self.last_pump.is_some();
557        let mut elapsed = self
558            .last_pump
559            .map_or(timeout, |prev| now.saturating_duration_since(prev));
560        self.last_pump = Some(now);
561
562        // r10-O-10: a slot still settling after `CA_RESET` gets no transport
563        // traffic and no timer advance — only the slot-status sample, so a
564        // hot-plug edge (which restarts the settle) is still seen. Returns
565        // immediately; the caller's loop owns pacing.
566        if let Some(until) = self.settle_until {
567            if now < until {
568                self.run(vec![Action::QuerySlot])?;
569                return Ok(false);
570            }
571            self.settle_until = None;
572            let mut pending = std::mem::take(&mut self.deferred_writes).into_iter();
573            while let Some(w) = pending.next() {
574                match self.device.write(&w) {
575                    Ok(()) => {}
576                    // `EINVAL` (`InvalidInput`) from the post-reset write means
577                    // the slot is not RUNNING yet, not that the frame is bad:
578                    // keep this write and the rest, and try again shortly -
579                    // until the grace window runs out, then report it.
580                    Err(e)
581                        if e.kind() == io::ErrorKind::InvalidInput
582                            && self.slot_ready_deadline.is_some_and(|d| now < d) =>
583                    {
584                        self.deferred_writes = std::iter::once(w).chain(pending).collect();
585                        self.settle_until = Some(now + self.bounds.slot_retry);
586                        return Ok(false);
587                    }
588                    Err(e) => return Err(e),
589                }
590            }
591            self.slot_ready_deadline = None;
592            // The settle period must not count against the transport's
593            // reply timeout.
594            elapsed = Duration::ZERO;
595        }
596
597        self.run(vec![Action::QuerySlot])?;
598        if self.device.poll(timeout)? {
599            let n = self.device.read(&mut self.buf)?;
600            if n > 0 {
601                // `stack` and `buf` are disjoint fields: borrow the received
602                // bytes in place instead of copying each frame (audit
603                // r10-O-11).
604                let actions = self.stack.handle(Event::Readable(&self.buf[..n]));
605                self.run(actions)?;
606                if measured && !elapsed.is_zero() {
607                    let actions = self.stack.handle(Event::Tick { elapsed });
608                    self.run(actions)?;
609                    self.requery_tick(elapsed)?;
610                }
611                return Ok(true);
612            }
613        }
614        let actions = self.stack.handle(Event::Tick { elapsed });
615        self.run(actions)?;
616        self.requery_tick(elapsed)?;
617        Ok(false)
618    }
619
620    /// Advance the #763 Task 5 entitlement re-query cadence by `elapsed`
621    /// ([`ManagedCa::tick`](crate::managed::ManagedCa::tick), mirroring
622    /// `resource.rs`'s `DateTime::tick` accumulate-then-fire pattern). When
623    /// the interval elapses, rebuild and re-send, for every actively-managed
624    /// service, a `list_management = update` **pair**:
625    ///
626    /// 1. `cmd_id = query` (EN 50221 §8.4.3.5: "host expects a CA PMT Reply;
627    ///    application not allowed to start descrambling or MMI before a new
628    ///    CA PMT with `ok_descrambling`/`ok_mmi`") — solicits a fresh
629    ///    `ca_pmt_reply` from a CAM that answers queries, surfacing as
630    ///    [`Notification::CaPmtReply`] and, on a status change,
631    ///    [`Notification::Entitlement`].
632    /// 2. `cmd_id = ok_descrambling` (§8.4.3.5: "host expects no answer; the
633    ///    application may start descrambling ... immediately"), sent
634    ///    unconditionally right after — so descrambling is never left barred
635    ///    by the query above, whether or not the CAM answers it.
636    ///
637    /// **#1032 fix**: the pre-fix code sent only `only`/`first` + `query`.
638    /// EN 50221 §8.4.3.4 Table 25's `first`/`only` *replaces* every
639    /// previously-selected programme, and §8.4.3.5's `query` bars
640    /// descrambling until an `ok_descrambling` that was never sent — so
641    /// descrambling silently stopped ~`interval` after it started. `update`
642    /// ("the CA PMT of a programme already in the list is sent again ...
643    /// List management commands act only at programme level", §8.4.3.4)
644    /// never replaces the list, and the unconditional follow-up
645    /// `ok_descrambling` guarantees the bar is always lifted even though
646    /// `stack.rs`'s `descramble` already documents that a live
647    /// AlphaCrypt/Irdeto module never answers `query` at all — this is why
648    /// [`managed::REQUERY_DEFAULT`] is `Duration::ZERO`: the feature is
649    /// opt-in until the `query` half is verified to elicit a reply on a
650    /// caller's own hardware.
651    ///
652    /// **#765 (retained)**: the re-query set is rebuilt fresh from each
653    /// service's stored `pmt_raw` on *every* tick against the *current*
654    /// active set (`services`, a `BTreeMap`) — a removed service is not
655    /// resent, and a survivor is rebuilt from its own current PMT — rather
656    /// than freezing anything at `add_service` time. `update` needs no
657    /// first/more/last position bookkeeping (§8.4.3.4: "act only at
658    /// programme level"), so unlike the pre-fix code this no longer depends
659    /// on the active set's size or a service's position within it.
660    ///
661    /// CAID-filtered via [`build_ca_pmt_filtered`](Self::build_ca_pmt_filtered)
662    /// (#1067), same as [`add_service`](Self::add_service).
663    fn requery_tick(&mut self, elapsed: Duration) -> io::Result<()> {
664        // r10-W-20: a previously-recorded rejection is reported FIRST, on
665        // every pump until the caller fixes its state — never swallowed by
666        // an earlier `tick` return.
667        if let Some(err) = self.requery_pending.take() {
668            return Err(io::Error::other(err));
669        }
670        if !self.managed.tick(elapsed) {
671            return Ok(());
672        }
673        let mut ca_pmts: Vec<(Vec<u8>, Vec<u8>)> =
674            Vec::with_capacity(self.managed.services().len());
675        for s in self.managed.services().values() {
676            // r10-W-20: no `expect`/`to_bytes` here — `pmt_raw` is only
677            // as trustworthy as whatever the caller's CAM (or a
678            // corrupted capture) supplied, so a re-parse or re-serialize
679            // failure must end this re-query as `Err`, not a panic.
680            let outcome: Result<(Vec<u8>, Vec<u8>), CaError> = (|| {
681                let pmt = PmtSection::parse(&s.pmt_raw).map_err(CaError::PmtParse)?;
682                let query = self
683                    .build_ca_pmt_filtered(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
684                    .to_bytes()?;
685                let ok_descrambling = self
686                    .build_ca_pmt_filtered(
687                        &pmt,
688                        CaPmtListManagement::Update,
689                        CaPmtCmdId::OkDescrambling,
690                    )
691                    .to_bytes()?;
692                Ok((query, ok_descrambling))
693            })();
694            match outcome {
695                Ok(pair) => ca_pmts.push(pair),
696                Err(err) => {
697                    // One corrupt (or CAM-supplied) service must not poison
698                    // the healthy services' resend this tick: record it and
699                    // return the failure after the good pair(s) went out.
700                    self.requery_pending = Some(err);
701                }
702            }
703        }
704        for (query, ok_descrambling) in ca_pmts {
705            self.send_ca_pmt(&query)?;
706            self.send_ca_pmt(&ok_descrambling)?;
707        }
708        if let Some(err) = self.requery_pending.take() {
709            return Err(io::Error::other(err));
710        }
711        Ok(())
712    }
713
714    /// Pump once ([`pump`](Self::pump)), then invoke `handler` for each
715    /// [`Notification`] produced this cycle (drain-and-dispatch via
716    /// [`take_notifications`](Self::take_notifications)). Returns the same
717    /// bool as `pump`. The closure is per-call — nothing is stored, so there
718    /// are no lifetime constraints beyond the call itself. This crate is
719    /// sync/sans-IO (no channels/async runtime), so a closure callback is the
720    /// idiomatic push-style alternative to poll-draining `take_notifications`
721    /// yourself.
722    pub fn pump_with<F: FnMut(&Notification)>(
723        &mut self,
724        timeout: Duration,
725        mut handler: F,
726    ) -> io::Result<bool> {
727        let progressed = self.pump(timeout)?;
728        for n in self.take_notifications() {
729            handler(&n);
730        }
731        Ok(progressed)
732    }
733
734    /// Convenience over [`pump_with`](Self::pump_with): invoke `handler` only
735    /// for [`HotPlug`] transitions, ignoring every other [`Notification`]
736    /// produced this cycle.
737    pub fn pump_hotplug<F: FnMut(HotPlug)>(
738        &mut self,
739        timeout: Duration,
740        mut handler: F,
741    ) -> io::Result<bool> {
742        self.pump_with(timeout, |n| {
743            if let Some(h) = n.hotplug() {
744                handler(h);
745            }
746        })
747    }
748
749    /// Execute the stack's actions against the device.
750    fn run(&mut self, actions: Vec<Action>) -> io::Result<()> {
751        for action in actions {
752            match action {
753                Action::Write(bytes) => {
754                    if self.settle_until.is_some() {
755                        self.deferred_writes.push(bytes);
756                    } else {
757                        self.device.write(&bytes)?;
758                    }
759                }
760                Action::Reset => {
761                    self.device.reset()?;
762                    // r10-O-10: a (re)reset restarts the settle window and
763                    // discards writes queued for the previous incarnation.
764                    self.deferred_writes.clear();
765                    let settle = self.device.reset_settle();
766                    let now = (self.clock)();
767                    self.settle_until = (!settle.is_zero()).then(|| now + settle);
768                    self.slot_ready_deadline =
769                        (!settle.is_zero()).then(|| now + settle + self.bounds.slot_ready_grace);
770                }
771                Action::QuerySlot => {
772                    let info = self.device.slot_info()?;
773                    self.handle_slot_info(info)?;
774                }
775                Action::SetTimer { after } => self.next_timer = Some(after),
776                Action::Notify(n) => {
777                    let inferred = self.infer_card(&n);
778                    self.push_notification(n);
779                    for note in inferred {
780                        self.push_notification(note);
781                    }
782                }
783            }
784        }
785        Ok(())
786    }
787
788    /// Compare a freshly-queried [`SlotInfo`] against the last one observed
789    /// and react to a `module_present` edge (Part A, #726): the *first*
790    /// observation ever (`self.last_slot == None`) only establishes the
791    /// baseline — it must not fire a notification, or `Driver::init` against
792    /// an already-inserted module would spuriously report a hot-plug and
793    /// recurse into re-driving its own in-progress handshake.
794    fn handle_slot_info(&mut self, info: SlotInfo) -> io::Result<()> {
795        let prev = self.last_slot.replace(info);
796        match prev {
797            Some(prev) if !prev.module_present && info.module_present => {
798                self.push_notification(Notification::HotPlug(HotPlug::CamPresent));
799                self.reset_module_state();
800                // Re-drive the same reset/init path `Driver::init` uses, so
801                // the newly-inserted module gets a clean resource-manager
802                // handshake (no duplicated handshake logic).
803                let actions = self.stack.handle(Event::Host(HostRequest::Init));
804                self.run(actions)?;
805            }
806            Some(prev) if prev.module_present && !info.module_present => {
807                self.push_notification(Notification::HotPlug(HotPlug::CamRemoved));
808                self.reset_module_state();
809            }
810            _ => {}
811        }
812        Ok(())
813    }
814
815    /// Reset per-module protocol + card-inference state after a CAM
816    /// insert/remove edge: a fresh [`CiStack`] (so a re-insert re-handshakes
817    /// cleanly instead of reusing stale session numbers) and cleared Part B
818    /// baselines (so the next module's `ca_info`/`ca_pmt_reply` establishes
819    /// its own fresh baseline rather than diffing against the departed
820    /// module's), AND the managed CAS-layer state (#763 Task 6 fix): a stale
821    /// `services`/`descramble_pids`/`emm_pids` set must not survive a
822    /// departed or freshly-inserted module — the host must re-provision from
823    /// scratch (the next `add_service` then correctly picks `Only` again).
824    fn reset_module_state(&mut self) {
825        self.stack = CiStack::new(self.bounds.stack);
826        self.settle_until = None;
827        self.slot_ready_deadline = None;
828        self.deferred_writes.clear();
829        self.next_timer = None;
830        self.last_caids = None;
831        self.last_descrambling_ok = None;
832        self.last_mmi_card_present = None;
833        self.managed.clear();
834    }
835
836    /// Best-effort app-layer card-presence inference (Part B, #726): EN 50221
837    /// CI slots are module-level only — there is no card-detect line (verified
838    /// against real DD ddbridge / cxd2099 driver behaviour) — so this derives
839    /// card insert/remove/change from signals the module already sends for
840    /// other reasons. Returns any inferred [`Notification`]s (0 or 1); `note`
841    /// itself is pushed by the caller.
842    fn infer_card(&mut self, note: &Notification) -> Vec<Notification> {
843        match note {
844            Notification::CaInfo { ca_system_ids } => {
845                let new_set: BTreeSet<u16> = ca_system_ids.iter().copied().collect();
846                let mut out = Vec::new();
847                if let Some(prev) = &self.last_caids {
848                    if prev.is_empty() && !new_set.is_empty() {
849                        out.push(Notification::HotPlug(HotPlug::CardInserted));
850                    } else if !prev.is_empty() && new_set.is_empty() {
851                        out.push(Notification::HotPlug(HotPlug::CardRemoved));
852                    } else if !prev.is_empty() && !new_set.is_empty() && *prev != new_set {
853                        out.push(Notification::HotPlug(HotPlug::CardChanged));
854                    }
855                }
856                // #763 Task 4: feed the CAM's advertised CAIDs to the managed
857                // CAS-layer state so `emm_pids` recomputes against the
858                // already-stored CAT map (if `set_cat` ran first).
859                self.managed.set_cam_caids(new_set.clone());
860                self.last_caids = Some(new_set);
861                out
862            }
863            Notification::CaPmtReply {
864                program_number,
865                ca_enable,
866                descrambling_ok,
867            } => {
868                let mut out = Vec::new();
869                if let Some(prev) = self.last_descrambling_ok {
870                    if !prev && *descrambling_ok {
871                        out.push(Notification::HotPlug(HotPlug::CardInserted));
872                    } else if prev && !*descrambling_ok {
873                        out.push(Notification::HotPlug(HotPlug::CardRemoved));
874                    }
875                }
876                self.last_descrambling_ok = Some(*descrambling_ok);
877                // #763 Task 5: diff this reply's programme-level status
878                // against the last one recorded for `program_number` and
879                // surface the edge-triggered `Notification::Entitlement`.
880                if let Some((v, ok)) =
881                    self.managed
882                        .record_reply(*program_number, *ca_enable, *descrambling_ok)
883                {
884                    out.push(Notification::Entitlement {
885                        program_number: *program_number,
886                        ca_enable: v,
887                        descrambling_ok: ok,
888                    });
889                }
890                out
891            }
892            Notification::Mmi(ev) => {
893                let present = Self::mmi_text(ev).and_then(|text| {
894                    let lower = text.to_lowercase();
895                    if MMI_CARD_ABSENT_KEYWORDS.iter().any(|k| lower.contains(k)) {
896                        Some(false)
897                    } else if MMI_CARD_PRESENT_KEYWORDS.iter().any(|k| lower.contains(k)) {
898                        Some(true)
899                    } else {
900                        None
901                    }
902                });
903                match present {
904                    // Edge only: the same state repeated is not news.
905                    Some(p) if self.last_mmi_card_present != Some(p) => {
906                        self.last_mmi_card_present = Some(p);
907                        vec![Notification::HotPlug(if p {
908                            HotPlug::CardInserted
909                        } else {
910                            HotPlug::CardRemoved
911                        })]
912                    }
913                    _ => Vec::new(),
914                }
915            }
916            _ => Vec::new(),
917        }
918    }
919
920    /// The free-text an [`MmiEvent`] carries, for the keyword heuristic above
921    /// (title/subtitle/bottom/choices for a menu/list, the prompt for an
922    /// enquiry; a `Close` carries no text).
923    fn mmi_text(ev: &MmiEvent) -> Option<String> {
924        match ev {
925            MmiEvent::Menu(m) | MmiEvent::List(m) => {
926                let mut s = format!("{} {} {}", m.title, m.subtitle, m.bottom);
927                for choice in &m.choices {
928                    s.push(' ');
929                    s.push_str(choice);
930                }
931                Some(s)
932            }
933            MmiEvent::Enquiry { prompt, .. } => Some(prompt.clone()),
934            MmiEvent::Close => None,
935        }
936    }
937}
938
939#[cfg(test)]
940pub(crate) mod tests {
941    use super::*;
942    use crate::device::{DeviceOp, MockCaDevice};
943    use crate::event::{HostControlEvent, HotPlug, Notification};
944    use crate::test_support::*;
945    use broadcast_core::Serialize;
946    use dvb_ci::tpdu::tags;
947
948    pub(crate) fn ser<S: Serialize>(s: &S) -> Vec<u8> {
949        let mut b = vec![0u8; s.serialized_len()];
950        match s.serialize_into(&mut b) {
951            Ok(n) => b.truncate(n),
952            Err(_) => b.clear(),
953        }
954        b
955    }
956
957    /// A manually-advanced fake clock for [`Driver::with_clock`] (r10-W-21):
958    /// `pump`'s elapsed-time measurement is now real wall-clock time, so a
959    /// test that wants to simulate "N of simulated time passed" in one
960    /// `pump` call (rather than actually sleeping) advances this by that
961    /// same `N` immediately before the call.
962    #[derive(Clone)]
963    pub(crate) struct TestClock(std::rc::Rc<std::cell::Cell<Instant>>);
964
965    impl TestClock {
966        pub(crate) fn new() -> Self {
967            Self(std::rc::Rc::new(std::cell::Cell::new(Instant::now())))
968        }
969
970        /// Advance the simulated clock by `d`.
971        pub(crate) fn advance(&self, d: Duration) {
972            self.0.set(self.0.get() + d);
973        }
974
975        /// The `Fn() -> Instant` closure to pass to [`Driver::with_clock`].
976        pub(crate) fn as_fn(&self) -> impl Fn() -> Instant + 'static {
977            let cell = self.0.clone();
978            move || cell.get()
979        }
980    }
981
982    /// Wrap an SPDU as a module→host `T_Data_Last` R_TPDU (+ trailing T_SB,
983    /// data_available clear) on transport connection `tcid`.
984    fn r_data(tcid: u8, spdu: &[u8]) -> Vec<u8> {
985        use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};
986        let mut v = vec![tpdu_tags::DATA_LAST, (1 + spdu.len()) as u8, tcid];
987        v.extend_from_slice(spdu);
988        v.extend_from_slice(&[tpdu_tags::SB, 0x02, tcid, SbValue::new(false).0]);
989        v
990    }
991
992    /// Wrap an APDU for delivery on `session_nb` (session_number prefix), then as
993    /// a module→host R_TPDU on tcid 1.
994    pub(crate) fn r_apdu(session_nb: u16, apdu: &[u8]) -> Vec<u8> {
995        use dvb_ci::spdu::SessionNumber;
996        let mut spdu = ser(&SessionNumber {
997            length_form: dvb_ci::length::LengthForm::Minimal,
998            session_nb,
999        });
1000        spdu.extend_from_slice(apdu);
1001        r_data(1, &spdu)
1002    }
1003
1004    /// A standalone module→host `T_SB` (data_available clear) ack — flushes one
1005    /// queued host write per turn (#337).
1006    pub(crate) fn sb() -> Vec<u8> {
1007        use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};
1008        vec![tpdu_tags::SB, 0x02, 0x01, SbValue::new(false).0]
1009    }
1010
1011    /// Feed one scripted module frame into the mock and pump it, then pump a
1012    /// handful of SB acks so any queued host writes flush.
1013    pub(crate) fn feed(d: &mut Driver<MockCaDevice>, frame: Vec<u8>) {
1014        d.device_mut().inbound.push_back(frame);
1015        d.pump(Duration::from_millis(10)).unwrap();
1016        for _ in 0..8 {
1017            d.device_mut().inbound.push_back(sb());
1018            d.pump(Duration::from_millis(10)).unwrap();
1019        }
1020    }
1021
1022    /// Drive the EN 50221 handshake through the `Driver` until host_control and
1023    /// the other module-provided sessions are open (mirrors the stack-level
1024    /// `stack_with_ca_session`, but exercises the real driver I/O path).
1025    pub(crate) fn driver_with_sessions() -> Driver<MockCaDevice> {
1026        use dvb_ci::objects::resource_manager::Profile;
1027        use dvb_ci::resource::{
1028            APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, HOST_CONTROL, MMI,
1029            RESOURCE_MANAGER,
1030        };
1031        use dvb_ci::spdu::{CreateSessionResponse, OpenSessionRequest, SessionStatus};
1032
1033        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1034        d.init().unwrap();
1035        // module accepts the transport connection
1036        feed(&mut d, vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1037        // module opens the host's resource_manager → RM session 1
1038        feed(
1039            &mut d,
1040            r_data(
1041                1,
1042                &ser(&OpenSessionRequest {
1043                    length_form: dvb_ci::length::LengthForm::Minimal,
1044                    resource: RESOURCE_MANAGER,
1045                }),
1046            ),
1047        );
1048        // module's profile → host: CamReady + profile_change + create_session for
1049        // each module-provided resource.
1050        feed(
1051            &mut d,
1052            r_apdu(
1053                1,
1054                &ser(&Profile {
1055                    length_form: dvb_ci::length::LengthForm::Minimal,
1056                    resources: vec![
1057                        APPLICATION_INFORMATION,
1058                        CONDITIONAL_ACCESS_SUPPORT,
1059                        MMI,
1060                        HOST_CONTROL,
1061                    ],
1062                }),
1063            ),
1064        );
1065        // module accepts each create_session (session nbs 2..=5 in registration order)
1066        for (nb, res) in [
1067            (2u16, APPLICATION_INFORMATION),
1068            (3, CONDITIONAL_ACCESS_SUPPORT),
1069            (4, MMI),
1070            (5, HOST_CONTROL),
1071        ] {
1072            feed(
1073                &mut d,
1074                r_data(
1075                    1,
1076                    &ser(&CreateSessionResponse {
1077                        length_form: dvb_ci::length::LengthForm::Minimal,
1078                        status: SessionStatus::Ok,
1079                        resource: res,
1080                        session_nb: nb,
1081                    }),
1082                ),
1083            );
1084        }
1085        d
1086    }
1087
1088    // Session numbers the module allocates in `driver_with_sessions`, in
1089    // registration order: RM=1, app_info=2, conditional_access=3, mmi=4,
1090    // host_control=5. (Asserted by `handshake_opens_expected_sessions`.)
1091    const RM_SESSION: u16 = 1;
1092    pub(crate) const CA_SESSION: u16 = 3;
1093    const MMI_SESSION: u16 = 4;
1094    const HOST_CONTROL_SESSION: u16 = 5;
1095
1096    #[test]
1097    fn host_control_tune_apdu_surfaces_notification_via_driver() {
1098        use dvb_ci::objects::host_control::Tune;
1099
1100        let mut d = driver_with_sessions();
1101        let hc_nb = HOST_CONTROL_SESSION;
1102        d.take_notifications(); // drop handshake notifications
1103
1104        // Module (CAM) sends a Tune request on its host_control session.
1105        let tune = Tune {
1106            length_form: dvb_ci::length::LengthForm::Minimal,
1107            network_id: 0x1122,
1108            original_network_id: 0x3344,
1109            transport_stream_id: 0x5566,
1110            service_id: 0x7788,
1111        };
1112        feed(&mut d, r_apdu(hc_nb, &ser(&tune)));
1113
1114        // The runtime surfaces the decoded HostControl(Tune) notification.
1115        let notes = d.take_notifications();
1116        assert!(
1117            notes.contains(&Notification::HostControl(HostControlEvent::Tune {
1118                network_id: 0x1122,
1119                original_network_id: 0x3344,
1120                transport_stream_id: 0x5566,
1121                service_id: 0x7788,
1122            })),
1123            "expected HostControl(Tune) notification, got {notes:?}"
1124        );
1125    }
1126
1127    /// A padded `tune` from the CAM is refused by dvb-ci's strict parser; the
1128    /// runtime must surface that as `Notification::Error`, not drop it.
1129    #[test]
1130    fn padded_tune_from_the_cam_surfaces_an_error_notification() {
1131        let mut d = driver_with_sessions();
1132        d.take_notifications();
1133        // Tune: 9F 84 00, length 9 (one byte over the fixed 8), then 9 bytes.
1134        let padded = [
1135            0x9F, 0x84, 0x00, 0x09, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0xEE,
1136        ];
1137        feed(&mut d, r_apdu(HOST_CONTROL_SESSION, &padded));
1138        let notes = d.take_notifications();
1139        assert!(
1140            notes.iter().any(
1141                |n| matches!(n, Notification::Error { detail } if detail.contains("trailing bytes"))
1142            ),
1143            "expected an Error notification naming the trailing bytes, got {notes:?}"
1144        );
1145        assert!(
1146            !notes
1147                .iter()
1148                .any(|n| matches!(n, Notification::HostControl(_))),
1149            "a refused tune must not also surface as a HostControl event: {notes:?}"
1150        );
1151    }
1152
1153    /// A malformed APDU on other resources is reported too (MMI `enq` with a
1154    /// truncated body here), not silently ignored.
1155    #[test]
1156    fn malformed_mmi_apdu_from_the_cam_surfaces_an_error_notification() {
1157        let mut d = driver_with_sessions();
1158        d.take_notifications();
1159        // enq (9F 88 07) with a 1-byte body: shorter than its fixed prefix.
1160        feed(&mut d, r_apdu(MMI_SESSION, &[0x9F, 0x88, 0x07, 0x01, 0x00]));
1161        let notes = d.take_notifications();
1162        assert!(
1163            notes
1164                .iter()
1165                .any(|n| matches!(n, Notification::Error { .. })),
1166            "expected an Error notification, got {notes:?}"
1167        );
1168    }
1169
1170    #[test]
1171    fn profile_reply_advertises_host_control() {
1172        use broadcast_core::Parse;
1173        use dvb_ci::objects::resource_manager::{Profile, ProfileEnq};
1174        use dvb_ci::resource::{HOST_CONTROL, RESOURCE_MANAGER};
1175
1176        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1177        d.init().unwrap();
1178        feed(&mut d, vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1179        feed(
1180            &mut d,
1181            r_data(
1182                1,
1183                &ser(&dvb_ci::spdu::OpenSessionRequest {
1184                    length_form: dvb_ci::length::LengthForm::Minimal,
1185                    resource: RESOURCE_MANAGER,
1186                }),
1187            ),
1188        );
1189        // Module → profile_enq on the RM session → host replies with its profile.
1190        feed(&mut d, r_apdu(RM_SESSION, &ser(&ProfileEnq::default())));
1191
1192        // Find the host's `profile` reply (tag 9F 80 11) in the written frames and
1193        // confirm it lists HOST_CONTROL.
1194        let want = dvb_ci::tag::PROFILE.to_bytes();
1195        let found = d.device().ops.iter().any(|op| {
1196            if let DeviceOp::Write(w) = op
1197                && let Some(pos) = w.windows(3).position(|x| x == want)
1198                && let Ok(p) = Profile::parse(&w[pos..])
1199            {
1200                return p.resources.contains(&HOST_CONTROL);
1201            }
1202            false
1203        });
1204        assert!(found, "profile reply must advertise HOST_CONTROL");
1205    }
1206
1207    #[test]
1208    fn mmi_menu_answ_and_answ_are_byte_exact_on_the_mmi_session() {
1209        use dvb_ci::objects::mmi_high::{Answ, AnswId, MenuAnsw};
1210
1211        let mut d = driver_with_sessions();
1212        let mmi_nb = MMI_SESSION;
1213
1214        // menu_answ(choice_ref = 2): the driver method must put the exact dvb-ci
1215        // MenuAnsw serialization on the wire, on the MMI session.
1216        d.mmi_menu_answer(2).unwrap();
1217        d.device_mut().inbound.push_back(sb());
1218        d.pump(Duration::from_millis(10)).unwrap();
1219        assert_apdu_on_session(
1220            &d,
1221            mmi_nb,
1222            &ser(&MenuAnsw {
1223                length_form: dvb_ci::length::LengthForm::Minimal,
1224                choice_ref: 2,
1225            }),
1226        );
1227
1228        // answ(answer, "1234"): byte-exact Answ serialization on the MMI session.
1229        d.mmi_enquiry_answer(b"1234").unwrap();
1230        d.device_mut().inbound.push_back(sb());
1231        d.pump(Duration::from_millis(10)).unwrap();
1232        assert_apdu_on_session(
1233            &d,
1234            mmi_nb,
1235            &ser(&Answ {
1236                length_form: dvb_ci::length::LengthForm::Minimal,
1237                answ_id: AnswId::Answer,
1238                text_chars: b"1234",
1239            }),
1240        );
1241    }
1242
1243    /// Assert some host write carries `session_number(session_nb)` immediately
1244    /// followed by the exact `apdu` bytes (byte-exact APDU on the right session).
1245    fn assert_apdu_on_session(d: &Driver<MockCaDevice>, session_nb: u16, apdu: &[u8]) {
1246        use dvb_ci::spdu::SessionNumber;
1247        let mut want = ser(&SessionNumber {
1248            length_form: dvb_ci::length::LengthForm::Minimal,
1249            session_nb,
1250        });
1251        want.extend_from_slice(apdu);
1252        let hit = d.device().ops.iter().any(|op| match op {
1253            DeviceOp::Write(w) => w.windows(want.len()).any(|x| x == want.as_slice()),
1254            _ => false,
1255        });
1256        assert!(
1257            hit,
1258            "expected APDU {apdu:02X?} on session {session_nb} (session-prefixed {want:02X?}) in writes"
1259        );
1260    }
1261
1262    /// How many host writes carry `session_number(session_nb)` immediately
1263    /// followed by the exact `apdu` bytes — used to distinguish an initial
1264    /// send from a later re-send (#763 Task 5's re-query timer).
1265    fn count_apdu_on_session(d: &Driver<MockCaDevice>, session_nb: u16, apdu: &[u8]) -> usize {
1266        use dvb_ci::spdu::SessionNumber;
1267        let mut want = ser(&SessionNumber {
1268            length_form: dvb_ci::length::LengthForm::Minimal,
1269            session_nb,
1270        });
1271        want.extend_from_slice(apdu);
1272        d.device()
1273            .ops
1274            .iter()
1275            .filter(|op| match op {
1276                DeviceOp::Write(w) => w.windows(want.len()).any(|x| x == want.as_slice()),
1277                _ => false,
1278            })
1279            .count()
1280    }
1281
1282    /// A [`MockCaDevice`] that reports a non-zero [`CaDevice::reset_settle`],
1283    /// like the Linux device (r10-O-10).
1284    struct SettleDevice {
1285        inner: MockCaDevice,
1286        settle: Duration,
1287    }
1288
1289    impl CaDevice for SettleDevice {
1290        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1291            self.inner.read(buf)
1292        }
1293        fn write(&mut self, buf: &[u8]) -> io::Result<()> {
1294            self.inner.write(buf)
1295        }
1296        fn reset(&mut self) -> io::Result<()> {
1297            self.inner.reset()
1298        }
1299        fn reset_settle(&self) -> Duration {
1300            self.settle
1301        }
1302        fn slot_info(&mut self) -> io::Result<SlotInfo> {
1303            self.inner.slot_info()
1304        }
1305        fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
1306            self.inner.poll(timeout)
1307        }
1308    }
1309
1310    const SETTLE: Duration = Duration::from_secs(3);
1311
1312    fn settling_driver(clock: &TestClock) -> Driver<SettleDevice> {
1313        Driver::new(
1314            SettleDevice {
1315                inner: MockCaDevice::new([]),
1316                settle: SETTLE,
1317            },
1318            DRIVER,
1319        )
1320        .with_clock(clock.as_fn())
1321    }
1322
1323    fn create_tc_writes(d: &Driver<SettleDevice>) -> usize {
1324        d.device()
1325            .inner
1326            .ops
1327            .iter()
1328            .filter(|o| matches!(o, DeviceOp::Write(w) if w[0] == tags::CREATE_T_C))
1329            .count()
1330    }
1331
1332    /// A [`SettleDevice`] whose `write` is refused with `EINVAL`
1333    /// (`InvalidInput`) a set number of times, like the kernel's
1334    /// `dvb_ca_en50221_io_write` while the slot is not yet RUNNING.
1335    struct NotRunningDevice {
1336        inner: SettleDevice,
1337        refusals_left: u32,
1338        refused: u32,
1339    }
1340
1341    impl CaDevice for NotRunningDevice {
1342        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1343            self.inner.read(buf)
1344        }
1345        fn write(&mut self, buf: &[u8]) -> io::Result<()> {
1346            if self.refusals_left > 0 {
1347                self.refusals_left -= 1;
1348                self.refused += 1;
1349                return Err(io::Error::from(io::ErrorKind::InvalidInput));
1350            }
1351            self.inner.write(buf)
1352        }
1353        fn reset(&mut self) -> io::Result<()> {
1354            self.inner.reset()
1355        }
1356        fn reset_settle(&self) -> Duration {
1357            self.inner.reset_settle()
1358        }
1359        fn slot_info(&mut self) -> io::Result<SlotInfo> {
1360            self.inner.slot_info()
1361        }
1362        fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
1363            self.inner.poll(timeout)
1364        }
1365    }
1366
1367    fn not_running_driver(clock: &TestClock, refusals: u32) -> Driver<NotRunningDevice> {
1368        Driver::new(
1369            NotRunningDevice {
1370                inner: SettleDevice {
1371                    inner: MockCaDevice::new([]),
1372                    settle: SETTLE,
1373                },
1374                refusals_left: refusals,
1375                refused: 0,
1376            },
1377            DRIVER,
1378        )
1379        .with_clock(clock.as_fn())
1380    }
1381
1382    fn create_tc_count(d: &Driver<NotRunningDevice>) -> usize {
1383        d.device()
1384            .inner
1385            .inner
1386            .ops
1387            .iter()
1388            .filter(|o| matches!(o, DeviceOp::Write(w) if w[0] == tags::CREATE_T_C))
1389            .count()
1390    }
1391
1392    /// Real hardware (DD CXD2099 + AlphaCrypt, 4th re-open in ~12 min): the
1393    /// first post-settle write came back `EINVAL` because the CAM had not
1394    /// reached the kernel's RUNNING state yet, and `pump` returned it. It must
1395    /// be retried until the slot accepts it.
1396    #[test]
1397    fn post_reset_einval_is_retried_until_the_slot_is_running() {
1398        let clock = TestClock::new();
1399        let mut d = not_running_driver(&clock, 3);
1400        d.init().unwrap();
1401        clock.advance(SETTLE + Duration::from_millis(100));
1402        for _ in 0..10 {
1403            d.pump(Duration::from_millis(10))
1404                .expect("a not-yet-RUNNING slot (EINVAL) must be retried, not reported");
1405            if create_tc_count(&d) == 1 {
1406                break;
1407            }
1408            clock.advance(Duration::from_millis(300));
1409        }
1410        assert_eq!(d.device().refused, 3, "the three refusals were consumed");
1411        assert_eq!(create_tc_count(&d), 1, "Create_T_C delivered exactly once");
1412    }
1413
1414    /// The retry window is bounded: a slot that never comes up is reported
1415    /// (with the original `InvalidInput`), not retried forever.
1416    #[test]
1417    fn post_reset_einval_is_reported_once_the_grace_window_has_passed() {
1418        let clock = TestClock::new();
1419        let mut d = not_running_driver(&clock, u32::MAX);
1420        let start = clock.0.get();
1421        d.init().unwrap();
1422        clock.advance(SETTLE + Duration::from_millis(100));
1423        let mut failure = None;
1424        for _ in 0..80 {
1425            match d.pump(Duration::from_millis(10)) {
1426                Ok(_) => clock.advance(Duration::from_millis(300)),
1427                Err(e) => {
1428                    failure = Some(e);
1429                    break;
1430                }
1431            }
1432        }
1433        let e = failure.expect("a slot that never runs must eventually be reported");
1434        assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
1435        assert!(
1436            clock.0.get() >= start + SETTLE + SLOT_READY_GRACE,
1437            "reported before the grace window ended"
1438        );
1439        assert_eq!(create_tc_count(&d), 0);
1440    }
1441
1442    /// The re-query timer armed before the handshake completes must not put
1443    /// anything on the wire: with no service added there is nothing to
1444    /// re-query, and no `ca_pmt` APDU (tag `9F 80 32`) is ever written however
1445    /// long the pumping goes before the CAM answers.
1446    #[test]
1447    fn requery_armed_before_the_handshake_sends_nothing() {
1448        let clock = TestClock::new();
1449        let mut d = Driver::new(MockCaDevice::new([]), DRIVER).with_clock(clock.as_fn());
1450        d.set_requery_interval(Duration::from_secs(10));
1451        d.init().unwrap();
1452        for _ in 0..40 {
1453            clock.advance(Duration::from_secs(1));
1454            d.pump(Duration::from_millis(100)).unwrap();
1455        }
1456        let ca_pmt_tag = [0x9F, 0x80, 0x32];
1457        let ca_pmt_writes = d
1458            .device()
1459            .ops
1460            .iter()
1461            .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == ca_pmt_tag)))
1462            .count();
1463        assert_eq!(
1464            ca_pmt_writes, 0,
1465            "re-query wrote a ca_pmt before any service"
1466        );
1467    }
1468
1469    /// r10-O-10 (a): a reset no longer blocks — `init` and `pump` return
1470    /// at once while the slot settles (the pre-fix `reset` slept 3 s).
1471    #[test]
1472    fn reset_does_not_block_pump() {
1473        let clock = TestClock::new();
1474        let mut d = settling_driver(&clock);
1475        let t = std::time::Instant::now();
1476        d.init().unwrap();
1477        d.pump(Duration::from_millis(10)).unwrap();
1478        assert!(t.elapsed() < Duration::from_secs(1), "reset/pump blocked");
1479        assert_eq!(d.device().inner.ops[0], DeviceOp::Reset);
1480    }
1481
1482    /// r10-O-10 (b): no transport traffic before the deadline; the normal
1483    /// sequence (exactly one Create_T_C, same bytes as a zero-settle
1484    /// device) after it.
1485    #[test]
1486    fn no_transport_traffic_until_settle_elapsed() {
1487        let clock = TestClock::new();
1488        let mut d = settling_driver(&clock);
1489        d.device_mut()
1490            .inner
1491            .inbound
1492            .push_back(vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1493        d.init().unwrap();
1494        for _ in 0..5 {
1495            clock.advance(Duration::from_millis(500));
1496            d.pump(Duration::from_millis(10)).unwrap();
1497        }
1498        // t = 2.5 s < 3 s: still quiet, and the module frame is unread.
1499        assert_eq!(create_tc_writes(&d), 0);
1500        assert_eq!(
1501            d.device().inner.inbound.len(),
1502            1,
1503            "frame read while settling"
1504        );
1505
1506        clock.advance(Duration::from_millis(600));
1507        d.pump(Duration::from_millis(10)).unwrap();
1508        assert_eq!(create_tc_writes(&d), 1);
1509
1510        let mut z = Driver::new(MockCaDevice::new([]), DRIVER);
1511        z.init().unwrap();
1512        assert_eq!(
1513            d.device().inner.written()[..3],
1514            z.device().written()[..3],
1515            "post-settle Create_T_C differs from the zero-settle sequence"
1516        );
1517        // And the pump then proceeds normally: the queued reply was consumed
1518        // by that same post-settle pump.
1519        assert!(d.device().inner.inbound.is_empty());
1520    }
1521
1522    /// r10-O-10 (c): a second reset during settling restarts the deadline
1523    /// and drops the stale queued Create_T_C (still exactly one afterwards).
1524    #[test]
1525    fn second_reset_restarts_settle() {
1526        let clock = TestClock::new();
1527        let mut d = settling_driver(&clock);
1528        d.init().unwrap();
1529        clock.advance(Duration::from_secs(2));
1530        d.pump(Duration::from_millis(10)).unwrap();
1531        d.init().unwrap(); // second reset at t = 2 s -> deadline 5 s
1532        clock.advance(Duration::from_secs(2)); // t = 4 s: past the first deadline
1533        d.pump(Duration::from_millis(10)).unwrap();
1534        assert_eq!(create_tc_writes(&d), 0, "first deadline wrongly honoured");
1535        clock.advance(Duration::from_millis(1500)); // t = 5.5 s
1536        d.pump(Duration::from_millis(10)).unwrap();
1537        assert_eq!(create_tc_writes(&d), 1);
1538    }
1539
1540    /// r10-O-10 (d): slot sampling (hot-plug detection) keeps working while
1541    /// the transport is held back.
1542    #[test]
1543    fn slot_sampling_continues_while_settling() {
1544        let clock = TestClock::new();
1545        let mut d = settling_driver(&clock);
1546        d.init().unwrap();
1547        d.take_notifications();
1548        d.device_mut().inner.slot.module_present = false;
1549        clock.advance(Duration::from_millis(500));
1550        d.pump(Duration::from_millis(10)).unwrap();
1551        let notes = d.take_notifications();
1552        assert!(
1553            notes
1554                .iter()
1555                .any(|n| matches!(n, Notification::HotPlug(HotPlug::CamRemoved))),
1556            "{notes:?}"
1557        );
1558        assert_eq!(create_tc_writes(&d), 0);
1559    }
1560
1561    #[test]
1562    fn init_drives_reset_slotinfo_and_create_tc_to_device() {
1563        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1564        d.init().unwrap();
1565        let ops = &d.device().ops;
1566        assert_eq!(ops[0], DeviceOp::Reset);
1567        assert_eq!(ops[1], DeviceOp::SlotInfo);
1568        assert!(matches!(&ops[2], DeviceOp::Write(w) if w[0] == tags::CREATE_T_C));
1569    }
1570
1571    #[test]
1572    fn reads_reply_then_polls_on_pump() {
1573        // Script the module accepting the connection.
1574        let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
1575        let clock = TestClock::new();
1576        let mut d = Driver::new(dev, DRIVER).with_clock(clock.as_fn());
1577        d.init().unwrap();
1578        // first pump reads the C_T_C_Reply (activates the connection)
1579        assert!(d.pump(Duration::from_millis(100)).unwrap());
1580        // r10-W-21: `pump` now measures real (simulated, via TestClock)
1581        // elapsed time rather than trusting the `timeout` argument, so the
1582        // test advances the clock by the same amount `timeout` used to
1583        // stand in for.
1584        clock.advance(Duration::from_millis(100));
1585        // next pump has nothing to read → ticks → emits a poll write
1586        assert!(!d.pump(Duration::from_millis(100)).unwrap());
1587        let last = d.device().ops.last().unwrap();
1588        assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
1589    }
1590
1591    /// r10-W-21: `pump`'s stack-clock advance must reflect real (here,
1592    /// simulated) elapsed time, not the `timeout` argument on its own —
1593    /// pre-fix, calling `pump(1s)` twice back-to-back with almost no real
1594    /// time between them still advanced the stack's clock by a full second
1595    /// each time, exactly as if a full second really had passed.
1596    #[test]
1597    fn pump_advances_the_stack_clock_by_real_elapsed_time_not_by_timeout() {
1598        let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
1599        let clock = TestClock::new();
1600        let mut d = Driver::new(dev, DRIVER).with_clock(clock.as_fn());
1601        d.init().unwrap();
1602        assert!(d.pump(Duration::from_secs(1)).unwrap());
1603
1604        // Only 1ms of (simulated) real time actually passed, even though
1605        // `timeout` claims a full second — nowhere near the 100ms poll
1606        // cadence, so no poll write should go out.
1607        clock.advance(Duration::from_millis(1));
1608        assert!(!d.pump(Duration::from_secs(1)).unwrap());
1609        assert!(
1610            d.device().ops.last().is_none_or(|op| !matches!(
1611                op,
1612                DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)
1613            )),
1614            "must not poll after only 1ms of real elapsed time, regardless of the 1s `timeout` argument"
1615        );
1616
1617        clock.advance(Duration::from_millis(100));
1618        assert!(!d.pump(Duration::from_secs(1)).unwrap());
1619        let last = d.device().ops.last().unwrap();
1620        assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
1621    }
1622
1623    // --- #726: CAM + card hot-plug notifications ---
1624
1625    #[test]
1626    fn cam_insert_edge_emits_cam_present_once_and_redrives_handshake() {
1627        let mut dev = MockCaDevice::new([]);
1628        dev.slot = SlotInfo {
1629            num: 0,
1630            module_ready: false,
1631            module_present: false,
1632        };
1633        let mut d = Driver::new(dev, DRIVER);
1634        d.init().unwrap();
1635        // The first-ever slot observation only establishes the baseline
1636        // (absent) — it must not itself claim a hot-plug edge.
1637        let notes = d.take_notifications();
1638        assert!(
1639            !notes.contains(&Notification::HotPlug(HotPlug::CamPresent)),
1640            "baseline observation must not fire CamPresent, got {notes:?}"
1641        );
1642        let resets_before = d
1643            .device()
1644            .ops
1645            .iter()
1646            .filter(|o| **o == DeviceOp::Reset)
1647            .count();
1648
1649        // Module physically inserted and ready.
1650        d.device_mut().slot = SlotInfo {
1651            num: 0,
1652            module_ready: true,
1653            module_present: true,
1654        };
1655        d.pump(Duration::from_millis(10)).unwrap();
1656
1657        let notes = d.take_notifications();
1658        let cam_present_count = notes
1659            .iter()
1660            .filter(|n| **n == Notification::HotPlug(HotPlug::CamPresent))
1661            .count();
1662        assert_eq!(
1663            cam_present_count, 1,
1664            "expected exactly one CamPresent, got {notes:?}"
1665        );
1666        // Handshake re-driven: a fresh Reset, and the last write is CREATE_T_C.
1667        let resets_after = d
1668            .device()
1669            .ops
1670            .iter()
1671            .filter(|o| **o == DeviceOp::Reset)
1672            .count();
1673        assert_eq!(
1674            resets_after,
1675            resets_before + 1,
1676            "expected one fresh Reset on re-insert"
1677        );
1678        assert!(
1679            matches!(d.device().ops.last(), Some(DeviceOp::Write(w)) if w[0] == tags::CREATE_T_C),
1680            "expected the handshake re-driven (CREATE_T_C written), got {:?}",
1681            d.device().ops.last()
1682        );
1683    }
1684
1685    #[test]
1686    fn cam_remove_edge_emits_cam_removed_and_re_insert_re_handshakes() {
1687        let mut d = driver_with_sessions();
1688        d.take_notifications();
1689
1690        // Module physically removed.
1691        d.device_mut().slot.module_present = false;
1692        d.pump(Duration::from_millis(10)).unwrap();
1693        let notes = d.take_notifications();
1694        assert!(
1695            notes.contains(&Notification::HotPlug(HotPlug::CamRemoved)),
1696            "expected CamRemoved, got {notes:?}"
1697        );
1698
1699        // Session state was torn down: the MMI session from
1700        // `driver_with_sessions` no longer exists on the fresh stack, so an
1701        // answer to it now errors instead of silently going nowhere.
1702        d.mmi_menu_answer(0).unwrap();
1703        let notes = d.take_notifications();
1704        assert!(
1705            notes
1706                .iter()
1707                .any(|n| matches!(n, Notification::Error { .. })),
1708            "expected no open MMI session after teardown, got {notes:?}"
1709        );
1710
1711        // Re-insert: a fresh handshake starts (Reset + CamPresent).
1712        let resets_before = d
1713            .device()
1714            .ops
1715            .iter()
1716            .filter(|o| **o == DeviceOp::Reset)
1717            .count();
1718        d.device_mut().slot.module_present = true;
1719        d.device_mut().slot.module_ready = true;
1720        d.pump(Duration::from_millis(10)).unwrap();
1721        let notes = d.take_notifications();
1722        assert!(
1723            notes.contains(&Notification::HotPlug(HotPlug::CamPresent)),
1724            "expected CamPresent on re-insert, got {notes:?}"
1725        );
1726        let resets_after = d
1727            .device()
1728            .ops
1729            .iter()
1730            .filter(|o| **o == DeviceOp::Reset)
1731            .count();
1732        assert_eq!(resets_after, resets_before + 1, "expected a fresh Reset");
1733    }
1734
1735    #[test]
1736    fn slot_status_unchanged_across_polls_emits_no_hotplug_notifications() {
1737        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1738        d.init().unwrap();
1739        d.take_notifications();
1740
1741        for _ in 0..5 {
1742            d.pump(Duration::from_millis(10)).unwrap();
1743        }
1744        let notes = d.take_notifications();
1745        assert!(
1746            !notes.iter().any(|n| matches!(
1747                n,
1748                Notification::HotPlug(HotPlug::CamPresent | HotPlug::CamRemoved)
1749            )),
1750            "unchanged slot status must not emit hot-plug notifications, got {notes:?}"
1751        );
1752    }
1753
1754    #[test]
1755    fn ca_info_caid_set_change_infers_card_inserted_then_changed() {
1756        use dvb_ci::objects::ca_info::CaInfo;
1757
1758        let mut d = driver_with_sessions();
1759        d.take_notifications();
1760
1761        // First ca_info: no CAIDs (baseline only, no notification).
1762        feed(
1763            &mut d,
1764            r_apdu(
1765                CA_SESSION,
1766                &ser(&CaInfo {
1767                    length_form: dvb_ci::length::LengthForm::Minimal,
1768                    ca_system_ids: vec![],
1769                }),
1770            ),
1771        );
1772        let notes = d.take_notifications();
1773        assert!(
1774            !notes.iter().any(|n| matches!(
1775                n,
1776                Notification::HotPlug(
1777                    HotPlug::CardInserted | HotPlug::CardChanged | HotPlug::CardRemoved
1778                )
1779            )),
1780            "first ca_info must only establish the baseline, got {notes:?}"
1781        );
1782
1783        // CAID set becomes populated: card inserted.
1784        feed(
1785            &mut d,
1786            r_apdu(
1787                CA_SESSION,
1788                &ser(&CaInfo {
1789                    length_form: dvb_ci::length::LengthForm::Minimal,
1790                    ca_system_ids: vec![0x0B00],
1791                }),
1792            ),
1793        );
1794        let notes = d.take_notifications();
1795        assert!(
1796            notes.contains(&Notification::HotPlug(HotPlug::CardInserted)),
1797            "expected CardInserted, got {notes:?}"
1798        );
1799
1800        // CAID set changes to a different non-empty set: card changed.
1801        feed(
1802            &mut d,
1803            r_apdu(
1804                CA_SESSION,
1805                &ser(&CaInfo {
1806                    length_form: dvb_ci::length::LengthForm::Minimal,
1807                    ca_system_ids: vec![0x1800],
1808                }),
1809            ),
1810        );
1811        let notes = d.take_notifications();
1812        assert!(
1813            notes.contains(&Notification::HotPlug(HotPlug::CardChanged)),
1814            "expected CardChanged, got {notes:?}"
1815        );
1816    }
1817
1818    #[test]
1819    fn ca_pmt_reply_descrambling_transition_infers_card_present_then_removed() {
1820        use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
1821
1822        fn reply(ca_enable: Option<CaEnable>) -> CaPmtReply {
1823            CaPmtReply {
1824                reserved_ca_enable: Default::default(),
1825                reserved_version: Default::default(),
1826                length_form: dvb_ci::length::LengthForm::Minimal,
1827                program_number: 1,
1828                version_number: 1,
1829                current_next_indicator: true,
1830                ca_enable,
1831                streams: vec![],
1832            }
1833        }
1834
1835        let mut d = driver_with_sessions();
1836        d.take_notifications();
1837
1838        // Baseline: descrambling not (yet) possible.
1839        feed(&mut d, r_apdu(CA_SESSION, &ser(&reply(None))));
1840        let notes = d.take_notifications();
1841        assert!(
1842            !notes.iter().any(|n| matches!(
1843                n,
1844                Notification::HotPlug(HotPlug::CardInserted | HotPlug::CardRemoved)
1845            )),
1846            "first ca_pmt_reply must only establish the baseline, got {notes:?}"
1847        );
1848
1849        // false -> true: card-present inference.
1850        feed(
1851            &mut d,
1852            r_apdu(CA_SESSION, &ser(&reply(Some(CaEnable::Possible)))),
1853        );
1854        let notes = d.take_notifications();
1855        assert!(
1856            notes.contains(&Notification::HotPlug(HotPlug::CardInserted)),
1857            "expected CardInserted, got {notes:?}"
1858        );
1859
1860        // true -> false: card removed.
1861        feed(&mut d, r_apdu(CA_SESSION, &ser(&reply(None))));
1862        let notes = d.take_notifications();
1863        assert!(
1864            notes.contains(&Notification::HotPlug(HotPlug::CardRemoved)),
1865            "expected CardRemoved, got {notes:?}"
1866        );
1867    }
1868
1869    #[test]
1870    fn ca_pmt_reply_surfaces_typed_ca_enable() {
1871        use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
1872
1873        let mut d = driver_with_sessions();
1874        d.take_notifications();
1875
1876        // `CA_enable` = 0x03 (possible under conditions, technical dialogue) —
1877        // EN 50221 §8.4.3.5 Table 26.
1878        feed(
1879            &mut d,
1880            r_apdu(
1881                CA_SESSION,
1882                &ser(&CaPmtReply {
1883                    reserved_ca_enable: Default::default(),
1884                    reserved_version: Default::default(),
1885                    length_form: dvb_ci::length::LengthForm::Minimal,
1886                    program_number: 7,
1887                    version_number: 1,
1888                    current_next_indicator: true,
1889                    ca_enable: Some(CaEnable::PossibleTechnicalDialogue),
1890                    streams: vec![],
1891                }),
1892            ),
1893        );
1894        let notes = d.take_notifications();
1895        assert!(
1896            notes.contains(&Notification::CaPmtReply {
1897                program_number: 7,
1898                ca_enable: Some(CaEnable::PossibleTechnicalDialogue),
1899                descrambling_ok: true,
1900            }),
1901            "expected typed ca_enable on CaPmtReply, got {notes:?}"
1902        );
1903    }
1904
1905    #[test]
1906    fn ca_pmt_reply_flag_clear_surfaces_none() {
1907        use dvb_ci::objects::ca_pmt_reply::CaPmtReply;
1908
1909        let mut d = driver_with_sessions();
1910        d.take_notifications();
1911
1912        // Programme `CA_enable_flag` clear -> no programme-level status given
1913        // — EN 50221 §8.4.3.5 Table 26.
1914        feed(
1915            &mut d,
1916            r_apdu(
1917                CA_SESSION,
1918                &ser(&CaPmtReply {
1919                    reserved_ca_enable: Default::default(),
1920                    reserved_version: Default::default(),
1921                    length_form: dvb_ci::length::LengthForm::Minimal,
1922                    program_number: 7,
1923                    version_number: 1,
1924                    current_next_indicator: true,
1925                    ca_enable: None,
1926                    streams: vec![],
1927                }),
1928            ),
1929        );
1930        let notes = d.take_notifications();
1931        assert!(
1932            notes.contains(&Notification::CaPmtReply {
1933                program_number: 7,
1934                ca_enable: None,
1935                descrambling_ok: false,
1936            }),
1937            "expected ca_enable None on flag-clear CaPmtReply, got {notes:?}"
1938        );
1939    }
1940
1941    #[test]
1942    fn mmi_no_card_text_infers_card_removed() {
1943        use dvb_ci::objects::mmi_high::Enq;
1944
1945        let mut d = driver_with_sessions();
1946        d.take_notifications();
1947
1948        feed(
1949            &mut d,
1950            r_apdu(
1951                MMI_SESSION,
1952                &ser(&Enq {
1953                    reserved: Default::default(),
1954                    length_form: dvb_ci::length::LengthForm::Minimal,
1955                    blind_answer: false,
1956                    answer_text_length: 0,
1957                    text_chars: b"NO CARD detected - please insert your smart card",
1958                }),
1959            ),
1960        );
1961
1962        let notes = d.take_notifications();
1963        assert!(
1964            notes.contains(&Notification::HotPlug(HotPlug::CardRemoved)),
1965            "expected CardRemoved inferred from MMI 'no card' text, got {notes:?}"
1966        );
1967    }
1968
1969    /// r10-O-13: the MMI keyword heuristic reports a card *transition*, not
1970    /// every menu that repeats the same text.
1971    #[test]
1972    fn mmi_card_keyword_heuristic_is_edge_triggered() {
1973        use dvb_ci::objects::mmi_high::Enq;
1974
1975        let enq = |text: &'static [u8]| {
1976            r_apdu(
1977                MMI_SESSION,
1978                &ser(&Enq {
1979                    reserved: Default::default(),
1980                    length_form: dvb_ci::length::LengthForm::Minimal,
1981                    blind_answer: false,
1982                    answer_text_length: 0,
1983                    text_chars: text,
1984                }),
1985            )
1986        };
1987        let mut d = driver_with_sessions();
1988        d.take_notifications();
1989        let count = |notes: &[Notification], hp: HotPlug| {
1990            notes
1991                .iter()
1992                .filter(|n| **n == Notification::HotPlug(hp))
1993                .count()
1994        };
1995
1996        // The same "no card" prompt three times: one CardRemoved, not three.
1997        for _ in 0..3 {
1998            feed(&mut d, enq(b"No card - please insert your smart card"));
1999        }
2000        let notes = d.take_notifications();
2001        assert_eq!(count(&notes, HotPlug::CardRemoved), 1, "{notes:?}");
2002        assert_eq!(count(&notes, HotPlug::CardInserted), 0);
2003
2004        // A present-card prompt is an edge: one CardInserted, then silence.
2005        for _ in 0..2 {
2006            feed(&mut d, enq(b"Your entitlement is valid"));
2007        }
2008        let notes = d.take_notifications();
2009        assert_eq!(count(&notes, HotPlug::CardInserted), 1, "{notes:?}");
2010        assert_eq!(count(&notes, HotPlug::CardRemoved), 0);
2011
2012        // Back to absent: a fresh edge, reported once.
2013        feed(&mut d, enq(b"Card removed"));
2014        feed(&mut d, enq(b"Card removed"));
2015        let notes = d.take_notifications();
2016        assert_eq!(count(&notes, HotPlug::CardRemoved), 1, "{notes:?}");
2017    }
2018
2019    #[test]
2020    fn pump_hotplug_delivers_cam_present_via_closure_exactly_once() {
2021        let mut dev = MockCaDevice::new([]);
2022        dev.slot = SlotInfo {
2023            num: 0,
2024            module_ready: false,
2025            module_present: false,
2026        };
2027        let mut d = Driver::new(dev, DRIVER);
2028        d.init().unwrap();
2029        d.take_notifications(); // drop the baseline observation
2030
2031        // Module physically inserted and ready.
2032        d.device_mut().slot = SlotInfo {
2033            num: 0,
2034            module_ready: true,
2035            module_present: true,
2036        };
2037
2038        let mut seen = Vec::new();
2039        d.pump_hotplug(Duration::from_millis(10), |hp| seen.push(hp))
2040            .unwrap();
2041
2042        assert_eq!(
2043            seen,
2044            vec![HotPlug::CamPresent],
2045            "expected the closure to receive HotPlug::CamPresent exactly once, got {seen:?}"
2046        );
2047    }
2048
2049    // --- #763 Task 3: ManagedCa + add_service ---
2050
2051    /// A `CA_descriptor` TLV (ISO/IEC 13818-1 §2.6.16): tag `0x09`, len `4`,
2052    /// `CA_system_id`(2), `reserved(3)`/`CA_PID`(13).
2053    pub(crate) fn ca_descriptor(ca_system_id: u16, pid: Pid) -> [u8; 6] {
2054        [
2055            0x09,
2056            0x04,
2057            (ca_system_id >> 8) as u8,
2058            ca_system_id as u8,
2059            0xE0 | ((pid.value() >> 8) as u8 & 0x1F),
2060            pid.value() as u8,
2061        ]
2062    }
2063
2064    /// A synthetic scrambled-service PMT: programme-level `CA_descriptor`
2065    /// (`CA_system_id` `0x0500` = Viaccess, a real assigned value per the
2066    /// TSDuck CA-system registry consumed by `dvb_si::descriptors::ca::ca_system_name`),
2067    /// one scrambled H.264 video ES (own `CA_descriptor`), and one clear AAC
2068    /// audio ES.
2069    ///
2070    /// **Provenance:** no committed capture in this repo's fixture corpus
2071    /// carries a scrambled PMT — `fixtures/ts/tnt-5w-12732v-isi6-10s.ts`'s
2072    /// five PMTs (verified via `cargo run -p dvb-tools -- dump ... --json`)
2073    /// are all clear/FTA services, and no CA-descriptor-bearing capture exists
2074    /// under `private/fixtures/` either. This hand-rolls the wire bytes per
2075    /// ISO/IEC 13818-1 §2.4.4.9's PMT syntax instead, mirroring the exact
2076    /// precedent already established by `dvb-ci/src/builder.rs`'s
2077    /// `build_test_pmt()` (a hand-rolled buffer "that mirrors a real
2078    /// CA-protected service") — real `CA_system_id`/`stream_type` values, real
2079    /// CRC, just not sourced from an off-air capture.
2080    pub(crate) fn build_ca_pmt_fixture(program_number: u16) -> Vec<u8> {
2081        const VIACCESS: u16 = 0x0500;
2082        let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2083        let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0065));
2084
2085        let mut body = Vec::new();
2086        body.push(0x02); // table_id (PMT)
2087        body.push(0); // section_length placeholder (fixed up below)
2088        body.push(0);
2089        body.extend_from_slice(&program_number.to_be_bytes());
2090        body.push(0xC3); // reserved(2)='11' | version(5)=1 | current_next=1
2091        body.push(0x00); // section_number
2092        body.push(0x00); // last_section_number
2093        body.push(0xE0 | 0x01); // reserved(3) | PCR_PID(13) = 0x0100
2094        body.push(0x00);
2095        body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2096        body.push(prog_ca.len() as u8);
2097        body.extend_from_slice(&prog_ca);
2098        // ES0: H.264 video, pid 0x0100, scrambled (own CA_descriptor).
2099        body.push(0x1B);
2100        body.push(0xE0 | 0x01);
2101        body.push(0x00);
2102        body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2103        body.push(es0_ca.len() as u8);
2104        body.extend_from_slice(&es0_ca);
2105        // ES1: AAC ADTS audio, pid 0x0101, clear.
2106        body.push(0x0F);
2107        body.push(0xE0 | 0x01);
2108        body.push(0x01);
2109        body.push(0xF0);
2110        body.push(0x00);
2111
2112        let section_length = body.len() - 3 + 4;
2113        body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2114        body[2] = section_length as u8;
2115        let crc = broadcast_common::crc32_mpeg2::compute(&body);
2116        body.extend_from_slice(&crc.to_be_bytes());
2117        body
2118    }
2119
2120    /// Same layout as [`build_ca_pmt_fixture`] but with the PCR carried on its
2121    /// own **dedicated** `PCR_PID` (`0x00FF`) — distinct from every ES PID
2122    /// (`0x0100`/`0x0101`) and CA PID (`0x0064`/`0x0065`) — a legitimate DVB
2123    /// config (ISO/IEC 13818-1 §2.4.4.9) that `build_ca_pmt_fixture`'s
2124    /// `PCR_PID == video ES PID` masks: the #763 final-review regression
2125    /// fixture for `required_pids`/`feed_ts` PCR routing.
2126    pub(crate) fn build_ca_pmt_fixture_dedicated_pcr(program_number: u16) -> Vec<u8> {
2127        const VIACCESS: u16 = 0x0500;
2128        let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2129        let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0065));
2130
2131        let mut body = Vec::new();
2132        body.push(0x02); // table_id (PMT)
2133        body.push(0); // section_length placeholder (fixed up below)
2134        body.push(0);
2135        body.extend_from_slice(&program_number.to_be_bytes());
2136        body.push(0xC3); // reserved(2)='11' | version(5)=1 | current_next=1
2137        body.push(0x00); // section_number
2138        body.push(0x00); // last_section_number
2139        body.push(0xE0); // reserved(3) | PCR_PID(13) high byte = 0x00FF >> 8
2140        body.push(0xFF); // PCR_PID low byte — dedicated, outside the ES/CA set
2141        body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2142        body.push(prog_ca.len() as u8);
2143        body.extend_from_slice(&prog_ca);
2144        // ES0: H.264 video, pid 0x0100, scrambled (own CA_descriptor).
2145        body.push(0x1B);
2146        body.push(0xE0 | 0x01);
2147        body.push(0x00);
2148        body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2149        body.push(es0_ca.len() as u8);
2150        body.extend_from_slice(&es0_ca);
2151        // ES1: AAC ADTS audio, pid 0x0101, clear.
2152        body.push(0x0F);
2153        body.push(0xE0 | 0x01);
2154        body.push(0x01);
2155        body.push(0xF0);
2156        body.push(0x00);
2157
2158        let section_length = body.len() - 3 + 4;
2159        body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2160        body[2] = section_length as u8;
2161        let crc = broadcast_common::crc32_mpeg2::compute(&body);
2162        body.extend_from_slice(&crc.to_be_bytes());
2163        body
2164    }
2165
2166    /// Same layout as [`build_ca_pmt_fixture`] but with no `CA_descriptor`
2167    /// anywhere (an ordinary clear/FTA service) — the negative-control PMT for
2168    /// [`CaError::NoCaDescriptor`].
2169    pub(crate) fn build_clear_pmt_fixture(program_number: u16) -> Vec<u8> {
2170        let mut body = Vec::new();
2171        body.push(0x02);
2172        body.push(0);
2173        body.push(0);
2174        body.extend_from_slice(&program_number.to_be_bytes());
2175        body.push(0xC3);
2176        body.push(0x00);
2177        body.push(0x00);
2178        body.push(0xE0 | 0x01);
2179        body.push(0x00);
2180        body.push(0xF0); // program_info_length = 0
2181        body.push(0x00);
2182        // ES0: H.264 video, pid 0x0100, clear.
2183        body.push(0x1B);
2184        body.push(0xE0 | 0x01);
2185        body.push(0x00);
2186        body.push(0xF0);
2187        body.push(0x00);
2188
2189        let section_length = body.len() - 3 + 4;
2190        body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2191        body[2] = section_length as u8;
2192        let crc = broadcast_common::crc32_mpeg2::compute(&body);
2193        body.extend_from_slice(&crc.to_be_bytes());
2194        body
2195    }
2196
2197    #[test]
2198    fn add_service_builds_and_sends_ca_pmt_matching_builder_oracle() {
2199        use broadcast_core::Parse;
2200
2201        let mut d = driver_with_sessions();
2202        d.take_notifications();
2203
2204        let pmt_bytes = build_ca_pmt_fixture(1546);
2205        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2206
2207        d.add_service(&pmt).unwrap();
2208        d.device_mut().inbound.push_back(sb());
2209        d.pump(Duration::from_millis(10)).unwrap();
2210
2211        // Oracle: the same PMT built directly via dvb_ci::builder::build_ca_pmt
2212        // with `Only` (first-ever service on an empty managed set) +
2213        // `ok_descrambling`.
2214        let expected = build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2215            .to_bytes()
2216            .unwrap();
2217        assert_apdu_on_session(&d, CA_SESSION, &expected);
2218
2219        // The service was recorded with its ES/CA PIDs.
2220        let svc = d
2221            .managed_ca()
2222            .services()
2223            .get(&1546)
2224            .expect("program_number 1546 must be tracked after add_service");
2225        assert_eq!(
2226            svc.es_pids,
2227            vec![Pid::from_const(0x0100), Pid::from_const(0x0101)]
2228        );
2229        assert_eq!(
2230            svc.ca_pids,
2231            vec![Pid::from_const(0x0064), Pid::from_const(0x0065)]
2232        );
2233        assert_eq!(svc.cmd, CaPmtCmdId::OkDescrambling);
2234        assert_eq!(svc.last_ca_enable, None);
2235    }
2236
2237    #[test]
2238    fn add_service_rejects_pmt_without_ca_descriptor() {
2239        use broadcast_core::Parse;
2240
2241        let mut d = driver_with_sessions();
2242        let pmt_bytes = build_clear_pmt_fixture(999);
2243        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2244
2245        let err = d.add_service(&pmt).unwrap_err();
2246        assert!(
2247            matches!(
2248                err,
2249                CaError::NoCaDescriptor {
2250                    program_number: 999
2251                }
2252            ),
2253            "expected NoCaDescriptor{{program_number: 999}}, got {err:?}"
2254        );
2255        assert!(
2256            d.managed_ca().services().is_empty(),
2257            "a rejected PMT must not be recorded"
2258        );
2259    }
2260
2261    /// r10-W-20: the re-query timer must surface a corrupt stored PMT as an
2262    /// `Err` from the public `pump` entry point — never a panic — and the
2263    /// failure must be sticky: a corrupt (or CAM-supplied) service must not
2264    /// silently swallow the healthy services' resend, and must keep
2265    /// reporting on every later tick. A service with truncated stored
2266    /// `pmt_raw` (corruption of the caller's own state after a successful
2267    /// add — the only corrupt shape the stored bytes can hold, since
2268    /// `add_service` re-serializes them) joins a healthy service added
2269    /// through the public `add_service`; when the 5s timer fires, the
2270    /// healthy pair still goes out, the corrupt one's re-parse failure is
2271    /// recorded, and `pump` returns it as `Err` — twice in a row.
2272    #[test]
2273    fn requery_tick_serialize_failure_errors_from_pump_instead_of_panicking() {
2274        use broadcast_core::Parse;
2275
2276        let clock = TestClock::new();
2277        let mut d = driver_with_sessions().with_clock(clock.as_fn());
2278
2279        // A healthy service through the public path (feeds its CaInfo like
2280        // `requery_timer_resends_ca_pmt_then_reply_change_emits_one_entitlement`).
2281        let good_bytes = build_ca_pmt_fixture(1);
2282        let good = PmtSection::parse(&good_bytes).unwrap();
2283        assert_eq!(good.program_number, 1, "fixture precondition");
2284        d.add_service(&good).unwrap();
2285
2286        // The corrupt service, recorded via the same internals
2287        // `add_service` uses (its raw bytes cannot be written by the
2288        // serializer, so they never reach the stored set through the
2289        // public path).
2290        let pmt_bytes = build_ca_pmt_fixture(1546);
2291        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2292        let built = d
2293            .build_ca_pmt_filtered(
2294                &pmt,
2295                CaPmtListManagement::Update,
2296                CaPmtCmdId::OkDescrambling,
2297            )
2298            .to_bytes()
2299            .expect("fixture precondition: the good PMT encodes");
2300        let corrupt_raw = pmt_bytes[..pmt_bytes.len() - 6].to_vec();
2301        d.managed.record(
2302            1546,
2303            managed::service_of(&pmt, CaPmtCmdId::OkDescrambling, built, corrupt_raw),
2304        );
2305        d.take_notifications();
2306        // Drain every queued host write with module T_SBs (the transport
2307        // flushes one write per module turn, #337; `feed`'s tail leaves
2308        // handshake writes and `add_service` added one more).
2309        for _ in 0..16 {
2310            d.device_mut().inbound.push_back(sb());
2311            d.pump(Duration::from_millis(10)).unwrap();
2312        }
2313        d.set_requery_interval(Duration::from_secs(5));
2314
2315        // Advance past the interval and pump idle: the timer fires, the
2316        // healthy service's re-query pair goes out, and the corrupt one
2317        // fails its re-parse — an Err out of `pump`, not a panic.
2318        clock.advance(Duration::from_secs(5));
2319        let err = d
2320            .pump(Duration::ZERO)
2321            .expect_err("re-query of a corrupt stored PMT must error, not panic");
2322        assert!(
2323            matches!(
2324                err.get_ref(),
2325                Some(e) if e.downcast_ref::<CaError>()
2326                    .is_some_and(|ca| matches!(ca, CaError::PmtParse(_)))
2327            ),
2328            "expected CaError::PmtParse from the corrupt stored bytes, got {err:?}"
2329        );
2330        assert!(
2331            err.to_string().contains("stored PMT re-parse failed"),
2332            "error must name the re-parse failure, got: {err}"
2333        );
2334        // Sticky-but-not-swallowing: the failure was returned after the
2335        // healthy pair went out this tick; drain it, and the NEXT fire
2336        // re-detects the same corrupt stored bytes (never silently quiet).
2337        assert!(d.pump(Duration::ZERO).is_ok());
2338        clock.advance(Duration::from_secs(5));
2339        let err2 = d
2340            .pump(Duration::ZERO)
2341            .expect_err("the corrupt service must fail every re-query");
2342        assert!(
2343            err2.to_string().contains("stored PMT re-parse failed"),
2344            "failure must persist, got: {err2}"
2345        );
2346    }
2347
2348    /// The constructor-level corrupt PMT: a 5004-byte programme CA loop
2349    /// (CAID `0x0B00`), past dvb-ci's 4095-byte `program_info_length` cap.
2350    /// dvb-si's parse only 12-bit-checks lengths against the physical
2351    /// buffer, so this shape exists only via `PmtSection::new` — standing
2352    /// in for a corrupt reassembly reaching `add_service` as a value.
2353    fn corrupt_ca_section_ctor() -> PmtSection<'static> {
2354        const LOOP: usize = 5004;
2355        let mut prog_info: Vec<u8> = Vec::with_capacity(LOOP);
2356        for _ in 0..LOOP / 6 {
2357            // CA_descriptor: CAID 0x0B00, CA_PID 0x0100 (4-byte body).
2358            prog_info.extend_from_slice(&[0x09u8, 0x04, 0x0B, 0x00, 0xE1, 0x00]);
2359        }
2360        assert_eq!(prog_info.len(), LOOP);
2361        PmtSection::new(
2362            1,
2363            dvb_si::tables::SectionVersion::new(1, true, 0, 0),
2364            Pid::from_const(0x0200),
2365            dvb_si::descriptors::DescriptorLoop::new(Box::leak(prog_info.into_boxed_slice())),
2366            Vec::new(),
2367        )
2368    }
2369
2370    /// r10-W-20: `add_service` must reject a PMT whose CA loop cannot be
2371    /// encoded into a `ca_pmt` (over-range `program_info_length`) as
2372    /// `CaError::Serialize` from the public entry point — pre-fix this
2373    /// reached `.to_bytes().unwrap()` and panicked inside the dvb-ci serializer.
2374    #[test]
2375    fn add_service_serialize_failure_returns_err_instead_of_panicking() {
2376        let mut d = driver_with_sessions();
2377        d.managed.set_cam_caids([0x0B00u16].into_iter().collect());
2378        let pmt = corrupt_ca_section_ctor();
2379        let err = d
2380            .add_service(&pmt)
2381            .expect_err("a ca_pmt with no valid encoding must error, not panic");
2382        assert!(
2383            matches!(err, CaError::Serialize(_)),
2384            "expected CaError::Serialize, got {err:?}"
2385        );
2386        assert!(
2387            d.managed_ca().services().is_empty(),
2388            "a rejected PMT must not be recorded"
2389        );
2390    }
2391
2392    #[test]
2393    fn add_service_second_call_uses_add_list_management() {
2394        use broadcast_core::Parse;
2395
2396        let mut d = driver_with_sessions();
2397        d.take_notifications();
2398
2399        let pmt1_bytes = build_ca_pmt_fixture(1546);
2400        let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
2401        d.add_service(&pmt1).unwrap();
2402        d.device_mut().inbound.push_back(sb());
2403        d.pump(Duration::from_millis(10)).unwrap();
2404
2405        let pmt2_bytes = build_ca_pmt_fixture(1547);
2406        let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
2407        d.add_service(&pmt2).unwrap();
2408        d.device_mut().inbound.push_back(sb());
2409        d.pump(Duration::from_millis(10)).unwrap();
2410
2411        // Second service joins an already-active set → `Add`, not `Only`.
2412        let expected2 = build_ca_pmt(&pmt2, CaPmtListManagement::Add, CaPmtCmdId::OkDescrambling)
2413            .to_bytes()
2414            .unwrap();
2415        assert_apdu_on_session(&d, CA_SESSION, &expected2);
2416
2417        assert_eq!(d.managed_ca().services().len(), 2);
2418    }
2419
2420    // --- #1067: managed add_service/requery must CAID-filter like the raw
2421    // `descramble` path already does ---
2422
2423    /// Same layout as [`build_ca_pmt_fixture`] but with TWO programme-level
2424    /// `CA_descriptor`s (Viaccess `0x0500` and Nagravision `0x1800` — both
2425    /// real assigned values per the TSDuck CA-system registry, mirroring
2426    /// `dvb_ci::builder`'s own two-CAID `build_test_pmt` fixture) and no
2427    /// ES-level CA — the #1067 regression fixture: a CAM that advertises
2428    /// only one of the two CAIDs must have the other filtered out of the
2429    /// sent `ca_pmt`.
2430    fn build_ca_pmt_fixture_two_caids(program_number: u16) -> Vec<u8> {
2431        const VIACCESS: u16 = 0x0500;
2432        const NAGRA: u16 = 0x1800;
2433        let prog_ca_a = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2434        let prog_ca_b = ca_descriptor(NAGRA, Pid::from_const(0x0066));
2435        let mut prog_ca = Vec::new();
2436        prog_ca.extend_from_slice(&prog_ca_a);
2437        prog_ca.extend_from_slice(&prog_ca_b);
2438
2439        let mut body = Vec::new();
2440        body.push(0x02); // table_id (PMT)
2441        body.push(0);
2442        body.push(0);
2443        body.extend_from_slice(&program_number.to_be_bytes());
2444        body.push(0xC3);
2445        body.push(0x00);
2446        body.push(0x00);
2447        body.push(0xE0 | 0x01); // PCR_PID = 0x0100
2448        body.push(0x00);
2449        body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2450        body.push(prog_ca.len() as u8);
2451        body.extend_from_slice(&prog_ca);
2452        // ES0: clear AAC audio, pid 0x0100 — no ES-level CA, so this
2453        // fixture isolates the programme-level filter.
2454        body.push(0x0F);
2455        body.push(0xE0 | 0x01);
2456        body.push(0x00);
2457        body.push(0xF0);
2458        body.push(0x00);
2459
2460        let section_length = body.len() - 3 + 4;
2461        body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2462        body[2] = section_length as u8;
2463        let crc = broadcast_common::crc32_mpeg2::compute(&body);
2464        body.extend_from_slice(&crc.to_be_bytes());
2465        body
2466    }
2467
2468    #[test]
2469    fn add_service_filters_ca_descriptors_to_cam_advertised_caids() {
2470        use broadcast_core::Parse;
2471        use dvb_ci::objects::ca_info::CaInfo;
2472
2473        let mut d = driver_with_sessions();
2474        d.take_notifications();
2475
2476        // CAM advertises ONLY Viaccess (0x0500); the PMT carries both
2477        // Viaccess and Nagravision (0x1800) programme-level CA_descriptors.
2478        feed(
2479            &mut d,
2480            r_apdu(
2481                CA_SESSION,
2482                &ser(&CaInfo {
2483                    length_form: dvb_ci::length::LengthForm::Minimal,
2484                    ca_system_ids: vec![0x0500],
2485                }),
2486            ),
2487        );
2488        d.take_notifications();
2489
2490        let pmt_bytes = build_ca_pmt_fixture_two_caids(1560);
2491        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2492
2493        // Oracle: `dvb_ci::builder::build_ca_pmt_for_caids` — the exact
2494        // filter the raw `descramble` path already applies
2495        // (`CiStack::build_ca_pmt_bytes`) — vs. the unfiltered `build_ca_pmt`
2496        // a pre-fix `add_service` sent.
2497        let expected_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2498            &pmt,
2499            &[0x0500],
2500            CaPmtListManagement::Only,
2501            CaPmtCmdId::OkDescrambling,
2502        )
2503        .to_bytes()
2504        .unwrap();
2505        let unfiltered = build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2506            .to_bytes()
2507            .unwrap();
2508        assert_ne!(
2509            expected_filtered, unfiltered,
2510            "precondition: the fixture's two CAIDs must make filtered != unfiltered"
2511        );
2512        let sends_filtered_before = count_apdu_on_session(&d, CA_SESSION, &expected_filtered);
2513        let sends_unfiltered_before = count_apdu_on_session(&d, CA_SESSION, &unfiltered);
2514
2515        d.add_service(&pmt).unwrap();
2516        d.device_mut().inbound.push_back(sb());
2517        d.pump(Duration::from_millis(10)).unwrap();
2518
2519        assert_eq!(
2520            count_apdu_on_session(&d, CA_SESSION, &expected_filtered),
2521            sends_filtered_before + 1,
2522            "add_service must send the CAID-filtered ca_pmt"
2523        );
2524        assert_eq!(
2525            count_apdu_on_session(&d, CA_SESSION, &unfiltered),
2526            sends_unfiltered_before,
2527            "add_service must NOT send the unfiltered ca_pmt once the CAM's CAIDs are known"
2528        );
2529    }
2530
2531    #[test]
2532    fn requery_timer_filters_ca_descriptors_to_cam_advertised_caids() {
2533        use broadcast_core::Parse;
2534        use dvb_ci::objects::ca_info::CaInfo;
2535
2536        let clock = TestClock::new();
2537        let mut d = driver_with_sessions().with_clock(clock.as_fn());
2538        // #1032: re-query is opt-in (REQUERY_DEFAULT = Duration::ZERO) —
2539        // enable it explicitly to exercise the timer.
2540        d.set_requery_interval(Duration::from_secs(10));
2541        d.take_notifications();
2542
2543        let pmt_bytes = build_ca_pmt_fixture_two_caids(1561);
2544        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2545        // add_service before any ca_info is known: unfiltered, per the
2546        // documented fallback (no CAID info to filter against yet).
2547        d.add_service(&pmt).unwrap();
2548        d.device_mut().inbound.push_back(sb());
2549        clock.advance(Duration::from_millis(10));
2550        d.pump(Duration::from_millis(10)).unwrap();
2551
2552        // The CAM's ca_info now arrives, advertising only Viaccess (0x0500).
2553        feed(
2554            &mut d,
2555            r_apdu(
2556                CA_SESSION,
2557                &ser(&CaInfo {
2558                    length_form: dvb_ci::length::LengthForm::Minimal,
2559                    ca_system_ids: vec![0x0500],
2560                }),
2561            ),
2562        );
2563        d.take_notifications();
2564
2565        // #1032: the timer resends a `list_management = update` PAIR —
2566        // `query` then `ok_descrambling` — both CAID-filtered (#1067).
2567        let expected_query_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2568            &pmt,
2569            &[0x0500],
2570            CaPmtListManagement::Update,
2571            CaPmtCmdId::Query,
2572        )
2573        .to_bytes()
2574        .unwrap();
2575        let expected_ok_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2576            &pmt,
2577            &[0x0500],
2578            CaPmtListManagement::Update,
2579            CaPmtCmdId::OkDescrambling,
2580        )
2581        .to_bytes()
2582        .unwrap();
2583        let unfiltered_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
2584            .to_bytes()
2585            .unwrap();
2586        let unfiltered_ok = build_ca_pmt(
2587            &pmt,
2588            CaPmtListManagement::Update,
2589            CaPmtCmdId::OkDescrambling,
2590        )
2591        .to_bytes()
2592        .unwrap();
2593        assert_ne!(
2594            expected_query_filtered, unfiltered_query,
2595            "precondition: the fixture's two CAIDs must make filtered != unfiltered (query)"
2596        );
2597        assert_ne!(
2598            expected_ok_filtered, unfiltered_ok,
2599            "precondition: the fixture's two CAIDs must make filtered != unfiltered (ok_descrambling)"
2600        );
2601        let sends_query_before = count_apdu_on_session(&d, CA_SESSION, &expected_query_filtered);
2602        let sends_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_filtered);
2603        let sends_unfiltered_query_before =
2604            count_apdu_on_session(&d, CA_SESSION, &unfiltered_query);
2605        let sends_unfiltered_ok_before = count_apdu_on_session(&d, CA_SESSION, &unfiltered_ok);
2606
2607        clock.advance(Duration::from_secs(11));
2608        d.pump(Duration::from_secs(11)).unwrap();
2609        feed(&mut d, sb());
2610
2611        assert_eq!(
2612            count_apdu_on_session(&d, CA_SESSION, &expected_query_filtered),
2613            sends_query_before + 1,
2614            "the re-query `query` half must be CAID-filtered to the CAM's advertised CAIDs"
2615        );
2616        assert_eq!(
2617            count_apdu_on_session(&d, CA_SESSION, &expected_ok_filtered),
2618            sends_ok_before + 1,
2619            "the re-query `ok_descrambling` half must be CAID-filtered to the CAM's advertised CAIDs"
2620        );
2621        assert_eq!(
2622            count_apdu_on_session(&d, CA_SESSION, &unfiltered_query),
2623            sends_unfiltered_query_before,
2624            "the re-query resend must NOT be the unfiltered `query` ca_pmt"
2625        );
2626        assert_eq!(
2627            count_apdu_on_session(&d, CA_SESSION, &unfiltered_ok),
2628            sends_unfiltered_ok_before,
2629            "the re-query resend must NOT be the unfiltered `ok_descrambling` ca_pmt"
2630        );
2631    }
2632
2633    // --- #763 Task 4: set_cat + emm_pids/descramble_pids ---
2634
2635    /// A hand-built CAT section (ISO/IEC 13818-1 §2.4.4.7): table_id 0x01, a
2636    /// flat descriptor loop of `CA_descriptor`s (ISO/IEC 13818-1 §2.6.16, tag
2637    /// 0x09; the `ca_descriptor` helper above builds the same TLV used for
2638    /// PMTs). No off-air CAT capture exists in this repo's fixture corpus
2639    /// (verified: none of the committed `.ts` captures carry PID 0x0001),
2640    /// mirroring the same hand-rolled-fixture precedent as
2641    /// `build_ca_pmt_fixture` and `dvb_si::tables::cat`'s own unit tests.
2642    pub(crate) fn build_cat_fixture(descriptors: &[u8]) -> Vec<u8> {
2643        const EXTENSION_HEADER_LEN: u16 = 5;
2644        const CRC_LEN: u16 = 4;
2645        let section_length = EXTENSION_HEADER_LEN + descriptors.len() as u16 + CRC_LEN;
2646        let mut v = Vec::new();
2647        v.push(0x01); // table_id (CAT)
2648        v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
2649        v.push((section_length & 0xFF) as u8);
2650        v.extend_from_slice(&[0xFF, 0xFF]); // table_id_extension (reserved for CAT)
2651        v.push(0xC1); // reserved(2)='11' | version(5)=0 | current_next=1
2652        v.push(0x00); // section_number
2653        v.push(0x00); // last_section_number
2654        v.extend_from_slice(descriptors);
2655        let crc = broadcast_common::crc32_mpeg2::compute(&v);
2656        v.extend_from_slice(&crc.to_be_bytes());
2657        v
2658    }
2659
2660    #[test]
2661    fn set_cat_computes_emm_pids_as_cat_inter_ca_info_caids() {
2662        use broadcast_core::Parse;
2663        use dvb_ci::objects::ca_info::CaInfo;
2664        use dvb_si::tables::cat::CatSection;
2665
2666        let mut d = driver_with_sessions();
2667        d.take_notifications();
2668
2669        // ca_info arrives first: the CAM advertises CAIDs 0x0648, 0x0100.
2670        feed(
2671            &mut d,
2672            r_apdu(
2673                CA_SESSION,
2674                &ser(&CaInfo {
2675                    length_form: dvb_ci::length::LengthForm::Minimal,
2676                    ca_system_ids: vec![0x0648, 0x0100],
2677                }),
2678            ),
2679        );
2680        d.take_notifications();
2681
2682        // CAT maps 0x0648 -> 0x1FF0 (advertised) and 0x0500 -> 0x1FF1 (not
2683        // advertised by this CAM).
2684        let mut descriptors = Vec::new();
2685        descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2686        descriptors.extend_from_slice(&ca_descriptor(0x0500, Pid::from_const(0x1FF1)));
2687        let cat_bytes = build_cat_fixture(&descriptors);
2688        let cat = CatSection::parse(&cat_bytes).unwrap();
2689
2690        d.set_cat(&cat).unwrap();
2691
2692        assert_eq!(
2693            d.emm_pids(),
2694            &[Pid::from_const(0x1FF0)],
2695            "0x0500 -> 0x1FF1 must be excluded: the CAM never advertised CAID 0x0500"
2696        );
2697    }
2698
2699    #[test]
2700    fn set_cat_before_ca_info_is_not_an_error_and_recomputes_once_ca_info_arrives() {
2701        use broadcast_core::Parse;
2702        use dvb_ci::objects::ca_info::CaInfo;
2703        use dvb_si::tables::cat::CatSection;
2704
2705        let mut d = driver_with_sessions();
2706        d.take_notifications();
2707
2708        let mut descriptors = Vec::new();
2709        descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2710        descriptors.extend_from_slice(&ca_descriptor(0x0500, Pid::from_const(0x1FF1)));
2711        let cat_bytes = build_cat_fixture(&descriptors);
2712        let cat = CatSection::parse(&cat_bytes).unwrap();
2713
2714        // set_cat with no ca_info observed yet: not an error, emm_pids stays
2715        // empty (nothing to intersect against).
2716        d.set_cat(&cat).unwrap();
2717        assert!(
2718            d.emm_pids().is_empty(),
2719            "emm_pids must be empty before any ca_info arrives, got {:?}",
2720            d.emm_pids()
2721        );
2722
2723        // ca_info now arrives: emm_pids recomputes against the CAT stored
2724        // earlier, without a second set_cat call.
2725        feed(
2726            &mut d,
2727            r_apdu(
2728                CA_SESSION,
2729                &ser(&CaInfo {
2730                    length_form: dvb_ci::length::LengthForm::Minimal,
2731                    ca_system_ids: vec![0x0648, 0x0100],
2732                }),
2733            ),
2734        );
2735        d.take_notifications();
2736
2737        assert_eq!(
2738            d.emm_pids(),
2739            &[Pid::from_const(0x1FF0)],
2740            "emm_pids must recompute once ca_info arrives, using the CAT stored by the earlier set_cat"
2741        );
2742    }
2743
2744    /// Task 4 review fix (MEDIUM): `recompute_emm_pids` must dedup like its
2745    /// sibling `recompute_service_pids` does — two CAT `CA_descriptor`s
2746    /// (distinct `CA_system_id`s, both CAM-advertised) that happen to share
2747    /// one `EMM_PID` (a real multi-CAS-on-one-EMM-PID broadcast setup) must
2748    /// list that PID exactly once, not twice.
2749    #[test]
2750    fn set_cat_emm_pids_dedups_when_two_caids_share_one_emm_pid() {
2751        use broadcast_core::Parse;
2752        use dvb_ci::objects::ca_info::CaInfo;
2753        use dvb_si::tables::cat::CatSection;
2754
2755        let mut d = driver_with_sessions();
2756        d.take_notifications();
2757
2758        // CAM advertises both CAIDs.
2759        feed(
2760            &mut d,
2761            r_apdu(
2762                CA_SESSION,
2763                &ser(&CaInfo {
2764                    length_form: dvb_ci::length::LengthForm::Minimal,
2765                    ca_system_ids: vec![0x0648, 0x0100],
2766                }),
2767            ),
2768        );
2769        d.take_notifications();
2770
2771        // CAT maps BOTH CAIDs to the SAME EMM PID.
2772        let mut descriptors = Vec::new();
2773        descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2774        descriptors.extend_from_slice(&ca_descriptor(0x0100, Pid::from_const(0x1FF0)));
2775        let cat_bytes = build_cat_fixture(&descriptors);
2776        let cat = CatSection::parse(&cat_bytes).unwrap();
2777
2778        d.set_cat(&cat).unwrap();
2779
2780        assert_eq!(
2781            d.emm_pids(),
2782            &[Pid::from_const(0x1FF0)],
2783            "0x1FF0 must appear exactly once even though two CAM-advertised CAIDs map to it, got {:?}",
2784            d.emm_pids()
2785        );
2786    }
2787
2788    /// Same layout as [`build_ca_pmt_fixture`] but with a distinct PCR/ES PID
2789    /// set, so a second added service proves `descramble_pids` is a real
2790    /// union rather than one programme's PIDs happening to repeat.
2791    fn build_ca_pmt_fixture_distinct_pids(program_number: u16) -> Vec<u8> {
2792        const VIACCESS: u16 = 0x0500;
2793        let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0074));
2794        let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0075));
2795
2796        let mut body = Vec::new();
2797        body.push(0x02); // table_id (PMT)
2798        body.push(0);
2799        body.push(0);
2800        body.extend_from_slice(&program_number.to_be_bytes());
2801        body.push(0xC3);
2802        body.push(0x00);
2803        body.push(0x00);
2804        body.push(0xE0 | 0x02); // PCR_PID = 0x0200
2805        body.push(0x00);
2806        body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2807        body.push(prog_ca.len() as u8);
2808        body.extend_from_slice(&prog_ca);
2809        // ES0: H.264 video, pid 0x0200, scrambled.
2810        body.push(0x1B);
2811        body.push(0xE0 | 0x02);
2812        body.push(0x00);
2813        body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2814        body.push(es0_ca.len() as u8);
2815        body.extend_from_slice(&es0_ca);
2816        // ES1: AAC ADTS audio, pid 0x0201, clear.
2817        body.push(0x0F);
2818        body.push(0xE0 | 0x02);
2819        body.push(0x01);
2820        body.push(0xF0);
2821        body.push(0x00);
2822
2823        let section_length = body.len() - 3 + 4;
2824        body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2825        body[2] = section_length as u8;
2826        let crc = broadcast_common::crc32_mpeg2::compute(&body);
2827        body.extend_from_slice(&crc.to_be_bytes());
2828        body
2829    }
2830
2831    #[test]
2832    fn descramble_pids_is_the_union_of_active_services_es_pids() {
2833        use broadcast_core::Parse;
2834
2835        let mut d = driver_with_sessions();
2836        d.take_notifications();
2837
2838        assert!(
2839            d.descramble_pids().is_empty(),
2840            "no service added yet: descramble_pids must be empty"
2841        );
2842
2843        let pmt1_bytes = build_ca_pmt_fixture(1546);
2844        let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
2845        d.add_service(&pmt1).unwrap();
2846        d.device_mut().inbound.push_back(sb());
2847        d.pump(Duration::from_millis(10)).unwrap();
2848
2849        assert_eq!(
2850            d.descramble_pids(),
2851            &[Pid::from_const(0x0100), Pid::from_const(0x0101)]
2852        );
2853
2854        let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
2855        let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
2856        d.add_service(&pmt2).unwrap();
2857        d.device_mut().inbound.push_back(sb());
2858        d.pump(Duration::from_millis(10)).unwrap();
2859
2860        // Union of both programmes' ES PIDs, sorted.
2861        assert_eq!(
2862            d.descramble_pids(),
2863            &[
2864                Pid::from_const(0x0100),
2865                Pid::from_const(0x0101),
2866                Pid::from_const(0x0200),
2867                Pid::from_const(0x0201)
2868            ],
2869            "descramble_pids must be the union across both added services"
2870        );
2871    }
2872
2873    // --- #763 Task 5: re-query timer + edge-triggered Entitlement ---
2874
2875    /// Build a `ca_pmt_reply` (EN 50221 §8.4.3.5, Table 26) for `program_number`
2876    /// carrying programme-level `ca_enable` (`None` = `CA_enable_flag` clear).
2877    pub(crate) fn ca_pmt_reply_for(
2878        program_number: u16,
2879        ca_enable: Option<dvb_ci::objects::ca_pmt_reply::CaEnable>,
2880    ) -> dvb_ci::objects::ca_pmt_reply::CaPmtReply {
2881        dvb_ci::objects::ca_pmt_reply::CaPmtReply {
2882            length_form: dvb_ci::length::LengthForm::Minimal,
2883            program_number,
2884            version_number: 1,
2885            current_next_indicator: true,
2886            ca_enable,
2887            streams: vec![],
2888            reserved_version: Default::default(),
2889            reserved_ca_enable: Default::default(),
2890        }
2891    }
2892
2893    #[test]
2894    fn requery_timer_resends_ca_pmt_then_reply_change_emits_one_entitlement() {
2895        use broadcast_core::Parse;
2896        use dvb_ci::objects::ca_pmt_reply::CaEnable;
2897
2898        let clock = TestClock::new();
2899        let mut d = driver_with_sessions().with_clock(clock.as_fn());
2900        // #1032: re-query is opt-in (REQUERY_DEFAULT = Duration::ZERO) —
2901        // enable it explicitly to exercise the timer.
2902        d.set_requery_interval(Duration::from_secs(10));
2903        d.take_notifications();
2904
2905        let pmt_bytes = build_ca_pmt_fixture(1546);
2906        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2907        d.add_service(&pmt).unwrap();
2908        d.device_mut().inbound.push_back(sb());
2909        clock.advance(Duration::from_millis(10));
2910        d.pump(Duration::from_millis(10)).unwrap();
2911        d.take_notifications();
2912
2913        // The initial `add_service` send is `ok_descrambling` — assert it
2914        // happened, so the test proves the resend below (a distinct `query`
2915        // cmd_id) is a genuinely different wire message, not the same bytes.
2916        let expected_initial_ca_pmt =
2917            build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2918                .to_bytes()
2919                .unwrap();
2920        assert_apdu_on_session(&d, CA_SESSION, &expected_initial_ca_pmt);
2921
2922        // #1032: the re-query timer resends a `list_management = update`
2923        // PAIR — `query` (to solicit a fresh `ca_pmt_reply`) immediately
2924        // followed by `ok_descrambling` (so descrambling is never left
2925        // barred, EN 50221 §8.4.3.5, whether or not the CAM answers the
2926        // query) — never the pre-fix `only`/`first` + `query` alone.
2927        let expected_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
2928            .to_bytes()
2929            .unwrap();
2930        let expected_ok_descrambling = build_ca_pmt(
2931            &pmt,
2932            CaPmtListManagement::Update,
2933            CaPmtCmdId::OkDescrambling,
2934        )
2935        .to_bytes()
2936        .unwrap();
2937        let query_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_query);
2938        let ok_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling);
2939
2940        let mut all_notes = Vec::new();
2941
2942        // Reply 1: not entitled (baseline — first-ever reply for this
2943        // program; `descrambling_ok` is derived: `NotPossibleNoEntitlement`
2944        // is not in the "possible" set, so `false`).
2945        feed(
2946            &mut d,
2947            r_apdu(
2948                CA_SESSION,
2949                &ser(&ca_pmt_reply_for(
2950                    1546,
2951                    Some(CaEnable::NotPossibleNoEntitlement),
2952                )),
2953            ),
2954        );
2955        all_notes.extend(d.take_notifications());
2956
2957        // Advance the clock past the 10s re-query interval: a single pump
2958        // ticks the stack with elapsed = 11s (nothing readable this turn),
2959        // which the #763 Task 5 re-query timer picks up and queues the
2960        // tracked service's `query`+`ok_descrambling` pair for resend (EN
2961        // 50221 §8.4.3.4 Table 25). EN 50221's link is half-duplex — this
2962        // tick's own keep-alive poll already claimed the turn, so the pair
2963        // is written across the module's next two `T_SB`s (the #337
2964        // one-write-per-turn rule), same as any other queued host write in
2965        // this test suite.
2966        clock.advance(Duration::from_secs(11));
2967        d.pump(Duration::from_secs(11)).unwrap();
2968        all_notes.extend(d.take_notifications());
2969        feed(&mut d, sb());
2970
2971        assert_eq!(
2972            count_apdu_on_session(&d, CA_SESSION, &expected_query),
2973            query_sends_before + 1,
2974            "expected the re-query timer to resend the `query` half exactly once"
2975        );
2976        assert_eq!(
2977            count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling),
2978            ok_sends_before + 1,
2979            "expected the re-query timer to resend the `ok_descrambling` half exactly once"
2980        );
2981
2982        // Reply 2: the CAM's re-evaluated answer to the re-query says
2983        // descrambling is now possible.
2984        feed(
2985            &mut d,
2986            r_apdu(
2987                CA_SESSION,
2988                &ser(&ca_pmt_reply_for(1546, Some(CaEnable::Possible))),
2989            ),
2990        );
2991        all_notes.extend(d.take_notifications());
2992
2993        let hits = all_notes
2994            .iter()
2995            .filter(|n| {
2996                matches!(
2997                    n,
2998                    Notification::Entitlement {
2999                        program_number: 1546,
3000                        ca_enable: CaEnable::Possible,
3001                        descrambling_ok: true,
3002                    }
3003                )
3004            })
3005            .count();
3006        assert_eq!(
3007            hits, 1,
3008            "expected exactly one Entitlement{{program_number:1546, ca_enable:Possible, descrambling_ok:true}}, got {all_notes:?}"
3009        );
3010    }
3011
3012    #[test]
3013    fn requery_timer_unchanged_reply_across_two_requeries_emits_no_entitlement() {
3014        use broadcast_core::Parse;
3015        use dvb_ci::objects::ca_pmt_reply::CaEnable;
3016
3017        let mut d = driver_with_sessions();
3018        // #1032: re-query is opt-in (REQUERY_DEFAULT = Duration::ZERO) —
3019        // enable it explicitly so the loop below exercises real re-queries.
3020        d.set_requery_interval(Duration::from_secs(10));
3021        d.take_notifications();
3022
3023        let pmt_bytes = build_ca_pmt_fixture(1547);
3024        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3025        d.add_service(&pmt).unwrap();
3026        d.device_mut().inbound.push_back(sb());
3027        d.pump(Duration::from_millis(10)).unwrap();
3028        d.take_notifications();
3029
3030        // Baseline reply: descrambling possible. First-ever reply — this
3031        // establishes the baseline and DOES emit once (per the transition
3032        // rule); drop it so the loop below only asserts on the re-queries.
3033        feed(
3034            &mut d,
3035            r_apdu(
3036                CA_SESSION,
3037                &ser(&ca_pmt_reply_for(1547, Some(CaEnable::Possible))),
3038            ),
3039        );
3040        d.take_notifications();
3041
3042        // Two re-queries, the CAM replying with the SAME unchanged status
3043        // both times: no Entitlement either time (negative control).
3044        for _ in 0..2 {
3045            d.pump(Duration::from_secs(11)).unwrap();
3046            d.take_notifications();
3047            feed(
3048                &mut d,
3049                r_apdu(
3050                    CA_SESSION,
3051                    &ser(&ca_pmt_reply_for(1547, Some(CaEnable::Possible))),
3052                ),
3053            );
3054            let notes = d.take_notifications();
3055            assert!(
3056                !notes
3057                    .iter()
3058                    .any(|n| matches!(n, Notification::Entitlement { .. })),
3059                "unchanged status across a re-query must not emit Entitlement, got {notes:?}"
3060            );
3061        }
3062    }
3063
3064    #[test]
3065    fn requery_reply_withdrawn_to_none_emits_no_entitlement() {
3066        use broadcast_core::Parse;
3067        use dvb_ci::objects::ca_pmt_reply::CaEnable;
3068
3069        let mut d = driver_with_sessions();
3070        d.take_notifications();
3071
3072        let pmt_bytes = build_ca_pmt_fixture(1548);
3073        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3074        d.add_service(&pmt).unwrap();
3075        d.device_mut().inbound.push_back(sb());
3076        d.pump(Duration::from_millis(10)).unwrap();
3077        d.take_notifications();
3078
3079        // Baseline: descrambling possible (drop the baseline Entitlement).
3080        feed(
3081            &mut d,
3082            r_apdu(
3083                CA_SESSION,
3084                &ser(&ca_pmt_reply_for(1548, Some(CaEnable::Possible))),
3085            ),
3086        );
3087        d.take_notifications();
3088
3089        // Programme `CA_enable_flag` now clear (`None`) — status withdrawn.
3090        // Per the transition rule this NEVER emits Entitlement (#726 HotPlug
3091        // covers the coarse withdrawal signal instead).
3092        feed(
3093            &mut d,
3094            r_apdu(CA_SESSION, &ser(&ca_pmt_reply_for(1548, None))),
3095        );
3096        let notes = d.take_notifications();
3097        assert!(
3098            !notes
3099                .iter()
3100                .any(|n| matches!(n, Notification::Entitlement { .. })),
3101            "ca_enable transitioning to None must not emit Entitlement, got {notes:?}"
3102        );
3103    }
3104
3105    #[test]
3106    fn requery_disabled_by_default_sends_nothing() {
3107        use broadcast_core::Parse;
3108
3109        // #1032: no `set_requery_interval` call at all — `REQUERY_DEFAULT`
3110        // (`Duration::ZERO`) must leave re-query off by default (it stays opt-in
3111        // although the `query` + `ok_descrambling` pair is hardware-verified).
3112        let mut d = driver_with_sessions();
3113        d.take_notifications();
3114
3115        let pmt_bytes = build_ca_pmt_fixture(1549);
3116        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3117        d.add_service(&pmt).unwrap();
3118        d.device_mut().inbound.push_back(sb());
3119        d.pump(Duration::from_millis(10)).unwrap();
3120
3121        // Count the `update`-variant bytes — the ones the timer would
3122        // resend if enabled — not the `only` bytes `add_service` sent.
3123        let expected_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
3124            .to_bytes()
3125            .unwrap();
3126        let expected_ok_descrambling = build_ca_pmt(
3127            &pmt,
3128            CaPmtListManagement::Update,
3129            CaPmtCmdId::OkDescrambling,
3130        )
3131        .to_bytes()
3132        .unwrap();
3133        let query_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_query);
3134        let ok_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling);
3135
3136        // Even a very long tick must not trigger a re-query by default.
3137        d.pump(Duration::from_secs(1_000_000)).unwrap();
3138        feed(&mut d, sb());
3139        feed(&mut d, sb());
3140        assert_eq!(
3141            count_apdu_on_session(&d, CA_SESSION, &expected_query),
3142            query_sends_before,
3143            "the default (Duration::ZERO) must never send a re-query `query`"
3144        );
3145        assert_eq!(
3146            count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling),
3147            ok_sends_before,
3148            "the default (Duration::ZERO) must never send a re-query `ok_descrambling`"
3149        );
3150    }
3151
3152    #[test]
3153    fn set_requery_interval_zero_disables_resend_after_being_enabled() {
3154        use broadcast_core::Parse;
3155
3156        let mut d = driver_with_sessions();
3157        // Enable, then explicitly disable again — proves `Duration::ZERO`
3158        // works as an override, not merely as an unexercised default.
3159        d.set_requery_interval(Duration::from_secs(5));
3160        d.set_requery_interval(Duration::ZERO);
3161        d.take_notifications();
3162
3163        let pmt_bytes = build_ca_pmt_fixture(1549);
3164        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3165        d.add_service(&pmt).unwrap();
3166        d.device_mut().inbound.push_back(sb());
3167        d.pump(Duration::from_millis(10)).unwrap();
3168
3169        // Count the `update`-variant bytes — the ones the timer would resend
3170        // if it fired — not the `only` bytes `add_service` sent (both are
3171        // `cmd_id = ok_descrambling`; they differ only in `list_management`).
3172        let expected_ca_pmt = build_ca_pmt(
3173            &pmt,
3174            CaPmtListManagement::Update,
3175            CaPmtCmdId::OkDescrambling,
3176        )
3177        .to_bytes()
3178        .unwrap();
3179        let sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ca_pmt);
3180
3181        // Even a very long tick must not trigger a re-query once disabled.
3182        d.pump(Duration::from_secs(1000)).unwrap();
3183        feed(&mut d, sb());
3184        feed(&mut d, sb());
3185
3186        let sends_after = count_apdu_on_session(&d, CA_SESSION, &expected_ca_pmt);
3187        assert_eq!(
3188            sends_after, sends_before,
3189            "Duration::ZERO must disable the re-query resend"
3190        );
3191    }
3192
3193    #[test]
3194    fn requery_timer_resends_every_active_service_not_just_one() {
3195        use broadcast_core::Parse;
3196
3197        let clock = TestClock::new();
3198        let mut d = driver_with_sessions().with_clock(clock.as_fn());
3199        // #1032: re-query is opt-in (REQUERY_DEFAULT = Duration::ZERO) —
3200        // enable it explicitly to exercise the timer.
3201        d.set_requery_interval(Duration::from_secs(10));
3202        d.take_notifications();
3203
3204        // Two services on the managed set: 1546 (`Only`, first-ever) and
3205        // 1547 (`Add`, joining the active set).
3206        let pmt1_bytes = build_ca_pmt_fixture(1546);
3207        let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3208        d.add_service(&pmt1).unwrap();
3209        d.device_mut().inbound.push_back(sb());
3210        clock.advance(Duration::from_millis(10));
3211        d.pump(Duration::from_millis(10)).unwrap();
3212
3213        let pmt2_bytes = build_ca_pmt_fixture(1547);
3214        let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3215        d.add_service(&pmt2).unwrap();
3216        d.device_mut().inbound.push_back(sb());
3217        clock.advance(Duration::from_millis(10));
3218        d.pump(Duration::from_millis(10)).unwrap();
3219        d.take_notifications();
3220
3221        // The `update`-variant PAIR the re-query timer rebuilds for each
3222        // service (#1032: `list_management = update`, `query` then
3223        // `ok_descrambling`, for every active service — `update` acts only
3224        // at programme level per EN 50221 §8.4.3.4, so unlike the pre-fix
3225        // `first`/`more`/`last` scheme it needs no position bookkeeping).
3226        let expected1_query = build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::Query)
3227            .to_bytes()
3228            .unwrap();
3229        let expected1_ok = build_ca_pmt(
3230            &pmt1,
3231            CaPmtListManagement::Update,
3232            CaPmtCmdId::OkDescrambling,
3233        )
3234        .to_bytes()
3235        .unwrap();
3236        let expected2_query = build_ca_pmt(&pmt2, CaPmtListManagement::Update, CaPmtCmdId::Query)
3237            .to_bytes()
3238            .unwrap();
3239        let expected2_ok = build_ca_pmt(
3240            &pmt2,
3241            CaPmtListManagement::Update,
3242            CaPmtCmdId::OkDescrambling,
3243        )
3244        .to_bytes()
3245        .unwrap();
3246        let sends_before1_query = count_apdu_on_session(&d, CA_SESSION, &expected1_query);
3247        let sends_before1_ok = count_apdu_on_session(&d, CA_SESSION, &expected1_ok);
3248        let sends_before2_query = count_apdu_on_session(&d, CA_SESSION, &expected2_query);
3249        let sends_before2_ok = count_apdu_on_session(&d, CA_SESSION, &expected2_ok);
3250
3251        // Advance the clock past the 10s re-query interval: this queues
3252        // BOTH services' `query`+`ok_descrambling` pairs (`requery_tick`
3253        // iterates the whole active set), but EN 50221's half-duplex link
3254        // (the #337 one-write-per-turn rule) only lets one out per turn —
3255        // feed enough `T_SB` acks to flush all four queued writes.
3256        clock.advance(Duration::from_secs(11));
3257        d.pump(Duration::from_secs(11)).unwrap();
3258        feed(&mut d, sb());
3259        feed(&mut d, sb());
3260
3261        assert_eq!(
3262            count_apdu_on_session(&d, CA_SESSION, &expected1_query),
3263            sends_before1_query + 1,
3264            "expected service 1546's `query` resent exactly once on the shared tick"
3265        );
3266        assert_eq!(
3267            count_apdu_on_session(&d, CA_SESSION, &expected1_ok),
3268            sends_before1_ok + 1,
3269            "expected service 1546's `ok_descrambling` resent exactly once on the shared tick"
3270        );
3271        assert_eq!(
3272            count_apdu_on_session(&d, CA_SESSION, &expected2_query),
3273            sends_before2_query + 1,
3274            "expected service 1547's `query` resent exactly once on the shared tick"
3275        );
3276        assert_eq!(
3277            count_apdu_on_session(&d, CA_SESSION, &expected2_ok),
3278            sends_before2_ok + 1,
3279            "expected service 1547's `ok_descrambling` resent exactly once on the shared tick"
3280        );
3281    }
3282
3283    // --- #765 (retained under #1032): re-query must reflect the CURRENT
3284    // active set, rebuilt fresh each tick, not a stale/frozen list ---
3285
3286    #[test]
3287    fn requery_after_remove_resends_only_the_surviving_service() {
3288        use broadcast_core::Parse;
3289
3290        let clock = TestClock::new();
3291        let mut d = driver_with_sessions().with_clock(clock.as_fn());
3292        // #1032: re-query is opt-in (REQUERY_DEFAULT = Duration::ZERO) —
3293        // enable it explicitly to exercise the timer.
3294        d.set_requery_interval(Duration::from_secs(10));
3295        d.take_notifications();
3296
3297        let pmt1_bytes = build_ca_pmt_fixture(1546);
3298        let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3299        d.add_service(&pmt1).unwrap();
3300        d.device_mut().inbound.push_back(sb());
3301        clock.advance(Duration::from_millis(10));
3302        d.pump(Duration::from_millis(10)).unwrap();
3303
3304        let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
3305        let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3306        d.add_service(&pmt2).unwrap();
3307        d.device_mut().inbound.push_back(sb());
3308        clock.advance(Duration::from_millis(10));
3309        d.pump(Duration::from_millis(10)).unwrap();
3310
3311        // Remove 1546: 1547 is now the SOLE survivor.
3312        d.remove_service(1546).unwrap();
3313        d.device_mut().inbound.push_back(sb());
3314        clock.advance(Duration::from_millis(10));
3315        d.pump(Duration::from_millis(10)).unwrap();
3316        d.take_notifications();
3317
3318        // The #765 bite (still relevant under #1032's `update`-based
3319        // resend): the timer must rebuild its re-query set from the CURRENT
3320        // active set on every tick, not a list frozen at `add_service` time
3321        // — so 1546 (removed) must never be resent, and 1547 (surviving)
3322        // must be resent as the `query`+`ok_descrambling` pair.
3323        let expected_survivor_query =
3324            build_ca_pmt(&pmt2, CaPmtListManagement::Update, CaPmtCmdId::Query)
3325                .to_bytes()
3326                .unwrap();
3327        let expected_survivor_ok = build_ca_pmt(
3328            &pmt2,
3329            CaPmtListManagement::Update,
3330            CaPmtCmdId::OkDescrambling,
3331        )
3332        .to_bytes()
3333        .unwrap();
3334        let expected_removed_query =
3335            build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::Query)
3336                .to_bytes()
3337                .unwrap();
3338        let expected_removed_ok = build_ca_pmt(
3339            &pmt1,
3340            CaPmtListManagement::Update,
3341            CaPmtCmdId::OkDescrambling,
3342        )
3343        .to_bytes()
3344        .unwrap();
3345        let sends_survivor_query_before =
3346            count_apdu_on_session(&d, CA_SESSION, &expected_survivor_query);
3347        let sends_survivor_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_survivor_ok);
3348        let sends_removed_query_before =
3349            count_apdu_on_session(&d, CA_SESSION, &expected_removed_query);
3350        let sends_removed_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_removed_ok);
3351
3352        clock.advance(Duration::from_secs(11));
3353        d.pump(Duration::from_secs(11)).unwrap();
3354        feed(&mut d, sb());
3355
3356        assert_eq!(
3357            count_apdu_on_session(&d, CA_SESSION, &expected_survivor_query),
3358            sends_survivor_query_before + 1,
3359            "the surviving service's `query` must be re-sent"
3360        );
3361        assert_eq!(
3362            count_apdu_on_session(&d, CA_SESSION, &expected_survivor_ok),
3363            sends_survivor_ok_before + 1,
3364            "the surviving service's `ok_descrambling` must be re-sent"
3365        );
3366        assert_eq!(
3367            count_apdu_on_session(&d, CA_SESSION, &expected_removed_query),
3368            sends_removed_query_before,
3369            "the removed service's `query` must NOT be re-sent"
3370        );
3371        assert_eq!(
3372            count_apdu_on_session(&d, CA_SESSION, &expected_removed_ok),
3373            sends_removed_ok_before,
3374            "the removed service's `ok_descrambling` must NOT be re-sent"
3375        );
3376    }
3377
3378    // --- #763 Task 6: remove_service + clear managed state on CAM hot-plug ---
3379
3380    #[test]
3381    fn remove_service_sends_update_not_selected_and_drops_from_managed_state() {
3382        use broadcast_core::Parse;
3383
3384        let mut d = driver_with_sessions();
3385        d.take_notifications();
3386
3387        // 1546 (`Only`, distinct PIDs 0x100/0x101) and 1547 (`Add`, distinct
3388        // PIDs 0x200/0x201) — distinct PID sets so removing 1546 is
3389        // observably different from removing 1547.
3390        let pmt1_bytes = build_ca_pmt_fixture(1546);
3391        let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3392        d.add_service(&pmt1).unwrap();
3393        d.device_mut().inbound.push_back(sb());
3394        d.pump(Duration::from_millis(10)).unwrap();
3395
3396        let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
3397        let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3398        d.add_service(&pmt2).unwrap();
3399        d.device_mut().inbound.push_back(sb());
3400        d.pump(Duration::from_millis(10)).unwrap();
3401
3402        d.remove_service(1546).unwrap();
3403        d.device_mut().inbound.push_back(sb());
3404        d.pump(Duration::from_millis(10)).unwrap();
3405
3406        // Oracle: the same PMT re-built directly via
3407        // dvb_ci::builder::build_ca_pmt with `Update`/`NotSelected` (EN 50221
3408        // §8.4.3.4 Table 25) — the exact bytes `remove_program` sends.
3409        let expected = build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3410            .to_bytes()
3411            .unwrap();
3412        assert_apdu_on_session(&d, CA_SESSION, &expected);
3413
3414        assert_eq!(
3415            d.descramble_pids(),
3416            &[Pid::from_const(0x0200), Pid::from_const(0x0201)],
3417            "1546's ES PIDs must be gone; 1547's must remain"
3418        );
3419        assert!(
3420            d.managed_ca().services().get(&1546).is_none(),
3421            "1546 must no longer be tracked"
3422        );
3423        assert!(
3424            d.managed_ca().services().get(&1547).is_some(),
3425            "1547 must remain tracked"
3426        );
3427    }
3428
3429    #[test]
3430    fn remove_service_of_untracked_program_is_a_no_op() {
3431        let mut d = driver_with_sessions();
3432        d.take_notifications();
3433
3434        let ops_before = d.device().ops.len();
3435        d.remove_service(0xFFFF).unwrap();
3436        assert_eq!(
3437            d.device().ops.len(),
3438            ops_before,
3439            "removing an untracked program must not send anything to the device"
3440        );
3441        assert!(
3442            d.managed_ca().services().is_empty(),
3443            "removing an untracked program must not disturb the (empty) managed set"
3444        );
3445    }
3446
3447    #[test]
3448    fn cam_removed_edge_clears_managed_state() {
3449        use broadcast_core::Parse;
3450        use dvb_ci::objects::ca_info::CaInfo;
3451        use dvb_si::tables::cat::CatSection;
3452
3453        let mut d = driver_with_sessions();
3454        d.take_notifications();
3455
3456        let pmt_bytes = build_ca_pmt_fixture(1546);
3457        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3458        d.add_service(&pmt).unwrap();
3459        d.device_mut().inbound.push_back(sb());
3460        d.pump(Duration::from_millis(10)).unwrap();
3461
3462        // Populate emm_pids too, via ca_info + set_cat, so the test proves
3463        // the fix clears more than just `services`.
3464        feed(
3465            &mut d,
3466            r_apdu(
3467                CA_SESSION,
3468                &ser(&CaInfo {
3469                    length_form: dvb_ci::length::LengthForm::Minimal,
3470                    ca_system_ids: vec![0x0648],
3471                }),
3472            ),
3473        );
3474        d.take_notifications();
3475        let mut descriptors = Vec::new();
3476        descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
3477        let cat_bytes = build_cat_fixture(&descriptors);
3478        let cat = CatSection::parse(&cat_bytes).unwrap();
3479        d.set_cat(&cat).unwrap();
3480
3481        assert!(
3482            !d.managed_ca().services().is_empty(),
3483            "precondition: a service is tracked"
3484        );
3485        assert!(
3486            !d.descramble_pids().is_empty(),
3487            "precondition: descramble_pids populated"
3488        );
3489        assert!(!d.emm_pids().is_empty(), "precondition: emm_pids populated");
3490
3491        // Module physically removed: a CamRemoved hot-plug edge.
3492        d.device_mut().slot.module_present = false;
3493        d.pump(Duration::from_millis(10)).unwrap();
3494        let notes = d.take_notifications();
3495        assert!(
3496            notes.contains(&Notification::HotPlug(HotPlug::CamRemoved)),
3497            "expected CamRemoved, got {notes:?}"
3498        );
3499
3500        assert!(
3501            d.managed_ca().services().is_empty(),
3502            "services must be cleared on CamRemoved"
3503        );
3504        assert!(
3505            d.descramble_pids().is_empty(),
3506            "descramble_pids must be cleared on CamRemoved"
3507        );
3508        assert!(
3509            d.emm_pids().is_empty(),
3510            "emm_pids must be cleared on CamRemoved"
3511        );
3512    }
3513
3514    #[test]
3515    fn update_service_not_managed_returns_not_managed_and_sends_nothing() {
3516        use broadcast_core::Parse;
3517
3518        let mut d = driver_with_sessions();
3519        d.take_notifications();
3520
3521        let pmt_bytes = build_clear_pmt_fixture(9999);
3522        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3523
3524        let before = d.device().ops.len();
3525        let err = d
3526            .update_service(&pmt)
3527            .expect_err("unknown program must error");
3528        assert!(
3529            matches!(
3530                err,
3531                CaError::NotManaged {
3532                    program_number: 9999
3533                }
3534            ),
3535            "got {err:?}"
3536        );
3537        assert_eq!(d.device().ops.len(), before, "must send nothing");
3538        assert!(d.managed_ca().services().is_empty());
3539    }
3540
3541    #[test]
3542    fn update_service_no_ca_descriptor_leaves_record_unchanged() {
3543        use broadcast_core::Parse;
3544
3545        let mut d = driver_with_sessions();
3546        d.take_notifications();
3547
3548        let pmt_bytes = build_ca_pmt_fixture(1546);
3549        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3550        d.add_service(&pmt).unwrap();
3551
3552        let svc_before = d.managed_ca().services().get(&1546).unwrap().clone();
3553
3554        let clear_bytes = build_clear_pmt_fixture(1546);
3555        let clear_pmt = PmtSection::parse(&clear_bytes).unwrap();
3556        let err = d
3557            .update_service(&clear_pmt)
3558            .expect_err("CA-free PMT must error");
3559        assert!(
3560            matches!(
3561                err,
3562                CaError::NoCaDescriptor {
3563                    program_number: 1546
3564                }
3565            ),
3566            "got {err:?}"
3567        );
3568
3569        let svc_after = d.managed_ca().services().get(&1546).unwrap();
3570        assert_eq!(svc_before, *svc_after, "record must be unchanged");
3571    }
3572
3573    /// #1389 wire-level: A and B are added; A's PMT then changes its ECM PIDs
3574    /// (`0x0064`/`0x0065` -> `0x0074`/`0x0075`, same programme number). Exactly
3575    /// one new `ca_pmt` goes out: `list_management = update`, `cmd_id =
3576    /// ok_descrambling`, carrying the NEW PIDs and none of the old; B's record
3577    /// is untouched; A's record is the NEW one (its PIDs, built bytes and raw PMT).
3578    #[test]
3579    fn update_service_sends_one_update_ca_pmt_with_the_new_pids_and_replaces_only_that_record() {
3580        use broadcast_core::Parse;
3581
3582        let mut d = driver_with_sessions();
3583        d.take_notifications();
3584
3585        let a_bytes = build_ca_pmt_fixture(1546);
3586        let a = PmtSection::parse(&a_bytes).unwrap();
3587        d.add_service(&a).unwrap();
3588        d.device_mut().inbound.push_back(sb());
3589        d.pump(Duration::from_millis(10)).unwrap();
3590
3591        let b_bytes = build_ca_pmt_fixture_dedicated_pcr(1547);
3592        let b = PmtSection::parse(&b_bytes).unwrap();
3593        d.add_service(&b).unwrap();
3594        d.device_mut().inbound.push_back(sb());
3595        d.pump(Duration::from_millis(10)).unwrap();
3596
3597        let a_old_record = d.managed_ca().services().get(&1546).unwrap().clone();
3598        let b_record_before = d.managed_ca().services().get(&1547).unwrap().clone();
3599        assert_eq!(
3600            a_old_record.ca_pids,
3601            vec![Pid::from_const(0x0064), Pid::from_const(0x0065)],
3602            "fixture sanity: A starts on the 0x0064/0x0065 ECM PIDs"
3603        );
3604
3605        // Same programme number, different ECM PIDs.
3606        let a2_bytes = build_ca_pmt_fixture_distinct_pids(1546);
3607        let a2 = PmtSection::parse(&a2_bytes).unwrap();
3608        let update = build_ca_pmt(&a2, CaPmtListManagement::Update, CaPmtCmdId::OkDescrambling)
3609            .to_bytes()
3610            .unwrap();
3611        let writes_before = d.device().ops.len();
3612
3613        d.update_service(&a2).unwrap();
3614        d.device_mut().inbound.push_back(sb());
3615        d.pump(Duration::from_millis(10)).unwrap();
3616
3617        // Exactly ONE update ca_pmt, on the CA session, and nothing else carrying a ca_pmt.
3618        assert_eq!(count_apdu_on_session(&d, CA_SESSION, &update), 1);
3619        let new_ca_pmt_writes = d.device().ops[writes_before..]
3620            .iter()
3621            .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == [0x9F, 0x80, 0x32])))
3622            .count();
3623        assert_eq!(new_ca_pmt_writes, 1, "exactly one ca_pmt APDU may be sent");
3624
3625        // The update carries the new ECM PIDs and none of the old ones.
3626        let new_prog_ca = ca_descriptor(0x0500, Pid::from_const(0x0074));
3627        let old_prog_ca = ca_descriptor(0x0500, Pid::from_const(0x0064));
3628        assert!(update.windows(new_prog_ca.len()).any(|x| x == new_prog_ca));
3629        assert!(!update.windows(old_prog_ca.len()).any(|x| x == old_prog_ca));
3630
3631        // A's record is replaced: new PIDs, new built bytes, new raw PMT.
3632        let a_new_record = d.managed_ca().services().get(&1546).unwrap();
3633        assert_eq!(
3634            a_new_record.ca_pids,
3635            vec![Pid::from_const(0x0074), Pid::from_const(0x0075)]
3636        );
3637        assert_eq!(a_new_record.built_ca_pmt, update);
3638        assert_ne!(a_new_record.built_ca_pmt, a_old_record.built_ca_pmt);
3639        assert_ne!(a_new_record.pmt_raw, a_old_record.pmt_raw);
3640        assert_eq!(
3641            a_new_record.pmt_raw, a2_bytes,
3642            "raw PMT must be the new section"
3643        );
3644
3645        // B is untouched, and so is the size of the managed set.
3646        assert_eq!(
3647            *d.managed_ca().services().get(&1547).unwrap(),
3648            b_record_before
3649        );
3650        assert_eq!(d.managed_ca().services().len(), 2);
3651    }
3652
3653    /// #1389: after an update, `remove_service` re-drives the removal from the
3654    /// NEW raw PMT (distinct PIDs, so the old PMT would produce different bytes).
3655    #[test]
3656    fn remove_service_after_update_service_uses_the_new_pmt() {
3657        use broadcast_core::Parse;
3658
3659        let mut d = driver_with_sessions();
3660        d.take_notifications();
3661
3662        let a_bytes = build_ca_pmt_fixture(1546);
3663        let a = PmtSection::parse(&a_bytes).unwrap();
3664        d.add_service(&a).unwrap();
3665        d.device_mut().inbound.push_back(sb());
3666        d.pump(Duration::from_millis(10)).unwrap();
3667        let a2_bytes = build_ca_pmt_fixture_distinct_pids(1546);
3668        let a2 = PmtSection::parse(&a2_bytes).unwrap();
3669        d.update_service(&a2).unwrap();
3670        d.device_mut().inbound.push_back(sb());
3671        d.pump(Duration::from_millis(10)).unwrap();
3672
3673        d.remove_service(1546).unwrap();
3674        d.device_mut().inbound.push_back(sb());
3675        d.pump(Duration::from_millis(10)).unwrap();
3676
3677        let removal_new = build_ca_pmt(&a2, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3678            .to_bytes()
3679            .unwrap();
3680        let removal_old = build_ca_pmt(&a, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3681            .to_bytes()
3682            .unwrap();
3683        assert_ne!(
3684            removal_new, removal_old,
3685            "fixture sanity: the two PMTs differ"
3686        );
3687        assert_eq!(count_apdu_on_session(&d, CA_SESSION, &removal_new), 1);
3688        assert_eq!(count_apdu_on_session(&d, CA_SESSION, &removal_old), 0);
3689        assert!(d.managed_ca().services().is_empty());
3690    }
3691
3692    /// #1389: the update `ca_pmt` is CAID-filtered exactly like `add_service`'s
3693    /// (#1067): a CAM advertising only Viaccess must not be sent the Nagra descriptor.
3694    #[test]
3695    fn update_service_filters_caids_like_add_service() {
3696        use broadcast_core::Parse;
3697
3698        let mut d = driver_with_sessions();
3699        d.take_notifications();
3700
3701        let two_caids = build_ca_pmt_fixture_two_caids(1546);
3702        let pmt = PmtSection::parse(&two_caids).unwrap();
3703        d.add_service(&pmt).unwrap();
3704        let added = d
3705            .managed_ca()
3706            .services()
3707            .get(&1546)
3708            .unwrap()
3709            .built_ca_pmt
3710            .clone();
3711
3712        d.update_service(&pmt).unwrap();
3713        let updated = d
3714            .managed_ca()
3715            .services()
3716            .get(&1546)
3717            .unwrap()
3718            .built_ca_pmt
3719            .clone();
3720
3721        // Same filtering as add_service: identical bytes except the list_management byte.
3722        assert_eq!(added.len(), updated.len());
3723        let diff: Vec<usize> = (0..added.len())
3724            .filter(|&i| added[i] != updated[i])
3725            .collect();
3726        assert_eq!(
3727            diff.len(),
3728            1,
3729            "only list_management may differ, got offsets {diff:?}"
3730        );
3731        assert_eq!(updated[diff[0]], 0x05, "list_management must be update");
3732    }
3733
3734    #[test]
3735    fn update_service_serialize_failure_leaves_record_unchanged() {
3736        let mut d = driver_with_sessions();
3737        // add a managed service for program_number 1 first
3738        let pmt_bytes = build_ca_pmt_fixture(1);
3739        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3740        d.add_service(&pmt).unwrap();
3741
3742        let svc_before = d.managed_ca().services().get(&1).unwrap().clone();
3743
3744        let corrupt = corrupt_ca_section_ctor();
3745        let err = d
3746            .update_service(&corrupt)
3747            .expect_err("unencodable PMT must error");
3748        assert!(
3749            matches!(err, CaError::Serialize(_)),
3750            "expected CaError::Serialize, got {err:?}"
3751        );
3752
3753        let svc_after = d.managed_ca().services().get(&1).unwrap();
3754        assert_eq!(svc_before, *svc_after, "record must be unchanged");
3755    }
3756
3757    #[test]
3758    fn add_service_without_an_open_ca_session_errors_and_records_nothing() {
3759        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
3760        let pmt_bytes = build_ca_pmt_fixture(1546);
3761        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3762        let result = d.add_service(&pmt);
3763        let wrote_ca_pmt = d.device().ops.iter().any(|op| match op {
3764            DeviceOp::Write(w) => w.windows(3).any(|x| x == [0x9F, 0x80, 0x32]),
3765            _ => false,
3766        });
3767        assert!(!wrote_ca_pmt, "precondition: nothing can have been sent");
3768        assert!(matches!(result, Err(CaError::NotSent { .. })), "{result:?}");
3769        assert!(d.managed_ca().services().is_empty());
3770    }
3771
3772    #[test]
3773    fn setup_timeout_is_followed_by_a_new_create_t_c() {
3774        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
3775        let clock = TestClock::new();
3776        d = d.with_clock(clock.as_fn());
3777        d.init().unwrap();
3778        for _ in 0..60 {
3779            clock.advance(Duration::from_millis(100));
3780            d.pump(Duration::from_millis(100)).unwrap();
3781        }
3782        let create_t_c = d
3783            .device()
3784            .ops
3785            .iter()
3786            .filter(|op| matches!(op, DeviceOp::Write(w) if w.first() == Some(&tags::CREATE_T_C)))
3787            .count();
3788        assert!(
3789            create_t_c > 1,
3790            "6 s of a silent CAM produced {create_t_c} Create_T_C"
3791        );
3792    }
3793
3794    #[test]
3795    fn readable_pumps_still_advance_the_requery_timer() {
3796        let clock = TestClock::new();
3797        let mut d = driver_with_sessions().with_clock(clock.as_fn());
3798        let pmt_bytes = build_ca_pmt_fixture(1546);
3799        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3800        d.add_service(&pmt).unwrap();
3801        d.set_requery_interval(Duration::from_secs(1));
3802        d.pump(Duration::from_millis(10)).unwrap();
3803        let ca_pmt_writes = |d: &Driver<MockCaDevice>| {
3804            d.device()
3805                .ops
3806                .iter()
3807                .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == [0x9F, 0x80, 0x32])))
3808                .count()
3809        };
3810        let before = ca_pmt_writes(&d);
3811        for _ in 0..8 {
3812            clock.advance(Duration::from_millis(500));
3813            d.device_mut().inbound.push_back(sb());
3814            d.pump(Duration::from_millis(10)).unwrap();
3815        }
3816        assert!(
3817            ca_pmt_writes(&d) > before,
3818            "4 s passed with a 1 s requery interval but no re-query was sent"
3819        );
3820    }
3821
3822    /// A CAM can deliver a legal link-layer frame far larger than 4094 bytes
3823    /// of TPDU (a `Tdata_last` block carries up to 65534 bytes); the driver
3824    /// must hand the device a buffer sized for the largest one, not a
3825    /// 4096-byte scratch buffer (audit a20-21).
3826    /// A host that only ever calls `pump` never drains the queue, so a CAM
3827    /// sending one notification per malformed frame must not grow it without
3828    /// bound (audit a20-38): the oldest are discarded past the cap, and every
3829    /// discard is counted.
3830    #[test]
3831    fn pending_notifications_are_bounded_and_the_overflow_counted() {
3832        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
3833        d.pump(Duration::from_millis(1)).unwrap();
3834        d.take_notifications();
3835
3836        d.device_mut().slot.module_present = false;
3837        d.pump(Duration::from_millis(1)).unwrap();
3838
3839        let overflow = 16;
3840        for _ in 0..(MAX_PENDING_NOTIFICATIONS + overflow) {
3841            d.device_mut().inbound.push_back(vec![0xFF, 0x00]);
3842            d.pump(Duration::from_millis(1)).unwrap();
3843        }
3844
3845        let notes = d.take_notifications();
3846        assert_eq!(
3847            notes.len(),
3848            MAX_PENDING_NOTIFICATIONS,
3849            "the pending queue must stay at its cap under a notification flood"
3850        );
3851        assert_eq!(
3852            d.notifications_dropped(),
3853            (overflow + 1) as u64,
3854            "the CAM-removed notification and the oldest errors are the ones discarded"
3855        );
3856        assert!(
3857            notes
3858                .iter()
3859                .all(|n| matches!(n, Notification::Error { .. })),
3860            "the discarded entries must be the oldest ones, not the newest"
3861        );
3862    }
3863
3864    #[test]
3865    fn read_buffer_covers_the_largest_legal_device_frame() {
3866        struct BufferProbe(Option<usize>);
3867
3868        impl CaDevice for BufferProbe {
3869            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3870                self.0 = Some(buf.len());
3871                Ok(0)
3872            }
3873            fn write(&mut self, _buf: &[u8]) -> io::Result<()> {
3874                Ok(())
3875            }
3876            fn reset(&mut self) -> io::Result<()> {
3877                Ok(())
3878            }
3879            fn slot_info(&mut self) -> io::Result<SlotInfo> {
3880                Ok(SlotInfo {
3881                    num: 0,
3882                    module_ready: true,
3883                    module_present: true,
3884                })
3885            }
3886            fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
3887                Ok(true)
3888            }
3889        }
3890
3891        let mut d = Driver::new(BufferProbe(None), DRIVER);
3892        d.pump(Duration::from_millis(1))
3893            .expect("a readable device with no frame is not an error");
3894        assert_eq!(
3895            d.device().0,
3896            Some(MAX_CA_FRAME),
3897            "the read buffer must cover the largest legal device frame"
3898        );
3899    }
3900
3901    /// The behavioural half of a20-21: a device that refuses a frame which
3902    /// does not fit the caller's buffer (exactly `LinuxCaDevice`'s contract)
3903    /// must not fail the pump for a legal `Tdata_last` block larger than the
3904    /// old 4096-byte buffer.
3905    #[test]
3906    fn a_legal_oversized_tpdu_is_read_without_an_io_error() {
3907        const DATA_LEN: usize = 5000;
3908
3909        struct OversizedFrameDevice(Option<Vec<u8>>);
3910
3911        impl CaDevice for OversizedFrameDevice {
3912            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3913                let Some(frame) = self.0.take() else {
3914                    return Ok(0);
3915                };
3916                if frame.len() > buf.len() {
3917                    return Err(io::Error::new(
3918                        io::ErrorKind::InvalidData,
3919                        "TPDU larger than the read buffer; dropped, not truncated",
3920                    ));
3921                }
3922                let n = frame.len();
3923                buf[..n].copy_from_slice(&frame);
3924                Ok(n)
3925            }
3926            fn write(&mut self, _buf: &[u8]) -> io::Result<()> {
3927                Ok(())
3928            }
3929            fn reset(&mut self) -> io::Result<()> {
3930                Ok(())
3931            }
3932            fn slot_info(&mut self) -> io::Result<SlotInfo> {
3933                Ok(SlotInfo {
3934                    num: 0,
3935                    module_ready: true,
3936                    module_present: true,
3937                })
3938            }
3939            fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
3940                Ok(self.0.is_some())
3941            }
3942        }
3943
3944        let mut frame = vec![tags::DATA_LAST];
3945        let mut length = [0u8; 4];
3946        let coded = dvb_ci::length::encode_into(1 + DATA_LEN, &mut length)
3947            .expect("a legal EN 50221 length");
3948        frame.extend_from_slice(&length[..coded]);
3949        frame.push(0x01);
3950        frame.extend(std::iter::repeat_n(0xAB, DATA_LEN));
3951
3952        let mut d = Driver::new(OversizedFrameDevice(Some(frame)), DRIVER);
3953        assert!(
3954            d.pump(Duration::from_millis(1)).is_ok(),
3955            "a legal {DATA_LEN}-byte TPDU must not fail the read"
3956        );
3957        assert!(
3958            d.device().0.is_none(),
3959            "the frame must have been taken off the device, not refused"
3960        );
3961    }
3962
3963    // --- #2947: the public control API, timers, CA PIDs and card inference ---
3964
3965    const APP_INFO_SESSION: u16 = 2;
3966
3967    fn ca_pmt_for(
3968        pmt: &PmtSection<'_>,
3969        list_management: CaPmtListManagement,
3970        cmd_id: CaPmtCmdId,
3971    ) -> Vec<u8> {
3972        let bytes = build_ca_pmt(pmt, list_management, cmd_id)
3973            .to_bytes()
3974            .unwrap();
3975        assert_eq!(&bytes[..3], &[0x9F, 0x80, 0x32], "ca_pmt APDU tag");
3976        let parsed = dvb_ci::objects::ca_pmt::CaPmt::parse(&bytes).unwrap();
3977        assert_eq!(parsed.list_management, list_management);
3978        assert_eq!(parsed.cmd_id, Some(cmd_id));
3979        assert_eq!(parsed.program_number, 1546);
3980        bytes
3981    }
3982
3983    #[test]
3984    fn descramble_writes_the_ok_descrambling_ca_pmt() {
3985        let mut d = driver_with_sessions();
3986        d.take_notifications();
3987        let pmt_bytes = build_ca_pmt_fixture(1546);
3988        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3989
3990        d.descramble(&pmt_bytes).unwrap();
3991        d.device_mut().inbound.push_back(sb());
3992        d.pump(Duration::from_millis(10)).unwrap();
3993
3994        assert_apdu_on_session(
3995            &d,
3996            CA_SESSION,
3997            &ca_pmt_for(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling),
3998        );
3999    }
4000
4001    #[test]
4002    fn descramble_programs_writes_the_ca_pmt_list() {
4003        let mut d = driver_with_sessions();
4004        d.take_notifications();
4005        let pmt_bytes = build_ca_pmt_fixture(1546);
4006        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4007
4008        d.descramble_programs(&[&pmt_bytes]).unwrap();
4009        d.device_mut().inbound.push_back(sb());
4010        d.pump(Duration::from_millis(10)).unwrap();
4011
4012        assert_apdu_on_session(
4013            &d,
4014            CA_SESSION,
4015            &ca_pmt_for(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling),
4016        );
4017    }
4018
4019    #[test]
4020    fn add_program_writes_the_add_ca_pmt() {
4021        let mut d = driver_with_sessions();
4022        d.take_notifications();
4023        let pmt_bytes = build_ca_pmt_fixture(1546);
4024        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4025
4026        d.add_program(&pmt_bytes).unwrap();
4027        d.device_mut().inbound.push_back(sb());
4028        d.pump(Duration::from_millis(10)).unwrap();
4029
4030        assert_apdu_on_session(
4031            &d,
4032            CA_SESSION,
4033            &ca_pmt_for(&pmt, CaPmtListManagement::Add, CaPmtCmdId::OkDescrambling),
4034        );
4035    }
4036
4037    #[test]
4038    fn ca_pids_lists_the_programme_and_es_ca_descriptor_pids() {
4039        let mut d = driver_with_sessions();
4040        let pmt_bytes = build_ca_pmt_fixture(1546);
4041        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4042        d.add_service(&pmt).unwrap();
4043
4044        assert_eq!(
4045            d.ca_pids(),
4046            [Pid::from_const(0x0064), Pid::from_const(0x0065)]
4047        );
4048    }
4049
4050    #[test]
4051    fn enter_menu_and_mmi_cancel_write_their_apdus() {
4052        use dvb_ci::objects::application_info::EnterMenu;
4053        use dvb_ci::objects::mmi_high::{Answ, AnswId};
4054
4055        let mut d = driver_with_sessions();
4056        d.take_notifications();
4057
4058        d.enter_menu().unwrap();
4059        d.device_mut().inbound.push_back(sb());
4060        d.pump(Duration::from_millis(10)).unwrap();
4061        assert_apdu_on_session(&d, APP_INFO_SESSION, &ser(&EnterMenu::default()));
4062
4063        d.mmi_cancel().unwrap();
4064        d.device_mut().inbound.push_back(sb());
4065        d.pump(Duration::from_millis(10)).unwrap();
4066        assert_apdu_on_session(
4067            &d,
4068            MMI_SESSION,
4069            &ser(&Answ {
4070                length_form: dvb_ci::length::LengthForm::Minimal,
4071                answ_id: AnswId::Cancel,
4072                text_chars: &[],
4073            }),
4074        );
4075    }
4076
4077    #[test]
4078    fn next_timer_is_none_until_a_write_arms_the_poll_cadence() {
4079        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4080        assert_eq!(d.next_timer(), None);
4081        d.init().unwrap();
4082        assert_eq!(
4083            d.next_timer(),
4084            Some(crate::test_support::DEFAULT_REPLY_TIMEOUT),
4085            "the outstanding Create_T_C arms the reply timer"
4086        );
4087        assert!(d.next_timer().is_some_and(|d| d > Duration::ZERO));
4088    }
4089
4090    /// #2947: exactly at the settle deadline the deferred writes flush; one
4091    /// nanosecond earlier they must not.
4092    #[test]
4093    fn the_settle_deadline_flushes_writes_at_the_exact_instant() {
4094        let clock = TestClock::new();
4095        let mut d = settling_driver(&clock);
4096        d.init().unwrap();
4097
4098        clock.advance(SETTLE - Duration::from_nanos(1));
4099        d.pump(Duration::from_millis(10)).unwrap();
4100        assert_eq!(
4101            create_tc_writes(&d),
4102            0,
4103            "1ns before the deadline the slot is still settling"
4104        );
4105
4106        clock.advance(Duration::from_nanos(1));
4107        d.pump(Duration::from_millis(10)).unwrap();
4108        assert_eq!(
4109            create_tc_writes(&d),
4110            1,
4111            "at the deadline the deferred write flushes"
4112        );
4113    }
4114
4115    /// #2947: an `EINVAL` at the exact instant the slot-ready grace window
4116    /// ends is reported, not retried.
4117    #[test]
4118    fn an_einval_at_the_grace_deadline_is_reported() {
4119        let clock = TestClock::new();
4120        let mut d = not_running_driver(&clock, 1);
4121        d.init().unwrap();
4122        clock.advance(SETTLE + SLOT_READY_GRACE);
4123        let err = d
4124            .pump(Duration::from_millis(10))
4125            .expect_err("at the deadline the refusal must be reported");
4126        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
4127    }
4128
4129    /// #2947: a retry armed after an `EINVAL` waits `SLOT_RETRY`, not zero
4130    /// time.
4131    #[test]
4132    fn an_einval_retry_waits_slot_retry_before_the_next_attempt() {
4133        let clock = TestClock::new();
4134        let mut d = not_running_driver(&clock, u32::MAX);
4135        d.init().unwrap();
4136        clock.advance(SETTLE + Duration::from_millis(100));
4137        d.pump(Duration::from_millis(10)).unwrap();
4138        assert_eq!(d.device().refused, 1);
4139
4140        clock.advance(Duration::from_millis(100));
4141        d.pump(Duration::from_millis(10)).unwrap();
4142        assert_eq!(d.device().refused, 1, "the retry waits for SLOT_RETRY");
4143
4144        clock.advance(Duration::from_millis(200));
4145        d.pump(Duration::from_millis(10)).unwrap();
4146        assert_eq!(d.device().refused, 2, "the retry fires after SLOT_RETRY");
4147    }
4148
4149    /// A device that reports a readiness edge but hands back no bytes.
4150    struct ReadBreaksDevice(MockCaDevice);
4151
4152    impl CaDevice for ReadBreaksDevice {
4153        fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
4154            Ok(0)
4155        }
4156        fn write(&mut self, buf: &[u8]) -> io::Result<()> {
4157            self.0.write(buf)
4158        }
4159        fn reset(&mut self) -> io::Result<()> {
4160            self.0.reset()
4161        }
4162        fn reset_settle(&self) -> Duration {
4163            self.0.reset_settle()
4164        }
4165        fn slot_info(&mut self) -> io::Result<SlotInfo> {
4166            self.0.slot_info()
4167        }
4168        fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
4169            Ok(true)
4170        }
4171    }
4172
4173    /// #2947: a readiness edge that yields zero bytes is not a processed frame.
4174    #[test]
4175    fn a_readiness_edge_with_no_bytes_is_not_a_frame() {
4176        let mut d = Driver::new(ReadBreaksDevice(MockCaDevice::new([])), DRIVER);
4177        d.init().unwrap();
4178        assert!(
4179            !d.pump(Duration::from_millis(10)).unwrap(),
4180            "a zero-byte read is not a processed frame"
4181        );
4182    }
4183
4184    /// #2947: a refusal produced by an earlier call, still in a full queue,
4185    /// is not attributed to a later successful call.
4186    #[test]
4187    fn an_old_refusal_in_a_full_queue_is_not_reported_for_a_healthy_send() {
4188        let mut d = driver_with_sessions();
4189        for _ in 0..MAX_PENDING_NOTIFICATIONS + 5 {
4190            d.push_notification(Notification::CamReady);
4191        }
4192        d.push_notification(Notification::Error {
4193            detail: "an earlier failure".to_string(),
4194        });
4195        assert_eq!(d.notifications.len(), MAX_PENDING_NOTIFICATIONS);
4196        assert!(d.notifications_dropped() > 0);
4197
4198        let pmt_bytes = build_ca_pmt_fixture(1546);
4199        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4200        d.add_service(&pmt)
4201            .expect("a healthy send must not inherit an older refusal");
4202    }
4203
4204    /// #2947: the refusal produced by this very call is reported.
4205    #[test]
4206    fn a_refusal_produced_by_this_call_is_reported() {
4207        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4208        d.init().unwrap();
4209        let pmt_bytes = build_ca_pmt_fixture(1546);
4210        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4211        let err = d
4212            .add_service(&pmt)
4213            .expect_err("no open CA session means the ca_pmt was not handed over");
4214        assert!(
4215            matches!(err, CaError::NotSent { .. }),
4216            "expected CaError::NotSent, got {err:?}"
4217        );
4218    }
4219
4220    fn ca_info(ids: &[u16]) -> Notification {
4221        Notification::CaInfo {
4222            ca_system_ids: ids.to_vec(),
4223        }
4224    }
4225
4226    fn ca_pmt_reply(descrambling_ok: bool) -> Notification {
4227        Notification::CaPmtReply {
4228            program_number: 1546,
4229            ca_enable: None,
4230            descrambling_ok,
4231        }
4232    }
4233
4234    #[test]
4235    fn infer_card_follows_the_ca_info_edges() {
4236        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4237        assert!(d.infer_card(&ca_info(&[])).is_empty());
4238        assert_eq!(
4239            d.infer_card(&ca_info(&[0x0500])),
4240            vec![Notification::HotPlug(HotPlug::CardInserted)]
4241        );
4242        assert!(
4243            d.infer_card(&ca_info(&[0x0500])).is_empty(),
4244            "the same CAID set repeated is not an edge"
4245        );
4246        assert_eq!(
4247            d.infer_card(&ca_info(&[0x0500, 0x0B00])),
4248            vec![Notification::HotPlug(HotPlug::CardChanged)]
4249        );
4250        assert_eq!(
4251            d.infer_card(&ca_info(&[])),
4252            vec![Notification::HotPlug(HotPlug::CardRemoved)]
4253        );
4254    }
4255
4256    #[test]
4257    fn infer_card_follows_the_descrambling_reply_edges() {
4258        let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4259        assert!(d.infer_card(&ca_pmt_reply(false)).is_empty());
4260        assert_eq!(
4261            d.infer_card(&ca_pmt_reply(true)),
4262            vec![Notification::HotPlug(HotPlug::CardInserted)]
4263        );
4264        assert!(
4265            d.infer_card(&ca_pmt_reply(true)).is_empty(),
4266            "the same state repeated is not an edge"
4267        );
4268        assert_eq!(
4269            d.infer_card(&ca_pmt_reply(false)),
4270            vec![Notification::HotPlug(HotPlug::CardRemoved)]
4271        );
4272    }
4273}