rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
use std::rc::Rc;

use rustduck_sys::bridge::ffi;

use crate::buffer::encode_utf16;
use crate::error::native_exception;
use crate::{Error, Report, Result};

/// Standards mask used by a [`DuckContext`].
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Standards(pub u32);

impl Standards {
    /// No standards selected.
    pub const NONE: Self = Self(0x00);
    /// MPEG standards.
    pub const MPEG: Self = Self(0x01);
    /// DVB standards.
    pub const DVB: Self = Self(0x02);
    /// SCTE standards.
    pub const SCTE: Self = Self(0x04);
    /// ATSC standards.
    pub const ATSC: Self = Self(0x08);
    /// ISDB standards.
    pub const ISDB: Self = Self(0x10);
    /// Japanese standards.
    pub const JAPAN: Self = Self(0x20);
    /// ABNT standards.
    pub const ABNT: Self = Self(0x40);
    /// All defined standards.
    pub const ALL: Self = Self(0x7f);

    /// Returns the raw TSDuck standards bitmask.
    pub const fn bits(self) -> u32 {
        self.0
    }

    /// Returns all defined standards.
    pub const fn all() -> Self {
        Self::ALL
    }
}

impl BitOr for Standards {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}
impl BitOrAssign for Standards {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}
impl BitAnd for Standards {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self::Output {
        Self(self.0 & rhs.0)
    }
}
impl BitAndAssign for Standards {
    fn bitand_assign(&mut self, rhs: Self) {
        self.0 &= rhs.0;
    }
}
impl Not for Standards {
    type Output = Self;
    fn not(self) -> Self::Output {
        Self(!self.0 & Self::ALL.0)
    }
}

/// A TSDuck execution context borrowing a [`Report`].
///
/// `DuckContext` is `!Send + !Sync`. The native owner is declared before its
/// report dependency, so it is destroyed first.
pub struct DuckContext {
    native: cxx::UniquePtr<ffi::RustDuckDuckContext>,
    report: Rc<Report>,
}

impl DuckContext {
    /// Creates a context retaining `report` until native context destruction.
    pub fn new(report: Rc<Report>) -> Result<Rc<Self>> {
        let native = ffi::rustduck_context_new(report.native())
            .map_err(|error| native_exception("DuckContext::new", error))?;
        if native.is_null() {
            return Err(Error::NativeFailure {
                operation: "DuckContext::new",
            });
        }
        Ok(Rc::new(Self { native, report }))
    }

    /// Returns the retained report.
    pub fn report(&self) -> &Rc<Report> {
        &self.report
    }

    /// Sets the default character set.
    pub fn set_default_charset(&mut self, charset: &str) -> Result<()> {
        let charset = encode_utf16(charset);
        let accepted =
            ffi::rustduck_context_set_default_charset(self.native.pin_mut(), &charset)
                .map_err(|error| native_exception("DuckContext::set_default_charset", error))?;
        accepted.then_some(()).ok_or(Error::NativeFailure {
            operation: "DuckContext::set_default_charset",
        })
    }

    /// Sets the default conditional-access system identifier.
    pub fn set_default_cas_id(&mut self, cas_id: u16) -> Result<()> {
        ffi::rustduck_context_set_default_cas_id(self.native.pin_mut(), cas_id)
            .map_err(|error| native_exception("DuckContext::set_default_cas_id", error))
    }

    /// Sets the default private data specifier.
    pub fn set_default_pds(&mut self, pds: u32) -> Result<()> {
        ffi::rustduck_context_set_default_pds(self.native.pin_mut(), pds)
            .map_err(|error| native_exception("DuckContext::set_default_pds", error))
    }

    /// Adds standards to the active mask.
    pub fn add_standards(&mut self, standards: Standards) -> Result<()> {
        ffi::rustduck_context_add_standards(self.native.pin_mut(), standards.bits())
            .map_err(|error| native_exception("DuckContext::add_standards", error))
    }

    /// Returns the active standards mask.
    pub fn standards(&self) -> Result<Standards> {
        ffi::rustduck_context_standards(
            self.native
                .as_ref()
                .expect("DuckContext construction rejects null owners"),
        )
        .map(Standards)
        .map_err(|error| native_exception("DuckContext::standards", error))
    }

    /// Replaces the active standards mask.
    pub fn reset_standards(&mut self, standards: Standards) -> Result<()> {
        ffi::rustduck_context_reset_standards(self.native.pin_mut(), standards.bits())
            .map_err(|error| native_exception("DuckContext::reset_standards", error))
    }

    /// Sets the time-reference offset in milliseconds.
    pub fn set_time_reference_offset(&mut self, offset_millis: i64) -> Result<()> {
        ffi::rustduck_context_set_time_reference_offset(self.native.pin_mut(), offset_millis)
            .map_err(|error| native_exception("DuckContext::set_time_reference_offset", error))
    }

    /// Selects a named time reference.
    pub fn set_time_reference(&mut self, name: &str) -> Result<()> {
        let name = encode_utf16(name);
        let accepted = ffi::rustduck_context_set_time_reference(self.native.pin_mut(), &name)
            .map_err(|error| native_exception("DuckContext::set_time_reference", error))?;
        accepted.then_some(()).ok_or(Error::NativeFailure {
            operation: "DuckContext::set_time_reference",
        })
    }

    pub(crate) fn native(&self) -> &ffi::RustDuckDuckContext {
        self.native
            .as_ref()
            .expect("DuckContext construction rejects null owners")
    }
}

#[cfg(test)]
mod tests {
    use super::Standards;

    #[test]
    fn all_covers_every_defined_standard() {
        let defined = Standards::MPEG
            | Standards::DVB
            | Standards::SCTE
            | Standards::ATSC
            | Standards::ISDB
            | Standards::JAPAN
            | Standards::ABNT;
        assert_eq!(Standards::ALL.bits(), 0x7f);
        assert_eq!(Standards::all().bits(), 0x7f);
        assert_eq!(defined.bits(), Standards::ALL.bits());
    }

    #[test]
    fn not_keeps_only_defined_standard_bits() {
        assert_eq!((!Standards::NONE).bits(), Standards::ALL.bits());
        assert_eq!((!Standards::ALL).bits(), Standards::NONE.bits());
        assert_eq!((!Standards::MPEG).bits(), 0x7e);
        assert_eq!((!Standards(0xffff_ffff)).bits(), Standards::NONE.bits());
        assert_eq!((!Standards(0x80)).bits(), Standards::ALL.bits());
    }
}