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