Skip to main content

vapoursynth4_rs/node/
filter.rs

1use std::{
2    ffi::{CStr, c_void},
3    ptr::{from_ref, null_mut},
4};
5
6use crate::{
7    core::CoreRef,
8    ffi,
9    frame::{Frame, FrameContext},
10    map::{MapMut, MapRef},
11    node::FilterMode,
12};
13
14/// A filter instance that `VapourSynth` can move between worker threads and call concurrently.
15pub trait Filter: Sized + Send + Sync + std::panic::RefUnwindSafe + 'static {
16    /// Bitmask of [`ffi::VSFilterFlags`] used when creating video nodes.
17    /// GPU output must agree with [`Self::RETURN_TYPE`]; defaults to CPU output.
18    #[cfg(feature = "vs-43")]
19    const FLAGS: i32 = 0;
20
21    const FILTER_MODE: FilterMode = FilterMode::Parallel;
22    /// Filter error that can turned into a [`&CStr`](std::ffi::CStr)
23    type Error: AsRef<CStr>;
24    type FrameType: Frame;
25    /// Shared registration data available to each call to [`Self::create`].
26    type FilterData: Sync + 'static;
27
28    const NAME: &'static CStr;
29    const ARGS: &'static CStr;
30    const RETURN_TYPE: &'static CStr;
31
32    /// # Errors
33    ///
34    /// Return [`Self::Error`] if anything happens during the filter creation.
35    /// The error message will be passed to `VapourSynth`.
36    fn create(
37        input: MapRef,
38        output: MapMut,
39        data: Option<&Self::FilterData>,
40        core: CoreRef,
41    ) -> Result<(), Self::Error>;
42
43    /// # Errors
44    ///
45    /// Return [`Self::Error`] if anything happens during the filter creation.
46    /// The error message will be passed to `VapourSynth`.
47    fn get_frame(
48        &self,
49        n: i32,
50        activation_reason: ffi::VSActivationReason,
51        frame_data: *mut *mut c_void,
52        frame_ctx: FrameContext,
53        core: CoreRef,
54    ) -> Result<Option<Self::FrameType>, Self::Error>;
55    /// Free the filter
56    fn free(self, core: CoreRef) {
57        let _ = core;
58    }
59}
60
61pub struct FilterRegister<F: Filter> {
62    data: Option<&'static F::FilterData>,
63}
64
65impl<F: Filter> FilterRegister<F> {
66    #[must_use]
67    pub fn new(data: Option<&'static F::FilterData>) -> Self {
68        Self { data }
69    }
70
71    /// # Safety
72    ///
73    /// Both pointers must be valid for a `VapourSynth` plugin registration call.
74    pub unsafe fn register(self, plugin: *mut ffi::VSPlugin, vspapi: *const ffi::VSPLUGINAPI) {
75        use super::internal::FilterExtern;
76
77        unsafe {
78            ((*vspapi).registerFunction)(
79                F::NAME.as_ptr(),
80                F::ARGS.as_ptr(),
81                F::RETURN_TYPE.as_ptr(),
82                F::filter_create,
83                self.data
84                    .map_or(null_mut(), |data| from_ref(data).cast_mut().cast()),
85                plugin,
86            )
87        };
88    }
89}
90
91pub type ActivationReason = ffi::VSActivationReason;