rustsynth 0.7.0

Safe VapourSynth wrapper
Documentation
//! `VapourSynth` callable functions.

use rustsynth_sys as ffi;
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::ptr::NonNull;
use std::{mem, panic, process};

use crate::api::API;
use crate::core::CoreRef;
use crate::map::MapRef;

/// Holds a reference to a function that may be called.
#[derive(Debug, PartialEq, Eq)]
pub struct Function<'core> {
    handle: NonNull<ffi::VSFunction>,
    _owner: PhantomData<&'core ()>,
}

unsafe impl Send for Function<'_> {}
unsafe impl Sync for Function<'_> {}

impl Drop for Function<'_> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            API::get_cached().free_func(self.handle.as_ptr());
        }
    }
}

impl Clone for Function<'_> {
    #[inline]
    fn clone(&self) -> Self {
        let handle = unsafe { API::get_cached().clone_func(self.handle.as_ptr()) };
        Self {
            handle: unsafe { NonNull::new_unchecked(handle) },
            _owner: PhantomData,
        }
    }
}

impl<'core> Function<'core> {
    /// Wraps `handle` in a `Function`.
    ///
    /// # Safety
    /// The caller must ensure `handle` and the lifetime are valid and API is cached.
    #[inline]
    pub const unsafe fn from_ptr(handle: *mut ffi::VSFunction) -> Self {
        Self {
            handle: NonNull::new_unchecked(handle),
            _owner: PhantomData,
        }
    }

    /// Returns the underlying pointer.
    #[inline]
    #[must_use]
    pub const fn as_ptr(&self) -> *mut ffi::VSFunction {
        self.handle.as_ptr()
    }

    /// Creates a new function.
    ///
    /// To indicate an error from the callback, set an error on the output map.
    pub fn new<F>(core: CoreRef<'core>, callback: F) -> Self
    where
        F: Fn(CoreRef<'core>, &MapRef<'core>, &mut MapRef<'core>) + Send + Sync + 'core,
    {
        unsafe extern "C" fn c_callback<'core, F>(
            in_: *const ffi::VSMap,
            out: *mut ffi::VSMap,
            user_data: *mut c_void,
            core: *mut ffi::VSCore,
            _vsapi: *const ffi::VSAPI,
        ) where
            F: Fn(CoreRef<'core>, &MapRef<'core>, &mut MapRef<'core>) + Send + Sync + 'core,
        {
            let closure = move || {
                let core = CoreRef::from_ptr(core);
                let in_map = MapRef::from_ptr(in_);
                let out_map = MapRef::from_ptr_mut(out);
                let callback = Box::from_raw(user_data.cast::<F>());

                callback(core, in_map, out_map);

                mem::forget(callback);
            };

            if panic::catch_unwind(closure).is_err() {
                process::abort();
            }
        }

        unsafe extern "C" fn c_free<F>(user_data: *mut c_void) {
            drop(Box::from_raw(user_data.cast::<F>()));
        }

        let data = Box::new(callback);

        let handle = unsafe {
            API::get_cached().create_func(
                Some(c_callback::<'core, F>),
                Box::into_raw(data).cast(),
                Some(c_free::<F>),
                core.as_ptr(),
            )
        };

        Self {
            handle: unsafe { NonNull::new_unchecked(handle) },
            _owner: PhantomData,
        }
    }

    /// Calls the function. If the call fails `out` will have an error set.
    #[inline]
    pub fn call(&self, in_: &MapRef<'core>, out: &mut MapRef<'core>) {
        unsafe {
            API::get_cached().call_func(
                self.handle.as_ptr(),
                &*in_.as_ptr(),
                &mut *out.as_mut_ptr(),
            )
        };
    }
}