objc2-video-toolbox 0.3.2

Bindings to the VideoToolbox framework
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! This file has been automatically generated by `objc2`'s `header-translator`.
//! DO NOT EDIT
use core::cell::UnsafeCell;
use core::ffi::*;
use core::marker::{PhantomData, PhantomPinned};
use core::ptr::NonNull;
#[cfg(feature = "objc2")]
use objc2::__framework_prelude::*;
use objc2_core_foundation::*;
#[cfg(feature = "objc2-core-media")]
use objc2_core_media::*;
#[cfg(feature = "objc2-core-video")]
use objc2_core_video::*;

use crate::*;

/// A reference to a Video Toolbox Decompression Session.
///
/// A decompression session supports the decompression of a sequence of video frames.
/// The session reference is a reference-counted CF object.
/// To create a decompression session, call VTDecompressionSessionCreate;
/// then you can optionally configure the session using VTSessionSetProperty;
/// then to decode frames, call VTDecompressionSessionDecodeFrame.
/// When you are done with the session, you should call VTDecompressionSessionInvalidate
/// to tear it down and CFRelease to release your object reference.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/videotoolbox/vtdecompressionsession?language=objc)
#[doc(alias = "VTDecompressionSessionRef")]
#[repr(C)]
pub struct VTDecompressionSession {
    inner: [u8; 0],
    _p: UnsafeCell<PhantomData<(*const UnsafeCell<()>, PhantomPinned)>>,
}

cf_type!(
    unsafe impl VTDecompressionSession {}
);
#[cfg(feature = "objc2")]
cf_objc2_type!(
    unsafe impl RefEncode<"OpaqueVTDecompressionSession"> for VTDecompressionSession {}
);

/// Prototype for callback invoked when frame decompression is complete.
///
/// When you create a decompression session, you pass in a callback function to be called
/// for decompressed frames.  This function will not necessarily be called in display order.
///
/// Parameter `decompressionOutputRefCon`: The callback's reference value, copied from the decompressionOutputRefCon field of the
/// VTDecompressionOutputCallbackRecord structure.
///
/// Parameter `sourceFrameRefCon`: The frame's reference value, copied from the sourceFrameRefCon argument to
/// VTDecompressionSessionDecodeFrame.
///
/// Parameter `status`: noErr if decompression was successful; an error code if decompression was not successful.
///
/// Parameter `infoFlags`: Contains information about the decode operation.
/// The kVTDecodeInfo_Asynchronous bit may be set if the decode ran asynchronously.
/// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped.
/// If the kVTDecodeInfo_ImageBufferModifiable bit is set, it is safe for the client to modify the imageBuffer.
///
/// Parameter `imageBuffer`: Contains the decompressed frame, if decompression was successful; otherwise, NULL.
/// IMPORTANT: The video decompressor may still be referencing the imageBuffer returned in this
/// callback if the kVTDecodeInfo_ImageBufferModifiable flag is not set.  Unless this flag
/// is set, it is not safe to modify the returned imageBuffer.
///
/// Parameter `presentationTimeStamp`: The frame's presentation timestamp, which will be determined by calling
/// CMSampleBufferGetOutputPresentationTimeStamp; kCMTimeInvalid if not available.
///
/// Parameter `presentationDuration`: The frame's presentation duration, which will be determined by calling
/// CMSampleBufferGetOutputDuration; kCMTimeInvalid if not available.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/videotoolbox/vtdecompressionoutputcallback?language=objc)
#[cfg(all(
    feature = "VTErrors",
    feature = "objc2-core-media",
    feature = "objc2-core-video"
))]
pub type VTDecompressionOutputCallback = Option<
    unsafe extern "C-unwind" fn(
        *mut c_void,
        *mut c_void,
        OSStatus,
        VTDecodeInfoFlags,
        *mut CVImageBuffer,
        CMTime,
        CMTime,
    ),
>;

/// [Apple's documentation](https://developer.apple.com/documentation/videotoolbox/vtdecompressionoutputcallbackrecord?language=objc)
#[cfg(all(
    feature = "VTErrors",
    feature = "objc2-core-media",
    feature = "objc2-core-video"
))]
#[repr(C, packed(4))]
#[allow(unpredictable_function_pointer_comparisons)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VTDecompressionOutputCallbackRecord {
    pub decompressionOutputCallback: VTDecompressionOutputCallback,
    pub decompressionOutputRefCon: *mut c_void,
}

#[cfg(all(
    feature = "VTErrors",
    feature = "objc2",
    feature = "objc2-core-media",
    feature = "objc2-core-video"
))]
unsafe impl Encode for VTDecompressionOutputCallbackRecord {
    const ENCODING: Encoding = Encoding::Struct(
        "VTDecompressionOutputCallbackRecord",
        &[
            <VTDecompressionOutputCallback>::ENCODING,
            <*mut c_void>::ENCODING,
        ],
    );
}

#[cfg(all(
    feature = "VTErrors",
    feature = "objc2",
    feature = "objc2-core-media",
    feature = "objc2-core-video"
))]
unsafe impl RefEncode for VTDecompressionOutputCallbackRecord {
    const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}

impl VTDecompressionSession {
    /// Creates a session for decompressing video frames.
    ///
    /// Decompressed frames will be emitted through calls to outputCallback.
    ///
    /// Parameter `allocator`: An allocator for the session.  Pass NULL to use the default allocator.
    ///
    /// Parameter `videoFormatDescription`: Describes the source video frames.
    ///
    /// Parameter `videoDecoderSpecification`: Specifies a particular video decoder that must be used.
    /// Pass NULL to let the video toolbox choose a decoder.
    ///
    /// Parameter `destinationImageBufferAttributes`: Describes requirements for emitted pixel buffers.
    /// Pass NULL to set no requirements.
    ///
    /// Parameter `outputCallback`: The callback to be called with decompressed frames.
    /// Pass NULL if and only if you will be calling VTDecompressionSessionDecodeFrameWithOutputHandler for decoding frames.
    ///
    /// Parameter `decompressionSessionOut`: Points to a variable to receive the new decompression session.
    ///
    /// # Safety
    ///
    /// - `video_decoder_specification` generics must be of the correct type.
    /// - `destination_image_buffer_attributes` generics must be of the correct type.
    /// - `output_callback` must be a valid pointer or null.
    /// - `decompression_session_out` must be a valid pointer.
    #[doc(alias = "VTDecompressionSessionCreate")]
    #[cfg(all(
        feature = "VTErrors",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[inline]
    pub unsafe fn create(
        allocator: Option<&CFAllocator>,
        video_format_description: &CMVideoFormatDescription,
        video_decoder_specification: Option<&CFDictionary>,
        destination_image_buffer_attributes: Option<&CFDictionary>,
        output_callback: *const VTDecompressionOutputCallbackRecord,
        decompression_session_out: NonNull<*mut VTDecompressionSession>,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionCreate(
                allocator: Option<&CFAllocator>,
                video_format_description: &CMVideoFormatDescription,
                video_decoder_specification: Option<&CFDictionary>,
                destination_image_buffer_attributes: Option<&CFDictionary>,
                output_callback: *const VTDecompressionOutputCallbackRecord,
                decompression_session_out: NonNull<*mut VTDecompressionSession>,
            ) -> OSStatus;
        }
        unsafe {
            VTDecompressionSessionCreate(
                allocator,
                video_format_description,
                video_decoder_specification,
                destination_image_buffer_attributes,
                output_callback,
                decompression_session_out,
            )
        }
    }

    /// Tears down a decompression session.
    ///
    /// When you are done with a decompression session you created, call VTDecompressionSessionInvalidate
    /// to tear it down and then CFRelease to release your object reference.
    /// When a decompression session's retain count reaches zero, it is automatically invalidated, but
    /// since sessions may be retained by multiple parties, it can be hard to predict when this will happen.
    /// Calling VTDecompressionSessionInvalidate ensures a deterministic, orderly teardown.
    #[doc(alias = "VTDecompressionSessionInvalidate")]
    #[inline]
    pub unsafe fn invalidate(&self) {
        extern "C-unwind" {
            fn VTDecompressionSessionInvalidate(session: &VTDecompressionSession);
        }
        unsafe { VTDecompressionSessionInvalidate(self) }
    }
}

unsafe impl ConcreteType for VTDecompressionSession {
    /// Returns the CFTypeID for decompression sessions.
    #[doc(alias = "VTDecompressionSessionGetTypeID")]
    #[inline]
    fn type_id() -> CFTypeID {
        extern "C-unwind" {
            fn VTDecompressionSessionGetTypeID() -> CFTypeID;
        }
        unsafe { VTDecompressionSessionGetTypeID() }
    }
}

impl VTDecompressionSession {
    /// Decompresses a video frame.
    ///
    /// If an error is returned from this function, there will be no callback.  Otherwise
    /// the callback provided during VTDecompressionSessionCreate will be called.
    ///
    /// Parameter `session`: The decompression session.
    ///
    /// Parameter `sampleBuffer`: A CMSampleBuffer containing one or more video frames.
    ///
    /// Parameter `decodeFlags`: A bitfield of directives to the decompression session and decoder.
    /// The kVTDecodeFrame_EnableAsynchronousDecompression bit indicates whether the video decoder
    /// may decompress the frame asynchronously.
    /// The kVTDecodeFrame_EnableTemporalProcessing bit indicates whether the decoder may delay calls to the output callback
    /// so as to enable processing in temporal (display) order.
    /// If both flags are clear, the decompression shall complete and your output callback function will be called
    /// before VTDecompressionSessionDecodeFrame returns.
    /// If either flag is set, VTDecompressionSessionDecodeFrame may return before the output callback function is called.
    ///
    /// Parameter `sourceFrameRefCon`: Your reference value for the frame.
    /// Note that if sampleBuffer contains multiple frames, the output callback function will be called
    /// multiple times with this sourceFrameRefCon.
    ///
    /// Parameter `infoFlagsOut`: Points to a VTDecodeInfoFlags to receive information about the decode operation.
    /// The kVTDecodeInfo_Asynchronous bit may be set if the decode is (or was) running
    /// asynchronously.
    /// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped (synchronously).
    /// Pass NULL if you do not want to receive this information.
    ///
    /// # Safety
    ///
    /// - `source_frame_ref_con` must be a valid pointer or null.
    /// - `info_flags_out` must be a valid pointer or null.
    #[doc(alias = "VTDecompressionSessionDecodeFrame")]
    #[cfg(all(feature = "VTErrors", feature = "objc2-core-media"))]
    #[inline]
    pub unsafe fn decode_frame(
        &self,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        source_frame_ref_con: *mut c_void,
        info_flags_out: *mut VTDecodeInfoFlags,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionDecodeFrame(
                session: &VTDecompressionSession,
                sample_buffer: &CMSampleBuffer,
                decode_flags: VTDecodeFrameFlags,
                source_frame_ref_con: *mut c_void,
                info_flags_out: *mut VTDecodeInfoFlags,
            ) -> OSStatus;
        }
        unsafe {
            VTDecompressionSessionDecodeFrame(
                self,
                sample_buffer,
                decode_flags,
                source_frame_ref_con,
                info_flags_out,
            )
        }
    }
}

/// Prototype for block invoked when frame decompression is complete.
///
/// When you decode a frame, you pass in a callback block to be called
/// for that decompressed frame.  This block will not necessarily be called in display order.
/// If the VTDecompressionSessionDecodeFrameWithOutputHandler call returns an error, the block
/// will not be called.
///
/// Parameter `status`: noErr if decompression was successful; an error code if decompression was not successful.
///
/// Parameter `infoFlags`: Contains information about the decode operation.
/// The kVTDecodeInfo_Asynchronous bit may be set if the decode ran asynchronously.
/// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped.
/// If the kVTDecodeInfo_ImageBufferModifiable bit is set, it is safe for the client to modify the imageBuffer.
///
/// Parameter `imageBuffer`: Contains the decompressed frame, if decompression was successful; otherwise, NULL.
/// IMPORTANT: The video decompressor may still be referencing the imageBuffer returned in this
/// callback if the kVTDecodeInfo_ImageBufferModifiable flag is not set.  Unless this flag
/// is set, it is not safe to modify the returned imageBuffer.
///
/// Parameter `presentationTimeStamp`: The frame's presentation timestamp; kCMTimeInvalid if not available.
///
/// Parameter `presentationDuration`: The frame's presentation duration; kCMTimeInvalid if not available.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/videotoolbox/vtdecompressionoutputhandler?language=objc)
#[cfg(all(
    feature = "VTErrors",
    feature = "block2",
    feature = "objc2-core-media",
    feature = "objc2-core-video"
))]
pub type VTDecompressionOutputHandler =
    *mut block2::DynBlock<dyn Fn(OSStatus, VTDecodeInfoFlags, *mut CVImageBuffer, CMTime, CMTime)>;

impl VTDecompressionSession {
    /// Decompresses a video frame.
    ///
    /// Cannot be called with a session created with a VTDecompressionOutputCallbackRecord.
    /// If the VTDecompressionSessionDecodeFrameWithOutputHandler call returns an error, the block
    /// will not be called.
    ///
    /// Parameter `session`: The decompression session.
    ///
    /// Parameter `sampleBuffer`: A CMSampleBuffer containing one or more video frames.
    ///
    /// Parameter `decodeFlags`: A bitfield of directives to the decompression session and decoder.
    /// The kVTDecodeFrame_EnableAsynchronousDecompression bit indicates whether the video decoder
    /// may decompress the frame asynchronously.
    /// The kVTDecodeFrame_EnableTemporalProcessing bit indicates whether the decoder may delay calls to the output callback
    /// so as to enable processing in temporal (display) order.
    /// If both flags are clear, the decompression shall complete and your output callback function will be called
    /// before VTDecompressionSessionDecodeFrame returns.
    /// If either flag is set, VTDecompressionSessionDecodeFrame may return before the output callback function is called.
    ///
    /// Parameter `infoFlagsOut`: Points to a VTDecodeInfoFlags to receive information about the decode operation.
    /// The kVTDecodeInfo_Asynchronous bit may be set if the decode is (or was) running
    /// asynchronously.
    /// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped (synchronously).
    /// Pass NULL if you do not want to receive this information.
    ///
    /// Parameter `outputHandler`: The block to be called when decoding the frame is completed.  If the VTDecompressionSessionDecodeFrameWithOutputHandler
    /// call returns an error, the block will not be called.
    ///
    /// # Safety
    ///
    /// - `info_flags_out` must be a valid pointer or null.
    /// - `output_handler` must be a valid pointer.
    #[doc(alias = "VTDecompressionSessionDecodeFrameWithOutputHandler")]
    #[cfg(all(
        feature = "VTErrors",
        feature = "block2",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[inline]
    pub unsafe fn decode_frame_with_output_handler(
        &self,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        info_flags_out: *mut VTDecodeInfoFlags,
        output_handler: VTDecompressionOutputHandler,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionDecodeFrameWithOutputHandler(
                session: &VTDecompressionSession,
                sample_buffer: &CMSampleBuffer,
                decode_flags: VTDecodeFrameFlags,
                info_flags_out: *mut VTDecodeInfoFlags,
                output_handler: VTDecompressionOutputHandler,
            ) -> OSStatus;
        }
        unsafe {
            VTDecompressionSessionDecodeFrameWithOutputHandler(
                self,
                sample_buffer,
                decode_flags,
                info_flags_out,
                output_handler,
            )
        }
    }

    /// Directs the decompression session to emit all delayed frames.
    ///
    /// By default, the decompression session may not delay frames indefinitely;
    /// frames may only be indefinitely delayed if the client opts in via
    /// kVTDecodeFrame_EnableTemporalProcessing.
    /// IMPORTANT NOTE: This function may return before all delayed frames are emitted.
    /// To wait for them, call VTDecompressionSessionWaitForAsynchronousFrames instead.
    #[doc(alias = "VTDecompressionSessionFinishDelayedFrames")]
    #[inline]
    pub unsafe fn finish_delayed_frames(&self) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionFinishDelayedFrames(
                session: &VTDecompressionSession,
            ) -> OSStatus;
        }
        unsafe { VTDecompressionSessionFinishDelayedFrames(self) }
    }

    /// Indicates whether the session can decode frames with the given format description.
    ///
    /// Some video decoders are able to accommodate minor changes in format without needing to be
    /// completely reset in a new session.  This function can be used to test whether a format change
    /// is sufficiently minor.
    #[doc(alias = "VTDecompressionSessionCanAcceptFormatDescription")]
    #[cfg(feature = "objc2-core-media")]
    #[inline]
    pub unsafe fn can_accept_format_description(
        &self,
        new_format_desc: &CMFormatDescription,
    ) -> bool {
        extern "C-unwind" {
            fn VTDecompressionSessionCanAcceptFormatDescription(
                session: &VTDecompressionSession,
                new_format_desc: &CMFormatDescription,
            ) -> Boolean;
        }
        let ret =
            unsafe { VTDecompressionSessionCanAcceptFormatDescription(self, new_format_desc) };
        ret != 0
    }

    /// Waits for any and all outstanding asynchronous and delayed frames to complete, then returns.
    ///
    /// This function automatically calls VTDecompressionSessionFinishDelayedFrames,
    /// so clients don't have to call both.
    #[doc(alias = "VTDecompressionSessionWaitForAsynchronousFrames")]
    #[inline]
    pub unsafe fn wait_for_asynchronous_frames(&self) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionWaitForAsynchronousFrames(
                session: &VTDecompressionSession,
            ) -> OSStatus;
        }
        unsafe { VTDecompressionSessionWaitForAsynchronousFrames(self) }
    }

    /// Copies a black pixel buffer from the decompression session.
    ///
    /// The pixel buffer is in the same format that the session is decompressing to.
    ///
    /// Parameter `session`: The decompression session.
    ///
    /// Parameter `pixelBufferOut`: Points to a variable to receive the copied pixel buffer.
    ///
    /// # Safety
    ///
    /// `pixel_buffer_out` must be a valid pointer.
    #[doc(alias = "VTDecompressionSessionCopyBlackPixelBuffer")]
    #[cfg(feature = "objc2-core-video")]
    #[inline]
    pub unsafe fn copy_black_pixel_buffer(
        &self,
        pixel_buffer_out: NonNull<*mut CVPixelBuffer>,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionCopyBlackPixelBuffer(
                session: &VTDecompressionSession,
                pixel_buffer_out: NonNull<*mut CVPixelBuffer>,
            ) -> OSStatus;
        }
        unsafe { VTDecompressionSessionCopyBlackPixelBuffer(self, pixel_buffer_out) }
    }
}

/// Indicates whether the current system supports hardware decode for a given codec
///
/// This routine reports whether the current system supports hardware decode.  Using
/// this information, clients can make informed decisions regarding remote assets to load,
/// favoring alternate encodings when hardware decode is not supported.
/// This call returning true does not guarantee that hardware decode resources will be
/// available at all times.
#[cfg(feature = "objc2-core-media")]
#[inline]
pub unsafe extern "C-unwind" fn VTIsHardwareDecodeSupported(codec_type: CMVideoCodecType) -> bool {
    extern "C-unwind" {
        fn VTIsHardwareDecodeSupported(codec_type: CMVideoCodecType) -> Boolean;
    }
    let ret = unsafe { VTIsHardwareDecodeSupported(codec_type) };
    ret != 0
}

/// Indicates whether the current system supports stereo MV-HEVC decode.
///
/// This call returning true does not guarantee that decode resources will be available at all times.
#[inline]
pub unsafe extern "C-unwind" fn VTIsStereoMVHEVCDecodeSupported() -> bool {
    extern "C-unwind" {
        fn VTIsStereoMVHEVCDecodeSupported() -> Boolean;
    }
    let ret = unsafe { VTIsStereoMVHEVCDecodeSupported() };
    ret != 0
}

/// Prototype for callback invoked when multi-image frame decompression is complete.
///
/// When you create a decompression session, you pass in a callback function to be called
/// for decompressed frames.  This function will not necessarily be called in display order.
///
/// Parameter `decompressionOutputMultiImageRefCon`: The callback's reference value, copied from the outputMultiImageRefcon passed to
/// VTDecompressionSessionSetMultiImageCallback.
///
/// Parameter `sourceFrameRefCon`: The frame's reference value, copied from the sourceFrameRefCon argument to
/// VTDecompressionSessionDecodeFrame.
///
/// Parameter `status`: noErr if decompression was successful; an error code if decompression was not successful.
///
/// Parameter `infoFlags`: Contains information about the decode operation.
/// The kVTDecodeInfo_Asynchronous bit may be set if the decode ran asynchronously.
/// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped.
/// If the kVTDecodeInfo_ImageBufferModifiable bit is set, it is safe for the client to modify the imageBuffer.
///
/// Parameter `taggedBufferGroup`: Contains the decompressed frame's multiple images, if decompression was successful; otherwise, NULL.
/// IMPORTANT: The video decompressor may still be referencing the pixelBuffers returned in this
/// callback if the kVTDecodeInfo_ImageBufferModifiable flag is not set.  Unless this flag
/// is set, it is not safe to modify the returned pixelBuffers.
///
/// Parameter `presentationTimeStamp`: The frame's presentation timestamp, which will be determined by calling
/// CMSampleBufferGetOutputPresentationTimeStamp; kCMTimeInvalid if not available.
///
/// Parameter `presentationDuration`: The frame's presentation duration, which will be determined by calling
/// CMSampleBufferGetOutputDuration; kCMTimeInvalid if not available.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/videotoolbox/vtdecompressionoutputmultiimagecallback?language=objc)
#[cfg(all(feature = "VTErrors", feature = "objc2-core-media"))]
pub type VTDecompressionOutputMultiImageCallback = Option<
    unsafe extern "C-unwind" fn(
        *mut c_void,
        *mut c_void,
        OSStatus,
        VTDecodeInfoFlags,
        *mut CMTaggedBufferGroup,
        CMTime,
        CMTime,
    ),
>;

impl VTDecompressionSession {
    /// Provides a callback capable of receiving multiple images for individual DecodeFrame requests.
    ///
    /// The outputMultiImageCallback will be used when the video decoder outputs CMTaggedBufferGroups.
    /// When installed, outputMultiImageCallback will also be used when DecodeFrame operations fail and return a nonzero status.
    /// The original single-image callback will only be used in the case where the video decoder outputs a CVImageBuffer instead of a CMTaggedBufferGroup.
    /// Terminology note: in multi-image decompression, a single video sample (from one CMSampleBuffer) contains a single frame (with one PTS) that is decoded to produce multiple images.
    ///
    /// # Safety
    ///
    /// - `output_multi_image_callback` must be implemented correctly.
    /// - `output_multi_image_refcon` must be a valid pointer or null.
    #[doc(alias = "VTDecompressionSessionSetMultiImageCallback")]
    #[cfg(all(feature = "VTErrors", feature = "objc2-core-media"))]
    #[inline]
    pub unsafe fn set_multi_image_callback(
        &self,
        output_multi_image_callback: VTDecompressionOutputMultiImageCallback,
        output_multi_image_refcon: *mut c_void,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionSetMultiImageCallback(
                decompression_session: &VTDecompressionSession,
                output_multi_image_callback: VTDecompressionOutputMultiImageCallback,
                output_multi_image_refcon: *mut c_void,
            ) -> OSStatus;
        }
        unsafe {
            VTDecompressionSessionSetMultiImageCallback(
                self,
                output_multi_image_callback,
                output_multi_image_refcon,
            )
        }
    }
}

/// Prototype for block invoked when frame decompression is complete.
///
/// When you decode a frame, you pass in a callback block to be called
/// for that decompressed frame.  This block will not necessarily be called in display order.
/// If the VTDecompressionSessionDecodeFrameWithOutputHandler call returns an error, the block
/// will not be called.
///
/// Parameter `status`: noErr if decompression was successful; an error code if decompression was not successful.
///
/// Parameter `infoFlags`: Contains information about the decode operation.
/// The kVTDecodeInfo_Asynchronous bit may be set if the decode ran asynchronously.
/// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped.
/// If the kVTDecodeInfo_ImageBufferModifiable bit is set, it is safe for the client to modify the imageBuffer.
///
/// Parameter `imageBuffer`: Contains the decompressed frame, if decompression was successful and the CMSampleBuffer contained
/// a single image frame; otherwise, NULL.
/// IMPORTANT: The video decompressor may still be referencing the imageBuffer returned in this
/// callback if the kVTDecodeInfo_ImageBufferModifiable flag is not set.  Unless this flag
/// is set, it is not safe to modify the returned imageBuffer.
///
/// Parameter `taggedBufferGroup`: Contains the decompressed frame's multiple images, if decompression was successful and the CMSampleBuffer
/// contained a multi-image frame; otherwise, NULL.
/// IMPORTANT: The video decompressor may still be referencing the pixelBuffers returned in this
/// callback if the kVTDecodeInfo_ImageBufferModifiable flag is not set.  Unless this flag
/// is set, it is not safe to modify the returned pixelBuffers.
///
/// Parameter `presentationTimeStamp`: The frame's presentation timestamp; kCMTimeInvalid if not available.
///
/// Parameter `presentationDuration`: The frame's presentation duration; kCMTimeInvalid if not available.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/videotoolbox/vtdecompressionmultiimagecapableoutputhandler?language=objc)
#[cfg(all(
    feature = "VTErrors",
    feature = "block2",
    feature = "objc2-core-media",
    feature = "objc2-core-video"
))]
pub type VTDecompressionMultiImageCapableOutputHandler = *mut block2::DynBlock<
    dyn Fn(
        OSStatus,
        VTDecodeInfoFlags,
        *mut CVImageBuffer,
        *mut CMTaggedBufferGroup,
        CMTime,
        CMTime,
    ),
>;

impl VTDecompressionSession {
    /// Decompresses a video frame.
    ///
    /// Cannot be called with a session created with a VTDecompressionOutputCallbackRecord.
    /// If the VTDecompressionSessionDecodeFrameWithOutputHandler call returns an error, the block
    /// will not be called.
    ///
    /// Parameter `session`: The decompression session.
    ///
    /// Parameter `sampleBuffer`: A CMSampleBuffer containing one or more video frames.
    ///
    /// Parameter `decodeFlags`: A bitfield of directives to the decompression session and decoder.
    /// The kVTDecodeFrame_EnableAsynchronousDecompression bit indicates whether the video decoder
    /// may decompress the frame asynchronously.
    /// The kVTDecodeFrame_EnableTemporalProcessing bit indicates whether the decoder may delay calls to the output callback
    /// so as to enable processing in temporal (display) order.
    /// If both flags are clear, the decompression shall complete and your output callback function will be called
    /// before VTDecompressionSessionDecodeFrame returns.
    /// If either flag is set, VTDecompressionSessionDecodeFrame may return before the output callback function is called.
    ///
    /// Parameter `infoFlagsOut`: Points to a VTDecodeInfoFlags to receive information about the decode operation.
    /// The kVTDecodeInfo_Asynchronous bit may be set if the decode is (or was) running
    /// asynchronously.
    /// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped (synchronously).
    /// Pass NULL if you do not want to receive this information.
    ///
    /// Parameter `multiImageCapableOutputHandler`: The block to be called when decoding the frame is completed.  If the
    /// VTDecompressionSessionDecodeFrameWithMultiImageCapableOutputHandler call returns an error,
    /// the block will not be called.
    ///
    /// # Safety
    ///
    /// - `info_flags_out` must be a valid pointer or null.
    /// - `multi_image_capable_output_handler` must be a valid pointer.
    #[doc(alias = "VTDecompressionSessionDecodeFrameWithMultiImageCapableOutputHandler")]
    #[cfg(all(
        feature = "VTErrors",
        feature = "block2",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[inline]
    pub unsafe fn decode_frame_with_multi_image_capable_output_handler(
        &self,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        info_flags_out: *mut VTDecodeInfoFlags,
        multi_image_capable_output_handler: VTDecompressionMultiImageCapableOutputHandler,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionDecodeFrameWithMultiImageCapableOutputHandler(
                session: &VTDecompressionSession,
                sample_buffer: &CMSampleBuffer,
                decode_flags: VTDecodeFrameFlags,
                info_flags_out: *mut VTDecodeInfoFlags,
                multi_image_capable_output_handler: VTDecompressionMultiImageCapableOutputHandler,
            ) -> OSStatus;
        }
        unsafe {
            VTDecompressionSessionDecodeFrameWithMultiImageCapableOutputHandler(
                self,
                sample_buffer,
                decode_flags,
                info_flags_out,
                multi_image_capable_output_handler,
            )
        }
    }

    /// Decompresses a video frame.
    ///
    /// If an error is returned from this function, there will be no callback.  Otherwise
    /// the callback provided during VTDecompressionSessionCreate will be called.
    ///
    /// Parameter `session`: The decompression session.
    ///
    /// Parameter `sampleBuffer`: A CMSampleBuffer containing one or more video frames.
    ///
    /// Parameter `decodeFlags`: A bitfield of directives to the decompression session and decoder.
    /// The kVTDecodeFrame_EnableAsynchronousDecompression bit indicates whether the video decoder
    /// may decompress the frame asynchronously.
    /// The kVTDecodeFrame_EnableTemporalProcessing bit indicates whether the decoder may delay calls to the output callback
    /// so as to enable processing in temporal (display) order.
    /// If both flags are clear, the decompression shall complete and your output callback function will be called
    /// before VTDecompressionSessionDecodeFrameWithOptions returns.
    /// If either flag is set, VTDecompressionSessionDecodeFrameWithOptions may return before the output callback function is called.
    ///
    /// Parameter `frameOptions`: Contains key/value pairs specifying additional options for decoding this frame.
    /// Only keys with `kVTDecodeFrameOptionKey_` prefix should be used in this dictionary.
    ///
    /// Parameter `sourceFrameRefCon`: Your reference value for the frame.
    /// Note that if sampleBuffer contains multiple frames, the output callback function will be called
    /// multiple times with this sourceFrameRefCon.
    ///
    /// Parameter `infoFlagsOut`: Points to a VTDecodeInfoFlags to receive information about the decode operation.
    /// The kVTDecodeInfo_Asynchronous bit may be set if the decode is (or was) running
    /// asynchronously.
    /// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped (synchronously).
    /// Pass NULL if you do not want to receive this information.
    ///
    /// # Safety
    ///
    /// - `frame_options` generics must be of the correct type.
    /// - `source_frame_ref_con` must be a valid pointer or null.
    /// - `info_flags_out` must be a valid pointer or null.
    #[doc(alias = "VTDecompressionSessionDecodeFrameWithOptions")]
    #[cfg(all(feature = "VTErrors", feature = "objc2-core-media"))]
    #[inline]
    pub unsafe fn decode_frame_with_options(
        &self,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        frame_options: Option<&CFDictionary>,
        source_frame_ref_con: *mut c_void,
        info_flags_out: *mut VTDecodeInfoFlags,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionDecodeFrameWithOptions(
                session: &VTDecompressionSession,
                sample_buffer: &CMSampleBuffer,
                decode_flags: VTDecodeFrameFlags,
                frame_options: Option<&CFDictionary>,
                source_frame_ref_con: *mut c_void,
                info_flags_out: *mut VTDecodeInfoFlags,
            ) -> OSStatus;
        }
        unsafe {
            VTDecompressionSessionDecodeFrameWithOptions(
                self,
                sample_buffer,
                decode_flags,
                frame_options,
                source_frame_ref_con,
                info_flags_out,
            )
        }
    }

    /// Decompresses a video frame.
    ///
    /// Cannot be called with a session created with a VTDecompressionOutputCallbackRecord.
    /// If the VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler call returns an error,
    /// the block will not be called.
    ///
    /// Parameter `session`: The decompression session.
    ///
    /// Parameter `sampleBuffer`: A CMSampleBuffer containing one or more video frames.
    ///
    /// Parameter `decodeFlags`: A bitfield of directives to the decompression session and decoder.
    /// The kVTDecodeFrame_EnableAsynchronousDecompression bit indicates whether the video decoder
    /// may decompress the frame asynchronously.
    /// The kVTDecodeFrame_EnableTemporalProcessing bit indicates whether the decoder may delay calls to the output callback
    /// so as to enable processing in temporal (display) order.
    /// If both flags are clear, the decompression shall complete and your output callback function will be called
    /// before VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler returns.
    /// If either flag is set, VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler may return before the output
    /// callback function is called.
    ///
    /// Parameter `frameOptions`: Contains key/value pairs specifying additional options for decoding this frame.
    /// Only keys with `kVTDecodeFrameOptionKey_` prefix should be used in this dictionary.
    ///
    /// Parameter `infoFlagsOut`: Points to a VTDecodeInfoFlags to receive information about the decode operation.
    /// The kVTDecodeInfo_Asynchronous bit may be set if the decode is (or was) running
    /// asynchronously.
    /// The kVTDecodeInfo_FrameDropped bit may be set if the frame was dropped (synchronously).
    /// Pass NULL if you do not want to receive this information.
    ///
    /// Parameter `outputHandler`: The block to be called when decoding the frame is completed.  If the VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler
    /// call returns an error, the block will not be called.
    ///
    /// # Safety
    ///
    /// - `frame_options` generics must be of the correct type.
    /// - `info_flags_out` must be a valid pointer or null.
    /// - `output_handler` must be a valid pointer.
    #[doc(alias = "VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler")]
    #[cfg(all(
        feature = "VTErrors",
        feature = "block2",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[inline]
    pub unsafe fn decode_frame_with_options_and_output_handler(
        &self,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        frame_options: Option<&CFDictionary>,
        info_flags_out: *mut VTDecodeInfoFlags,
        output_handler: VTDecompressionOutputHandler,
    ) -> OSStatus {
        extern "C-unwind" {
            fn VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler(
                session: &VTDecompressionSession,
                sample_buffer: &CMSampleBuffer,
                decode_flags: VTDecodeFrameFlags,
                frame_options: Option<&CFDictionary>,
                info_flags_out: *mut VTDecodeInfoFlags,
                output_handler: VTDecompressionOutputHandler,
            ) -> OSStatus;
        }
        unsafe {
            VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler(
                self,
                sample_buffer,
                decode_flags,
                frame_options,
                info_flags_out,
                output_handler,
            )
        }
    }
}

extern "C-unwind" {
    #[cfg(all(
        feature = "VTErrors",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[deprecated = "renamed to `VTDecompressionSession::create`"]
    pub fn VTDecompressionSessionCreate(
        allocator: Option<&CFAllocator>,
        video_format_description: &CMVideoFormatDescription,
        video_decoder_specification: Option<&CFDictionary>,
        destination_image_buffer_attributes: Option<&CFDictionary>,
        output_callback: *const VTDecompressionOutputCallbackRecord,
        decompression_session_out: NonNull<*mut VTDecompressionSession>,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[deprecated = "renamed to `VTDecompressionSession::invalidate`"]
    pub fn VTDecompressionSessionInvalidate(session: &VTDecompressionSession);
}

extern "C-unwind" {
    #[cfg(all(feature = "VTErrors", feature = "objc2-core-media"))]
    #[deprecated = "renamed to `VTDecompressionSession::decode_frame`"]
    pub fn VTDecompressionSessionDecodeFrame(
        session: &VTDecompressionSession,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        source_frame_ref_con: *mut c_void,
        info_flags_out: *mut VTDecodeInfoFlags,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[cfg(all(
        feature = "VTErrors",
        feature = "block2",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[deprecated = "renamed to `VTDecompressionSession::decode_frame_with_output_handler`"]
    pub fn VTDecompressionSessionDecodeFrameWithOutputHandler(
        session: &VTDecompressionSession,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        info_flags_out: *mut VTDecodeInfoFlags,
        output_handler: VTDecompressionOutputHandler,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[deprecated = "renamed to `VTDecompressionSession::finish_delayed_frames`"]
    pub fn VTDecompressionSessionFinishDelayedFrames(session: &VTDecompressionSession) -> OSStatus;
}

#[cfg(feature = "objc2-core-media")]
#[deprecated = "renamed to `VTDecompressionSession::can_accept_format_description`"]
#[inline]
pub unsafe extern "C-unwind" fn VTDecompressionSessionCanAcceptFormatDescription(
    session: &VTDecompressionSession,
    new_format_desc: &CMFormatDescription,
) -> bool {
    extern "C-unwind" {
        fn VTDecompressionSessionCanAcceptFormatDescription(
            session: &VTDecompressionSession,
            new_format_desc: &CMFormatDescription,
        ) -> Boolean;
    }
    let ret = unsafe { VTDecompressionSessionCanAcceptFormatDescription(session, new_format_desc) };
    ret != 0
}

extern "C-unwind" {
    #[deprecated = "renamed to `VTDecompressionSession::wait_for_asynchronous_frames`"]
    pub fn VTDecompressionSessionWaitForAsynchronousFrames(
        session: &VTDecompressionSession,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[cfg(feature = "objc2-core-video")]
    #[deprecated = "renamed to `VTDecompressionSession::copy_black_pixel_buffer`"]
    pub fn VTDecompressionSessionCopyBlackPixelBuffer(
        session: &VTDecompressionSession,
        pixel_buffer_out: NonNull<*mut CVPixelBuffer>,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[cfg(all(feature = "VTErrors", feature = "objc2-core-media"))]
    #[deprecated = "renamed to `VTDecompressionSession::set_multi_image_callback`"]
    pub fn VTDecompressionSessionSetMultiImageCallback(
        decompression_session: &VTDecompressionSession,
        output_multi_image_callback: VTDecompressionOutputMultiImageCallback,
        output_multi_image_refcon: *mut c_void,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[cfg(all(
        feature = "VTErrors",
        feature = "block2",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[deprecated = "renamed to `VTDecompressionSession::decode_frame_with_multi_image_capable_output_handler`"]
    pub fn VTDecompressionSessionDecodeFrameWithMultiImageCapableOutputHandler(
        session: &VTDecompressionSession,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        info_flags_out: *mut VTDecodeInfoFlags,
        multi_image_capable_output_handler: VTDecompressionMultiImageCapableOutputHandler,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[cfg(all(feature = "VTErrors", feature = "objc2-core-media"))]
    #[deprecated = "renamed to `VTDecompressionSession::decode_frame_with_options`"]
    pub fn VTDecompressionSessionDecodeFrameWithOptions(
        session: &VTDecompressionSession,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        frame_options: Option<&CFDictionary>,
        source_frame_ref_con: *mut c_void,
        info_flags_out: *mut VTDecodeInfoFlags,
    ) -> OSStatus;
}

extern "C-unwind" {
    #[cfg(all(
        feature = "VTErrors",
        feature = "block2",
        feature = "objc2-core-media",
        feature = "objc2-core-video"
    ))]
    #[deprecated = "renamed to `VTDecompressionSession::decode_frame_with_options_and_output_handler`"]
    pub fn VTDecompressionSessionDecodeFrameWithOptionsAndOutputHandler(
        session: &VTDecompressionSession,
        sample_buffer: &CMSampleBuffer,
        decode_flags: VTDecodeFrameFlags,
        frame_options: Option<&CFDictionary>,
        info_flags_out: *mut VTDecodeInfoFlags,
        output_handler: VTDecompressionOutputHandler,
    ) -> OSStatus;
}