1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//! VapourSynth nodes.

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

use crate::api::API;
use crate::format::{AudioInfo, MediaType, VideoInfo};
use crate::frame::FrameRef;

mod errors;
pub use self::errors::GetFrameError;

/// A reference to a node in the constructed filter graph.
#[derive(Debug)]
pub struct Node<'core> {
    handle: NonNull<ffi::VSNode>,
    _owner: PhantomData<&'core ()>,
}

unsafe impl<'core> Send for Node<'core> {}
unsafe impl<'core> Sync for Node<'core> {}

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

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

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

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

    /// Returns the video info associated with this `Node`.
    // Since we don't store the pointer to the actual `ffi::VSVideoInfo` and the lifetime is that
    // of the `ffi::VSFormat`, this returns `VideoInfo<'core>` rather than `VideoInfo<'a>`.
    #[inline]
    pub fn video_info(&self) -> Option<VideoInfo> {
        unsafe {
            let ptr = API::get_cached().get_video_info(self.handle.as_ptr());
            if ptr.is_null() {
                None
            } else {
                Some(VideoInfo::from_ptr(ptr))
            }
        }
    }

    /// Returns the audio info associated with this `Node`.
    // Since we don't store the pointer to the actual `ffi::VSVideoInfo` and the lifetime is that
    // of the `ffi::VSFormat`, this returns `VideoInfo<'core>` rather than `VideoInfo<'a>`.
    #[inline]
    pub fn audio_info(&self) -> Option<AudioInfo> {
        unsafe {
            let ptr = API::get_cached().get_audio_info(self.handle.as_ptr());
            if ptr.is_null() {
                None
            } else {
                Some(AudioInfo::from_ptr(ptr))
            }
        }
    }

    /// Generates a frame directly.
    ///
    /// The `'error` lifetime is unbounded because this function always returns owned data.
    ///
    /// # Panics
    /// Panics is `n` is greater than `i32::max_value()`.
    pub fn get_frame<'error>(&self, n: usize) -> Result<FrameRef<'core>, GetFrameError<'error>> {
        assert!(n <= i32::max_value() as usize);

        let vi = &self.video_info().unwrap();

        let total = vi.num_frames;
        if n >= total as usize {
            let err_cstring = CString::new("Requested frame number beyond the last one").unwrap();
            return Err(GetFrameError::new(Cow::Owned(err_cstring)));
        }

        // Kinda arbitrary. Same value as used in vsvfw.
        const ERROR_BUF_CAPACITY: usize = 32 * 1024;

        let err_buf = vec![0; ERROR_BUF_CAPACITY];
        let mut err_buf = err_buf.into_boxed_slice();

        let handle =
            unsafe { API::get_cached().get_frame(n as i32, self.handle.as_ptr(), &mut err_buf) };

        if handle.is_null() {
            // TODO: remove this extra allocation by reusing `Box<[c_char]>`.
            let error = unsafe { CStr::from_ptr(err_buf.as_ptr()) }.to_owned();
            Err(GetFrameError::new(Cow::Owned(error)))
        } else {
            Ok(unsafe { FrameRef::from_ptr(handle) })
        }
    }

    /// Requests the generation of a frame. When the frame is ready, a user-provided function is
    /// called.
    ///
    /// If multiple frames were requested, they can be returned in any order.
    ///
    /// The callback arguments are:
    ///
    /// - the generated frame or an error message if the generation failed,
    /// - the frame number (equal to `n`),
    /// - the node that generated the frame (the same as `self`).
    ///
    /// If the callback panics, the process is aborted.
    ///
    /// # Panics
    /// Panics is `n` is greater than `i32::max_value()`.
    pub fn get_frame_async<F>(&self, n: usize, callback: F)
    where
        F: FnOnce(Result<FrameRef<'core>, GetFrameError>, usize, Node<'core>) + Send + 'core,
    {
        struct CallbackData<'core> {
            callback: Box<dyn CallbackFn<'core> + 'core>,
        }

        // A little bit of magic for Box<FnOnce>.
        trait CallbackFn<'core> {
            fn call(
                self: Box<Self>,
                frame: Result<FrameRef<'core>, GetFrameError>,
                n: usize,
                node: Node<'core>,
            );
        }

        impl<'core, F> CallbackFn<'core> for F
        where
            F: FnOnce(Result<FrameRef<'core>, GetFrameError>, usize, Node<'core>),
        {
            #[allow(clippy::boxed_local)]
            fn call(
                self: Box<Self>,
                frame: Result<FrameRef<'core>, GetFrameError>,
                n: usize,
                node: Node<'core>,
            ) {
                (self)(frame, n, node)
            }
        }

        unsafe extern "C" fn c_callback(
            user_data: *mut c_void,
            frame: *const ffi::VSFrame,
            n: i32,
            node: *mut ffi::VSNode,
            error_msg: *const c_char,
        ) {
            // The actual lifetime isn't 'static, it's 'core, but we don't really have a way of
            // retrieving it.
            let user_data = Box::from_raw(user_data as *mut CallbackData<'static>);

            let closure = panic::AssertUnwindSafe(move || {
                let frame = if frame.is_null() {
                    debug_assert!(!error_msg.is_null());
                    let error_msg = Cow::Borrowed(CStr::from_ptr(error_msg));
                    Err(GetFrameError::new(error_msg))
                } else {
                    debug_assert!(error_msg.is_null());
                    Ok(FrameRef::from_ptr(frame))
                };

                let node = Node::from_ptr(node);

                debug_assert!(n >= 0);
                let n = n as usize;

                user_data.callback.call(frame, n, node);
            });

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

        assert!(n <= i32::max_value() as usize);
        let n = n as i32;

        let user_data = Box::new(CallbackData {
            callback: Box::new(callback),
        });

        let new_node = self.clone();

        unsafe {
            API::get_cached().get_frame_async(
                n,
                new_node.handle.as_ptr(),
                Some(c_callback),
                Box::into_raw(user_data) as *mut c_void,
            );
        }

        // It'll be dropped by the callback.
        mem::forget(new_node);
    }

    pub fn media_type(&self) -> MediaType {
        let int = unsafe { API::get_cached().get_node_type(self.ptr()) };
        match int {
            x if x == ffi::VSMediaType::mtAudio as i32 => MediaType::Audio,
            x if x == ffi::VSMediaType::mtVideo as i32 => MediaType::Video,
            _ => unreachable!(),
        }
    }
}