Skip to main content

vapoursynth4_rs/
node.rs

1/*
2 This Source Code Form is subject to the terms of the Mozilla Public
3 License, v. 2.0. If a copy of the MPL was not distributed with this
4 file, You can obtain one at http://mozilla.org/MPL/2.0/.
5*/
6
7mod dependency;
8mod filter;
9pub(crate) mod internal;
10
11use std::ffi::{CStr, CString, c_void};
12
13use crate::{
14    AudioInfo, VideoInfo,
15    api::Api,
16    core::CoreHandle,
17    ffi,
18    frame::{AudioFrame, Frame, FrameContext, VideoFrame, internal::FrameFromPtr},
19    node::internal::FilterExtern,
20};
21
22pub use dependency::*;
23pub use filter::*;
24use vapoursynth4_sys::VSFrameDoneCallback;
25
26pub trait Node: Sized + Send + Sync + crate::_private::Sealed {
27    type FrameType: Frame;
28
29    fn api(&self) -> Api;
30
31    #[must_use]
32    fn as_ptr(&self) -> *mut ffi::VSNode;
33
34    #[must_use]
35    fn get_frame_filter(&self, n: i32, ctx: &mut FrameContext) -> Self::FrameType;
36
37    /// Returns whether the data resides in host or GPU memory.
38    #[cfg(feature = "vs-43")]
39    #[must_use]
40    fn residency(&self) -> ffi::VSNodeResidency {
41        unsafe { (self.api().getNodeResidency)(self.as_ptr()) }
42    }
43
44    fn set_linear_filter(&mut self) -> i32 {
45        unsafe { (self.api().setLinearFilter)(self.as_ptr()) }
46    }
47
48    fn set_cache_mode(&mut self, mode: CacheMode) {
49        unsafe {
50            (self.api().setCacheMode)(self.as_ptr(), mode);
51        }
52    }
53
54    fn set_cache_options(&mut self, fixed_size: i32, max_size: i32, max_history_size: i32) {
55        unsafe {
56            (self.api().setCacheOptions)(self.as_ptr(), fixed_size, max_size, max_history_size);
57        }
58    }
59
60    /// # Errors
61    ///
62    /// Return the internal error message if the frame is not ready.
63    fn get_frame(&self, n: i32) -> Result<Self::FrameType, CString> {
64        let mut buf = [0; 1024];
65        let ptr = unsafe { (self.api().getFrame)(n, self.as_ptr(), buf.as_mut_ptr(), 1024) };
66
67        if ptr.is_null() {
68            Err(unsafe { CStr::from_ptr(buf.as_ptr()).into() })
69        } else {
70            unsafe { Ok(Self::FrameType::from_ptr(ptr, self.api())) }
71        }
72    }
73
74    // TODO: Find a better way to handle callbacks
75    /// # Safety
76    ///
77    /// The caller must ensure that:
78    /// - `data` is a valid pointer to the data needed by the callback
79    /// - `callback` is a valid function pointer that safely handles the frame data
80    /// - The callback and data remain valid until the frame processing is complete
81    unsafe fn get_frame_async(&self, n: i32, data: *mut c_void, callback: VSFrameDoneCallback) {
82        unsafe {
83            (self.api().getFrameAsync)(n, self.as_ptr(), callback, data);
84        }
85    }
86
87    /// Name of the function that created this filter.
88    ///
89    /// `level` 0 is the creating function itself; higher levels walk up to the
90    /// function that invoked it. Returns [`None`] for a non-existent level.
91    ///
92    /// Only meaningful on a core built with
93    /// [`enable_graph_inspection()`](crate::core::CoreBuilder::enable_graph_inspection),
94    /// and not safe to call concurrently with frame requests.
95    #[cfg(feature = "vs-graph")]
96    #[must_use]
97    fn creation_function_name(&self, level: i32) -> Option<&CStr> {
98        unsafe {
99            to_cstr((self.api().getNodeCreationFunctionName)(
100                self.as_ptr(),
101                level,
102            ))
103        }
104    }
105
106    /// Identifier of the plugin that created this filter.
107    ///
108    /// See [`creation_function_name()`](Self::creation_function_name) for `level`
109    /// and for the constraints on when this may be called.
110    #[cfg(feature = "vs-graph")]
111    #[must_use]
112    fn creation_plugin_id(&self, level: i32) -> Option<&CStr> {
113        unsafe { to_cstr((self.api().getNodeCreationPluginID)(self.as_ptr(), level)) }
114    }
115
116    /// Namespace of the plugin that created this filter.
117    ///
118    /// See [`creation_function_name()`](Self::creation_function_name) for `level`
119    /// and for the constraints on when this may be called.
120    #[cfg(feature = "vs-graph")]
121    #[must_use]
122    fn creation_plugin_namespace(&self, level: i32) -> Option<&CStr> {
123        unsafe { to_cstr((self.api().getNodeCreationPluginNS)(self.as_ptr(), level)) }
124    }
125
126    /// Arguments passed to the function that created this filter.
127    ///
128    /// See [`creation_function_name()`](Self::creation_function_name) for `level`
129    /// and for the constraints on when this may be called.
130    #[cfg(feature = "vs-graph")]
131    #[must_use]
132    fn creation_function_arguments(&self, level: i32) -> Option<crate::map::MapRef<'_>> {
133        let ptr = unsafe { (self.api().getNodeCreationFunctionArguments)(self.as_ptr(), level) };
134        (!ptr.is_null()).then(|| unsafe { crate::map::MapRef::from_ptr(ptr, self.api()) })
135    }
136}
137
138/// The graph inspection functions return strings owned by the node, so the
139/// result borrows from `self` rather than being copied out.
140#[cfg(feature = "vs-graph")]
141unsafe fn to_cstr<'a>(ptr: *const std::ffi::c_char) -> Option<&'a CStr> {
142    (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) })
143}
144
145#[derive(Debug, PartialEq, Eq, Hash)]
146pub struct VideoNode {
147    handle: *const ffi::VSNode,
148    api: Api,
149}
150
151impl crate::_private::Sealed for VideoNode {}
152unsafe impl Send for VideoNode {}
153unsafe impl Sync for VideoNode {}
154
155impl Node for VideoNode {
156    type FrameType = VideoFrame;
157
158    #[inline]
159    fn api(&self) -> Api {
160        self.api
161    }
162
163    #[inline]
164    fn as_ptr(&self) -> *mut ffi::VSNode {
165        self.handle.cast_mut()
166    }
167
168    fn get_frame_filter(&self, n: i32, ctx: &mut FrameContext) -> Self::FrameType {
169        unsafe {
170            VideoFrame::from_ptr(
171                (self.api.getFrameFilter)(n, self.as_ptr(), ctx.as_ptr()),
172                self.api,
173            )
174        }
175    }
176}
177
178impl VideoNode {
179    /// # Safety
180    ///
181    /// The caller must ensure that `ptr` is a valid pointer to a [`ffi::VSNode`] that represents a video node.
182    #[must_use]
183    pub unsafe fn from_ptr(ptr: *mut ffi::VSNode, api: Api) -> Self {
184        Self { handle: ptr, api }
185    }
186
187    #[must_use]
188    pub fn info(&self) -> &VideoInfo {
189        // SAFETY: `vi` is valid if the node is a video node
190        unsafe { &*(self.api.getVideoInfo)(self.as_ptr()) }
191    }
192
193    /// # Panics
194    ///
195    /// Panics if the the dependency index is larger than [`i32::MAX`].
196    pub fn new<F: Filter>(
197        name: &str,
198        info: &VideoInfo,
199        filter: F,
200        dependencies: &[ffi::VSFilterDependency],
201        core: &CoreHandle,
202    ) -> Option<Self> {
203        let filter = Box::new(filter);
204        let name = CString::new(name).ok()?;
205        let create = core::cfg_select! {
206            feature = "vs-43" => core.api().createVideoFilterEx2,
207            _ => core.api().createVideoFilter2,
208        };
209        let ptr = unsafe {
210            create(
211                name.as_ptr(),
212                info,
213                F::filter_get_frame,
214                Some(F::filter_free),
215                F::FILTER_MODE,
216                #[cfg(feature = "vs-43")]
217                F::FLAGS,
218                dependencies.as_ptr(),
219                dependencies.len().try_into().unwrap(),
220                Box::into_raw(filter).cast(),
221                core.as_ptr(),
222            )
223        };
224        (!ptr.is_null()).then(|| unsafe { Self::from_ptr(ptr, core.api()) })
225    }
226}
227
228impl Clone for VideoNode {
229    fn clone(&self) -> Self {
230        unsafe { Self::from_ptr((self.api.addNodeRef)(self.as_ptr()), self.api) }
231    }
232}
233
234impl Drop for VideoNode {
235    fn drop(&mut self) {
236        unsafe { (self.api.freeNode)(self.as_ptr()) }
237    }
238}
239
240#[derive(PartialEq, Eq, Hash, Debug)]
241pub struct AudioNode {
242    handle: *const ffi::VSNode,
243    api: Api,
244}
245
246impl crate::_private::Sealed for AudioNode {}
247unsafe impl Send for AudioNode {}
248unsafe impl Sync for AudioNode {}
249
250impl Node for AudioNode {
251    type FrameType = AudioFrame;
252
253    #[inline]
254    fn api(&self) -> Api {
255        self.api
256    }
257
258    #[inline]
259    fn as_ptr(&self) -> *mut ffi::VSNode {
260        self.handle.cast_mut()
261    }
262
263    fn get_frame_filter(&self, n: i32, ctx: &mut FrameContext) -> Self::FrameType {
264        unsafe {
265            AudioFrame::from_ptr(
266                (self.api.getFrameFilter)(n, self.as_ptr(), ctx.as_ptr()),
267                self.api,
268            )
269        }
270    }
271}
272
273impl AudioNode {
274    /// # Safety
275    ///
276    /// The caller must ensure that `ptr` is a valid pointer to a [`ffi::VSNode`] that represents an audio node.
277    #[must_use]
278    pub unsafe fn from_ptr(ptr: *mut ffi::VSNode, api: Api) -> Self {
279        Self { handle: ptr, api }
280    }
281
282    #[must_use]
283    pub fn info(&self) -> &AudioInfo {
284        // SAFETY: `ai` is valid if the node is an audio node
285        unsafe { &*(self.api.getAudioInfo)(self.as_ptr()) }
286    }
287
288    /// # Panics
289    ///
290    /// Panics if the the dependency index is larger than [`i32::MAX`].
291    pub fn new<F: Filter>(
292        name: &str,
293        info: &AudioInfo,
294        filter: F,
295        dependencies: &[ffi::VSFilterDependency],
296        core: &CoreHandle,
297    ) -> Option<Self> {
298        let filter = Box::new(filter);
299        let name = CString::new(name).ok()?;
300        let ptr = unsafe {
301            (core.api().createAudioFilter2)(
302                name.as_ptr(),
303                info,
304                F::filter_get_frame,
305                Some(F::filter_free),
306                F::FILTER_MODE,
307                dependencies.as_ptr(),
308                dependencies.len().try_into().unwrap(),
309                Box::into_raw(filter).cast(),
310                core.as_ptr(),
311            )
312        };
313        ptr.is_null()
314            .then_some(unsafe { Self::from_ptr(ptr, core.api()) })
315    }
316}
317
318impl Clone for AudioNode {
319    fn clone(&self) -> Self {
320        unsafe { Self::from_ptr((self.api.addNodeRef)(self.as_ptr()), self.api) }
321    }
322}
323
324impl Drop for AudioNode {
325    fn drop(&mut self) {
326        unsafe { (self.api.freeNode)(self.as_ptr()) }
327    }
328}
329
330pub type FilterMode = ffi::VSFilterMode;
331pub type CacheMode = ffi::VSCacheMode;
332
333#[cfg(all(test, feature = "link-vs"))]
334mod tests {
335    use std::{ffi::c_char, sync::mpsc, time::Duration};
336
337    use super::*;
338    use crate::core::Core;
339
340    type FrameResult = Result<VideoFrame, CString>;
341
342    unsafe extern "system-unwind" fn complete(
343        data: *mut c_void,
344        frame: *const ffi::VSFrame,
345        _: i32,
346        _: *mut ffi::VSNode,
347        error: *const c_char,
348    ) {
349        unsafe {
350            let sender = Box::from_raw(data.cast::<mpsc::Sender<FrameResult>>());
351            let result = if frame.is_null() {
352                Err(CStr::from_ptr(error).into())
353            } else {
354                Ok(VideoFrame::from_ptr(frame, Api::default()))
355            };
356            let _ = sender.send(result);
357        }
358    }
359
360    #[test]
361    fn async_frame_requests_deliver_success_and_failure() -> testresult::TestResult {
362        let core = Core::builder().disable_auto_loading().build();
363        let plugin = core.get_plugin_by_namespace(c"std").unwrap();
364        let output = plugin.invoke(c"BlankClip", core.create_map());
365        let mut node = output.get_video_node(crate::key!(c"clip"), 0)?;
366        node.set_cache_mode(CacheMode::ForceEnable);
367        node.set_cache_options(0, 4, 2);
368        node.set_linear_filter();
369
370        for n in [0, node.info().num_frames] {
371            let (sender, receiver) = mpsc::channel::<FrameResult>();
372            unsafe {
373                node.get_frame_async(n, Box::into_raw(Box::new(sender)).cast(), complete);
374            }
375            let result = receiver.recv_timeout(Duration::from_secs(10))?;
376            if n == 0 {
377                assert_eq!(result.unwrap().frame_width(0), node.info().width);
378            } else {
379                assert_ne!(result.unwrap_err().as_bytes(), b"");
380            }
381        }
382        Ok(())
383    }
384}