Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
test(video-decode): scripted media source for decoder model tests
Richie McIlroy26be79432b04
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.tomlindex cce5010de..c54023e8c 100644--- a/crates/rendering/Cargo.toml+++ b/crates/rendering/Cargo.toml@@ -70,6 +70,7 @@ windows_0_58 = { package = "windows", version = "0.58", features = [[dev-dependencies]cap-media-info = { path = "../media-info" }+cap-video-decode = { path = "../video-decode", features = ["scripted"] }tempfile = "3"pollster = "0.4.0"pretty_assertions = "1.4.1"diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rsindex af79c9560..d9ab926e6 100644--- a/crates/rendering/src/decoder/avassetreader.rs+++ b/crates/rendering/src/decoder/avassetreader.rs@@ -639,6 +639,10 @@ impl AVAssetReaderDecoder {sequential_access: Arc<AtomicBool>,) {let dimensions = (|| {+ #[cfg(test)]+ if let Some(dimensions) = cap_video_decode::scripted::dimensions(&path) {+ return Ok(dimensions);+ }let input = format::input(&path).map_err(|error| error.to_string())?;let stream = input.streams()diff --git a/crates/video-decode/Cargo.toml b/crates/video-decode/Cargo.tomlindex f9a0a2be4..486da43a1 100644--- a/crates/video-decode/Cargo.toml+++ b/crates/video-decode/Cargo.toml@@ -6,6 +6,10 @@ edition = "2024"[lints]workspace = true+[features]+# Test-only: lets decoder model tests register scripted media in place of files.+scripted = []+[dependencies]cap-enc-ffmpeg = { path = "../enc-ffmpeg" }ffmpeg.workspace = truediff --git a/crates/video-decode/src/avassetreader.rs b/crates/video-decode/src/avassetreader.rsindex 1f2dfc7b0..14f1c1205 100644--- a/crates/video-decode/src/avassetreader.rs+++ b/crates/video-decode/src/avassetreader.rs@@ -196,6 +196,11 @@ fn scan_keyframes(impl KeyframeIndex {pub fn build(path: &Path) -> Result<Self, String> {+ #[cfg(feature = "scripted")]+ if let Some(state) = crate::scripted::lookup(path) {+ return Ok(Self::from_script(&state.script));+ }+let build_start = std::time::Instant::now();let mut input = avformat::input(path)@@ -279,6 +284,28 @@ impl KeyframeIndex {})}+ #[cfg(feature = "scripted")]+ fn from_script(script: &crate::scripted::Script) -> Self {+ let fps = script.avg_fps();+ let keyframes = script+ .frames+ .iter()+ .filter(|frame| frame.keyframe)+ .map(|frame| {+ let secs = script.secs(frame.pts);+ ((secs * fps).round() as u32, secs)+ })+ .collect();+ Self {+ keyframes,+ fps,+ duration_secs: script.duration_secs(),+ pixel_format: Some(cv::PixelFormat::_420V),+ width: crate::scripted::FRAME_WIDTH,+ height: crate::scripted::FRAME_HEIGHT,+ }+ }+pub fn nearest_keyframe_before(&self, target_frame: u32) -> Option<(u32, f64)> {if self.keyframes.is_empty() {return None;@@ -394,8 +421,7 @@ pub struct AVAssetReaderDecoder {path: PathBuf,pixel_format: cv::PixelFormat,tokio_handle: TokioHandle,- track_output: R<av::AssetReaderTrackOutput>,- reader: R<av::AssetReader>,+ source: ReaderSource,width: u32,height: u32,keyframe_index: Option<Arc<KeyframeIndex>>,@@ -462,7 +488,7 @@ impl AVAssetReaderDecoder {let seek_time = compute_seek_time(keyframe_index.as_ref(), start_time);- let (track_output, reader) = Self::get_reader_track_output(+ let source = Self::get_reader_track_output(&path,seek_time,&tokio_handle,@@ -475,8 +501,7 @@ impl AVAssetReaderDecoder {path,pixel_format,tokio_handle,- track_output,- reader,+ source,width,height,keyframe_index,@@ -485,11 +510,11 @@ impl AVAssetReaderDecoder {}pub fn reset(&mut self, requested_time: f32) -> Result<(), String> {- self.reader.cancel_reading();+ self.source.cancel_reading();let seek_time = compute_seek_time(self.keyframe_index.as_ref(), requested_time);- (self.track_output, self.reader) = Self::get_reader_track_output(+ self.source = Self::get_reader_track_output(&self.path,seek_time,&self.tokio_handle,@@ -538,7 +563,20 @@ impl AVAssetReaderDecoder {pixel_format: cv::PixelFormat,width: u32,height: u32,- ) -> Result<(R<av::AssetReaderTrackOutput>, R<av::AssetReader>), String> {+ ) -> Result<ReaderSource, String> {+ let time_range = cm::TimeRange {+ start: cm::Time::with_secs(time as f64, 100),+ duration: cm::Time::infinity(),+ };++ #[cfg(feature = "scripted")]+ if let Some(state) = crate::scripted::lookup(path) {+ return Ok(ReaderSource::Scripted(crate::scripted::AvfReader::start(+ state,+ time_range.start,+ )));+ }+let asset = av::UrlAsset::with_url(&ns::Url::with_fs_path_str(path.to_str()@@ -552,11 +590,6 @@ impl AVAssetReaderDecoder {let mut reader = av::AssetReader::with_asset(&asset).map_err(|e| format!("AssetReader::with_asset: {e}"))?;- let time_range = cm::TimeRange {- start: cm::Time::with_secs(time as f64, 100),- duration: cm::Time::infinity(),- };-reader.set_time_range(time_range);let tracks = handle@@ -592,12 +625,15 @@ impl AVAssetReaderDecoder {.start_reading().map_err(|e| format!("reader.start_reading: {e}"))?;- Ok((reader_track_output, reader))+ Ok(ReaderSource::Native {+ track_output: reader_track_output,+ reader,+ })}pub fn frames(&mut self) -> FramesIter<'_> {FramesIter {- track_output: &mut self.track_output,+ source: &mut self.source,}}@@ -610,13 +646,32 @@ impl AVAssetReaderDecoder {}}+enum ReaderSource {+ Native {+ track_output: R<av::AssetReaderTrackOutput>,+ reader: R<av::AssetReader>,+ },+ #[cfg(feature = "scripted")]+ Scripted(crate::scripted::AvfReader),+}++impl ReaderSource {+ fn cancel_reading(&mut self) {+ match self {+ Self::Native { reader, .. } => reader.cancel_reading(),+ #[cfg(feature = "scripted")]+ Self::Scripted(_) => {}+ }+ }+}+pub struct FramesIter<'a> {- track_output: &'a mut av::AssetReaderTrackOutput,+ source: &'a mut ReaderSource,}impl Drop for AVAssetReaderDecoder {fn drop(&mut self) {- self.reader.cancel_reading();+ self.source.cancel_reading();}}@@ -624,7 +679,11 @@ impl<'a> Iterator for FramesIter<'a> {type Item = ns::ExResult<'static, arc::R<cm::SampleBuf>>;fn next(&mut self) -> Option<Self::Item> {- self.track_output.next_sample_buf().transpose()+ match self.source {+ ReaderSource::Native { track_output, .. } => track_output.next_sample_buf().transpose(),+ #[cfg(feature = "scripted")]+ ReaderSource::Scripted(reader) => reader.next_sample_buf().map(Ok),+ }}}diff --git a/crates/video-decode/src/ffmpeg.rs b/crates/video-decode/src/ffmpeg.rsindex b343f8544..75481f629 100644--- a/crates/video-decode/src/ffmpeg.rs+++ b/crates/video-decode/src/ffmpeg.rs@@ -192,6 +192,8 @@ pub struct FFmpegDecoder {enum DecoderInput {File(avformat::context::Input),Segmented(cap_enc_ffmpeg::SegmentedInput),+ #[cfg(feature = "scripted")]+ Scripted(crate::scripted::Demuxer),}impl DecoderInput {@@ -199,6 +201,8 @@ impl DecoderInput {match self {Self::File(input) => input,Self::Segmented(input) => input.input(),+ #[cfg(feature = "scripted")]+ Self::Scripted(_) => unreachable!("scripted media has no container"),}}@@ -206,6 +210,8 @@ impl DecoderInput {match self {Self::File(input) => input.seek(position, ..position),Self::Segmented(input) => input.seek(position),+ #[cfg(feature = "scripted")]+ Self::Scripted(demuxer) => demuxer.seek(position),}}@@ -213,6 +219,8 @@ impl DecoderInput {match self {Self::File(input) => DecoderPackets::File(input.packets()),Self::Segmented(input) => DecoderPackets::Segmented(input),+ #[cfg(feature = "scripted")]+ Self::Scripted(demuxer) => DecoderPackets::Scripted(demuxer),}}}@@ -220,6 +228,8 @@ impl DecoderInput {enum DecoderPackets<'a> {File(PacketIter<'a>),Segmented(&'a mut cap_enc_ffmpeg::SegmentedInput),+ #[cfg(feature = "scripted")]+ Scripted(&'a mut crate::scripted::Demuxer),}impl Iterator for DecoderPackets<'_> {@@ -238,6 +248,8 @@ impl Iterator for DecoderPackets<'_> {Err(error) => Some(Err(error)),}}+ #[cfg(feature = "scripted")]+ Self::Scripted(_) => None,}}}@@ -278,6 +290,18 @@ impl FFmpegDecoder {) -> Result<Self, String> {let path = path.into();+ #[cfg(feature = "scripted")]+ if let Some(state) = crate::scripted::lookup(&path) {+ let demuxer = crate::scripted::Demuxer::new(state);+ return Ok(FFmpegDecoder {+ decoder: demuxer.open_decoder()?,+ start_time: demuxer.start_time(),+ input: DecoderInput::Scripted(demuxer),+ stream_index: 0,+ hw_device: None,+ });+ }+let input = if path.is_dir() {DecoderInput::Segmented(open_fragmented_input(&path)?)} else {@@ -430,6 +454,11 @@ impl<'a> Iterator for FramesIter<'a> {type Item = Result<avframe::Video, avutil::error::Error>;fn next(&mut self) -> Option<Self::Item> {+ #[cfg(feature = "scripted")]+ if let DecoderPackets::Scripted(demuxer) = &mut self.packets {+ return demuxer.next_frame().map(Ok);+ }+let mut frame = avframe::Video::empty();loop {diff --git a/crates/video-decode/src/lib.rs b/crates/video-decode/src/lib.rsindex 682df7a77..110d4b687 100644--- a/crates/video-decode/src/lib.rs+++ b/crates/video-decode/src/lib.rs@@ -3,6 +3,8 @@ pub mod avassetreader;pub mod ffmpeg;#[cfg(target_os = "windows")]pub mod media_foundation;+#[cfg(feature = "scripted")]+pub mod scripted;#[cfg(target_os = "macos")]pub use avassetreader::{AVAssetReaderDecoder, KeyframeIndex};diff --git a/crates/video-decode/src/scripted.rs b/crates/video-decode/src/scripted.rsnew file mode 100644index 000000000..2b30ceb72--- /dev/null+++ b/crates/video-decode/src/scripted.rs@@ -0,0 +1,413 @@+//! Scripted media for decoder model tests, compiled only with the `scripted`+//! feature (enabled by test builds, never by the app). A script is a list of+//! video samples with exact presentation times and sync flags. Registering it+//! yields a path; opening that path with the real decoders reads the script+//! instead of a file, so everything above the container and the native reader+//! runs unchanged.+//!+//! Modelled container and reader behaviour:+//! - FFmpeg: `seek(ts)` lands on the newest sync sample at or before `ts`+//! (the first sample when there is none), as `avformat_seek_file` with+//! `max_ts = ts` does for MP4. Decoding then vends every sample from there in+//! presentation order.+//! - AVAssetReader: a reader started at time `T` vends the sample on screen at+//! `T` (the newest at or before it) and every later one. When that sample+//! starts before `T` its presentation time is trimmed to `T`. A reader started+//! at or after the end of the track vends nothing.+//!+//! Every vended frame carries its sample index in its first luma row, see+//! [`frame_id`].++use std::{+ collections::HashMap,+ path::{Path, PathBuf},+ sync::{+ Arc, Mutex, OnceLock,+ atomic::{AtomicU64, Ordering},+ },+};++const MAGIC: [u8; 4] = *b"CAPS";+pub const FRAME_WIDTH: u32 = 16;+pub const FRAME_HEIGHT: u32 = 16;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ScriptFrame {+ pub pts: i64,+ pub keyframe: bool,+}++#[derive(Clone, Debug)]+pub struct Script {+ /// Stream time base as (numerator, denominator).+ pub time_base: (i32, i32),+ /// Samples in strictly increasing presentation order.+ pub frames: Vec<ScriptFrame>,+ /// Duration of the last sample, in time base ticks.+ pub last_duration: i64,+}++impl Script {+ pub fn end_pts(&self) -> i64 {+ self.frames.last().map_or(0, |frame| frame.pts) + self.last_duration+ }++ pub fn secs(&self, ticks: i64) -> f64 {+ ticks as f64 * self.time_base.0 as f64 / self.time_base.1 as f64+ }++ pub fn duration_secs(&self) -> f64 {+ self.secs(self.end_pts() - self.frames.first().map_or(0, |frame| frame.pts))+ }++ /// Average frame rate as the MP4 demuxer reports it: sample count over+ /// track duration.+ pub fn avg_fps(&self) -> f64 {+ let duration = self.duration_secs();+ if duration > 0.0 {+ self.frames.len() as f64 / duration+ } else {+ 30.0+ }+ }++ fn validate(&self) {+ assert!(self.time_base.0 > 0 && self.time_base.1 > 0);+ assert!(!self.frames.is_empty(), "scripts need at least one frame");+ assert!(+ self.frames[0].keyframe,+ "the first sample must be a sync sample"+ );+ assert!(self.last_duration > 0);+ assert!(+ self.frames.windows(2).all(|pair| pair[0].pts < pair[1].pts),+ "sample presentation times must increase"+ );+ }+}++#[derive(Default)]+struct Counters {+ reader_starts: AtomicU64,+ seeks: AtomicU64,+}++pub(crate) struct ScriptState {+ pub(crate) script: Script,+ counters: Counters,+ vended: Mutex<Vec<u32>>,+ #[cfg(target_os = "macos")]+ samples: Mutex<HashMap<usize, avf::SharedSample>>,+}++impl ScriptState {+ fn record_vend(&self, index: usize) {+ self.vended.lock().unwrap().push(index as u32);+ }++ /// Whether `pts` (in stream ticks) is at or before `value / scale` seconds.+ fn at_or_before(&self, pts: i64, value: i64, scale: i32) -> bool {+ let (num, den) = self.script.time_base;+ (pts as i128) * (num as i128) * (scale as i128) <= (value as i128) * (den as i128)+ }++ fn newest_at_or_before(&self, value: i64, scale: i32) -> Option<usize> {+ self.script+ .frames+ .partition_point(|frame| self.at_or_before(frame.pts, value, scale))+ .checked_sub(1)+ }+}++fn registry() -> &'static Mutex<HashMap<PathBuf, Arc<ScriptState>>> {+ static REGISTRY: OnceLock<Mutex<HashMap<PathBuf, Arc<ScriptState>>>> = OnceLock::new();+ REGISTRY.get_or_init(Default::default)+}++pub(crate) fn lookup(path: &Path) -> Option<Arc<ScriptState>> {+ registry().lock().unwrap().get(path).cloned()+}++/// Frame dimensions of a registered script, for probes that would otherwise+/// open the path as a file.+pub fn dimensions(path: &Path) -> Option<(u32, u32)> {+ lookup(path).map(|_| (FRAME_WIDTH, FRAME_HEIGHT))+}++/// A registered script. Dropping it unregisters the path.+pub struct Registration {+ path: PathBuf,+ state: Arc<ScriptState>,+}++impl Registration {+ pub fn path(&self) -> &Path {+ &self.path+ }++ pub fn script(&self) -> &Script {+ &self.state.script+ }++ /// Sample indices vended by every reader of this script since the last call.+ pub fn take_vended(&self) -> Vec<u32> {+ std::mem::take(&mut *self.state.vended.lock().unwrap())+ }++ /// AVAssetReader starts: creations and resets.+ pub fn reader_starts(&self) -> u64 {+ self.state.counters.reader_starts.load(Ordering::Relaxed)+ }++ /// FFmpeg demuxer seeks.+ pub fn seeks(&self) -> u64 {+ self.state.counters.seeks.load(Ordering::Relaxed)+ }+}++impl Drop for Registration {+ fn drop(&mut self) {+ registry().lock().unwrap().remove(&self.path);+ }+}++pub fn register(script: Script) -> Registration {+ static NEXT: AtomicU64 = AtomicU64::new(0);+ script.validate();+ let path = PathBuf::from(format!(+ "/nonexistent/cap-scripted-media/{}-{}.mp4",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::Relaxed)+ ));+ let state = Arc::new(ScriptState {+ script,+ counters: Counters::default(),+ vended: Mutex::new(Vec::new()),+ #[cfg(target_os = "macos")]+ samples: Mutex::new(HashMap::new()),+ });+ registry()+ .lock()+ .unwrap()+ .insert(path.clone(), state.clone());+ Registration { path, state }+}++fn identity_row(index: u32) -> [u8; FRAME_WIDTH as usize] {+ let mut row = [0u8; FRAME_WIDTH as usize];+ row[..4].copy_from_slice(&MAGIC);+ row[4..8].copy_from_slice(&index.to_le_bytes());+ row[8..12].copy_from_slice(&(!index).to_le_bytes());+ row+}++/// The sample index a decoded frame was made from: reads the first luma row of+/// the frame's raw planes.+pub fn frame_id(first_row: &[u8]) -> Option<u32> {+ if first_row.len() < 12 || first_row[..4] != MAGIC {+ return None;+ }+ let index = u32::from_le_bytes(first_row[4..8].try_into().ok()?);+ let check = u32::from_le_bytes(first_row[8..12].try_into().ok()?);+ (check == !index).then_some(index)+}++pub(crate) struct Demuxer {+ state: Arc<ScriptState>,+ next: usize,+}++impl Demuxer {+ pub(crate) fn new(state: Arc<ScriptState>) -> Self {+ Self { state, next: 0 }+ }++ pub(crate) fn start_time(&self) -> i64 {+ self.state.script.frames[0].pts+ }++ pub(crate) fn time_base(&self) -> ffmpeg::Rational {+ let (num, den) = self.state.script.time_base;+ ffmpeg::Rational::new(num, den)+ }++ /// `position` is in `AV_TIME_BASE` units, as `avformat_seek_file` receives+ /// it with no stream index.+ pub(crate) fn seek(&mut self, position: i64) -> Result<(), ffmpeg::Error> {+ self.state.counters.seeks.fetch_add(1, Ordering::Relaxed);+ let (num, den) = self.state.script.time_base;+ let ticks = rescale_rounded(position, den as i64, 1_000_000 * num as i64);+ let frames = &self.state.script.frames;+ let at_or_before = frames.partition_point(|frame| frame.pts <= ticks);+ self.next = frames[..at_or_before]+ .iter()+ .rposition(|frame| frame.keyframe)+ .unwrap_or(0);+ Ok(())+ }++ pub(crate) fn next_frame(&mut self) -> Option<ffmpeg::frame::Video> {+ let frame = self.state.script.frames.get(self.next)?;+ let index = self.next;+ self.next += 1;+ self.state.record_vend(index);+ let mut video =+ ffmpeg::frame::Video::new(ffmpeg::format::Pixel::YUV420P, FRAME_WIDTH, FRAME_HEIGHT);+ video.data_mut(0).fill(16);+ let row = identity_row(index as u32);+ video.data_mut(0)[..row.len()].copy_from_slice(&row);+ video.data_mut(1).fill(128);+ video.data_mut(2).fill(128);+ video.set_pts(Some(frame.pts));+ Some(video)+ }++ pub(crate) fn open_decoder(&self) -> Result<ffmpeg::decoder::Video, String> {+ let codec = ffmpeg::decoder::find(ffmpeg::codec::Id::RAWVIDEO)+ .or_else(|| ffmpeg::decoder::find(ffmpeg::codec::Id::H264))+ .ok_or("no decoder available for scripted media")?;+ let mut context = ffmpeg::codec::Context::new_with_codec(codec);+ unsafe {+ let raw = context.as_mut_ptr();+ (*raw).width = FRAME_WIDTH as i32;+ (*raw).height = FRAME_HEIGHT as i32;+ (*raw).pix_fmt = ffmpeg::ffi::AVPixelFormat::AV_PIX_FMT_YUV420P;+ }+ let mut decoder = context+ .decoder()+ .video()+ .map_err(|error| format!("scripted decoder / {error}"))?;+ decoder.set_time_base(self.time_base());+ Ok(decoder)+ }+}++/// `a * b / c` rounded half away from zero, as `av_rescale` does.+fn rescale_rounded(a: i64, b: i64, c: i64) -> i64 {+ let product = a as i128 * b as i128;+ let c = c as i128;+ let rounded = if product >= 0 {+ (product + c / 2) / c+ } else {+ (product - c / 2) / c+ };+ rounded as i64+}++#[cfg(target_os = "macos")]+pub(crate) use avf::AvfReader;++#[cfg(target_os = "macos")]+mod avf {+ use super::*;+ use cidre::{arc::R, cm, cv};++ /// Sample buffers are immutable once built and CoreFoundation reference+ /// counting is thread safe, so a script shares them across its readers.+ pub(crate) struct SharedSample(R<cm::SampleBuf>);++ unsafe impl Send for SharedSample {}++ pub(crate) struct AvfReader {+ state: Arc<ScriptState>,+ next: usize,+ trimmed_start: Option<cm::Time>,+ }++ impl AvfReader {+ pub(crate) fn start(state: Arc<ScriptState>, start: cm::Time) -> Self {+ state.counters.reader_starts.fetch_add(1, Ordering::Relaxed);+ let script = &state.script;+ let past_end = state.at_or_before(script.end_pts(), start.value, start.scale);+ let (next, trimmed_start) = if past_end {+ (script.frames.len(), None)+ } else {+ match state.newest_at_or_before(start.value, start.scale) {+ None => (0, None),+ Some(index) => {+ let pts = script.frames[index].pts;+ let (num, den) = script.time_base;+ let exact = (pts as i128) * (num as i128) * (start.scale as i128)+ == (start.value as i128) * (den as i128);+ (index, (!exact).then_some(start))+ }+ }+ };+ Self {+ state,+ next,+ trimmed_start,+ }+ }++ pub(crate) fn next_sample_buf(&mut self) -> Option<R<cm::SampleBuf>> {+ let script = &self.state.script;+ let frame = script.frames.get(self.next)?;+ let index = self.next;+ self.next += 1;+ self.state.record_vend(index);++ let trimmed = self.trimmed_start.take();+ if trimmed.is_none()+ && let Some(SharedSample(sample)) = self.state.samples.lock().unwrap().get(&index)+ {+ return Some(sample.retained());+ }+ let (num, den) = script.time_base;+ let pts = trimmed.unwrap_or_else(|| cm::Time::new(frame.pts * num as i64, den));+ let end = script+ .frames+ .get(index + 1)+ .map_or(script.end_pts(), |next| next.pts);+ let duration = cm::Time::new((end - frame.pts) * num as i64, den);++ let mut pixel_buf = cv::PixelBuf::new(+ FRAME_WIDTH as usize,+ FRAME_HEIGHT as usize,+ cv::PixelFormat::_420V,+ None,+ )+ .ok()?;+ unsafe {+ pixel_buf+ .lock_base_addr(cv::pixel_buffer::LockFlags::DEFAULT)+ .result()+ .ok()?;+ let row = identity_row(index as u32);+ for plane in 0..2 {+ let bytes =+ pixel_buf.plane_bytes_per_row(plane) * pixel_buf.plane_height(plane);+ let base = pixel_buf.plane_base_address(plane) as *mut u8;+ std::ptr::write_bytes(base, if plane == 0 { 16 } else { 128 }, bytes);+ if plane == 0 {+ std::ptr::copy_nonoverlapping(row.as_ptr(), base, row.len());+ }+ }+ pixel_buf.unlock_lock_base_addr(cv::pixel_buffer::LockFlags::DEFAULT);+ }+ let format = cm::VideoFormatDesc::with_image_buf(&pixel_buf).ok()?;+ let timing = cm::SampleTimingInfo {+ duration,+ pts,+ dts: cm::Time::invalid(),+ };+ let sample = cm::SampleBuf::with_image_buf(+ &pixel_buf,+ true,+ None,+ std::ptr::null(),+ &format,+ &timing,+ )+ .ok()?;+ if trimmed.is_none() {+ self.state+ .samples+ .lock()+ .unwrap()+ .insert(index, SharedSample(sample.retained()));+ }+ Some(sample)+ }+ }+}