Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf: encode ProRes MOV exports across all cores
Aqua-123b6cd10c22a45
diff --git a/crates/enc-ffmpeg/src/mux/mov.rs b/crates/enc-ffmpeg/src/mux/mov.rsindex 0580de59c..3b1303272 100644--- a/crates/enc-ffmpeg/src/mux/mov.rs+++ b/crates/enc-ffmpeg/src/mux/mov.rs@@ -83,3 +83,91 @@ impl Drop for MOVFile {let _ = self.finish();}}++#[cfg(test)]+mod tests {+ use super::*;+ use cap_media_info::{RawVideoFormat, VideoInfo};++ const WIDTH: u32 = 64;+ const HEIGHT: u32 = 48;++ fn shade(index: usize) -> u8 {+ (16 + index * 9) as u8+ }++ fn decoded_shades(path: &std::path::Path) -> Vec<u8> {+ let mut input = format::input(path).unwrap();+ let stream = input.streams().best(ffmpeg::media::Type::Video).unwrap();+ let stream_index = stream.index();+ let mut decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters())+ .unwrap()+ .decoder()+ .video()+ .unwrap();+ let mut scaler = ffmpeg::software::scaling::Context::get(+ decoder.format(),+ WIDTH,+ HEIGHT,+ format::Pixel::RGBA,+ WIDTH,+ HEIGHT,+ ffmpeg::software::scaling::Flags::POINT,+ )+ .unwrap();++ let mut shades = Vec::new();+ let mut decoded = frame::Video::empty();+ let mut rgba = frame::Video::empty();+ let mut receive = |decoder: &mut ffmpeg::decoder::Video, shades: &mut Vec<u8>| {+ while decoder.receive_frame(&mut decoded).is_ok() {+ scaler.run(&decoded, &mut rgba).unwrap();+ shades.push(rgba.data(0)[0]);+ }+ };+ for (stream, packet) in input.packets() {+ if stream.index() == stream_index {+ decoder.send_packet(&packet).unwrap();+ receive(&mut decoder, &mut shades);+ }+ }+ decoder.send_eof().unwrap();+ receive(&mut decoder, &mut shades);+ shades+ }++ #[test]+ fn every_queued_frame_is_encoded_with_its_own_pixels() {+ ffmpeg::init().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("frames.mov");+ let info = VideoInfo::from_raw(RawVideoFormat::Rgba, WIDTH, HEIGHT, 30);+ let mut mov = MOVFile::init(path.clone(), |output| {+ ProResEncoder::builder(info).build(output)+ })+ .unwrap();++ let frame_count = 24;+ let mut source = frame::Video::new(format::Pixel::RGBA, WIDTH, HEIGHT);+ for index in 0..frame_count {+ let value = shade(index);+ source.data_mut(0).fill(value);+ for pixel in source.data_mut(0).chunks_exact_mut(4) {+ pixel[3] = 255;+ }+ mov.queue_video_frame(&mut source, Duration::from_secs_f64(index as f64 / 30.0))+ .unwrap();+ }+ mov.finish().unwrap();++ let shades = decoded_shades(&path);+ assert_eq!(shades.len(), frame_count);+ for (index, actual) in shades.into_iter().enumerate() {+ let expected = shade(index);+ assert!(+ actual.abs_diff(expected) <= 2,+ "frame {index} decoded as {actual}, expected {expected}"+ );+ }+ }+}diff --git a/crates/enc-ffmpeg/src/video/prores.rs b/crates/enc-ffmpeg/src/video/prores.rsindex f88ccb70c..bf74ba429 100644--- a/crates/enc-ffmpeg/src/video/prores.rs+++ b/crates/enc-ffmpeg/src/video/prores.rs@@ -5,7 +5,7 @@ use ffmpeg::{Dictionary,codec::{context, encoder},color, format, frame,- threading::Config,+ threading::{Config, Type},};use crate::base::EncoderBase;@@ -74,7 +74,18 @@ impl ProResEncoderBuilder {let thread_count = thread::available_parallelism().map(|v| v.get()).unwrap_or(1);- encoder_ctx.set_threading(Config::count(thread_count));+ // `Config::count` leaves `thread_type` at 0, which libavcodec treats as+ // "no threading" for prores_ks. Frame threading keeps a reference to each+ // sent frame until a worker encodes it, so it is only safe when frames+ // come from `converted_frames`, which never rewrites a frame the encoder+ // still holds.+ let mut threading = Config::kind(if converter.is_some() {+ Type::Frame+ } else {+ Type::None+ });+ threading.count = thread_count;+ encoder_ctx.set_threading(threading);let mut encoder = encoder_ctx.encoder().video()?;encoder.set_width(output_width);@@ -103,15 +114,13 @@ impl ProResEncoderBuilder {output_stream.set_rate(input_config.frame_rate);output_stream.set_parameters(&encoder);- let converted_frame_pool = converter- .as_ref()- .map(|_| frame::Video::new(output_format, output_width, output_height));-Ok(ProResEncoder {base: EncoderBase::new(stream_index),encoder,converter,- converted_frame_pool,+ converted_frames: Vec::new(),+ output_format,+ output_size: (output_width, output_height),})}}@@ -120,7 +129,9 @@ pub struct ProResEncoder {base: EncoderBase,encoder: encoder::Video,converter: Option<ffmpeg::software::scaling::Context>,- converted_frame_pool: Option<frame::Video>,+ converted_frames: Vec<frame::Video>,+ output_format: format::Pixel,+ output_size: (u32, u32),}#[derive(thiserror::Error, Debug)]@@ -148,23 +159,30 @@ impl ProResEncoder {) -> Result<(), QueueFrameError> {self.base.update_pts(frame, timestamp, &mut self.encoder);- let frame_to_send = if let Some(converter) = &mut self.converter {- let pts = frame.pts();- let converted = self.converted_frame_pool.as_mut().unwrap();- converter- .run(frame, converted)- .map_err(QueueFrameError::Converter)?;- converted.set_pts(pts);- converted as &frame::Video- } else {- frame as &frame::Video+ let Some(converter) = &mut self.converter else {+ return self+ .base+ .send_frame(frame, output, &mut self.encoder)+ .map_err(QueueFrameError::Encode);};- self.base- .send_frame(frame_to_send, output, &mut self.encoder)- .map_err(QueueFrameError::Encode)?;-- Ok(())+ let mut converted = match self.converted_frames.iter_mut().position(+ |pooled| unsafe { ffmpeg::ffi::av_frame_is_writable(pooled.as_mut_ptr()) } != 0,+ ) {+ Some(index) => self.converted_frames.swap_remove(index),+ None => frame::Video::new(self.output_format, self.output_size.0, self.output_size.1),+ };+ converter+ .run(frame, &mut converted)+ .map_err(QueueFrameError::Converter)?;+ converted.set_pts(frame.pts());++ let result = self+ .base+ .send_frame(&converted, output, &mut self.encoder)+ .map_err(QueueFrameError::Encode);+ self.converted_frames.push(converted);+ result}pub fn flush(&mut self, output: &mut format::context::Output) -> Result<(), ffmpeg::Error> {diff --git a/crates/export/examples/mov-export-benchmark.rs b/crates/export/examples/mov-export-benchmark.rsnew file mode 100644index 000000000..ee2235ed3--- /dev/null+++ b/crates/export/examples/mov-export-benchmark.rs@@ -0,0 +1,144 @@+use cap_export::{ExporterBase, mov::MovExportSettings};+use cap_project::XY;+use clap::Parser;+use std::{+ fs,+ path::Path,+ process::Command,+ time::{Duration, Instant},+};++#[derive(Parser)]+#[command(about = "Time ProRes 4444 MOV exports of a synthetic recording")]+struct Cli {+ #[arg(long, default_value = "1920")]+ width: u32,+ #[arg(long, default_value = "1080")]+ height: u32,+ #[arg(long, default_value = "30")]+ fps: u32,+ #[arg(long, default_value = "10")]+ duration: u32,+ #[arg(long, default_value = "5")]+ runs: usize,+}++fn generate_test_video(path: &Path, cli: &Cli) {+ let output = Command::new("ffmpeg")+ .args([+ "-y",+ "-f",+ "lavfi",+ "-i",+ &format!(+ "testsrc2=duration={}:size={}x{}:rate={}",+ cli.duration, cli.width, cli.height, cli.fps+ ),+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-pix_fmt",+ "yuv420p",+ path.to_str().unwrap(),+ ])+ .output()+ .expect("ffmpeg must be on PATH");+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+}++fn create_project(dir: &Path, cli: &Cli) {+ fs::create_dir_all(dir.join("content")).unwrap();+ let meta = serde_json::json!({+ "pretty_name": "MOV Export Benchmark",+ "sharing": null,+ "display": { "path": "content/display.mp4", "fps": cli.fps },+ "camera": null,+ "audio": null,+ "cursor": null+ });+ fs::write(dir.join("recording-meta.json"), meta.to_string()).unwrap();+ let config = serde_json::json!({+ "aspectRatio": null,+ "background": {+ "source": { "type": "color", "value": [30, 30, 46] },+ "blur": 0.0, "padding": 10.0, "rounding": 12.0, "inset": 0, "shadow": 50.0+ },+ "camera": { "hide": true, "mirror": false, "position": {}, "rounding": 100.0, "shadow": 40.0, "size": 30.0 },+ "audio": { "mute": true },+ "cursor": { "hideWhenIdle": false, "size": 100, "type": "pointer", "tension": 170.0, "mass": 1.0, "friction": 18.0, "raw": false },+ "hotkeys": { "show": true },+ "timeline": {+ "segments": [{ "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": cli.duration as f64 }],+ "zoomSegments": []+ }+ });+ fs::write(dir.join("project-config.json"), config.to_string()).unwrap();+ generate_test_video(&dir.join("content/display.mp4"), cli);+}++async fn export_once(dir: &Path, cli: &Cli) -> (Duration, u32, u64) {+ let base = ExporterBase::builder(dir.to_path_buf())+ .build()+ .await+ .expect("exporter base");+ let settings = MovExportSettings {+ fps: cli.fps,+ resolution_base: XY::new(cli.width, cli.height),+ cursor_only: false,+ };+ let frames = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));+ let counter = frames.clone();+ let start = Instant::now();+ let path = settings+ .export(base, move |_| {+ counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ true+ })+ .await+ .expect("mov export");+ let elapsed = start.elapsed();+ let bytes = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);+ if let Ok(keep) = std::env::var("MOV_BENCH_KEEP") {+ fs::copy(&path, keep).ok();+ }+ fs::remove_file(&path).ok();+ (+ elapsed,+ frames.load(std::sync::atomic::Ordering::Relaxed),+ bytes,+ )+}++#[tokio::main]+async fn main() {+ let cli = Cli::parse();+ let temp = tempfile::TempDir::new().unwrap();+ create_project(temp.path(), &cli);++ let mut fps_samples = Vec::with_capacity(cli.runs);+ for run in 0..cli.runs {+ let (elapsed, frames, bytes) = export_once(temp.path(), &cli).await;+ let fps = frames as f64 / elapsed.as_secs_f64();+ println!(+ "run={run} frames={frames} secs={:.3} fps={fps:.1} bytes={bytes}",+ elapsed.as_secs_f64()+ );+ fps_samples.push(fps);+ }+ fps_samples.sort_by(f64::total_cmp);+ println!(+ "mov_export {}x{}@{} duration={}s median_fps={:.1} min_fps={:.1} max_fps={:.1}",+ cli.width,+ cli.height,+ cli.fps,+ cli.duration,+ fps_samples[fps_samples.len() / 2],+ fps_samples[0],+ fps_samples[fps_samples.len() - 1]+ );+}