Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(export): stream MP4 audio through fullscreen title holds
Dheeraj45675b6c02799264
diff --git a/apps/desktop-gpui/examples/export-audio-memory-benchmark.md b/apps/desktop-gpui/examples/export-audio-memory-benchmark.mdnew file mode 100644index 000000000..d32f487d6--- /dev/null+++ b/apps/desktop-gpui/examples/export-audio-memory-benchmark.md@@ -0,0 +1,105 @@+# MP4 audio memory with fullscreen titles++Run the example on disposable project copies. Loading can migrate their config,+and exporting can refresh their thumbnail. It uses the same `build_for_mp4` and+`export_prepared` calls as GPUI, at 1080p/60 fps with Social compression.++```sh+cd apps/desktop-gpui+cargo +stable build --locked --example export-audio-memory-benchmark+target/debug/examples/export-audio-memory-benchmark /tmp/copy.cap /tmp/new-output.mp4 --hold+```++`--hold` adds a fullscreen title at output seconds 5–7 in memory. Omit it for+the control. `--prepare-only` stops after exporter preparation;+`--studio-sound` enables microphone enhancement. The output path must be unused.++## Fixtures++- **Official recording:** `reference-recording.cap` from+ [Cap's performance fixtures](https://github.com/CapSoftware/cap-performance-fixtures/tree/75c8ed2ed92da26685c3b3590644b54c2460e55e).+ Its two recorded takes total 30.818333 seconds. Download the full bundle,+ including cursor images and audio. The example adds the title, yielding+ 1,970 output frames. No source events or media are repeated.+- **Long voice source:** an assembled stress project using the first 15 seconds+ of the official recording's first display track and the original 27:50 mono+ MP3 of [LibriVox's *A Scandal in Bohemia*, read by Ruth Golding](https://archive.org/details/adventures_sherlock_holmes_rg_librivox).+ This is recorded speech in an assembled project, not an authentic long Cap+ capture. It tests retained audio outside a short edit. The title makes the+ output 17 seconds / 1,020 frames. There is no generated or repeated audio.++Create the second fixture from a downloaded official copy:++```sh+python3 - /tmp/reference-recording.cap /tmp/voice-title.cap <<'PY'+import json, shutil, sys, urllib.request+from pathlib import Path+source, target = map(Path, sys.argv[1:])+target.mkdir()+shutil.copy2(source / 'content/segments/segment-0/display.mp4', target / 'display.mp4')+name = 'adventuresholmes_01_doyle_64kb.mp3'+url = 'https://archive.org/download/adventures_sherlock_holmes_rg_librivox/' + name+with urllib.request.urlopen(url) as response, (target / name).open('wb') as output:+ shutil.copyfileobj(response, output)+meta = dict(pretty_name='Recorded voice title export test', platform='MacOS',+ segments=[dict(display=dict(path='display.mp4', fps=59), mic=dict(path=name))])+(target / 'recording-meta.json').write_text(json.dumps(meta))+config = json.loads((source / 'project-config.json').read_text())+config['timeline'] = dict(segments=[dict(recordingSegment=0, timescale=1, start=0, end=15)],+ zoomSegments=[])+config['clips'] = []+config['camera']['hide'] = True+config['audio']['improve'] = False+(target / 'project-config.json').write_text(json.dumps(config))+PY+```++MP3 SHA-256: `08dbdb62400d61e51ef3bc1cb6112306c5cf253821f5f295e2b0b698d35e70f2`.+The source is 13,366,784 bytes, 22,050 Hz mono, 1,670.635102 seconds.++## Comparison procedure++Build this identical example on base `db7ecfcf205446de4e9d4192deed698a4175450f`+and on the changed revision. Preserve both binaries before measurement. The+measurements below used the GPUI development profile: dependencies at opt-level+2, the example at opt-level 0, Rust stable 1.96, Apple M1 Pro, macOS 27.0.1.++For each fixture, run three pairs in before/after, after/before, before/after+order, each as a fresh process. Use a unique output per run, warm filesystem+caches, and no concurrent builds, tests or app runs. On macOS, set library paths+*after* `/usr/bin/time`, because protected system executables strip inherited+`DYLD_*` variables:++```sh+/usr/bin/time -l /usr/bin/env \+ DYLD_LIBRARY_PATH="$REPO/target/native-deps/Spacedrive.framework/Libraries:$REPO/target/native-deps/onnxruntime/lib" \+ ORT_DYLIB_PATH="$REPO/target/native-deps/onnxruntime/lib/libonnxruntime.dylib" \+ /tmp/benchmark-before /tmp/copy.cap /tmp/before-1.mp4 --hold+```++`build_ms` ends when exporter preparation completes; `total_ms` ends after+encoder completion and audio validation. Config loading is outside the timer.+Maximum RSS is the whole benchmark process, excluding external decoder services.++| Fixture | Prepare median, before → after | Complete export median | Peak RSS median |+| --- | --- | --- | --- |+| Official recording + title | 131.78 → 119.31 ms | 9.350 → 9.337 s | 158.48 → 144.50 MiB |+| Long recorded voice + title | 2187.92 → 35.71 ms | 7.063 → 6.957 s | 413.30 → 104.73 MiB |++This establishes a memory/preparation improvement, not a large full-export+speedup. Streaming still validates the complete audio source before success,+including unused tails, so that work has moved out of preparation rather than+disappeared. Short-clip timing changes are within normal run-to-run variation.++For all six pairs, compare decoded video and audio plus timestamps:++```sh+ffmpeg -v error -i /tmp/before-1.mp4 -map 0:v:0 -f framemd5 /tmp/before-video.md5+ffmpeg -v error -i /tmp/after-1.mp4 -map 0:v:0 -f framemd5 /tmp/after-video.md5+diff -u /tmp/before-video.md5 /tmp/after-video.md5+# Repeat with -map 0:a:0 for audio.+```++All six measured pairs matched, including frame sizes, sample counts and+timestamps. The native GPUI auto-export hook also completed an export of the+official fixture with the title, using an isolated `CAP_GPUI_APP_DATA_DIR`.diff --git a/apps/desktop-gpui/examples/export-audio-memory-benchmark.rs b/apps/desktop-gpui/examples/export-audio-memory-benchmark.rsnew file mode 100644index 000000000..29bffd172--- /dev/null+++ b/apps/desktop-gpui/examples/export-audio-memory-benchmark.rs@@ -0,0 +1,83 @@+use std::{+ path::PathBuf,+ sync::{Arc, atomic::AtomicBool},+ time::Instant,+};++use cap_export::{+ ExporterBase,+ mp4::{ExportCompression, Mp4ExportSettings},+};+use cap_project::{ProjectConfiguration, XY};++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ let mut args = std::env::args_os().skip(1);+ let project_path = args.next().map(PathBuf::from).ok_or_else(|| {+ anyhow::anyhow!("Usage: export-audio-memory-benchmark <copy.cap> <output.mp4> [--hold] [--prepare-only] [--studio-sound]")+ })?;+ let output_path = args+ .next()+ .map(PathBuf::from)+ .ok_or_else(|| anyhow::anyhow!("Pass an unused output path"))?;+ anyhow::ensure!(!output_path.exists(), "Output already exists");+ let mut config = ProjectConfiguration::load(&project_path).map_err(anyhow::Error::msg)?;+ let mut prepare_only = false;+ for arg in args {+ match arg.to_str() {+ Some("--hold") => {+ let timeline = config+ .timeline+ .as_mut()+ .ok_or_else(|| anyhow::anyhow!("The project needs a timeline"))?;+ anyhow::ensure!(+ timeline.duration() > 7.0,+ "The timeline must exceed seven seconds"+ );+ timeline+ .text_segments+ .push(serde_json::from_value(serde_json::json!({+ "start": 5.0, "end": 7.0, "content": "Next step", "layout": "fullscreen"+ }))?);+ }+ Some("--prepare-only") => prepare_only = true,+ Some("--studio-sound") => config.audio.improve = true,+ _ => anyhow::bail!("Unknown argument: {arg:?}"),+ }+ }+ let settings = Mp4ExportSettings {+ fps: 60,+ resolution_base: XY::new(1920, 1080),+ compression: ExportCompression::Social,+ custom_bpp: None,+ force_ffmpeg_decoder: false,+ optimize_filesize: false,+ };+ let started = Instant::now();+ let base = ExporterBase::builder(project_path)+ .with_config(config)+ .with_output_path(output_path)+ .build_for_mp4(Arc::new(AtomicBool::new(false)))+ .await+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;+ let build_ms = started.elapsed().as_secs_f64() * 1000.0;+ let streaming = base.uses_streaming_audio();+ let total_frames = base.total_frames(settings.fps);+ if !prepare_only {+ settings+ .export_prepared(base, |_| true)+ .await+ .map_err(anyhow::Error::msg)?;+ }+ println!(+ "{}",+ serde_json::json!({+ "streaming_audio": streaming,+ "prepare_only": prepare_only,+ "build_ms": build_ms,+ "total_ms": started.elapsed().as_secs_f64() * 1000.0,+ "total_frames": total_frames,+ })+ );+ Ok(())+}diff --git a/crates/editor/src/export_audio.rs b/crates/editor/src/export_audio.rsindex 8df5e4df7..0caaf0b59 100644--- a/crates/editor/src/export_audio.rs+++ b/crates/editor/src/export_audio.rs@@ -313,11 +313,21 @@ impl ExportAudioRenderer {let Some(timeline) = &project.timeline else {return true;};- if !timeline.audio_segments.is_empty() || !timeline.hold_windows().is_empty() {+ if !timeline.audio_segments.is_empty() {+ return false;+ }+ let holds = timeline.hold_windows();+ if holds+ .iter()+ .any(|(start, end)| !start.is_finite() || !end.is_finite() || *start < 0.0)+ {return false;}let mut ends = HashMap::new();- let mut duration = 0.0;+ let mut duration = holds.iter().map(|(start, end)| end - start).sum::<f64>();+ if !duration.is_finite() || duration * 48_000.0 >= isize::MAX as f64 / 2.0 {+ return false;+ }for segment in &timeline.segments {if segment.timescale != 1.0|| !segment.start.is_finite()@@ -1470,6 +1480,99 @@ mod tests {assert_bounded_sink_variants([19], &[1]);}+ #[test]+ fn fullscreen_holds_match_full_renderer_without_retaining_whole_tracks() {+ assert_bounded_sink_variants(26..32, &[1, 7, 997, 4_096, 48_001]);+ }++ #[test]+ fn streaming_eligibility_accepts_valid_fullscreen_holds() {+ let mut project = project();+ let hold = serde_json::from_value(serde_json::json!({+ "start": 0.1, "end": 0.2, "layout": "fullscreen"+ }))+ .unwrap();+ project.timeline.as_mut().unwrap().text_segments.push(hold);+ assert!(ExportAudioRenderer::eligible_sources(&project, 3));+ for (start, end) in [+ (f64::NEG_INFINITY, 0.2),+ (-1.0, 0.2),+ (0.1, f64::INFINITY),+ (0.1, f64::MAX),+ ] {+ let hold = &mut project.timeline.as_mut().unwrap().text_segments[0];+ hold.start = start;+ hold.end = end;+ assert!(+ !ExportAudioRenderer::eligible_sources(&project, 3),+ "{start}..{end}"+ );+ }+ }++ #[test]+ fn fullscreen_hold_emits_silence_without_reading_audio_and_cancels_between_blocks() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("source.wav");+ write_wav(&path, 48_000, 1);+ let data = Arc::new(AudioData::from_file(&path).unwrap());+ let (_, mut candidate) = fixture(+ &[path.clone(), path.clone(), path],+ &[data.clone(), data.clone(), data],+ );+ let mut project = project();+ project.timeline.as_mut().unwrap().text_segments.push(+ serde_json::from_value(serde_json::json!({+ "start": 0.0, "end": 1.0, "layout": "fullscreen"+ }))+ .unwrap(),+ );+ let mut samples = Vec::new();+ assert_eq!(+ candidate+ .render_chunks(4_096, &project, |_, block| {+ samples.extend_from_slice(block);+ Ok(())+ })+ .unwrap(),+ Some(4_096)+ );+ assert_eq!(samples, vec![0.0; 4_096 * 2]);+ assert!(+ candidate+ .sources+ .tracks+ .iter()+ .flatten()+ .all(|track| track.source.position() == 0)+ );++ let cancellation = candidate.sources.cancellation.clone();+ let mut blocks = 0;+ assert!(matches!(+ candidate.render_chunks(48_000, &project, |_, block| {+ assert!(block.iter().all(|sample| *sample == 0.0));+ blocks += 1;+ cancellation.store(true, Ordering::Relaxed);+ Ok(())+ }),+ Err(ExportAudioError::Cancelled)+ ));+ assert_eq!(blocks, 1);+ assert!(+ candidate+ .sources+ .tracks+ .iter()+ .flatten()+ .all(|track| track.source.position() == 0)+ );+ assert!(matches!(+ candidate.validate_to_end(),+ Err(ExportAudioError::Cancelled)+ ));+ }+fn assert_bounded_sink_variants(variants: impl IntoIterator<Item = usize>, requests: &[usize]) {ffmpeg::init().unwrap();let directory = tempfile::tempdir().unwrap();@@ -1570,6 +1673,34 @@ mod tests {});}}+ 26..=31 => {+ project.audio.improve = variant == 30;+ let timeline = project.timeline.as_mut().unwrap();+ let windows: &[(f64, f64)] = match variant {+ 26 => &[(0.0, 0.071_234_567)],+ 27 | 30 => &[(0.113_456_789, 0.224_567_891)],+ 28 => &[(0.1, 0.2), (0.15, 0.25), (0.25, 0.3)],+ 29 => &[(0.25, 0.4)],+ 31 => &[(0.0, 0.1), (0.4, 0.5), (0.816_98, 0.9)],+ _ => unreachable!(),+ };+ timeline.text_segments = windows+ .iter()+ .map(|&(start, end)| {+ serde_json::from_value(serde_json::json!({+ "start": start, "end": end, "layout": "fullscreen"+ }))+ .unwrap()+ })+ .collect();+ if variant == 29 {+ timeline.transitions.push(ClipTransition {+ segment_index: 1,+ kind: ClipTransitionType::CrossFade,+ duration: 0.131_234_567,+ });+ }+ }_ => unreachable!(),}for &request in requests {