rustsynth 0.7.0

Safe VapourSynth wrapper
Documentation
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! Module for frame related types and functionality.
mod enums;

use std::{borrow::Cow, marker::PhantomData, ops::Deref, ptr::NonNull};

use rustsynth_sys as ffi;

use crate::{
    api::API,
    core::CoreRef,
    format::{AudioFormat, MediaType, VideoFormat},
    map::{MapRef, MapResult},
};

// 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::VSFrame>,
    _owner: PhantomData<&'core ()>,
}

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

impl Drop for Frame<'_> {
    fn drop(&mut self) {
        // Frames are reference counted, so just free one reference
        unsafe {
            API::get_cached().free_frame(self.handle.as_ptr());
        }
    }
}

impl Clone for Frame<'_> {
    fn clone(&self) -> Self {
        // Properly increment the reference count when cloning
        unsafe {
            let new_handle = API::get_cached().clone_frame(self.handle.as_ptr());
            Self::from_ptr(new_handle)
        }
    }
}

/// Represents a reference to the obscure object
#[derive(Debug)]
pub struct FrameContext {
    handle: NonNull<ffi::VSFrameContext>,
}

impl FrameContext {
    /// Creates a `FrameContext` from a raw pointer.
    ///
    /// # Safety
    /// The pointer must be valid and point to a [`ffi::VSFrameContext`].
    #[inline]
    pub const unsafe fn from_ptr(ptr: *mut ffi::VSFrameContext) -> Self {
        Self {
            handle: NonNull::new_unchecked(ptr),
        }
    }

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

    /// Adds an error message to a frame context, replacing the existing message, if any.
    ///
    /// This is the way to report errors in a filter’s “getframe” function. Such errors are not necessarily fatal, i.e. the caller can try to request the same frame again.
    pub fn set_filter_error(&self, message: &str) {
        let c_message = std::ffi::CString::new(message).unwrap();
        unsafe {
            API::get_cached().set_filter_error(c_message.as_ptr(), self.as_ptr());
        }
    }
}

impl<'core> Frame<'core> {
    /// # Safety
    /// The pointer must be valid and point to a [`ffi::VSFrame`]
    #[inline]
    #[must_use]
    pub const unsafe fn from_ptr(ptr: *const ffi::VSFrame) -> Self {
        Self {
            handle: NonNull::new_unchecked(ptr.cast_mut()),
            _owner: PhantomData,
        }
    }

    /// # Safety
    /// The frame must be owned (not borrowed) and not passed to vapoursynth core.
    pub unsafe fn free(self) {
        API::get_cached().free_frame(self.handle.as_ptr());
    }

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

    /// Returns the height of a plane of a given frame, in pixels. The height depends on the plane number because of the possible chroma subsampling.
    #[inline]
    #[must_use]
    pub fn get_height(&self, plane: i32) -> i32 {
        unsafe { API::get_cached().get_frame_height(self.handle.as_ref(), plane) }
    }

    /// Returns the width of a plane of a given frame, in pixels. The width depends on the plane number because of the possible chroma subsampling.
    #[inline]
    #[must_use]
    pub fn get_width(&self, plane: i32) -> i32 {
        unsafe { API::get_cached().get_frame_width(self.handle.as_ref(), plane) }
    }

    #[inline]
    #[must_use]
    pub fn get_length(&self) -> i32 {
        unsafe { API::get_cached().get_frame_length(self.handle.as_ref()) }
    }

    /// Returns the distance in bytes between two consecutive lines of a plane of a frame. The stride is always positive.
    ///
    /// Passing an invalid plane number will cause a fatal error.
    #[inline]
    #[must_use]
    pub fn get_stride(&self, plane: i32) -> isize {
        unsafe { API::get_cached().get_frame_stride(self.handle.as_ref(), plane) }
    }

    #[inline]
    #[must_use]
    pub fn get_video_format(&self) -> Option<VideoFormat> {
        let ptr = unsafe { API::get_cached().get_video_frame_format(self.handle.as_ref()) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { VideoFormat::from_ptr(ptr) })
        }
    }

    #[must_use]
    pub fn get_audio_format(&self) -> Option<AudioFormat> {
        let ptr = unsafe { API::get_cached().get_audio_frame_format(self.handle.as_ptr()) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { AudioFormat::from_ptr(ptr) })
        }
    }

    /// Creates a new video frame, optionally copying the properties attached to another frame.
    #[must_use]
    pub fn new_video_frame(
        core: &CoreRef,
        width: i32,
        height: i32,
        format: &VideoFormat,
        prop_src: Option<&Frame<'_>>,
    ) -> Self {
        let ptr = unsafe {
            API::get_cached().new_video_frame(
                std::ptr::from_ref::<ffi::VSVideoFormat>(&format.as_ffi()),
                width,
                height,
                prop_src.map_or(std::ptr::null(), Frame::as_ptr),
                core.as_ptr(),
            )
        };
        unsafe { Frame::from_ptr(ptr) }
    }

    /// Creates a new video frame from the planes of existing frames, optionally copying the properties attached to another frame
    pub fn new_video_frame_from_existing_planes<const T: usize>(
        core: &CoreRef,
        width: i32,
        height: i32,
        format: VideoFormat,
        planesrc: &mut [&Frame<'_>; T],
        planes: &[i32; T],
        propsrc: Option<&Frame<'_>>,
    ) -> Self {
        let ptr = unsafe {
            let mut planesrcptr: [*const ffi::VSFrame; T] = [std::ptr::null(); T];
            for (i, frame) in planesrc.iter().enumerate() {
                planesrcptr[i] = frame.as_ptr();
            }
            API::get_cached().new_video_frame2(
                std::ptr::from_ref::<ffi::VSVideoFormat>(&format.as_ffi()),
                width,
                height,
                planesrcptr.as_mut_ptr(),
                planes.as_ptr(),
                propsrc.map_or(std::ptr::null(), Frame::as_ptr),
                core.as_ptr(),
            )
        };
        unsafe { Frame::from_ptr(ptr) }
    }

    /// Creates a new audio frame, optionally copying the properties attached to another frame. It is a fatal error to pass invalid arguments to this function
    #[must_use]
    pub fn new_audio_frame(
        core: &CoreRef,
        length: i32,
        format: &AudioFormat,
        prop_src: Option<&Frame<'_>>,
    ) -> Self {
        let ptr = unsafe {
            API::get_cached().new_audio_frame(
                std::ptr::from_ref::<ffi::VSAudioFormat>(&format.as_ffi()),
                prop_src.map_or(std::ptr::null(), Frame::as_ptr),
                length,
                core.as_ptr(),
            )
        };
        unsafe { Frame::from_ptr(ptr) }
    }

    /// Creates a new audio frame, optionally copying the properties attached to another frame. It is a fatal error to pass invalid arguments to this function.
    ///
    /// See also [`Frame::new_video_frame_from_existing_planes`]
    pub fn new_audio_frame_from_existing_channels<const T: usize>(
        core: &CoreRef,
        num_samples: i32,
        format: &AudioFormat,
        channelsrc: &mut [&Frame<'_>; T],
        channels: &[i32; T],
        propsrc: Option<&Frame<'_>>,
    ) -> Self {
        let ptr = unsafe {
            let mut channelsrcptr: [*const ffi::VSFrame; T] = [std::ptr::null(); T];
            for (i, frame) in channelsrc.iter().enumerate() {
                channelsrcptr[i] = frame.as_ptr();
            }
            API::get_cached().new_audio_frame2(
                std::ptr::from_ref::<ffi::VSAudioFormat>(&format.as_ffi()),
                num_samples,
                channelsrcptr.as_mut_ptr(),
                channels.as_ptr(),
                propsrc.map_or(std::ptr::null(), Frame::as_ptr),
                core.as_ptr(),
            )
        };
        unsafe { Frame::from_ptr(ptr) }
    }

    /// Get read-only access to plane data
    #[inline(always)]
    #[must_use]
    pub fn get_read_ptr(&self, plane: i32) -> *const u8 {
        unsafe { API::get_cached().get_frame_read_ptr(self.handle.as_ref(), plane) }
    }

    /// Get mutable access to plane data (only for owned frames)
    #[inline(always)]
    pub fn get_write_ptr(&mut self, plane: i32) -> *mut u8 {
        unsafe { API::get_cached().get_frame_write_ptr(self.handle.as_ptr(), plane) }
    }

    /// Get mutable slice to plane data (only for owned frames)
    pub fn get_write_slice(&mut self, plane: i32) -> &mut [u8] {
        let height = self.get_height(plane) as usize;
        let stride = self.get_stride(plane) as usize;
        let ptr = self.get_write_ptr(plane);
        unsafe { std::slice::from_raw_parts_mut(ptr, height * stride) }
    }

    /// Get read-only slice to plane data
    #[must_use]
    pub fn get_read_slice(&self, plane: i32) -> &[u8] {
        let height = self.get_height(plane) as usize;
        let stride = self.get_stride(plane) as usize;
        let ptr = self.get_read_ptr(plane);
        unsafe { std::slice::from_raw_parts(ptr, height * stride) }
    }

    /// Get read-only access to frame properties
    #[inline]
    #[must_use]
    pub fn properties(&self) -> &MapRef<'core> {
        let map_ptr = unsafe { API::get_cached().get_frame_props_ro(self.handle.as_ref()) };
        unsafe { MapRef::from_ptr(map_ptr) }
    }

    /// Get read-write access to frame properties (only for owned frames)
    #[inline]
    pub fn properties_mut(&mut self) -> &mut MapRef<'core> {
        let map_ptr = unsafe { API::get_cached().get_frame_props_rw(self.handle.as_ptr()) };
        unsafe { MapRef::from_ptr_mut(map_ptr) }
    }

    // Standard frame property getters

    /// Get chroma sample position in YUV formats
    #[must_use]
    pub fn chroma_location(&self) -> Option<ChromaLocation> {
        unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_ChromaLocation", 0)
                .ok()
                .and_then(|val| match val {
                    0 => Some(ChromaLocation::Left),
                    1 => Some(ChromaLocation::Center),
                    2 => Some(ChromaLocation::TopLeft),
                    3 => Some(ChromaLocation::Top),
                    4 => Some(ChromaLocation::BottomLeft),
                    5 => Some(ChromaLocation::Bottom),
                    _ => None,
                })
        }
    }

    /// Get color range (full or limited)
    #[must_use]
    pub fn color_range(&self) -> Option<ColorRange> {
        unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_ColorRange", 0)
                .ok()
                .and_then(|val| match val {
                    0 => Some(ColorRange::Full),
                    1 => Some(ColorRange::Limited),
                    _ => None,
                })
        }
    }

    /// Get color primaries as specified in ITU-T H.273 Table 2
    #[must_use]
    pub fn primaries(&self) -> ColorPrimaries {
        let res = unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_Primaries", 0)
                .unwrap_or(2)
        };
        ColorPrimaries::from(res)
    }

    /// Get matrix coefficients as specified in ITU-T H.273 Table 4
    #[must_use]
    pub fn matrix(&self) -> MatrixCoefficients {
        let res = unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_Matrix", 0)
                .unwrap_or(2)
        };
        MatrixCoefficients::from(res)
    }

    /// Get transfer characteristics as specified in ITU-T H.273 Table 3
    #[must_use]
    pub fn transfer(&self) -> TransferCharacteristics {
        let res = unsafe { self.properties().get_int_raw_unchecked(c"_Transfer", 2) }.unwrap_or(0);
        TransferCharacteristics::from(res)
    }

    /// Get field based information (interlaced)
    #[must_use]
    pub fn field_based(&self) -> Option<FieldBased> {
        unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_FieldBased", 0)
                .ok()
                .and_then(|val| match val {
                    0 => Some(FieldBased::Progressive),
                    1 => Some(FieldBased::BottomFieldFirst),
                    2 => Some(FieldBased::TopFieldFirst),
                    _ => None,
                })
        }
    }

    /// Get absolute timestamp in seconds
    #[must_use]
    pub fn absolute_time(&self) -> Option<f64> {
        unsafe {
            self.properties()
                .get_float_raw_unchecked(c"_AbsoluteTime", 0)
                .ok()
        }
    }

    /// Get frame duration as a rational number (numerator, denominator)
    #[must_use]
    pub fn duration(&self) -> Option<(i64, i64)> {
        let num = unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_DurationNum", 0)
                .ok()?
        };
        let den = unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_DurationDen", 0)
                .ok()?
        };
        Some((num, den))
    }

    /// Get whether the frame needs postprocessing
    #[must_use]
    pub fn combed(&self) -> Option<bool> {
        unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_Combed", 0)
                .ok()
                .map(|val| val != 0)
        }
    }

    /// Get which field was used to generate this frame
    #[must_use]
    pub fn field(&self) -> Option<Field> {
        unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_Field", 0)
                .ok()
                .and_then(|val| match val {
                    0 => Some(Field::Bottom),
                    1 => Some(Field::Top),
                    _ => None,
                })
        }
    }

    /// Get picture type (single character describing frame type)
    #[must_use]
    pub fn picture_type(&self) -> Option<Cow<'core, str>> {
        unsafe {
            self.properties()
                .get_string_raw_unchecked(c"_PictType", 0)
                .ok()
        }
    }

    /// Get pixel (sample) aspect ratio as a rational number (numerator, denominator)
    #[must_use]
    pub fn sample_aspect_ratio(&self) -> Option<(i64, i64)> {
        let num = unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_SARNum", 0)
                .ok()?
        };
        let den = unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_SARDen", 0)
                .ok()?
        };
        Some((num, den))
    }

    /// Get whether this frame is the last frame of the current scene
    #[must_use]
    pub fn scene_change_next(&self) -> Option<bool> {
        unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_SceneChangeNext", 0)
                .ok()
                .map(|val| val != 0)
        }
    }

    /// Get whether this frame starts a new scene
    #[must_use]
    pub fn scene_change_prev(&self) -> Option<bool> {
        unsafe {
            self.properties()
                .get_int_raw_unchecked(c"_SceneChangePrev", 0)
                .ok()
                .map(|val| val != 0)
        }
    }

    /// Get alpha channel frame attached to this frame
    #[must_use]
    pub fn alpha(&self) -> Option<Self> {
        unsafe { self.properties().get_frame_raw_unchecked(c"_Alpha", 0).ok() }
    }

    // Standard frame property setters (for owned frames only)

    /// Set chroma sample position in YUV formats
    pub fn set_chroma_location(&mut self, location: ChromaLocation) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_ChromaLocation", location as i64);
        }
        Ok(())
    }

    /// Set color range (full or limited)
    pub fn set_color_range(&mut self, range: ColorRange) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_ColorRange", range as i64);
        }
        Ok(())
    }

    /// Set color primaries as specified in ITU-T H.273 Table 2
    pub fn set_primaries(&mut self, primaries: ColorPrimaries) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_Primaries", primaries as i64);
        }
        Ok(())
    }

    /// Set matrix coefficients as specified in ITU-T H.273 Table 4
    pub fn set_matrix(&mut self, matrix: MatrixCoefficients) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_Matrix", matrix as i64);
        }
        Ok(())
    }

    /// Set transfer characteristics as specified in ITU-T H.273 Table 3
    pub fn set_transfer(&mut self, transfer: TransferCharacteristics) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_Transfer", transfer as i64);
        }
        Ok(())
    }

    /// Set field based information (interlaced)
    pub fn set_field_based(&mut self, field_based: FieldBased) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_FieldBased", field_based as i64);
        }
        Ok(())
    }

    /// Set absolute timestamp in seconds (should only be set by source filter)
    pub fn set_absolute_time(&mut self, time: f64) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_float_raw_unchecked(c"_AbsoluteTime", time);
        }
        Ok(())
    }

    /// Set frame duration as a rational number (numerator, denominator)
    pub fn set_duration(&mut self, num: i64, den: i64) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_DurationNum", num);
            self.properties_mut()
                .set_int_raw_unchecked(c"_DurationDen", den);
        }
        Ok(())
    }

    /// Set whether the frame needs postprocessing
    pub fn set_combed(&mut self, combed: bool) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_Combed", i64::from(combed));
        }
        Ok(())
    }

    /// Set which field was used to generate this frame
    pub fn set_field(&mut self, field: Field) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_Field", field as i64);
        }
        Ok(())
    }

    /// Set picture type (single character describing frame type)
    pub fn set_picture_type(&mut self, pic_type: &str) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_string_raw_unchecked(c"_PictType", pic_type);
        }
        Ok(())
    }

    /// Set pixel (sample) aspect ratio as a rational number (numerator, denominator)
    pub fn set_sample_aspect_ratio(&mut self, num: i64, den: i64) -> MapResult<()> {
        unsafe {
            self.properties_mut().set_int_raw_unchecked(c"_SARNum", num);
            self.properties_mut().set_int_raw_unchecked(c"_SARDen", den);
        }
        Ok(())
    }

    /// Set whether this frame is the last frame of the current scene
    pub fn set_scene_change_next(&mut self, scene_change: bool) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_SceneChangeNext", i64::from(scene_change));
        }
        Ok(())
    }

    /// Set whether this frame starts a new scene
    pub fn set_scene_change_prev(&mut self, scene_change: bool) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_int_raw_unchecked(c"_SceneChangePrev", i64::from(scene_change));
        }
        Ok(())
    }

    /// Set alpha channel frame for this frame
    pub fn set_alpha(&mut self, alpha_frame: &Self) -> MapResult<()> {
        unsafe {
            self.properties_mut()
                .set_frame_raw_unchecked(c"_Alpha", alpha_frame);
        }
        Ok(())
    }

    #[must_use]
    pub fn get_frame_type(&self) -> MediaType {
        MediaType::from_ffi(unsafe { API::get_cached().get_frame_type(self.handle.as_ref()) })
    }

    /// Pushes a not requested frame into the cache. This is useful for (source) filters that greatly benefit from completely linear access and producing all output in linear order.
    /// This function may only be used in filters that were created with setLinearFilter.
    /// Only use inside a filter’s “getframe” function.
    pub fn cache_frame(&self, n: i32, frame_ctxt: &FrameContext) {
        unsafe { API::get_cached().cache_frame(self.handle.as_ref(), n, frame_ctxt.as_ptr()) }
    }

    /// RAII fn that provides access to all planes of a video frame
    pub fn with_planes<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&[Plane]) -> R,
    {
        let planes: Vec<_> = self.planes().collect();
        f(&planes)
    }

    /// RAII fn that provides mutable access to all planes of a video frame (only for owned frames)
    pub fn map_pixels<T, F>(&mut self, plane: i32, mut f: F)
    where
        F: FnMut(&mut [T]),
    {
        let ptr = self.get_write_ptr(plane).cast::<T>();
        let stride = self.get_stride(plane) / std::mem::size_of::<T>() as isize;
        let width = self.get_width(plane) as isize;
        let height = self.get_height(plane) as isize;
        unsafe {
            for row in 0..height {
                let row_ptr = ptr.offset(row * stride);
                let slice = std::slice::from_raw_parts_mut(row_ptr, width as usize);
                f(slice);
            }
        }
    }

    #[must_use]
    pub fn planes(&self) -> Planes<'_> {
        Planes {
            frame: self,
            total: self.get_video_format().map_or(0, |vf| vf.num_planes),
            current: 0,
        }
    }
}

impl Deref for Frame<'_> {
    type Target = ffi::VSFrame;

    fn deref(&self) -> &Self::Target {
        unsafe { self.handle.as_ref() }
    }
}
pub struct Plane {
    pub data: *const u8,
    pub stride: isize,
    pub width: i32,
    pub height: i32,
}

pub struct Planes<'a> {
    frame: &'a Frame<'a>,
    total: i32,
    current: i32,
}

impl Iterator for Planes<'_> {
    type Item = Plane;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current >= self.total {
            None
        } else {
            let plane = Plane {
                data: self.frame.get_read_ptr(self.current),
                stride: self.frame.get_stride(self.current),
                width: self.frame.get_width(self.current),
                height: self.frame.get_height(self.current),
            };
            self.current += 1;
            Some(plane)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.total - self.current) as usize;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for Planes<'_> {}

pub use enums::{
    ChromaLocation, ColorPrimaries, ColorRange, Field, FieldBased, MatrixCoefficients,
    TransferCharacteristics,
};