videotoolbox 0.21.0

Safe Rust bindings for Apple's VideoToolbox framework — hardware H.264/HEVC/ProRes encode and decode on macOS
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
//! [`DecompressionSession`] — hardware H.264/HEVC/ProRes decoder.
//!
//! Mirror of [`crate::compression::CompressionSession`] for the decoder
//! direction. Feed `CMSampleBuffer`s in via [`DecompressionSession::decode`],
//! receive `CVPixelBuffer`s out via the callback you registered at construction.

use core::ffi::c_void;
use core::ptr;
use std::sync::{Arc, Mutex};

use apple_cf::cf::{AsCFType, CFDictionary, CFType};
use apple_cf::cm::CMTime;
#[cfg(feature = "async")]
use doom_fish_utils::completion::AsyncCompletion;
use doom_fish_utils::panic_safe::catch_user_panic;

use crate::error::VTError;
use crate::ffi;
use crate::session::{self, Codec};
use crate::tagged_buffer_group::TaggedBufferGroup;

/// One decoded video frame.
pub struct DecodedFrame {
    /// Underlying `CVImageBuffer` (typically a `CVPixelBuffer`) — `None`
    /// when the decoder dropped or skipped a frame.
    pub image_buffer: Option<apple_cf::cv::CVPixelBuffer>,
    /// Presentation timestamp of the source sample buffer.
    pub presentation_time: CMTime,
    /// Presentation duration of the decoded frame.
    pub duration: CMTime,
    /// Decoder hint flags (asynchronous / image-buffer-modifiable / etc.).
    pub info_flags: ffi::VTDecodeInfoFlags,
    /// Apple's decoder status code. 0 indicates success.
    pub status: i32,
}

/// One decoded multi-image frame.
pub struct DecodedMultiImageFrame {
    /// Multi-image output (for example left/right eye pixel buffers).
    pub tagged_buffer_group: Option<TaggedBufferGroup>,
    /// Presentation timestamp of the source sample buffer.
    pub presentation_time: CMTime,
    /// Presentation duration of the decoded frame.
    pub duration: CMTime,
    /// Decoder hint flags (asynchronous / image-buffer-modifiable / etc.).
    pub info_flags: ffi::VTDecodeInfoFlags,
    /// Apple's decoder status code. 0 indicates success.
    pub status: i32,
}

type DecodeCallback = Box<dyn FnMut(DecodedFrame) + Send + 'static>;
type MultiImageDecodeCallback = Box<dyn FnMut(DecodedMultiImageFrame) + Send + 'static>;

struct CallbackState {
    callback: Mutex<DecodeCallback>,
    multi_image_callback: Mutex<Option<MultiImageDecodeCallback>>,
}

/// Hardware video decompression session.
///
/// Build with [`DecompressionSession::new`] passing a format description
/// (from the encoder side, or extracted from your input file). Decoded
/// frames flow through the callback you supply.
///
/// # Lifetime / threading
///
/// Drop the session to invalidate it. Decoder callbacks fire on Apple's
/// internal queue — they may run after `decode()` returns and before
/// `wait_for_async_frames()`.
pub struct DecompressionSession {
    session: ffi::VTDecompressionSessionRef,
    state: Arc<CallbackState>,
    callback_ref_con: *const CallbackState,
}

unsafe impl Send for DecompressionSession {}

impl DecompressionSession {
    /// CoreFoundation type identifier for `VTDecompressionSession`.
    #[must_use]
    pub fn type_id() -> usize {
        // SAFETY: `VTDecompressionSessionGetTypeID` is a standard Apple SDK function
        // that returns a static type ID. Safe to call from any thread.
        unsafe { ffi::VTDecompressionSessionGetTypeID() }
    }

    /// Returns `true` when the current machine advertises hardware decode for
    /// the given codec family.
    #[must_use]
    pub fn is_hardware_decode_supported(codec: Codec) -> bool {
        // SAFETY: `VTIsHardwareDecodeSupported` is a standard query function
        // that performs no I/O and has no side effects.
        unsafe { ffi::VTIsHardwareDecodeSupported(codec.as_cm_codec_type()) != 0 }
    }

    /// Returns `true` when the current machine advertises stereo MV-HEVC
    /// decode support.
    #[must_use]
    pub fn is_stereo_mvhevc_decode_supported() -> bool {
        ffi::dynamic::VTIsStereoMVHEVCDecodeSupported()
            .is_ok_and(|is_supported| unsafe { is_supported() } != 0)
    }

    /// Open a decompression session for the given format description.
    /// `format_description` is the `CMFormatDescriptionRef` Apple expects
    /// — typically obtained from `CMSampleBuffer.format_description()` on
    /// the first sample of the stream.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::EncoderCallback`] wrapping the raw `OSStatus`
    /// if `VTDecompressionSessionCreate` fails.
    pub fn new<F>(
        format_description: &apple_cf::cm::CMFormatDescription,
        callback: F,
    ) -> Result<Self, VTError>
    where
        F: FnMut(DecodedFrame) + Send + 'static,
    {
        Self::new_with_image_buffer_attributes(format_description, None, callback)
    }

    /// Like [`new`](Self::new) but lets you specify the decoder's destination
    /// image-buffer attributes (the `destinationImageBufferAttributes` argument
    /// to `VTDecompressionSessionCreate`).
    ///
    /// Use this to force the output pixel format (for example a `420f`
    /// full-range NV12 buffer required by some renderers) or to require
    /// `IOSurface` backing for zero-copy GPU interop, by passing a dictionary
    /// keyed on `kCVPixelBufferPixelFormatTypeKey` /
    /// `kCVPixelBufferIOSurfacePropertiesKey`.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::EncoderCallback`] wrapping the raw `OSStatus`
    /// if `VTDecompressionSessionCreate` fails.
    pub fn new_with_image_buffer_attributes<F>(
        format_description: &apple_cf::cm::CMFormatDescription,
        image_buffer_attributes: Option<&CFDictionary>,
        callback: F,
    ) -> Result<Self, VTError>
    where
        F: FnMut(DecodedFrame) + Send + 'static,
    {
        let state = Arc::new(CallbackState {
            callback: Mutex::new(Box::new(callback)),
            multi_image_callback: Mutex::new(None),
        });
        let callback_ref_con = Arc::into_raw(Arc::clone(&state));
        let ref_con = callback_ref_con.cast::<c_void>().cast_mut();

        let record = ffi::VTDecompressionOutputCallbackRecord {
            decompression_output_callback: decode_trampoline,
            decompression_output_ref_con: ref_con,
        };

        let mut session: ffi::VTDecompressionSessionRef = ptr::null_mut();
        let status = unsafe {
            ffi::VTDecompressionSessionCreate(
                ffi::kCFAllocatorDefault,
                format_description.as_ptr().cast(),
                ptr::null(),
                image_buffer_attributes.map_or(ptr::null(), |d| AsCFType::as_ptr(d).cast()),
                &raw const record,
                &raw mut session,
            )
        };
        if status != 0 || session.is_null() {
            unsafe { drop(Arc::from_raw(callback_ref_con)) };
            return Err(VTError::EncoderCallback(if status == 0 {
                -1
            } else {
                status
            }));
        }
        Ok(Self {
            session,
            state,
            callback_ref_con,
        })
    }

    /// Decode `sample_buffer`. The callback you registered at construction
    /// will fire with the resulting [`DecodedFrame`] — either synchronously
    /// before this method returns, or asynchronously after, depending on
    /// the decoder backend.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::EncoderCallback`] wrapping the raw `OSStatus`
    /// if `VTDecompressionSessionDecodeFrame` rejects the sample buffer.
    pub fn decode(&self, sample_buffer: &apple_cf::cm::CMSampleBuffer) -> Result<(), VTError> {
        self.decode_with_options(sample_buffer, 0, None).map(|_| ())
    }

    /// Decode `sample_buffer` with explicit `VTDecodeFrameFlags` and optional
    /// per-frame `kVTDecodeFrameOptionKey_*` entries.
    ///
    /// Returns the `VTDecodeInfoFlags` reported for the submit operation.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::Unsupported`] if `frame_options` is set before
    /// macOS 15.0 (`VTDecompressionSessionDecodeFrameWithOptions`), or
    /// [`VTError::EncoderCallback`] wrapping the raw `OSStatus` if the decoder
    /// rejects the sample buffer.
    pub fn decode_with_options(
        &self,
        sample_buffer: &apple_cf::cm::CMSampleBuffer,
        decode_flags: ffi::VTDecodeFrameFlags,
        frame_options: Option<&CFDictionary>,
    ) -> Result<ffi::VTDecodeInfoFlags, VTError> {
        let mut info_flags: ffi::VTDecodeInfoFlags = 0;
        let status = match frame_options {
            None => unsafe {
                ffi::VTDecompressionSessionDecodeFrame(
                    self.session,
                    sample_buffer.as_ptr().cast(),
                    decode_flags,
                    ptr::null_mut(),
                    &raw mut info_flags,
                )
            },
            Some(frame_options) => {
                let decode = ffi::dynamic::VTDecompressionSessionDecodeFrameWithOptions()?;
                unsafe {
                    decode(
                        self.session,
                        sample_buffer.as_ptr().cast(),
                        decode_flags,
                        frame_options.as_ptr().cast_const().cast(),
                        ptr::null_mut(),
                        &raw mut info_flags,
                    )
                }
            }
        };
        if status == 0 {
            Ok(info_flags)
        } else {
            Err(VTError::EncoderCallback(status))
        }
    }

    /// Submit `sample_buffer` for decoding and await the decoded `CVImageBuffer`.
    ///
    /// This method requires the crate's `async` feature.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::UnexpectedSampleCount`] if `sample_buffer` does not
    /// contain exactly one sample. Returns [`VTError::EncoderCallback`] if the
    /// decoder rejects the frame, reports an asynchronous failure, or completes
    /// without an image buffer.
    #[cfg(feature = "async")]
    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
    #[allow(clippy::future_not_send)]
    pub async fn decode_frame_async(
        &self,
        sample_buffer: apple_cf::cm::CMSampleBuffer,
        frame_flags: u32,
    ) -> Result<apple_cf::cv::CVImageBuffer, VTError> {
        validate_async_sample_count(&sample_buffer)?;

        let (future, completion) = AsyncCompletion::<apple_cf::cv::CVImageBuffer>::create();
        let status = unsafe {
            ffi::VTDecompressionSessionDecodeFrame(
                self.session,
                sample_buffer.as_ptr().cast(),
                frame_flags,
                completion,
                ptr::null_mut(),
            )
        };
        if status != 0 {
            unsafe {
                AsyncCompletion::<apple_cf::cv::CVImageBuffer>::complete_err(
                    completion,
                    status.to_string(),
                );
            };
            return Err(VTError::EncoderCallback(status));
        }

        future
            .await
            .map_err(|error| VTError::EncoderCallback(parse_async_status(&error)))
    }

    /// Install a callback that receives multi-image output when the decoder
    /// produces a `CMTaggedBufferGroup` instead of a single `CVImageBuffer`.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::Unsupported`] before macOS 14.0, or
    /// [`VTError::ApiFailed`] if the decoder rejects the callback.
    pub fn set_multi_image_callback<F>(&self, callback: F) -> Result<(), VTError>
    where
        F: FnMut(DecodedMultiImageFrame) + Send + 'static,
    {
        let set_callback = ffi::dynamic::VTDecompressionSessionSetMultiImageCallback()?;
        {
            let mut slot = self
                .state
                .multi_image_callback
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *slot = Some(Box::new(callback));
        }

        let status = unsafe {
            set_callback(
                self.session,
                decode_multi_image_trampoline,
                Arc::as_ptr(&self.state).cast::<c_void>().cast_mut(),
            )
        };
        if status != 0 {
            let mut slot = self
                .state
                .multi_image_callback
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *slot = None;
            drop(slot);
            return Err(VTError::ApiFailed {
                api: "VTDecompressionSessionSetMultiImageCallback",
                status,
            });
        }
        Ok(())
    }

    /// Wait for any queued async decodes to complete. Equivalent to
    /// `VTDecompressionSessionWaitForAsynchronousFrames`. Call this
    /// before dropping the session if you want to be sure every frame's
    /// callback has fired.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::EncoderCallback`] on a non-zero `OSStatus`.
    pub fn wait_for_async_frames(&self) -> Result<(), VTError> {
        let status = unsafe { ffi::VTDecompressionSessionWaitForAsynchronousFrames(self.session) };
        if status == 0 {
            Ok(())
        } else {
            Err(VTError::EncoderCallback(status))
        }
    }

    /// Drain pending callbacks, invalidate the decoder, and release its native resources.
    ///
    /// Unlike `Drop`, this surfaces a failure to prove that callbacks are
    /// quiescent. On that exceptional path the native callback context is kept
    /// alive to prevent an in-flight callback from observing freed Rust state.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::ApiFailed`] if
    /// `VTDecompressionSessionWaitForAsynchronousFrames` fails.
    pub fn invalidate(mut self) -> Result<(), VTError> {
        self.teardown()
    }

    /// Copy a black pixel buffer matching the session's current output format.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::ApiFailed`] on a non-zero `OSStatus`.
    pub fn copy_black_pixel_buffer(&self) -> Result<apple_cf::cv::CVPixelBuffer, VTError> {
        let mut out = ptr::null_mut();
        let status =
            unsafe { ffi::VTDecompressionSessionCopyBlackPixelBuffer(self.session, &raw mut out) };
        if status != 0 || out.is_null() {
            return Err(VTError::ApiFailed {
                api: "VTDecompressionSessionCopyBlackPixelBuffer",
                status,
            });
        }
        unsafe { apple_cf::cv::CVPixelBuffer::from_raw(out.cast()) }.ok_or(VTError::ApiFailed {
            api: "VTDecompressionSessionCopyBlackPixelBuffer",
            status,
        })
    }

    /// Copy one `VTSession` property from the decoder.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::ApiFailed`] if the underlying property query fails.
    ///
    /// # Safety
    ///
    /// `key` must be a valid CoreFoundation string pointer accepted by
    /// `VTSessionCopyProperty` for a decompression session.
    pub unsafe fn copy_property(&self, key: ffi::CFStringRef) -> Result<Option<CFType>, VTError> {
        session::copy_property(self.session.cast(), key)
    }

    /// Copy the decoder's supported-property dictionary.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::ApiFailed`] if the query fails.
    pub fn supported_property_dictionary(&self) -> Result<CFDictionary, VTError> {
        unsafe { session::copy_supported_property_dictionary(self.session.cast()) }
    }

    /// Copy the decoder's serializable property dictionary.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::ApiFailed`] if the query fails.
    pub fn serializable_properties(&self) -> Result<CFDictionary, VTError> {
        unsafe { session::copy_serializable_properties(self.session.cast()) }
    }

    /// Set multiple decoder properties at once.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::ApiFailed`] if `VideoToolbox` rejects the dictionary.
    pub fn set_properties(&self, properties: &CFDictionary) -> Result<(), VTError> {
        unsafe { session::set_properties(self.session.cast(), properties) }
    }

    /// Set an arbitrary property on the underlying
    /// `VTDecompressionSession`. `value` must be a CoreFoundation
    /// object matching Apple's per-key contract (see
    /// `VTDecompressionProperties.h`).
    ///
    /// # Errors
    ///
    /// Returns [`VTError::SetPropertyFailed`] if Apple rejects the
    /// key/value pair.
    ///
    /// # Safety
    ///
    /// `key` must be a valid `CFStringRef` and `value` must be a
    /// valid CoreFoundation pointer for the property's expected type.
    pub unsafe fn set_property(
        &self,
        key: ffi::CFStringRef,
        value: ffi::CFTypeRef,
    ) -> Result<(), VTError> {
        let status = ffi::VTSessionSetProperty(self.session.cast(), key, value);
        if status != 0 {
            return Err(VTError::SetPropertyFailed {
                key: "<custom>".to_string(),
                status,
            });
        }
        Ok(())
    }

    /// Tell the decoder that this is real-time playback (prioritise
    /// low latency over throughput). Wraps the boolean property
    /// `kVTDecompressionPropertyKey_RealTime`.
    ///
    /// # Errors
    ///
    /// See [`Self::set_property`].
    pub fn set_real_time(&self, real_time: bool) -> Result<(), VTError> {
        let v = unsafe {
            if real_time {
                ffi::kCFBooleanTrue
            } else {
                ffi::kCFBooleanFalse
            }
        };
        unsafe { self.set_property(ffi::kVTDecompressionPropertyKey_RealTime, v.cast()) }
    }

    /// Finish any decoded frames the decoder has been holding back
    /// for B-frame reordering. Wraps
    /// `VTDecompressionSessionFinishDelayedFrames`.
    ///
    /// # Errors
    ///
    /// Returns [`VTError::EncoderCallback`] on non-zero `OSStatus`.
    pub fn finish_delayed_frames(&self) -> Result<(), VTError> {
        let status = unsafe { ffi::VTDecompressionSessionFinishDelayedFrames(self.session) };
        if status == 0 {
            Ok(())
        } else {
            Err(VTError::EncoderCallback(status))
        }
    }

    /// True if this session can decode samples described by `format`
    /// without rebuilding the session. Wraps
    /// `VTDecompressionSessionCanAcceptFormatDescription`.
    ///
    /// # Safety
    ///
    /// `format` must be a valid `CMFormatDescriptionRef` (typically
    /// obtained from another `CMSampleBuffer`).
    #[must_use]
    pub unsafe fn can_accept_format(&self, format: ffi::CMFormatDescriptionRef) -> bool {
        ffi::VTDecompressionSessionCanAcceptFormatDescription(self.session, format)
    }

    fn teardown(&mut self) -> Result<(), VTError> {
        if self.session.is_null() {
            return Ok(());
        }

        let wait_status =
            unsafe { ffi::VTDecompressionSessionWaitForAsynchronousFrames(self.session) };
        unsafe {
            ffi::VTDecompressionSessionInvalidate(self.session);
            ffi::CFRelease(self.session.cast());
        }
        self.session = ptr::null_mut();

        if wait_status == 0 {
            self.release_callback_ref_con();
            Ok(())
        } else {
            // A failed drain cannot prove that native code is done with the ref-con.
            self.callback_ref_con = ptr::null();
            Err(VTError::ApiFailed {
                api: "VTDecompressionSessionWaitForAsynchronousFrames",
                status: wait_status,
            })
        }
    }

    fn release_callback_ref_con(&mut self) {
        let callback_ref_con = core::mem::replace(&mut self.callback_ref_con, ptr::null());
        if !callback_ref_con.is_null() {
            unsafe { drop(Arc::from_raw(callback_ref_con)) };
        }
    }
}

impl Drop for DecompressionSession {
    fn drop(&mut self) {
        let _ = self.teardown();
    }
}

#[cfg(feature = "async")]
fn parse_async_status(error: &str) -> ffi::OSStatus {
    error.parse().unwrap_or(-1)
}

#[cfg(feature = "async")]
fn validate_async_sample_count(
    sample_buffer: &apple_cf::cm::CMSampleBuffer,
) -> Result<(), VTError> {
    let actual = sample_buffer.num_samples();
    if actual == 1 {
        Ok(())
    } else {
        Err(VTError::UnexpectedSampleCount {
            operation: "DecompressionSession::decode_frame_async",
            expected: 1,
            actual,
        })
    }
}

#[cfg(feature = "async")]
fn complete_async_decode(
    source_frame_ref_con: *mut c_void,
    status: ffi::OSStatus,
    image_buffer: *mut c_void,
) {
    catch_user_panic("videotoolbox::decompression::decode_frame_async", || {
        if status != 0 {
            unsafe {
                AsyncCompletion::<apple_cf::cv::CVImageBuffer>::complete_err(
                    source_frame_ref_con,
                    status.to_string(),
                );
            };
            return;
        }

        if image_buffer.is_null() {
            unsafe {
                AsyncCompletion::<apple_cf::cv::CVImageBuffer>::complete_err(
                    source_frame_ref_con,
                    "-1".into(),
                );
            };
            return;
        }

        let Some(image_buffer) =
            (unsafe { apple_cf::cv::CVImageBuffer::from_raw_borrowed(image_buffer) })
        else {
            unsafe {
                AsyncCompletion::<apple_cf::cv::CVImageBuffer>::complete_err(
                    source_frame_ref_con,
                    "-1".into(),
                );
            };
            return;
        };

        unsafe {
            AsyncCompletion::<apple_cf::cv::CVImageBuffer>::complete_ok(
                source_frame_ref_con,
                image_buffer,
            );
        };
    });
}

unsafe extern "C" fn decode_trampoline(
    output_ref_con: *mut c_void,
    source_frame_ref_con: *mut c_void,
    status: ffi::OSStatus,
    info_flags: ffi::VTDecodeInfoFlags,
    image_buffer: *mut c_void,
    pts: ffi::CMTime,
    duration: ffi::CMTime,
) {
    #[cfg(not(feature = "async"))]
    let _ = source_frame_ref_con;
    #[cfg(feature = "async")]
    if !source_frame_ref_con.is_null() {
        complete_async_decode(source_frame_ref_con, status, image_buffer);
        return;
    }

    if output_ref_con.is_null() {
        return;
    }
    // Borrow the Arc without consuming the reference held by the session.
    let state = unsafe { Arc::from_raw(output_ref_con.cast::<CallbackState>()) };
    let state_clone = state.clone();
    core::mem::forget(state);

    let image = if image_buffer.is_null() {
        None
    } else {
        unsafe { apple_cf::cv::CVPixelBuffer::from_raw_borrowed(image_buffer) }
    };

    let frame = DecodedFrame {
        image_buffer: image,
        presentation_time: pts,
        duration,
        info_flags,
        status,
    };

    let Ok(mut guard) = state_clone.callback.lock() else {
        return;
    };
    // The user closure may panic. Unwinding across this `extern "C"` boundary
    // back into VideoToolbox is undefined behaviour, so guard the invocation.
    catch_user_panic("videotoolbox::decompression::decode_callback", || {
        guard(frame);
    });
}

unsafe extern "C" fn decode_multi_image_trampoline(
    output_ref_con: *mut c_void,
    source_frame_ref_con: *mut c_void,
    status: ffi::OSStatus,
    info_flags: ffi::VTDecodeInfoFlags,
    tagged_buffer_group: ffi::CMTaggedBufferGroupRef,
    pts: ffi::CMTime,
    duration: ffi::CMTime,
) {
    #[cfg(not(feature = "async"))]
    let _ = source_frame_ref_con;
    #[cfg(feature = "async")]
    if !source_frame_ref_con.is_null() {
        complete_async_decode(source_frame_ref_con, status, ptr::null_mut());
        return;
    }

    if output_ref_con.is_null() {
        return;
    }
    let state = unsafe { Arc::from_raw(output_ref_con.cast::<CallbackState>()) };
    let state_clone = state.clone();
    core::mem::forget(state);

    let frame = DecodedMultiImageFrame {
        tagged_buffer_group: unsafe { TaggedBufferGroup::from_raw_retained(tagged_buffer_group) },
        presentation_time: pts,
        duration,
        info_flags,
        status,
    };

    let Ok(mut guard) = state_clone.multi_image_callback.lock() else {
        return;
    };
    let Some(callback) = guard.as_mut() else {
        return;
    };
    // The user closure may panic; unwinding across this `extern "C"` boundary
    // back into VideoToolbox is undefined behaviour, so guard the invocation.
    catch_user_panic("videotoolbox::decompression::multi_image_callback", || {
        callback(frame);
    });
}

#[cfg(test)]
mod tests {
    use core::ptr;
    use std::sync::{Arc, Mutex};

    use apple_cf::cm::CMTime;

    use super::{decode_multi_image_trampoline, CallbackState};

    fn state() -> Arc<CallbackState> {
        Arc::new(CallbackState {
            callback: Mutex::new(Box::new(|_| {})),
            multi_image_callback: Mutex::new(None),
        })
    }

    #[cfg(feature = "async")]
    fn deliver_to_pending_decode(status: i32) -> Result<apple_cf::cv::CVImageBuffer, String> {
        use doom_fish_utils::completion::AsyncCompletion;

        let state = state();
        let (future, context) = AsyncCompletion::<apple_cf::cv::CVImageBuffer>::create();
        unsafe {
            decode_multi_image_trampoline(
                Arc::as_ptr(&state).cast_mut().cast(),
                context,
                status,
                0,
                ptr::null_mut(),
                CMTime::new(1, 30),
                CMTime::new(1, 30),
            );
        }
        pollster::block_on(future)
    }

    #[cfg(feature = "async")]
    #[test]
    fn multi_image_failure_resolves_the_pending_async_decode() {
        assert_eq!(
            deliver_to_pending_decode(-12909).err().as_deref(),
            Some("-12909")
        );
    }

    #[cfg(feature = "async")]
    #[test]
    fn multi_image_output_without_an_image_buffer_resolves_the_async_decode() {
        assert_eq!(deliver_to_pending_decode(0).err().as_deref(), Some("-1"));
    }

    #[test]
    fn multi_image_output_without_a_frame_context_reaches_the_callback() {
        let received = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&received);
        let state = state();
        *state.multi_image_callback.lock().expect("unpoisoned") =
            Some(Box::new(move |frame: super::DecodedMultiImageFrame| {
                sink.lock().expect("unpoisoned").push((
                    frame.status,
                    frame.presentation_time,
                    frame.duration,
                ));
            }));

        unsafe {
            decode_multi_image_trampoline(
                Arc::as_ptr(&state).cast_mut().cast(),
                ptr::null_mut(),
                -12909,
                0,
                ptr::null_mut(),
                CMTime::new(3, 30),
                CMTime::new(1, 30),
            );
        }

        assert_eq!(
            *received.lock().expect("unpoisoned"),
            [(-12909, CMTime::new(3, 30), CMTime::new(1, 30))]
        );
    }

    #[test]
    fn panicking_multi_image_callback_is_contained() {
        let state = state();
        *state.multi_image_callback.lock().expect("unpoisoned") =
            Some(Box::new(|_| panic!("callback panic")));

        unsafe {
            decode_multi_image_trampoline(
                Arc::as_ptr(&state).cast_mut().cast(),
                ptr::null_mut(),
                0,
                0,
                ptr::null_mut(),
                CMTime::new(0, 30),
                CMTime::new(1, 30),
            );
        }
    }
}