Skip to main content

vapoursynth4_rs/
sciprt.rs

1use std::{
2    ffi::{CStr, c_int},
3    mem::ManuallyDrop,
4    ptr::{NonNull, null_mut},
5};
6
7use thiserror::Error;
8use vapoursynth4_sys::VAPOURSYNTH_API_VERSION;
9
10use crate::{
11    api::{Api, VssApi},
12    core::{Core, CoreRef},
13    node::{AudioNode, VideoNode},
14};
15
16use super::ffi;
17#[cfg(feature = "vsscript-44")]
18use crate::map::Map;
19
20#[derive(Debug, PartialEq, Eq, Hash)]
21pub struct Script {
22    handle: NonNull<ffi::VSScript>,
23    vssapi: VssApi,
24    api: Api,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Hash)]
28pub enum OutputNode {
29    Audio(AudioNode),
30    Video(VideoNode),
31}
32
33impl OutputNode {
34    #[must_use]
35    pub fn as_audio(&self) -> Option<&AudioNode> {
36        if let OutputNode::Audio(node) = self {
37            Some(node)
38        } else {
39            None
40        }
41    }
42
43    #[must_use]
44    pub fn as_video(&self) -> Option<&VideoNode> {
45        if let OutputNode::Video(node) = self {
46            Some(node)
47        } else {
48            None
49        }
50    }
51}
52
53impl Script {
54    /// Creates a new script instance.
55    ///
56    /// A supplied core is transferred to `VSScript`. Pass `None` to use a default core.
57    ///
58    /// # Panics
59    ///
60    /// Panics if the `VapourSynth` API version is unavailable or script creation fails.
61    #[must_use]
62    pub fn new(core: Option<Core>, vssapi: VssApi) -> Self {
63        unsafe {
64            let api_ptr = (vssapi.getVSAPI)(VAPOURSYNTH_API_VERSION);
65            assert!(!api_ptr.is_null(), "VapourSynth API version unavailable");
66            let api = Api::from_ptr(api_ptr);
67            // createScript takes ownership even if it returns null.
68            let core = core.map_or(null_mut(), |core| ManuallyDrop::new(core).as_ptr());
69            let handle =
70                NonNull::new((vssapi.createScript)(core)).expect("Failed to create script");
71            Self {
72                handle,
73                vssapi,
74                api,
75            }
76        }
77    }
78
79    #[must_use]
80    pub fn get_api(&self) -> Api {
81        self.api
82    }
83
84    /// Returns a reference to the core associated with this script.
85    ///
86    /// # Errors
87    ///
88    /// Returns an error message if the core could not be retrieved.
89    pub fn core(&self) -> Result<CoreRef<'_>, ScriptError> {
90        unsafe {
91            let core = (self.vssapi.getCore)(self.handle.as_ptr());
92            self.get_ptr_error(core)
93                .map(|core| CoreRef::from_ptr(core, self.api))
94        }
95    }
96
97    /// Evaluates a script buffer with the given filename.
98    ///
99    /// # Errors
100    ///
101    /// Returns an error message if the script evaluation fails.
102    pub fn evaluate(&self, buffer: &CStr, filename: &CStr) -> Result<(), ScriptError> {
103        unsafe {
104            let result = (self.vssapi.evaluateBuffer)(
105                self.handle.as_ptr(),
106                buffer.as_ptr(),
107                filename.as_ptr(),
108            );
109            self.get_error(result)
110        }
111    }
112
113    /// Evaluates a script from a file.
114    ///
115    /// # Errors
116    ///
117    /// Returns an error message if the script evaluation fails.
118    pub fn evaluate_file(&self, filename: &CStr) -> Result<(), ScriptError> {
119        unsafe {
120            let result = (self.vssapi.evaluateFile)(self.handle.as_ptr(), filename.as_ptr());
121            self.get_error(result)
122        }
123    }
124
125    /// Gets the output node at the specified index.
126    ///
127    /// # Errors
128    ///
129    /// Returns a `ScriptError` if the output node could not be retrieved.
130    pub fn get_output(&self, index: c_int) -> Result<OutputNode, ScriptError> {
131        unsafe {
132            let ptr =
133                self.get_ptr_error((self.vssapi.getOutputNode)(self.handle.as_ptr(), index))?;
134            Ok(self.output_from_ptr(ptr))
135        }
136    }
137
138    /// Gets an output node, using a bitmask of [`ffi::VSScriptGetFlags`].
139    /// Pass 0 to download GPU output or `AllowGPUResident` to preserve residency.
140    /// Release the returned node before this script.
141    ///
142    /// # Errors
143    ///
144    /// Returns a `ScriptError` if the output is unset or could not be retrieved.
145    #[cfg(feature = "vsscript-44")]
146    pub fn get_output_ex(&self, index: c_int, flags: c_int) -> Result<OutputNode, ScriptError> {
147        unsafe {
148            let ptr = self.get_ptr_error((self.vssapi.getOutputNodeEx)(
149                self.handle.as_ptr(),
150                index,
151                flags,
152            ))?;
153            Ok(self.output_from_ptr(ptr))
154        }
155    }
156
157    /// Gets an alpha output using a bitmask of [`ffi::VSScriptGetFlags`].
158    /// Pass 0 to download GPU output or `AllowGPUResident` to preserve residency.
159    /// Release the returned node before this script.
160    ///
161    /// # Errors
162    ///
163    /// Returns a `ScriptError` if the alpha output is unset or unavailable.
164    #[cfg(feature = "vsscript-44")]
165    pub fn get_output_alpha_ex(
166        &self,
167        index: c_int,
168        flags: c_int,
169    ) -> Result<VideoNode, ScriptError> {
170        unsafe {
171            let ptr = self.get_ptr_error((self.vssapi.getOutputAlphaNodeEx)(
172                self.handle.as_ptr(),
173                index,
174                flags,
175            ))?;
176            Ok(VideoNode::from_ptr(ptr, self.api))
177        }
178    }
179
180    /// Lists output indices using a bitmask of [`ffi::VSScriptGetFlags`].
181    ///
182    /// # Errors
183    ///
184    /// Returns a `ScriptError` if output enumeration fails.
185    #[cfg(feature = "vsscript-44")]
186    pub fn get_available_outputs_ex(&self, flags: c_int) -> Result<Vec<c_int>, ScriptError> {
187        let count = unsafe {
188            (self.vssapi.getAvailableOutputNodesEx)(self.handle.as_ptr(), 0, null_mut(), flags)
189        };
190        let len = usize::try_from(count).map_err(|_| unsafe { ScriptError::from_vss(self) })?;
191        let mut outputs = vec![0; len];
192        let count = unsafe {
193            (self.vssapi.getAvailableOutputNodesEx)(
194                self.handle.as_ptr(),
195                count,
196                outputs.as_mut_ptr(),
197                flags,
198            )
199        };
200        outputs
201            .truncate(usize::try_from(count).map_err(|_| unsafe { ScriptError::from_vss(self) })?);
202        Ok(outputs)
203    }
204
205    /// Copies a script variable into `dst` under its name.
206    /// `flags` is a bitmask of [`ffi::VSScriptGetFlags`]. With no flags GPU nodes
207    /// are downloaded and GPU frame variables are rejected. `AllowGPUResident`
208    /// preserves the residency of nodes and frames.
209    ///
210    /// # Errors
211    ///
212    /// Returns a `ScriptError` if the variable is missing or cannot be stored.
213    #[cfg(feature = "vsscript-44")]
214    pub fn get_variable_ex(
215        &self,
216        name: &CStr,
217        dst: &mut Map,
218        flags: c_int,
219    ) -> Result<(), ScriptError> {
220        let result = unsafe {
221            (self.vssapi.getVariableEx)(self.handle.as_ptr(), name.as_ptr(), dst.as_ptr(), flags)
222        };
223        self.get_error(result)
224    }
225}
226
227// MARK: Helper
228impl Script {
229    unsafe fn output_from_ptr(&self, ptr: *mut ffi::VSNode) -> OutputNode {
230        unsafe {
231            match (self.api.getNodeType)(ptr) {
232                ffi::VSMediaType::Audio => OutputNode::Audio(AudioNode::from_ptr(ptr, self.api)),
233                ffi::VSMediaType::Video => OutputNode::Video(VideoNode::from_ptr(ptr, self.api)),
234            }
235        }
236    }
237
238    fn get_error(&self, ret: c_int) -> Result<(), ScriptError> {
239        if ret == 0 {
240            Ok(())
241        } else {
242            Err(unsafe { ScriptError::from_vss(self) })
243        }
244    }
245
246    fn get_ptr_error<T>(&self, ptr: *mut T) -> Result<*mut T, ScriptError> {
247        if ptr.is_null() {
248            Err(unsafe { ScriptError::from_vss(self) })
249        } else {
250            Ok(ptr)
251        }
252    }
253}
254
255impl Drop for Script {
256    fn drop(&mut self) {
257        unsafe { (self.vssapi.freeScript)(self.handle.as_ptr()) };
258    }
259}
260
261#[cfg(feature = "link-vsscript")]
262impl Default for Script {
263    fn default() -> Self {
264        Self::new(None, VssApi::default())
265    }
266}
267
268// MARK: ScriptError
269
270#[derive(Debug, Clone, PartialEq, Eq, Hash, Error)]
271#[error("VSScript error: {0}")]
272pub struct ScriptError(String);
273
274impl ScriptError {
275    unsafe fn from_vss(vss: &Script) -> Self {
276        unsafe {
277            let error = (vss.vssapi.getError)(vss.handle.as_ptr());
278            Self(if error.is_null() {
279                "Script operation failed without an error message".into()
280            } else {
281                CStr::from_ptr(error).to_string_lossy().into_owned()
282            })
283        }
284    }
285}
286
287#[cfg(all(test, feature = "link-vs", feature = "link-vsscript"))]
288#[test]
289fn script_uses_the_supplied_core() {
290    let core = Core::builder()
291        .disable_auto_loading()
292        .thread_count(2)
293        .build();
294    let ptr = core.as_ptr();
295    let script = Script::new(Some(core), VssApi::default());
296    let borrowed = script.core().unwrap();
297    assert_eq!(borrowed.as_ptr(), ptr);
298    assert_eq!(borrowed.get_info().num_threads, 2);
299}
300
301#[cfg(all(test, feature = "link-vsscript", feature = "vsscript-44"))]
302mod tests {
303    use super::*;
304    use crate::map::KeyStr;
305    use crate::node::Node;
306
307    #[test]
308    fn map_media_transfers_check_type_and_keep_references() -> testresult::TestResult {
309        use crate::{
310            key,
311            map::{AppendMode, MapPropertyError, Value},
312        };
313
314        let script = Script::default();
315        script.evaluate(
316            c"import vapoursynth as vs\nvs.core.std.BlankAudio().set_output(0)\nvs.core.std.BlankClip(width=16, height=16).set_output(1)\n",
317            c"map-media.vpy",
318        )?;
319        let audio = script.get_output_ex(0, 0)?;
320        let video = script.get_output_ex(1, 0)?;
321        let audio = audio.as_audio().unwrap().clone();
322        let video = video.as_video().unwrap().clone();
323        let audio_frame = audio.get_frame(0).unwrap();
324        let video_frame = video.get_frame(0).unwrap();
325
326        let audio_key = key!(c"audio");
327        let video_key = key!(c"video");
328        let mut map = script.core()?.create_map();
329        let replace = AppendMode::Replace;
330        macro_rules! check_nodes {
331            ($map:expr) => {{
332                let view = $map;
333                assert!(matches!(view.get(audio_key, 0)?, Value::AudioNode(_)));
334                assert!(matches!(view.get(video_key, 0)?, Value::VideoNode(_)));
335                assert!(matches!(
336                    view.get_video_node(audio_key, 0),
337                    Err(MapPropertyError::InvalidType)
338                ));
339                assert!(matches!(
340                    view.get_audio_node(video_key, 0),
341                    Err(MapPropertyError::InvalidType)
342                ));
343            }};
344        }
345        macro_rules! check_frames {
346            ($map:expr) => {{
347                let view = $map;
348                assert!(matches!(view.get(audio_key, 0)?, Value::AudioFrame(_)));
349                assert!(matches!(view.get(video_key, 0)?, Value::VideoFrame(_)));
350                assert!(matches!(
351                    view.get_video_frame(audio_key, 0),
352                    Err(MapPropertyError::InvalidType)
353                ));
354                assert!(matches!(
355                    view.get_audio_frame(video_key, 0),
356                    Err(MapPropertyError::InvalidType)
357                ));
358            }};
359        }
360
361        map.set(audio_key, Value::AudioNode(audio.clone()), replace)?;
362        map.set(video_key, Value::VideoNode(video.clone()), replace)?;
363        check_nodes!(&map);
364        map.as_mut()
365            .set(audio_key, Value::AudioNode(audio.clone()), replace)?;
366        map.as_mut()
367            .set(video_key, Value::VideoNode(video.clone()), replace)?;
368        check_nodes!(map.as_ref());
369        map.consume_node(audio_key, audio.clone(), replace)?;
370        map.consume_node(video_key, video.clone(), replace)?;
371        map.as_mut().consume_node(audio_key, audio, replace)?;
372        map.as_mut().consume_node(video_key, video, replace)?;
373        check_nodes!(map.as_mut());
374
375        map.set(audio_key, Value::AudioFrame(audio_frame.clone()), replace)?;
376        map.set(video_key, Value::VideoFrame(video_frame.clone()), replace)?;
377        check_frames!(&map);
378        map.as_mut()
379            .set(audio_key, Value::AudioFrame(audio_frame.clone()), replace)?;
380        map.as_mut()
381            .set(video_key, Value::VideoFrame(video_frame.clone()), replace)?;
382        check_frames!(map.as_ref());
383        map.consume_frame(audio_key, audio_frame.clone(), replace)?;
384        map.consume_frame(video_key, video_frame.clone(), replace)?;
385        map.as_mut()
386            .consume_frame(audio_key, audio_frame, replace)?;
387        map.as_mut()
388            .consume_frame(video_key, video_frame, replace)?;
389        check_frames!(map.as_mut());
390
391        let audio = map.get_audio_frame(audio_key, 0)?;
392        let video = map.get_video_frame(video_key, 0)?;
393        drop(map);
394        assert!(audio.frame_length() > 0);
395        assert_eq!(video.frame_width(0), 16);
396        Ok(())
397    }
398
399    #[test]
400    fn api_44_audio_output() -> testresult::TestResult {
401        let script = Script::default();
402        script.evaluate(
403            c"import vapoursynth as vs\nvs.core.std.BlankAudio().set_output(3)\n",
404            c"audio.vpy",
405        )?;
406        assert_eq!(script.get_available_outputs_ex(0)?, [3]);
407        let output = script.get_output_ex(3, 0)?;
408        assert!(output.as_video().is_none());
409        assert!(
410            output
411                .as_audio()
412                .ok_or("Expected audio output")?
413                .info()
414                .num_samples
415                > 0
416        );
417        assert!(script.get_output_alpha_ex(3, 0).is_err());
418        Ok(())
419    }
420
421    #[test]
422    fn video_filter_delivers_frames_and_reports_failures() -> testresult::TestResult {
423        use crate::{
424            frame::{FrameContext, VideoFrame},
425            map::{MapMut, MapRef},
426            node::{ActivationReason, Dependencies, Filter},
427        };
428        use std::ffi::c_void;
429
430        struct Passthrough(VideoNode);
431
432        impl Filter for Passthrough {
433            type Error = &'static CStr;
434            type FrameType = VideoFrame;
435            type FilterData = ();
436            const NAME: &'static CStr = c"Passthrough";
437            const ARGS: &'static CStr = c"";
438            const RETURN_TYPE: &'static CStr = c"clip:vnode;";
439
440            fn create(_: MapRef, _: MapMut, _: Option<&()>, _: CoreRef) -> Result<(), Self::Error> {
441                Err(c"Construct this filter directly")
442            }
443
444            fn get_frame(
445                &self,
446                n: i32,
447                reason: ActivationReason,
448                _: *mut *mut c_void,
449                mut ctx: FrameContext,
450                _: CoreRef,
451            ) -> Result<Option<VideoFrame>, Self::Error> {
452                match reason {
453                    ActivationReason::Initial => ctx.request_frame_filter(n, &self.0),
454                    ActivationReason::AllFramesReady => {
455                        return match n {
456                            0 => Ok(Some(self.0.get_frame_filter(n, &mut ctx))),
457                            1 => Err(c"frame error"),
458                            _ => panic!("frame panic"),
459                        };
460                    }
461                    ActivationReason::Error => {}
462                }
463                Ok(None)
464            }
465        }
466
467        let script = Script::default();
468        script.evaluate(
469            c"import vapoursynth as vs\nvs.core.std.BlankClip(width=16, height=16, length=3).set_output(0)\n",
470            c"filter.vpy",
471        )?;
472        let OutputNode::Video(source) = script.get_output_ex(0, 0)? else {
473            return Err("Expected video output".into());
474        };
475        let info = source.info().clone();
476        let dependencies = [ffi::VSFilterDependency {
477            source: source.as_ptr(),
478            request_pattern: ffi::VSRequestPattern::StrictSpatial,
479        }];
480        let core = script.core()?;
481        let mut output = core.create_map();
482        core.create_video_filter(
483            &mut output.as_mut(),
484            c"Passthrough",
485            &info,
486            Box::new(Passthrough(source.clone())),
487            Dependencies::new(&dependencies).unwrap(),
488        );
489        let mapped = output.get_video_node(crate::key!(c"clip"), 0)?;
490        drop(output);
491        assert_eq!(mapped.get_frame(0).unwrap().frame_width(0), 16);
492
493        let node = VideoNode::new(
494            "Passthrough",
495            &info,
496            Passthrough(source),
497            &dependencies,
498            &core,
499        )
500        .ok_or("Could not create passthrough filter")?;
501        let frame = node.get_frame(0).expect("Passthrough frame");
502        assert_eq!(frame.frame_width(0), 16);
503        assert_eq!(frame.frame_height(0), 16);
504        assert_eq!(node.get_frame(1).unwrap_err().as_c_str(), c"frame error");
505        #[cfg(panic = "unwind")]
506        assert_eq!(
507            node.get_frame(2).unwrap_err().as_c_str(),
508            c"Rust filter panicked: frame panic"
509        );
510        Ok(())
511    }
512
513    #[test]
514    fn api_44_accessors() -> testresult::TestResult {
515        let script = Script::default();
516        assert_eq!(script.get_available_outputs_ex(0)?, Vec::<c_int>::new());
517        script.evaluate(c"import vapoursynth as vs\nclip = vs.core.std.BlankClip(width=16, height=16, length=1, format=vs.RGB24)\nalpha = vs.core.std.BlankClip(clip, format=vs.GRAY8)\nclip.set_output(0, alpha=alpha)\nclip.set_output(2)\nvalue = 42\n", c"api44.vpy")?;
518        let mut variables = script.core()?.create_map();
519        for flags in [0, ffi::VSScriptGetFlags::AllowGPUResident as c_int] {
520            assert_eq!(script.get_available_outputs_ex(flags)?, vec![0, 2]);
521            let output = script.get_output_ex(0, flags)?;
522            assert_eq!(output.as_video().unwrap().info().width, 16);
523            let alpha = script.get_output_alpha_ex(0, flags)?;
524            assert_eq!(alpha.info().width, 16);
525            #[cfg(feature = "vs-43")]
526            {
527                assert_eq!(
528                    output.as_video().unwrap().residency(),
529                    ffi::VSNodeResidency::CPU
530                );
531                assert_eq!(alpha.residency(), ffi::VSNodeResidency::CPU);
532            }
533            script.get_variable_ex(c"value", &mut variables, flags)?;
534            assert_eq!(variables.get_int(KeyStr::from_cstr(c"value"), 0)?, 42);
535            script.get_variable_ex(c"clip", &mut variables, flags)?;
536            assert!(script.get_output_ex(99, flags).is_err());
537            assert!(script.get_output_alpha_ex(2, flags).is_err());
538            assert!(
539                script
540                    .get_variable_ex(c"missing", &mut variables, flags)
541                    .is_err()
542            );
543        }
544        assert!(script.get_output(99).is_err());
545        Ok(())
546    }
547
548    #[cfg(feature = "vulkan")]
549    #[test]
550    fn api_44_gpu_residency() -> testresult::TestResult {
551        let script = Script::default();
552        let api = script.get_api();
553        let mut info = std::mem::MaybeUninit::<ffi::VSVulkanCoreInfo>::uninit();
554        let mut error = [0; 1024];
555        let status = unsafe {
556            (api.vulkan().getVulkanCoreInfo)(
557                script.core()?.as_ptr(),
558                info.as_mut_ptr(),
559                error.as_mut_ptr(),
560                1024,
561            )
562        };
563        if status != 0 {
564            let error = unsafe { CStr::from_ptr(error.as_ptr()) }.to_string_lossy();
565            if std::env::var_os("VAPOURSYNTH_REQUIRE_VULKAN").is_some() {
566                return Err(format!("Vulkan initialization failed: {error}").into());
567            }
568            eprintln!("Skipping GPU residency test: {error}");
569            return Ok(());
570        }
571        script.evaluate(c"import vapoursynth as vs\nclip = vs.core.std.BlankClip(width=16, height=16, length=1, format=vs.GRAY8, color=[42])\ngpu = vs.core.std.GPUUpload(clip)\ngpu.set_output(0, alpha=gpu)\ngpu_frame = gpu.get_frame(0)\n", c"api44_gpu.vpy")?;
572        let allow_gpu = ffi::VSScriptGetFlags::AllowGPUResident as c_int;
573        for (flags, residency) in [
574            (0, ffi::VSNodeResidency::CPU),
575            (allow_gpu, ffi::VSNodeResidency::GPU),
576        ] {
577            let output = script.get_output_ex(0, flags)?;
578            let node = output.as_video().unwrap();
579            assert_eq!(node.residency(), residency);
580            assert_eq!(script.get_output_alpha_ex(0, flags)?.residency(), residency);
581            let frame = node
582                .get_frame(0)
583                .map_err(|error| error.to_string_lossy().into_owned())?;
584            assert_eq!(frame.residency(), residency);
585            if residency == ffi::VSNodeResidency::CPU {
586                assert_eq!(unsafe { frame.plane(0).read() }, 42);
587            }
588            let mut variables = script.core()?.create_map();
589            script.get_variable_ex(c"gpu", &mut variables, flags)?;
590            assert_eq!(
591                variables
592                    .get_video_node(KeyStr::from_cstr(c"gpu"), 0)?
593                    .residency(),
594                residency
595            );
596        }
597        let mut variables = script.core()?.create_map();
598        assert!(
599            script
600                .get_variable_ex(c"gpu_frame", &mut variables, 0)
601                .is_err()
602        );
603        variables.clear();
604        script.get_variable_ex(c"gpu_frame", &mut variables, allow_gpu)?;
605        assert_eq!(
606            variables
607                .get_video_frame(KeyStr::from_cstr(c"gpu_frame"), 0)?
608                .residency(),
609            ffi::VSNodeResidency::GPU
610        );
611        Ok(())
612    }
613}