Skip to main content

dvb_ci_runtime/
managed.rs

1//! Managed CAS-layer state (#763) — the [`Driver`](crate::Driver)'s owned view
2//! of the slot's active descrambled-service set.
3//!
4//! This is Layer 1 of the #763 CAS orchestration design
5//! (`docs/superpowers/specs/2026-07-24-dvb-ci-cas-layer-design.md`): parsed
6//! `dvb-si` structures in (never raw bytes), the existing
7//! `dvb_ci::builder::build_ca_pmt` PMT→`ca_pmt` projection
8//! (ETSI EN 50221 §8.4.3.4, Table 25) does the wire work, and this module just
9//! tracks what was sent. [`Driver::add_service`](crate::driver::Driver::add_service)
10//! builds + sends the `ca_pmt` and records the service here.
11
12use mpeg_ts::pid::Pid;
13use mpeg_ts::pid::well_known::CAT as CAT_PID;
14use std::collections::{BTreeMap, BTreeSet};
15use std::time::Duration;
16
17use dvb_ci::objects::ca_pmt::CaPmtCmdId;
18use dvb_ci::objects::ca_pmt_reply::CaEnable;
19use dvb_si::descriptors::DescriptorLoop;
20use dvb_si::descriptors::ca::{CaDescriptor, TAG as CA_DESCRIPTOR_TAG};
21use dvb_si::tables::cat::CatCaEntry;
22use dvb_si::tables::pmt::PmtSection;
23
24/// Default entitlement re-query cadence (#763 Task 5's `Resource::tick`-driven
25/// refresh; `Duration::ZERO` disables it). Set on [`ManagedCa::new`] so the
26/// field is in place before the re-query timer is wired up.
27///
28/// **`Duration::ZERO` (opt-in, since #1032).** The feature was on by default
29/// at 10s until #1032, when a lone `query` every 10 s was found to stop an
30/// AlphaCrypt/Irdeto module descrambling. The timer now sends `update/query`
31/// immediately followed by `update/ok_descrambling`, which was hardware-verified
32/// on an entitled AlphaCrypt One4All V2.5 (the module answered most queries with
33/// `ca_enable = 0x81` and descrambling never gapped), but it stays opt-in: the
34/// periodic re-query only helps a host that wants a fresh `ca_pmt_reply`, and it
35/// has been verified on that one CAM only. Call
36/// [`Driver::set_requery_interval`](crate::driver::Driver::set_requery_interval)
37/// explicitly once re-query is verified against your own CAM.
38pub const REQUERY_DEFAULT: Duration = Duration::ZERO;
39
40/// Sentinel `PCR_PID` value meaning "no PCR carried for this programme" (ISO/IEC
41/// 13818-1 §2.4.4.9, Table 2-33's `PCR_PID` field). A `ManagedService` whose
42/// `pcr_pid` is this value carries no dedicated PCR PID to route — it must be
43/// excluded from [`ManagedCa::required_pids`], never treated as a routable PID.
44const PCR_PID_NONE: Pid = Pid::from_const(0x1FFF);
45
46/// Errors from the managed CAS-layer API (`Driver::add_service` and friends,
47/// #763).
48#[derive(Debug, thiserror::Error)]
49#[non_exhaustive]
50pub enum CaError {
51    /// The PMT carries no `CA_descriptor` (ISO/IEC 13818-1 §2.6.16, tag
52    /// `0x09`) at programme or elementary-stream level — there is nothing for
53    /// the CAM to descramble, so no `ca_pmt` is built or sent.
54    #[error("PMT for program_number {program_number} has no CA_descriptor at program or ES level")]
55    #[non_exhaustive]
56    NoCaDescriptor {
57        /// The programme whose PMT carried no CA info.
58        program_number: u16,
59    },
60    /// Sending the built `ca_pmt` to the device failed.
61    #[error("ca_pmt send failed: {0}")]
62    Io(#[from] std::io::Error),
63    /// The stack could not hand the `ca_pmt` to the CAM (no open
64    /// conditional-access session, connection not active, or a full outbound
65    /// queue); the managed service set is left unchanged.
66    #[error("ca_pmt was not sent: {detail}")]
67    #[non_exhaustive]
68    NotSent {
69        /// The stack's diagnostic, forwarded verbatim from its `Notification::Error`.
70        detail: String,
71    },
72    /// The `ca_pmt` projected from the caller's PMT has no valid wire
73    /// encoding (a `program_info_length`/`ES_info_length` or `version_number`
74    /// out of its spec range — e.g. a source PMT whose descriptor loop is
75    /// corrupted past the section end) or its stored raw PMT no longer
76    /// re-parses. r10-W-20: `Driver::add_service` and the re-query timer
77    /// must reject such a PMT as an `Err` value rather than panic inside
78    /// the serialization.
79    #[error("ca_pmt serialization failed: {0}")]
80    Serialize(#[from] dvb_ci::Error),
81    /// The raw PMT bytes stored at `add_service` time no longer re-parse on
82    /// a re-query tick (corruption of the caller's own state); the re-query
83    /// is reported as an error instead of panicking (r10-W-20). Shares the
84    /// `dvb_si::error::Error` payload of the `Cat` arm.
85    #[error("stored PMT re-parse failed: {0}")]
86    PmtParse(dvb_si::error::Error),
87    /// The CAT's descriptor loop (ISO/IEC 13818-1 §2.4.4.7) carried a
88    /// truncated `CA_descriptor` (ISO/IEC 13818-1 §2.6.16) — [`Driver::set_cat`](crate::driver::Driver::set_cat)
89    /// could not extract the CAID/EMM-PID map.
90    #[error("CAT CA_descriptor parse failed: {0}")]
91    Cat(#[from] dvb_si::error::Error),
92    /// The programme is not in the slot's managed CAS-layer service set, so
93    /// there is nothing to `update` (EN 50221 §8.4.3.4 Table 25,
94    /// `ca_pmt_list_management = update`). Returned by
95    /// [`Driver::update_service`](crate::driver::Driver::update_service) for an
96    /// unknown `program_number`.
97    #[error("program_number {program_number} is not a managed service")]
98    #[non_exhaustive]
99    NotManaged {
100        /// The programme that is not currently managed.
101        program_number: u16,
102    },
103}
104
105/// One actively-managed service (owned, no borrowed lifetime — copied out of
106/// the caller's `PmtSection` at [`Driver::add_service`](crate::driver::Driver::add_service)
107/// time).
108///
109/// `cmd` and `last_ca_enable` are recorded starting now but are only *read* by
110/// Task 6's `remove_service`; `last_ca_enable`/`last_descrambling_ok` are also
111/// read+written by `ManagedCa::record_reply` (#763 Task 5's edge-triggered
112/// `Notification::Entitlement`).
113#[derive(Debug, Clone, PartialEq, Eq)]
114#[non_exhaustive]
115pub struct ManagedService {
116    /// Elementary-stream PIDs carried by this programme (every stream, not
117    /// only the CA-bearing ones — a caller routing PIDs into `ci0` needs the
118    /// full component set).
119    pub es_pids: Vec<Pid>,
120    /// `CA_PID`s (ECM PIDs) advertised by this programme's `CA_descriptor`s,
121    /// programme- and ES-level combined.
122    pub ca_pids: Vec<Pid>,
123    /// This programme's PMT `PCR_PID` (ISO/IEC 13818-1 §2.4.4.9) — the PID
124    /// carrying the programme clock reference. May coincide with an
125    /// `es_pids` entry (PCR piggybacked on a component stream) or be a PID of
126    /// its own (a dedicated PCR PID, carrying no other stream) — either way a
127    /// caller routing PIDs into `ci0` needs it, or the descrambled TS loses
128    /// its clock reference. `0x1FFF` means the programme carries no PCR (ISO/IEC
129    /// 13818-1 §2.4.4.9) and is excluded from routing.
130    pub pcr_pid: Pid,
131    /// The `ca_pmt_cmd_id` last sent for this service (EN 50221 §8.4.3.4
132    /// Table 25).
133    pub cmd: CaPmtCmdId,
134    /// The last observed programme-level `CA_enable` (EN 50221 §8.4.3.5 Table
135    /// 26), for the Task 5 edge-triggered `Notification::Entitlement`. `None`
136    /// until a `ca_pmt_reply` has been seen for this programme, or when the
137    /// last-seen reply's programme `CA_enable_flag` was clear.
138    pub last_ca_enable: Option<CaEnable>,
139    /// The last observed `descrambling_ok` (derived from `last_ca_enable`),
140    /// paired with it for the Task 5 transition diff.
141    pub(crate) last_descrambling_ok: bool,
142    /// The exact `ca_pmt` bytes sent by [`Driver::add_service`](crate::driver::Driver::add_service)
143    /// to start descrambling — `list_management = only`/`add`,
144    /// `cmd_id = ok_descrambling` (EN 50221 §8.4.3.4 Table 25). Kept for the
145    /// add_service oracle test to assert what was actually sent; this is
146    /// *not* what the #765/#1032 re-query timer resends —
147    /// `Driver::requery_tick` rebuilds a fresh `list_management = update`
148    /// `query`/`ok_descrambling` pair (#1032) per tick from
149    /// [`pmt_raw`](Self::pmt_raw), against the *current* active set each
150    /// time (not frozen at this service's `add_service` time).
151    pub(crate) built_ca_pmt: Vec<u8>,
152    /// The owned raw PMT section bytes this service was built from (#763
153    /// Task 6), kept so [`Driver::remove_service`](crate::driver::Driver::remove_service)
154    /// can re-drive the existing [`Driver::remove_program`](crate::driver::Driver::remove_program)
155    /// path (which needs the raw PMT to build the `Update`/`NotSelected`
156    /// `ca_pmt`, EN 50221 §8.4.3.4 Table 25) without the caller re-supplying
157    /// it.
158    pub(crate) pmt_raw: Vec<u8>,
159}
160
161/// The [`Driver`](crate::Driver)'s owned CAS-layer state (#763 Layer 1) — one
162/// CI slot's active service set plus the entitlement re-query cadence.
163#[derive(Debug, Clone)]
164pub struct ManagedCa {
165    /// Active services, keyed by `program_number`.
166    services: BTreeMap<u16, ManagedService>,
167    /// Entitlement re-query cadence (Task 5); `Duration::ZERO` disables it.
168    requery_interval: Duration,
169    /// Elapsed time accumulated since the last re-query (Task 5's
170    /// [`tick`](Self::tick), mirroring `resource.rs`'s `DateTime::tick`
171    /// accumulate-then-fire pattern).
172    since: Duration,
173    /// The last `set_cat`'s (CAID, EMM PID) entries, one per `CA_descriptor` (a CAID may list several EMM PIDs; ISO/IEC 13818-1 §2.4.4.7's
174    /// `CA_descriptor`s, ISO/IEC 13818-1 §2.6.16). Kept even when it yields no
175    /// `emm_pids` (no `ca_info` seen yet) so a later `ca_info` can recompute
176    /// against it (#763 Task 4).
177    cat_emm_pids: Vec<(u16, Pid)>,
178    /// The last-observed `Notification::CaInfo` CAID set — the CAM's
179    /// advertised systems (#763 Task 4).
180    cam_caids: BTreeSet<u16>,
181    /// `cat_emm_pids` ∩ `cam_caids` — the EMM PIDs to route into `ci0`.
182    /// Recomputed on every [`set_cat`](Self::set_cat)/
183    /// [`set_cam_caids`](Self::set_cam_caids) call.
184    emm_pids: Vec<Pid>,
185    /// Union of active services' ES PIDs. Recomputed on every
186    /// [`record`](Self::record)/[`remove`](Self::remove) call.
187    descramble_pids: Vec<Pid>,
188    /// Union of active services' `ca_pids` (ECM PIDs, programme+ES combined).
189    /// Recomputed on every [`record`](Self::record)/[`remove`](Self::remove)
190    /// call, exactly like [`descramble_pids`](Self::descramble_pids).
191    ca_pids: Vec<Pid>,
192}
193
194impl Default for ManagedCa {
195    fn default() -> Self {
196        Self {
197            services: BTreeMap::new(),
198            requery_interval: REQUERY_DEFAULT,
199            since: Duration::ZERO,
200            cat_emm_pids: Vec::new(),
201            cam_caids: BTreeSet::new(),
202            emm_pids: Vec::new(),
203            descramble_pids: Vec::new(),
204            ca_pids: Vec::new(),
205        }
206    }
207}
208
209impl ManagedCa {
210    /// New, empty managed-CA state at the default re-query cadence
211    /// ([`REQUERY_DEFAULT`]).
212    #[must_use]
213    pub fn new() -> Self {
214        Self::default()
215    }
216
217    /// The currently-tracked services, keyed by `program_number`.
218    #[must_use]
219    pub fn services(&self) -> &BTreeMap<u16, ManagedService> {
220        &self.services
221    }
222
223    /// The re-query cadence currently configured (Task 5 consumes this).
224    #[must_use]
225    pub fn requery_interval(&self) -> Duration {
226        self.requery_interval
227    }
228
229    /// Set the entitlement re-query cadence
230    /// ([`Driver::set_requery_interval`](crate::driver::Driver::set_requery_interval)).
231    /// `Duration::ZERO` disables re-query. Resets the accumulated `since` so a
232    /// newly-set interval doesn't fire immediately off stale accumulation.
233    pub(crate) fn set_requery_interval(&mut self, interval: Duration) {
234        self.requery_interval = interval;
235        self.since = Duration::ZERO;
236    }
237
238    /// Whether no service is currently tracked — used to pick
239    /// `CaPmtListManagement::Only` (first-ever service) vs `Add` (joining an
240    /// already-active set) for the next `add_service`, mirroring
241    /// [`Driver::descramble_programs`](crate::driver::Driver::descramble_programs)/
242    /// [`Driver::add_program`](crate::driver::Driver::add_program)'s existing
243    /// multi-programme list-management convention (EN 50221 §8.4.3.4 Table 25).
244    #[must_use]
245    pub(crate) fn is_empty(&self) -> bool {
246        self.services.is_empty()
247    }
248
249    /// Record a service after its `ca_pmt` has been built and sent.
250    pub(crate) fn record(&mut self, program_number: u16, service: ManagedService) {
251        self.services.insert(program_number, service);
252        self.recompute_service_pids();
253    }
254
255    /// Stop tracking `program_number` (#763 Task 6's
256    /// [`Driver::remove_service`](crate::driver::Driver::remove_service)),
257    /// recomputing [`descramble_pids`](Self::descramble_pids)/[`ca_pids`](Self::ca_pids)
258    /// afterwards. Returns whether the programme was actually tracked
259    /// (`false` is a no-op — nothing to remove).
260    pub(crate) fn remove(&mut self, program_number: u16) -> bool {
261        let removed = self.services.remove(&program_number).is_some();
262        if removed {
263            self.recompute_service_pids();
264        }
265        removed
266    }
267
268    /// Clear all module-scoped managed state (#763 Task 6's CAM hot-plug
269    /// fix): the active service set, the CAT/CAM CAID-derived EMM-PID state,
270    /// and the descramble-PID union, plus the re-query accumulator (`since`)
271    /// so a freshly (re)inserted module doesn't inherit a departed module's
272    /// partially-elapsed re-query countdown. `requery_interval` is
273    /// deliberately **not** reset — it is host configuration
274    /// ([`set_requery_interval`](Self::set_requery_interval)), not
275    /// per-module state, and must survive a CAM insert/remove edge.
276    pub(crate) fn clear(&mut self) {
277        self.services.clear();
278        self.cat_emm_pids.clear();
279        self.cam_caids.clear();
280        self.emm_pids.clear();
281        self.descramble_pids.clear();
282        self.ca_pids.clear();
283        self.since = Duration::ZERO;
284    }
285
286    /// The EMM PIDs to route into `ci0`: the last `set_cat`'s list of
287    /// `(CAID, EMM PID)` entries (one per `CA_descriptor`; a CAID may have
288    /// several), intersected with the CAM's advertised CAIDs (last `ca_info`) — a
289    /// CAT entry for a CAID the CAM never advertised is never fed (#763 Task
290    /// 4).
291    #[must_use]
292    pub fn emm_pids(&self) -> &[Pid] {
293        &self.emm_pids
294    }
295
296    /// The union of every actively-managed service's elementary-stream PIDs
297    /// — the PIDs a caller must route into `ci0` for descrambling.
298    #[must_use]
299    pub fn descramble_pids(&self) -> &[Pid] {
300        &self.descramble_pids
301    }
302
303    /// The union of every actively-managed service's `CA_PID`s (ECM PIDs,
304    /// ISO/IEC 13818-1 §2.6.16 `CA_descriptor` `CA_PID`, programme + ES level
305    /// combined) — the control-word channel a caller must route into `ci0`
306    /// alongside [`descramble_pids`](Self::descramble_pids); without these
307    /// the module has ES to descramble but no control words to do it with.
308    #[must_use]
309    pub fn ca_pids(&self) -> &[Pid] {
310        &self.ca_pids
311    }
312
313    /// `descramble_pids ∪ ca_pids ∪ emm_pids ∪ PCR ∪ CAT` — every PID class a
314    /// caller must route into `ci0` for this slot to both descramble the
315    /// tracked services (ES + ECM), keep entitlements current (EMM), and
316    /// carry each active service's programme clock reference (PCR — ISO/IEC
317    /// 13818-1 §2.4.4.9). The PCR PID is folded in here rather than into
318    /// [`descramble_pids`](Self::descramble_pids) because a dedicated PCR PID
319    /// carries no elementary stream of its own; a service whose `pcr_pid` is
320    /// `0x1FFF` ("no PCR") contributes nothing. Computed on demand (small
321    /// sets); dedup + sorted.
322    ///
323    /// The CAT PID ([`CAT_PID`], 0x0001) is **always** included, even with no
324    /// services and no CAM. This is hardware-evidenced, not mandated by
325    /// EN 50221: on a Digital Devices CXD2099 with an entitled AlphaCrypt
326    /// One4All V2.5 (CAID 0x0650) decrypting ORF1 over 180 s runs, routing the
327    /// CAT plus only EMM PID 0x259 descrambled from about 55 s, while routing
328    /// all seven EMM PIDs without the CAT never descrambled (#1296).
329    #[must_use]
330    pub fn required_pids(&self) -> Vec<Pid> {
331        let mut pids: BTreeSet<Pid> = BTreeSet::new();
332        pids.extend(self.descramble_pids.iter().copied());
333        pids.extend(self.ca_pids.iter().copied());
334        pids.extend(self.emm_pids.iter().copied());
335        pids.insert(CAT_PID);
336        for service in self.services.values() {
337            if service.pcr_pid != PCR_PID_NONE {
338                pids.insert(service.pcr_pid);
339            }
340        }
341        pids.into_iter().collect()
342    }
343
344    /// Store the CAT's CAID → EMM-PID map (ISO/IEC 13818-1 §2.4.4.7's
345    /// `CA_descriptor`s, ISO/IEC 13818-1 §2.6.16) and recompute [`emm_pids`](Self::emm_pids).
346    /// Calling this before any `ca_info` is not an error: the map is kept so
347    /// a later [`set_cam_caids`](Self::set_cam_caids) recomputes against it.
348    pub(crate) fn set_cat(&mut self, entries: &[CatCaEntry]) {
349        self.cat_emm_pids = entries.iter().map(|e| (e.ca_system_id, e.ca_pid)).collect();
350        self.recompute_emm_pids();
351    }
352
353    /// Record the CAM's advertised CAID set (from `Notification::CaInfo`)
354    /// and recompute [`emm_pids`](Self::emm_pids).
355    pub(crate) fn set_cam_caids(&mut self, caids: BTreeSet<u16>) {
356        self.cam_caids = caids;
357        self.recompute_emm_pids();
358    }
359
360    /// The CAM's advertised CAID set (last `Notification::CaInfo`), for a
361    /// caller that must CAID-filter a `ca_pmt` before sending it (#1067) —
362    /// mirrors `CiStack`'s existing filter on the raw `descramble` path
363    /// (`dvb_ci::builder::build_ca_pmt_for_caids`, whose own doc cites: "a
364    /// CICAM rejects a `ca_pmt` carrying a `CA_descriptor` for a
365    /// `CA_system_id` it does not support, declining even the streams it
366    /// could descramble"). Empty means no `ca_info` has been observed yet —
367    /// the caller falls back to sending every `CA_descriptor` unfiltered,
368    /// same as `CiStack::build_ca_pmt_bytes`.
369    #[must_use]
370    pub(crate) fn cam_caids(&self) -> &BTreeSet<u16> {
371        &self.cam_caids
372    }
373
374    /// `emm_pids` = `cat_emm_pids` ∩ `cam_caids`, deduped and sorted by PID
375    /// (matching [`recompute_service_pids`](Self::recompute_service_pids)'s
376    /// convention) — two CAIDs the CAT maps to the *same* EMM PID must not
377    /// list that PID twice.
378    fn recompute_emm_pids(&mut self) {
379        let pids: BTreeSet<Pid> = self
380            .cat_emm_pids
381            .iter()
382            .filter(|(caid, _)| self.cam_caids.contains(caid))
383            .map(|(_, pid)| *pid)
384            .collect();
385        self.emm_pids = pids.into_iter().collect();
386    }
387
388    /// Advance the entitlement re-query cadence by `elapsed` — mirrors
389    /// `resource.rs`'s `DateTime::tick` accumulate-then-fire pattern:
390    /// accumulate `since`, and once it reaches `requery_interval`, reset it
391    /// and report that a re-query is due. Returns `false` (never fires) when
392    /// re-query is disabled (`requery_interval == Duration::ZERO`) or there
393    /// are no active services to re-query.
394    pub(crate) fn tick(&mut self, elapsed: Duration) -> bool {
395        if self.requery_interval.is_zero() || self.services.is_empty() {
396            return false;
397        }
398        self.since += elapsed;
399        if self.since >= self.requery_interval {
400            self.since = Duration::ZERO;
401            true
402        } else {
403            false
404        }
405    }
406
407    /// Diff an incoming `ca_pmt_reply`'s programme-level status (EN 50221
408    /// §8.4.3.5 Table 26) against the last-observed status for
409    /// `program_number` and report the edge-triggered transition (#763 Task
410    /// 5): `Some((v, descrambling_ok))` fires only when `ca_enable` is
411    /// `Some(v)` *and* `(ca_enable, descrambling_ok)` differs from what was
412    /// last observed for this programme — including the first-ever reply
413    /// (no prior observation) establishing the baseline and reporting it.
414    /// `ca_enable == None` (programme status withdrawn) never fires: there is
415    /// no per-programme status to report (the coarse withdrawal signal is
416    /// #726 `HotPlug`'s job). The last-observed status is updated
417    /// unconditionally, whether or not this call fires.
418    ///
419    /// No-op (`None`) if `program_number` names no actively-managed service
420    /// (never `add_service`'d, or already removed) — there is nothing to
421    /// diff against.
422    pub(crate) fn record_reply(
423        &mut self,
424        program_number: u16,
425        ca_enable: Option<CaEnable>,
426        descrambling_ok: bool,
427    ) -> Option<(CaEnable, bool)> {
428        let service = self.services.get_mut(&program_number)?;
429        let prev = (service.last_ca_enable, service.last_descrambling_ok);
430        service.last_ca_enable = ca_enable;
431        service.last_descrambling_ok = descrambling_ok;
432        match ca_enable {
433            Some(v) if prev != (ca_enable, descrambling_ok) => Some((v, descrambling_ok)),
434            _ => None,
435        }
436    }
437
438    /// `descramble_pids`/`ca_pids` = the union (dedup, sorted) of every
439    /// active service's `es_pids`/`ca_pids` respectively.
440    fn recompute_service_pids(&mut self) {
441        let mut descramble: BTreeSet<Pid> = BTreeSet::new();
442        let mut ca: BTreeSet<Pid> = BTreeSet::new();
443        for service in self.services.values() {
444            descramble.extend(service.es_pids.iter().copied());
445            ca.extend(service.ca_pids.iter().copied());
446        }
447        self.descramble_pids = descramble.into_iter().collect();
448        self.ca_pids = ca.into_iter().collect();
449    }
450}
451
452/// `true` if `loop_` carries at least one `CA_descriptor` (ISO/IEC 13818-1
453/// §2.6.16, tag `0x09`).
454fn has_ca_descriptor(loop_: &DescriptorLoop<'_>) -> bool {
455    loop_.raw_tags().any(|(tag, _)| tag == CA_DESCRIPTOR_TAG)
456}
457
458/// Collect the `CA_PID`s from every `CA_descriptor` in `loop_`.
459fn ca_pids_in(loop_: &DescriptorLoop<'_>) -> Vec<Pid> {
460    loop_
461        .raw_tags()
462        .filter(|(tag, _)| *tag == CA_DESCRIPTOR_TAG)
463        .filter_map(|(_, body)| CaDescriptor::from_body(body).ok())
464        .map(|ca| ca.ca_pid)
465        .collect()
466}
467
468/// Whether `pmt` carries a `CA_descriptor` at programme or any ES level (ISO/IEC
469/// 13818-1 §2.6.16) — used to reject a CA-free PMT before building a useless
470/// `ca_pmt`.
471pub(crate) fn pmt_has_ca(pmt: &PmtSection<'_>) -> bool {
472    has_ca_descriptor(&pmt.program_info)
473        || pmt.streams.iter().any(|s| has_ca_descriptor(&s.es_info))
474}
475
476/// The owned [`ManagedService`] state to record for `pmt`, sent with `cmd`;
477/// `built_ca_pmt` is the exact `ok_descrambling` bytes sent (kept for the
478/// add_service oracle test). `pmt_raw` is kept so a later re-query
479/// (`Driver::requery_tick`, #765) can rebuild a fresh `query`-variant
480/// `ca_pmt` against the *current* active set rather than freezing
481/// `list_management` at this moment.
482pub(crate) fn service_of(
483    pmt: &PmtSection<'_>,
484    cmd: CaPmtCmdId,
485    built_ca_pmt: Vec<u8>,
486    pmt_raw: Vec<u8>,
487) -> ManagedService {
488    let mut ca_pids = ca_pids_in(&pmt.program_info);
489    for s in &pmt.streams {
490        ca_pids.extend(ca_pids_in(&s.es_info));
491    }
492    ManagedService {
493        es_pids: pmt.streams.iter().map(|s| s.elementary_pid).collect(),
494        ca_pids,
495        pcr_pid: pmt.pcr_pid,
496        cmd,
497        last_ca_enable: None,
498        last_descrambling_ok: false,
499        built_ca_pmt,
500        pmt_raw,
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn new_managed_ca_is_empty_at_default_cadence() {
510        let m = ManagedCa::new();
511        assert!(m.is_empty());
512        assert!(m.services().is_empty());
513        assert_eq!(m.requery_interval(), REQUERY_DEFAULT);
514    }
515
516    #[test]
517    fn required_pids_always_includes_the_cat_pid() {
518        let m = ManagedCa::new();
519        assert_eq!(m.required_pids(), vec![CAT_PID]);
520    }
521
522    #[test]
523    fn set_cat_keeps_every_emm_pid_of_a_shared_caid() {
524        let entry = |caid, pid| CatCaEntry {
525            ca_system_id: caid,
526            ca_pid: Pid::from_wire_masked(pid),
527            private_data: Vec::new(),
528        };
529        let mut m = ManagedCa::new();
530        m.set_cam_caids(BTreeSet::from([0x0650]));
531        m.set_cat(&[
532            entry(0x0650, 0x0258),
533            entry(0x0650, 0x0259),
534            entry(0x0650, 0x025A),
535            entry(0x0100, 0x0300), // CAID the CAM never advertised
536            entry(0x0650, 0x033E),
537            entry(0x0100, 0x033E), // duplicated PID under two CAIDs
538        ]);
539        assert_eq!(
540            m.emm_pids(),
541            &[
542                Pid::from_const(0x0258),
543                Pid::from_const(0x0259),
544                Pid::from_const(0x025A),
545                Pid::from_const(0x033E)
546            ]
547        );
548    }
549
550    fn ca_pid_of(body: &[u8]) -> Option<Pid> {
551        CaDescriptor::from_body(body).ok().map(|ca| ca.ca_pid)
552    }
553
554    #[test]
555    fn ca_pid_of_reads_the_upper_byte_of_the_masked_field() {
556        // CA_descriptor body: CA_system_id (2 bytes), then the
557        // reserved(3)/CA_PID(13) field, whose top three bits are set on the
558        // wire and masked off (ISO/IEC 13818-1 §2.6.16).
559        assert_eq!(
560            ca_pid_of(&[0x06, 0x04, 0xE1, 0x23]),
561            Some(Pid::from_const(0x0123))
562        );
563        assert_eq!(
564            ca_pid_of(&[0x06, 0x04, 0xFF, 0xFF]),
565            Some(Pid::from_const(0x1FFF)),
566            "the three reserved bits are masked off, not read as PID bits"
567        );
568        assert_eq!(
569            ca_pid_of(&[0x06, 0x04]),
570            None,
571            "a body too short for the CA_PID field carries no PID"
572        );
573    }
574
575    #[test]
576    fn record_tracks_the_service() {
577        let mut m = ManagedCa::new();
578        let svc = ManagedService {
579            es_pids: vec![Pid::from_const(0x100), Pid::from_const(0x101)],
580            ca_pids: vec![Pid::from_const(0x0064)],
581            pcr_pid: PCR_PID_NONE,
582            cmd: CaPmtCmdId::OkDescrambling,
583            last_ca_enable: None,
584            last_descrambling_ok: false,
585            built_ca_pmt: vec![0xAA, 0xBB],
586            pmt_raw: vec![0x02, 0x00],
587        };
588        m.record(7, svc.clone());
589        assert!(!m.is_empty());
590        assert_eq!(m.services().get(&7), Some(&svc));
591    }
592
593    #[test]
594    fn ca_error_no_ca_descriptor_displays_program_number() {
595        let e = CaError::NoCaDescriptor { program_number: 42 };
596        assert!(e.to_string().contains("42"));
597    }
598
599    // --- #763 Task 5 ---
600
601    #[test]
602    fn set_requery_interval_updates_and_resets_accumulator() {
603        let mut m = ManagedCa::new();
604        assert_eq!(m.requery_interval(), REQUERY_DEFAULT);
605        m.set_requery_interval(Duration::from_secs(3));
606        assert_eq!(m.requery_interval(), Duration::from_secs(3));
607    }
608
609    #[test]
610    fn tick_fires_once_interval_elapses_and_resets() {
611        let mut m = ManagedCa::new();
612        m.set_requery_interval(Duration::from_secs(5));
613        m.record(
614            1,
615            ManagedService {
616                es_pids: vec![Pid::from_const(0x100)],
617                ca_pids: vec![Pid::from_const(0x64)],
618                pcr_pid: PCR_PID_NONE,
619                cmd: CaPmtCmdId::OkDescrambling,
620                last_ca_enable: None,
621                last_descrambling_ok: false,
622                built_ca_pmt: vec![],
623                pmt_raw: vec![],
624            },
625        );
626        assert!(
627            !m.tick(Duration::from_secs(3)),
628            "before the interval: no fire"
629        );
630        assert!(
631            m.tick(Duration::from_secs(3)),
632            "crossing the interval: fires"
633        );
634        assert!(!m.tick(Duration::from_secs(1)), "since resets after firing");
635    }
636
637    #[test]
638    fn tick_disabled_at_zero_interval_never_fires() {
639        let mut m = ManagedCa::new();
640        m.set_requery_interval(Duration::ZERO);
641        m.record(
642            1,
643            ManagedService {
644                es_pids: vec![Pid::from_const(0x100)],
645                ca_pids: vec![Pid::from_const(0x64)],
646                pcr_pid: PCR_PID_NONE,
647                cmd: CaPmtCmdId::OkDescrambling,
648                last_ca_enable: None,
649                last_descrambling_ok: false,
650                built_ca_pmt: vec![],
651                pmt_raw: vec![],
652            },
653        );
654        assert!(!m.tick(Duration::from_secs(1000)));
655    }
656
657    #[test]
658    fn tick_with_no_active_services_never_fires() {
659        let mut m = ManagedCa::new();
660        m.set_requery_interval(Duration::from_secs(1));
661        assert!(!m.tick(Duration::from_secs(1000)));
662    }
663
664    #[test]
665    fn record_reply_first_ever_some_establishes_baseline_and_reports() {
666        let mut m = ManagedCa::new();
667        m.record(
668            1,
669            ManagedService {
670                es_pids: vec![Pid::from_const(0x100)],
671                ca_pids: vec![Pid::from_const(0x64)],
672                pcr_pid: PCR_PID_NONE,
673                cmd: CaPmtCmdId::OkDescrambling,
674                last_ca_enable: None,
675                last_descrambling_ok: false,
676                built_ca_pmt: vec![],
677                pmt_raw: vec![],
678            },
679        );
680        let out = m.record_reply(1, Some(CaEnable::NotPossibleNoEntitlement), false);
681        assert_eq!(out, Some((CaEnable::NotPossibleNoEntitlement, false)));
682    }
683
684    #[test]
685    fn record_reply_unchanged_status_does_not_re_fire() {
686        let mut m = ManagedCa::new();
687        m.record(
688            1,
689            ManagedService {
690                es_pids: vec![Pid::from_const(0x100)],
691                ca_pids: vec![Pid::from_const(0x64)],
692                pcr_pid: PCR_PID_NONE,
693                cmd: CaPmtCmdId::OkDescrambling,
694                last_ca_enable: None,
695                last_descrambling_ok: false,
696                built_ca_pmt: vec![],
697                pmt_raw: vec![],
698            },
699        );
700        assert!(m.record_reply(1, Some(CaEnable::Possible), true).is_some());
701        assert_eq!(m.record_reply(1, Some(CaEnable::Possible), true), None);
702    }
703
704    #[test]
705    fn record_reply_none_never_fires_but_updates_last() {
706        let mut m = ManagedCa::new();
707        m.record(
708            1,
709            ManagedService {
710                es_pids: vec![Pid::from_const(0x100)],
711                ca_pids: vec![Pid::from_const(0x64)],
712                pcr_pid: PCR_PID_NONE,
713                cmd: CaPmtCmdId::OkDescrambling,
714                last_ca_enable: None,
715                last_descrambling_ok: false,
716                built_ca_pmt: vec![],
717                pmt_raw: vec![],
718            },
719        );
720        assert!(m.record_reply(1, Some(CaEnable::Possible), true).is_some());
721        // Withdrawn: None never fires.
722        assert_eq!(m.record_reply(1, None, false), None);
723        // Re-affirmed with the SAME value as before the withdrawal: fires
724        // again, because `last` was overwritten to `None` in between.
725        assert_eq!(
726            m.record_reply(1, Some(CaEnable::Possible), true),
727            Some((CaEnable::Possible, true))
728        );
729    }
730
731    #[test]
732    fn record_reply_unknown_program_is_a_no_op() {
733        let mut m = ManagedCa::new();
734        assert_eq!(m.record_reply(99, Some(CaEnable::Possible), true), None);
735    }
736
737    // --- #763 Task 6: remove + clear ---
738
739    #[test]
740    fn remove_drops_tracked_service_and_recomputes_descramble_pids_false_for_untracked() {
741        let mut m = ManagedCa::new();
742        m.record(
743            1,
744            ManagedService {
745                es_pids: vec![Pid::from_const(0x100), Pid::from_const(0x101)],
746                ca_pids: vec![Pid::from_const(0x64)],
747                pcr_pid: PCR_PID_NONE,
748                cmd: CaPmtCmdId::OkDescrambling,
749                last_ca_enable: None,
750                last_descrambling_ok: false,
751                built_ca_pmt: vec![],
752                pmt_raw: vec![],
753            },
754        );
755        m.record(
756            2,
757            ManagedService {
758                es_pids: vec![Pid::from_const(0x200)],
759                ca_pids: vec![Pid::from_const(0x65)],
760                pcr_pid: PCR_PID_NONE,
761                cmd: CaPmtCmdId::OkDescrambling,
762                last_ca_enable: None,
763                last_descrambling_ok: false,
764                built_ca_pmt: vec![],
765                pmt_raw: vec![],
766            },
767        );
768
769        assert!(
770            !m.remove(99),
771            "removing an untracked program_number must return false"
772        );
773        assert_eq!(
774            m.services().len(),
775            2,
776            "an untracked remove must not disturb the tracked set"
777        );
778
779        assert!(
780            m.remove(1),
781            "removing a tracked program_number must return true"
782        );
783        assert!(m.services().get(&1).is_none());
784        assert_eq!(
785            m.descramble_pids(),
786            &[Pid::from_const(0x200)],
787            "descramble_pids must recompute (drop program 1's PIDs) after remove"
788        );
789    }
790
791    #[test]
792    fn clear_resets_module_state_but_preserves_requery_interval() {
793        use dvb_si::tables::cat::CatCaEntry;
794
795        let mut m = ManagedCa::new();
796        m.set_requery_interval(Duration::from_secs(3));
797        m.record(
798            1,
799            ManagedService {
800                es_pids: vec![Pid::from_const(0x100)],
801                ca_pids: vec![Pid::from_const(0x64)],
802                pcr_pid: PCR_PID_NONE,
803                cmd: CaPmtCmdId::OkDescrambling,
804                last_ca_enable: None,
805                last_descrambling_ok: false,
806                built_ca_pmt: vec![],
807                pmt_raw: vec![],
808            },
809        );
810        m.set_cat(&[CatCaEntry {
811            ca_system_id: 0x0648,
812            ca_pid: Pid::from_const(0x1FF0),
813            private_data: Vec::new(),
814        }]);
815        m.set_cam_caids([0x0648].into_iter().collect());
816        assert!(!m.emm_pids().is_empty(), "precondition: emm_pids populated");
817        assert!(
818            !m.descramble_pids().is_empty(),
819            "precondition: descramble_pids populated"
820        );
821
822        m.clear();
823
824        assert!(m.services().is_empty(), "services must be cleared");
825        assert!(m.emm_pids().is_empty(), "emm_pids must be cleared");
826        assert!(
827            m.descramble_pids().is_empty(),
828            "descramble_pids must be cleared"
829        );
830        assert!(m.ca_pids().is_empty(), "ca_pids must be cleared");
831        assert_eq!(
832            m.requery_interval(),
833            Duration::from_secs(3),
834            "requery_interval is host config, must survive clear()"
835        );
836    }
837
838    // --- #763 Task 7: ca_pids()/required_pids() ---
839
840    #[test]
841    fn ca_pids_is_the_dedup_sorted_union_of_active_services_and_required_pids_unions_all_three() {
842        use dvb_si::tables::cat::CatCaEntry;
843
844        let mut m = ManagedCa::new();
845        m.record(
846            1,
847            ManagedService {
848                es_pids: vec![Pid::from_const(0x0100), Pid::from_const(0x0101)],
849                ca_pids: vec![Pid::from_const(0x0064), Pid::from_const(0x0065)],
850                pcr_pid: PCR_PID_NONE,
851                cmd: CaPmtCmdId::OkDescrambling,
852                last_ca_enable: None,
853                last_descrambling_ok: false,
854                built_ca_pmt: vec![],
855                pmt_raw: vec![],
856            },
857        );
858        m.record(
859            2,
860            ManagedService {
861                es_pids: vec![Pid::from_const(0x0200)],
862                // Shares 0x0065 with program 1 to prove dedup, plus a
863                // distinct 0x0066.
864                ca_pids: vec![Pid::from_const(0x0065), Pid::from_const(0x0066)],
865                pcr_pid: PCR_PID_NONE,
866                cmd: CaPmtCmdId::OkDescrambling,
867                last_ca_enable: None,
868                last_descrambling_ok: false,
869                built_ca_pmt: vec![],
870                pmt_raw: vec![],
871            },
872        );
873
874        assert_eq!(
875            m.ca_pids(),
876            &[
877                Pid::from_const(0x0064),
878                Pid::from_const(0x0065),
879                Pid::from_const(0x0066)
880            ],
881            "ca_pids must be the dedup+sorted union of both services' ca_pids"
882        );
883
884        // Populate emm_pids too (CAT ∩ ca_info CAIDs), so required_pids
885        // exercises all three classes.
886        m.set_cat(&[CatCaEntry {
887            ca_system_id: 0x0648,
888            ca_pid: Pid::from_const(0x1FF0),
889            private_data: Vec::new(),
890        }]);
891        m.set_cam_caids([0x0648].into_iter().collect());
892        assert_eq!(
893            m.emm_pids(),
894            &[Pid::from_const(0x1FF0)],
895            "precondition: emm_pids populated"
896        );
897
898        assert_eq!(
899            m.required_pids(),
900            vec![
901                CAT_PID,
902                Pid::from_const(0x0064),
903                Pid::from_const(0x0065),
904                Pid::from_const(0x0066),
905                Pid::from_const(0x0100),
906                Pid::from_const(0x0101),
907                Pid::from_const(0x0200),
908                Pid::from_const(0x1FF0)
909            ],
910            "required_pids must be CAT ∪ descramble_pids ∪ ca_pids ∪ emm_pids"
911        );
912    }
913
914    // --- #763 final-review Fix 1: dedicated PCR PID routing ---
915
916    #[test]
917    fn service_of_captures_pcr_pid_and_required_pids_includes_dedicated_pcr() {
918        use broadcast_core::Parse;
919        use dvb_si::tables::pmt::PmtSection;
920
921        // A PMT whose PCR is carried on its own dedicated PID (0x00FF),
922        // distinct from every ES PID (0x0100/0x0101) and CA PID (0x0064/
923        // 0x0065) — a legitimate DVB config `service_of` must not lose.
924        let pmt_bytes = crate::driver::tests::build_ca_pmt_fixture_dedicated_pcr(1550);
925        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
926        assert_eq!(
927            pmt.pcr_pid,
928            Pid::from_const(0x00FF),
929            "fixture precondition: dedicated PCR PID outside the ES/CA set"
930        );
931
932        let svc = service_of(&pmt, CaPmtCmdId::OkDescrambling, vec![], vec![]);
933        assert_eq!(
934            svc.pcr_pid,
935            Pid::from_const(0x00FF),
936            "service_of must capture pmt.pcr_pid"
937        );
938        assert_eq!(
939            svc.es_pids,
940            vec![Pid::from_const(0x0100), Pid::from_const(0x0101)]
941        );
942        assert_eq!(
943            svc.ca_pids,
944            vec![Pid::from_const(0x0064), Pid::from_const(0x0065)]
945        );
946
947        let mut m = ManagedCa::new();
948        m.record(1550, svc);
949
950        // Bite: without folding pcr_pid into required_pids, this PID is
951        // absent (it's neither an ES nor a CA nor an EMM PID) and the
952        // dedicated PCR clock reference never reaches ci0.
953        assert!(
954            m.required_pids().contains(&Pid::from_const(0x00FF)),
955            "required_pids must include the service's dedicated PCR PID, got {:?}",
956            m.required_pids()
957        );
958    }
959
960    #[test]
961    fn required_pids_excludes_pcr_pid_none() {
962        let mut m = ManagedCa::new();
963        m.record(
964            1,
965            ManagedService {
966                es_pids: vec![Pid::from_const(0x0100)],
967                ca_pids: vec![Pid::from_const(0x0064)],
968                // PCR_PID_NONE (0x1FFF, ISO/IEC 13818-1 §2.4.4.9) — this
969                // programme carries no PCR of its own.
970                pcr_pid: PCR_PID_NONE,
971                cmd: CaPmtCmdId::OkDescrambling,
972                last_ca_enable: None,
973                last_descrambling_ok: false,
974                built_ca_pmt: vec![],
975                pmt_raw: vec![],
976            },
977        );
978        assert_eq!(
979            m.required_pids(),
980            vec![CAT_PID, Pid::from_const(0x0064), Pid::from_const(0x0100)],
981            "PCR_PID_NONE (0x1FFF) must never be added to required_pids"
982        );
983    }
984
985    #[test]
986    fn required_pids_pcr_pid_matching_an_es_pid_adds_no_spurious_pid() {
987        let mut m = ManagedCa::new();
988        m.record(
989            1,
990            ManagedService {
991                es_pids: vec![Pid::from_const(0x0100)],
992                ca_pids: vec![Pid::from_const(0x0064)],
993                // PCR piggybacked on the ES PID (the common case, already
994                // covered by every other fixture in this file) — must not
995                // produce a duplicate/spurious entry.
996                pcr_pid: Pid::from_const(0x0100),
997                cmd: CaPmtCmdId::OkDescrambling,
998                last_ca_enable: None,
999                last_descrambling_ok: false,
1000                built_ca_pmt: vec![],
1001                pmt_raw: vec![],
1002            },
1003        );
1004        assert_eq!(
1005            m.required_pids(),
1006            vec![CAT_PID, Pid::from_const(0x0064), Pid::from_const(0x0100)],
1007            "a pcr_pid coinciding with an ES PID must not duplicate/add a spurious entry"
1008        );
1009    }
1010}