#![expect(
unsafe_code,
reason = "VideoToolbox calls the output callback through a C function pointer and a raw pointer"
)]
use std::{
ffi::c_void,
ptr::NonNull,
sync::{
Arc,
atomic::{AtomicBool, Ordering::Relaxed},
},
time::{Duration, Instant},
};
use objc2_core_foundation::CFRetained;
use objc2_core_media::CMTime;
use objc2_core_video::CVImageBuffer;
use objc2_video_toolbox::{
VTDecodeInfoFlags, VTDecompressionOutputCallbackRecord, kVTInvalidSessionErr,
kVTVideoDecoderMalfunctionErr,
};
use parking_lot::{Condvar, Mutex};
use super::{
AccessUnit, DecoderConfig, DecoderError, DecoderOutput, FrameInfo, VideoCodec, VideoFrame,
admission::Admission,
annex_b::AccessUnitNals,
decompression_session::{Format, Session, TIMESCALE},
frame_queue::{FrameQueue, Frames},
pending_units::{PendingUnit, PendingUnits},
pixel_buffer::{Image, LivePictures},
};
const MAX_IN_FLIGHT: usize = 8;
struct Shared {
pending: Mutex<PendingUnits>,
room: Condvar,
queue: Arc<FrameQueue>,
live: LivePictures,
depth: usize,
session_lost: AtomicBool,
}
#[derive(Default)]
struct Stream {
format: Option<Format>,
session: Option<Session>,
}
pub(super) struct Backend {
stream: Stream,
shared: Arc<Shared>,
codec: VideoCodec,
nals: AccessUnitNals,
admission: Admission,
input_wait: Duration,
}
impl Backend {
pub(super) fn new(config: DecoderConfig) -> Result<Self, DecoderError> {
let DecoderConfig {
codec,
width,
height,
output,
input_wait,
} = config;
if codec == VideoCodec::Av1 {
return Err(DecoderError::NoDecoder(codec));
}
let DecoderOutput::Frames { depth } = output else {
return Err(DecoderError::Unavailable);
};
let depth = depth.max(2);
Ok(Self {
stream: Stream::default(),
shared: Arc::new(Shared {
pending: Mutex::new(PendingUnits::new()),
room: Condvar::new(),
queue: Arc::new(FrameQueue::new(depth, 0)),
live: LivePictures::default(),
depth,
session_lost: AtomicBool::new(false),
}),
codec,
nals: AccessUnitNals::default(),
admission: Admission::new((width as usize) * (height as usize)),
input_wait,
})
}
pub(super) fn submit(&mut self, unit: AccessUnit<'_>) -> Result<(), DecoderError> {
let pts_us = self.admission.check(&unit)?;
self.nals.parse(self.codec, unit.data);
if let Some(sets) = self.nals.parameter_sets(self.codec, unit.data) {
self.stream.follow(self.codec, sets)?;
}
if self.nals.has_picture() {
self.decode(unit, pts_us)?;
}
self.admission.accept(pts_us);
self.shared.queue.stats.submitted();
Ok(())
}
fn decode(&mut self, unit: AccessUnit<'_>, pts_us: u64) -> Result<(), DecoderError> {
self.stream.start(&self.shared, self.nals.has_keyframe())?;
let (Some(format), Some(session)) = (&self.stream.format, &self.stream.session) else {
return Err(DecoderError::NeedsKeyframe);
};
self.shared.reserve(
PendingUnit {
pts_us,
timestamp: unit.timestamp,
metadata: unit.metadata,
submitted: Instant::now(),
},
self.input_wait,
)?;
let sample = format.sample(
self.nals.length_prefixed_len(),
|bytes| self.nals.write_length_prefixed(unit.data, bytes),
pts_us,
);
let sample = match sample {
Ok(sample) => sample,
Err(error) => {
self.shared.withdraw(pts_us);
return Err(error);
}
};
let status = session.decode(&sample);
if status == 0 {
return Ok(());
}
self.shared.withdraw(pts_us);
if is_session_lost(status) {
self.stream.session = None;
return Err(DecoderError::NeedsKeyframe);
}
Err(DecoderError::Failed(format!(
"the decoder refused the unit: {status}"
)))
}
pub(super) fn frames(&self) -> Frames {
Frames(Arc::clone(&self.shared.queue))
}
}
impl Stream {
fn follow<'a>(
&mut self,
codec: VideoCodec,
sets: impl Iterator<Item = &'a [u8]> + Clone,
) -> Result<(), DecoderError> {
if self
.format
.as_ref()
.is_some_and(|format| format.is_made_of(sets.clone()))
{
return Ok(());
}
let format = Format::new(codec, sets)?;
if self
.session
.as_ref()
.is_some_and(|session| !session.can_accept(&format))
{
self.session = None;
}
self.format = Some(format);
Ok(())
}
fn start(&mut self, shared: &Arc<Shared>, keyframe: bool) -> Result<(), DecoderError> {
if shared.session_lost.swap(false, Relaxed) {
self.session = None;
}
if self.session.is_some() {
return Ok(());
}
let format = self.format.as_ref().ok_or(DecoderError::NeedsKeyframe)?;
if !keyframe {
return Err(DecoderError::NeedsKeyframe);
}
let callback = VTDecompressionOutputCallbackRecord {
decompressionOutputCallback: Some(on_output),
decompressionOutputRefCon: Arc::as_ptr(shared).cast_mut().cast(),
};
self.session = Some(Session::new(format, callback)?);
Ok(())
}
}
impl Shared {
fn reserve(&self, unit: PendingUnit, wait: Duration) -> Result<(), DecoderError> {
let deadline = Instant::now() + wait;
let mut pending = self.pending.lock();
while pending.len() >= MAX_IN_FLIGHT {
if self.room.wait_until(&mut pending, deadline).timed_out() {
self.queue.stats.refused();
return Err(DecoderError::Full);
}
}
pending.push(unit);
drop(pending);
Ok(())
}
fn withdraw(&self, pts_us: u64) {
self.pending.lock().remove(pts_us);
self.room.notify_one();
}
fn output(&self, status: i32, info: VTDecodeInfoFlags, image: *mut CVImageBuffer, pts_us: u64) {
let unit = self.pending.lock().remove(pts_us);
self.room.notify_one();
let Some(image) = NonNull::new(image).filter(|_| status == 0) else {
if status != 0 {
log::warn!("video decoder: picture at {pts_us} us failed: {status}");
if is_session_lost(status) {
self.session_lost.store(true, Relaxed);
}
}
self.queue.stats.dropped();
return;
};
if info.contains(VTDecodeInfoFlags::FrameDropped) {
self.queue.stats.dropped();
return;
}
let image = Image::new(unsafe { CFRetained::retain(image) }, &self.live);
let frame_info = unit.map_or_else(
|| FrameInfo {
timestamp: Duration::from_micros(pts_us),
metadata: 0,
decode_time: Duration::ZERO,
},
|unit| FrameInfo {
timestamp: unit.timestamp,
metadata: unit.metadata,
decode_time: unit.submitted.elapsed(),
},
);
let decode_time = frame_info.decode_time;
let frame = VideoFrame::new(frame_info, image.size(), image.crop(), image);
self.enqueue(frame);
self.queue.stats.decoded(decode_time);
}
fn enqueue(&self, frame: VideoFrame) {
let mut frames = self.queue.frames.lock();
while self.live.load(Relaxed) > self.depth {
self.queue.stats.dropped();
if frames.pop_front().is_none() {
return;
}
}
frames.push_back(frame);
drop(frames);
self.queue.wake();
}
}
fn is_session_lost(status: i32) -> bool {
status == kVTInvalidSessionErr || status == kVTVideoDecoderMalfunctionErr
}
unsafe extern "C-unwind" fn on_output(
refcon: *mut c_void,
_frame_refcon: *mut c_void,
status: i32,
info: VTDecodeInfoFlags,
image: *mut CVImageBuffer,
pts: CMTime,
_duration: CMTime,
) {
let shared = unsafe { &*refcon.cast::<Shared>() };
let micros = i128::from(pts.value) * i128::from(TIMESCALE) / i128::from(pts.timescale.max(1));
shared.output(status, info, image, u64::try_from(micros).unwrap_or(0));
}
#[cfg(test)]
#[path = "tests/video_toolbox_tests.rs"]
mod tests;