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 record_tracks_the_service() {
567        let mut m = ManagedCa::new();
568        let svc = ManagedService {
569            es_pids: vec![Pid::from_const(0x100), Pid::from_const(0x101)],
570            ca_pids: vec![Pid::from_const(0x0064)],
571            pcr_pid: PCR_PID_NONE,
572            cmd: CaPmtCmdId::OkDescrambling,
573            last_ca_enable: None,
574            last_descrambling_ok: false,
575            built_ca_pmt: vec![0xAA, 0xBB],
576            pmt_raw: vec![0x02, 0x00],
577        };
578        m.record(7, svc.clone());
579        assert!(!m.is_empty());
580        assert_eq!(m.services().get(&7), Some(&svc));
581    }
582
583    #[test]
584    fn ca_error_no_ca_descriptor_displays_program_number() {
585        let e = CaError::NoCaDescriptor { program_number: 42 };
586        assert!(e.to_string().contains("42"));
587    }
588
589    // --- #763 Task 5 ---
590
591    #[test]
592    fn set_requery_interval_updates_and_resets_accumulator() {
593        let mut m = ManagedCa::new();
594        assert_eq!(m.requery_interval(), REQUERY_DEFAULT);
595        m.set_requery_interval(Duration::from_secs(3));
596        assert_eq!(m.requery_interval(), Duration::from_secs(3));
597    }
598
599    #[test]
600    fn tick_fires_once_interval_elapses_and_resets() {
601        let mut m = ManagedCa::new();
602        m.set_requery_interval(Duration::from_secs(5));
603        m.record(
604            1,
605            ManagedService {
606                es_pids: vec![Pid::from_const(0x100)],
607                ca_pids: vec![Pid::from_const(0x64)],
608                pcr_pid: PCR_PID_NONE,
609                cmd: CaPmtCmdId::OkDescrambling,
610                last_ca_enable: None,
611                last_descrambling_ok: false,
612                built_ca_pmt: vec![],
613                pmt_raw: vec![],
614            },
615        );
616        assert!(
617            !m.tick(Duration::from_secs(3)),
618            "before the interval: no fire"
619        );
620        assert!(
621            m.tick(Duration::from_secs(3)),
622            "crossing the interval: fires"
623        );
624        assert!(!m.tick(Duration::from_secs(1)), "since resets after firing");
625    }
626
627    #[test]
628    fn tick_disabled_at_zero_interval_never_fires() {
629        let mut m = ManagedCa::new();
630        m.set_requery_interval(Duration::ZERO);
631        m.record(
632            1,
633            ManagedService {
634                es_pids: vec![Pid::from_const(0x100)],
635                ca_pids: vec![Pid::from_const(0x64)],
636                pcr_pid: PCR_PID_NONE,
637                cmd: CaPmtCmdId::OkDescrambling,
638                last_ca_enable: None,
639                last_descrambling_ok: false,
640                built_ca_pmt: vec![],
641                pmt_raw: vec![],
642            },
643        );
644        assert!(!m.tick(Duration::from_secs(1000)));
645    }
646
647    #[test]
648    fn tick_with_no_active_services_never_fires() {
649        let mut m = ManagedCa::new();
650        m.set_requery_interval(Duration::from_secs(1));
651        assert!(!m.tick(Duration::from_secs(1000)));
652    }
653
654    #[test]
655    fn record_reply_first_ever_some_establishes_baseline_and_reports() {
656        let mut m = ManagedCa::new();
657        m.record(
658            1,
659            ManagedService {
660                es_pids: vec![Pid::from_const(0x100)],
661                ca_pids: vec![Pid::from_const(0x64)],
662                pcr_pid: PCR_PID_NONE,
663                cmd: CaPmtCmdId::OkDescrambling,
664                last_ca_enable: None,
665                last_descrambling_ok: false,
666                built_ca_pmt: vec![],
667                pmt_raw: vec![],
668            },
669        );
670        let out = m.record_reply(1, Some(CaEnable::NotPossibleNoEntitlement), false);
671        assert_eq!(out, Some((CaEnable::NotPossibleNoEntitlement, false)));
672    }
673
674    #[test]
675    fn record_reply_unchanged_status_does_not_re_fire() {
676        let mut m = ManagedCa::new();
677        m.record(
678            1,
679            ManagedService {
680                es_pids: vec![Pid::from_const(0x100)],
681                ca_pids: vec![Pid::from_const(0x64)],
682                pcr_pid: PCR_PID_NONE,
683                cmd: CaPmtCmdId::OkDescrambling,
684                last_ca_enable: None,
685                last_descrambling_ok: false,
686                built_ca_pmt: vec![],
687                pmt_raw: vec![],
688            },
689        );
690        assert!(m.record_reply(1, Some(CaEnable::Possible), true).is_some());
691        assert_eq!(m.record_reply(1, Some(CaEnable::Possible), true), None);
692    }
693
694    #[test]
695    fn record_reply_none_never_fires_but_updates_last() {
696        let mut m = ManagedCa::new();
697        m.record(
698            1,
699            ManagedService {
700                es_pids: vec![Pid::from_const(0x100)],
701                ca_pids: vec![Pid::from_const(0x64)],
702                pcr_pid: PCR_PID_NONE,
703                cmd: CaPmtCmdId::OkDescrambling,
704                last_ca_enable: None,
705                last_descrambling_ok: false,
706                built_ca_pmt: vec![],
707                pmt_raw: vec![],
708            },
709        );
710        assert!(m.record_reply(1, Some(CaEnable::Possible), true).is_some());
711        // Withdrawn: None never fires.
712        assert_eq!(m.record_reply(1, None, false), None);
713        // Re-affirmed with the SAME value as before the withdrawal: fires
714        // again, because `last` was overwritten to `None` in between.
715        assert_eq!(
716            m.record_reply(1, Some(CaEnable::Possible), true),
717            Some((CaEnable::Possible, true))
718        );
719    }
720
721    #[test]
722    fn record_reply_unknown_program_is_a_no_op() {
723        let mut m = ManagedCa::new();
724        assert_eq!(m.record_reply(99, Some(CaEnable::Possible), true), None);
725    }
726
727    // --- #763 Task 6: remove + clear ---
728
729    #[test]
730    fn remove_drops_tracked_service_and_recomputes_descramble_pids_false_for_untracked() {
731        let mut m = ManagedCa::new();
732        m.record(
733            1,
734            ManagedService {
735                es_pids: vec![Pid::from_const(0x100), Pid::from_const(0x101)],
736                ca_pids: vec![Pid::from_const(0x64)],
737                pcr_pid: PCR_PID_NONE,
738                cmd: CaPmtCmdId::OkDescrambling,
739                last_ca_enable: None,
740                last_descrambling_ok: false,
741                built_ca_pmt: vec![],
742                pmt_raw: vec![],
743            },
744        );
745        m.record(
746            2,
747            ManagedService {
748                es_pids: vec![Pid::from_const(0x200)],
749                ca_pids: vec![Pid::from_const(0x65)],
750                pcr_pid: PCR_PID_NONE,
751                cmd: CaPmtCmdId::OkDescrambling,
752                last_ca_enable: None,
753                last_descrambling_ok: false,
754                built_ca_pmt: vec![],
755                pmt_raw: vec![],
756            },
757        );
758
759        assert!(
760            !m.remove(99),
761            "removing an untracked program_number must return false"
762        );
763        assert_eq!(
764            m.services().len(),
765            2,
766            "an untracked remove must not disturb the tracked set"
767        );
768
769        assert!(
770            m.remove(1),
771            "removing a tracked program_number must return true"
772        );
773        assert!(m.services().get(&1).is_none());
774        assert_eq!(
775            m.descramble_pids(),
776            &[Pid::from_const(0x200)],
777            "descramble_pids must recompute (drop program 1's PIDs) after remove"
778        );
779    }
780
781    #[test]
782    fn clear_resets_module_state_but_preserves_requery_interval() {
783        use dvb_si::tables::cat::CatCaEntry;
784
785        let mut m = ManagedCa::new();
786        m.set_requery_interval(Duration::from_secs(3));
787        m.record(
788            1,
789            ManagedService {
790                es_pids: vec![Pid::from_const(0x100)],
791                ca_pids: vec![Pid::from_const(0x64)],
792                pcr_pid: PCR_PID_NONE,
793                cmd: CaPmtCmdId::OkDescrambling,
794                last_ca_enable: None,
795                last_descrambling_ok: false,
796                built_ca_pmt: vec![],
797                pmt_raw: vec![],
798            },
799        );
800        m.set_cat(&[CatCaEntry {
801            ca_system_id: 0x0648,
802            ca_pid: Pid::from_const(0x1FF0),
803            private_data: Vec::new(),
804        }]);
805        m.set_cam_caids([0x0648].into_iter().collect());
806        assert!(!m.emm_pids().is_empty(), "precondition: emm_pids populated");
807        assert!(
808            !m.descramble_pids().is_empty(),
809            "precondition: descramble_pids populated"
810        );
811
812        m.clear();
813
814        assert!(m.services().is_empty(), "services must be cleared");
815        assert!(m.emm_pids().is_empty(), "emm_pids must be cleared");
816        assert!(
817            m.descramble_pids().is_empty(),
818            "descramble_pids must be cleared"
819        );
820        assert!(m.ca_pids().is_empty(), "ca_pids must be cleared");
821        assert_eq!(
822            m.requery_interval(),
823            Duration::from_secs(3),
824            "requery_interval is host config, must survive clear()"
825        );
826    }
827
828    // --- #763 Task 7: ca_pids()/required_pids() ---
829
830    #[test]
831    fn ca_pids_is_the_dedup_sorted_union_of_active_services_and_required_pids_unions_all_three() {
832        use dvb_si::tables::cat::CatCaEntry;
833
834        let mut m = ManagedCa::new();
835        m.record(
836            1,
837            ManagedService {
838                es_pids: vec![Pid::from_const(0x0100), Pid::from_const(0x0101)],
839                ca_pids: vec![Pid::from_const(0x0064), Pid::from_const(0x0065)],
840                pcr_pid: PCR_PID_NONE,
841                cmd: CaPmtCmdId::OkDescrambling,
842                last_ca_enable: None,
843                last_descrambling_ok: false,
844                built_ca_pmt: vec![],
845                pmt_raw: vec![],
846            },
847        );
848        m.record(
849            2,
850            ManagedService {
851                es_pids: vec![Pid::from_const(0x0200)],
852                // Shares 0x0065 with program 1 to prove dedup, plus a
853                // distinct 0x0066.
854                ca_pids: vec![Pid::from_const(0x0065), Pid::from_const(0x0066)],
855                pcr_pid: PCR_PID_NONE,
856                cmd: CaPmtCmdId::OkDescrambling,
857                last_ca_enable: None,
858                last_descrambling_ok: false,
859                built_ca_pmt: vec![],
860                pmt_raw: vec![],
861            },
862        );
863
864        assert_eq!(
865            m.ca_pids(),
866            &[
867                Pid::from_const(0x0064),
868                Pid::from_const(0x0065),
869                Pid::from_const(0x0066)
870            ],
871            "ca_pids must be the dedup+sorted union of both services' ca_pids"
872        );
873
874        // Populate emm_pids too (CAT ∩ ca_info CAIDs), so required_pids
875        // exercises all three classes.
876        m.set_cat(&[CatCaEntry {
877            ca_system_id: 0x0648,
878            ca_pid: Pid::from_const(0x1FF0),
879            private_data: Vec::new(),
880        }]);
881        m.set_cam_caids([0x0648].into_iter().collect());
882        assert_eq!(
883            m.emm_pids(),
884            &[Pid::from_const(0x1FF0)],
885            "precondition: emm_pids populated"
886        );
887
888        assert_eq!(
889            m.required_pids(),
890            vec![
891                CAT_PID,
892                Pid::from_const(0x0064),
893                Pid::from_const(0x0065),
894                Pid::from_const(0x0066),
895                Pid::from_const(0x0100),
896                Pid::from_const(0x0101),
897                Pid::from_const(0x0200),
898                Pid::from_const(0x1FF0)
899            ],
900            "required_pids must be CAT ∪ descramble_pids ∪ ca_pids ∪ emm_pids"
901        );
902    }
903
904    // --- #763 final-review Fix 1: dedicated PCR PID routing ---
905
906    #[test]
907    fn service_of_captures_pcr_pid_and_required_pids_includes_dedicated_pcr() {
908        use broadcast_common::Parse;
909        use dvb_si::tables::pmt::PmtSection;
910
911        // A PMT whose PCR is carried on its own dedicated PID (0x00FF),
912        // distinct from every ES PID (0x0100/0x0101) and CA PID (0x0064/
913        // 0x0065) — a legitimate DVB config `service_of` must not lose.
914        let pmt_bytes = crate::driver::tests::build_ca_pmt_fixture_dedicated_pcr(1550);
915        let pmt = PmtSection::parse(&pmt_bytes).unwrap();
916        assert_eq!(
917            pmt.pcr_pid,
918            Pid::from_const(0x00FF),
919            "fixture precondition: dedicated PCR PID outside the ES/CA set"
920        );
921
922        let svc = service_of(&pmt, CaPmtCmdId::OkDescrambling, vec![], vec![]);
923        assert_eq!(
924            svc.pcr_pid,
925            Pid::from_const(0x00FF),
926            "service_of must capture pmt.pcr_pid"
927        );
928        assert_eq!(
929            svc.es_pids,
930            vec![Pid::from_const(0x0100), Pid::from_const(0x0101)]
931        );
932        assert_eq!(
933            svc.ca_pids,
934            vec![Pid::from_const(0x0064), Pid::from_const(0x0065)]
935        );
936
937        let mut m = ManagedCa::new();
938        m.record(1550, svc);
939
940        // Bite: without folding pcr_pid into required_pids, this PID is
941        // absent (it's neither an ES nor a CA nor an EMM PID) and the
942        // dedicated PCR clock reference never reaches ci0.
943        assert!(
944            m.required_pids().contains(&Pid::from_const(0x00FF)),
945            "required_pids must include the service's dedicated PCR PID, got {:?}",
946            m.required_pids()
947        );
948    }
949
950    #[test]
951    fn required_pids_excludes_pcr_pid_none() {
952        let mut m = ManagedCa::new();
953        m.record(
954            1,
955            ManagedService {
956                es_pids: vec![Pid::from_const(0x0100)],
957                ca_pids: vec![Pid::from_const(0x0064)],
958                // PCR_PID_NONE (0x1FFF, ISO/IEC 13818-1 §2.4.4.9) — this
959                // programme carries no PCR of its own.
960                pcr_pid: PCR_PID_NONE,
961                cmd: CaPmtCmdId::OkDescrambling,
962                last_ca_enable: None,
963                last_descrambling_ok: false,
964                built_ca_pmt: vec![],
965                pmt_raw: vec![],
966            },
967        );
968        assert_eq!(
969            m.required_pids(),
970            vec![CAT_PID, Pid::from_const(0x0064), Pid::from_const(0x0100)],
971            "PCR_PID_NONE (0x1FFF) must never be added to required_pids"
972        );
973    }
974
975    #[test]
976    fn required_pids_pcr_pid_matching_an_es_pid_adds_no_spurious_pid() {
977        let mut m = ManagedCa::new();
978        m.record(
979            1,
980            ManagedService {
981                es_pids: vec![Pid::from_const(0x0100)],
982                ca_pids: vec![Pid::from_const(0x0064)],
983                // PCR piggybacked on the ES PID (the common case, already
984                // covered by every other fixture in this file) — must not
985                // produce a duplicate/spurious entry.
986                pcr_pid: Pid::from_const(0x0100),
987                cmd: CaPmtCmdId::OkDescrambling,
988                last_ca_enable: None,
989                last_descrambling_ok: false,
990                built_ca_pmt: vec![],
991                pmt_raw: vec![],
992            },
993        );
994        assert_eq!(
995            m.required_pids(),
996            vec![CAT_PID, Pid::from_const(0x0064), Pid::from_const(0x0100)],
997            "a pcr_pid coinciding with an ES PID must not duplicate/add a spurious entry"
998        );
999    }
1000}