clapper-player-sys 0.10.1

Rust bindings for the clapper video player library
Documentation
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from ..
// from ../../gir-files-gstreamer
// from ../../gir-files-gtk
// DO NOT EDIT

#![cfg(unix)]

use clapper_sys::*;
use std::mem::{align_of, size_of};
use std::env;
use std::error::Error;
use std::ffi::OsString;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str;
use tempfile::Builder;

static PACKAGES: &[&str] = &["clapper-0.0"];

#[derive(Clone, Debug)]
struct Compiler {
    pub args: Vec<String>,
}

impl Compiler {
    pub fn new() -> Result<Self, Box<dyn Error>> {
        let mut args = get_var("CC", "cc")?;
        args.push("-Wno-deprecated-declarations".to_owned());
        // For _Generic
        args.push("-std=c11".to_owned());
        // For %z support in printf when using MinGW.
        args.push("-D__USE_MINGW_ANSI_STDIO".to_owned());
        args.extend(get_var("CFLAGS", "")?);
        args.extend(get_var("CPPFLAGS", "")?);
        args.extend(pkg_config_cflags(PACKAGES)?);
        Ok(Self { args })
    }

    pub fn compile(&self, src: &Path, out: &Path) -> Result<(), Box<dyn Error>> {
        let mut cmd = self.to_command();
        cmd.arg(src);
        cmd.arg("-o");
        cmd.arg(out);
        let status = cmd.spawn()?.wait()?;
        if !status.success() {
            return Err(format!("compilation command {cmd:?} failed, {status}").into());
        }
        Ok(())
    }

    fn to_command(&self) -> Command {
        let mut cmd = Command::new(&self.args[0]);
        cmd.args(&self.args[1..]);
        cmd
    }
}

fn get_var(name: &str, default: &str) -> Result<Vec<String>, Box<dyn Error>> {
    match env::var(name) {
        Ok(value) => Ok(shell_words::split(&value)?),
        Err(env::VarError::NotPresent) => Ok(shell_words::split(default)?),
        Err(err) => Err(format!("{name} {err}").into()),
    }
}

fn pkg_config_cflags(packages: &[&str]) -> Result<Vec<String>, Box<dyn Error>> {
    if packages.is_empty() {
        return Ok(Vec::new());
    }
    let pkg_config = env::var_os("PKG_CONFIG")
        .unwrap_or_else(|| OsString::from("pkg-config"));
    let mut cmd = Command::new(pkg_config);
    cmd.arg("--cflags");
    cmd.args(packages);
    cmd.stderr(Stdio::inherit());
    let out = cmd.output()?;
    if !out.status.success() {
        let (status, stdout) = (out.status, String::from_utf8_lossy(&out.stdout));
        return Err(format!("command {cmd:?} failed, {status:?}\nstdout: {stdout}").into());
    }
    let stdout = str::from_utf8(&out.stdout)?;
    Ok(shell_words::split(stdout.trim())?)
}


#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Layout {
    size: usize,
    alignment: usize,
}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
struct Results {
    /// Number of successfully completed tests.
    passed: usize,
    /// Total number of failed tests (including those that failed to compile).
    failed: usize,
}

impl Results {
    fn record_passed(&mut self) {
        self.passed += 1;
    }
    fn record_failed(&mut self) {
        self.failed += 1;
    }
    fn summary(&self) -> String {
        format!("{} passed; {} failed", self.passed, self.failed)
    }
    fn expect_total_success(&self) {
        if self.failed == 0 {
            println!("OK: {}", self.summary());
        } else {
            panic!("FAILED: {}", self.summary());
        };
    }
}

#[test]
fn cross_validate_constants_with_c() {
    let mut c_constants: Vec<(String, String)> = Vec::new();

    for l in get_c_output("constant").unwrap().lines() {
        let (name, value) = l.split_once(';').expect("Missing ';' separator");
        c_constants.push((name.to_owned(), value.to_owned()));
    }

    let mut results = Results::default();

    for ((rust_name, rust_value), (c_name, c_value)) in
        RUST_CONSTANTS.iter().zip(c_constants.iter())
    {
        if rust_name != c_name {
            results.record_failed();
            eprintln!("Name mismatch:\nRust: {rust_name:?}\nC:    {c_name:?}");
            continue;
        }

        if rust_value != c_value {
            results.record_failed();
            eprintln!(
                "Constant value mismatch for {rust_name}\nRust: {rust_value:?}\nC:    {c_value:?}",
            );
            continue;
        }

        results.record_passed();
    }

    results.expect_total_success();
}

#[test]
fn cross_validate_layout_with_c() {
    let mut c_layouts = Vec::new();

    for l in get_c_output("layout").unwrap().lines() {
        let (name, value) = l.split_once(';').expect("Missing first ';' separator");
        let (size, alignment) = value.split_once(';').expect("Missing second ';' separator");
        let size = size.parse().expect("Failed to parse size");
        let alignment = alignment.parse().expect("Failed to parse alignment");
        c_layouts.push((name.to_owned(), Layout { size, alignment }));
    }

    let mut results = Results::default();

    for ((rust_name, rust_layout), (c_name, c_layout)) in
        RUST_LAYOUTS.iter().zip(c_layouts.iter())
    {
        if rust_name != c_name {
            results.record_failed();
            eprintln!("Name mismatch:\nRust: {rust_name:?}\nC:    {c_name:?}");
            continue;
        }

        if rust_layout != c_layout {
            results.record_failed();
            eprintln!(
                "Layout mismatch for {rust_name}\nRust: {rust_layout:?}\nC:    {c_layout:?}",
            );
            continue;
        }

        results.record_passed();
    }

    results.expect_total_success();
}

fn get_c_output(name: &str) -> Result<String, Box<dyn Error>> {
    let tmpdir = Builder::new().prefix("abi").tempdir()?;
    let exe = tmpdir.path().join(name);
    let c_file = Path::new("tests").join(name).with_extension("c");

    let cc = Compiler::new().expect("configured compiler");
    cc.compile(&c_file, &exe)?;

    let mut cmd = Command::new(exe);
    cmd.stderr(Stdio::inherit());
    let out = cmd.output()?;
    if !out.status.success() {
        let (status, stdout) = (out.status, String::from_utf8_lossy(&out.stdout));
        return Err(format!("command {cmd:?} failed, {status:?}\nstdout: {stdout}").into());
    }

    Ok(String::from_utf8(out.stdout)?)
}

const RUST_LAYOUTS: &[(&str, Layout)] = &[
    ("ClapperAudioStreamClass", Layout {size: size_of::<ClapperAudioStreamClass>(), alignment: align_of::<ClapperAudioStreamClass>()}),
    ("ClapperDiscovererClass", Layout {size: size_of::<ClapperDiscovererClass>(), alignment: align_of::<ClapperDiscovererClass>()}),
    ("ClapperDiscovererDiscoveryMode", Layout {size: size_of::<ClapperDiscovererDiscoveryMode>(), alignment: align_of::<ClapperDiscovererDiscoveryMode>()}),
    ("ClapperEnhancerParamFlags", Layout {size: size_of::<ClapperEnhancerParamFlags>(), alignment: align_of::<ClapperEnhancerParamFlags>()}),
    ("ClapperEnhancerProxyClass", Layout {size: size_of::<ClapperEnhancerProxyClass>(), alignment: align_of::<ClapperEnhancerProxyClass>()}),
    ("ClapperEnhancerProxyListClass", Layout {size: size_of::<ClapperEnhancerProxyListClass>(), alignment: align_of::<ClapperEnhancerProxyListClass>()}),
    ("ClapperExtractableInterface", Layout {size: size_of::<ClapperExtractableInterface>(), alignment: align_of::<ClapperExtractableInterface>()}),
    ("ClapperFeature", Layout {size: size_of::<ClapperFeature>(), alignment: align_of::<ClapperFeature>()}),
    ("ClapperFeatureClass", Layout {size: size_of::<ClapperFeatureClass>(), alignment: align_of::<ClapperFeatureClass>()}),
    ("ClapperHarvestClass", Layout {size: size_of::<ClapperHarvestClass>(), alignment: align_of::<ClapperHarvestClass>()}),
    ("ClapperMarkerClass", Layout {size: size_of::<ClapperMarkerClass>(), alignment: align_of::<ClapperMarkerClass>()}),
    ("ClapperMarkerType", Layout {size: size_of::<ClapperMarkerType>(), alignment: align_of::<ClapperMarkerType>()}),
    ("ClapperMediaItemClass", Layout {size: size_of::<ClapperMediaItemClass>(), alignment: align_of::<ClapperMediaItemClass>()}),
    ("ClapperMprisClass", Layout {size: size_of::<ClapperMprisClass>(), alignment: align_of::<ClapperMprisClass>()}),
    ("ClapperPlayerClass", Layout {size: size_of::<ClapperPlayerClass>(), alignment: align_of::<ClapperPlayerClass>()}),
    ("ClapperPlayerMessageDestination", Layout {size: size_of::<ClapperPlayerMessageDestination>(), alignment: align_of::<ClapperPlayerMessageDestination>()}),
    ("ClapperPlayerSeekMethod", Layout {size: size_of::<ClapperPlayerSeekMethod>(), alignment: align_of::<ClapperPlayerSeekMethod>()}),
    ("ClapperPlayerState", Layout {size: size_of::<ClapperPlayerState>(), alignment: align_of::<ClapperPlayerState>()}),
    ("ClapperPlaylistableInterface", Layout {size: size_of::<ClapperPlaylistableInterface>(), alignment: align_of::<ClapperPlaylistableInterface>()}),
    ("ClapperQueueClass", Layout {size: size_of::<ClapperQueueClass>(), alignment: align_of::<ClapperQueueClass>()}),
    ("ClapperQueueProgressionMode", Layout {size: size_of::<ClapperQueueProgressionMode>(), alignment: align_of::<ClapperQueueProgressionMode>()}),
    ("ClapperReactableInterface", Layout {size: size_of::<ClapperReactableInterface>(), alignment: align_of::<ClapperReactableInterface>()}),
    ("ClapperReactableItemUpdatedFlags", Layout {size: size_of::<ClapperReactableItemUpdatedFlags>(), alignment: align_of::<ClapperReactableItemUpdatedFlags>()}),
    ("ClapperServerClass", Layout {size: size_of::<ClapperServerClass>(), alignment: align_of::<ClapperServerClass>()}),
    ("ClapperStream", Layout {size: size_of::<ClapperStream>(), alignment: align_of::<ClapperStream>()}),
    ("ClapperStreamClass", Layout {size: size_of::<ClapperStreamClass>(), alignment: align_of::<ClapperStreamClass>()}),
    ("ClapperStreamListClass", Layout {size: size_of::<ClapperStreamListClass>(), alignment: align_of::<ClapperStreamListClass>()}),
    ("ClapperStreamType", Layout {size: size_of::<ClapperStreamType>(), alignment: align_of::<ClapperStreamType>()}),
    ("ClapperSubtitleStreamClass", Layout {size: size_of::<ClapperSubtitleStreamClass>(), alignment: align_of::<ClapperSubtitleStreamClass>()}),
    ("ClapperThreadedObject", Layout {size: size_of::<ClapperThreadedObject>(), alignment: align_of::<ClapperThreadedObject>()}),
    ("ClapperThreadedObjectClass", Layout {size: size_of::<ClapperThreadedObjectClass>(), alignment: align_of::<ClapperThreadedObjectClass>()}),
    ("ClapperTimelineClass", Layout {size: size_of::<ClapperTimelineClass>(), alignment: align_of::<ClapperTimelineClass>()}),
    ("ClapperVideoStreamClass", Layout {size: size_of::<ClapperVideoStreamClass>(), alignment: align_of::<ClapperVideoStreamClass>()}),
];

const RUST_CONSTANTS: &[(&str, &str)] = &[
    ("(gint) CLAPPER_DISCOVERER_DISCOVERY_ALWAYS", "0"),
    ("(gint) CLAPPER_DISCOVERER_DISCOVERY_NONCURRENT", "1"),
    ("(guint) CLAPPER_ENHANCER_PARAM_DIRPATH", "1048576"),
    ("(guint) CLAPPER_ENHANCER_PARAM_FILEPATH", "524288"),
    ("(guint) CLAPPER_ENHANCER_PARAM_GLOBAL", "131072"),
    ("(guint) CLAPPER_ENHANCER_PARAM_LOCAL", "262144"),
    ("CLAPPER_HAVE_DISCOVERER", "1"),
    ("CLAPPER_HAVE_MPRIS", "1"),
    ("CLAPPER_HAVE_SERVER", "1"),
    ("CLAPPER_MAJOR_VERSION", "0"),
    ("CLAPPER_MARKER_NO_END", "-1"),
    ("(gint) CLAPPER_MARKER_TYPE_CHAPTER", "2"),
    ("(gint) CLAPPER_MARKER_TYPE_CUSTOM_1", "101"),
    ("(gint) CLAPPER_MARKER_TYPE_CUSTOM_2", "102"),
    ("(gint) CLAPPER_MARKER_TYPE_CUSTOM_3", "103"),
    ("(gint) CLAPPER_MARKER_TYPE_TITLE", "1"),
    ("(gint) CLAPPER_MARKER_TYPE_TRACK", "3"),
    ("(gint) CLAPPER_MARKER_TYPE_UNKNOWN", "0"),
    ("CLAPPER_MICRO_VERSION", "0"),
    ("CLAPPER_MINOR_VERSION", "10"),
    ("(gint) CLAPPER_PLAYER_MESSAGE_DESTINATION_APPLICATION", "2"),
    ("(gint) CLAPPER_PLAYER_MESSAGE_DESTINATION_PLAYER", "0"),
    ("(gint) CLAPPER_PLAYER_MESSAGE_DESTINATION_REACTABLES", "1"),
    ("(gint) CLAPPER_PLAYER_SEEK_METHOD_ACCURATE", "0"),
    ("(gint) CLAPPER_PLAYER_SEEK_METHOD_FAST", "2"),
    ("(gint) CLAPPER_PLAYER_SEEK_METHOD_NORMAL", "1"),
    ("(gint) CLAPPER_PLAYER_STATE_BUFFERING", "1"),
    ("(gint) CLAPPER_PLAYER_STATE_PAUSED", "2"),
    ("(gint) CLAPPER_PLAYER_STATE_PLAYING", "3"),
    ("(gint) CLAPPER_PLAYER_STATE_STOPPED", "0"),
    ("CLAPPER_QUEUE_INVALID_POSITION", "4294967295"),
    ("(gint) CLAPPER_QUEUE_PROGRESSION_CAROUSEL", "3"),
    ("(gint) CLAPPER_QUEUE_PROGRESSION_CONSECUTIVE", "1"),
    ("(gint) CLAPPER_QUEUE_PROGRESSION_NONE", "0"),
    ("(gint) CLAPPER_QUEUE_PROGRESSION_REPEAT_ITEM", "2"),
    ("(gint) CLAPPER_QUEUE_PROGRESSION_SHUFFLE", "4"),
    ("(guint) CLAPPER_REACTABLE_ITEM_UPDATED_CACHE_LOCATION", "32"),
    ("(guint) CLAPPER_REACTABLE_ITEM_UPDATED_DURATION", "2"),
    ("(guint) CLAPPER_REACTABLE_ITEM_UPDATED_REDIRECT_URI", "16"),
    ("(guint) CLAPPER_REACTABLE_ITEM_UPDATED_TAGS", "8"),
    ("(guint) CLAPPER_REACTABLE_ITEM_UPDATED_TIMELINE", "4"),
    ("(guint) CLAPPER_REACTABLE_ITEM_UPDATED_TITLE", "1"),
    ("CLAPPER_STREAM_LIST_INVALID_POSITION", "4294967295"),
    ("(gint) CLAPPER_STREAM_TYPE_AUDIO", "2"),
    ("(gint) CLAPPER_STREAM_TYPE_SUBTITLE", "3"),
    ("(gint) CLAPPER_STREAM_TYPE_UNKNOWN", "0"),
    ("(gint) CLAPPER_STREAM_TYPE_VIDEO", "1"),
    ("CLAPPER_TIME_FORMAT", "02u:%02u:%02u"),
    ("CLAPPER_TIME_MS_FORMAT", "02u:%02u:%02u.%03u"),
    ("CLAPPER_VERSION_S", "0.10.0"),
    ("CLAPPER_WITH_ENHANCERS_LOADER", "1"),
];