rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
//! Owned transport-stream analyzer snapshots and analysis options.

use std::rc::Rc;

use rustduck_sys::bridge::ffi;

use crate::error::native_exception;
use crate::{DuckContext, Error, Result, TS_PACKET_SIZE};

/// Confidence in a caller-supplied transport-stream bitrate hint.
///
/// Mirrors TSDuck's `BitRateConfidence`. When several bitrate values are
/// available, TSDuck keeps the one with the highest confidence; use
/// [`BitRateConfidence::Override`] to make a caller-supplied hint win over the
/// value TSDuck evaluates from PCR values.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
#[non_exhaustive]
pub enum BitRateConfidence {
    /// Lowest confidence; used only when nothing better is available.
    #[default]
    Low = 0,
    /// Evaluated from PCR values and continuously adjusted.
    PcrContinuous = 1,
    /// Evaluated from PCR values, averaged over the whole stream.
    PcrAverage = 2,
    /// Evaluated from the system clock on a real-time stream.
    Clock = 3,
    /// Reported by a hardware input device, such as a demodulator or ASI input.
    Hardware = 4,
    /// Highest confidence; overrides any bitrate TSDuck evaluates itself.
    Override = 5,
}

impl BitRateConfidence {
    const fn abi_value(self) -> u8 {
        self as u8
    }
}

/// Aggregate transport-stream statistics from one analyzer snapshot.
#[derive(Debug, Clone, PartialEq)]
pub struct TSAnalyzerSummary {
    /// Number of 188-byte transport packets fed into the analyzer.
    pub packet_count: u64,
    /// Current transport-stream bitrate in bits per second.
    pub ts_bitrate: f64,
    /// PCR-derived bitrate normalized to 188-byte packets, in bits per second.
    pub ts_pcr_bitrate_188: f64,
    /// Packets whose sync byte was invalid.
    pub invalid_sync_count: u64,
    /// Packets with the transport-error indicator set.
    pub transport_error_count: u64,
    /// Number of PIDs carrying PCR values.
    pub pcr_pid_count: u64,
}

/// A conditional-access descriptor observed in a service PMT.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TSAnalyzerCaDescriptor {
    /// Conditional-access system identifier.
    pub cas_id: u16,
    /// PID carrying entitlement control messages.
    pub ca_pid: u16,
    /// Whether the descriptor is in the program descriptor loop.
    pub program_level: bool,
    /// Elementary PID for an ES-level descriptor.
    pub elementary_pid: Option<u16>,
}

/// Statistics for one service.
#[derive(Debug, Clone, PartialEq)]
pub struct TSAnalyzerService {
    /// DVB service identifier.
    pub service_id: u16,
    /// Displayable service name.
    pub name: String,
    /// Displayable service provider.
    pub provider: String,
    /// Number of service PIDs.
    pub pid_count: u64,
    /// Program-map-table PID.
    pub pmt_pid: u16,
    /// Program-clock-reference PID.
    pub pcr_pid: u16,
    /// Service bitrate in bits per second.
    pub bitrate: f64,
    /// Number of packets attributed to the service.
    pub packet_count: u64,
    /// Number of scrambled service PIDs.
    pub scrambled_pid_count: u64,
    /// Conditional-access descriptors from the service PMT.
    pub ca_descriptors: Vec<TSAnalyzerCaDescriptor>,
}

/// Statistics for one transport-stream PID.
#[derive(Debug, Clone, PartialEq)]
pub struct TSAnalyzerPid {
    /// Packet identifier.
    pub pid: u16,
    /// Services referencing this PID.
    pub services: Vec<u16>,
    /// Whether the PID carries video elementary-stream data.
    pub carries_video: bool,
    /// Whether the PID carries audio elementary-stream data.
    pub carries_audio: bool,
    /// Whether the PID is currently scrambled.
    pub scrambled: bool,
    /// TSDuck's displayable PID description.
    pub description: String,
    /// Number of packets on this PID.
    pub packet_count: u64,
    /// Number of packets with a non-clear scrambling-control value.
    pub scrambled_packet_count: u64,
    /// Invalid PES packet count.
    pub invalid_pes_count: u64,
    /// Invalid PES-start packet count.
    pub invalid_pes_start_count: u64,
    /// PID bitrate in bits per second.
    pub bitrate: f64,
    /// PCR-derived PID bitrate in bits per second.
    pub ts_pcr_bitrate: f64,
    /// Last observed continuity-counter value.
    pub current_continuity: u8,
    /// Unexpected continuity-discontinuity count.
    pub unexpected_discontinuity_count: u64,
    /// Duplicated packet count.
    pub duplicated_packet_count: u64,
    /// Invalid scrambling-control count.
    pub invalid_scrambling_control_count: u64,
    /// Conditional-access system identifier for an EMM or ECM PID; zero means
    /// that TSDuck did not classify this PID as one of those streams.
    pub cas_id: u16,
    /// Conditional-access operator identifiers observed for an EMM or ECM PID.
    pub cas_operators: Vec<u32>,
    /// Current MPEG-TS scrambling-control value from the packet header.
    ///
    /// Values `0`, `2`, and `3` are the standardized clear/even/odd values;
    /// `1` is reserved by MPEG-TS and is counted separately as invalid.
    pub current_scrambling_control: u8,
}

/// A complete Rust-owned analyzer snapshot.
#[derive(Debug, Clone, PartialEq)]
pub struct TSAnalyzerReport {
    /// Aggregate stream statistics.
    pub summary: TSAnalyzerSummary,
    /// Services discovered in the current analysis window.
    pub services: Vec<TSAnalyzerService>,
    /// PIDs discovered in the current analysis window.
    pub pids: Vec<TSAnalyzerPid>,
}

/// A `!Send + !Sync` owner of TSDuck's version-matched `TSAnalyzer` adapter.
///
/// The native analyzer is destroyed before its retained [`DuckContext`]. All
/// snapshots are fully owned Rust values; no TSDuck model references escape.
///
/// # Stability
///
/// TSDuck exposes no stable public API for analysis statistics: the public
/// `ts::TSAnalyzer` surface only covers feeding, reset, options, and PID/service
/// identifier lists. The per-PID and per-service statistics live in protected
/// members that TSDuck documents as accessible to subclasses. This adapter reads
/// that protected, version-matched state, so a TSDuck change to those fields can
/// break the build or change reported values. Only TSDuck 3.44.x is supported.
pub struct TSAnalyzer {
    native: cxx::UniquePtr<ffi::RustDuckTSAnalyzer>,
    context: Rc<DuckContext>,
    reset_failed: bool,
}

impl TSAnalyzer {
    /// Creates an analyzer retaining `context` for its full native lifetime.
    pub fn new(context: Rc<DuckContext>) -> Result<Self> {
        let native = ffi::rustduck_analyzer_new(context.native())
            .map_err(|error| native_exception("TSAnalyzer::new", error))?;
        if native.is_null() {
            return Err(Error::NativeFailure {
                operation: "TSAnalyzer::new",
            });
        }
        Ok(Self {
            native,
            context,
            reset_failed: false,
        })
    }

    /// Returns the execution context retained by this analyzer.
    pub fn context(&self) -> &Rc<DuckContext> {
        &self.context
    }

    /// Supplies a transport-stream bitrate hint used by analysis.
    ///
    /// `bitrate` is in bits per second based on 188-byte packets. A value of
    /// `0.0` is accepted and means "derive the bitrate from PCR values". The
    /// hint may be set at any time before [`Self::snapshot`]. `confidence`
    /// states how much the hint should be trusted; [`BitRateConfidence::Override`]
    /// makes it take precedence over TSDuck's own estimate, which is useful for
    /// live streams whose PCR-derived bitrate is unreliable.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArgument`] when `bitrate` is negative or not
    /// finite, [`Error::InvalidState`] when a previous reset failure made this
    /// analyzer unusable, or [`Error::NativeException`] when the hint is
    /// rejected at the native boundary.
    pub fn set_bitrate_hint(&mut self, bitrate: f64, confidence: BitRateConfidence) -> Result<()> {
        self.require_usable("set_bitrate_hint")?;
        if !bitrate.is_finite() || bitrate < 0.0 {
            return Err(Error::InvalidArgument {
                field: "bitrate",
                message: "must be a finite, non-negative bits-per-second value".to_owned(),
            });
        }
        ffi::rustduck_analyzer_set_bitrate_hint(
            self.native.pin_mut(),
            bitrate,
            confidence.abi_value(),
        )
        .map_err(|error| native_exception("TSAnalyzer::set_bitrate_hint", error))
    }

    /// Feeds an integral number of 188-byte transport packets.
    ///
    /// # Errors
    ///
    /// Returns an error for non-188-byte-aligned input or when native analysis
    /// fails. A native feed failure resets the analyzer, so it cannot leave a
    /// partial analysis window behind. If that reset itself fails, its
    /// `TSAnalyzer::feed_reset` error takes precedence over the original feed
    /// error, this analyzer becomes unusable, and all later analyzer operations
    /// return [`Error::InvalidState`].
    pub fn feed(&mut self, packets: &[u8]) -> Result<()> {
        self.require_usable("feed")?;
        if packets.len() % TS_PACKET_SIZE != 0 {
            return Err(Error::InvalidArgument {
                field: "packets",
                message: format!(
                    "size must be a multiple of {TS_PACKET_SIZE} bytes, got {}",
                    packets.len()
                ),
            });
        }
        if let Err(error) = ffi::rustduck_analyzer_feed(self.native.pin_mut(), packets) {
            let feed_error = native_exception("TSAnalyzer::feed", error);
            if let Err(error) = ffi::rustduck_analyzer_reset(self.native.pin_mut()) {
                self.reset_failed = true;
                return Err(native_exception("TSAnalyzer::feed_reset", error));
            }
            return Err(feed_error);
        }
        Ok(())
    }

    /// Copies the current native state into one complete owned snapshot.
    ///
    /// # Errors
    ///
    /// Returns a native error rather than a partial report when snapshot
    /// construction fails.
    pub fn snapshot(&mut self) -> Result<TSAnalyzerReport> {
        self.require_usable("snapshot")?;
        ffi::rustduck_analyzer_snapshot(self.native.pin_mut())
            .map(copy_report)
            .map_err(|error| native_exception("TSAnalyzer::snapshot", error))
    }

    /// Clears all state from the current analysis window.
    ///
    /// # Errors
    ///
    /// Returns a native error if reset fails. In that case, this analyzer is
    /// permanently unusable, and subsequent [`Self::feed`], [`Self::snapshot`],
    /// and `reset` calls return [`Error::InvalidState`].
    pub fn reset(&mut self) -> Result<()> {
        self.require_usable("reset")?;
        if let Err(error) = ffi::rustduck_analyzer_reset(self.native.pin_mut()) {
            self.reset_failed = true;
            return Err(native_exception("TSAnalyzer::reset", error));
        }
        Ok(())
    }

    fn require_usable(&self, operation: &'static str) -> Result<()> {
        if self.reset_failed {
            Err(Error::InvalidState {
                object: "TSAnalyzer",
                operation,
                state: "failed",
            })
        } else {
            Ok(())
        }
    }
}

fn copy_report(value: ffi::RustDuckAnalyzerReport) -> TSAnalyzerReport {
    TSAnalyzerReport {
        summary: copy_summary(value.summary),
        services: value.services.into_iter().map(copy_service).collect(),
        pids: value.pids.into_iter().map(copy_pid).collect(),
    }
}

fn copy_summary(value: ffi::RustDuckAnalyzerSummary) -> TSAnalyzerSummary {
    TSAnalyzerSummary {
        packet_count: value.packet_count,
        ts_bitrate: value.ts_bitrate,
        ts_pcr_bitrate_188: value.ts_pcr_bitrate_188,
        invalid_sync_count: value.invalid_sync_count,
        transport_error_count: value.transport_error_count,
        pcr_pid_count: value.pcr_pid_count,
    }
}

fn copy_service(value: ffi::RustDuckAnalyzerService) -> TSAnalyzerService {
    TSAnalyzerService {
        service_id: value.service_id,
        name: value.name,
        provider: value.provider,
        pid_count: value.pid_count,
        pmt_pid: value.pmt_pid,
        pcr_pid: value.pcr_pid,
        bitrate: value.bitrate,
        packet_count: value.packet_count,
        scrambled_pid_count: value.scrambled_pid_count,
        ca_descriptors: value
            .ca_descriptors
            .into_iter()
            .map(copy_ca_descriptor)
            .collect(),
    }
}

fn copy_ca_descriptor(value: ffi::RustDuckAnalyzerCaDescriptor) -> TSAnalyzerCaDescriptor {
    TSAnalyzerCaDescriptor {
        cas_id: value.cas_id,
        ca_pid: value.ca_pid,
        program_level: value.program_level,
        elementary_pid: value.has_elementary_pid.then_some(value.elementary_pid),
    }
}

fn copy_pid(value: ffi::RustDuckAnalyzerPid) -> TSAnalyzerPid {
    TSAnalyzerPid {
        pid: value.pid,
        services: value.services,
        carries_video: value.carries_video,
        carries_audio: value.carries_audio,
        scrambled: value.scrambled,
        description: value.description,
        packet_count: value.packet_count,
        scrambled_packet_count: value.scrambled_packet_count,
        invalid_pes_count: value.invalid_pes_count,
        invalid_pes_start_count: value.invalid_pes_start_count,
        bitrate: value.bitrate,
        ts_pcr_bitrate: value.ts_pcr_bitrate,
        current_continuity: value.current_continuity,
        unexpected_discontinuity_count: value.unexpected_discontinuity_count,
        duplicated_packet_count: value.duplicated_packet_count,
        invalid_scrambling_control_count: value.invalid_scrambling_control_count,
        cas_id: value.cas_id,
        cas_operators: value.cas_operators,
        current_scrambling_control: value.current_scrambling_control,
    }
}