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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! VapourSynth frames.

use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, NonNull};
use std::{mem, slice};
use vapoursynth_sys as ffi;

use thiserror::Error;

use crate::api::API;
use crate::component::Component;
use crate::core::CoreRef;
use crate::format::Format;
use crate::map::{MapRef, MapRefMut};
use crate::video_info::Resolution;

/// An error indicating that the frame data has non-zero padding.
#[derive(Error, Debug, Clone, Copy, Eq, PartialEq)]
#[error("Frame data has non-zero padding: {}", _0)]
pub struct NonZeroPadding(usize);

/// One frame of a clip.
// This type is intended to be publicly used only in reference form.
#[derive(Debug)]
pub struct Frame<'core> {
    // The actual mutability of this depends on whether it's accessed via `&Frame` or `&mut Frame`.
    handle: NonNull<ffi::VSFrameRef>,
    // The cached frame format for fast access.
    format: Format<'core>,
    _owner: PhantomData<&'core ()>,
}

/// A reference to a ref-counted frame.
#[derive(Debug)]
pub struct FrameRef<'core> {
    // Only immutable references to this are allowed.
    frame: Frame<'core>,
}

/// A reference to a mutable frame.
#[derive(Debug)]
pub struct FrameRefMut<'core> {
    // Both mutable and immutable references to this are allowed.
    frame: Frame<'core>,
}

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

#[doc(hidden)]
impl<'core> Deref for Frame<'core> {
    type Target = ffi::VSFrameRef;

    // Technically this should return `&'core`.
    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe { self.handle.as_ref() }
    }
}

#[doc(hidden)]
impl<'core> DerefMut for Frame<'core> {
    // Technically this should return `&'core`.
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.handle.as_mut() }
    }
}

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

impl<'core> Clone for FrameRef<'core> {
    #[inline]
    fn clone(&self) -> Self {
        unsafe {
            let handle = API::get_cached().clone_frame(self);
            Self {
                frame: Frame::from_ptr(handle),
            }
        }
    }
}

impl<'core> Deref for FrameRef<'core> {
    type Target = Frame<'core>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.frame
    }
}

impl<'core> Deref for FrameRefMut<'core> {
    type Target = Frame<'core>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.frame
    }
}

impl<'core> DerefMut for FrameRefMut<'core> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.frame
    }
}

impl<'core> FrameRef<'core> {
    /// Wraps `handle` in a `FrameRef`.
    ///
    /// # Safety
    /// The caller must ensure `handle` and the lifetime is valid and API is cached.
    #[inline]
    pub(crate) unsafe fn from_ptr(handle: *const ffi::VSFrameRef) -> Self {
        Self {
            frame: Frame::from_ptr(handle),
        }
    }
}

impl<'core> FrameRefMut<'core> {
    /// Wraps `handle` in a `FrameRefMut`.
    ///
    /// # 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::VSFrameRef) -> Self {
        Self {
            frame: Frame::from_ptr(handle),
        }
    }

    /// Creates a copy of the given frame.
    ///
    /// The plane data is copy-on-write, so this isn't very expensive by itself.
    ///
    /// Judging by the underlying implementation, it seems that any valid `core` can be used.
    #[inline]
    pub fn copy_of(core: CoreRef, frame: &Frame<'core>) -> Self {
        Self {
            frame: unsafe { Frame::from_ptr(API::get_cached().copy_frame(frame, core.ptr())) },
        }
    }

    /// Creates a new frame with uninitialized plane data.
    ///
    /// Optionally copies the frame properties from the provided `prop_src` frame.
    ///
    /// # Safety
    /// The returned frame contains uninitialized plane data. This should be handled carefully. See
    /// the docs for `std::mem::uninitialized()` for more information.
    ///
    /// # Panics
    /// Panics if the given resolution has components that don't fit into an `i32`.
    #[inline]
    pub unsafe fn new_uninitialized(
        core: CoreRef<'core>,
        prop_src: Option<&Frame<'core>>,
        format: Format<'core>,
        resolution: Resolution,
    ) -> Self {
        assert!(resolution.width <= i32::max_value() as usize);
        assert!(resolution.height <= i32::max_value() as usize);

        Self {
            frame: unsafe {
                Frame::from_ptr(API::get_cached().new_video_frame(
                    &format,
                    resolution.width as i32,
                    resolution.height as i32,
                    prop_src.map(|f| f.deref() as _).unwrap_or(ptr::null()),
                    core.ptr(),
                ))
            },
        }
    }
}

impl<'core> From<FrameRefMut<'core>> for FrameRef<'core> {
    #[inline]
    fn from(x: FrameRefMut<'core>) -> Self {
        Self { frame: x.frame }
    }
}

impl<'core> Frame<'core> {
    /// Converts a pointer to a frame to a reference.
    ///
    /// # Safety
    /// The caller needs to ensure the pointer and the lifetime is valid, and that the resulting
    /// `Frame` gets put into `FrameRef` or `FrameRefMut` according to the input pointer
    /// mutability.
    #[inline]
    pub(crate) unsafe fn from_ptr(handle: *const ffi::VSFrameRef) -> Self {
        Self {
            handle: NonNull::new_unchecked(handle as *mut ffi::VSFrameRef),
            format: unsafe {
                let ptr = API::get_cached().get_frame_format(&*handle);
                Format::from_ptr(ptr)
            },
            _owner: PhantomData,
        }
    }

    /// Returns the frame format.
    #[inline]
    pub fn format(&self) -> Format<'core> {
        self.format
    }

    /// Returns the width of a plane, in pixels.
    ///
    /// The width depends on the plane number because of the possible chroma subsampling.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()`.
    #[inline]
    pub fn width(&self, plane: usize) -> usize {
        assert!(plane < self.format().plane_count());

        unsafe { API::get_cached().get_frame_width(self, plane as i32) as usize }
    }

    /// Returns the height of a plane, in pixels.
    ///
    /// The height depends on the plane number because of the possible chroma subsampling.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()`.
    #[inline]
    pub fn height(&self, plane: usize) -> usize {
        assert!(plane < self.format().plane_count());

        unsafe { API::get_cached().get_frame_height(self, plane as i32) as usize }
    }

    /// Returns the resolution of a plane.
    ///
    /// The resolution depends on the plane number because of the possible chroma subsampling.
    ///
    /// # Panics
    /// Panics if `plane` is invalid for this frame.
    #[inline]
    pub fn resolution(&self, plane: usize) -> Resolution {
        assert!(plane < self.format().plane_count());

        Resolution {
            width: self.width(plane),
            height: self.height(plane),
        }
    }

    /// Returns the distance in bytes between two consecutive lines of a plane.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()`.
    #[inline]
    pub fn stride(&self, plane: usize) -> usize {
        assert!(plane < self.format().plane_count());

        unsafe { API::get_cached().get_frame_stride(self, plane as i32) as usize }
    }

    /// Returns a slice of a plane's pixel row.
    ///
    /// # Panics
    /// Panics if the requested plane, row or component type is invalid.
    #[inline]
    pub fn plane_row<T: Component>(&self, plane: usize, row: usize) -> &[T] {
        assert!(plane < self.format().plane_count());
        assert!(row < self.height(plane));
        assert!(T::is_valid(self.format()));

        let stride = self.stride(plane);
        let ptr = self.data_ptr(plane);

        let offset = stride * row;
        assert!(offset <= isize::max_value() as usize);
        let offset = offset as isize;

        let row_ptr = unsafe { ptr.offset(offset) };
        let width = self.width(plane);

        unsafe { slice::from_raw_parts(row_ptr as *const T, width) }
    }

    /// Returns a mutable slice of a plane's pixel row.
    ///
    /// # Panics
    /// Panics if the requested plane, row or component type is invalid.
    #[inline]
    pub fn plane_row_mut<T: Component>(&mut self, plane: usize, row: usize) -> &mut [T] {
        assert!(plane < self.format().plane_count());
        assert!(row < self.height(plane));
        assert!(T::is_valid(self.format()));

        let stride = self.stride(plane);
        let ptr = self.data_ptr_mut(plane);

        let offset = stride * row;
        assert!(offset <= isize::max_value() as usize);
        let offset = offset as isize;

        let row_ptr = unsafe { ptr.offset(offset) };
        let width = self.width(plane);

        unsafe { slice::from_raw_parts_mut(row_ptr as *mut T, width) }
    }

    /// Returns a slice of the plane's pixels.
    ///
    /// The length of the returned slice is `height() * width()`. If the pixel data has non-zero
    /// padding (that is, `stride()` is larger than `width()`), an error is returned, since
    /// returning the data slice would open access to uninitialized bytes.
    ///
    /// # Panics
    /// Panics if the requested plane or component type is invalid.
    pub fn plane<T: Component>(&self, plane: usize) -> Result<&[T], NonZeroPadding> {
        assert!(plane < self.format().plane_count());
        assert!(T::is_valid(self.format()));

        let stride = self.stride(plane);
        let width_in_bytes = self.width(plane) * usize::from(self.format().bytes_per_sample());
        if stride != width_in_bytes {
            return Err(NonZeroPadding(stride - width_in_bytes));
        }

        let height = self.height(plane);
        let length = height * self.width(plane);
        let ptr = self.data_ptr(plane);

        Ok(unsafe { slice::from_raw_parts(ptr as *const T, length) })
    }

    /// Returns a mutable slice of the plane's pixels.
    ///
    /// The length of the returned slice is `height() * width()`. If the pixel data has non-zero
    /// padding (that is, `stride()` is larger than `width()`), an error is returned, since
    /// returning the data slice would open access to uninitialized bytes.
    ///
    /// # Panics
    /// Panics if the requested plane or component type is invalid.
    pub fn plane_mut<T: Component>(&mut self, plane: usize) -> Result<&mut [T], NonZeroPadding> {
        assert!(plane < self.format().plane_count());
        assert!(T::is_valid(self.format()));

        let stride = self.stride(plane);
        let width_in_bytes = self.width(plane) * usize::from(self.format().bytes_per_sample());
        if stride != width_in_bytes {
            return Err(NonZeroPadding(stride - width_in_bytes));
        }

        let height = self.height(plane);
        let length = height * self.width(plane);
        let ptr = self.data_ptr_mut(plane);

        Ok(unsafe { slice::from_raw_parts_mut(ptr as *mut T, length) })
    }

    /// Returns a pointer to the plane's pixels.
    ///
    /// The pointer points to an array with a length of `height() * stride()` and is valid for as
    /// long as the frame is alive.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()`.
    #[inline]
    pub fn data_ptr(&self, plane: usize) -> *const u8 {
        assert!(plane < self.format().plane_count());

        unsafe { API::get_cached().get_frame_read_ptr(self, plane as i32) }
    }

    /// Returns a mutable pointer to the plane's pixels.
    ///
    /// The pointer points to an array with a length of `height() * stride()` and is valid for as
    /// long as the frame is alive.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()`.
    #[inline]
    pub fn data_ptr_mut(&mut self, plane: usize) -> *mut u8 {
        assert!(plane < self.format().plane_count());

        unsafe { API::get_cached().get_frame_write_ptr(self, plane as i32) }
    }

    /// Returns a slice of a plane's pixel row.
    ///
    /// The length of the returned slice is equal to `width() * format().bytes_per_sample()`.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()` or if `row >= height()`.
    pub fn data_row(&self, plane: usize, row: usize) -> &[u8] {
        assert!(plane < self.format().plane_count());
        assert!(row < self.height(plane));

        let stride = self.stride(plane);
        let ptr = self.data_ptr(plane);

        let offset = stride * row;
        assert!(offset <= isize::max_value() as usize);
        let offset = offset as isize;

        let row_ptr = unsafe { ptr.offset(offset) };
        let width = self.width(plane) * usize::from(self.format().bytes_per_sample());

        unsafe { slice::from_raw_parts(row_ptr, width) }
    }

    /// Returns a mutable slice of a plane's pixel row.
    ///
    /// The length of the returned slice is equal to `width() * format().bytes_per_sample()`.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()` or if `row >= height()`.
    pub fn data_row_mut(&mut self, plane: usize, row: usize) -> &mut [u8] {
        assert!(plane < self.format().plane_count());
        assert!(row < self.height(plane));

        let stride = self.stride(plane);
        let ptr = self.data_ptr_mut(plane);

        let offset = stride * row;
        assert!(offset <= isize::max_value() as usize);
        let offset = offset as isize;

        let row_ptr = unsafe { ptr.offset(offset) };
        let width = self.width(plane) * usize::from(self.format().bytes_per_sample());

        unsafe { slice::from_raw_parts_mut(row_ptr, width) }
    }

    /// Returns a slice of the plane's pixels.
    ///
    /// The length of the returned slice is `height() * width() * format().bytes_per_sample()`. If
    /// the pixel data has non-zero padding (that is, `stride()` is larger than `width()`), an
    /// error is returned, since returning the data slice would open access to uninitialized bytes.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()` or if `row >= height()`.
    pub fn data(&self, plane: usize) -> Result<&[u8], NonZeroPadding> {
        assert!(plane < self.format().plane_count());

        let stride = self.stride(plane);
        let width = self.width(plane) * usize::from(self.format().bytes_per_sample());
        if stride != width {
            return Err(NonZeroPadding(stride - width));
        }

        let height = self.height(plane);
        let length = height * stride;
        let ptr = self.data_ptr(plane);

        Ok(unsafe { slice::from_raw_parts(ptr, length) })
    }

    /// Returns a mutable slice of the plane's pixels.
    ///
    /// The length of the returned slice is `height() * width() * format().bytes_per_sample()`. If
    /// the pixel data has non-zero padding (that is, `stride()` is larger than `width()`), an
    /// error is returned, since returning the data slice would open access to uninitialized bytes.
    ///
    /// # Panics
    /// Panics if `plane >= format().plane_count()` or if `row >= height()`.
    pub fn data_mut(&mut self, plane: usize) -> Result<&mut [u8], NonZeroPadding> {
        assert!(plane < self.format().plane_count());

        let stride = self.stride(plane);
        let width = self.width(plane) * usize::from(self.format().bytes_per_sample());
        if stride != width {
            return Err(NonZeroPadding(stride - width));
        }

        let height = self.height(plane);
        let length = height * stride;
        let ptr = self.data_ptr_mut(plane);

        Ok(unsafe { slice::from_raw_parts_mut(ptr, length) })
    }

    /// Returns a map of frame's properties.
    #[inline]
    pub fn props(&self) -> MapRef {
        unsafe { MapRef::from_ptr(API::get_cached().get_frame_props_ro(self)) }
    }

    /// Returns a mutable map of frame's properties.
    #[inline]
    pub fn props_mut(&mut self) -> MapRefMut {
        unsafe { MapRefMut::from_ptr(API::get_cached().get_frame_props_rw(self)) }
    }
}