Skip to main content

vapoursynth4_rs/
core.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
7use std::{
8    ffi::CStr,
9    marker::PhantomData,
10    mem::MaybeUninit,
11    ops::Deref,
12    ptr::{NonNull, null_mut},
13};
14
15use bon::bon;
16use core_builder::State;
17
18use crate::{
19    AudioInfo, ColorFamily, SampleType, VideoInfo,
20    api::Api,
21    ffi,
22    frame::{
23        AudioFormat, AudioFrame, AudioFrameMut, FormatName, Frame, VideoFormat, VideoFrame,
24        VideoFrameMut,
25    },
26    function::Function,
27    map::{Map, MapMut},
28    node::{Dependencies, Filter, internal::FilterExtern},
29    plugin::{Plugin, Plugins},
30};
31
32/// A borrowed core supplied by `VapourSynth`.
33#[derive(Debug, PartialEq, Eq, Hash)]
34pub struct CoreRef<'c> {
35    handle: CoreHandle,
36    marker: PhantomData<&'c ()>,
37}
38
39impl CoreRef<'_> {
40    // The core must remain alive for the lifetime of the borrow.
41    #[must_use]
42    pub(crate) unsafe fn from_ptr(ptr: *const ffi::VSCore, api: Api) -> Self {
43        Self {
44            handle: CoreHandle { handle: ptr, api },
45            marker: PhantomData,
46        }
47    }
48}
49
50impl AsRef<CoreHandle> for CoreRef<'_> {
51    fn as_ref(&self) -> &CoreHandle {
52        &self.handle
53    }
54}
55
56impl Deref for CoreRef<'_> {
57    type Target = CoreHandle;
58
59    fn deref(&self) -> &Self::Target {
60        &self.handle
61    }
62}
63
64#[derive(Debug, PartialEq, Eq, Hash)]
65pub struct Core {
66    handle: CoreHandle,
67}
68
69impl Deref for Core {
70    type Target = CoreHandle;
71
72    fn deref(&self) -> &Self::Target {
73        &self.handle
74    }
75}
76
77/// Operations available on both owned and borrowed cores.
78#[derive(Debug, PartialEq, Eq, Hash)]
79pub struct CoreHandle {
80    handle: *const ffi::VSCore,
81    api: Api,
82}
83
84impl CoreHandle {
85    #[must_use]
86    pub fn as_ptr(&self) -> *mut ffi::VSCore {
87        self.handle.cast_mut()
88    }
89
90    #[must_use]
91    pub fn get_info(&self) -> ffi::VSCoreInfo {
92        unsafe {
93            let mut info = MaybeUninit::uninit();
94            (self.api.getCoreInfo)(self.as_ptr(), info.as_mut_ptr());
95            info.assume_init()
96        }
97    }
98
99    /// Same as [`get_info()`](Self::get_info), but also reports the
100    /// [`ffi::VSCoreCreationFlags`] the core was created with.
101    #[cfg(feature = "vs-42")]
102    #[must_use]
103    pub fn get_info2(&self) -> ffi::VSCoreInfo2 {
104        unsafe {
105            let mut info = MaybeUninit::uninit();
106            (self.api.getCoreInfo2)(self.as_ptr(), info.as_mut_ptr());
107            info.assume_init()
108        }
109    }
110
111    /// # Panics
112    ///
113    /// Panic if the `dependencies` has more item than [`i32::MAX`]
114    pub fn create_video_filter<F: Filter>(
115        &self,
116        out: &mut MapMut,
117        name: &CStr,
118        info: &VideoInfo,
119        filter: Box<F>,
120        dependencies: &Dependencies,
121    ) {
122        debug_assert!(!out.as_ptr().is_null());
123        unsafe {
124            (self.api.createVideoFilter)(
125                out.as_ptr(),
126                name.as_ptr(),
127                info,
128                F::filter_get_frame,
129                Some(F::filter_free),
130                F::FILTER_MODE,
131                dependencies.as_ptr(),
132                dependencies.len().try_into().unwrap(),
133                Box::into_raw(filter).cast(),
134                self.as_ptr(),
135            );
136        }
137    }
138
139    /// # Panics
140    ///
141    /// Panic if the `dependencies` has more item than [`i32::MAX`]
142    pub fn create_audio_filter<F: Filter>(
143        &self,
144        out: &mut MapMut,
145        name: &CStr,
146        info: &AudioInfo,
147        filter: F,
148        dependencies: &Dependencies,
149    ) {
150        let filter = Box::new(filter);
151        unsafe {
152            (self.api.createAudioFilter)(
153                out.as_ptr(),
154                name.as_ptr(),
155                info,
156                F::filter_get_frame,
157                Some(F::filter_free),
158                F::FILTER_MODE,
159                dependencies.as_ptr(),
160                dependencies.len().try_into().unwrap(),
161                Box::into_raw(filter).cast(),
162                self.as_ptr(),
163            );
164        }
165    }
166
167    #[must_use]
168    pub fn new_video_frame(
169        &self,
170        format: &VideoFormat,
171        width: i32,
172        height: i32,
173        prop_src: Option<&VideoFrame>,
174    ) -> VideoFrameMut {
175        unsafe {
176            let ptr = (self.api.newVideoFrame)(
177                format,
178                width,
179                height,
180                prop_src.map_or(null_mut(), |f| f.as_ptr().cast()),
181                self.as_ptr(),
182            );
183            VideoFrameMut::from_unique_ptr(ptr, self.api)
184        }
185    }
186
187    /// Calls `VapourSynth`'s video plane assembly without validation.
188    ///
189    /// # Safety
190    ///
191    /// The destination format and size must be valid. Both arrays must contain at
192    /// least `format.num_planes` entries. Each non-null source must be a live
193    /// video frame with a valid plane index, matching dimensions and sample
194    /// storage, and compatible residency and device. Frames must be valid for
195    /// this core's API.
196    #[must_use]
197    pub unsafe fn new_video_frame2(
198        &self,
199        format: &VideoFormat,
200        width: i32,
201        height: i32,
202        plane_src: &[*const ffi::VSFrame],
203        planes: &[i32],
204        prop_src: Option<&VideoFrame>,
205    ) -> VideoFrameMut {
206        unsafe {
207            let ptr = (self.api.newVideoFrame2)(
208                format,
209                width,
210                height,
211                plane_src.as_ptr(),
212                planes.as_ptr(),
213                prop_src.map_or(null_mut(), |f| f.as_ptr().cast()),
214                self.as_ptr(),
215            );
216            VideoFrameMut::from_unique_ptr(ptr, self.api)
217        }
218    }
219
220    #[must_use]
221    pub fn new_audio_frame(
222        &self,
223        format: &AudioFormat,
224        num_samples: i32,
225        prop_src: Option<&AudioFrame>,
226    ) -> AudioFrameMut {
227        unsafe {
228            let ptr = (self.api.newAudioFrame)(
229                format,
230                num_samples,
231                prop_src.map_or(null_mut(), |f| f.as_ptr().cast()),
232                self.as_ptr(),
233            );
234            AudioFrameMut::from_unique_ptr(ptr, self.api)
235        }
236    }
237
238    /// Calls `VapourSynth`'s audio channel assembly without validation.
239    ///
240    /// # Safety
241    ///
242    /// The destination format and sample count must be valid. Both arrays must
243    /// contain at least `format.num_channels` entries. Each non-null source must
244    /// be a live audio frame with a valid channel index and matching sample
245    /// storage and frame length. Frames must be valid for this core's API.
246    #[must_use]
247    pub unsafe fn new_audio_frame2(
248        &self,
249        format: &AudioFormat,
250        num_samples: i32,
251        channel_src: &[*const ffi::VSFrame],
252        channels: &[i32],
253        prop_src: Option<&AudioFrame>,
254    ) -> AudioFrameMut {
255        unsafe {
256            let ptr = (self.api.newAudioFrame2)(
257                format,
258                num_samples,
259                channel_src.as_ptr(),
260                channels.as_ptr(),
261                prop_src.map_or(null_mut(), |f| f.as_ptr().cast()),
262                self.as_ptr(),
263            );
264            AudioFrameMut::from_unique_ptr(ptr, self.api)
265        }
266    }
267
268    #[must_use]
269    pub fn copy_frame<F: Frame>(&self, frame: &F) -> F::Writable {
270        unsafe {
271            F::writable_from_ptr(
272                (self.api.copyFrame)(frame.as_ptr(), self.as_ptr()),
273                self.api,
274            )
275        }
276    }
277
278    /// Returns the format if `VapourSynth` accepts the requested parameters.
279    #[must_use]
280    pub fn query_video_format(
281        &self,
282        color_family: ColorFamily,
283        sample_type: SampleType,
284        bits_per_sample: i32,
285        subsampling_w: i32,
286        subsampling_h: i32,
287    ) -> Option<VideoFormat> {
288        unsafe {
289            let mut format = MaybeUninit::uninit();
290            let success = (self.api.queryVideoFormat)(
291                format.as_mut_ptr(),
292                color_family,
293                sample_type,
294                bits_per_sample,
295                subsampling_w,
296                subsampling_h,
297                self.as_ptr(),
298            );
299            (success != 0).then(|| format.assume_init())
300        }
301    }
302
303    #[must_use]
304    pub fn get_video_format_name(&self, format: &VideoFormat) -> Option<String> {
305        let mut buffer = FormatName::new();
306        if 0 == unsafe { (self.api.getVideoFormatName)(format, buffer.as_mut_ptr().cast()) } {
307            None
308        } else {
309            buffer.as_str().map(str::to_owned)
310        }
311    }
312
313    /// Returns the format if `VapourSynth` accepts the requested parameters.
314    #[must_use]
315    pub fn query_audio_format(
316        &self,
317        sample_type: SampleType,
318        bits_per_sample: i32,
319        channel_layout: u64,
320    ) -> Option<AudioFormat> {
321        unsafe {
322            let mut format = MaybeUninit::uninit();
323            let success = (self.api.queryAudioFormat)(
324                format.as_mut_ptr(),
325                sample_type,
326                bits_per_sample,
327                channel_layout,
328                self.as_ptr(),
329            );
330            (success != 0).then(|| format.assume_init())
331        }
332    }
333
334    #[must_use]
335    pub fn get_audio_format_name(&self, format: &AudioFormat) -> Option<String> {
336        let mut buffer = FormatName::new();
337        if 0 == unsafe { (self.api.getAudioFormatName)(format, buffer.as_mut_ptr().cast()) } {
338            None
339        } else {
340            buffer.as_str().map(str::to_owned)
341        }
342    }
343
344    #[must_use]
345    pub fn query_video_format_id(
346        &self,
347        color_family: ColorFamily,
348        sample_type: SampleType,
349        bits_per_sample: i32,
350        subsampling_w: i32,
351        subsampling_h: i32,
352    ) -> u32 {
353        unsafe {
354            (self.api.queryVideoFormatID)(
355                color_family,
356                sample_type,
357                bits_per_sample,
358                subsampling_w,
359                subsampling_h,
360                self.as_ptr(),
361            )
362        }
363    }
364
365    /// Returns the format if `VapourSynth` recognizes the ID.
366    #[must_use]
367    pub fn get_video_format_by_id(&self, id: u32) -> Option<VideoFormat> {
368        unsafe {
369            let mut format = MaybeUninit::uninit();
370            let success = (self.api.getVideoFormatByID)(format.as_mut_ptr(), id, self.as_ptr());
371            (success != 0).then(|| format.assume_init())
372        }
373    }
374
375    pub fn create_function<T>(
376        &self,
377        func: ffi::VSPublicFunction,
378        data: Box<T>,
379        free: ffi::VSFreeFunctionData,
380    ) -> Function {
381        unsafe {
382            Function::from_ptr(
383                (self.api.createFunction)(func, Box::into_raw(data).cast(), free, self.as_ptr()),
384                self.api,
385            )
386        }
387    }
388
389    #[must_use]
390    pub fn get_plugin_by_id(&self, id: &CStr) -> Option<Plugin> {
391        unsafe {
392            NonNull::new((self.api.getPluginByID)(id.as_ptr(), self.as_ptr()))
393                .map(|p| Plugin::new(p, self.api))
394        }
395    }
396
397    #[must_use]
398    pub fn get_plugin_by_namespace(&self, ns: &CStr) -> Option<Plugin> {
399        unsafe {
400            NonNull::new((self.api.getPluginByNamespace)(ns.as_ptr(), self.as_ptr()))
401                .map(|p| Plugin::new(p, self.api))
402        }
403    }
404
405    #[must_use]
406    pub fn plugins(&self) -> Plugins<'_> {
407        Plugins::new(self)
408    }
409
410    pub fn log(&self, level: ffi::VSMessageType, msg: &CStr) {
411        unsafe {
412            (self.api.logMessage)(level, msg.as_ptr(), self.as_ptr());
413        }
414    }
415    #[must_use]
416    pub fn api(&self) -> Api {
417        self.api
418    }
419
420    #[must_use]
421    pub fn create_map(&self) -> Map {
422        unsafe {
423            let ptr = (self.api.createMap)();
424            Map::from_ptr(ptr, self.api)
425        }
426    }
427}
428
429impl Core {
430    unsafe fn new_with(flags: i32, api: Api) -> Self {
431        let handle = unsafe { (api.createCore)(flags) };
432        Self {
433            handle: CoreHandle { handle, api },
434        }
435    }
436
437    pub fn set_max_cache_size(&mut self, size: i64) {
438        unsafe {
439            (self.api.setMaxCacheSize)(size, self.as_ptr());
440        }
441    }
442
443    pub fn set_thread_count(&mut self, count: i32) {
444        unsafe {
445            (self.api.setThreadCount)(count, self.as_ptr());
446        }
447    }
448}
449
450impl Drop for Core {
451    fn drop(&mut self) {
452        unsafe { (self.api.freeCore)(self.as_ptr()) }
453    }
454}
455
456// MARK: Builder
457
458#[bon]
459impl Core {
460    #[builder]
461    pub fn new(
462        #[builder(field)] flags: i32,
463        max_cache_size: Option<i64>,
464        thread_count: Option<i32>,
465        #[cfg(feature = "link-vs")]
466        #[builder(default)]
467        api: Api,
468        #[cfg(not(feature = "link-vs"))] api: Api,
469    ) -> Self {
470        let mut core = unsafe { Core::new_with(flags, api) };
471        if let Some(size) = max_cache_size {
472            core.set_max_cache_size(size);
473        }
474        if let Some(count) = thread_count {
475            core.set_thread_count(count);
476        }
477
478        core
479    }
480}
481
482impl<S: State> CoreBuilder<S> {
483    pub fn enable_graph_inspection(mut self) -> Self {
484        self.flags |= ffi::VSCoreCreationFlags::EnableGraphInspection as i32;
485        self
486    }
487
488    pub fn disable_auto_loading(mut self) -> Self {
489        self.flags |= ffi::VSCoreCreationFlags::DisableAutoLoading as i32;
490        self
491    }
492
493    pub fn disable_library_unloading(mut self) -> Self {
494        self.flags |= ffi::VSCoreCreationFlags::DisableLibraryUnloading as i32;
495        self
496    }
497
498    /// Log a list of all allocated frames after every completed external frame request.
499    #[cfg(feature = "vs-42")]
500    pub fn enable_frame_ref_debug(mut self) -> Self {
501        self.flags |= ffi::VSCoreCreationFlags::EnableFrameRefDebug as i32;
502        self
503    }
504}
505
506#[cfg(test)]
507#[cfg(feature = "link-vs")]
508mod tests {
509    use super::*;
510
511    #[test]
512    fn format_queries_check_native_results() {
513        let core = Core::builder().disable_auto_loading().build();
514        assert!(
515            core.query_video_format(ColorFamily::Gray, SampleType::Integer, 0, 0, 0)
516                .is_none()
517        );
518        assert!(
519            core.query_audio_format(SampleType::Integer, 16, 0)
520                .is_none()
521        );
522        assert!(core.get_video_format_by_id(u32::MAX).is_none());
523
524        let video = core
525            .query_video_format(ColorFamily::Gray, SampleType::Integer, 8, 0, 0)
526            .unwrap();
527        let id = core.query_video_format_id(ColorFamily::Gray, SampleType::Integer, 8, 0, 0);
528        let preset = core.get_video_format_by_id(id).unwrap();
529        assert_eq!(video.bits_per_sample, 8);
530        assert_eq!(core.get_video_format_name(&video).as_deref(), Some("Gray8"));
531        assert_eq!(preset.bits_per_sample, video.bits_per_sample);
532        assert_eq!(preset.color_family, video.color_family);
533
534        let audio = core.query_audio_format(SampleType::Integer, 16, 3).unwrap();
535        assert_eq!(audio.bits_per_sample, 16);
536        assert_eq!(audio.num_channels, 2);
537        assert_ne!(core.get_audio_format_name(&audio).unwrap(), "");
538    }
539
540    #[test]
541    fn borrowed_core_leaves_owner_alive() {
542        let core = Core::builder()
543            .disable_auto_loading()
544            .thread_count(2)
545            .build();
546        {
547            let borrowed = unsafe { CoreRef::from_ptr(core.as_ptr(), core.api()) };
548            assert_eq!(borrowed.as_ptr(), core.as_ptr());
549            assert_eq!(borrowed.get_info().num_threads, 2);
550        }
551        assert_eq!(core.get_info().num_threads, 2);
552    }
553
554    #[test]
555    fn builder() {
556        let api = Api::default();
557        let core = Core::builder()
558            .api(api)
559            .enable_graph_inspection()
560            .disable_auto_loading()
561            .disable_library_unloading()
562            .max_cache_size(1024)
563            .thread_count(4)
564            .build();
565        assert_eq!(core.get_info().max_framebuffer_size, 1024);
566        assert_eq!(core.get_info().num_threads, 4);
567    }
568
569    #[cfg(feature = "vs-42")]
570    #[test]
571    fn info2_reports_creation_flags() {
572        let core = Core::builder()
573            .api(Api::default())
574            .enable_graph_inspection()
575            .disable_auto_loading()
576            .build();
577
578        let info = core.get_info2();
579        let expected = ffi::VSCoreCreationFlags::EnableGraphInspection
580            | ffi::VSCoreCreationFlags::DisableAutoLoading;
581        assert_eq!(info.creation_flags, expected);
582        assert_eq!(info.core, core.get_info().core);
583    }
584}