Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(video-decode): apply software decode threads before opening the decoder
ajanraj2a44b59a8c4c
diff --git a/crates/video-decode/src/ffmpeg.rs b/crates/video-decode/src/ffmpeg.rsindex b343f8544..9ed515886 100644--- a/crates/video-decode/src/ffmpeg.rs+++ b/crates/video-decode/src/ffmpeg.rs@@ -148,16 +148,18 @@ pub fn get_hw_decoder_capabilities() -> &'static HwDecoderCapabilities {HW_CAPABILITIES.get_or_init(query_d3d11_video_decoder_capabilities)}-fn configure_software_threading(decoder: &mut avcodec::decoder::Video, width: u32, height: u32) {+fn configure_software_threading(decoder: &mut avcodec::decoder::Decoder, width: u32, height: u32) {let pixel_count = (width as u64) * (height as u64);let cpu_count = num_cpus::get();- let thread_count = if pixel_count > 8294400 {- 0- } else if pixel_count > 2073600 {+ // Frame threads refill their pipeline after every seek, so each extra+ // thread adds seek latency. Measured on a 3024x1964 recording, export+ // throughput stops improving at 4 threads while editor seeks keep slowing;+ // only 3840x2160 and larger sources still gain random-access speed up to 8.+ let thread_count = if pixel_count >= 3840 * 2160 {cpu_count.clamp(2, 8) as i32} else {- cpu_count.clamp(2, 6) as i32+ cpu_count.clamp(2, 4) as i32};let thread_type = ffmpeg::sys::FF_THREAD_FRAME | ffmpeg::sys::FF_THREAD_SLICE;@@ -171,13 +173,7 @@ fn configure_software_threading(decoder: &mut avcodec::decoder::Video, width: u3}info!(- "Software decode configured: {width}x{height}, thread_count={}, thread_type=frame+slice, cpus={}",- if thread_count == 0 {- "auto".to_string()- } else {- thread_count.to_string()- },- cpu_count+ "Software decode configured: {width}x{height}, thread_count={thread_count}, thread_type=frame+slice, cpus={cpu_count}");}@@ -326,50 +322,62 @@ impl FFmpegDecoder {let stream_index = input_stream.index();- let mut decoder = avcodec::Context::from_parameters(input_stream.parameters())- .map_err(|e| format!("decoder context / {e}"))?- .decoder()- .video()- .map_err(|e| format!("video decoder / {e}"))?;-- decoder.set_time_base(input_stream.time_base());+ let (width, height) = unsafe {+ let parameters = input_stream.parameters().as_ptr();+ (+ (*parameters).width.max(0) as u32,+ (*parameters).height.max(0) as u32,+ )+ };- let width = decoder.width();- let height = decoder.height();+ // avcodec_open2, which `.video()` calls, reads the thread settings, so+ // software threading must be configured on the unopened decoder.+ let open = |software_threading: bool| -> Result<avcodec::decoder::Video, String> {+ let mut decoder = avcodec::Context::from_parameters(input_stream.parameters())+ .map_err(|e| format!("decoder context / {e}"))?+ .decoder();+ if software_threading {+ configure_software_threading(&mut decoder, width, height);+ }+ let mut decoder = decoder+ .video()+ .map_err(|e| format!("video decoder / {e}"))?;+ decoder.set_time_base(input_stream.time_base());+ Ok(decoder)+ };let hw_caps = get_hw_decoder_capabilities();let exceeds_hw_limits =width > hw_caps.max_width || height > hw_caps.max_height || !hw_caps.supports_hw_decode;- let hw_device = hw_device_type.and_then(|hw_device_type| {- if exceeds_hw_limits {+ let (decoder, hw_device) = match hw_device_type {+ Some(_) if exceeds_hw_limits => {warn!("Video dimensions {width}x{height} exceed hardware decoder limits ({}x{}), using software decode",hw_caps.max_width, hw_caps.max_height);- configure_software_threading(&mut decoder, width, height);- None- } else {+ (open(true)?, None)+ }+ Some(hw_device_type) => {+ let mut decoder = open(false)?;match decoder.try_use_hw_device(hw_device_type) {Ok(device) => {info!("Using hardware acceleration for {width}x{height} video (device: {:?})",hw_device_type);- Some(device)+ (decoder, Some(device))}Err(error) => {- warn!("Failed to enable hardware decoder: {error:?}, falling back to optimized software decode");- configure_software_threading(&mut decoder, width, height);- None+ warn!(+ "Failed to enable hardware decoder: {error:?}, falling back to optimized software decode"+ );+ (open(true)?, None)}}}- });-- if hw_device.is_none() && hw_device_type.is_none() {- configure_software_threading(&mut decoder, width, height);- }+ None => (open(true)?, None),+ };Ok(FFmpegDecoder {input,@@ -395,6 +403,7 @@ impl FFmpegDecoder {decoder: &mut self.decoder,stream_index: self.stream_index,hw_device: self.hw_device.as_mut(),+ eof_sent: false,}}@@ -418,6 +427,7 @@ pub struct FramesIter<'a> {packets: DecoderPackets<'a>,stream_index: usize,hw_device: Option<&'a mut HwDevice>,+ eof_sent: bool,}impl FramesIter<'_> {@@ -450,9 +460,20 @@ impl<'a> Iterator for FramesIter<'a> {Err(e) => return Some(Err(e)),}- let (stream_index, packet) = match self.packets.next()? {- Ok(packet) => packet,- Err(error) => return Some(Err(error)),+ // Frame threads hold up to thread_count - 1 decoded frames; only+ // an end-of-stream signal drains them at the end of the input.+ let (stream_index, packet) = match self.packets.next() {+ Some(Ok(packet)) => packet,+ Some(Err(error)) => return Some(Err(error)),+ None if self.eof_sent => return None,+ None => {+ self.eof_sent = true;+ match self.decoder.send_eof() {+ Ok(()) => continue,+ Err(ffmpeg::Error::Eof) => return None,+ Err(e) => return Some(Err(e)),+ }+ }};if stream_index != self.stream_index {@@ -560,6 +581,33 @@ mod tests {}}+ #[test]+ fn software_decoder_opens_with_frame_threads() {+ let directory = tempfile::tempdir().unwrap();+ let source = directory.path().join("segments");+ encode_segments(&source);+ // MediaCodec never exists on desktop, so it exercises the failed+ // hardware fallback.+ for hw_device_type in [None, Some(AVHWDeviceType::AV_HWDEVICE_TYPE_MEDIACODEC)] {+ let decoder = FFmpegDecoder::new(&source, hw_device_type).unwrap();+ assert!(decoder.hw_device.is_none());+ let context = unsafe { &*decoder.decoder.as_ptr() };+ assert!(context.thread_count >= 2);+ assert_ne!(context.active_thread_type & ffmpeg::sys::FF_THREAD_FRAME, 0);+ }+ }++ #[test]+ fn threaded_decoder_drains_every_frame_at_end_of_input() {+ let directory = tempfile::tempdir().unwrap();+ let source = directory.path().join("segments");+ encode_segments(&source);+ let mut decoder = FFmpegDecoder::new(&source, None).unwrap();+ assert_eq!(frames(&mut decoder).len(), 120);+ decoder.reset(0.0).unwrap();+ assert_eq!(frames(&mut decoder).len(), 120);+ }+#[test]fn relocatable_decoder_preserves_live_frames_and_seeks_after_publication() {let directory = tempfile::tempdir().unwrap();