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