videotoolbox 0.10.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
//! Raw `extern "C"` declarations against `<VideoToolbox/VideoToolbox.h>`,
//! `<CoreMedia/CoreMedia.h>`, `<CoreVideo/CVPixelBuffer.h>`, and
//! `<CoreFoundation/CoreFoundation.h>`.
//!
//! These are intentionally `unsafe` and opaque (`*const c_void` / `*mut c_void`).
//! Safe wrappers live in [`crate::compression`] and [`crate::session`].

#![allow(missing_docs, non_camel_case_types, non_upper_case_globals)]

use core::ffi::{c_char, c_int, c_uint, c_void};

// ---- type aliases that match the C headers ----

pub type OSStatus = i32;
pub type CMVideoCodecType = u32;
pub type CMTimeFlags = u32;

#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct CMTime {
    pub value: i64,
    pub timescale: i32,
    pub flags: CMTimeFlags,
    pub epoch: i64,
}

impl CMTime {
    pub const VALID: CMTimeFlags = 1;

    /// Construct a `CMTime` from a numerator + denominator. e.g. `CMTime::new(1, 30)`
    /// for 1/30s (one 30 fps frame).
    #[must_use]
    pub const fn new(value: i64, timescale: i32) -> Self {
        Self {
            value,
            timescale,
            flags: Self::VALID,
            epoch: 0,
        }
    }

    pub const INVALID: Self = Self {
        value: 0,
        timescale: 0,
        flags: 0,
        epoch: 0,
    };
}

#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct CMTimeRange {
    pub start: CMTime,
    pub duration: CMTime,
}

impl CMTimeRange {
    pub const INVALID: Self = Self {
        start: CMTime::INVALID,
        duration: CMTime::INVALID,
    };
}

// CMVideoCodecType FourCC codes (ASCII bytes).
pub const kCMVideoCodecType_H264: CMVideoCodecType = u32::from_be_bytes(*b"avc1");
pub const kCMVideoCodecType_HEVC: CMVideoCodecType = u32::from_be_bytes(*b"hvc1");
pub const kCMVideoCodecType_AppleProRes422: CMVideoCodecType = u32::from_be_bytes(*b"apcn");
pub const kCMVideoCodecType_AppleProRes422HQ: CMVideoCodecType = u32::from_be_bytes(*b"apch");
pub const kCMVideoCodecType_AppleProRes422LT: CMVideoCodecType = u32::from_be_bytes(*b"apcs");
pub const kCMVideoCodecType_AppleProRes422Proxy: CMVideoCodecType = u32::from_be_bytes(*b"apco");
pub const kCMVideoCodecType_AppleProRes4444: CMVideoCodecType = u32::from_be_bytes(*b"ap4h");

// VTEncodeInfoFlags (returned via the encode callback)
pub const kVTEncodeInfo_Asynchronous: u32 = 1;
pub const kVTEncodeInfo_FrameDropped: u32 = 1 << 1;

// ---- CoreFoundation minimum required surface ----

pub type CFAllocatorRef = *const c_void;
pub type CFTypeRef = *const c_void;
pub type CFStringRef = *const c_void;
pub type CFNumberRef = *const c_void;
pub type CFBooleanRef = *const c_void;
pub type CFDictionaryRef = *const c_void;
pub type CFMutableDictionaryRef = *mut c_void;

pub type CFNumberType = c_int;
pub const kCFNumberSInt32Type: CFNumberType = 3;
pub const kCFNumberFloat64Type: CFNumberType = 13;

// CFNumberFormatter etc. — not needed for the encoder API.
pub const kCFStringEncodingUTF8: u32 = 0x0800_0100;

extern "C" {
    pub static kCFAllocatorDefault: CFAllocatorRef;
    pub static kCFBooleanTrue: CFBooleanRef;
    pub static kCFBooleanFalse: CFBooleanRef;
    pub static kCFTypeDictionaryKeyCallBacks: c_void;
    pub static kCFTypeDictionaryValueCallBacks: c_void;

    pub fn CFRelease(cf: CFTypeRef);
    pub fn CFRetain(cf: CFTypeRef) -> CFTypeRef;

    pub fn CFArrayGetCount(array: CFArrayRef) -> isize;
    pub fn CFArrayGetValueAtIndex(array: CFArrayRef, index: isize) -> *const c_void;
    pub fn CFDictionaryGetValue(d: CFDictionaryRef, key: *const c_void) -> *const c_void;
    pub fn CFStringGetCString(
        s: CFStringRef,
        buffer: *mut c_char,
        buffer_size: isize,
        encoding: u32,
    ) -> bool;
    pub fn CFStringGetLength(s: CFStringRef) -> isize;
    pub fn CFNumberGetValue(num: CFNumberRef, the_type: CFNumberType, value_ptr: *mut c_void) -> bool;

    pub fn CFNumberCreate(
        allocator: CFAllocatorRef,
        the_type: CFNumberType,
        value_ptr: *const c_void,
    ) -> CFNumberRef;

    pub fn CFStringCreateWithCString(
        allocator: CFAllocatorRef,
        c_str: *const c_char,
        encoding: u32,
    ) -> CFStringRef;

    pub fn CFDictionaryCreateMutable(
        allocator: CFAllocatorRef,
        capacity: isize,
        key_callbacks: *const c_void,
        value_callbacks: *const c_void,
    ) -> CFMutableDictionaryRef;
    pub fn CFDictionarySetValue(
        dict: CFMutableDictionaryRef,
        key: *const c_void,
        value: *const c_void,
    );
}

// ---- CoreMedia: CMSampleBuffer ----

pub type CMSampleBufferRef = *mut c_void;
pub type CMBlockBufferRef = *mut c_void;
pub type CMFormatDescriptionRef = *mut c_void;

extern "C" {
    pub fn CMSampleBufferGetDataBuffer(sbuf: CMSampleBufferRef) -> CMBlockBufferRef;
    pub fn CMSampleBufferGetTotalSampleSize(sbuf: CMSampleBufferRef) -> usize;
    pub fn CMSampleBufferGetFormatDescription(sbuf: CMSampleBufferRef) -> CMFormatDescriptionRef;
    pub fn CMSampleBufferGetPresentationTimeStamp(sbuf: CMSampleBufferRef) -> CMTime;
    pub fn CMSampleBufferGetDuration(sbuf: CMSampleBufferRef) -> CMTime;
    pub fn CMBlockBufferCopyDataBytes(
        the_source_buffer: CMBlockBufferRef,
        offset_to_data: usize,
        data_length: usize,
        destination: *mut c_void,
    ) -> OSStatus;
    pub fn CMBlockBufferGetDataLength(the_buffer: CMBlockBufferRef) -> usize;
}

// ---- CoreVideo: CVPixelBuffer (we only need create-with-IOSurface here) ----

pub type CVPixelBufferRef = *mut c_void;
pub type IOSurfaceRef = *mut c_void;

extern "C" {
    pub fn CVPixelBufferCreateWithIOSurface(
        allocator: CFAllocatorRef,
        surface: IOSurfaceRef,
        pixel_buffer_attributes: CFDictionaryRef,
        pixel_buffer_out: *mut CVPixelBufferRef,
    ) -> i32;
}

// ---- VideoToolbox: VTCompressionSession ----

pub type VTCompressionSessionRef = *mut c_void;
pub type VTEncodeInfoFlags = u32;

/// Encode-completion callback signature. Invoked once per encoded frame.
pub type VTCompressionOutputCallback = unsafe extern "C" fn(
    output_callback_ref_con: *mut c_void,
    source_frame_ref_con: *mut c_void,
    status: OSStatus,
    info_flags: VTEncodeInfoFlags,
    sample_buffer: CMSampleBufferRef,
);

extern "C" {
    pub fn VTCompressionSessionCreate(
        allocator: CFAllocatorRef,
        width: i32,
        height: i32,
        codec_type: CMVideoCodecType,
        encoder_specification: CFDictionaryRef,
        source_image_buffer_attributes: CFDictionaryRef,
        compressed_data_allocator: CFAllocatorRef,
        output_callback: Option<VTCompressionOutputCallback>,
        output_callback_ref_con: *mut c_void,
        compression_session_out: *mut VTCompressionSessionRef,
    ) -> OSStatus;

    pub fn VTCompressionSessionInvalidate(session: VTCompressionSessionRef);

    pub fn VTCompressionSessionPrepareToEncodeFrames(session: VTCompressionSessionRef) -> OSStatus;

    pub fn VTCompressionSessionEncodeFrame(
        session: VTCompressionSessionRef,
        image_buffer: CVPixelBufferRef,
        presentation_time_stamp: CMTime,
        duration: CMTime,
        frame_properties: CFDictionaryRef,
        source_frame_ref_con: *mut c_void,
        info_flags_out: *mut VTEncodeInfoFlags,
    ) -> OSStatus;

    pub fn VTCompressionSessionCompleteFrames(
        session: VTCompressionSessionRef,
        complete_until_presentation_time_stamp: CMTime,
    ) -> OSStatus;

    pub fn VTSessionSetProperty(
        session: VTCompressionSessionRef,
        property_key: CFStringRef,
        property_value: CFTypeRef,
    ) -> OSStatus;

    // Common compression property keys (declared as CFStringRef constants by the framework).
    pub static kVTCompressionPropertyKey_RealTime: CFStringRef;
    pub static kVTCompressionPropertyKey_AllowFrameReordering: CFStringRef;
    pub static kVTCompressionPropertyKey_AverageBitRate: CFStringRef;
    pub static kVTCompressionPropertyKey_ExpectedFrameRate: CFStringRef;
    pub static kVTCompressionPropertyKey_MaxKeyFrameInterval: CFStringRef;
    pub static kVTCompressionPropertyKey_ProfileLevel: CFStringRef;
    pub static kVTCompressionPropertyKey_H264EntropyMode: CFStringRef;
    pub static kVTCompressionPropertyKey_Quality: CFStringRef;

    pub static kVTProfileLevel_H264_Baseline_AutoLevel: CFStringRef;
    pub static kVTProfileLevel_H264_Main_AutoLevel: CFStringRef;
    pub static kVTProfileLevel_H264_High_AutoLevel: CFStringRef;
    pub static kVTProfileLevel_HEVC_Main_AutoLevel: CFStringRef;
    pub static kVTProfileLevel_HEVC_Main10_AutoLevel: CFStringRef;

    pub static kVTH264EntropyMode_CABAC: CFStringRef;
    pub static kVTH264EntropyMode_CAVLC: CFStringRef;

    // ---- VTDecompressionSession (decoder side, added v0.3) ----
    pub fn VTDecompressionSessionCreate(
        allocator: CFAllocatorRef,
        video_format_description: CMFormatDescriptionRef,
        video_decoder_specification: CFDictionaryRef,
        destination_image_buffer_attributes: CFDictionaryRef,
        output_callback: *const VTDecompressionOutputCallbackRecord,
        decompression_session_out: *mut VTDecompressionSessionRef,
    ) -> OSStatus;

    pub fn VTDecompressionSessionInvalidate(session: VTDecompressionSessionRef);

    pub fn VTDecompressionSessionDecodeFrame(
        session: VTDecompressionSessionRef,
        sample_buffer: CMSampleBufferRef,
        decode_flags: u32,
        source_frame_ref_con: *mut c_void,
        info_flags_out: *mut u32,
    ) -> OSStatus;

    pub fn VTDecompressionSessionWaitForAsynchronousFrames(
        session: VTDecompressionSessionRef,
    ) -> OSStatus;

    pub fn VTDecompressionSessionFinishDelayedFrames(
        session: VTDecompressionSessionRef,
    ) -> OSStatus;

    pub fn VTDecompressionSessionCanAcceptFormatDescription(
        session: VTDecompressionSessionRef,
        new_format_desc: CMFormatDescriptionRef,
    ) -> bool;

    pub static kVTDecompressionPropertyKey_RealTime: CFStringRef;
    pub static kVTDecompressionPropertyKey_MaximumOutputBufferDepth: CFStringRef;

    // ---- VTPixelTransferSession (v0.6) ----
    pub fn VTPixelTransferSessionCreate(
        allocator: CFAllocatorRef,
        pixel_transfer_session_out: *mut VTPixelTransferSessionRef,
    ) -> OSStatus;
    pub fn VTPixelTransferSessionInvalidate(session: VTPixelTransferSessionRef);
    pub fn VTPixelTransferSessionTransferImage(
        session: VTPixelTransferSessionRef,
        source_buffer: CVPixelBufferRef,
        destination_buffer: CVPixelBufferRef,
    ) -> OSStatus;

    // ---- VTPixelRotationSession (v0.6) ----
    pub fn VTPixelRotationSessionCreate(
        allocator: CFAllocatorRef,
        pixel_rotation_session_out: *mut VTPixelRotationSessionRef,
    ) -> OSStatus;
    pub fn VTPixelRotationSessionInvalidate(session: VTPixelRotationSessionRef);
    pub fn VTPixelRotationSessionRotateImage(
        session: VTPixelRotationSessionRef,
        source_buffer: CVPixelBufferRef,
        destination_buffer: CVPixelBufferRef,
    ) -> OSStatus;

    pub static kVTPixelRotationPropertyKey_Rotation: CFStringRef;
    pub static kVTPixelRotationPropertyKey_FlipHorizontalOrientation: CFStringRef;
    pub static kVTPixelRotationPropertyKey_FlipVerticalOrientation: CFStringRef;

    pub static kVTRotation_0: CFStringRef;
    pub static kVTRotation_CW90: CFStringRef;
    pub static kVTRotation_180: CFStringRef;
    pub static kVTRotation_CCW90: CFStringRef;

    // ---- VTVideoEncoderList (v0.7) ----
    pub fn VTCopyVideoEncoderList(
        options: CFDictionaryRef,
        list_out: *mut CFArrayRef,
    ) -> OSStatus;
    pub static kVTVideoEncoderList_CodecType: CFStringRef;
    pub static kVTVideoEncoderList_EncoderID: CFStringRef;
    pub static kVTVideoEncoderList_CodecName: CFStringRef;
    pub static kVTVideoEncoderList_EncoderName: CFStringRef;
    pub static kVTVideoEncoderList_DisplayName: CFStringRef;

    // ---- VTFrameSilo (v0.9) ----
    pub fn VTFrameSiloCreate(
        allocator: CFAllocatorRef,
        file_url: *const c_void,
        time_range: CMTimeRange,
        options: CFDictionaryRef,
        silo_out: *mut VTFrameSiloRef,
    ) -> OSStatus;
    pub fn VTFrameSiloAddSampleBuffer(
        silo: VTFrameSiloRef,
        sample_buffer: CMSampleBufferRef,
    ) -> OSStatus;
    pub fn VTFrameSiloGetProgressOfCurrentPass(
        silo: VTFrameSiloRef,
        progress_out: *mut f32,
    ) -> OSStatus;

    // ---- VTMultiPassStorage (v0.9) ----
    pub fn VTMultiPassStorageCreate(
        allocator: CFAllocatorRef,
        file_url: *const c_void,
        time_range: CMTimeRange,
        options: CFDictionaryRef,
        storage_out: *mut VTMultiPassStorageRef,
    ) -> OSStatus;
    pub fn VTMultiPassStorageClose(storage: VTMultiPassStorageRef) -> OSStatus;

    // ---- VTHDRPerFrameMetadataGenerationSession (v0.9) ----
    pub fn VTHDRPerFrameMetadataGenerationSessionCreate(
        allocator: CFAllocatorRef,
        frames_per_second: f32,
        options: CFDictionaryRef,
        session_out: *mut VTHDRPerFrameMetadataGenerationSessionRef,
    ) -> OSStatus;
    pub fn VTHDRPerFrameMetadataGenerationSessionAttachMetadata(
        session: VTHDRPerFrameMetadataGenerationSessionRef,
        pixel_buffer: CVPixelBufferRef,
        scene_change: bool,
    ) -> OSStatus;

    // ---- VTUtilities + VTProfessionalVideoWorkflow (v0.9) ----
    pub fn VTCreateCGImageFromCVPixelBuffer(
        pixel_buffer: CVPixelBufferRef,
        options: CFDictionaryRef,
        image_out: *mut *mut c_void,
    ) -> OSStatus;
    pub fn VTRegisterProfessionalVideoWorkflowVideoDecoders();
    pub fn VTRegisterProfessionalVideoWorkflowVideoEncoders();

    // ---- VTMotionEstimationSession (v0.10, macOS 26+) ----
    pub fn VTMotionEstimationSessionGetTypeID() -> usize;
    pub fn VTMotionEstimationSessionCreate(
        allocator: CFAllocatorRef,
        selection_options: CFDictionaryRef,
        width: u32,
        height: u32,
        session_out: *mut VTMotionEstimationSessionRef,
    ) -> OSStatus;
    pub fn VTMotionEstimationSessionInvalidate(session: VTMotionEstimationSessionRef);
    pub fn VTMotionEstimationSessionCopySourcePixelBufferAttributes(
        session: VTMotionEstimationSessionRef,
        attributes_out: *mut CFDictionaryRef,
    ) -> OSStatus;
    pub fn VTMotionEstimationSessionCompleteFrames(
        session: VTMotionEstimationSessionRef,
    ) -> OSStatus;

    // ---- VTRAWProcessingSession (v0.10, macOS 15+) ----
    pub fn VTRAWProcessingSessionGetTypeID() -> usize;
    pub fn VTRAWProcessingSessionCreate(
        allocator: CFAllocatorRef,
        format_description: *const c_void,
        output_pixel_buffer_attributes: CFDictionaryRef,
        processing_session_options: CFDictionaryRef,
        session_out: *mut VTRAWProcessingSessionRef,
    ) -> OSStatus;
    pub fn VTRAWProcessingSessionInvalidate(session: VTRAWProcessingSessionRef);
    pub fn VTRAWProcessingSessionCompleteFrames(session: VTRAWProcessingSessionRef) -> OSStatus;
    pub fn VTRAWProcessingSessionCopyProcessingParameters(
        session: VTRAWProcessingSessionRef,
        out_parameter_array: *mut CFArrayRef,
    ) -> OSStatus;
    pub fn VTRAWProcessingSessionSetProcessingParameters(
        session: VTRAWProcessingSessionRef,
        processing_parameters: CFDictionaryRef,
    ) -> OSStatus;

    // ---- VTRAW parameter keys (v0.10) ----
    pub static kVTRAWProcessingParameter_Key: CFStringRef;
    pub static kVTRAWProcessingParameter_Name: CFStringRef;
    pub static kVTRAWProcessingParameter_Description: CFStringRef;
    pub static kVTRAWProcessingParameter_Enabled: CFStringRef;
    pub static kVTRAWProcessingParameter_ValueType: CFStringRef;
    pub static kVTRAWProcessingParameterValueType_Boolean: CFStringRef;
    pub static kVTRAWProcessingParameterValueType_Integer: CFStringRef;
    pub static kVTRAWProcessingParameterValueType_Float: CFStringRef;
    pub static kVTRAWProcessingParameterValueType_List: CFStringRef;
    pub static kVTRAWProcessingParameterValueType_SubGroup: CFStringRef;
    pub static kVTRAWProcessingParameter_ListArray: CFStringRef;
    pub static kVTRAWProcessingParameterListElement_Label: CFStringRef;
    pub static kVTRAWProcessingParameterListElement_Description: CFStringRef;
    pub static kVTRAWProcessingParameterListElement_ListElementID: CFStringRef;
    pub static kVTRAWProcessingParameter_SubGroup: CFStringRef;
    pub static kVTRAWProcessingParameter_MaximumValue: CFStringRef;
    pub static kVTRAWProcessingParameter_MinimumValue: CFStringRef;
    pub static kVTRAWProcessingParameter_InitialValue: CFStringRef;
    pub static kVTRAWProcessingParameter_NeutralValue: CFStringRef;
    pub static kVTRAWProcessingParameter_CameraValue: CFStringRef;
    pub static kVTRAWProcessingParameter_CurrentValue: CFStringRef;
}

pub type CFArrayRef = *const c_void;
pub type VTFrameSiloRef = *mut c_void;
pub type VTMultiPassStorageRef = *mut c_void;
pub type VTHDRPerFrameMetadataGenerationSessionRef = *mut c_void;
pub type VTMotionEstimationSessionRef = *mut c_void;
pub type VTRAWProcessingSessionRef = *mut c_void;

pub type VTPixelTransferSessionRef = *mut c_void;
pub type VTPixelRotationSessionRef = *mut c_void;

pub type VTDecompressionSessionRef = *mut c_void;
pub type VTDecompressionOutputCallback = unsafe extern "C" fn(
    decompression_output_ref_con: *mut c_void,
    source_frame_ref_con: *mut c_void,
    status: OSStatus,
    info_flags: u32,
    image_buffer: *mut c_void,
    presentation_time_stamp: CMTime,
    presentation_duration: CMTime,
);

#[repr(C)]
pub struct VTDecompressionOutputCallbackRecord {
    pub decompression_output_callback: VTDecompressionOutputCallback,
    pub decompression_output_ref_con: *mut c_void,
}

// Suppress unused variant warnings on c_uint placeholder types.
const _: () = {
    let _ = core::mem::size_of::<c_uint>();
};