Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(rendering): bound decoder caches and harden media seeking

Richie McIlroy31adcd22ee42
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index fac9e4c0d..900b80d07 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -559,13 +559,14 @@ impl AVAssetReaderDecoder {
ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,
tokio_handle: tokio::runtime::Handle,
) {
- let mut this = match AVAssetReaderDecoder::new(path, tokio_handle) {
- Ok(v) => v,
- Err(e) => {
- ready_tx.send(Err(e)).ok();
- return;
- }
- };
+ let mut this =
+ match objc2::rc::autoreleasepool(|_| AVAssetReaderDecoder::new(path, tokio_handle)) {
+ Ok(v) => v,
+ Err(e) => {
+ ready_tx.send(Err(e)).ok();
+ return;
+ }
+ };
let video_width = this.decoders[0].inner.width();
let video_height = this.decoders[0].inner.height();
@@ -606,6 +607,7 @@ impl AVAssetReaderDecoder {
let mut deferred_requests = VecDeque::<PendingRequest>::new();
loop {
+ let _autorelease_pool = cidre::objc::AutoreleasePoolPage::push();
let mut pending_requests: Vec<PendingRequest> = Vec::with_capacity(8);
let processing_deferred = !deferred_requests.is_empty();
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index f0c0d1b84..92d271337 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -70,6 +70,7 @@ struct PendingRequest {
}
const MAX_FRAME_LOOKBACK_TOLERANCE: u32 = 2;
+const MAX_FRAME_CACHE_BYTES: usize = 128 * 1024 * 1024;
fn extract_yuv_planes(frame: &frame::Video) -> Option<(Vec<u8>, PixelFormat, u32, u32)> {
let height = frame.height();
@@ -201,6 +202,76 @@ enum CachedFrame {
},
}
+impl CachedFrame {
+ fn estimated_bytes(&self) -> usize {
+ match self {
+ Self::Raw { frame, .. } => {
+ let height = frame.height() as usize;
+ match frame.format() {
+ format::Pixel::YUV420P => {
+ frame.stride(0).saturating_mul(height).saturating_add(
+ frame
+ .stride(1)
+ .saturating_add(frame.stride(2))
+ .saturating_mul(height / 2),
+ )
+ }
+ format::Pixel::NV12 => frame
+ .stride(0)
+ .saturating_mul(height)
+ .saturating_add(frame.stride(1).saturating_mul(height / 2)),
+ _ => (frame.width() as usize)
+ .saturating_mul(height)
+ .saturating_mul(4),
+ }
+ }
+ Self::Processed(frame) => frame.data.len(),
+ #[cfg(target_os = "windows")]
+ Self::Gpu { frame, .. } => (frame.width() as usize)
+ .saturating_mul(frame.height() as usize)
+ .saturating_mul(3),
+ }
+ }
+}
+
+fn insert_cached_frame(
+ cache: &mut BTreeMap<u32, CachedFrame>,
+ number: u32,
+ frame: CachedFrame,
+ requested_frame: u32,
+ last_active_frame: Option<u32>,
+ max_bytes: usize,
+) {
+ let frame_bytes = frame.estimated_bytes();
+ let mut cache_bytes = cache
+ .values()
+ .map(CachedFrame::estimated_bytes)
+ .fold(0usize, usize::saturating_add);
+
+ while !cache.is_empty()
+ && (cache.len() >= FRAME_CACHE_SIZE || cache_bytes.saturating_add(frame_bytes) > max_bytes)
+ {
+ let Some(last_active_frame) = last_active_frame else {
+ cache.clear();
+ break;
+ };
+ let first = *cache.keys().next().unwrap();
+ let last = *cache.keys().next_back().unwrap();
+ let evicted = if requested_frame > last_active_frame {
+ first
+ } else if requested_frame < last_active_frame || number <= last {
+ last
+ } else {
+ first
+ };
+ if let Some(frame) = cache.remove(&evicted) {
+ cache_bytes = cache_bytes.saturating_sub(frame.estimated_bytes());
+ }
+ }
+
+ cache.insert(number, frame);
+}
+
pub struct FfmpegDecoder;
impl FfmpegDecoder {
@@ -571,24 +642,14 @@ impl FfmpegDecoder {
{
cache_frame.produce(&mut sw_converter);
- if sw_cache.len() >= FRAME_CACHE_SIZE {
- if let Some(last_active_frame) = &sw_last_active_frame {
- let frame = if requested_frame > *last_active_frame {
- *sw_cache.keys().next().unwrap()
- } else if requested_frame < *last_active_frame {
- *sw_cache.keys().next_back().unwrap()
- } else {
- let min = *sw_cache.keys().min().unwrap();
- let max = *sw_cache.keys().max().unwrap();
- if current_frame > max { min } else { max }
- };
- sw_cache.remove(&frame);
- } else {
- sw_cache.clear()
- }
- }
-
- sw_cache.insert(current_frame, cache_frame);
+ insert_cached_frame(
+ &mut sw_cache,
+ current_frame,
+ cache_frame,
+ requested_frame,
+ sw_last_active_frame,
+ MAX_FRAME_CACHE_BYTES,
+ );
// Serve exact matches from the cache so
// sequentially played frames stay available as
@@ -1032,26 +1093,14 @@ impl FfmpegDecoder {
{
cache_frame.produce(&mut converter);
- if cache.len() >= FRAME_CACHE_SIZE {
- if let Some(last_active_frame) = &last_active_frame {
- let frame = if requested_frame > *last_active_frame {
- *cache.keys().next().unwrap()
- } else if requested_frame < *last_active_frame {
- *cache.keys().next_back().unwrap()
- } else {
- let min = *cache.keys().min().unwrap();
- let max = *cache.keys().max().unwrap();
-
- if current_frame > max { min } else { max }
- };
-
- cache.remove(&frame);
- } else {
- cache.clear()
- }
- }
-
- cache.insert(current_frame, cache_frame);
+ insert_cached_frame(
+ &mut cache,
+ current_frame,
+ cache_frame,
+ requested_frame,
+ last_active_frame,
+ MAX_FRAME_CACHE_BYTES,
+ );
// Serve exact matches from the cache so
// sequentially played frames stay available as
@@ -1216,6 +1265,69 @@ impl FfmpegDecoder {
}
}
+#[cfg(test)]
+mod cache_tests {
+ use super::*;
+
+ fn frame(number: u32, bytes: usize) -> CachedFrame {
+ CachedFrame::Processed(ProcessedFrame {
+ number,
+ data: Arc::new(vec![0; bytes]),
+ width: 2,
+ height: 2,
+ format: PixelFormat::Nv12,
+ y_stride: 2,
+ uv_stride: 2,
+ })
+ }
+
+ #[test]
+ fn forward_playback_keeps_recent_frames_within_byte_budget() {
+ let mut cache = BTreeMap::new();
+
+ for number in 0..5 {
+ insert_cached_frame(&mut cache, number, frame(number, 6), 5, Some(4), 13);
+ }
+
+ assert_eq!(cache.keys().copied().collect::<Vec<_>>(), vec![3, 4]);
+ assert_eq!(
+ cache
+ .values()
+ .map(CachedFrame::estimated_bytes)
+ .sum::<usize>(),
+ 12
+ );
+ }
+
+ #[test]
+ fn backward_seek_keeps_earliest_frames_within_byte_budget() {
+ let mut cache = BTreeMap::new();
+
+ for number in [5, 4, 3, 2] {
+ insert_cached_frame(&mut cache, number, frame(number, 5), 2, Some(6), 11);
+ }
+
+ assert_eq!(cache.keys().copied().collect::<Vec<_>>(), vec![2, 3]);
+ assert_eq!(
+ cache
+ .values()
+ .map(CachedFrame::estimated_bytes)
+ .sum::<usize>(),
+ 10
+ );
+ }
+
+ #[test]
+ fn oversize_frame_remains_available_without_retaining_older_frames() {
+ let mut cache = BTreeMap::new();
+ insert_cached_frame(&mut cache, 1, frame(1, 4), 1, Some(1), 8);
+ insert_cached_frame(&mut cache, 2, frame(2, 12), 2, Some(1), 8);
+
+ assert_eq!(cache.keys().copied().collect::<Vec<_>>(), vec![2]);
+ assert_eq!(cache[&2].estimated_bytes(), 12);
+ }
+}
+
// pub fn find_decoder(
// s: &format::context::Input,
// st: &format::stream::Stream,
diff --git a/crates/rendering/src/decoder/media_foundation.rs b/crates/rendering/src/decoder/media_foundation.rs
index 263dbf8b0..e98262d96 100644
--- a/crates/rendering/src/decoder/media_foundation.rs
+++ b/crates/rendering/src/decoder/media_foundation.rs
@@ -12,6 +12,8 @@ use windows::Win32::{Foundation::HANDLE, Graphics::Direct3D11::ID3D11Texture2D};
use super::{DecodedFrame, DecoderInitResult, DecoderType, FRAME_CACHE_SIZE, VideoDecoderMessage};
+const MAX_FRAME_CACHE_BYTES: usize = 128 * 1024 * 1024;
+
struct DecoderHealthMonitor {
consecutive_errors: u32,
consecutive_texture_read_failures: u32,
@@ -123,7 +125,7 @@ impl DecoderHealthMonitor {
#[derive(Clone)]
struct CachedFrame {
number: u32,
- _texture: ID3D11Texture2D,
+ _texture: Option<ID3D11Texture2D>,
_shared_handle: Option<HANDLE>,
_y_handle: Option<HANDLE>,
_uv_handle: Option<HANDLE>,
@@ -133,15 +135,26 @@ struct CachedFrame {
}
impl CachedFrame {
+ fn estimated_bytes(&self) -> usize {
+ let texture_bytes = self._texture.as_ref().map_or(0, |_| {
+ (self.width as usize)
+ .saturating_mul(self.height as usize)
+ .saturating_mul(3)
+ });
+ texture_bytes.saturating_add(self.nv12_data.as_ref().map_or(0, |data| data.data.len()))
+ }
+
fn to_decoded_frame(&self) -> DecodedFrame {
let null_ptr = std::ptr::null_mut();
let y_handle = self._y_handle.filter(|h| h.0 != null_ptr);
let uv_handle = self._uv_handle.filter(|h| h.0 != null_ptr);
- if let (Some(y_handle), Some(uv_handle)) = (y_handle, uv_handle) {
+ if let (Some(texture), Some(y_handle), Some(uv_handle)) =
+ (&self._texture, y_handle, uv_handle)
+ {
return DecodedFrame::new_nv12_with_d3d11_texture_and_yuv_handles(
self.width,
self.height,
- self._texture.clone(),
+ texture.clone(),
self._shared_handle,
Some(y_handle),
Some(uv_handle),
@@ -149,8 +162,8 @@ impl CachedFrame {
}
if let Some(nv12_data) = &self.nv12_data {
- DecodedFrame::new_nv12(
- nv12_data.data.clone(),
+ DecodedFrame::new_nv12_with_arc(
+ Arc::clone(&nv12_data.data),
self.width,
self.height,
nv12_data.y_stride,
@@ -218,6 +231,7 @@ impl MFDecoder {
let video_height = decoder.height();
let mut cache = BTreeMap::<u32, CachedFrame>::new();
+ let mut cache_bytes = 0usize;
let mut last_decoded_frame: Option<u32> = None;
let mut health = DecoderHealthMonitor::new();
@@ -324,6 +338,7 @@ impl MFDecoder {
warn!("MediaFoundation seek failed: {e}");
}
cache.clear();
+ cache_bytes = 0;
last_decoded_frame = None;
}
@@ -393,27 +408,47 @@ impl MFDecoder {
let cached = CachedFrame {
number: frame_number,
- _texture: mf_frame.textures.nv12.texture.clone(),
- _shared_handle: Some(mf_frame.textures.nv12.handle),
- _y_handle: Some(mf_frame.textures.y.handle),
- _uv_handle: Some(mf_frame.textures.uv.handle),
+ _texture: has_valid_zero_copy_handles
+ .then(|| mf_frame.textures.nv12.texture.clone()),
+ _shared_handle: has_valid_zero_copy_handles
+ .then_some(mf_frame.textures.nv12.handle),
+ _y_handle: has_valid_zero_copy_handles
+ .then_some(mf_frame.textures.y.handle),
+ _uv_handle: has_valid_zero_copy_handles
+ .then_some(mf_frame.textures.uv.handle),
nv12_data,
width: mf_frame.width,
height: mf_frame.height,
};
+ if !has_valid_zero_copy_handles {
+ decoder.recycle_textures(mf_frame.textures);
+ }
+
last_decoded_frame = Some(frame_number);
if frame_number >= cache_min && frame_number <= cache_max {
- if cache.len() >= FRAME_CACHE_SIZE {
+ let frame_bytes = cached.estimated_bytes();
+ while !cache.is_empty()
+ && (cache.len() >= FRAME_CACHE_SIZE
+ || cache_bytes.saturating_add(frame_bytes)
+ > MAX_FRAME_CACHE_BYTES)
+ {
let key_to_remove = if frame_number > requested_frame {
*cache.keys().next().unwrap()
} else {
*cache.keys().next_back().unwrap()
};
- cache.remove(&key_to_remove);
+ if let Some(evicted) = cache.remove(&key_to_remove) {
+ cache_bytes =
+ cache_bytes.saturating_sub(evicted.estimated_bytes());
+ }
+ }
+ if let Some(replaced) = cache.insert(frame_number, cached.clone()) {
+ cache_bytes =
+ cache_bytes.saturating_sub(replaced.estimated_bytes());
}
- cache.insert(frame_number, cached.clone());
+ cache_bytes = cache_bytes.saturating_add(frame_bytes);
}
if frame_number <= requested_frame {
diff --git a/crates/video-decode/src/media_foundation.rs b/crates/video-decode/src/media_foundation.rs
index 83bb3a86d..9e41c2d2a 100644
--- a/crates/video-decode/src/media_foundation.rs
+++ b/crates/video-decode/src/media_foundation.rs
@@ -144,7 +144,7 @@ pub struct MFDecodedFrame {
}
pub struct NV12Data {
- pub data: Vec<u8>,
+ pub data: Arc<Vec<u8>>,
pub y_stride: u32,
pub uv_stride: u32,
}
@@ -731,7 +731,7 @@ impl MediaFoundationDecoder {
}
Ok(NV12Data {
- data,
+ data: Arc::new(data),
y_stride,
uv_stride: y_stride,
})
@@ -825,12 +825,14 @@ impl MediaFoundationDecoder {
None,
);
- self.plane_converter.convert(
- &frame_textures.nv12.texture,
- &frame_textures,
- self.width,
- self.height,
- )?;
+ if !frame_textures.y.handle.0.is_null() && !frame_textures.uv.handle.0.is_null() {
+ self.plane_converter.convert(
+ &frame_textures.nv12.texture,
+ &frame_textures,
+ self.width,
+ self.height,
+ )?;
+ }
}
let plane_time = plane_start.elapsed();
@@ -1031,11 +1033,7 @@ unsafe fn create_source_reader(
.map_err(|e| format!("SetUINT32 ENABLE_ADVANCED_VIDEO_PROCESSING failed: {e:?}"))?;
}
- let path_wide: Vec<u16> = path
- .to_string_lossy()
- .encode_utf16()
- .chain(std::iter::once(0))
- .collect();
+ let path_wide = media_foundation_path(path);
let source_reader = unsafe {
MFCreateSourceReaderFromURL(PCWSTR(path_wide.as_ptr()), &attributes)
@@ -1045,6 +1043,23 @@ unsafe fn create_source_reader(
Ok(source_reader)
}
+fn media_foundation_path(path: &Path) -> Vec<u16> {
+ use std::os::windows::ffi::OsStrExt;
+
+ let mut path: Vec<u16> = path.as_os_str().encode_wide().collect();
+ let extended_unc = [92, 92, 63, 92, 85, 78, 67, 92];
+ let extended_drive = [92, 92, 63, 92];
+
+ if path.starts_with(&extended_unc) {
+ path.splice(..extended_unc.len(), [92, 92]);
+ } else if path.starts_with(&extended_drive) {
+ path.drain(..extended_drive.len());
+ }
+
+ path.push(0);
+ path
+}
+
unsafe fn configure_output_type(source_reader: &IMFSourceReader) -> Result<(), String> {
let media_type =
unsafe { MFCreateMediaType().map_err(|e| format!("MFCreateMediaType failed: {e:?}"))? };
@@ -1099,3 +1114,35 @@ unsafe fn get_video_info(source_reader: &IMFSourceReader) -> Result<(u32, u32, u
}
unsafe impl Send for MediaFoundationDecoder {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn normalized(path: &str) -> String {
+ let encoded = media_foundation_path(Path::new(path));
+ assert_eq!(encoded.last(), Some(&0));
+ String::from_utf16(&encoded[..encoded.len().saturating_sub(1)]).unwrap()
+ }
+
+ #[test]
+ fn removes_extended_drive_prefix_for_media_foundation() {
+ assert_eq!(
+ normalized(r"\\?\C:\Recordings\clip.mp4"),
+ r"C:\Recordings\clip.mp4"
+ );
+ }
+
+ #[test]
+ fn restores_unc_prefix_for_media_foundation() {
+ assert_eq!(
+ normalized(r"\\?\UNC\server\recordings\clip.mp4"),
+ r"\\server\recordings\clip.mp4"
+ );
+ }
+
+ #[test]
+ fn preserves_regular_unicode_paths() {
+ assert_eq!(normalized(r"C:\Vidéos\录制.mp4"), r"C:\Vidéos\录制.mp4");
+ }
+}