Skip to main content

rustduck_core/
analyzer.rs

1//! Owned transport-stream analyzer snapshots and analysis options.
2
3use std::rc::Rc;
4
5use rustduck_sys::bridge::ffi;
6
7use crate::error::native_exception;
8use crate::{DuckContext, Error, Result, TS_PACKET_SIZE};
9
10/// Confidence in a caller-supplied transport-stream bitrate hint.
11///
12/// Mirrors TSDuck's `BitRateConfidence`. When several bitrate values are
13/// available, TSDuck keeps the one with the highest confidence; use
14/// [`BitRateConfidence::Override`] to make a caller-supplied hint win over the
15/// value TSDuck evaluates from PCR values.
16#[repr(u8)]
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
18#[non_exhaustive]
19pub enum BitRateConfidence {
20    /// Lowest confidence; used only when nothing better is available.
21    #[default]
22    Low = 0,
23    /// Evaluated from PCR values and continuously adjusted.
24    PcrContinuous = 1,
25    /// Evaluated from PCR values, averaged over the whole stream.
26    PcrAverage = 2,
27    /// Evaluated from the system clock on a real-time stream.
28    Clock = 3,
29    /// Reported by a hardware input device, such as a demodulator or ASI input.
30    Hardware = 4,
31    /// Highest confidence; overrides any bitrate TSDuck evaluates itself.
32    Override = 5,
33}
34
35impl BitRateConfidence {
36    const fn abi_value(self) -> u8 {
37        self as u8
38    }
39}
40
41/// Aggregate transport-stream statistics from one analyzer snapshot.
42#[derive(Debug, Clone, PartialEq)]
43pub struct TSAnalyzerSummary {
44    /// Number of 188-byte transport packets fed into the analyzer.
45    pub packet_count: u64,
46    /// Current transport-stream bitrate in bits per second.
47    pub ts_bitrate: f64,
48    /// PCR-derived bitrate normalized to 188-byte packets, in bits per second.
49    pub ts_pcr_bitrate_188: f64,
50    /// Packets whose sync byte was invalid.
51    pub invalid_sync_count: u64,
52    /// Packets with the transport-error indicator set.
53    pub transport_error_count: u64,
54    /// Number of PIDs carrying PCR values.
55    pub pcr_pid_count: u64,
56}
57
58/// A conditional-access descriptor observed in a service PMT.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct TSAnalyzerCaDescriptor {
61    /// Conditional-access system identifier.
62    pub cas_id: u16,
63    /// PID carrying entitlement control messages.
64    pub ca_pid: u16,
65    /// Whether the descriptor is in the program descriptor loop.
66    pub program_level: bool,
67    /// Elementary PID for an ES-level descriptor.
68    pub elementary_pid: Option<u16>,
69}
70
71/// Statistics for one service.
72#[derive(Debug, Clone, PartialEq)]
73pub struct TSAnalyzerService {
74    /// DVB service identifier.
75    pub service_id: u16,
76    /// Displayable service name.
77    pub name: String,
78    /// Displayable service provider.
79    pub provider: String,
80    /// Number of service PIDs.
81    pub pid_count: u64,
82    /// Program-map-table PID.
83    pub pmt_pid: u16,
84    /// Program-clock-reference PID.
85    pub pcr_pid: u16,
86    /// Service bitrate in bits per second.
87    pub bitrate: f64,
88    /// Number of packets attributed to the service.
89    pub packet_count: u64,
90    /// Number of scrambled service PIDs.
91    pub scrambled_pid_count: u64,
92    /// Conditional-access descriptors from the service PMT.
93    pub ca_descriptors: Vec<TSAnalyzerCaDescriptor>,
94}
95
96/// Statistics for one transport-stream PID.
97#[derive(Debug, Clone, PartialEq)]
98pub struct TSAnalyzerPid {
99    /// Packet identifier.
100    pub pid: u16,
101    /// Services referencing this PID.
102    pub services: Vec<u16>,
103    /// Whether the PID carries video elementary-stream data.
104    pub carries_video: bool,
105    /// Whether the PID carries audio elementary-stream data.
106    pub carries_audio: bool,
107    /// Whether the PID is currently scrambled.
108    pub scrambled: bool,
109    /// TSDuck's displayable PID description.
110    pub description: String,
111    /// Number of packets on this PID.
112    pub packet_count: u64,
113    /// Number of packets with a non-clear scrambling-control value.
114    pub scrambled_packet_count: u64,
115    /// Invalid PES packet count.
116    pub invalid_pes_count: u64,
117    /// Invalid PES-start packet count.
118    pub invalid_pes_start_count: u64,
119    /// PID bitrate in bits per second.
120    pub bitrate: f64,
121    /// PCR-derived PID bitrate in bits per second.
122    pub ts_pcr_bitrate: f64,
123    /// Last observed continuity-counter value.
124    pub current_continuity: u8,
125    /// Unexpected continuity-discontinuity count.
126    pub unexpected_discontinuity_count: u64,
127    /// Duplicated packet count.
128    pub duplicated_packet_count: u64,
129    /// Invalid scrambling-control count.
130    pub invalid_scrambling_control_count: u64,
131    /// Conditional-access system identifier for an EMM or ECM PID; zero means
132    /// that TSDuck did not classify this PID as one of those streams.
133    pub cas_id: u16,
134    /// Conditional-access operator identifiers observed for an EMM or ECM PID.
135    pub cas_operators: Vec<u32>,
136    /// Current MPEG-TS scrambling-control value from the packet header.
137    ///
138    /// Values `0`, `2`, and `3` are the standardized clear/even/odd values;
139    /// `1` is reserved by MPEG-TS and is counted separately as invalid.
140    pub current_scrambling_control: u8,
141}
142
143/// A complete Rust-owned analyzer snapshot.
144#[derive(Debug, Clone, PartialEq)]
145pub struct TSAnalyzerReport {
146    /// Aggregate stream statistics.
147    pub summary: TSAnalyzerSummary,
148    /// Services discovered in the current analysis window.
149    pub services: Vec<TSAnalyzerService>,
150    /// PIDs discovered in the current analysis window.
151    pub pids: Vec<TSAnalyzerPid>,
152}
153
154/// A `!Send + !Sync` owner of TSDuck's version-matched `TSAnalyzer` adapter.
155///
156/// The native analyzer is destroyed before its retained [`DuckContext`]. All
157/// snapshots are fully owned Rust values; no TSDuck model references escape.
158///
159/// # Stability
160///
161/// TSDuck exposes no stable public API for analysis statistics: the public
162/// `ts::TSAnalyzer` surface only covers feeding, reset, options, and PID/service
163/// identifier lists. The per-PID and per-service statistics live in protected
164/// members that TSDuck documents as accessible to subclasses. This adapter reads
165/// that protected, version-matched state, so a TSDuck change to those fields can
166/// break the build or change reported values. Only TSDuck 3.44.x is supported.
167pub struct TSAnalyzer {
168    native: cxx::UniquePtr<ffi::RustDuckTSAnalyzer>,
169    context: Rc<DuckContext>,
170    reset_failed: bool,
171}
172
173impl TSAnalyzer {
174    /// Creates an analyzer retaining `context` for its full native lifetime.
175    pub fn new(context: Rc<DuckContext>) -> Result<Self> {
176        let native = ffi::rustduck_analyzer_new(context.native())
177            .map_err(|error| native_exception("TSAnalyzer::new", error))?;
178        if native.is_null() {
179            return Err(Error::NativeFailure {
180                operation: "TSAnalyzer::new",
181            });
182        }
183        Ok(Self {
184            native,
185            context,
186            reset_failed: false,
187        })
188    }
189
190    /// Returns the execution context retained by this analyzer.
191    pub fn context(&self) -> &Rc<DuckContext> {
192        &self.context
193    }
194
195    /// Supplies a transport-stream bitrate hint used by analysis.
196    ///
197    /// `bitrate` is in bits per second based on 188-byte packets. A value of
198    /// `0.0` is accepted and means "derive the bitrate from PCR values". The
199    /// hint may be set at any time before [`Self::snapshot`]. `confidence`
200    /// states how much the hint should be trusted; [`BitRateConfidence::Override`]
201    /// makes it take precedence over TSDuck's own estimate, which is useful for
202    /// live streams whose PCR-derived bitrate is unreliable.
203    ///
204    /// # Errors
205    ///
206    /// Returns [`Error::InvalidArgument`] when `bitrate` is negative or not
207    /// finite, [`Error::InvalidState`] when a previous reset failure made this
208    /// analyzer unusable, or [`Error::NativeException`] when the hint is
209    /// rejected at the native boundary.
210    pub fn set_bitrate_hint(&mut self, bitrate: f64, confidence: BitRateConfidence) -> Result<()> {
211        self.require_usable("set_bitrate_hint")?;
212        if !bitrate.is_finite() || bitrate < 0.0 {
213            return Err(Error::InvalidArgument {
214                field: "bitrate",
215                message: "must be a finite, non-negative bits-per-second value".to_owned(),
216            });
217        }
218        ffi::rustduck_analyzer_set_bitrate_hint(
219            self.native.pin_mut(),
220            bitrate,
221            confidence.abi_value(),
222        )
223        .map_err(|error| native_exception("TSAnalyzer::set_bitrate_hint", error))
224    }
225
226    /// Feeds an integral number of 188-byte transport packets.
227    ///
228    /// # Errors
229    ///
230    /// Returns an error for non-188-byte-aligned input or when native analysis
231    /// fails. A native feed failure resets the analyzer, so it cannot leave a
232    /// partial analysis window behind. If that reset itself fails, its
233    /// `TSAnalyzer::feed_reset` error takes precedence over the original feed
234    /// error, this analyzer becomes unusable, and all later analyzer operations
235    /// return [`Error::InvalidState`].
236    pub fn feed(&mut self, packets: &[u8]) -> Result<()> {
237        self.require_usable("feed")?;
238        if packets.len() % TS_PACKET_SIZE != 0 {
239            return Err(Error::InvalidArgument {
240                field: "packets",
241                message: format!(
242                    "size must be a multiple of {TS_PACKET_SIZE} bytes, got {}",
243                    packets.len()
244                ),
245            });
246        }
247        if let Err(error) = ffi::rustduck_analyzer_feed(self.native.pin_mut(), packets) {
248            let feed_error = native_exception("TSAnalyzer::feed", error);
249            if let Err(error) = ffi::rustduck_analyzer_reset(self.native.pin_mut()) {
250                self.reset_failed = true;
251                return Err(native_exception("TSAnalyzer::feed_reset", error));
252            }
253            return Err(feed_error);
254        }
255        Ok(())
256    }
257
258    /// Copies the current native state into one complete owned snapshot.
259    ///
260    /// # Errors
261    ///
262    /// Returns a native error rather than a partial report when snapshot
263    /// construction fails.
264    pub fn snapshot(&mut self) -> Result<TSAnalyzerReport> {
265        self.require_usable("snapshot")?;
266        ffi::rustduck_analyzer_snapshot(self.native.pin_mut())
267            .map(copy_report)
268            .map_err(|error| native_exception("TSAnalyzer::snapshot", error))
269    }
270
271    /// Clears all state from the current analysis window.
272    ///
273    /// # Errors
274    ///
275    /// Returns a native error if reset fails. In that case, this analyzer is
276    /// permanently unusable, and subsequent [`Self::feed`], [`Self::snapshot`],
277    /// and `reset` calls return [`Error::InvalidState`].
278    pub fn reset(&mut self) -> Result<()> {
279        self.require_usable("reset")?;
280        if let Err(error) = ffi::rustduck_analyzer_reset(self.native.pin_mut()) {
281            self.reset_failed = true;
282            return Err(native_exception("TSAnalyzer::reset", error));
283        }
284        Ok(())
285    }
286
287    fn require_usable(&self, operation: &'static str) -> Result<()> {
288        if self.reset_failed {
289            Err(Error::InvalidState {
290                object: "TSAnalyzer",
291                operation,
292                state: "failed",
293            })
294        } else {
295            Ok(())
296        }
297    }
298}
299
300fn copy_report(value: ffi::RustDuckAnalyzerReport) -> TSAnalyzerReport {
301    TSAnalyzerReport {
302        summary: copy_summary(value.summary),
303        services: value.services.into_iter().map(copy_service).collect(),
304        pids: value.pids.into_iter().map(copy_pid).collect(),
305    }
306}
307
308fn copy_summary(value: ffi::RustDuckAnalyzerSummary) -> TSAnalyzerSummary {
309    TSAnalyzerSummary {
310        packet_count: value.packet_count,
311        ts_bitrate: value.ts_bitrate,
312        ts_pcr_bitrate_188: value.ts_pcr_bitrate_188,
313        invalid_sync_count: value.invalid_sync_count,
314        transport_error_count: value.transport_error_count,
315        pcr_pid_count: value.pcr_pid_count,
316    }
317}
318
319fn copy_service(value: ffi::RustDuckAnalyzerService) -> TSAnalyzerService {
320    TSAnalyzerService {
321        service_id: value.service_id,
322        name: value.name,
323        provider: value.provider,
324        pid_count: value.pid_count,
325        pmt_pid: value.pmt_pid,
326        pcr_pid: value.pcr_pid,
327        bitrate: value.bitrate,
328        packet_count: value.packet_count,
329        scrambled_pid_count: value.scrambled_pid_count,
330        ca_descriptors: value
331            .ca_descriptors
332            .into_iter()
333            .map(copy_ca_descriptor)
334            .collect(),
335    }
336}
337
338fn copy_ca_descriptor(value: ffi::RustDuckAnalyzerCaDescriptor) -> TSAnalyzerCaDescriptor {
339    TSAnalyzerCaDescriptor {
340        cas_id: value.cas_id,
341        ca_pid: value.ca_pid,
342        program_level: value.program_level,
343        elementary_pid: value.has_elementary_pid.then_some(value.elementary_pid),
344    }
345}
346
347fn copy_pid(value: ffi::RustDuckAnalyzerPid) -> TSAnalyzerPid {
348    TSAnalyzerPid {
349        pid: value.pid,
350        services: value.services,
351        carries_video: value.carries_video,
352        carries_audio: value.carries_audio,
353        scrambled: value.scrambled,
354        description: value.description,
355        packet_count: value.packet_count,
356        scrambled_packet_count: value.scrambled_packet_count,
357        invalid_pes_count: value.invalid_pes_count,
358        invalid_pes_start_count: value.invalid_pes_start_count,
359        bitrate: value.bitrate,
360        ts_pcr_bitrate: value.ts_pcr_bitrate,
361        current_continuity: value.current_continuity,
362        unexpected_discontinuity_count: value.unexpected_discontinuity_count,
363        duplicated_packet_count: value.duplicated_packet_count,
364        invalid_scrambling_control_count: value.invalid_scrambling_control_count,
365        cas_id: value.cas_id,
366        cas_operators: value.cas_operators,
367        current_scrambling_control: value.current_scrambling_control,
368    }
369}