#![expect(
unsafe_code,
reason = "VideoToolbox and CoreMedia are C APIs whose objects the bindings hand out as references"
)]
use std::{
ptr::{self, NonNull},
slice,
};
use objc2_core_foundation::{
CFArray, CFBoolean, CFDictionary, CFNumber, CFRetained, CFString, CFType,
};
use objc2_core_media::{
CMBlockBuffer, CMFormatDescription, CMSampleBuffer, CMSampleTimingInfo, CMTime, CMTimeFlags,
CMVideoFormatDescriptionCreateFromH264ParameterSets,
CMVideoFormatDescriptionCreateFromHEVCParameterSets, kCMBlockBufferAssureMemoryNowFlag,
kCMTimeInvalid,
};
use objc2_core_video::{
kCVPixelBufferIOSurfacePropertiesKey, kCVPixelBufferMetalCompatibilityKey,
kCVPixelBufferPixelFormatTypeKey, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
};
#[cfg(target_os = "macos")]
use objc2_video_toolbox::kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder;
use objc2_video_toolbox::{
VTDecodeFrameFlags, VTDecompressionOutputCallbackRecord, VTDecompressionSession,
kVTDecompressionPropertyKey_RealTime,
};
use super::{DecoderError, VideoCodec, annex_b::LENGTH_SIZE};
const OUTPUT_FORMATS: [u32; 2] = [
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
];
pub(super) const TIMESCALE: i32 = 1_000_000;
pub(super) struct Format {
description: CFRetained<CMFormatDescription>,
sets: Vec<Vec<u8>>,
}
unsafe impl Send for Format {}
impl Format {
pub(super) fn new<'a>(
codec: VideoCodec,
sets: impl Iterator<Item = &'a [u8]>,
) -> Result<Self, DecoderError> {
let sets: Vec<Vec<u8>> = sets.map(<[u8]>::to_vec).collect();
let pointers: Vec<NonNull<u8>> = sets
.iter()
.map(|set| NonNull::from(set.as_slice()).cast())
.collect();
let sizes: Vec<usize> = sets.iter().map(Vec::len).collect();
let (Some(pointers_in), Some(sizes_in)) = (
NonNull::new(pointers.as_ptr().cast_mut()),
NonNull::new(sizes.as_ptr().cast_mut()),
) else {
return Err(DecoderError::NeedsKeyframe);
};
let header = i32::try_from(LENGTH_SIZE).unwrap_or(4);
let mut description = ptr::null();
let status = unsafe {
match codec {
VideoCodec::H264 => CMVideoFormatDescriptionCreateFromH264ParameterSets(
None,
sets.len(),
pointers_in,
sizes_in,
header,
NonNull::from(&mut description),
),
VideoCodec::Hevc => CMVideoFormatDescriptionCreateFromHEVCParameterSets(
None,
sets.len(),
pointers_in,
sizes_in,
header,
None,
NonNull::from(&mut description),
),
VideoCodec::Av1 => return Err(DecoderError::NoDecoder(codec)),
}
};
let description = NonNull::new(description.cast_mut())
.filter(|_| status == 0)
.map(|description| unsafe { CFRetained::from_raw(description) })
.ok_or_else(|| {
DecoderError::Configure(format!("the parameter sets give no format: {status}"))
})?;
Ok(Self { description, sets })
}
pub(super) fn is_made_of<'a>(&self, sets: impl Iterator<Item = &'a [u8]>) -> bool {
sets.eq(self.sets.iter().map(Vec::as_slice))
}
pub(super) fn sample(
&self,
len: usize,
fill: impl FnOnce(&mut [u8]),
pts_us: u64,
) -> Result<CFRetained<CMSampleBuffer>, DecoderError> {
let failed = |what: &str, status| DecoderError::Failed(format!("{what}: {status}"));
let mut block = ptr::null_mut();
let status = unsafe {
CMBlockBuffer::create_with_memory_block(
None,
ptr::null_mut(),
len,
None,
ptr::null(),
0,
len,
kCMBlockBufferAssureMemoryNowFlag,
NonNull::from(&mut block),
)
};
let block = NonNull::new(block)
.filter(|_| status == 0)
.map(|block| unsafe { CFRetained::from_raw(block) })
.ok_or_else(|| failed("the block buffer", status))?;
let mut bytes = ptr::null_mut();
let status = unsafe {
block.data_pointer(
0,
ptr::null_mut(),
ptr::null_mut(),
NonNull::from(&mut bytes).as_ptr(),
)
};
let bytes = NonNull::new(bytes.cast::<u8>())
.filter(|_| status == 0)
.ok_or_else(|| failed("the block buffer's bytes", status))?;
fill(unsafe { slice::from_raw_parts_mut(bytes.as_ptr(), len) });
let timing = CMSampleTimingInfo {
duration: invalid_time(),
presentationTimeStamp: CMTime {
value: i64::try_from(pts_us).unwrap_or(i64::MAX),
timescale: TIMESCALE,
flags: CMTimeFlags::Valid,
epoch: 0,
},
decodeTimeStamp: invalid_time(),
};
let mut sample = ptr::null_mut();
let status = unsafe {
CMSampleBuffer::create_ready(
None,
Some(&block),
Some(&self.description),
1,
1,
&raw const timing,
1,
&raw const len,
NonNull::from(&mut sample),
)
};
NonNull::new(sample)
.filter(|_| status == 0)
.map(|sample| unsafe { CFRetained::from_raw(sample) })
.ok_or_else(|| failed("the sample buffer", status))
}
}
fn invalid_time() -> CMTime {
unsafe { kCMTimeInvalid }
}
pub(super) struct Session {
raw: CFRetained<VTDecompressionSession>,
}
unsafe impl Send for Session {}
impl Session {
pub(super) fn new(
format: &Format,
callback: VTDecompressionOutputCallbackRecord,
) -> Result<Self, DecoderError> {
let attributes = destination_attributes();
let specification = decoder_specification();
let mut raw = ptr::null_mut();
let status = unsafe {
VTDecompressionSession::create(
None,
&format.description,
specification.as_deref(),
Some(&attributes),
&raw const callback,
NonNull::from(&mut raw),
)
};
let raw = NonNull::new(raw)
.filter(|_| status == 0)
.map(|raw| unsafe { CFRetained::from_raw(raw) })
.ok_or_else(|| {
DecoderError::Configure(format!("the decompression session: {status}"))
})?;
let real_time = unsafe {
objc2_video_toolbox::VTSessionSetProperty(
&raw,
kVTDecompressionPropertyKey_RealTime,
Some(CFBoolean::new(true).as_ref()),
)
};
if real_time != 0 {
log::debug!("video decoder: no real-time mode: {real_time}");
}
Ok(Self { raw })
}
pub(super) fn can_accept(&self, format: &Format) -> bool {
unsafe { self.raw.can_accept_format_description(&format.description) }
}
pub(super) fn decode(&self, sample: &CMSampleBuffer) -> i32 {
unsafe {
self.raw.decode_frame(
sample,
VTDecodeFrameFlags::Frame_EnableAsynchronousDecompression,
ptr::null_mut(),
ptr::null_mut(),
)
}
}
}
impl Drop for Session {
fn drop(&mut self) {
unsafe {
self.raw.wait_for_asynchronous_frames();
self.raw.invalidate();
}
}
}
fn destination_attributes() -> CFRetained<CFDictionary> {
let formats: Vec<CFRetained<CFNumber>> = OUTPUT_FORMATS
.iter()
.map(|format| CFNumber::new_i32(i32::try_from(*format).unwrap_or(0)))
.collect();
let formats =
CFArray::<CFNumber>::from_objects(&formats.iter().map(|n| &**n).collect::<Vec<_>>());
let surface_properties = CFDictionary::<CFString, CFType>::empty();
let (format_key, surface_key, metal_key) = unsafe {
(
kCVPixelBufferPixelFormatTypeKey,
kCVPixelBufferIOSurfacePropertiesKey,
kCVPixelBufferMetalCompatibilityKey,
)
};
let dictionary = CFDictionary::<CFString, CFType>::from_slices(
&[format_key, surface_key, metal_key],
&[
formats.as_ref(),
surface_properties.as_ref(),
CFBoolean::new(true).as_ref(),
],
);
unsafe { CFRetained::cast_unchecked::<CFDictionary>(dictionary) }
}
#[cfg(target_os = "macos")]
fn decoder_specification() -> Option<CFRetained<CFDictionary>> {
let key = unsafe { kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder };
let dictionary =
CFDictionary::<CFString, CFType>::from_slices(&[key], &[CFBoolean::new(true).as_ref()]);
Some(unsafe { CFRetained::cast_unchecked::<CFDictionary>(dictionary) })
}
#[cfg(not(target_os = "macos"))]
fn decoder_specification() -> Option<CFRetained<CFDictionary>> {
None
}