use std::{ffi::c_void, sync::Arc};
use alpha2_ffmpeg_bridge::{BridgeError, NativeGpuBackend, VideoToolboxFrameLease};
use super::{
ImportedMetalFrame, MetalEncoderPlanes, MetalImportError, SharedMetalContext, SharedMetalError,
pixel_buffer_surface_id,
};
unsafe extern "C" {
fn alpha2_native_gpu_vt_hardware_decodes(codec_type: u32) -> i32;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoToolboxCodec {
H264,
Hevc,
Vp9,
Av1,
}
impl VideoToolboxCodec {
const ALL: [Self; 4] = [Self::H264, Self::Hevc, Self::Vp9, Self::Av1];
const fn name(self) -> &'static str {
match self {
Self::H264 => "h264",
Self::Hevc => "hevc",
Self::Vp9 => "vp9",
Self::Av1 => "av1",
}
}
const fn four_cc(self) -> u32 {
u32::from_be_bytes(*match self {
Self::H264 => b"avc1",
Self::Hevc => b"hvc1",
Self::Vp9 => b"vp09",
Self::Av1 => b"av01",
})
}
}
#[must_use]
pub fn videotoolbox_hardware_decodes(codec: VideoToolboxCodec) -> bool {
unsafe { alpha2_native_gpu_vt_hardware_decodes(codec.four_cc()) != 0 }
}
pub(super) fn hardware_decode_codecs() -> &'static [&'static str] {
static CODECS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
CODECS.get_or_init(|| {
VideoToolboxCodec::ALL
.into_iter()
.filter(|codec| videotoolbox_hardware_decodes(*codec))
.map(VideoToolboxCodec::name)
.collect()
})
}
#[must_use]
pub fn videotoolbox_surface_id(frame: &VideoToolboxFrameLease) -> Option<u32> {
let pixel_buffer = usize::try_from(frame.info().ok()?.pixel_buffer).ok()? as *mut c_void;
unsafe { pixel_buffer_surface_id(pixel_buffer) }
}
fn bridge_error(error: MetalImportError) -> BridgeError {
match error {
MetalImportError::Unsupported(reason) => {
BridgeError::UnsupportedSurface(format!("VideoToolbox frame {reason}"))
}
MetalImportError::NoSixteenBitPlanes => {
BridgeError::InvalidInput("renderer does not expose 16-bit plane textures")
}
MetalImportError::Helper {
operation,
step,
status,
} => crate::status::helper_failure(NativeGpuBackend::Metal, operation, step, status),
MetalImportError::Missing(what) => BridgeError::InvalidInput(what),
MetalImportError::NotRenderTarget { .. } => {
BridgeError::UnsupportedSurface(error.to_string())
}
MetalImportError::NotMetal => BridgeError::InvalidInput("renderer is not using Metal"),
}
}
impl SharedMetalContext {
#[must_use]
pub fn decode_codecs(&self) -> &'static [&'static str] {
hardware_decode_codecs()
}
pub fn import_surface(
&self,
frame: Arc<VideoToolboxFrameLease>,
) -> Result<ImportedMetalFrame, BridgeError> {
let decoded = frame.info()?;
let pixel_buffer = usize::try_from(decoded.pixel_buffer)
.map_err(|_| BridgeError::InvalidInput("invalid CoreVideo pointer"))?
as *mut c_void;
unsafe { self.import_pixel_buffer(pixel_buffer, Box::new(frame)) }.map_err(bridge_error)
}
pub fn encoder_planes(
&self,
frame: &rsmpeg::avutil::AVFrame,
) -> Result<MetalEncoderPlanes, SharedMetalError> {
let info = alpha2_ffmpeg_bridge::videotoolbox_frame_info(frame)
.map_err(|error| SharedMetalError(format!("encoder frame: {error}")))?;
let pixel_buffer = usize::try_from(info.pixel_buffer)
.ok()
.filter(|pointer| *pointer != 0)
.ok_or_else(|| SharedMetalError("encoder frame has no pixel buffer".into()))?
as *mut c_void;
unsafe { self.pixel_buffer_planes(pixel_buffer) }
.map_err(|error| SharedMetalError(error.to_string()))
}
}