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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

use std::{
    ffi::CStr,
    marker::PhantomData,
    mem::MaybeUninit,
    ops::{Deref, DerefMut},
    ptr::{null_mut, NonNull},
};

use crate::{
    api, ffi,
    frame::Frame,
    frame::{AudioFormat, AudioFrame, VideoFormat, VideoFrame},
    function::Function,
    map::MapMut,
    node::{internal::FilterExtern, Dependencies, Filter},
    plugin::Plugin,
    plugin::Plugins,
    AudioInfo, ColorFamily, SampleType, VideoInfo,
};

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[repr(transparent)]
pub struct CoreRef<'c> {
    handle: NonNull<ffi::VSCore>,
    marker: PhantomData<&'c Core>,
}

impl<'c> CoreRef<'c> {
    #[must_use]
    pub(crate) unsafe fn from_ptr(ptr: *const ffi::VSCore) -> Self {
        Self {
            handle: NonNull::new_unchecked(ptr.cast_mut()),
            marker: PhantomData,
        }
    }
}

impl<'c> Deref for CoreRef<'c> {
    type Target = Core;

    fn deref(&self) -> &'c Self::Target {
        unsafe { &*(self as *const CoreRef<'c>).cast() }
    }
}

impl<'c> DerefMut for CoreRef<'c> {
    fn deref_mut(&mut self) -> &'c mut Self::Target {
        unsafe { &mut *(self as *mut CoreRef<'c>).cast() }
    }
}

#[derive(PartialEq, Eq, Hash, Debug)]
#[repr(transparent)]
pub struct Core {
    handle: NonNull<ffi::VSCore>,
}

impl Core {
    #[must_use]
    pub fn new() -> Self {
        Self::new_with(0)
    }

    fn new_with(flags: i32) -> Self {
        let core = unsafe { (api().createCore)(flags) };
        Self {
            // Safety: `core` is always a valid pointer to a `VSCore` instance.
            handle: unsafe { NonNull::new_unchecked(core) },
        }
    }

    #[must_use]
    pub fn as_ptr(&self) -> *const ffi::VSCore {
        self.handle.as_ptr()
    }

    #[must_use]
    pub fn as_mut_ptr(&mut self) -> *mut ffi::VSCore {
        self.handle.as_ptr()
    }

    pub fn set_max_cache_size(&mut self, size: i64) {
        unsafe {
            (api().setMaxCacheSize)(size, self.as_mut_ptr());
        }
    }

    pub fn set_thread_count(&mut self, count: i32) {
        unsafe {
            (api().setThreadCount)(count, self.as_mut_ptr());
        }
    }

    #[must_use]
    pub fn get_info(&self) -> ffi::VSCoreInfo {
        unsafe {
            let mut info = MaybeUninit::uninit();
            (api().getCoreInfo)(self.as_ptr().cast_mut(), info.as_mut_ptr());
            info.assume_init()
        }
    }

    /// # Panics
    ///
    /// Panic if the `dependencies` has more item than [`i32::MAX`]
    pub fn create_video_filter<F: Filter>(
        &mut self,
        mut out: MapMut<'_>,
        name: &CStr,
        info: &VideoInfo,
        filter: Box<F>,
        dependencies: &Dependencies,
    ) {
        unsafe {
            (api().createVideoFilter)(
                (*out).as_mut_ptr(),
                name.as_ptr(),
                info,
                F::filter_get_frame,
                Some(F::filter_free),
                F::FILTER_MODE,
                dependencies.as_ptr(),
                dependencies.len().try_into().unwrap(),
                Box::into_raw(filter).cast(),
                self.as_mut_ptr(),
            );
        }
    }

    /// # Panics
    ///
    /// Panic if the `dependencies` has more item than [`i32::MAX`]
    pub fn create_audio_filter<F: Filter>(
        &mut self,
        mut out: MapMut<'_>,
        name: &CStr,
        info: &AudioInfo,
        filter: F,
        dependencies: &Dependencies,
    ) {
        let filter = Box::new(filter);
        unsafe {
            (api().createAudioFilter)(
                out.as_mut_ptr(),
                name.as_ptr(),
                info,
                F::filter_get_frame,
                Some(F::filter_free),
                F::FILTER_MODE,
                dependencies.as_ptr(),
                dependencies.len().try_into().unwrap(),
                Box::into_raw(filter).cast(),
                self.as_mut_ptr(),
            );
        }
    }

    #[must_use]
    pub fn new_video_frame(
        &self,
        format: &VideoFormat,
        width: i32,
        height: i32,
        prop_src: Option<&VideoFrame>,
    ) -> VideoFrame {
        unsafe {
            let ptr = (api().newVideoFrame)(
                format,
                width,
                height,
                prop_src.map_or(null_mut(), Frame::as_ptr),
                self.as_ptr().cast_mut(),
            );
            VideoFrame::from_ptr(ptr)
        }
    }

    #[must_use]
    pub fn new_video_frame2(
        &self,
        format: &VideoFormat,
        width: i32,
        height: i32,
        plane_src: &[*const ffi::VSFrame],
        planes: &[i32],
        prop_src: Option<&VideoFrame>,
    ) -> VideoFrame {
        unsafe {
            let ptr = (api().newVideoFrame2)(
                format,
                width,
                height,
                plane_src.as_ptr(),
                planes.as_ptr(),
                prop_src.map_or(null_mut(), Frame::as_ptr),
                self.as_ptr().cast_mut(),
            );
            VideoFrame::from_ptr(ptr)
        }
    }

    #[must_use]
    pub fn new_audio_frame(
        &self,
        format: &AudioFormat,
        num_samples: i32,
        prop_src: Option<&AudioFrame>,
    ) -> AudioFrame {
        unsafe {
            let ptr = (api().newAudioFrame)(
                format,
                num_samples,
                prop_src.map_or(null_mut(), Frame::as_ptr),
                self.as_ptr().cast_mut(),
            );
            AudioFrame::from_ptr(ptr)
        }
    }

    #[must_use]
    pub fn new_audio_frame2(
        &self,
        format: &AudioFormat,
        num_samples: i32,
        channel_src: &[*const ffi::VSFrame],
        channels: &[i32],
        prop_src: Option<&AudioFrame>,
    ) -> AudioFrame {
        unsafe {
            let ptr = (api().newAudioFrame2)(
                format,
                num_samples,
                channel_src.as_ptr(),
                channels.as_ptr(),
                prop_src.map_or(null_mut(), Frame::as_ptr),
                self.as_ptr().cast_mut(),
            );
            AudioFrame::from_ptr(ptr)
        }
    }

    #[must_use]
    pub fn copy_frame<F: Frame>(&self, frame: &F) -> F {
        unsafe { F::from_ptr((api().copyFrame)(frame.as_ptr(), self.as_ptr().cast_mut())) }
    }

    #[must_use]
    pub fn query_video_format(
        &self,
        color_family: ColorFamily,
        sample_type: SampleType,
        bits_per_sample: i32,
        subsampling_w: i32,
        subsampling_h: i32,
    ) -> VideoFormat {
        unsafe {
            let mut format = MaybeUninit::uninit();
            (api().queryVideoFormat)(
                format.as_mut_ptr(),
                color_family,
                sample_type,
                bits_per_sample,
                subsampling_w,
                subsampling_h,
                self.as_ptr().cast_mut(),
            );
            format.assume_init()
        }
    }

    #[must_use]
    pub fn query_audio_format(
        &self,
        sample_type: SampleType,
        bits_per_sample: i32,
        channel_layout: u64,
    ) -> AudioFormat {
        unsafe {
            let mut format = MaybeUninit::uninit();
            (api().queryAudioFormat)(
                format.as_mut_ptr(),
                sample_type,
                bits_per_sample,
                channel_layout,
                self.as_ptr().cast_mut(),
            );
            format.assume_init()
        }
    }

    #[must_use]
    pub fn query_video_format_id(
        &self,
        color_family: ColorFamily,
        sample_type: SampleType,
        bits_per_sample: i32,
        subsampling_w: i32,
        subsampling_h: i32,
    ) -> u32 {
        unsafe {
            (api().queryVideoFormatID)(
                color_family,
                sample_type,
                bits_per_sample,
                subsampling_w,
                subsampling_h,
                self.as_ptr().cast_mut(),
            )
        }
    }

    #[must_use]
    pub fn get_video_format_by_id(&self, id: u32) -> VideoFormat {
        unsafe {
            let mut format = MaybeUninit::uninit();
            (api().getVideoFormatByID)(format.as_mut_ptr(), id, self.as_ptr().cast_mut());
            format.assume_init()
        }
    }

    pub fn create_function<T>(
        &mut self,
        func: ffi::VSPublicFunction,
        data: Box<T>,
        free: ffi::VSFreeFunctionData,
    ) -> Function {
        unsafe {
            Function::from_ptr((api().createFunction)(
                func,
                Box::into_raw(data).cast(),
                free,
                self.as_mut_ptr(),
            ))
        }
    }

    pub fn get_plugin_by_id(&self, id: &CStr) -> Option<Plugin> {
        unsafe {
            NonNull::new((api().getPluginByID)(id.as_ptr(), self.as_ptr().cast_mut()))
                .map(Plugin::new)
        }
    }

    pub fn get_plugin_by_namespace(&self, ns: &CStr) -> Option<Plugin> {
        unsafe {
            NonNull::new((api().getPluginByNamespace)(
                ns.as_ptr(),
                self.as_ptr().cast_mut(),
            ))
            .map(Plugin::new)
        }
    }

    #[must_use]
    pub fn plugins(&self) -> Plugins<'_> {
        Plugins::new(self)
    }

    pub fn log(&mut self, level: ffi::VSMessageType, msg: &CStr) {
        unsafe {
            (api().logMessage)(level, msg.as_ptr(), self.as_mut_ptr());
        }
    }
}

impl Default for Core {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for Core {
    fn drop(&mut self) {
        unsafe {
            (api().freeCore)(self.handle.as_ptr());
        }
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)]
pub struct CoreBuilder {
    flags: i32,
    max_cache_size: Option<i64>,
    thread_count: Option<i32>,
}

impl CoreBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn build(self) -> Core {
        let mut core = Core::new_with(self.flags);
        if let Some(size) = self.max_cache_size {
            core.set_max_cache_size(size);
        }
        if let Some(count) = self.thread_count {
            core.set_thread_count(count);
        }
        core
    }

    pub fn enable_graph_inspection(&mut self) -> &mut Self {
        self.flags |= ffi::VSCoreCreationFlags::EnableGraphInspection as i32;
        self
    }

    pub fn disable_auto_loading(&mut self) -> &mut Self {
        self.flags |= ffi::VSCoreCreationFlags::DisableAutoLoading as i32;
        self
    }

    pub fn disable_library_unloading(&mut self) -> &mut Self {
        self.flags |= ffi::VSCoreCreationFlags::DisableLibraryUnloading as i32;
        self
    }

    pub fn max_cache_size(&mut self, size: i64) -> &mut Self {
        self.max_cache_size = Some(size);
        self
    }

    pub fn thread_count(&mut self, count: i32) -> &mut Self {
        self.thread_count = Some(count);
        self
    }
}

#[cfg(test)]
mod tests {
    use testresult::TestResult;

    use crate::set_api_default;

    use super::*;

    #[test]
    fn builder() -> TestResult {
        set_api_default()?;

        let core = CoreBuilder::new()
            .enable_graph_inspection()
            .disable_auto_loading()
            .disable_library_unloading()
            .max_cache_size(1024)
            .thread_count(4)
            .build();
        assert_eq!(core.get_info().max_framebuffer_size, 1024);
        assert_eq!(core.get_info().num_threads, 4);

        Ok(())
    }
}