Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve: desktop recording and editor responsiveness

Richie McIlroy2fca0fe936df
diff --git a/Cargo.lock b/Cargo.lock
index c395bf647..9197d0938 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1268,6 +1268,7 @@ dependencies = [
name = "cap-audio"
version = "0.1.0"
dependencies = [
+ "cap-enc-ffmpeg",
"cidre",
"cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=6013cb5f8bd3)",
"ffmpeg-next",
@@ -1560,6 +1561,7 @@ dependencies = [
"thiserror 1.0.69",
"tokio",
"tokio-stream",
+ "tokio-tungstenite",
"tokio-util",
"tracing",
"tracing-appender",
@@ -1584,6 +1586,7 @@ version = "0.1.0"
dependencies = [
"axum",
"cap-audio",
+ "cap-enc-ffmpeg",
"cap-media",
"cap-media-info",
"cap-project",
@@ -1593,6 +1596,7 @@ dependencies = [
"ffmpeg-next",
"flume",
"futures",
+ "image 0.25.8",
"lru",
"ringbuf",
"sentry",
@@ -1635,6 +1639,7 @@ dependencies = [
"tempfile",
"thiserror 1.0.69",
"tracing",
+ "windows 0.60.0",
"workspace-hack",
]
@@ -1926,7 +1931,9 @@ dependencies = [
"bytemuck",
"cap-camera-effects",
"cap-cursor-info",
+ "cap-enc-ffmpeg",
"cap-flags",
+ "cap-media-info",
"cap-project",
"cap-video-decode",
"cidre",
@@ -1950,6 +1957,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
+ "tempfile",
"thiserror 1.0.69",
"tiny-skia",
"tokio",
@@ -2054,10 +2062,14 @@ name = "cap-video-decode"
version = "0.1.0"
dependencies = [
"cap-d3d-adapter",
+ "cap-enc-ffmpeg",
+ "cap-media-info",
"cidre",
"ffmpeg-hw-device",
"ffmpeg-next",
"num_cpus",
+ "serde_json",
+ "sha2",
"tempfile",
"tokio",
"tracing",
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index d36888cc5..686399628 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1396,6 +1396,7 @@ dependencies = [
name = "cap-audio"
version = "0.1.0"
dependencies = [
+ "cap-enc-ffmpeg",
"cidre",
"cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=6013cb5f8bd3)",
"ffmpeg-next",
@@ -1538,6 +1539,7 @@ dependencies = [
"anyhow",
"ashpd 0.11.1",
"base64 0.22.1",
+ "cap-audio",
"cap-camera",
"cap-camera-effects",
"cap-cursor-info",
@@ -1619,6 +1621,7 @@ dependencies = [
"ringbuf",
"sentry",
"serde",
+ "serde_json",
"specta",
"tokio",
"tokio-util",
@@ -1654,6 +1657,7 @@ dependencies = [
"sysinfo 0.32.1",
"thiserror 1.0.69",
"tracing",
+ "windows 0.60.0",
"workspace-hack",
]
@@ -1909,6 +1913,7 @@ dependencies = [
"bytemuck",
"cap-camera-effects",
"cap-cursor-info",
+ "cap-enc-ffmpeg",
"cap-flags",
"cap-project",
"cap-video-decode",
@@ -1979,6 +1984,7 @@ name = "cap-video-decode"
version = "0.1.0"
dependencies = [
"cap-d3d-adapter",
+ "cap-enc-ffmpeg",
"cidre",
"ffmpeg-hw-device",
"ffmpeg-next",
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index 83aa68e18..b2411ea5a 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -18,6 +18,10 @@ publish = false
name = "cap-gpui"
path = "src/main.rs"
+[[example]]
+name = "studio-finalization-benchmark"
+path = "../../crates/recording/examples/studio-finalization-benchmark.rs"
+
[package.metadata.bundle]
name = "Cap GPUI"
identifier = "so.cap.desktop.gpui"
@@ -28,6 +32,7 @@ osx_info_plist_exts = ["resources/Info.plist"]
osx_url_schemes = ["cap-desktop"]
[dependencies]
+cap-audio = { path = "../../crates/audio" }
# gpui — the wingleeio/zed fork Comet ships. The pinned rev carries f596cde
# ("destination alpha on transparent windows: Porter-Duff OVER, not additive"),
# which our transparent rounded main-window shell depends on.
@@ -183,6 +188,7 @@ windows-sys = { version = "0.59", features = [
"Win32_Security",
"Win32_System_SystemInformation",
"Win32_System_Threading",
+ "Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
diff --git a/apps/desktop-gpui/dev.sh b/apps/desktop-gpui/dev.sh
index 8dff62512..cd92c3edd 100755
--- a/apps/desktop-gpui/dev.sh
+++ b/apps/desktop-gpui/dev.sh
@@ -4,17 +4,12 @@
# app persists its window state through CAP_GPUI_DEV_RESTORE and reopens where
# it was, and the swap waits out an in-flight recording (see dev_restore.rs).
set -uo pipefail
-cd "$(dirname "$0")"
+cd "$(dirname "$0")" || exit 1
STATE_FILE="$PWD/target/dev-restore.json"
BIN="$PWD/target/debug/cap-gpui"
BUILD=cargo
-# Cargo.toml turns incremental off to keep the dep tree's caches off a full
-# disk, but deps never rebuild in this loop -- the cache this creates is the
-# app crate's only, and it takes a warm rebuild from ~41s to 3-23s.
-export CARGO_INCREMENTAL=1
-
WATCH_PATHS=(src assets Cargo.toml)
[ -d resources ] && WATCH_PATHS+=(resources)
for crate in camera scap-targets recording timestamp utils project rendering editor export; do
@@ -84,7 +79,7 @@ while true; do
if [ "$CURRENT" != "$LAST" ]; then
LAST="$CURRENT"
echo "[dev] building..."
- if "$BUILD" build; then
+ if "$BUILD" build --config profile.dev.package.cap-desktop-gpui.incremental=true; then
if [ -n "$APP_PID" ] || gpui_owns_session || instance_live; then
stop_app
start_app
diff --git a/apps/desktop-gpui/examples/audio-readiness-benchmark.rs b/apps/desktop-gpui/examples/audio-readiness-benchmark.rs
new file mode 100644
index 000000000..e0fcf6231
--- /dev/null
+++ b/apps/desktop-gpui/examples/audio-readiness-benchmark.rs
@@ -0,0 +1,302 @@
+use std::{
+ path::PathBuf,
+ sync::{Arc, atomic::AtomicBool},
+ time::Instant,
+};
+
+use cap_audio::{AudioData, AudioStream, ChunkRead};
+use sha2::{Digest, Sha256};
+use tokio::sync::watch;
+
+fn main() -> anyhow::Result<()> {
+ let path = std::env::args_os()
+ .nth(1)
+ .map(PathBuf::from)
+ .ok_or_else(|| anyhow::anyhow!("Pass an audio path"))?;
+ if std::env::var_os("CAP_BENCH_PROGRESSIVE_AUDIO").is_some() {
+ return progressive_audio(path);
+ }
+ background_audio(path)
+}
+
+#[derive(Clone)]
+struct PreviousAudioLoader {
+ rx: watch::Receiver<Option<Result<Option<Arc<AudioData>>, String>>>,
+}
+
+impl PreviousAudioLoader {
+ fn spawn(path: PathBuf, label: String) -> Self {
+ let (tx, rx) = watch::channel(None);
+ tokio::task::spawn_blocking(move || {
+ let result = AudioData::from_file(&path)
+ .map(|data| Some(Arc::new(data)))
+ .map_err(|e| format!("{label} / {e}"));
+ let _ = tx.send(Some(result));
+ });
+ Self { rx }
+ }
+
+ async fn get(&self) -> Result<Option<Arc<AudioData>>, String> {
+ let mut rx = self.rx.clone();
+ loop {
+ if let Some(result) = rx.borrow_and_update().clone() {
+ return result;
+ }
+ if rx.changed().await.is_err() {
+ return Err("Audio load task was dropped".to_string());
+ }
+ }
+ }
+}
+
+fn background_audio(path: PathBuf) -> anyhow::Result<()> {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()?
+ .block_on(async move {
+ let started = Instant::now();
+ let loader = PreviousAudioLoader::spawn(path.clone(), "benchmark".into());
+ let full = loader
+ .get()
+ .await
+ .map_err(anyhow::Error::msg)?
+ .ok_or_else(|| anyhow::anyhow!("Missing decoded audio"))?;
+ let full_ms = started.elapsed().as_secs_f64() * 1000.0;
+ background_audio_report(path, full.as_ref(), full_ms)
+ })
+}
+
+fn background_audio_report(path: PathBuf, full: &AudioData, full_ms: f64) -> anyhow::Result<()> {
+ let full_hash = format!(
+ "{:x}",
+ Sha256::digest(unsafe { cap_audio::cast_f32_slice_to_bytes(full.samples()) })
+ );
+ let mix = mix_benchmark(full);
+ let channels = usize::from(full.channels());
+ let sample_frames = full.samples().len() / channels;
+ let window_frames = AudioData::SAMPLE_RATE as usize * 2;
+ let mut windows = Vec::new();
+ let mut matches_reference = true;
+ let streaming = if std::env::var_os("CAP_BENCH_STREAM_AUDIO").is_some() {
+ let started = Instant::now();
+ let mut stream = AudioStream::open(&path, Arc::new(AtomicBool::new(false)))?;
+ let open_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let mut decode_ms = open_ms;
+ let mut first_chunk_ms = None;
+ let mut next_sample = 0usize;
+ let mut maximum_chunk_bytes = 0usize;
+ let mut streamed_hash = Sha256::new();
+ loop {
+ let read_started = Instant::now();
+ let result = stream.read_chunk(12_000)?;
+ decode_ms += read_started.elapsed().as_secs_f64() * 1000.0;
+ match result {
+ ChunkRead::Chunk(chunk) => {
+ first_chunk_ms.get_or_insert(decode_ms);
+ anyhow::ensure!(chunk.channels == full.channels(), "Channel count changed");
+ anyhow::ensure!(
+ chunk.source_start_sample == (next_sample / channels) as u64,
+ "Noncontiguous audio chunk"
+ );
+ let end = next_sample + chunk.samples.len();
+ let reference = full.samples().get(next_sample..end).ok_or_else(|| {
+ anyhow::anyhow!("Streaming decode exceeded full-track length")
+ })?;
+ anyhow::ensure!(
+ chunk
+ .samples
+ .iter()
+ .zip(reference)
+ .all(|(actual, expected)| { actual.to_bits() == expected.to_bits() }),
+ "Streaming samples differ at source sample {next_sample}"
+ );
+ let bytes = unsafe { cap_audio::cast_f32_slice_to_bytes(&chunk.samples) };
+ maximum_chunk_bytes = maximum_chunk_bytes.max(bytes.len());
+ streamed_hash.update(bytes);
+ next_sample = end;
+ }
+ ChunkRead::Eof { next_sample: end } => {
+ anyhow::ensure!(end == sample_frames as u64, "Streaming EOF differs");
+ anyhow::ensure!(
+ next_sample == full.samples().len(),
+ "Streaming audio is short"
+ );
+ break;
+ }
+ }
+ }
+ Some(serde_json::json!({
+ "openMs": open_ms,
+ "firstChunkMs": first_chunk_ms,
+ "chunkDurationSeconds": 0.25,
+ "decodeMsExcludingComparison": decode_ms,
+ "maximumChunkBytes": maximum_chunk_bytes,
+ "samplesSha256": format!("{:x}", streamed_hash.finalize()),
+ "bitExact": true,
+ }))
+ } else {
+ None
+ };
+ for start in [
+ 0,
+ sample_frames / 2,
+ sample_frames.saturating_sub(window_frames),
+ ] {
+ if std::env::var_os("CAP_BENCH_FULL_AUDIO_ONLY").is_some() {
+ break;
+ }
+ let end = start.saturating_add(window_frames).min(sample_frames);
+ let started = Instant::now();
+ let range = AudioData::from_file_range(&path, start, end).map_err(anyhow::Error::msg)?;
+ let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let reference = &full.samples()[start * channels..end * channels];
+ let sample_count_matches = range.samples().len() == reference.len();
+ let maximum_difference = range
+ .samples()
+ .iter()
+ .zip(reference)
+ .map(|(actual, expected)| (actual - expected).abs())
+ .fold(0.0_f32, f32::max);
+ matches_reference &= sample_count_matches && maximum_difference <= 0.000_001;
+ windows.push(serde_json::json!({
+ "startSeconds": start as f64 / f64::from(AudioData::SAMPLE_RATE),
+ "elapsedMs": elapsed_ms,
+ "decodedBytes": std::mem::size_of_val(range.samples()),
+ "expectedSamples": reference.len(),
+ "actualSamples": range.samples().len(),
+ "sampleCountMatches": sample_count_matches,
+ "maximumSampleDifference": maximum_difference,
+ }));
+ }
+ println!(
+ "{}",
+ serde_json::json!({
+ "path": path,
+ "mode": "background-baseline",
+ "baselineMode": "spawn-blocking-watch-arc",
+ "methodology": methodology(),
+ "fullDecodeMs": full_ms,
+ "fullDecodedBytes": std::mem::size_of_val(full.samples()),
+ "fullSamplesSha256": full_hash,
+ "durationSeconds": sample_frames as f64 / f64::from(AudioData::SAMPLE_RATE),
+ "channels": full.channels(),
+ "sampleFrames": sample_frames,
+ "windows": windows,
+ "streaming": streaming,
+ "mix": mix,
+ })
+ );
+ anyhow::ensure!(
+ matches_reference,
+ "Window decoding differs from full-track decoding"
+ );
+ Ok(())
+}
+
+fn progressive_audio(path: PathBuf) -> anyhow::Result<()> {
+ use cap_audio::AudioSampleSource;
+
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()?
+ .block_on(async move {
+ let started = Instant::now();
+ let loader = cap_audio::ProgressiveAudio::spawn(path.clone(), "benchmark".into());
+ let window = loader
+ .window(0..12_000)
+ .await
+ .map_err(anyhow::Error::msg)?
+ .ok_or_else(|| anyhow::anyhow!("Missing decoded audio"))?;
+ let first_window_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let progress = loader.progress();
+ let audio = loader
+ .get()
+ .await
+ .map_err(anyhow::Error::msg)?
+ .ok_or_else(|| anyhow::anyhow!("Missing decoded audio"))?;
+ let full_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let mut first_hash = Sha256::new();
+ for index in 0..12_000.min(window.sample_count()) * usize::from(window.channels()) {
+ first_hash.update(window.sample(index).unwrap().to_le_bytes());
+ }
+ let mut hash = Sha256::new();
+ let mut decoded_bytes = 0;
+ for samples in audio.sample_slices() {
+ decoded_bytes += std::mem::size_of_val(samples);
+ hash.update(unsafe { cap_audio::cast_f32_slice_to_bytes(samples) });
+ }
+ println!(
+ "{}",
+ serde_json::json!({
+ "path": path,
+ "mode": "progressive",
+ "methodology": methodology(),
+ "firstWindowMs": first_window_ms,
+ "readyFramesAtFirstWindow": progress.ready_frames,
+ "completeAtFirstWindow": progress.complete,
+ "fullDecodedAudioMs": full_ms,
+ "fullDecodedBytes": decoded_bytes,
+ "channels": audio.channels(),
+ "sampleFrames": audio.sample_count(),
+ "decodedSha256": format!("{:x}", hash.finalize()),
+ "firstWindowSha256": format!("{:x}", first_hash.finalize()),
+ "mix": mix_benchmark(audio.as_ref()),
+ })
+ );
+ Ok(())
+ })
+}
+
+fn methodology() -> serde_json::Value {
+ serde_json::json!({
+ "runtime": "tokio-current-thread",
+ "decodeExecution": "spawn-blocking",
+ "fullDecodeTimer": "before-loader-spawn-through-completed-get",
+ "runtimeSetupIncluded": false,
+ "hashingIncluded": false,
+ "mixingIncluded": false,
+ "renderer": "current-cap-audio",
+ "mixTiming": "after-full-pcm-hash-before-stream-or-range-diagnostics",
+ })
+}
+
+fn mix_benchmark(audio: &impl cap_audio::AudioSampleSource) -> Option<serde_json::Value> {
+ if std::env::var_os("CAP_BENCH_MIX_AUDIO").is_none() || audio.sample_count() < 48_000 {
+ return None;
+ }
+ let tracks = [cap_audio::AudioRendererTrack {
+ data: audio,
+ gain: -4.0,
+ stereo_mode: cap_audio::StereoMode::Stereo,
+ offset: 0,
+ }];
+ let mut output = vec![0.0_f32; 48_000 * 2 * 3];
+ let started = Instant::now();
+ for _ in 0..20 {
+ for (range, start) in [0, audio.sample_count() / 2, audio.sample_count() - 48_000]
+ .into_iter()
+ .enumerate()
+ {
+ for offset in (0..48_000).step_by(1_024) {
+ let count = 1_024.min(48_000 - offset);
+ let written = cap_audio::render_audio(
+ &tracks,
+ start + offset,
+ count,
+ (range * 48_000 + offset) * 2,
+ &mut output,
+ );
+ assert_eq!(written, count);
+ }
+ }
+ std::hint::black_box(output.as_slice());
+ }
+ let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
+ Some(serde_json::json!({
+ "elapsedMs": elapsed_ms,
+ "renderedSeconds": 60,
+ "repetitions": 20,
+ "outputBarrier": "after-each-repetition",
+ "sha256": format!("{:x}", Sha256::digest(unsafe { cap_audio::cast_f32_slice_to_bytes(&output) })),
+ }))
+}
diff --git a/apps/desktop-gpui/examples/media-readiness-benchmark.rs b/apps/desktop-gpui/examples/media-readiness-benchmark.rs
new file mode 100644
index 000000000..ee496e455
--- /dev/null
+++ b/apps/desktop-gpui/examples/media-readiness-benchmark.rs
@@ -0,0 +1,71 @@
+use std::{path::PathBuf, time::Instant};
+
+use cap_rendering::{Video, decoder::spawn_decoder};
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ tracing_subscriber::fmt()
+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
+ .with_writer(std::io::stderr)
+ .init();
+ let mut arguments = std::env::args_os().skip(1);
+ let path = arguments
+ .next()
+ .map(PathBuf::from)
+ .ok_or_else(|| anyhow::anyhow!("Pass a video path and optional audio path"))?;
+ let audio_path = arguments.next().map(PathBuf::from);
+ let force_ffmpeg = std::env::var_os("CAP_BENCH_FORCE_FFMPEG").is_some();
+ let started = Instant::now();
+ let video = Video::new(&path, 0.0).map_err(anyhow::Error::msg)?;
+ let probe_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let decoder = spawn_decoder(
+ "readiness-benchmark",
+ path.clone(),
+ video.fps,
+ 0.0,
+ force_ffmpeg,
+ )
+ .await
+ .map_err(anyhow::Error::msg)?;
+ let initialized_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let mut frames = Vec::new();
+ for time in [0.0, video.duration * 0.5, video.duration - 1.0, 1.0] {
+ let requested = Instant::now();
+ let frame = decoder
+ .get_frame_initial(time.max(0.0) as f32)
+ .await
+ .ok_or_else(|| anyhow::anyhow!("No frame at {time}"))?;
+ frames.push(serde_json::json!({
+ "timeSeconds": time,
+ "elapsedMs": requested.elapsed().as_secs_f64() * 1000.0,
+ "sinceOpenMs": started.elapsed().as_secs_f64() * 1000.0,
+ "width": frame.width(),
+ "height": frame.height(),
+ }));
+ }
+ let audio_ms = if let Some(audio_path) = audio_path {
+ let started = Instant::now();
+ cap_editor::AudioLoader::spawn(audio_path, "readiness-benchmark".into())
+ .get()
+ .await
+ .map_err(anyhow::Error::msg)?
+ .ok_or_else(|| anyhow::anyhow!("No decoded audio"))?;
+ Some(started.elapsed().as_secs_f64() * 1000.0)
+ } else {
+ None
+ };
+ println!(
+ "{}",
+ serde_json::json!({
+ "path": path,
+ "durationSeconds": video.duration,
+ "probeMs": probe_ms,
+ "initializedMs": initialized_ms,
+ "decoder": decoder.decoder_type().to_string(),
+ "fallbackReason": decoder.fallback_reason(),
+ "frames": frames,
+ "audioReadyMs": audio_ms,
+ })
+ );
+ Ok(())
+}
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index 5665a04bc..fc8067b1b 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -29,9 +29,9 @@ use crate::{
mode_select_window::{self, ModeSelectWindow},
onboarding_window::{self, OnboardingWindow},
platform,
- recording::{RecordingMode, StartConfig},
+ recording::{RecordingMode, StartConfig, StudioFinalization},
screenshot_editor::{self, ScreenshotEditorWindow},
- session::{Phase, RecordingSession},
+ session::{Phase, RecordingSession, StudioEditorPresentation},
settings_window::{self, Page, SettingsWindow},
target_overlay::{AreaRect, HoveredWindow, OverlayWindow, TargetSelect},
teleprompter_window::{self, TeleprompterWindow},
@@ -206,6 +206,7 @@ pub struct AppWindows {
/// incrementing id; the path is the identity in both.
pub editors: Vec<(PathBuf, WindowHandle<EditorWindow>)>,
deleting_editors: HashSet<PathBuf>,
+ preparing_cleanup: crate::editor_preparing::PreparingCleanupRegistry,
/// One screenshot editor per `.cap` bundle -- the gpui spelling of
/// `ScreenshotEditorWindowIds`, keyed by the bundle directory.
pub screenshot_editors: Vec<(PathBuf, WindowHandle<ScreenshotEditorWindow>)>,
@@ -486,6 +487,7 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
overlays: Vec::new(),
editors: Vec::new(),
deleting_editors: HashSet::new(),
+ preparing_cleanup: crate::editor_preparing::PreparingCleanupRegistry::default(),
screenshot_editors: Vec::new(),
main_hidden_for_picker: false,
editor_hidden_for_picker: None,
@@ -521,6 +523,9 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
// status item becomes a stop button while a capture runs.
crate::tray::set_recording(recording, cx);
}
+ if phase == Phase::Stopping {
+ open_preparing_studio_editor(&session, cx);
+ }
if phase == Phase::Idle && last_phase != Phase::Idle {
#[cfg(target_os = "linux")]
if !session.read(cx).instant_cleanup_safe() {
@@ -532,7 +537,12 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
if !restore_clean_capture_ui(cx) {
return;
}
- let finished_studio = session.update(cx, |session, _| session.finished_studio.take());
+ let (finished_studio, preparing_editor) = session.update(cx, |session, _| {
+ (
+ session.finished_studio.take(),
+ session.take_preparing_studio_editor(),
+ )
+ });
// The in-editor re-record target is consumed first, before
// `postStudioRecordingBehaviour` is even consulted -- the order
// `apply_post_studio_editor_behaviour` checks them
@@ -549,6 +559,20 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
session.update(cx, |session, _| session.take_editor_recording_target());
if let Some(editor_path) = editor_target {
editor_recording_finished(editor_path, finished_studio, cx);
+ } else if let Some(preparing) =
+ preparing_editor.filter(|pending| pending.presentation.suppresses_completion_open())
+ {
+ let key = editor_key(&preparing.project_path);
+ if !cx
+ .global::<AppWindows>()
+ .editors
+ .iter()
+ .any(|(path, _)| path == &key)
+ {
+ restore_after_editor_close(&key, cx);
+ } else {
+ park_idle_camera_preview(cx);
+ }
} else {
// `postStudioRecordingBehaviour` (`openEditor` is the
// default): a cleanly-stopped studio recording goes straight
@@ -593,6 +617,40 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
crate::deeplink::init(cx);
}
+fn open_preparing_studio_editor(session: &Entity<RecordingSession>, cx: &mut App) {
+ let Some(pending) = session.read(cx).preparing_studio_editor().cloned() else {
+ return;
+ };
+ if !pending.capture_stopped
+ || pending.presentation != StudioEditorPresentation::Pending
+ || !pending.finalization.is_finalizing()
+ || crate::store::GeneralSettings::load().post_studio_recording_behaviour
+ != crate::store::PostStudioBehaviour::OpenEditor
+ {
+ return;
+ }
+ #[cfg(target_os = "linux")]
+ if !restore_clean_capture_ui(cx) {
+ return;
+ }
+ session.update(cx, |session, _| {
+ if let Some(current) = session.preparing_studio_editor_mut() {
+ current.presentation = StudioEditorPresentation::Attempted;
+ }
+ });
+ open_editor(pending.project_path, cx);
+ if session
+ .read(cx)
+ .preparing_studio_editor()
+ .is_some_and(|pending| matches!(pending.presentation, StudioEditorPresentation::Opened(_)))
+ {
+ close_controls(session, cx);
+ close_target_overlays(cx);
+ close_camera_window(cx);
+ restore_content_protection(cx);
+ }
+}
+
/// `createThemeListener` + `commands.setTheme`: persist is already done; this
/// forces native appearance on every open window and invalidates so each
/// `sync_appearance` rebuilds the palette.
@@ -875,7 +933,10 @@ pub fn hide_main_window(cx: &mut App) {
fn hide_main_and_park_camera_preview(cx: &mut App) {
hide_main_window(cx);
+ park_idle_camera_preview(cx);
+}
+fn park_idle_camera_preview(cx: &mut App) {
if !camera_preview_can_be_parked(RecordingSession::global(cx).read(cx).phase) {
return;
}
@@ -2579,6 +2640,7 @@ fn own_windows(cx: &mut App) -> Vec<OwnWindowHandle> {
overlays,
editors,
deleting_editors: _,
+ preparing_cleanup: _,
screenshot_editors,
main_hidden_for_picker: _,
editor_hidden_for_picker: _,
@@ -4495,21 +4557,52 @@ fn editor_key(path: &Path) -> PathBuf {
/// Must be reached through `cx.defer` from anything inside an entity update:
/// opening a window paints it synchronously and would double-lease the caller.
pub fn open_editor(project_path: PathBuf, cx: &mut App) {
+ let key = editor_key(&project_path);
+ let session = RecordingSession::global(cx);
+ let preparing = session
+ .read(cx)
+ .preparing_studio_editor()
+ .filter(|pending| editor_key(&pending.project_path) == key)
+ .cloned();
+ if preparing
+ .as_ref()
+ .is_some_and(|pending| !pending.capture_stopped)
+ {
+ return;
+ }
+ let finalization = preparing.map(|pending| pending.finalization);
+ if let Some(window_id) = open_editor_window(project_path, finalization, cx) {
+ session.update(cx, |session, _| {
+ if let Some(pending) = session.preparing_studio_editor_mut()
+ && editor_key(&pending.project_path) == key
+ {
+ pending.presentation = StudioEditorPresentation::Opened(window_id);
+ }
+ });
+ }
+}
+
+fn open_editor_window(
+ project_path: PathBuf,
+ finalization: Option<StudioFinalization>,
+ cx: &mut App,
+) -> Option<gpui::WindowId> {
#[cfg(target_os = "linux")]
if defer_window_until_capture_safe(cx) {
- return;
+ return None;
}
let key = editor_key(&project_path);
if cx.global::<AppWindows>().deleting_editors.contains(&key) {
tracing::info!(path = %key.display(), "recording deletion is still settling; editor remains closed");
- return;
+ return None;
}
- if cx
+ if let Some(window_id) = cx
.global::<AppWindows>()
.editors
.iter()
- .any(|(path, _)| path == &key)
+ .find(|(path, _)| path == &key)
+ .map(|(_, handle)| handle.window_id())
{
tracing::info!(
path = %key.display(),
@@ -4517,7 +4610,7 @@ pub fn open_editor(project_path: PathBuf, cx: &mut App) {
);
hide_main_and_park_camera_preview(cx);
reveal_editor_window(&key, cx);
- return;
+ return Some(window_id);
}
let bounds = opening_window_bounds(
@@ -4571,7 +4664,7 @@ pub fn open_editor(project_path: PathBuf, cx: &mut App) {
Ok(handle) => handle,
Err(error) => {
tracing::error!("editor window failed to open: {error:#}");
- return;
+ return None;
}
};
@@ -4595,7 +4688,137 @@ pub fn open_editor(project_path: PathBuf, cx: &mut App) {
hide_main_and_park_camera_preview(cx);
reveal_editor_window(&key, cx);
- load_editor_project(key, handle, cx);
+ if finalization.is_some() {
+ tracing::info!(path = %key.display(), "preparing editor shell created");
+ let frame_path = key.clone();
+ handle.update(cx, |_, window, _| {
+ window.on_next_frame(move |window, _| {
+ window.on_next_frame(move |_, _| {
+ tracing::info!(path = %frame_path.display(), "preparing editor first frame cycle completed");
+ });
+ });
+ window.refresh();
+ }).ok();
+ }
+ load_editor_project(key, handle, finalization, cx);
+ Some(handle.window_id())
+}
+
+fn editor_audio_output() -> Arc<cap_editor::AudioOutput> {
+ if std::env::var("CAP_GPUI_MUTE_AUDIO").is_ok_and(|value| value == "1") {
+ Arc::new(cap_editor::AudioOutput::new_headless(Box::new(|_, _| {})))
+ } else {
+ Arc::new(cap_editor::AudioOutput::new())
+ }
+}
+
+fn start_preparing_editor(
+ path: PathBuf,
+ handle: WindowHandle<EditorWindow>,
+ finalization: StudioFinalization,
+ audio_output: Arc<cap_editor::AudioOutput>,
+ cx: &mut App,
+) -> crate::editor_preparing::PreparingJoin {
+ let resolution = editor_window::preview_resolution(
+ crate::store::GeneralSettings::load().editor_preview_quality,
+ );
+ let (consumer, joined, frames) = crate::editor_preparing::spawn(
+ finalization,
+ resolution,
+ audio_output,
+ &gpui_tokio::Tokio::handle(cx),
+ );
+ cx.global_mut::<AppWindows>()
+ .preparing_cleanup
+ .register(path.clone(), joined.clone());
+ let mut updates = consumer.updates();
+ handle
+ .update(cx, |view, window, cx| {
+ view.begin_preparing(consumer);
+ cx.notify();
+ window.refresh();
+ })
+ .ok();
+ cx.spawn({
+ let path = path.clone();
+ async move |cx| {
+ loop {
+ let update = updates.borrow_and_update().clone();
+ if let Some(update) = update {
+ let current_window = cx.update(|cx| {
+ cx.global::<AppWindows>()
+ .editors
+ .iter()
+ .any(|(key, current)| {
+ key == &path && current.window_id() == handle.window_id()
+ })
+ });
+ if !current_window
+ || handle
+ .update(cx, |view, window, cx| {
+ view.preparing_progress_arrived(update, window, cx)
+ })
+ .is_err()
+ {
+ return;
+ }
+ }
+ if updates.changed().await.is_err() {
+ return;
+ }
+ }
+ }
+ })
+ .detach();
+ cx.spawn(async move |cx| {
+ while let Ok(preparing) = frames.recv_async().await {
+ let frame = match preparing.output {
+ cap_editor::EditorFrameOutput::Rgba(frame) => {
+ let image = cx
+ .background_executor()
+ .spawn(async move { editor_window::frame_image(&frame) })
+ .await;
+ let Some(image) = image else { continue };
+ editor_window::EditorPreviewFrame::Image(image)
+ }
+ #[cfg(target_os = "macos")]
+ cap_editor::EditorFrameOutput::Surface(surface) => {
+ editor_window::surface_preview_frame(surface)
+ }
+ cap_editor::EditorFrameOutput::Nv12(_) => continue,
+ };
+ let current_window = cx.update(|cx| {
+ cx.global::<AppWindows>()
+ .editors
+ .iter()
+ .any(|(key, current)| key == &path && current.window_id() == handle.window_id())
+ });
+ if !current_window {
+ return;
+ }
+ if handle
+ .update(cx, |view, window, cx| {
+ view.preparing_frame_arrived(
+ &preparing.epoch,
+ &preparing.identity,
+ preparing.request.sequence,
+ editor_window::EditorFrame {
+ frame,
+ layout: preparing.layout,
+ number: preparing.request.frame_number,
+ },
+ window,
+ cx,
+ );
+ })
+ .is_err()
+ {
+ return;
+ }
+ }
+ })
+ .detach();
+ joined
}
/// Build the `EditorInstance` and get frame 0 on screen.
@@ -4605,8 +4828,119 @@ pub fn open_editor(project_path: PathBuf, cx: &mut App) {
/// preview renderer, all of which are tokio-spawned -- is constructed on the
/// `gpui_tokio` runtime. `EditorInstance::new` on the main thread would block
/// it for however long the first segment takes to open.
-fn load_editor_project(path: PathBuf, handle: WindowHandle<EditorWindow>, cx: &mut App) {
+fn load_editor_project(
+ path: PathBuf,
+ handle: WindowHandle<EditorWindow>,
+ finalization: Option<StudioFinalization>,
+ cx: &mut App,
+) {
+ load_editor_project_candidate(path, handle, finalization, None, cx);
+}
+
+pub(crate) fn retry_preparing_editor(
+ path: PathBuf,
+ handle: WindowHandle<EditorWindow>,
+ previous: Arc<cap_editor::EditorInstance>,
+ cx: &mut App,
+) {
+ load_editor_project_candidate(path, handle, None, Some(previous), cx);
+}
+
+fn load_editor_project_candidate(
+ path: PathBuf,
+ handle: WindowHandle<EditorWindow>,
+ finalization: Option<StudioFinalization>,
+ previous: Option<Arc<cap_editor::EditorInstance>>,
+ cx: &mut App,
+) {
+ let preparing_output = finalization.as_ref().map(|_| editor_audio_output());
+ let current_join =
+ finalization
+ .as_ref()
+ .zip(preparing_output.as_ref())
+ .map(|(finalization, output)| {
+ start_preparing_editor(
+ path.clone(),
+ handle,
+ finalization.clone(),
+ output.clone(),
+ cx,
+ )
+ });
+ let continuing_join = current_join.clone();
+ let mut preparing_joins = if previous.is_some() {
+ Vec::new()
+ } else {
+ cx.global_mut::<AppWindows>()
+ .preparing_cleanup
+ .pending(&path)
+ };
+ if let Some(joined) = current_join
+ && !preparing_joins.iter().any(|pending| pending.same(&joined))
+ {
+ preparing_joins.push(joined);
+ }
cx.spawn(async move |cx| {
+ let finalized = match finalization {
+ Some(finalization) => finalization.wait().await,
+ None => Ok(()),
+ };
+ let mut completed_audio = None;
+ let mut live_handoff = None;
+ for joined in &preparing_joins {
+ if finalized.is_ok()
+ && continuing_join
+ .as_ref()
+ .is_some_and(|current| current.same(joined))
+ && let Some(handoff) = joined.continuing_handoff().await
+ {
+ match handoff.take_completed_audio().await {
+ Ok(audio) => {
+ completed_audio = Some(audio);
+ live_handoff = Some(handoff);
+ continue;
+ }
+ Err(_) => {
+ handoff.cancel();
+ }
+ }
+ }
+ let completed = match joined.wait().await {
+ Ok(completed) => completed,
+ Err(message) => {
+ handle
+ .update(cx, |view, window, cx| view.set_error(message, window, cx))
+ .ok();
+ return;
+ }
+ };
+ let audio = completed.take_audio();
+ let accepted = handle
+ .update(cx, |view, window, cx| {
+ let accepted = view.finish_preparing(&completed);
+ cx.notify();
+ window.refresh();
+ accepted
+ })
+ .unwrap_or(false);
+ if accepted && finalized.is_ok() {
+ completed_audio = audio;
+ }
+ }
+ cx.update(|cx| {
+ cx.global_mut::<AppWindows>()
+ .preparing_cleanup
+ .prune_completed()
+ });
+ if let Err(message) = finalized {
+ handle
+ .update(cx, |view, window, cx| view.set_error(message, window, cx))
+ .ok();
+ return;
+ }
+ if handle.update(cx, |_, _, _| ()).is_err() {
+ return;
+ }
let preflight_path = path.clone();
let summary = cx
.background_executor()
@@ -4671,23 +5005,28 @@ fn load_editor_project(path: PathBuf, handle: WindowHandle<EditorWindow>, cx: &m
let frame_format = cap_editor::EditorFrameFormat::BgraSurface;
#[cfg(not(target_os = "macos"))]
let frame_format = cap_editor::EditorFrameFormat::Rgba;
- let audio_output = if std::env::var("CAP_GPUI_MUTE_AUDIO").is_ok_and(|v| v == "1") {
- std::sync::Arc::new(cap_editor::AudioOutput::new_headless(Box::new(
- |_samples, _at| {},
- )))
- } else {
- std::sync::Arc::new(cap_editor::AudioOutput::new())
- };
- cap_editor::EditorInstance::new_with_preloaded_recordings(
+ if let Some(previous) = previous {
+ return previous
+ .recreate_preparing_candidate(state_cb, frame_cb, frame_format)
+ .await;
+ }
+ let instance = cap_editor::EditorInstance::new_with_startup_inputs(
instance_path,
state_cb,
frame_cb,
None,
frame_format,
- audio_output,
- recordings,
+ preparing_output.unwrap_or_else(editor_audio_output),
+ cap_editor::EditorStartupInputs {
+ recordings: Some(recordings),
+ completed_audio,
+ },
)
- .await
+ .await?;
+ if let Some(handoff) = live_handoff {
+ instance.install_preparing_handoff(&handoff).await?;
+ }
+ Ok::<_, String>(instance)
})
});
@@ -4753,6 +5092,7 @@ fn load_editor_project(path: PathBuf, handle: WindowHandle<EditorWindow>, cx: &m
// BGRA swap is a few megabytes per frame), deliver on the main one.
cx.spawn({
let stats = stats.clone();
+ let pump_instance = instance.clone();
async move |cx| {
while let Ok((output, layout)) = frame_rx.recv_async().await {
let (frame, number) = match output {
@@ -4788,6 +5128,9 @@ fn load_editor_project(path: PathBuf, handle: WindowHandle<EditorWindow>, cx: &m
};
if handle
.update(cx, |view, window, cx| {
+ if !view.is_instance(&pump_instance) {
+ return;
+ }
view.frame_arrived(
editor_window::EditorFrame {
frame,
@@ -4810,12 +5153,15 @@ fn load_editor_project(path: PathBuf, handle: WindowHandle<EditorWindow>, cx: &m
// The playhead drain. The signal is latest-wins, so this reads the
// atomic rather than a queue: at 60Hz a backlog would only ever
// describe the past.
+ let playhead_instance = instance.clone();
cx.spawn(async move |cx| {
while playhead_rx.recv_async().await.is_ok() {
let frame = playhead.position();
if handle
.update(cx, |view, window, cx| {
- view.playhead_changed(frame, window, cx)
+ if view.is_instance(&playhead_instance) {
+ view.playhead_changed(frame, window, cx);
+ }
})
.is_err()
{
@@ -4840,10 +5186,15 @@ fn load_editor_project(path: PathBuf, handle: WindowHandle<EditorWindow>, cx: &m
// The engine-stop drain: the driver's message that the engine died on
// its own (end of timeline under a live seek, warmup abort, error),
// delivered on the main thread like every other foreign-thread seam.
+ let stopped_instance = instance.clone();
cx.spawn(async move |cx| {
while engine_stopped_rx.recv_async().await.is_ok() {
if handle
- .update(cx, |view, window, cx| view.engine_stopped(window, cx))
+ .update(cx, |view, window, cx| {
+ if view.is_instance(&stopped_instance) {
+ view.engine_stopped(window, cx);
+ }
+ })
.is_err()
{
return;
@@ -4863,17 +5214,6 @@ fn load_editor_project(path: PathBuf, handle: WindowHandle<EditorWindow>, cx: &m
return;
}
- // The initial kick, exactly as `lib.rs:6617-6618` does it after
- // creating an instance. Without this the canvas stays black: `seek_to`
- // and `set_playhead_position` render nothing.
- editor_window::request_frame(
- &instance,
- 0,
- editor_window::preview_resolution(
- crate::store::GeneralSettings::load().editor_preview_quality,
- ),
- );
-
drive_auto_sidebar(handle, cx).await;
drive_auto_playback(path, handle, cx).await;
drive_auto_export(handle, cx).await;
@@ -4978,7 +5318,7 @@ fn load_editor_waveforms(
.map(|audio| {
Arc::new(match audio {
Some(audio) => editor_timeline::waveform_peaks(
- audio.samples(),
+ audio.sample_slices().flatten(),
audio.channels(),
),
None => Vec::new(),
@@ -5082,6 +5422,10 @@ async fn drive_auto_playback(
let seek = std::env::var("CAP_GPUI_AUTO_SEEK")
.ok()
.and_then(|value| value.parse::<f64>().ok());
+ let seek_time = std::env::var("CAP_GPUI_AUTO_SEEK_TIME")
+ .ok()
+ .and_then(|value| value.parse::<f64>().ok())
+ .filter(|seconds| seconds.is_finite() && *seconds >= 0.0);
// `CAP_GPUI_AUTO_SCRUB_PLAYING=<n>`: a synthetic ruler drag during
// playback -- n seeks at 33ms intervals sweeping 20% to 70% of the
// timeline. This is the live-seek path's perf gate: every seek lands on a
@@ -5089,7 +5433,12 @@ async fn drive_auto_playback(
let scrub_playing = std::env::var("CAP_GPUI_AUTO_SCRUB_PLAYING")
.ok()
.and_then(|value| value.parse::<u32>().ok());
- if play_secs.is_none() && torture.is_none() && seek.is_none() && scrub_playing.is_none() {
+ if play_secs.is_none()
+ && torture.is_none()
+ && seek.is_none()
+ && seek_time.is_none()
+ && scrub_playing.is_none()
+ {
return;
}
@@ -5144,6 +5493,16 @@ async fn drive_auto_playback(
tracing::info!(fraction, "auto seek");
}
+ if let Some(seconds) = seek_time {
+ handle
+ .update(cx, |view, _window, cx| {
+ let seconds = seconds.min(view.total_duration());
+ view.seek_to_time(seconds, cx);
+ tracing::info!(seconds, "auto seek to recording time");
+ })
+ .ok();
+ }
+
if let Some(n) = scrub_playing {
if handle
.update(cx, |view, window, cx| view.toggle_play(window, cx))
@@ -5261,6 +5620,34 @@ pub fn editor_closed(project_path: &Path, window_id: gpui::WindowId, cx: &mut Ap
return;
};
+ RecordingSession::global(cx).update(cx, |session, _| {
+ if let Some(pending) = session.preparing_studio_editor_mut()
+ && editor_key(&pending.project_path) == key
+ {
+ pending.presentation.closed(window_id);
+ }
+ });
+
+ handle.update(cx, |view, _, _| view.cancel_preparing()).ok();
+ let preparing_joins = cx
+ .global_mut::<AppWindows>()
+ .preparing_cleanup
+ .pending(&key);
+ cx.spawn(async move |cx| {
+ for joined in preparing_joins {
+ if let Err(error) = joined.wait().await {
+ tracing::warn!(%error, "Closed preparing editor cleanup failed");
+ return;
+ }
+ }
+ cx.update(|cx| {
+ cx.global_mut::<AppWindows>()
+ .preparing_cleanup
+ .prune_completed()
+ });
+ })
+ .detach();
+
// `onCleanup(() => { clearTimeout(saveTimer); flushProjectConfig() })`
// (`ED/context.ts:1246-1252`): a `.cap` closed inside the 250ms save
// debounce still gets its last edit written.
@@ -5313,8 +5700,9 @@ fn restore_after_editor_close(key: &Path, cx: &mut App) {
settings_open,
"editor window closed"
);
- let idle = RecordingSession::global(cx).read(cx).phase == Phase::Idle;
- if reveal_main_after_editor_close(editors_left, settings_open, idle) {
+ let session = session.read(cx);
+ let capture_safe = session.phase == Phase::Idle || session.capture_stopped_for_editor();
+ if reveal_main_after_editor_close(editors_left, settings_open, capture_safe) {
show_main_window(cx);
} else {
// A dock-activating window closed; the policy has to be recomputed
diff --git a/apps/desktop-gpui/src/editor_crop.rs b/apps/desktop-gpui/src/editor_crop.rs
index 84b8ff276..7f8a58fe0 100644
--- a/apps/desktop-gpui/src/editor_crop.rs
+++ b/apps/desktop-gpui/src/editor_crop.rs
@@ -26,11 +26,6 @@
//! raw = max(0, real / scale) (`boundsToRaw`, :422-430)
//! ```
//!
-//! The container is [`crop_box_size`]: the display's aspect fitted into
-//! `min(vw * 0.4, 520) x min(vh * 0.5, 520)` (`Editor.tsx:1010-1023`). At the
-//! editor's 1275x800 that is 510x400, so a 3024x1964 recording gets a 510x331
-//! box and one container pixel is `3024 / 510 = 5.929` target pixels.
-//!
//! Every number the user sees in the header -- Size and Position -- is
//! `realBounds`, i.e. target space. Every number the pointer maths works in is
//! `rawBounds`.
@@ -43,6 +38,9 @@
//! what `constrainBoundsToSize` does and the capture-area cropper does pass
//! them.
+mod alignment;
+
+use alignment::{CropGuides, ResizeAlignment, align_crop};
use std::collections::BTreeSet;
use crate::{
@@ -725,12 +723,10 @@ pub fn bounds_to_raw(real: CropBounds, scale: Vec2) -> CropBounds {
}
}
-/// `boxSize` (`Editor.tsx:1010-1023`): the display's aspect fitted into
-/// `min(vw * 0.4, 520) x min(vh * 0.5, 520)`, rounded.
pub fn crop_box_size(viewport: (f32, f32), display: (u32, u32)) -> (f32, f32) {
let ratio = f64::from(display.0) / f64::from(display.1).max(1.);
- let max_w = f64::from(viewport.0 * 0.4).min(520.);
- let max_h = f64::from(viewport.1 * 0.5).min(520.);
+ let max_w = f64::from((viewport.0 - 164.).clamp(120., 1280.) * 0.68);
+ let max_h = f64::from((viewport.1 - 280.).clamp(100., 760.));
let mut w = max_w;
let mut h = w / ratio;
if h > max_h {
@@ -1067,6 +1063,7 @@ pub struct CropState {
pub aspect: Option<Ratio>,
/// `aspectState.snapped` -- the ratio a free drag landed on.
pub snapped: Option<Ratio>,
+ pub alignment_guides: CropGuides,
pub drag: Option<CropDrag>,
/// `mouseState.hoveringHandle`, for the corner-cursor rule.
pub hovering: Option<Handle>,
@@ -1101,6 +1098,7 @@ impl CropState {
initial,
aspect: None,
snapped: None,
+ alignment_guides: CropGuides::default(),
drag: None,
hovering: None,
frame: None,
@@ -1307,6 +1305,17 @@ impl CropState {
/// `handleResizePointerMove` (`:798-868`).
pub fn resize_move(&mut self, point: Vec2, alt: bool, shift: bool, snap_enabled: bool) {
+ self.resize_move_with_alignment(point, alt, shift, snap_enabled, false);
+ }
+
+ fn resize_move_with_alignment(
+ &mut self,
+ point: Vec2,
+ alt: bool,
+ shift: bool,
+ snap_enabled: bool,
+ alignment_enabled: bool,
+ ) {
let Some(session) = self.session_mut() else {
return;
};
@@ -1349,6 +1358,44 @@ impl CropState {
let container = self.container_vec();
let final_bounds = slide_bounds_into_container(next, container.x, container.y);
+ self.alignment_guides = CropGuides::default();
+ let final_bounds = if alignment_enabled && !shift {
+ let movable = session.active_handle.movable;
+ let start = session.start_bounds;
+ let centered = session.is_alt && options.ratio.is_none();
+ let origin = Vec2::new(
+ if centered {
+ 0.5
+ } else if point.x < start.x + if movable.left { start.width } else { 0. } {
+ 1.
+ } else {
+ 0.
+ },
+ if centered {
+ 0.5
+ } else if point.y < start.y + if movable.top { start.height } else { 0. } {
+ 1.
+ } else {
+ 0.
+ },
+ );
+ let (aligned, guides) = align_crop(
+ final_bounds,
+ container,
+ Some(ResizeAlignment {
+ origin,
+ axes: (movable.left || movable.right, movable.top || movable.bottom),
+ ratio: options.ratio,
+ }),
+ );
+ self.alignment_guides = guides;
+ if guides.x.is_some() || guides.y.is_some() {
+ self.snapped = None;
+ }
+ aligned
+ } else {
+ final_bounds
+ };
self.set_raw(final_bounds);
}
@@ -1672,7 +1719,7 @@ impl EditorWindow {
// lands outside the region -- but a **handle**'s double-click expands
// that side (`:1097, 1143, 1200, 1286`).
if event.click_count == 2 {
- let hit = hit_test(point, state.raw);
+ let hit = editor_hit_test(point, state.raw);
match hit {
CropHit::Handle(handle) => {
state.stop_animation();
@@ -1690,7 +1737,13 @@ impl EditorWindow {
}
state.stop_animation();
- let hit = hit_test(point, state.raw);
+ let hit = editor_hit_test(point, state.raw);
+ let container = state.container_vec();
+ if matches!(hit, CropHit::Draw)
+ && (point.x < 0. || point.y < 0. || point.x > container.x || point.y > container.y)
+ {
+ return;
+ }
// The press log every crop probe calibrates against: where the box is
// on screen, where the pointer landed inside it, and what it grabbed.
tracing::info!(
@@ -1761,7 +1814,7 @@ impl EditorWindow {
let Some(drag) = state.drag else {
// `onMouseEnter` on the handles is what seeds `hoveringHandle`,
// which the corner-cursor rule reads.
- let hovering = match hit_test(point, state.raw) {
+ let hovering = match editor_hit_test(point, state.raw) {
CropHit::Handle(handle) => Some(handle),
_ => None,
};
@@ -1781,10 +1834,22 @@ impl EditorWindow {
let new_x = clamp(point.x - start_offset.x, 0., container.x - bounds.width);
let new_y = clamp(point.y - start_offset.y, 0., container.y - bounds.height);
let moved = move_bounds(bounds, Some(new_x), Some(new_y));
+ let (moved, guides) = if event.modifiers.shift {
+ (moved, CropGuides::default())
+ } else {
+ align_crop(moved, container, None)
+ };
+ state.alignment_guides = guides;
state.set_raw(moved);
}
CropDrag::Handle(_) | CropDrag::Overlay { .. } => {
- state.resize_move(point, event.modifiers.alt, event.modifiers.shift, snap);
+ state.resize_move_with_alignment(
+ point,
+ event.modifiers.alt,
+ event.modifiers.shift,
+ snap,
+ true,
+ );
}
}
self.crop_changed(cx);
@@ -1797,6 +1862,7 @@ impl EditorWindow {
let Some(drag) = state.drag.take() else {
return;
};
+ state.alignment_guides = CropGuides::default();
// `onOverlayPointerDown`'s end (`:934-941`): a drag that never grew
// past 5px in either axis is a stray click, and the previous region
// comes back.
@@ -2246,7 +2312,7 @@ async fn decode_display_frame(
// ---------------------------------------------------------------------------
/// `Dialog.Root`'s `max-w-[1180px]` (`Editor.tsx:809`).
-const CROP_DIALOG_MAX_WIDTH: f32 = 1180.;
+const CROP_DIALOG_MAX_WIDTH: f32 = 1440.;
/// `h-14 px-4` (`ui.tsx:231`).
const DIALOG_HEADER_HEIGHT: f32 = 56.;
/// `h-16 px-4 gap-3` (`ui.tsx:213-215`).
@@ -2483,7 +2549,7 @@ impl EditorWindow {
.gap(px(12.))
.justify_center()
.items_stretch()
- .child(labelled("Crop area", self.render_crop_area(state, cx)))
+ .child(labelled("Crop area", self.render_crop_stage(state, cx)))
.child(
div()
.flex()
@@ -2498,14 +2564,44 @@ impl EditorWindow {
.text_color(Hsla::from(theme.gray_8)),
),
)
- .child(labelled("Preview", self.render_crop_preview(px(w), px(h)))),
+ .child(labelled("Preview", self.render_crop_preview(px((w * 0.44).round()), px(h + 32.)))),
)
+ .child(div().flex().items_center().justify_between().gap(px(12.)).pt(px(16.)).text_size(px(12.)).text_color(Hsla::from(theme.gray_11))
+ .child("Drag to move · Snap to center, halves and quarters · Hold Shift to skip snapping")
+ .child(ui::EditorButton::plain(&theme, "crop-center").label("Center crop").on_click(cx.listener(|this, _, window, cx| {
+ if let Some(state) = this.crop.as_mut() {
+ let bounds = state.raw;
+ let container = state.container_vec();
+ state.set_raw_and_animate(CropBounds::new((container.x - bounds.width) / 2., (container.y - bounds.height) / 2., bounds.width, bounds.height), ORIGIN_CENTER, CropAnim::DEFAULT);
+ }
+ this.start_crop_ticker(window, cx);
+ this.crop_changed(cx);
+ }))))
.into_any_element()
}
/// The cropper itself: the raw frame, the occluder, the region and the
/// eight handles.
- fn render_crop_area(&self, state: &CropState, cx: &mut Context<Self>) -> AnyElement {
+ fn render_crop_stage(&self, state: &CropState, cx: &mut Context<Self>) -> AnyElement {
+ div()
+ .id("crop-stage")
+ .p(px(16.))
+ .rounded(px(12.))
+ .bg(Hsla::from(self.theme.gray_3))
+ .child(self.render_crop_area(state))
+ .on_mouse_down(MouseButton::Left, cx.listener(Self::crop_mouse_down))
+ // `onContextMenu={(e) => showCropOptionsMenu(e, true)}` -- anchored
+ // at the cursor (`Editor.tsx:1333-1335`).
+ .on_mouse_down(
+ MouseButton::Right,
+ cx.listener(|this, event: &MouseDownEvent, window, cx| {
+ this.open_crop_menu(event.position, window, cx);
+ }),
+ )
+ .into_any_element()
+ }
+
+ fn render_crop_area(&self, state: &CropState) -> AnyElement {
let theme = self.theme;
let (w, h) = state.container;
let (box_w, box_h) = state.box_size;
@@ -2528,12 +2624,16 @@ impl EditorWindow {
.w(px(bounds.width as f32))
.h(px(bounds.height as f32))
.border_1()
- // `border border-white/50` (`:1139`).
- .border_color(gpui::hsla(0., 0., 1., 0.5))
+ .border_color(gpui::rgb(0xffffff))
+ .child(
+ div()
+ .absolute()
+ .inset(px(1.))
+ .border_1()
+ .border_color(gpui::rgb(0x111827)),
+ )
.cursor(drag_cursor.unwrap_or(CursorStyle::OpenHand))
- // The rule-of-thirds grid, shown while any drag is live
- // (`:1168-1174`): `border-white/40`.
- .children(dragging.then(|| thirds_grid(bounds)))
+ .children(dragging.then(|| editor_thirds_grid(bounds)))
// The snapped-ratio badge (`:1295-1321`). Only while free.
.children(
(state.aspect.is_none() && !too_small)
@@ -2569,24 +2669,13 @@ impl EditorWindow {
)
}),
)
- // The corner glyphs: an L of two bars, `stroke="white"` with a
- // drop shadow, shrinking to nothing when the region is tiny
- // (`:1205-1238`).
.children(
HANDLES
.iter()
- .filter(|handle| handle.is_corner)
- .flat_map(|handle| corner_glyph(*handle, bounds, too_small)),
+ .map(|handle| editor_handle_glyph(*handle, bounds)),
);
- // The eight hit zones, in the source's paint order: edges first (which
- // is why the move layer occludes their inner halves), then the move
- // layer, then the corners.
- let mut layers = div().absolute().inset_0();
- for handle in HANDLES.iter().filter(|handle| !handle.is_corner) {
- layers = layers.child(handle_zone(*handle, bounds, drag_cursor));
- }
- layers = layers.child(
+ let mut layers = div().absolute().inset_0().child(
div()
.absolute()
.left(px(bounds.x as f32))
@@ -2595,15 +2684,17 @@ impl EditorWindow {
.h(px(bounds.height as f32))
.cursor(drag_cursor.unwrap_or(CursorStyle::OpenHand)),
);
- for handle in HANDLES.iter().filter(|handle| handle.is_corner) {
- let cursor = match (drag_cursor, state.hovering) {
- // `mouseState.drag === "handle" &&
- // mouseState.hoveringHandle?.isCorner` (`:1186-1189`).
- (Some(_), Some(hovering)) if hovering.is_corner => hovering.direction.cursor(),
- (Some(cursor), _) => cursor,
- (None, _) => handle.direction.cursor(),
- };
- layers = layers.child(handle_zone_with_cursor(*handle, bounds, cursor));
+ for handle in HANDLES.iter().rev() {
+ let rect = editor_handle_rect(*handle, bounds);
+ layers = layers.child(
+ div()
+ .absolute()
+ .left(px((bounds.x + rect.x) as f32))
+ .top(px((bounds.y + rect.y) as f32))
+ .w(px(rect.width as f32))
+ .h(px(rect.height as f32))
+ .cursor(drag_cursor.unwrap_or(handle.direction.cursor())),
+ );
}
div()
@@ -2615,7 +2706,6 @@ impl EditorWindow {
.border_1()
.border_color(Hsla::from(theme.gray_3))
.bg(Hsla::from(theme.gray_3))
- .overflow_hidden()
.cursor(base_cursor)
// The box's painted origin, so a pointer position can be made
// container-local. gpui has no `getBoundingClientRect`; this is
@@ -2653,6 +2743,7 @@ impl EditorWindow {
// The four occluder quads (`:1124-1133`).
.children(occluders(bounds, w, h))
.child(region)
+ .child(editor_alignment_guides(state.alignment_guides, w, h))
.child(layers)
// `Loading frame…` (`Editor.tsx:1356-1364`).
.children((state.frame.is_none() && !state.frame_failed).then(|| {
@@ -2668,15 +2759,6 @@ impl EditorWindow {
.text_color(Hsla::from(theme.gray_10))
.child("Loading frame…")
}))
- .on_mouse_down(MouseButton::Left, cx.listener(Self::crop_mouse_down))
- // `onContextMenu={(e) => showCropOptionsMenu(e, true)}` -- anchored
- // at the cursor (`Editor.tsx:1333-1335`).
- .on_mouse_down(
- MouseButton::Right,
- cx.listener(|this, event: &MouseDownEvent, window, cx| {
- this.open_crop_menu(event.position, window, cx);
- }),
- )
.into_any_element()
}
@@ -2935,24 +3017,204 @@ pub(crate) fn handle_zone_with_cursor(
.cursor(cursor)
}
+fn editor_handle_rect(handle: Handle, bounds: CropBounds) -> LocalRect {
+ let mut rect = handle_rect(handle, bounds);
+ if !handle.is_corner {
+ if handle.x == Axis::Center {
+ rect.y -= 4.;
+ rect.height = 18.;
+ } else {
+ rect.x -= 4.;
+ rect.width = 18.;
+ }
+ }
+ rect
+}
+
+fn editor_hit_test(point: Vec2, bounds: CropBounds) -> CropHit {
+ for handle in HANDLES {
+ if editor_handle_rect(handle, bounds).contains(point.x - bounds.x, point.y - bounds.y) {
+ return CropHit::Handle(handle);
+ }
+ }
+ hit_test(point, bounds)
+}
+
+fn editor_handle_glyph(handle: Handle, bounds: CropBounds) -> gpui::Div {
+ let outline = gpui::rgb(0x111827);
+ if handle.is_corner {
+ return div().absolute().inset_0().children(
+ corner_glyph(handle, bounds, false)
+ .into_iter()
+ .map(|glyph| glyph.border_1().border_color(outline)),
+ );
+ }
+ let horizontal = handle.x == Axis::Center;
+ let x = match handle.x {
+ Axis::Low => -1.,
+ Axis::High => bounds.width + 1.,
+ Axis::Center => bounds.width / 2.,
+ };
+ let y = match handle.y {
+ Axis::Low => -1.,
+ Axis::High => bounds.height + 1.,
+ Axis::Center => bounds.height / 2.,
+ };
+ let (w, h) = if horizontal { (26., 7.) } else { (7., 26.) };
+ div()
+ .absolute()
+ .left(px(x as f32 - w / 2.))
+ .top(px(y as f32 - h / 2.))
+ .w(px(w))
+ .h(px(h))
+ .rounded(px(3.))
+ .border_1()
+ .border_color(outline)
+ .bg(gpui::rgb(0xffffff))
+}
+
+fn editor_thirds_grid(bounds: CropBounds) -> gpui::Div {
+ let mut grid = div().absolute().inset_0();
+ for fraction in [1. / 3., 2. / 3.] {
+ grid = grid.child(
+ div()
+ .absolute()
+ .left_0()
+ .top(px((bounds.height * fraction) as f32))
+ .w_full()
+ .h(px(2.))
+ .bg(gpui::rgb(0xffffff))
+ .child(
+ div()
+ .absolute()
+ .inset_0()
+ .h(px(1.))
+ .bg(gpui::rgba(0x111827cc)),
+ ),
+ );
+ grid = grid.child(
+ div()
+ .absolute()
+ .top_0()
+ .left(px((bounds.width * fraction) as f32))
+ .h_full()
+ .w(px(2.))
+ .bg(gpui::rgb(0xffffff))
+ .child(
+ div()
+ .absolute()
+ .inset_0()
+ .w(px(1.))
+ .bg(gpui::rgba(0x111827cc)),
+ ),
+ );
+ }
+ grid
+}
+
+fn editor_alignment_guides(guides: CropGuides, w: f32, h: f32) -> gpui::Div {
+ let mut layer = div().absolute().inset_0();
+ for (horizontal, guide) in [(false, guides.x), (true, guides.y)] {
+ if let Some(guide) = guide {
+ layer = layer.child(
+ div()
+ .absolute()
+ .left(px(if horizontal { 0. } else { guide as f32 - 1. }))
+ .top(px(if horizontal { guide as f32 - 1. } else { 0. }))
+ .w(px(if horizontal { w } else { 3. }))
+ .h(px(if horizontal { 3. } else { h }))
+ .bg(gpui::rgba(0xffffff99))
+ .child(
+ div()
+ .absolute()
+ .left(px(if horizontal { 0. } else { 1. }))
+ .top(px(if horizontal { 1. } else { 0. }))
+ .w(px(if horizontal { w } else { 1. }))
+ .h(px(if horizontal { 1. } else { h }))
+ .bg(gpui::rgb(0xd946ef)),
+ ),
+ );
+ }
+ }
+ layer
+}
+
#[cfg(test)]
mod tests {
use super::*;
// -- The coordinate spaces ----------------------------------------------
- /// The box the editor's 1275x800 window gives a 3024x1964 recording, and
- /// the scale that follows from it.
#[test]
- fn crop_box_fits_the_display_aspect_into_the_source_caps() {
- // maxW = min(1275 * 0.4, 520) = 510; maxH = min(800 * 0.5, 520) = 400.
- // 510 / (3024/1964) = 331.2 -> under 400, so the width wins.
- assert_eq!(crop_box_size((1275., 800.), (3024, 1964)), (510., 331.));
- // An ultrawide is capped by width too, but a tall display is capped by
- // height: 510 / (1080/1920) = 906 > 400, so h = 400, w = 225.
- assert_eq!(crop_box_size((1275., 800.), (1080, 1920)), (225., 400.));
- // A large viewport is still capped at 520.
- assert_eq!(crop_box_size((2000., 1400.), (1000, 1000)), (520., 520.));
+ fn crop_box_leaves_room_for_handles_controls_and_preview() {
+ assert_eq!(crop_box_size((1275., 800.), (3024, 1964)), (755., 491.));
+ assert_eq!(crop_box_size((1275., 800.), (1080, 1920)), (293., 520.));
+ assert_eq!(crop_box_size((2000., 1400.), (1000, 1000)), (760., 760.));
+ }
+
+ #[test]
+ fn editor_edge_handles_are_live_on_both_sides_of_the_border() {
+ let bounds = CropBounds::new(100., 80., 300., 200.);
+ for (point, direction) in [
+ (Vec2::new(106., 180.), Direction::W),
+ (Vec2::new(93., 180.), Direction::W),
+ (Vec2::new(394., 180.), Direction::E),
+ (Vec2::new(406., 180.), Direction::E),
+ (Vec2::new(250., 86.), Direction::N),
+ (Vec2::new(250., 74.), Direction::N),
+ (Vec2::new(250., 274.), Direction::S),
+ (Vec2::new(250., 286.), Direction::S),
+ ] {
+ assert!(
+ matches!(editor_hit_test(point, bounds), CropHit::Handle(handle) if handle.direction == direction)
+ );
+ }
+ assert!(matches!(
+ editor_hit_test(Vec2::new(250., 180.), bounds),
+ CropHit::Move
+ ));
+ assert!(matches!(
+ hit_test(Vec2::new(106., 180.), bounds),
+ CropHit::Move
+ ));
+ }
+
+ #[test]
+ fn editor_resize_snaps_in_source_space_and_shift_releases_it() {
+ let mut state = CropState::new((2400, 1800), (802., 602.), CROP_ZERO);
+ state.set_container((802., 602.), (800., 600.));
+ let start = CropBounds::new(80., 70., 300., 180.);
+ state.set_raw(start);
+ state.drag = Some(CropDrag::Handle(ResizeSession {
+ start_bounds: start,
+ is_alt: false,
+ active_handle: HANDLES[7],
+ original_handle: HANDLES[7],
+ }));
+ state.resize_move_with_alignment(Vec2::new(397., 150.), false, false, false, true);
+ assert_eq!(state.raw, CropBounds::new(80., 70., 320., 180.));
+ assert_eq!(state.real(), CropBounds::new(240., 210., 960., 540.));
+ assert_eq!(state.alignment_guides.x, Some(400.));
+ state.resize_move_with_alignment(Vec2::new(397., 150.), false, true, false, true);
+ assert_eq!(state.raw, CropBounds::new(80., 70., 317., 180.));
+ assert_eq!(state.alignment_guides, CropGuides::default());
+ }
+
+ #[test]
+ fn editor_resize_keeps_the_anchor_after_crossing_it() {
+ let mut state = CropState::new((800, 600), (802., 602.), CROP_ZERO);
+ state.set_container((802., 602.), (800., 600.));
+ let start = CropBounds::new(100., 70., 200., 180.);
+ state.set_raw(start);
+ state.drag = Some(CropDrag::Handle(ResizeSession {
+ start_bounds: start,
+ is_alt: false,
+ active_handle: HANDLES[6],
+ original_handle: HANDLES[6],
+ }));
+ state.resize_move_with_alignment(Vec2::new(397., 150.), false, false, false, true);
+ assert_eq!(state.raw, CropBounds::new(300., 70., 100., 180.));
+ assert_eq!(state.alignment_guides.x, Some(400.));
}
#[test]
diff --git a/apps/desktop-gpui/src/editor_crop/alignment.rs b/apps/desktop-gpui/src/editor_crop/alignment.rs
new file mode 100644
index 000000000..873f6d98a
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_crop/alignment.rs
@@ -0,0 +1,257 @@
+use super::{CropBounds, Vec2};
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct CropGuides {
+ pub x: Option<f64>,
+ pub y: Option<f64>,
+}
+
+#[derive(Clone, Copy)]
+pub struct ResizeAlignment {
+ pub origin: Vec2,
+ pub axes: (bool, bool),
+ pub ratio: Option<f64>,
+}
+
+pub fn align_crop(
+ bounds: CropBounds,
+ container: Vec2,
+ resize: Option<ResizeAlignment>,
+) -> (CropBounds, CropGuides) {
+ let mut next = bounds;
+ let mut guides = CropGuides::default();
+ let mut best_ratio_distance = f64::INFINITY;
+ for horizontal in [true, false] {
+ if resize.is_some_and(|r| if horizontal { !r.axes.0 } else { !r.axes.1 }) {
+ continue;
+ }
+ let base = if resize.is_some_and(|r| r.ratio.is_some()) {
+ bounds
+ } else {
+ next
+ };
+ let (position, size, extent) = if horizontal {
+ (base.x, base.width, container.x)
+ } else {
+ (base.y, base.height, container.y)
+ };
+ let mut best_distance = 7.;
+ let mut candidate = base;
+ let mut guide = None;
+ let anchors: &[f64] = if resize.is_some() {
+ &[0., 1.]
+ } else {
+ &[0.5, 0., 1.]
+ };
+ for target in [0.5, 0., 1., 0.25, 0.75] {
+ for &anchor in anchors {
+ let origin =
+ resize.map_or(0., |r| if horizontal { r.origin.x } else { r.origin.y });
+ if resize.is_some() && anchor == origin {
+ continue;
+ }
+ let line = target * extent;
+ let delta = line - (position + size * anchor);
+ let distance = delta.abs();
+ if distance > 6. || distance >= best_distance {
+ continue;
+ }
+ let mut proposed = base;
+ if let Some(resize) = resize {
+ if horizontal {
+ proposed.width += delta / (anchor - origin);
+ if let Some(ratio) = resize.ratio {
+ proposed.height = proposed.width / ratio;
+ }
+ } else {
+ proposed.height += delta / (anchor - origin);
+ if let Some(ratio) = resize.ratio {
+ proposed.width = proposed.height * ratio;
+ }
+ }
+ proposed.x += (base.width - proposed.width) * resize.origin.x;
+ proposed.y += (base.height - proposed.height) * resize.origin.y;
+ } else if horizontal {
+ proposed.x += delta;
+ } else {
+ proposed.y += delta;
+ }
+ if proposed.width < 1.
+ || proposed.height < 1.
+ || proposed.x < -0.001
+ || proposed.y < -0.001
+ || proposed.x + proposed.width > container.x + 0.001
+ || proposed.y + proposed.height > container.y + 0.001
+ {
+ continue;
+ }
+ candidate = proposed;
+ guide = Some(line);
+ best_distance = distance;
+ }
+ }
+ if resize.is_some_and(|r| r.ratio.is_some()) {
+ if guide.is_none() || best_distance >= best_ratio_distance {
+ continue;
+ }
+ best_ratio_distance = best_distance;
+ guides = CropGuides::default();
+ }
+ next = candidate;
+ if horizontal {
+ guides.x = guide;
+ } else {
+ guides.y = guide;
+ }
+ }
+ (next, guides)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn centers_a_moved_crop_on_both_axes() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(253.0, 197.0, 300.0, 200.0),
+ Vec2::new(800., 600.),
+ None,
+ );
+ assert_eq!(bounds, CropBounds::new(250.0, 200.0, 300.0, 200.0));
+ assert_eq!(
+ guides,
+ CropGuides {
+ x: Some(400.0),
+ y: Some(300.0)
+ }
+ );
+ }
+
+ #[test]
+ fn snaps_a_resize_to_the_halfway_line() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(80.0, 70.0, 317.0, 180.0),
+ Vec2::new(800., 600.),
+ Some(ResizeAlignment {
+ origin: Vec2::new(0.0, 0.0),
+ axes: (true, false),
+ ratio: None,
+ }),
+ );
+ assert_eq!(bounds, CropBounds::new(80.0, 70.0, 320.0, 180.0));
+ assert_eq!(
+ guides,
+ CropGuides {
+ x: Some(400.0),
+ y: None
+ }
+ );
+ }
+
+ #[test]
+ fn keeps_the_opposite_corner_fixed() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(197.0, 153.0, 343.0, 237.0),
+ Vec2::new(800., 600.),
+ Some(ResizeAlignment {
+ origin: Vec2::new(1.0, 1.0),
+ axes: (true, true),
+ ratio: None,
+ }),
+ );
+ assert_eq!(bounds, CropBounds::new(200.0, 150.0, 340.0, 240.0));
+ assert_eq!(
+ guides,
+ CropGuides {
+ x: Some(200.0),
+ y: Some(150.0)
+ }
+ );
+ }
+
+ #[test]
+ fn keeps_alt_resizing_centered() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(163.0, 85.0, 234.0, 190.0),
+ Vec2::new(800., 600.),
+ Some(ResizeAlignment {
+ origin: Vec2::new(0.5, 0.5),
+ axes: (true, false),
+ ratio: None,
+ }),
+ );
+ assert_eq!(bounds, CropBounds::new(160.0, 85.0, 240.0, 190.0));
+ assert_eq!(
+ guides,
+ CropGuides {
+ x: Some(400.0),
+ y: None
+ }
+ );
+ }
+
+ #[test]
+ fn preserves_a_locked_ratio() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(80.0, 70.0, 317.0, 158.5),
+ Vec2::new(800., 600.),
+ Some(ResizeAlignment {
+ origin: Vec2::new(0.0, 0.0),
+ axes: (true, true),
+ ratio: Some(2.0),
+ }),
+ );
+ assert_eq!(bounds, CropBounds::new(80.0, 70.0, 320.0, 160.0));
+ assert_eq!(
+ guides,
+ CropGuides {
+ x: Some(400.0),
+ y: None
+ }
+ );
+ }
+
+ #[test]
+ fn releases_beyond_six_display_pixels() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(263.0, 217.0, 300.0, 200.0),
+ Vec2::new(800., 600.),
+ None,
+ );
+ assert_eq!(bounds, CropBounds::new(263.0, 217.0, 300.0, 200.0));
+ assert_eq!(guides, CropGuides { x: None, y: None });
+ }
+
+ #[test]
+ fn never_collapses_a_tiny_crop() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(400.0, 300.0, 3.0, 3.0),
+ Vec2::new(800., 600.),
+ Some(ResizeAlignment {
+ origin: Vec2::new(0.0, 0.0),
+ axes: (true, true),
+ ratio: None,
+ }),
+ );
+ assert_eq!(bounds, CropBounds::new(400.0, 300.0, 3.0, 3.0));
+ assert_eq!(guides, CropGuides { x: None, y: None });
+ }
+
+ #[test]
+ fn snaps_to_the_image_boundary() {
+ let (bounds, guides) = align_crop(
+ CropBounds::new(3.0, 91.0, 318.0, 217.0),
+ Vec2::new(800., 600.),
+ None,
+ );
+ assert_eq!(bounds, CropBounds::new(0.0, 91.0, 318.0, 217.0));
+ assert_eq!(
+ guides,
+ CropGuides {
+ x: Some(0.0),
+ y: None
+ }
+ );
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs
index 677caf825..12e7f5837 100644
--- a/apps/desktop-gpui/src/editor_export.rs
+++ b/apps/desktop-gpui/src/editor_export.rs
@@ -189,6 +189,7 @@ pub struct ExportUi {
pub sign_in_cancel: Arc<AtomicBool>,
pub organization_id: Option<String>,
pub share_link: Option<String>,
+ pub reuploading: bool,
pub upload_progress: f32,
pub copy_link_pressed: bool,
}
@@ -245,6 +246,7 @@ impl ExportUi {
sign_in_cancel: Arc::new(AtomicBool::new(false)),
organization_id: prefs.organization_id,
share_link: None,
+ reuploading: false,
upload_progress: 0.0,
copy_link_pressed: false,
}
@@ -357,11 +359,52 @@ fn decode_jpeg_bytes(bytes: &[u8]) -> Option<Arc<RenderImage>> {
}
impl EditorWindow {
+ pub(crate) fn render_reupload_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ div()
+ .rounded(px(8.))
+ .bg(Hsla::from(self.theme.blue_3))
+ .border_1()
+ .border_color(Hsla::from(self.theme.blue_5))
+ .child(
+ ui::EditorButton::plain(&self.theme, "editor-reupload")
+ .left_icon("icons/cloud-upload.svg")
+ .label("Reupload")
+ .tooltip(
+ &self.theme,
+ if has_transparent_background(&self.project) {
+ "Share links require a background without transparency"
+ } else {
+ "Upload your latest edit to the same link"
+ },
+ )
+ .disabled(!self.project_ready() || has_transparent_background(&self.project))
+ .on_click(cx.listener(|this, _, window, cx| {
+ if !this.project_ready() {
+ return;
+ }
+ this.open_export(window, cx);
+ if !has_transparent_background(&this.project)
+ && let Some(ui) = this.export.as_mut()
+ {
+ ui.destination = ExportDestination::Link;
+ ui.format = ExportFormatKind::Mp4;
+ ui.cursor_only = false;
+ }
+ this.normalize_loaded_export_fps();
+ this.refresh_export_preview(window, cx);
+ cx.notify();
+ })),
+ )
+ }
+
pub(crate) fn open_export(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.playing {
self.toggle_play_from_crop(cx);
}
let mut ui = ExportUi::load();
+ if let Ok(meta) = RecordingMeta::load_for_project(&self.project_path) {
+ self.sharing = meta.sharing;
+ }
if has_transparent_background(&self.project) {
ui.format = ExportFormatKind::Gif;
if ui.resolution == ExportResolution::P4k {
@@ -880,6 +923,7 @@ impl EditorWindow {
ui.cancel = Arc::new(AtomicBool::new(false));
let cancel = ui.cancel.clone();
ui.phase = ExportPhase::Starting;
+ ui.reuploading = self.sharing.is_some();
ui.error = None;
ui.share_link = None;
ui.upload_progress = 0.0;
@@ -993,6 +1037,11 @@ impl EditorWindow {
match upload.await {
Ok(Ok(crate::upload::UploadResult::Success(link))) => {
let _ = this.update(cx, |this, cx| {
+ if let Ok(meta) =
+ RecordingMeta::load_for_project(&this.project_path)
+ {
+ this.sharing = meta.sharing;
+ }
if let Some(ui) = this.export.as_mut() {
ui.phase = ExportPhase::Done;
ui.share_link = Some(link.clone());
@@ -1387,7 +1436,11 @@ impl EditorWindow {
),
ExportDestination::Link => (
ui::ButtonVariant::Primary,
- "Export to Link",
+ if self.sharing.is_some() {
+ "Reupload to same link"
+ } else {
+ "Create shareable link"
+ },
Some("icons/link.svg"),
),
};
@@ -1426,8 +1479,15 @@ impl EditorWindow {
ExportDestination::ALL
.iter()
.map(|dest| {
+ let label = if *dest == ExportDestination::Link
+ && self.sharing.is_some()
+ {
+ "Reupload"
+ } else {
+ dest.label()
+ };
let mut option =
- ui::SegmentOption::new(dest.label(), ui.destination == *dest)
+ ui::SegmentOption::new(label, ui.destination == *dest)
.disabled(*dest == ExportDestination::Link && link_disabled);
option.icon = Some(dest.icon().into());
option
@@ -1454,8 +1514,48 @@ impl EditorWindow {
cx.notify();
})),
)
+ .when(
+ ui.destination == ExportDestination::Link && self.sharing.is_some(),
+ |field| {
+ let link = self.sharing.as_ref()
+ .map(|sharing| sharing.link.clone())
+ .unwrap_or_default();
+ field.child(
+ div()
+ .p(px(12.))
+ .rounded(px(8.))
+ .bg(Hsla::from(theme.blue_3))
+ .flex()
+ .flex_col()
+ .gap(px(6.))
+ .child(
+ div()
+ .text_size(px(13.))
+ .font_weight(FontWeight::MEDIUM)
+ .child("Update your existing link"),
+ )
+ .child(
+ div()
+ .text_size(px(12.))
+ .text_color(Hsla::from(theme.gray_11))
+ .child("Reupload replaces the video at this link with your latest edit. Everyone with the link will see the updated version."),
+ )
+ .child(
+ div()
+ .id("reupload-existing-link")
+ .text_size(px(12.))
+ .text_color(Hsla::from(theme.blue_11))
+ .truncate()
+ .cursor_pointer()
+ .child(link.clone())
+ .on_click(move |_, _, cx| cx.open_url(&link)),
+ ),
+ )
+ },
+ )
.when(
ui.destination == ExportDestination::Link
+ && self.sharing.is_none()
&& store::auth_snapshot().organizations.len() > 1,
|this| {
let orgs = store::auth_snapshot().organizations;
@@ -1922,10 +2022,14 @@ impl EditorWindow {
"Copying to clipboard"
}
ExportPhase::Copying => "Saving to file",
+ ExportPhase::Uploading if ui.reuploading => "Reuploading to your link",
ExportPhase::Uploading => "Creating shareable link",
ExportPhase::Done if ui.destination == ExportDestination::Clipboard => {
"Copied to clipboard"
}
+ ExportPhase::Done if ui.destination == ExportDestination::Link && ui.reuploading => {
+ "Reupload complete"
+ }
ExportPhase::Done if ui.destination == ExportDestination::Link => "Upload complete",
ExportPhase::Done => "Export complete",
ExportPhase::Failed if ui.clipboard_retry_path().is_some() => {
@@ -1982,7 +2086,11 @@ impl EditorWindow {
div()
.text_size(px(12.))
.text_color(Hsla::from(theme.gray_11))
- .child("Your Cap has been uploaded successfully"),
+ .child(if ui.reuploading {
+ "Your latest edit is ready at the same link"
+ } else {
+ "Your Cap has been uploaded successfully"
+ }),
)
},
),
diff --git a/apps/desktop-gpui/src/editor_preparing.rs b/apps/desktop-gpui/src/editor_preparing.rs
new file mode 100644
index 000000000..9c938990e
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_preparing.rs
@@ -0,0 +1,988 @@
+use std::{
+ io::{self, BufReader, Read},
+ panic::AssertUnwindSafe,
+ path::{Path, PathBuf},
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::Instant,
+};
+
+use cap_editor::{
+ EditorFrameFormat, EditorFrameOutput, PreparingFrameRequest, PreparingPlaybackExit,
+ PreparingPlaybackOptions, PreparingPlaybackSession, PreparingPlaybackStopHandle,
+ PreparingPreviewInput, PreparingPreviewOptions, PreparingPreviewSegment,
+};
+use cap_project::{CursorEvents, XY};
+
+mod audio;
+pub(crate) mod presentation;
+
+use cap_recording::recovery::{
+ PreparingSidecarKind, PreparingStudioIdentity, PreparingStudioSources, PreparingStudioState,
+ PreparingVideoTrack,
+};
+use cap_rendering::{
+ FrameLayout, FrozenRecordedCursorAssets, ManagedSegmentVideoInput, ManagedVideoTrackInput,
+};
+use futures_util::{
+ FutureExt,
+ future::{BoxFuture, Shared},
+};
+use presentation::PreparingTimelineSeed;
+use tokio::sync::watch;
+
+use crate::recording::StudioFinalization;
+
+const MAX_CURSOR_BYTES: u64 = 256 * 1024 * 1024;
+
+#[derive(Clone)]
+pub(crate) struct PreparingEpoch(Arc<()>);
+
+impl PreparingEpoch {
+ fn same(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.0, &other.0)
+ }
+}
+
+struct ConsumerControl {
+ epoch: PreparingEpoch,
+ finalization: StudioFinalization,
+ cancelled: watch::Sender<bool>,
+ accepts_frames: AtomicBool,
+ started: Instant,
+ updates: watch::Sender<Option<PreparingUpdate>>,
+ commands: tokio::sync::mpsc::Sender<(PreparingCommand, cap_editor::PreparingPlaybackIntent)>,
+ completed: Mutex<Option<PreparingPlaybackExit>>,
+ discarded: AtomicBool,
+ admitted_identity: Mutex<Option<PreparingStudioIdentity>>,
+ handoff: watch::Sender<Option<cap_editor::PreparingPlaybackHandoff>>,
+}
+
+impl ConsumerControl {
+ fn cancel(&self) {
+ if let Some(handoff) = &*self.handoff.borrow() {
+ handoff.cancel();
+ }
+ self.accepts_frames.store(false, Ordering::Release);
+ self.cancelled.send_replace(true);
+ }
+
+ fn discard(&self) {
+ self.discarded.store(true, Ordering::Release);
+ self.cancel();
+ if let Some(exit) = self
+ .completed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take()
+ {
+ drop(exit.take_completed_audio());
+ }
+ }
+
+ fn accepts_status(&self, epoch: &PreparingEpoch, identity: &PreparingStudioIdentity) -> bool {
+ self.epoch.same(epoch)
+ && !*self.cancelled.borrow()
+ && ((self.finalization.is_finalizing()
+ && self.finalization.matches_preparing_identity(identity))
+ || self.finalization.allows_preparing_continuation(identity))
+ }
+
+ fn accepts(&self, epoch: &PreparingEpoch, identity: &PreparingStudioIdentity) -> bool {
+ self.accepts_frames.load(Ordering::Acquire) && self.accepts_status(epoch, identity)
+ }
+}
+
+pub(crate) struct PreparingConsumer {
+ control: Arc<ConsumerControl>,
+}
+
+#[derive(Clone)]
+pub(crate) struct PreparingUpdate {
+ pub(crate) epoch: PreparingEpoch,
+ pub(crate) identity: PreparingStudioIdentity,
+ pub(crate) sequence: u64,
+ pub(crate) seed: Arc<PreparingTimelineSeed>,
+ pub(crate) progress: cap_editor::PreparingEditorProgress,
+ pub(crate) playback: cap_editor::PreparingPlaybackState,
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct PreparingCommand {
+ pub(crate) seek: Option<f64>,
+ pub(crate) playing: Option<bool>,
+}
+
+impl PreparingConsumer {
+ pub(crate) fn can_command(&self) -> bool {
+ !*self.control.cancelled.borrow()
+ && (self.control.finalization.is_finalizing()
+ || self
+ .control
+ .admitted_identity
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .is_some_and(|identity| {
+ self.control
+ .finalization
+ .allows_preparing_continuation(identity)
+ }))
+ && !self.control.commands.is_closed()
+ }
+
+ pub(crate) fn command(&self, command: PreparingCommand) -> bool {
+ if !self.can_command() {
+ return false;
+ }
+ let Some(handoff) = self.control.handoff.borrow().clone() else {
+ return false;
+ };
+ let Ok(intent) = handoff.reserve_command() else {
+ return false;
+ };
+ self.control.commands.try_send((command, intent)).is_ok()
+ }
+
+ pub(crate) fn updates(&self) -> watch::Receiver<Option<PreparingUpdate>> {
+ self.control.updates.subscribe()
+ }
+
+ pub(crate) fn accepts_status(&self, update: &PreparingUpdate) -> bool {
+ self.control.accepts_status(&update.epoch, &update.identity)
+ || (update.progress.phase == cap_editor::PreparingEditorPhase::Unavailable
+ && !self.control.discarded.load(Ordering::Acquire)
+ && self.control.epoch.same(&update.epoch)
+ && self
+ .control
+ .admitted_identity
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .is_some_and(|identity| identity.same_job(&update.identity)))
+ }
+
+ pub(crate) fn accepts(
+ &self,
+ epoch: &PreparingEpoch,
+ identity: &PreparingStudioIdentity,
+ ) -> bool {
+ self.control.accepts(epoch, identity)
+ }
+}
+
+impl Drop for PreparingConsumer {
+ fn drop(&mut self) {
+ if !self
+ .control
+ .handoff
+ .borrow()
+ .as_ref()
+ .is_some_and(|handoff| handoff.committed())
+ {
+ self.control.discard();
+ }
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct PreparingJoined {
+ epoch: PreparingEpoch,
+ pub(crate) exit: Option<PreparingPlaybackExit>,
+}
+
+impl PreparingJoined {
+ pub(crate) fn matches(&self, consumer: &PreparingConsumer) -> bool {
+ self.epoch.same(&consumer.control.epoch)
+ }
+
+ pub(crate) fn take_audio(&self) -> Option<cap_editor::CompletedAudioHandoff> {
+ self.exit
+ .as_ref()
+ .and_then(PreparingPlaybackExit::take_completed_audio)
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct PreparingJoin {
+ completion: Shared<BoxFuture<'static, Result<PreparingJoined, String>>>,
+ identity: Arc<()>,
+ control: std::sync::Weak<ConsumerControl>,
+}
+
+impl PreparingJoin {
+ fn from_task(
+ runtime: &tokio::runtime::Handle,
+ task: tokio::task::JoinHandle<Result<PreparingJoined, String>>,
+ ) -> Self {
+ let completion = async move {
+ task.await
+ .map_err(|error| format!("Preparing preview task cleanup failed: {error}"))?
+ }
+ .boxed()
+ .shared();
+ let retained = completion.clone();
+ drop(runtime.spawn(async move {
+ let _ = retained.await;
+ }));
+ Self {
+ completion,
+ identity: Arc::new(()),
+ control: Default::default(),
+ }
+ }
+
+ pub(crate) async fn continuing_handoff(&self) -> Option<cap_editor::PreparingPlaybackHandoff> {
+ let control = self.control.upgrade()?;
+ let mut handoff = control.handoff.subscribe();
+ loop {
+ let value = handoff.borrow_and_update().clone();
+ if let Some(value) = value {
+ let admitted = control
+ .admitted_identity
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()?;
+ return control
+ .finalization
+ .allows_preparing_continuation(&admitted)
+ .then_some(value);
+ }
+ tokio::select! {
+ _ = self.completion.clone() => return None,
+ changed = handoff.changed() => if changed.is_err() { return None; },
+ }
+ }
+ }
+
+ pub(crate) async fn wait(&self) -> Result<PreparingJoined, String> {
+ self.completion.clone().await
+ }
+
+ pub(crate) fn same(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.identity, &other.identity)
+ }
+
+ fn completed_successfully(&self) -> bool {
+ self.completion.peek().is_some_and(Result::is_ok)
+ }
+}
+
+#[derive(Default)]
+pub(crate) struct PreparingCleanupRegistry {
+ entries: Vec<(PathBuf, PreparingJoin)>,
+}
+
+impl PreparingCleanupRegistry {
+ pub(crate) fn prune_completed(&mut self) {
+ self.entries
+ .retain(|(_, joined)| !joined.completed_successfully());
+ }
+
+ pub(crate) fn register(&mut self, path: PathBuf, joined: PreparingJoin) {
+ self.entries
+ .retain(|(_, joined)| !joined.completed_successfully());
+ self.entries.push((path, joined));
+ }
+
+ pub(crate) fn pending(&mut self, path: &Path) -> Vec<PreparingJoin> {
+ self.entries
+ .retain(|(_, joined)| !joined.completed_successfully());
+ self.entries
+ .iter()
+ .filter(|(key, _)| key == path)
+ .map(|(_, joined)| joined.clone())
+ .collect()
+ }
+}
+
+pub(crate) struct PreparingFrame {
+ pub(crate) epoch: PreparingEpoch,
+ pub(crate) identity: PreparingStudioIdentity,
+ pub(crate) request: PreparingFrameRequest,
+ pub(crate) output: EditorFrameOutput,
+ pub(crate) layout: FrameLayout,
+}
+
+struct PreparingRunner {
+ control: Arc<ConsumerControl>,
+ frames: flume::Sender<PreparingFrame>,
+ stop: Option<PreparingPlaybackStopHandle>,
+ resolution: XY<u32>,
+ audio_output: Arc<cap_editor::AudioOutput>,
+ commands: Option<
+ tokio::sync::mpsc::Receiver<(PreparingCommand, cap_editor::PreparingPlaybackIntent)>,
+ >,
+ command_task: Option<tokio::task::JoinHandle<()>>,
+ frame_discard: flume::Receiver<PreparingFrame>,
+}
+
+pub(crate) fn spawn(
+ finalization: StudioFinalization,
+ resolution: XY<u32>,
+ audio_output: Arc<cap_editor::AudioOutput>,
+ runtime: &tokio::runtime::Handle,
+) -> (
+ PreparingConsumer,
+ PreparingJoin,
+ flume::Receiver<PreparingFrame>,
+) {
+ let (cancelled, _) = watch::channel(false);
+ let (updates, _) = watch::channel(None);
+ let (commands, command_rx) = tokio::sync::mpsc::channel(8);
+ let control = Arc::new(ConsumerControl {
+ epoch: PreparingEpoch(Arc::new(())),
+ finalization,
+ cancelled,
+ accepts_frames: AtomicBool::new(false),
+ started: Instant::now(),
+ updates,
+ commands,
+ completed: Mutex::new(None),
+ discarded: AtomicBool::new(false),
+ admitted_identity: Mutex::new(None),
+ handoff: watch::channel(None).0,
+ });
+ let (frames, frame_rx) = flume::bounded(1);
+ let runner = PreparingRunner {
+ control: control.clone(),
+ frames,
+ stop: None,
+ resolution,
+ audio_output,
+ commands: Some(command_rx),
+ command_task: None,
+ frame_discard: frame_rx.clone(),
+ };
+ let mut joined = PreparingJoin::from_task(runtime, runtime.spawn(runner.run()));
+ joined.control = Arc::downgrade(&control);
+ (PreparingConsumer { control }, joined, frame_rx)
+}
+
+impl PreparingRunner {
+ async fn run(mut self) -> Result<PreparingJoined, String> {
+ let result = AssertUnwindSafe(self.run_inner()).catch_unwind().await;
+ let adopted = matches!(&result, Ok(Ok(())))
+ && self
+ .control
+ .handoff
+ .borrow()
+ .as_ref()
+ .is_some_and(|handoff| handoff.committed());
+ if adopted {
+ self.control.accepts_frames.store(false, Ordering::Release);
+ self.control.cancelled.send_replace(true);
+ self.stop = None;
+ } else {
+ self.control.cancel();
+ }
+ match result {
+ Ok(Err(error)) => tracing::debug!(%error, "Preparing playback declined"),
+ Err(_) => tracing::warn!("Preparing playback adapter panicked"),
+ Ok(Ok(())) => {}
+ }
+ let command_error = if let Some(task) = self.command_task.take() {
+ task.await.err().map(|error| error.to_string())
+ } else {
+ None
+ };
+ let exit = if let Some(stop) = self.stop.take() {
+ Some(stop.stop_and_wait().await)
+ } else {
+ None
+ };
+ if let Some(exit) = &exit {
+ if exit.snapshot.progress.phase == cap_editor::PreparingEditorPhase::Unavailable {
+ let latest = self.control.updates.borrow().clone();
+ if let Some(mut update) = latest {
+ update.sequence = progress_sequence(exit.snapshot.sequence)?;
+ update.progress = exit.snapshot.progress.clone();
+ update.playback = exit.snapshot.playback;
+ self.control.updates.send_replace(Some(update));
+ }
+ }
+ let mut completed = self
+ .control
+ .completed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if self.control.discarded.load(Ordering::Acquire)
+ || exit.cleanup_failed
+ || command_error.is_some()
+ {
+ drop(exit.take_completed_audio());
+ } else {
+ *completed = Some(exit.clone());
+ }
+ }
+ if exit.as_ref().is_some_and(|exit| exit.cleanup_failed) {
+ return Err("Preparing playback workers could not be joined".into());
+ }
+ if let Some(error) = command_error {
+ return Err(format!("Preparing command task cleanup failed: {error}"));
+ }
+ if adopted {
+ self.control.handoff.send_replace(None);
+ }
+ Ok(PreparingJoined {
+ epoch: self.control.epoch.clone(),
+ exit,
+ })
+ }
+
+ async fn run_inner(&mut self) -> Result<(), String> {
+ let mut cancel = self.control.cancelled.subscribe();
+ if *cancel.borrow() {
+ return Ok(());
+ }
+ let observer = tokio::select! {
+ biased;
+ _ = cancel.changed() => return Ok(()),
+ observer = self.control.finalization.wait_for_preparing() => observer,
+ };
+ let Some(mut observer) = observer else {
+ return Ok(());
+ };
+ let sources = loop {
+ match observer.latest() {
+ PreparingStudioState::Available(sources) => break sources,
+ PreparingStudioState::Unavailable(reason) => return Err(reason),
+ PreparingStudioState::Ended => return Ok(()),
+ PreparingStudioState::Waiting => {}
+ }
+ tokio::select! {
+ biased;
+ _ = cancel.changed() => return Ok(()),
+ _ = observer.changed() => {}
+ }
+ };
+ if !self
+ .control
+ .accepts_status(&self.control.epoch, observer.identity())
+ {
+ return Ok(());
+ }
+ *self
+ .control
+ .admitted_identity
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(observer.identity().clone());
+ tracing::info!(
+ elapsed_ms = self.control.started.elapsed().as_secs_f64() * 1000.0,
+ "GPUI preparing sources available"
+ );
+ let adapter_control = self.control.clone();
+ let (input, audio) = tokio::task::spawn_blocking(move || adapt(sources, &adapter_control))
+ .await
+ .map_err(|error| error.to_string())??;
+ if *cancel.borrow() || !matches!(observer.latest(), PreparingStudioState::Available(_)) {
+ return Ok(());
+ }
+ tracing::info!(
+ elapsed_ms = self.control.started.elapsed().as_secs_f64() * 1000.0,
+ "GPUI preparing adapter ready"
+ );
+ let seed = Arc::new(PreparingTimelineSeed {
+ project: input.project.clone(),
+ pretty_name: input.recording_meta.pretty_name.clone(),
+ has_camera: input
+ .recording_meta
+ .studio_meta()
+ .is_some_and(|studio| match studio {
+ cap_project::StudioRecordingMeta::SingleSegment { segment } => {
+ segment.camera.is_some()
+ }
+ cap_project::StudioRecordingMeta::MultipleSegments { inner, .. } => inner
+ .segments
+ .iter()
+ .any(|segment| segment.camera.is_some()),
+ }),
+ multiple_clips: input.segments.len() > 1,
+ });
+ let total_duration = input
+ .project
+ .timeline
+ .as_ref()
+ .map(|timeline| timeline.duration())
+ .filter(|duration| duration.is_finite() && *duration > 0.0);
+ self.control.updates.send_replace(Some(PreparingUpdate {
+ epoch: self.control.epoch.clone(),
+ identity: observer.identity().clone(),
+ sequence: 1,
+ seed: seed.clone(),
+ progress: cap_editor::PreparingEditorProgress {
+ total_duration,
+ ..Default::default()
+ },
+ playback: cap_editor::PreparingPlaybackState::default(),
+ }));
+ let control = self.control.clone();
+ let identity = observer.identity().clone();
+ let frame_observer = observer.clone();
+ let frames = self.frames.clone();
+ let discard = self.frame_discard.clone();
+ #[cfg(target_os = "macos")]
+ let frame_format = EditorFrameFormat::BgraSurface;
+ #[cfg(not(target_os = "macos"))]
+ let frame_format = EditorFrameFormat::Rgba;
+ self.control.accepts_frames.store(true, Ordering::Release);
+ let playback = PreparingPlaybackSession::spawn_with_expected_metadata(
+ input,
+ audio.tracks,
+ PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions {
+ use_hardware_decoding: preparing_hardware_decode(),
+ frame_format,
+ },
+ fps: crate::editor_window::EDITOR_PREVIEW_FPS,
+ resolution: self.resolution,
+ },
+ self.audio_output.clone(),
+ Box::new(move |request, output, layout| {
+ if accepts_composed_frame(
+ control.accepts(&control.epoch, &identity),
+ frame_observer.latest(),
+ control
+ .finalization
+ .allows_preparing_continuation(&identity),
+ ) {
+ tracing::debug!(
+ elapsed_ms = control.started.elapsed().as_secs_f64() * 1000.0,
+ "GPUI preparing composed frame produced"
+ );
+ let frame = PreparingFrame {
+ epoch: control.epoch.clone(),
+ identity: identity.clone(),
+ request,
+ output,
+ layout,
+ };
+ if let Err(flume::TrySendError::Full(frame)) = frames.try_send(frame) {
+ drop(discard.try_recv());
+ let _ = frames.try_send(frame);
+ }
+ }
+ }),
+ audio.expected_metadata,
+ )?;
+ self.stop = Some(playback.stop_handle());
+ let handoff = playback.handoff_handle();
+ self.control.handoff.send_replace(Some(handoff.clone()));
+ let mut updates = playback.updates();
+ let controller = playback.controller();
+ let mut commands = self
+ .commands
+ .take()
+ .ok_or("Preparing commands already started")?;
+ let mut command_cancel = self.control.cancelled.subscribe();
+ self.command_task = Some(tokio::spawn(async move {
+ loop {
+ if *command_cancel.borrow() {
+ return;
+ }
+ let (command, _intent) = tokio::select! {
+ biased;
+ _ = command_cancel.changed() => return,
+ command = commands.recv() => match command { Some(command) => command, None => return },
+ };
+ let applied = async {
+ if command.playing == Some(false) {
+ controller.set_playing(false).await?;
+ }
+ if let Some(seek) = command.seek {
+ controller.seek(seek).await?;
+ }
+ if command.playing == Some(true) {
+ controller.set_playing(true).await?;
+ }
+ Ok::<(), String>(())
+ };
+ tokio::select! {
+ biased;
+ _ = command_cancel.changed() => return,
+ result = applied => {
+ if let Err(error) = result {
+ tracing::debug!(%error, "Preparing playback command declined");
+ }
+ }
+ }
+ }
+ }));
+ let mut observing = true;
+ loop {
+ let snapshot = updates.borrow_and_update().clone();
+ self.control.updates.send_replace(Some(PreparingUpdate {
+ epoch: self.control.epoch.clone(),
+ identity: observer.identity().clone(),
+ sequence: progress_sequence(snapshot.sequence)?,
+ seed: seed.clone(),
+ progress: snapshot.progress,
+ playback: snapshot.playback,
+ }));
+ tokio::select! {
+ biased;
+ _ = cancel.changed() => return Ok(()),
+ _ = handoff.wait_committed() => return Ok(()),
+ state = observer.changed(), if observing => {
+ if !matches!(state, PreparingStudioState::Available(_)) {
+ if !self.control.finalization.allows_preparing_continuation(observer.identity()) { return Ok(()); }
+ observing = false;
+ }
+ }
+ result = updates.changed() => { if result.is_err() { return Ok(()); } }
+ }
+ }
+ }
+}
+
+fn accepts_composed_frame(
+ consumer_accepts: bool,
+ state: PreparingStudioState,
+ publication_continues: bool,
+) -> bool {
+ consumer_accepts
+ && (matches!(state, PreparingStudioState::Available(_)) || publication_continues)
+}
+
+fn progress_sequence(sequence: u64) -> Result<u64, String> {
+ sequence
+ .checked_add(2)
+ .ok_or_else(|| "Preparing progress sequence exhausted".into())
+}
+
+fn preparing_hardware_decode() -> bool {
+ !cfg!(target_os = "windows")
+}
+
+fn adapt(
+ sources: Arc<PreparingStudioSources>,
+ control: &Arc<ConsumerControl>,
+) -> Result<(PreparingPreviewInput, audio::AudioAdaptation), String> {
+ let ended = || "Preparing sources ended".to_string();
+ let live = sources.live().ok_or_else(ended)?;
+ let recording_meta = live.metadata().ok_or_else(ended)?.clone();
+ let studio = recording_meta.studio_meta().ok_or_else(ended)?;
+ let mut project =
+ crate::recording::preparing_presentation(live.configuration().ok_or_else(ended)?)?;
+ if project.clips.is_empty() {
+ project.clips =
+ cap_editor::initial_clip_configuration(&recording_meta.project_path, studio);
+ }
+ let descriptors = live.segments().ok_or_else(ended)?;
+ let pointer_ids = studio.pointer_cursor_ids();
+ let mut segments = Vec::with_capacity(descriptors.len());
+ let mut cursor_budget = MAX_CURSOR_BYTES;
+ for descriptor in descriptors {
+ if *control.cancelled.borrow() || sources.live().is_none() {
+ return Err(ended());
+ }
+ let display = live
+ .video(descriptor.index(), PreparingVideoTrack::Display)
+ .ok_or_else(ended)?;
+ let (source, paths) = display.input().ok_or_else(ended)?;
+ let display = ManagedVideoTrackInput::new(source.clone(), paths.to_vec())
+ .map_err(|error| error.to_string())?;
+ let camera = if descriptor.camera().is_some() {
+ let camera = live
+ .video(descriptor.index(), PreparingVideoTrack::Camera)
+ .ok_or_else(ended)?;
+ let (source, paths) = camera.input().ok_or_else(ended)?;
+ Some(
+ ManagedVideoTrackInput::new(source.clone(), paths.to_vec())
+ .map_err(|error| error.to_string())?,
+ )
+ } else {
+ None
+ };
+ let mut cursor = if descriptor.cursor_path().is_some() {
+ let cursor = live
+ .sidecar(descriptor.index(), PreparingSidecarKind::Cursor)
+ .ok_or_else(ended)?;
+ let (source, path) = cursor.input().ok_or_else(ended)?;
+ let reader = source.reader(path).map_err(|error| error.to_string())?;
+ let mut reader = BufReader::new(CheckedCursorReader {
+ reader,
+ is_live: || !*control.cancelled.borrow() && sources.live().is_some(),
+ remaining: cursor_budget,
+ });
+ let cursor = CursorEvents::load_from_reader(&mut reader)?;
+ cursor_budget = reader.get_ref().remaining;
+ cursor
+ } else {
+ CursorEvents::default()
+ };
+ cursor.stabilize_short_lived_cursor_shapes(
+ (!pointer_ids.is_empty()).then_some(&pointer_ids),
+ cap_project::cursor::SHORT_CURSOR_SHAPE_DEBOUNCE_MS,
+ );
+ segments.push(PreparingPreviewSegment {
+ video: ManagedSegmentVideoInput::new(
+ descriptor.index() as usize,
+ studio,
+ display,
+ camera,
+ )
+ .map_err(|error| error.to_string())?,
+ cursor: Arc::new(cursor),
+ });
+ }
+ let images = descriptors
+ .first()
+ .ok_or_else(ended)?
+ .cursor_images()
+ .iter()
+ .map(|asset| {
+ (
+ asset.id().to_string(),
+ asset.metadata().clone(),
+ Arc::<[u8]>::from(asset.bytes()),
+ )
+ });
+ let cursor_assets =
+ FrozenRecordedCursorAssets::new(images).map_err(|error| error.to_string())?;
+ if *control.cancelled.borrow() || sources.live().is_none() {
+ return Err(ended());
+ }
+ let audio = audio::adapt_audio(&sources, &recording_meta, control)?;
+ Ok((
+ PreparingPreviewInput {
+ recording_meta,
+ project,
+ segments,
+ cursor_assets,
+ },
+ audio,
+ ))
+}
+
+struct CheckedCursorReader<R, F> {
+ reader: R,
+ is_live: F,
+ remaining: u64,
+}
+
+impl<R: Read, F: Fn() -> bool> Read for CheckedCursorReader<R, F> {
+ fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
+ if output.is_empty() {
+ return Ok(0);
+ }
+ if !(self.is_live)() {
+ return Err(io::Error::other("Preparing sources ended"));
+ }
+ if self.remaining == 0 {
+ let mut next = [0];
+ return if self.reader.read(&mut next)? == 0 {
+ Ok(0)
+ } else {
+ Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Cursor sidecar exceeds preparing limit",
+ ))
+ };
+ }
+ let length = output.len().min(self.remaining as usize);
+ let count = self.reader.read(&mut output[..length])?;
+ self.remaining -= count as u64;
+ Ok(count)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Cursor;
+
+ fn joined() -> PreparingJoined {
+ PreparingJoined {
+ epoch: PreparingEpoch(Arc::new(())),
+ exit: None,
+ }
+ }
+
+ #[test]
+ fn composed_frame_gate_keeps_published_footage_and_rejects_inactive_consumers() {
+ let (state, observer) = watch::channel(PreparingStudioState::Waiting);
+ assert!(!accepts_composed_frame(
+ true,
+ observer.borrow().clone(),
+ false
+ ));
+ state.send_replace(PreparingStudioState::Ended);
+ assert!(!accepts_composed_frame(
+ true,
+ observer.borrow().clone(),
+ false
+ ));
+ assert!(accepts_composed_frame(
+ true,
+ observer.borrow().clone(),
+ true
+ ));
+ assert!(
+ !accepts_composed_frame(false, observer.borrow().clone(), true),
+ "publication must not bypass cancellation or supersession"
+ );
+ state.send_replace(PreparingStudioState::Unavailable(
+ "finalization failed".into(),
+ ));
+ assert!(!accepts_composed_frame(
+ true,
+ observer.borrow().clone(),
+ false
+ ));
+ }
+
+ #[test]
+ fn preparing_epochs_do_not_alias_reopened_windows() {
+ let first = PreparingEpoch(Arc::new(()));
+ let reopened = PreparingEpoch(Arc::new(()));
+ assert!(first.same(&first.clone()));
+ assert!(!first.same(&reopened));
+ }
+
+ #[test]
+ fn cursor_reader_preserves_exact_limit_and_rejects_an_extra_byte() {
+ let bytes = br#"{"clicks":[],"moves":[]}"#;
+ for remaining in [bytes.len() as u64, bytes.len() as u64 - 1] {
+ let reader = CheckedCursorReader {
+ reader: Cursor::new(bytes),
+ is_live: || true,
+ remaining,
+ };
+ let result = CursorEvents::load_from_reader(BufReader::new(reader));
+ assert_eq!(result.is_ok(), remaining == bytes.len() as u64);
+ }
+ }
+
+ #[test]
+ fn cursor_cancellation_is_terminal_instead_of_retryable_interrupted() {
+ let mut reader = CheckedCursorReader {
+ reader: Cursor::new(b"retained"),
+ is_live: || false,
+ remaining: 100,
+ };
+ assert_eq!(
+ reader.read(&mut [0]).unwrap_err().kind(),
+ io::ErrorKind::Other
+ );
+ assert_eq!(reader.reader.position(), 0);
+ assert_eq!(reader.read(&mut []).unwrap(), 0);
+ }
+
+ #[tokio::test]
+ async fn close_before_admission_joins_even_when_first_waiter_is_dropped() {
+ let (_publisher, finalization) = StudioFinalization::channel("test.cap".into(), 7);
+ let (consumer, joined, _frames) = spawn(
+ finalization,
+ XY::new(320, 240),
+ Arc::new(cap_editor::AudioOutput::new_headless(Box::new(|_, _| {}))),
+ &tokio::runtime::Handle::current(),
+ );
+ let retained = joined.clone();
+ drop(joined);
+ drop(consumer);
+ retained.wait().await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn panicked_cleanup_task_never_allows_ordinary_loading() {
+ let runtime = tokio::runtime::Handle::current();
+ let joined =
+ PreparingJoin::from_task(&runtime, runtime.spawn(async { panic!("cleanup failed") }));
+ assert!(joined.wait().await.is_err());
+ assert!(!joined.completed_successfully());
+ }
+
+ #[tokio::test]
+ async fn reopened_window_waits_the_old_windows_actual_task_exit() {
+ let runtime = tokio::runtime::Handle::current();
+ let (release, stopped) = tokio::sync::oneshot::channel();
+ let old = PreparingJoin::from_task(
+ &runtime,
+ runtime.spawn(async move {
+ stopped.await.unwrap();
+ Ok(joined())
+ }),
+ );
+ let new = PreparingJoin::from_task(&runtime, runtime.spawn(async { Ok(joined()) }));
+ let mut registry = PreparingCleanupRegistry::default();
+ registry.register("recording.cap".into(), old.clone());
+ registry.register("recording.cap".into(), new.clone());
+ new.wait().await.unwrap();
+ let pending = registry.pending(Path::new("recording.cap"));
+ assert_eq!(pending.len(), 1);
+ assert!(pending[0].wait().now_or_never().is_none());
+ release.send(()).unwrap();
+ pending[0].wait().await.unwrap();
+ assert!(registry.pending(Path::new("recording.cap")).is_empty());
+ }
+
+ #[tokio::test]
+ async fn failed_join_is_retained_for_its_project_only() {
+ let runtime = tokio::runtime::Handle::current();
+ let failed = PreparingJoin::from_task(
+ &runtime,
+ runtime.spawn(async { Err("missing join".into()) }),
+ );
+ assert!(failed.wait().await.is_err());
+ let mut registry = PreparingCleanupRegistry::default();
+ registry.register("failed.cap".into(), failed);
+ assert!(registry.pending(Path::new("other.cap")).is_empty());
+ let pending = registry.pending(Path::new("failed.cap"));
+ assert_eq!(pending.len(), 1);
+ assert!(pending[0].wait().await.is_err());
+ }
+
+ #[test]
+ fn initial_core_progress_follows_seed_and_cannot_wrap() {
+ let mut presentation = presentation::PreparingPresentation::default();
+ assert!(presentation.apply(1, Default::default(), Default::default()));
+ assert!(presentation.apply(
+ progress_sequence(0).unwrap(),
+ Default::default(),
+ Default::default()
+ ));
+ assert!(!presentation.apply(1, Default::default(), Default::default()));
+ assert_eq!(progress_sequence(u64::MAX - 2).unwrap(), u64::MAX);
+ assert!(progress_sequence(u64::MAX - 1).is_err());
+ }
+
+ #[tokio::test]
+ async fn queued_commands_are_bounded_and_close_joins_without_admission() {
+ let (_publisher, finalization) = StudioFinalization::channel("test.cap".into(), 9);
+ let (consumer, joined, _frames) = spawn(
+ finalization,
+ XY::new(320, 240),
+ Arc::new(cap_editor::AudioOutput::new_headless(Box::new(|_, _| {}))),
+ &tokio::runtime::Handle::current(),
+ );
+ assert!(!consumer.command(PreparingCommand {
+ seek: Some(0.0),
+ playing: Some(true)
+ }));
+ let control = consumer.control.clone();
+ let permits = (0..8)
+ .map(|_| control.commands.try_reserve().unwrap())
+ .collect::<Vec<_>>();
+ assert!(control.commands.try_reserve().is_err());
+ drop(consumer);
+ tokio::time::timeout(std::time::Duration::from_secs(1), joined.wait())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(*control.cancelled.borrow());
+ assert!(control.discarded.load(Ordering::Acquire));
+ assert!(control.commands.is_closed());
+ drop(permits);
+ }
+
+ #[test]
+ fn preparing_decode_preference_matches_the_ordinary_platform_path() {
+ #[cfg(target_os = "windows")]
+ assert!(!preparing_hardware_decode());
+ #[cfg(not(target_os = "windows"))]
+ assert!(preparing_hardware_decode());
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_preparing/audio.rs b/apps/desktop-gpui/src/editor_preparing/audio.rs
new file mode 100644
index 000000000..62929f287
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_preparing/audio.rs
@@ -0,0 +1,362 @@
+use super::*;
+use cap_editor::PreparingAudioSegmentInput;
+use cap_project::{AudioMeta, RecordingMeta, StudioRecordingMeta};
+use cap_recording::recovery::PreparingAudioTrack;
+
+const MAX_AUDIO_TIMING_LOG_BYTES: u64 = 4 * 1024 * 1024;
+
+struct AudioTiming {
+ expected_metadata: RecordingMeta,
+ repairs: Option<Vec<cap_editor::SegmentAudioTimingRepair>>,
+}
+
+pub(super) struct AudioAdaptation {
+ pub(super) tracks: Vec<PreparingAudioSegmentInput>,
+ pub(super) expected_metadata: RecordingMeta,
+}
+
+pub(super) fn adapt_audio(
+ sources: &Arc<PreparingStudioSources>,
+ metadata: &RecordingMeta,
+ control: &Arc<ConsumerControl>,
+) -> Result<AudioAdaptation, String> {
+ let timing = audio_timing(metadata)?;
+ let live = sources.live().ok_or("Preparing audio sources ended")?;
+ let descriptors = live.segments().ok_or("Preparing audio sources ended")?;
+ let mut tracks = Vec::with_capacity(descriptors.len());
+ for (index, descriptor) in descriptors.iter().enumerate() {
+ let repair = match &timing.repairs {
+ Some(repairs) => *repairs
+ .get(index)
+ .ok_or("Preparing audio timing layout changed")?,
+ None => cap_editor::SegmentAudioTimingRepair::default(),
+ };
+ let track = |kind, stem| {
+ timing.repairs.as_ref()?;
+ let lease = live.audio(descriptor.index(), kind)?;
+ let metadata = lease.metadata()?;
+ let (source, path) = lease.input()?;
+ if !preserved_audio_path(metadata, path, stem) {
+ return None;
+ }
+ if path.extension().is_some_and(|extension| extension == "m4a") {
+ let control = control.clone();
+ let sources = sources.clone();
+ let input = cap_enc_ffmpeg::SegmentedInput::open_relocatable_interruptible(
+ source,
+ [path],
+ Arc::new(move || *control.cancelled.borrow() || sources.live().is_none()),
+ )
+ .ok()?;
+ if input
+ .input()
+ .streams()
+ .best(ffmpeg::media::Type::Video)
+ .is_some()
+ || !input
+ .input()
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .is_some_and(|stream| stream.parameters().id() == ffmpeg::codec::Id::AAC)
+ {
+ return None;
+ }
+ }
+ cap_audio::ManagedAudioInput::new(source.clone(), path.to_path_buf()).ok()
+ };
+ tracks.push(PreparingAudioSegmentInput {
+ mic: track(PreparingAudioTrack::Mic, "audio-input"),
+ system_audio: track(PreparingAudioTrack::SystemAudio, "system_audio"),
+ timing_repair: repair,
+ });
+ if *control.cancelled.borrow() || sources.live().is_none() {
+ return Err("Preparing audio sources ended".into());
+ }
+ }
+ Ok(AudioAdaptation {
+ tracks,
+ expected_metadata: timing.expected_metadata,
+ })
+}
+
+fn audio_timing(metadata: &RecordingMeta) -> Result<AudioTiming, String> {
+ let mut expected_metadata = metadata.clone();
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut expected_metadata.inner else {
+ return Err("Preparing audio requires Studio metadata".into());
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ return Err("Preparing audio requires stopped segments".into());
+ };
+ for segment in &mut inner.segments {
+ for audio in [&mut segment.mic, &mut segment.system_audio]
+ .into_iter()
+ .flatten()
+ {
+ audio.gap_summary = None;
+ }
+ }
+ // Clean Stop joins timing-log writers; finalization can still append unrelated events.
+ let timing_log = read_timing_log(
+ &metadata.project_path.join("recording-logs.log"),
+ MAX_AUDIO_TIMING_LOG_BYTES,
+ );
+ let repairs = match timing_log {
+ Ok(log) => Some(cap_editor::segment_audio_timing_repairs(
+ expected_metadata
+ .studio_meta()
+ .ok_or("Preparing Studio metadata ended")?,
+ log.as_deref(),
+ )),
+ Err(error) => {
+ tracing::debug!(%error, "Preparing audio timing requires ordinary loading");
+ None
+ }
+ };
+ Ok(AudioTiming {
+ expected_metadata,
+ repairs,
+ })
+}
+
+fn read_timing_log(path: &Path, limit: u64) -> Result<Option<String>, String> {
+ let initial = match std::fs::symlink_metadata(path) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(format!("Preparing audio timing log metadata: {error}")),
+ };
+ if !initial.is_file() || initial.len() > limit {
+ return Err("Preparing audio timing log is not a bounded regular file".into());
+ }
+ let file = std::fs::File::open(path)
+ .map_err(|error| format!("Preparing audio timing log open: {error}"))?;
+ let opened = file.metadata().map_err(|error| error.to_string())?;
+ if !opened.is_file()
+ || opened.len() != initial.len()
+ || opened.modified().ok() != initial.modified().ok()
+ {
+ return Err("Preparing audio timing log changed before reading".into());
+ }
+ let mut bytes = String::with_capacity(opened.len() as usize);
+ let mut bounded = file.take(limit.saturating_add(1));
+ bounded
+ .read_to_string(&mut bytes)
+ .map_err(|error| format!("Preparing audio timing log read: {error}"))?;
+ let finished = bounded
+ .get_ref()
+ .metadata()
+ .map_err(|error| error.to_string())?;
+ if bytes.len() as u64 != opened.len()
+ || finished.len() != opened.len()
+ || finished.modified().ok() != opened.modified().ok()
+ {
+ return Err("Preparing audio timing log changed while reading".into());
+ }
+ Ok(Some(bytes))
+}
+
+fn preserved_audio_path(metadata: &AudioMeta, relative: &Path, stem: &str) -> bool {
+ let expected = Path::new("content/segments").join(relative);
+ if Path::new(metadata.path.as_str()) != expected {
+ return false;
+ }
+ ["m4a", "ogg"].into_iter().any(|extension| {
+ relative
+ .file_name()
+ .is_some_and(|name| name == format!("{stem}.{extension}").as_str())
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct TestDirectory(PathBuf);
+
+ impl TestDirectory {
+ fn new() -> Self {
+ let nonce = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let path = std::env::temp_dir().join(format!(
+ "cap-gpui-preparing-audio-{}-{nonce}",
+ std::process::id()
+ ));
+ std::fs::create_dir(&path).unwrap();
+ Self(path)
+ }
+
+ fn metadata(&self) -> RecordingMeta {
+ let mut metadata: RecordingMeta = serde_json::from_value(serde_json::json!({
+ "pretty_name": "Timing snapshot",
+ "segments": [{
+ "display": { "path": "content/segments/segment-0/display", "fps": 30 },
+ "mic": {
+ "path": "content/segments/segment-0/audio-input.m4a",
+ "start_time": 0.125,
+ "gap_summary": {
+ "total_overlap_trimmed_ms": 867,
+ "startup_overlap_trimmed_ms": 867,
+ "overlap_dropped_frames": 3,
+ "startup_overlap_drops": 3
+ }
+ },
+ "system_audio": {
+ "path": "content/segments/segment-0/system_audio.m4a",
+ "start_time": 0.25
+ }
+ }]
+ }))
+ .unwrap();
+ metadata.project_path = self.0.clone();
+ metadata
+ }
+
+ fn log(&self) -> PathBuf {
+ self.0.join("recording-logs.log")
+ }
+ }
+
+ impl Drop for TestDirectory {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+
+ fn repair_log() -> String {
+ "segment{index=0}:mic-out: Dropping overlapping audio frame frame_count=1 overlap_ms=100\nsegment{index=0}:system-audio-out: Dropping overlapping audio frame frame_count=1 overlap_ms=50\n".repeat(3)
+ }
+
+ #[test]
+ fn present_and_missing_timing_logs_admit_ordinary_zero_offsets() {
+ let directory = TestDirectory::new();
+ let metadata = directory.metadata();
+ let absent = audio_timing(&metadata).unwrap();
+ assert_eq!(absent.repairs.unwrap(), vec![Default::default()]);
+ for text in [
+ "",
+ "Finalization finished 微phone\n",
+ "overlap_ms=not-a-number\n",
+ ] {
+ std::fs::write(directory.log(), text).unwrap();
+ let present = audio_timing(&metadata).unwrap();
+ assert_eq!(present.repairs.unwrap(), vec![Default::default()]);
+ }
+ }
+
+ #[test]
+ fn stopped_timing_matches_ordinary_gap_clearing_and_nonzero_log_repairs() {
+ let directory = TestDirectory::new();
+ let metadata = directory.metadata();
+ let before = serde_json::to_value(&metadata).unwrap();
+ assert_eq!(
+ cap_editor::segment_audio_timing_repairs(metadata.studio_meta().unwrap(), None)[0]
+ .mic_offset_secs,
+ -0.867
+ );
+ std::fs::write(directory.log(), repair_log()).unwrap();
+ let snapshot = audio_timing(&metadata).unwrap();
+ let mut finalized_value = before.clone();
+ finalized_value["segments"][0]["mic"]
+ .as_object_mut()
+ .unwrap()
+ .remove("gap_summary");
+ let finalized: RecordingMeta = serde_json::from_value(finalized_value.clone()).unwrap();
+ let ordinary_log = std::fs::read_to_string(directory.log()).unwrap();
+ let ordinary = cap_editor::segment_audio_timing_repairs(
+ finalized.studio_meta().unwrap(),
+ Some(&ordinary_log),
+ );
+ assert_eq!(snapshot.repairs.as_ref().unwrap(), &ordinary);
+ assert_eq!(ordinary[0].mic_offset_secs, -0.3);
+ assert_eq!(ordinary[0].system_audio_offset_secs, -0.15);
+ assert_eq!(
+ serde_json::to_value(&snapshot.expected_metadata).unwrap(),
+ finalized_value
+ );
+ assert_eq!(
+ snapshot.expected_metadata.project_path,
+ metadata.project_path
+ );
+ assert_eq!(serde_json::to_value(&metadata).unwrap(), before);
+ }
+
+ #[test]
+ fn malformed_oversized_and_nonregular_logs_decline_audio_timing() {
+ let directory = TestDirectory::new();
+ let metadata = directory.metadata();
+ std::fs::write(directory.log(), [0xff, 0xfe]).unwrap();
+ assert!(audio_timing(&metadata).unwrap().repairs.is_none());
+ let file = std::fs::File::create(directory.log()).unwrap();
+ file.set_len(MAX_AUDIO_TIMING_LOG_BYTES + 1).unwrap();
+ drop(file);
+ assert!(audio_timing(&metadata).unwrap().repairs.is_none());
+ std::fs::remove_file(directory.log()).unwrap();
+ std::fs::create_dir(directory.log()).unwrap();
+ assert!(audio_timing(&metadata).unwrap().repairs.is_none());
+ }
+
+ #[test]
+ fn captured_timing_is_immutable_across_later_log_updates() {
+ let directory = TestDirectory::new();
+ let metadata = directory.metadata();
+ let log = repair_log();
+ std::fs::write(directory.log(), &log).unwrap();
+ let snapshot = audio_timing(&metadata).unwrap();
+ std::fs::write(directory.log(), format!("{log}Finalization published\n")).unwrap();
+ assert_eq!(audio_timing(&metadata).unwrap().repairs, snapshot.repairs);
+ std::fs::write(directory.log(), "different later contents").unwrap();
+ assert_eq!(
+ audio_timing(&metadata).unwrap().repairs.unwrap(),
+ vec![Default::default()]
+ );
+ assert_eq!(snapshot.repairs.unwrap()[0].mic_offset_secs, -0.3);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlink_timing_log_is_not_admitted() {
+ let directory = TestDirectory::new();
+ let target = directory.0.join("target.log");
+ std::fs::write(&target, repair_log()).unwrap();
+ std::os::unix::fs::symlink(target, directory.log()).unwrap();
+ assert!(
+ audio_timing(&directory.metadata())
+ .unwrap()
+ .repairs
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn audio_admission_requires_the_unchanged_final_path_and_container_name() {
+ let metadata = |path: &str| AudioMeta {
+ path: path.into(),
+ start_time: Some(0.0),
+ device_id: None,
+ gap_summary: None,
+ };
+ for extension in ["m4a", "ogg"] {
+ let relative = PathBuf::from(format!("segment-0/audio-input.{extension}"));
+ let meta = metadata(&format!("content/segments/{}", relative.display()));
+ assert!(preserved_audio_path(&meta, &relative, "audio-input"));
+ assert!(!preserved_audio_path(&meta, &relative, "system_audio"));
+ }
+ for path in [
+ "segment-0/audio-input.mp3",
+ "segment-0/audio-input/audio.m4a",
+ "segment-0/audio-input.M4A",
+ ] {
+ assert!(!preserved_audio_path(
+ &metadata(&format!("content/segments/{path}")),
+ Path::new(path),
+ "audio-input"
+ ));
+ }
+ assert!(!preserved_audio_path(
+ &metadata("content/segments/other/audio-input.m4a"),
+ Path::new("segment-0/audio-input.m4a"),
+ "audio-input"
+ ));
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_preparing/presentation.rs b/apps/desktop-gpui/src/editor_preparing/presentation.rs
new file mode 100644
index 000000000..ebfa06eeb
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_preparing/presentation.rs
@@ -0,0 +1,275 @@
+use cap_editor::{PreparingEditorPhase, PreparingEditorProgress, PreparingPlaybackState};
+use cap_project::ProjectConfiguration;
+
+#[derive(Clone)]
+pub(crate) struct PreparingTimelineSeed {
+ pub(crate) project: ProjectConfiguration,
+ pub(crate) pretty_name: String,
+ pub(crate) has_camera: bool,
+ pub(crate) multiple_clips: bool,
+}
+
+#[derive(Default)]
+pub(crate) struct PreparingPresentation {
+ pub(crate) progress: PreparingEditorProgress,
+ pub(crate) playback: PreparingPlaybackState,
+ sequence: u64,
+}
+
+impl PreparingPresentation {
+ pub(crate) fn apply(
+ &mut self,
+ sequence: u64,
+ progress: PreparingEditorProgress,
+ playback: PreparingPlaybackState,
+ ) -> bool {
+ if sequence <= self.sequence
+ || !progress.playable_until.is_finite()
+ || progress.playable_until < 0.0
+ || progress.total_duration.is_some_and(|total| {
+ !total.is_finite() || total <= 0.0 || progress.playable_until > total
+ })
+ || (progress.total_duration.is_none() && progress.playable_until != 0.0)
+ || !playback.playhead_seconds.is_finite()
+ || playback.playhead_seconds < 0.0
+ || progress
+ .total_duration
+ .is_some_and(|total| playback.playhead_seconds > total)
+ || (progress.phase == PreparingEditorPhase::Unavailable
+ && progress.playable_until != 0.0)
+ || (playback.playing
+ && (!progress.preview_available
+ || progress.phase == PreparingEditorPhase::Unavailable
+ || playback.playhead_seconds > progress.playable_until
+ || (playback.playhead_seconds == progress.playable_until
+ && !playback.buffering)))
+ {
+ return false;
+ }
+ self.sequence = sequence;
+ self.progress = progress;
+ self.playback = playback;
+ true
+ }
+
+ pub(crate) fn controls_ready(&self) -> bool {
+ self.progress.phase == PreparingEditorPhase::Preparing
+ && self.progress.preview_available
+ && self.progress.playable_until > 0.0
+ }
+
+ pub(crate) fn last_playable_frame_time(&self, fps: u32) -> Option<f64> {
+ (self.controls_ready() && fps > 0).then(|| {
+ let frame =
+ ((self.progress.playable_until * f64::from(fps)).ceil() as u64).saturating_sub(1);
+ frame as f64 / f64::from(fps)
+ })
+ }
+
+ pub(crate) fn seek_target(&self, seconds: f64, fps: u32) -> Option<f64> {
+ if !self.controls_ready()
+ || !seconds.is_finite()
+ || seconds < 0.0
+ || seconds > self.progress.playable_until
+ {
+ return None;
+ }
+ self.last_playable_frame_time(fps)
+ .map(|last| seconds.min(last))
+ }
+
+ pub(crate) fn handoff(&mut self) {
+ self.progress.phase = PreparingEditorPhase::Handoff;
+ self.playback.buffering = false;
+ }
+
+ pub(crate) fn toggle_handoff_playback(&mut self, at_end: bool) -> Option<f64> {
+ if at_end {
+ self.playback.playing = true;
+ self.playback.playhead_seconds = 0.0;
+ Some(0.0)
+ } else {
+ self.playback.playing = !self.playback.playing;
+ None
+ }
+ }
+
+ pub(crate) fn handoff_frame(&self, total: f64, fps: u32) -> u32 {
+ let target = (self.playback.playhead_seconds * f64::from(fps)).round() as u32;
+ if total.is_finite() && total > 0.0 {
+ target.min(((total * f64::from(fps)).ceil() as u32).saturating_sub(1))
+ } else {
+ target
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn progress() -> PreparingEditorProgress {
+ PreparingEditorProgress {
+ total_duration: Some(60.0),
+ playable_until: 20.0,
+ preview_available: true,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn preview_alone_has_no_playable_prefix() {
+ let state = PreparingPresentation::default();
+ assert_eq!(state.progress.playable_until, 0.0);
+ assert!(!state.playback.playing);
+ assert_eq!(state.progress.total_duration, None);
+ }
+
+ #[test]
+ fn invalid_or_stale_readiness_preserves_last_confirmed_state() {
+ let mut state = PreparingPresentation::default();
+ assert!(state.apply(2, progress(), PreparingPlaybackState::default()));
+ assert!(!state.apply(1, PreparingEditorProgress::default(), Default::default()));
+ for invalid in [f64::NAN, f64::INFINITY, -1.0, 61.0] {
+ let mut next = progress();
+ next.playable_until = invalid;
+ assert!(!state.apply(3, next, Default::default()));
+ }
+ assert_eq!(state.progress, progress());
+ }
+
+ #[test]
+ fn unknown_duration_never_admits_a_playable_prefix() {
+ let mut state = PreparingPresentation::default();
+ let next = PreparingEditorProgress {
+ playable_until: 1.0,
+ ..Default::default()
+ };
+ assert!(!state.apply(1, next, Default::default()));
+ }
+
+ #[test]
+ fn playing_requires_a_real_preview_and_confirmed_prefix() {
+ let mut state = PreparingPresentation::default();
+ let playback = PreparingPlaybackState {
+ playhead_seconds: 20.0,
+ playing: true,
+ buffering: false,
+ };
+ assert!(!state.apply(1, progress(), playback));
+ let mut next = progress();
+ next.preview_available = false;
+ assert!(!state.apply(
+ 1,
+ next,
+ PreparingPlaybackState {
+ playhead_seconds: 10.0,
+ ..playback
+ }
+ ));
+ assert!(state.apply(
+ 1,
+ progress(),
+ PreparingPlaybackState {
+ playhead_seconds: 10.0,
+ ..playback
+ }
+ ));
+ }
+
+ #[test]
+ fn seeking_never_crosses_the_confirmed_frontier_or_exact_end_frame() {
+ let mut state = PreparingPresentation::default();
+ assert_eq!(state.seek_target(0.0, 30), None);
+ assert!(state.apply(1, progress(), Default::default()));
+ assert_eq!(state.seek_target(12.25, 30), Some(12.25));
+ assert_eq!(state.seek_target(20.0, 30), Some(599.0 / 30.0));
+ for invalid in [20.001, -0.1, f64::NAN, f64::INFINITY] {
+ assert_eq!(state.seek_target(invalid, 30), None);
+ }
+ assert_eq!(state.seek_target(0.0, 0), None);
+ state.handoff();
+ assert!(!state.controls_ready());
+ assert_eq!(state.seek_target(0.0, 30), None);
+ }
+
+ #[test]
+ fn terminal_failure_disables_controls_and_preserves_a_retained_image_position() {
+ let mut state = PreparingPresentation::default();
+ assert!(state.apply(
+ 1,
+ progress(),
+ PreparingPlaybackState {
+ playhead_seconds: 12.25,
+ ..Default::default()
+ }
+ ));
+ assert!(state.controls_ready());
+ let failed = PreparingEditorProgress {
+ phase: PreparingEditorPhase::Unavailable,
+ playable_until: 0.0,
+ ..progress()
+ };
+ assert!(state.apply(2, failed, state.playback));
+ assert!(!state.controls_ready());
+ assert_eq!(state.playback.playhead_seconds, 12.25);
+ assert!(!state.apply(1, progress(), Default::default()));
+ }
+
+ #[test]
+ fn natural_end_retains_exact_playhead_with_a_valid_last_image() {
+ let mut state = PreparingPresentation::default();
+ let ready = PreparingEditorProgress {
+ total_duration: Some(10.0),
+ playable_until: 10.0,
+ ..progress()
+ };
+ assert!(state.apply(
+ 1,
+ ready,
+ PreparingPlaybackState {
+ playhead_seconds: 10.0,
+ ..Default::default()
+ }
+ ));
+ state.handoff();
+ assert_eq!(state.handoff_frame(10.0, 30), 299);
+ assert_eq!(state.playback.playhead_seconds, 10.0);
+ assert!(!state.playback.playing);
+ }
+
+ #[test]
+ fn newer_handoff_play_intent_restarts_at_end_and_can_be_paused_again() {
+ let mut state = PreparingPresentation::default();
+ state.playback.playhead_seconds = 10.0;
+ state.handoff();
+ assert_eq!(state.toggle_handoff_playback(true), Some(0.0));
+ assert_eq!(state.handoff_frame(10.0, 30), 0);
+ assert!(state.playback.playing);
+ assert_eq!(state.toggle_handoff_playback(false), None);
+ assert!(!state.playback.playing);
+ assert_eq!(state.playback.playhead_seconds, 0.0);
+ }
+
+ #[test]
+ fn handoff_retains_position_and_playing_intent() {
+ let mut state = PreparingPresentation::default();
+ assert!(state.apply(
+ 1,
+ progress(),
+ PreparingPlaybackState {
+ playhead_seconds: 12.25,
+ playing: true,
+ buffering: false,
+ }
+ ));
+ state.handoff();
+ assert_eq!(state.progress.phase, PreparingEditorPhase::Handoff);
+ assert_eq!(state.handoff_frame(60.0, 30), 368);
+ assert_eq!(state.handoff_frame(10.0, 30), 299);
+ assert_eq!(state.playback.playhead_seconds, 12.25);
+ assert_eq!(state.handoff_frame(0.01, 30), 0);
+ assert_eq!(state.handoff_frame(10.01, 30), 300);
+ assert!(state.playback.playing);
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_timeline.rs b/apps/desktop-gpui/src/editor_timeline.rs
index 14ff44c47..ced9a0cb4 100644
--- a/apps/desktop-gpui/src/editor_timeline.rs
+++ b/apps/desktop-gpui/src/editor_timeline.rs
@@ -503,44 +503,8 @@ fn visible_box(start: f64, end: f64, transform: Transform, secs_per_pixel: f64)
// Waveform peaks
// ---------------------------------------------------------------------------
-/// `AudioData::SAMPLE_RATE` (`crates/audio/src/audio_data.rs:20`). Spelled out
-/// rather than imported because `cap-audio` is not a direct dependency here --
-/// the decoded track arrives through `cap_editor::AudioLoader`, and its
-/// inherent methods are all this needs.
-const AUDIO_SAMPLE_RATE: usize = 48_000;
-
-/// `get_waveform` (`apps/desktop/src-tauri/src/audio.rs:42-73`), transcribed:
-/// one absolute-dBFS value per ~100 ms chunk of the decoded track, with digital
-/// silence pinned to -60 dBFS rather than -inf.
-///
-/// It lives in the Tauri *app*, not in a crate, which is the only reason it is
-/// copied here rather than called. The data path itself needs nothing new:
-/// `EditorInstance::segment_medias[i].audio` is an `AudioLoader` whose `get()`
-/// resolves once the background decode finishes, exactly as
-/// `get_mic_waveforms` (`lib.rs:4395-4412`) awaits it.
-pub fn waveform_peaks(samples: &[f32], channels: u16) -> Vec<f32> {
- const CHUNK_SIZE: usize = AUDIO_SAMPLE_RATE / 10; // ~100ms
-
- let channels = (channels as usize).max(1);
- let mut waveform = Vec::new();
-
- let mut i = 0;
- while i < samples.len() {
- let end = (i + CHUNK_SIZE * channels).min(samples.len());
- let mut sum = 0.0f32;
- for s in &samples[i..end] {
- sum += s.abs();
- }
- let avg = if end > i { sum / (end - i) as f32 } else { 0.0 };
- waveform.push(avg);
- i += CHUNK_SIZE * channels;
- }
-
- for v in waveform.iter_mut() {
- *v = if *v > 0.0 { 20.0 * v.log10() } else { -60.0 };
- }
-
- waveform
+pub fn waveform_peaks<'a>(samples: impl IntoIterator<Item = &'a f32>, channels: u16) -> Vec<f32> {
+ cap_editor::waveform_peaks(samples.into_iter(), channels)
}
/// `WAVEFORM_MIN_DB` / `WAVEFORM_SAMPLE_STEP` / `WAVEFORM_MUTE_DB`
@@ -3290,6 +3254,8 @@ pub fn wheel_zoom_delta(dom_delta_y: f64, zoom: f64) -> f64 {
mod tests {
use super::*;
+ const AUDIO_SAMPLE_RATE: usize = 48_000;
+
// -- The ruler ----------------------------------------------------------
#[test]
@@ -4182,3 +4148,160 @@ mod style_image_tests {
assert!(!scene_available(&project, false));
}
}
+
+pub(crate) fn preparing_frontier_offset(
+ playable_until: f64,
+ view: TimelineView,
+ width: f32,
+) -> f32 {
+ if !playable_until.is_finite() || !width.is_finite() || width <= 0.0 {
+ return 0.0;
+ }
+ let seconds_per_pixel = view.transform.secs_per_pixel(width);
+ if !seconds_per_pixel.is_finite() || seconds_per_pixel <= 0.0 {
+ return 0.0;
+ }
+ ((playable_until - view.transform.position) / seconds_per_pixel).clamp(0.0, f64::from(width))
+ as f32
+}
+
+pub(crate) fn render_preparing_timeline(
+ theme: &Theme,
+ model: &TimelineModel,
+ view: TimelineView,
+ viewport_width: f32,
+ progress: Option<&cap_editor::PreparingEditorProgress>,
+) -> AnyElement {
+ let known_duration = progress.and_then(|progress| progress.total_duration);
+ let playable_until = progress.map_or(0.0, |progress| progress.playable_until);
+ let content_width = content_width(viewport_width);
+ let frontier = preparing_frontier_offset(playable_until, view, content_width);
+ let mut rows = div()
+ .flex()
+ .flex_col()
+ .gap(px(TRACK_ROW_GAP))
+ .w_full()
+ .pr(px(SCROLL_BODY_PADDING_RIGHT));
+ if known_duration.is_some() {
+ for row in &model.rows {
+ rows = rows.child(render_row(
+ theme,
+ model,
+ *row,
+ view,
+ viewport_width,
+ SegmentUi::default(),
+ ));
+ }
+ } else {
+ rows = rows.child(
+ div()
+ .flex()
+ .flex_row()
+ .h(px(TRACK_HEIGHT))
+ .rounded(px(TRACK_BAND_RADIUS))
+ .bg(Hsla::from(theme.editor.ctl))
+ .child(
+ div()
+ .w(px(TRACK_GUTTER))
+ .flex_none()
+ .flex()
+ .items_center()
+ .pl(px(10.))
+ .text_size(px(12.))
+ .child("Clip"),
+ )
+ .child(
+ div()
+ .flex_1()
+ .m(px(8.))
+ .rounded(px(6.))
+ .bg(Hsla::from(theme.editor.ctl_hover)),
+ ),
+ );
+ }
+ let mut veil = theme.editor.card;
+ veil.a = 0.88;
+ let mut edge = theme.editor.card;
+ edge.a = 0.35;
+ let mut clear = theme.editor.card;
+ clear.a = 0.0;
+ div()
+ .size_full()
+ .min_h_0()
+ .flex()
+ .flex_col()
+ .relative()
+ .overflow_hidden()
+ .pt(px(TIMELINE_TOP_PADDING))
+ .px(px(TIMELINE_PADDING))
+ .pb(px(TIMELINE_BOTTOM_PADDING))
+ .gap(px(TIMELINE_HEADER_GAP))
+ .child(
+ div()
+ .relative()
+ .h(px(TIMELINE_HEADER_HEIGHT))
+ .flex_none()
+ .children(known_duration.map(|_| render_ruler(theme, view, viewport_width)))
+ .child(
+ div()
+ .absolute()
+ .left(px(4.))
+ .bottom_0()
+ .text_size(px(12.))
+ .text_color(Hsla::from(theme.editor.text_3))
+ .child("Timeline"),
+ ),
+ )
+ .child(
+ div()
+ .relative()
+ .flex_1()
+ .min_h_0()
+ .overflow_hidden()
+ .child(rows)
+ .children((frontier < content_width).then(|| {
+ div()
+ .absolute()
+ .top_0()
+ .bottom_0()
+ .left(px(TRACK_GUTTER + frontier))
+ .right_0()
+ .bg(gpui::linear_gradient(
+ 90.,
+ gpui::linear_color_stop(edge, 0.),
+ gpui::linear_color_stop(veil, 1.),
+ ))
+ .child(div().absolute().left_0().top_0().bottom_0().w(px(20.)).bg(
+ gpui::linear_gradient(
+ 90.,
+ gpui::linear_color_stop(clear, 0.),
+ gpui::linear_color_stop(veil, 1.),
+ ),
+ ))
+ })),
+ )
+ .child(render_playhead(
+ theme,
+ playhead_offset(view, content_width),
+ 0.65,
+ ))
+ .into_any_element()
+}
+
+#[cfg(test)]
+mod preparing_frontier_tests {
+ use super::*;
+
+ #[test]
+ fn confirmed_boundary_stays_inside_visible_timeline() {
+ let mut view = TimelineView::default();
+ view.transform.zoom = 20.0;
+ view.transform.position = 10.0;
+ assert_eq!(preparing_frontier_offset(5.0, view, 400.0), 0.0);
+ assert_eq!(preparing_frontier_offset(20.0, view, 400.0), 200.0);
+ assert_eq!(preparing_frontier_offset(35.0, view, 400.0), 400.0);
+ assert_eq!(preparing_frontier_offset(f64::NAN, view, 400.0), 0.0);
+ assert_eq!(preparing_frontier_offset(20.0, view, 0.0), 0.0);
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_timeline/playback_follow.rs b/apps/desktop-gpui/src/editor_timeline/playback_follow.rs
index e587f6035..9fca91066 100644
--- a/apps/desktop-gpui/src/editor_timeline/playback_follow.rs
+++ b/apps/desktop-gpui/src/editor_timeline/playback_follow.rs
@@ -6,12 +6,14 @@ use super::Transform;
pub struct PlaybackFollow {
previous: Option<Transform>,
resume_at: Option<Instant>,
+ follow_offset: Option<f64>,
}
impl PlaybackFollow {
pub fn reset(&mut self) {
self.previous = None;
self.resume_at = None;
+ self.follow_offset = None;
}
pub fn update(
@@ -24,6 +26,7 @@ impl PlaybackFollow {
) {
if interacting || self.previous.is_some_and(|previous| previous != *transform) {
self.resume_at = Some(now + Duration::from_secs(1));
+ self.follow_offset = None;
}
if self.resume_at.is_none_or(|resume_at| now >= resume_at)
&& transform.position.is_finite()
@@ -33,14 +36,25 @@ impl PlaybackFollow {
&& transform.zoom > 0.
&& duration > 0.
{
+ let follow_offset = *self.follow_offset.get_or_insert_with(|| {
+ if playhead >= transform.position && playhead <= transform.position + transform.zoom
+ {
+ (transform.zoom * 0.8).max(playhead - transform.position)
+ } else {
+ transform.zoom * 0.8
+ }
+ });
let position = if playhead < transform.position {
playhead - transform.zoom * 0.2
- } else if playhead > transform.position + transform.zoom * 0.8 {
- playhead - transform.zoom * 0.8
+ } else if playhead > transform.position + follow_offset {
+ playhead - follow_offset
} else {
transform.position
};
- transform.position = position.clamp(0., (duration - transform.zoom).max(0.));
+ transform.position = position.clamp(
+ 0.,
+ (duration - transform.zoom).max(transform.position).max(0.),
+ );
}
self.previous = Some(*transform);
}
@@ -50,6 +64,89 @@ impl PlaybackFollow {
mod tests {
use super::*;
+ #[test]
+ fn playback_follow_starts_from_a_visible_playhead_without_jumping() {
+ for start in [28.1, 29., 30.] {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 20.,
+ zoom: 10.,
+ };
+ let now = Instant::now();
+ for frame in 0..=120 {
+ let elapsed = f64::from(frame) / 60.;
+ follow.update(
+ &mut transform,
+ start + elapsed,
+ 60.,
+ now + Duration::from_secs_f64(elapsed),
+ false,
+ );
+ assert!((transform.position - (20. + elapsed)).abs() < 1e-9);
+ }
+ }
+ }
+
+ #[test]
+ fn playback_follow_preserves_a_visible_playhead_after_pause_and_seek() {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 0.,
+ zoom: 10.,
+ };
+ let now = Instant::now();
+ follow.update(&mut transform, 8., 60., now, false);
+ follow.reset();
+ transform.position = 20.;
+ follow.update(&mut transform, 29., 60., now, false);
+ assert_eq!(transform.position, 20.);
+ follow.update(&mut transform, 29.1, 60., now, false);
+ assert!((transform.position - 20.1).abs() < 1e-9);
+ }
+
+ #[test]
+ fn playback_follow_preserves_manual_trailing_space() {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 54.,
+ zoom: 10.,
+ };
+ for playhead in [55., 58., 60.] {
+ follow.update(&mut transform, playhead, 60., Instant::now(), false);
+ assert_eq!(transform.position, 54.);
+ }
+ }
+
+ #[test]
+ fn playback_follow_resumes_after_panning_without_jumping() {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 0.,
+ zoom: 10.,
+ };
+ let now = Instant::now();
+ follow.update(&mut transform, 8., 60., now, false);
+ transform.position = 1.;
+ follow.update(&mut transform, 9., 60., now, false);
+ assert_eq!(transform.position, 1.);
+ follow.update(
+ &mut transform,
+ 10.,
+ 60.,
+ now + Duration::from_secs(1),
+ false,
+ );
+ assert_eq!(transform.position, 1.);
+ follow.update(
+ &mut transform,
+ 10.1,
+ 60.,
+ now + Duration::from_millis(1100),
+ false,
+ );
+ assert!((transform.position - 1.1).abs() < 1e-9);
+ }
+
#[test]
fn playback_follow_stays_still_then_tracks_at_playback_speed() {
let mut follow = PlaybackFollow::default();
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs
index 1c652b712..c430f9767 100644
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@ -757,9 +757,6 @@ impl Render for EditorSectionView {
return div().into_any_element();
};
editor.update(cx, |editor, cx| {
- if !editor.project_ready() && !matches!(self.section, EditorSection::Header) {
- return div().size_full().into_any_element();
- }
match self.section {
EditorSection::Header => editor.render_header(window, cx).into_any_element(),
EditorSection::Toolbar => {
@@ -770,6 +767,9 @@ impl Render for EditorSectionView {
// clips sidebar; the config sidebar is hidden, not destroyed
// (`Editor.tsx:728-747`).
EditorSection::Sidebar => {
+ if !editor.project_ready() {
+ return editor.render_preparing_sidebar().into_any_element();
+ }
if editor.clips.open {
editor.render_clips_sidebar(cx).into_any_element()
} else {
@@ -1116,6 +1116,9 @@ pub async fn run_transport(instance: Arc<EditorInstance>, driver: TransportDrive
break;
}
let active = *active_rx.borrow_and_update();
+ if active && instance.preparing_adoption().is_some() {
+ applied_playing = true;
+ }
// A false while this driver believes it is playing is an
// engine-initiated stop: the driver marks the engine gone and
// tells the window, which answers through its ordinary pause
@@ -1191,8 +1194,17 @@ pub async fn run_transport(instance: Arc<EditorInstance>, driver: TransportDrive
}
if want.playing && !applied_playing {
- instance.start_playback(fps, want.resolution).await;
- applied_playing = true;
+ match instance
+ .start_playback_with_handle(fps, want.resolution, None)
+ .await
+ {
+ Ok(_) => applied_playing = true,
+ Err(error) => {
+ tracing::warn!(?error, "Editor playback could not start");
+ applied_playing = false;
+ let _ = driver.engine_stopped.try_send(());
+ }
+ }
}
}
}
@@ -1372,6 +1384,17 @@ pub struct EditorWindow {
pub(crate) theme: Theme,
pub(crate) project_path: PathBuf,
state: LoadState,
+ preparing_consumer: Option<crate::editor_preparing::PreparingConsumer>,
+ preparing_candidate_frame: Option<u32>,
+ preparing_retry_pending: bool,
+ preparing_sequence: u64,
+ preparing_presentation: Option<crate::editor_preparing::presentation::PreparingPresentation>,
+ ordinary_handoff_frame: Option<u32>,
+ #[cfg(debug_assertions)]
+ preparing_auto_played: bool,
+ #[cfg(debug_assertions)]
+ preparing_frame_presented: bool,
+ preparing_seed: Option<Arc<crate::editor_preparing::presentation::PreparingTimelineSeed>>,
pub(crate) latest_frame: Option<EditorPreviewFrame>,
/// The bundle's `screenshots/display.jpg`, letterboxed into the canvas
/// until the first composed frame lands -- decoded in parallel with
@@ -1592,6 +1615,7 @@ pub struct EditorWindow {
preset_dialog: Option<PresetDialog>,
caption_sync_signature: Option<u64>,
pub(crate) export: Option<ExportUi>,
+ pub(crate) sharing: Option<cap_project::SharingMeta>,
/// The Clips layout mode (`ClipsSidebar.tsx`): while open, the config
/// sidebar's column draws the clips sidebar instead.
pub(crate) clips: crate::editor_clips::ClipsState,
@@ -1816,8 +1840,22 @@ impl EditorWindow {
// routes, and `is_transparent()` (`windows.rs:1069-1082`) does not
// list Editor. The root paints `bg-gray-2 dark:bg-gray-1`.
theme: Theme::for_window(window, cx, false),
+ sharing: RecordingMeta::load_for_project(&project_path)
+ .ok()
+ .and_then(|meta| meta.sharing),
project_path,
state: LoadState::Loading,
+ preparing_consumer: None,
+ preparing_candidate_frame: None,
+ preparing_retry_pending: false,
+ preparing_sequence: 0,
+ preparing_presentation: None,
+ ordinary_handoff_frame: None,
+ #[cfg(debug_assertions)]
+ preparing_auto_played: false,
+ #[cfg(debug_assertions)]
+ preparing_frame_presented: false,
+ preparing_seed: None,
latest_frame: None,
preview,
header,
@@ -1980,7 +2018,9 @@ impl EditorWindow {
// (`ED/context.ts:1455`), so it is set the moment a duration exists --
// the on-mount 80px fit then narrows it on the first render that knows
// the timeline's width.
- self.view.transform = Transform::initial(summary.duration);
+ if self.preparing_presentation.is_none() {
+ self.view.transform = Transform::initial(summary.duration);
+ }
self.name_input.update(cx, |input, cx| {
input.set_text(summary.pretty_name.clone(), cx);
input.set_disabled(false, cx);
@@ -2346,6 +2386,7 @@ impl EditorWindow {
pub fn set_error(&mut self, message: String, window: &mut Window, cx: &mut Context<Self>) {
tracing::error!(path = %self.project_path.display(), "editor project failed to open: {message}");
+ self.cancel_preparing();
self.state = LoadState::Failed(message);
cx.notify();
window.refresh();
@@ -2373,7 +2414,257 @@ impl EditorWindow {
&self.project
}
+ pub(crate) fn begin_preparing(&mut self, consumer: crate::editor_preparing::PreparingConsumer) {
+ self.preparing_sequence = 0;
+ #[cfg(debug_assertions)]
+ {
+ self.preparing_auto_played = false;
+ self.preparing_frame_presented = false;
+ }
+ self.preparing_presentation = Some(Default::default());
+ self.preparing_consumer = Some(consumer);
+ }
+
+ pub(crate) fn cancel_preparing(&mut self) {
+ drop(self.preparing_consumer.take());
+ if self.preparing_presentation.take().is_some() {
+ self.playing = false;
+ self.view.playing = false;
+ }
+ self.preparing_seed = None;
+ self.ordinary_handoff_frame = None;
+ }
+
+ pub(crate) fn finish_preparing(
+ &mut self,
+ joined: &crate::editor_preparing::PreparingJoined,
+ ) -> bool {
+ if !self
+ .preparing_consumer
+ .as_ref()
+ .is_some_and(|consumer| joined.matches(consumer))
+ {
+ return false;
+ }
+ if let Some(presentation) = &mut self.preparing_presentation {
+ if let Some(exit) = &joined.exit
+ && let Some(sequence) = exit.snapshot.sequence.checked_add(2)
+ {
+ presentation.apply(
+ sequence,
+ exit.snapshot.progress.clone(),
+ exit.snapshot.playback,
+ );
+ }
+ presentation.handoff();
+ self.playhead = presentation.playback.playhead_seconds;
+ self.view.playhead = self.playhead;
+ self.playing = false;
+ self.view.playing = false;
+ }
+ drop(self.preparing_consumer.take());
+ true
+ }
+
+ fn preparing_transport_active(&self) -> bool {
+ self.preparing_consumer.is_some()
+ && self
+ .instance
+ .as_ref()
+ .and_then(|instance| instance.preparing_adoption())
+ .is_none_or(|adoption| !adoption.is_owner())
+ }
+
+ fn preparing_controls_ready(&self) -> bool {
+ self.preparing_consumer
+ .as_ref()
+ .is_some_and(|consumer| consumer.can_command())
+ && self
+ .preparing_presentation
+ .as_ref()
+ .is_some_and(|presentation| presentation.controls_ready())
+ }
+
+ fn preparing_command(&self, seek: Option<f64>, playing: Option<bool>) -> bool {
+ self.preparing_consumer.as_ref().is_some_and(|consumer| {
+ consumer.command(crate::editor_preparing::PreparingCommand { seek, playing })
+ })
+ }
+
+ pub(crate) fn preparing_progress_arrived(
+ &mut self,
+ update: crate::editor_preparing::PreparingUpdate,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if (self.project_ready() && !self.preparing_transport_active())
+ || !self
+ .preparing_consumer
+ .as_ref()
+ .is_some_and(|consumer| consumer.accepts_status(&update))
+ {
+ return;
+ }
+ let Some(presentation) = &mut self.preparing_presentation else {
+ return;
+ };
+ let previous_playback = presentation.playback;
+ if !presentation.apply(update.sequence, update.progress, update.playback) {
+ return;
+ }
+ if previous_playback.playing != presentation.playback.playing
+ || previous_playback.buffering != presentation.playback.buffering
+ {
+ tracing::debug!(
+ playing = presentation.playback.playing,
+ buffering = presentation.playback.buffering,
+ playhead = presentation.playback.playhead_seconds,
+ playable_until = presentation.progress.playable_until,
+ "GPUI preparing playback state"
+ );
+ }
+ let initial_duration = self.total <= 0.0;
+ self.total = presentation.progress.total_duration.unwrap_or(0.0);
+ self.playhead = presentation.playback.playhead_seconds;
+ self.playing = presentation.playback.playing;
+ self.view.playhead = self.playhead;
+ self.view.playing = self.playing;
+ if !self
+ .preparing_seed
+ .as_ref()
+ .is_some_and(|seed| Arc::ptr_eq(seed, &update.seed))
+ {
+ self.has_camera = update.seed.has_camera;
+ self.multiple_clips = update.seed.multiple_clips;
+ self.timeline =
+ TimelineModel::build(&update.seed.project, self.has_camera, self.multiple_clips);
+ self.name_input.update(cx, |input, cx| {
+ input.set_text(update.seed.pretty_name.clone(), cx)
+ });
+ self.preparing_seed = Some(update.seed);
+ }
+ if initial_duration && self.total > 0.0 {
+ self.view.transform = Transform::initial(self.total);
+ self.fitted = false;
+ }
+ if self.preparing_sequence > 0 {
+ presentation.progress.preview_available = true;
+ }
+ #[cfg(debug_assertions)]
+ self.drive_auto_preparing_playback(window, cx);
+ self.retry_preparing_candidate(window, cx);
+ cx.notify();
+ window.refresh();
+ }
+
+ pub(crate) fn initial_frame_number(&self) -> u32 {
+ self.preparing_presentation.as_ref().map_or(
+ (self.playhead * f64::from(EDITOR_PREVIEW_FPS)).round() as u32,
+ |presentation| presentation.handoff_frame(self.total_duration(), EDITOR_PREVIEW_FPS),
+ )
+ }
+
+ pub(crate) fn preparing_frame_arrived(
+ &mut self,
+ epoch: &crate::editor_preparing::PreparingEpoch,
+ identity: &cap_recording::recovery::PreparingStudioIdentity,
+ sequence: u64,
+ frame: EditorFrame,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if (self.project_ready() && !self.preparing_transport_active())
+ || self.preparing_candidate_frame.is_some()
+ || sequence <= self.preparing_sequence
+ || !self
+ .preparing_consumer
+ .as_ref()
+ .is_some_and(|consumer| consumer.accepts(epoch, identity))
+ {
+ return;
+ }
+ self.preparing_sequence = sequence;
+ if let Some(presentation) = &mut self.preparing_presentation {
+ presentation.progress.preview_available = true;
+ }
+ self.display_frame(frame, false, window, cx);
+ let epoch = epoch.clone();
+ let identity = identity.clone();
+ cx.on_next_frame(window, move |this, window, cx| {
+ tracing::info!("Preparing composed frame reached presentation cycle");
+ if !this
+ .preparing_consumer
+ .as_ref()
+ .is_some_and(|consumer| consumer.accepts(&epoch, &identity))
+ {
+ return;
+ }
+ #[cfg(debug_assertions)]
+ {
+ this.preparing_frame_presented = true;
+ this.drive_auto_preparing_playback(window, cx);
+ }
+ #[cfg(not(debug_assertions))]
+ let _ = (window, cx);
+ });
+ window.refresh();
+ }
+
+ #[cfg(debug_assertions)]
+ fn drive_auto_preparing_playback(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.preparing_auto_played
+ || !self.preparing_frame_presented
+ || !self.preparing_controls_ready()
+ || !std::env::var("CAP_GPUI_AUTO_PREPARING_PLAY").is_ok_and(|value| value == "1")
+ {
+ return;
+ }
+ self.preparing_auto_played = true;
+ tracing::info!("auto preparing playback requested");
+ self.toggle_play(window, cx);
+ }
+
+ pub(crate) fn is_instance(&self, instance: &Arc<EditorInstance>) -> bool {
+ self.instance
+ .as_ref()
+ .is_some_and(|current| Arc::ptr_eq(current, instance))
+ }
+
+ fn retry_preparing_candidate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.preparing_retry_pending {
+ return;
+ }
+ let Some(instance) = self
+ .instance
+ .as_ref()
+ .filter(|instance| {
+ instance
+ .preparing_adoption()
+ .is_some_and(|adoption| adoption.invalidated())
+ })
+ .cloned()
+ else {
+ return;
+ };
+ let Some(handle) = window.window_handle().downcast::<Self>() else {
+ return;
+ };
+ self.preparing_retry_pending = true;
+ self.preparing_candidate_frame = None;
+ let path = self.project_path.clone();
+ cx.defer(move |cx| crate::app_windows::retry_preparing_editor(path, handle, instance, cx));
+ }
+
pub fn set_instance(&mut self, instance: Arc<EditorInstance>) {
+ self.preparing_retry_pending = false;
+ self.preparing_candidate_frame = None;
+ self.ordinary_handoff_frame = self
+ .preparing_presentation
+ .as_ref()
+ .map(|_| self.initial_frame_number());
+ if instance.preparing_adoption().is_some() {
+ self.ordinary_handoff_frame = None;
+ }
self.instance = Some(instance);
}
@@ -2397,8 +2688,36 @@ impl EditorWindow {
if total > 0.0 {
self.total = total;
}
+ let initial_frame = self.initial_frame_number();
+ self.ordinary_handoff_frame = self.preparing_presentation.as_ref().map(|_| initial_frame);
+ self.playhead = self.preparing_presentation.as_ref().map_or(
+ f64::from(initial_frame) / f64::from(EDITOR_PREVIEW_FPS),
+ |presentation| {
+ presentation
+ .playback
+ .playhead_seconds
+ .clamp(0.0, self.total_duration())
+ },
+ );
+ self.view.playhead = self.playhead;
if let Some(instance) = &self.instance {
- request_frame(instance, 0, self.preview_resolution());
+ if instance.preparing_adoption().is_some() {
+ self.ordinary_handoff_frame = None;
+ let instance = instance.clone();
+ let resolution = self.preview_resolution();
+ gpui_tokio::Tokio::spawn(cx, async move {
+ match instance
+ .start_preparing_handoff(EDITOR_PREVIEW_FPS, resolution)
+ .await
+ {
+ Ok(true) => {}
+ _ => request_frame(&instance, initial_frame, resolution),
+ }
+ })
+ .detach();
+ } else {
+ request_frame(instance, initial_frame, self.preview_resolution());
+ }
}
cx.notify();
window.refresh();
@@ -2463,8 +2782,15 @@ impl EditorWindow {
/// (`ClipsSidebar.tsx:508-511`).
pub(crate) fn stop_playback(&mut self, cx: &mut Context<Self>) {
self.playback_follow.reset();
+ if self.preparing_transport_active() {
+ self.preparing_command(None, Some(false));
+ return;
+ }
if let Some(transport) = &self.transport {
transport.pause();
+ if let Some(presentation) = &mut self.preparing_presentation {
+ presentation.playback.playing = false;
+ }
}
if self.playing {
self.playing = false;
@@ -2480,6 +2806,10 @@ impl EditorWindow {
/// pressed it twice. Runs the ordinary pause path so `Desired` stays
/// UI-owned and the run's stats still get reported.
pub fn engine_stopped(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.preparing_transport_active() {
+ self.retry_preparing_candidate(window, cx);
+ return;
+ }
if !self.playing {
return;
}
@@ -2492,6 +2822,9 @@ impl EditorWindow {
let Some(transport) = &self.transport else {
return;
};
+ self.ordinary_handoff_frame = None;
+ self.preparing_presentation = None;
+ self.preparing_seed = None;
self.playback_follow.reset();
// `Math.floor(editorState.playbackTime * FPS)`.
let frame = (from.max(0.0) * EDITOR_PREVIEW_FPS as f64).floor() as u32;
@@ -2562,7 +2895,23 @@ impl EditorWindow {
/// `handlePlayPauseClick` (`Player.tsx:212-233`), verbatim: at the end,
/// restart from 0; playing, stop; otherwise seek to the playhead and go.
pub fn toggle_play(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
- if self.transport.is_none() {
+ if self.preparing_transport_active() {
+ if self.preparing_controls_ready() {
+ let seek = self.is_at_end().then_some(0.0);
+ self.preparing_command(seek, Some(!self.playing));
+ }
+ return;
+ }
+ if self.ordinary_handoff_frame.is_some() {
+ let at_end = self.is_at_end();
+ let target = self
+ .preparing_presentation
+ .as_mut()
+ .and_then(|presentation| presentation.toggle_handoff_playback(at_end));
+ if let Some(target) = target {
+ self.seek_to_time(target, cx);
+ }
+ cx.notify();
return;
}
if self.is_at_end() {
@@ -2581,13 +2930,34 @@ impl EditorWindow {
/// (`PlaybackHandle::seek`), so a scrub during playback holds the last
/// picture for one decode instead of paying a warmup per tick.
pub fn seek_to_time(&mut self, time: f64, cx: &mut Context<Self>) {
+ if self.preparing_transport_active() {
+ self.preparing_command(Some(time), None);
+ return;
+ }
let Some(transport) = &self.transport else {
+ if let Some(target) = self
+ .preparing_presentation
+ .as_ref()
+ .and_then(|presentation| presentation.seek_target(time, EDITOR_PREVIEW_FPS))
+ {
+ self.preparing_command(Some(target), None);
+ }
return;
};
let time = time.clamp(0.0, self.total_duration());
// `Math.round(newTime * FPS)` -- "round to nearest frame to prevent
// off-by-one drift".
- let frame = (time * EDITOR_PREVIEW_FPS as f64).round() as u32;
+ let mut frame = (time * EDITOR_PREVIEW_FPS as f64).round() as u32;
+ if self.ordinary_handoff_frame.is_some() {
+ frame = frame.min(
+ ((self.total_duration() * f64::from(EDITOR_PREVIEW_FPS)).ceil() as u32)
+ .saturating_sub(1),
+ );
+ self.ordinary_handoff_frame = Some(frame);
+ if let Some(presentation) = &mut self.preparing_presentation {
+ presentation.playback.playhead_seconds = time;
+ }
+ }
if self.playing {
// A live seek re-anchors the engine's clock at the target, and
// the drawn line re-anchors with it: the engine's immediate
@@ -2610,12 +2980,26 @@ impl EditorWindow {
/// timeline transform back to the start. **Not** a frame step -- neither
/// transport button is one in the Tauri editor.
pub fn jump_to_start(&mut self, cx: &mut Context<Self>) {
+ if self.preparing_transport_active() && self.preparing_controls_ready() {
+ self.preparing_command(Some(0.0), Some(false));
+ return;
+ }
self.stop_playback(cx);
self.seek_to_time(0.0, cx);
}
/// The next button (`Player.tsx:395-405`): stop, playhead to the end.
pub fn jump_to_end(&mut self, cx: &mut Context<Self>) {
+ if self.preparing_transport_active() && self.preparing_controls_ready() {
+ if let Some(target) = self
+ .preparing_presentation
+ .as_ref()
+ .and_then(|presentation| presentation.last_playable_frame_time(EDITOR_PREVIEW_FPS))
+ {
+ self.preparing_command(Some(target), Some(false));
+ }
+ return;
+ }
self.stop_playback(cx);
let total = self.total_duration();
self.seek_to_time(total, cx);
@@ -5386,6 +5770,48 @@ impl EditorWindow {
window: &mut Window,
cx: &mut Context<Self>,
) {
+ self.display_frame(frame, true, window, cx);
+ }
+
+ fn display_frame(
+ &mut self,
+ frame: EditorFrame,
+ ordinary: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let adoption = ordinary
+ .then(|| {
+ self.instance
+ .as_ref()
+ .and_then(|instance| instance.preparing_adoption())
+ })
+ .flatten()
+ .filter(|adoption| !adoption.is_owner());
+ if let Some(adoption) = &adoption {
+ if adoption.invalidated() {
+ self.retry_preparing_candidate(window, cx);
+ return;
+ }
+ let Some(snapshot) = adoption.snapshot() else {
+ return;
+ };
+ let current =
+ (snapshot.playback.playhead_seconds * f64::from(EDITOR_PREVIEW_FPS)).floor() as u32;
+ if frame.number < current.saturating_sub(2) || frame.number > current.saturating_add(1)
+ {
+ return;
+ }
+ self.preparing_candidate_frame = Some(frame.number);
+ }
+ let candidate_number = frame.number;
+ if self
+ .ordinary_handoff_frame
+ .is_some_and(|target| frame.number != target)
+ {
+ return;
+ }
+ let handoff_target = self.transport.as_ref().and(self.ordinary_handoff_frame);
let first_frame = self.latest_frame.is_none();
let layout_changed = self.frame_layout != Some(frame.layout);
if self.frame_layout.map(|layout| layout.output_size) != Some(frame.layout.output_size) {
@@ -5439,6 +5865,43 @@ impl EditorWindow {
if !window.is_window_active() && (first_frame || !self.playing) {
window.refresh();
}
+ if let Some(adoption) = adoption {
+ cx.on_next_frame(window, move |this, window, cx| {
+ if this.preparing_candidate_frame != Some(candidate_number) {
+ return;
+ }
+ this.preparing_candidate_frame = None;
+ if adoption.try_commit(candidate_number, EDITOR_PREVIEW_FPS) {
+ this.preparing_presentation = None;
+ this.preparing_seed = None;
+ this.ordinary_handoff_frame = None;
+ drop(this.preparing_consumer.take());
+ } else {
+ this.retry_preparing_candidate(window, cx);
+ }
+ cx.notify();
+ window.refresh();
+ });
+ window.refresh();
+ } else if let Some(target) = handoff_target {
+ cx.on_next_frame(window, move |this, window, cx| {
+ if this.ordinary_handoff_frame != Some(target) {
+ return;
+ }
+ this.ordinary_handoff_frame = None;
+ let resume = this
+ .preparing_presentation
+ .take()
+ .is_some_and(|presentation| presentation.playback.playing);
+ this.preparing_seed = None;
+ if resume {
+ this.start_playback(this.playhead, cx);
+ }
+ cx.notify();
+ window.refresh();
+ });
+ window.refresh();
+ }
}
fn sync_appearance(&mut self, window: &Window, cx: &gpui::App) {
@@ -5482,6 +5945,9 @@ impl EditorWindow {
}
fn commit_pretty_name(&mut self, cx: &mut Context<Self>) -> Result<(), String> {
+ if !self.project_ready() {
+ return Ok(());
+ }
let Some(stored) = self.summary().map(|summary| summary.pretty_name.clone()) else {
return Ok(());
};
@@ -8086,6 +8552,9 @@ impl EditorWindow {
.then(|| self.header_pill("icons/captions.svg", "Captions", compact)),
)
.child(div().w(px(6.)).flex_none())
+ .when(self.sharing.is_some(), |group| {
+ group.child(self.render_reupload_button(cx))
+ })
.child(self.render_export_button(cx)),
);
@@ -8223,6 +8692,78 @@ impl EditorWindow {
)
}
+ fn render_preparing_sidebar(&self) -> impl IntoElement {
+ let theme = self.theme;
+ let project = self
+ .preparing_seed
+ .as_ref()
+ .map_or(&self.project, |seed| &seed.project);
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .rounded(px(12.))
+ .border_1()
+ .border_color(self.card_line())
+ .bg(self.panel_bg())
+ .overflow_hidden()
+ .child(
+ div()
+ .flex()
+ .flex_row()
+ .items_center()
+ .justify_between()
+ .px(px(10.))
+ .h(px(44.))
+ .flex_none()
+ .children(
+ crate::editor_sidebar::SidebarTab::ALL
+ .into_iter()
+ .map(|tab| {
+ div()
+ .size(px(28.))
+ .flex()
+ .items_center()
+ .justify_center()
+ .opacity(0.45)
+ .child(
+ svg()
+ .path(tab.icon())
+ .size(px(15.))
+ .text_color(Hsla::from(theme.editor.text_2)),
+ )
+ }),
+ ),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .p(px(16.))
+ .gap(px(16.))
+ .text_size(px(12.))
+ .child(
+ div()
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(Hsla::from(theme.editor.text_1))
+ .child("Background"),
+ )
+ .child(
+ div()
+ .flex()
+ .justify_between()
+ .text_color(Hsla::from(theme.editor.text_3))
+ .child("Aspect ratio")
+ .child(Self::aspect_ratio_label(project.aspect_ratio.as_ref())),
+ )
+ .child(
+ div()
+ .text_color(Hsla::from(theme.editor.text_3))
+ .child("Editing is available when your recording is ready."),
+ ),
+ )
+ }
+
/// The player's top row: the stage's own triggers on the left, the
/// preview-resolution control on the right.
fn render_player_toolbar(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
@@ -8271,9 +8812,16 @@ impl EditorWindow {
.text(&theme)
.left_icon("icons/layout.svg")
.when(!narrow, |button| {
- button.label(Self::aspect_ratio_label(self.project.aspect_ratio.as_ref()))
+ button.label(Self::aspect_ratio_label(
+ self.preparing_seed
+ .as_ref()
+ .map_or(&self.project, |seed| &seed.project)
+ .aspect_ratio
+ .as_ref(),
+ ))
})
.tooltip(&theme, "Aspect Ratio")
+ .disabled(!self.project_ready())
.pressed(
self.toolbar_menu
.as_ref()
@@ -8291,6 +8839,7 @@ impl EditorWindow {
.left_icon("icons/crop.svg")
.when(!narrow, |button| button.label("Crop"))
.tooltip(&theme, "Crop Video")
+ .disabled(!self.project_ready())
.pressed(self.crop.is_some())
.on_click(cx.listener(|this, _, window, cx| {
this.open_crop(window, cx);
@@ -8349,9 +8898,11 @@ impl EditorWindow {
}
})
.child(quality.label())
- .on_click(cx.listener(move |this, _, _window, cx| {
- this.set_preview_quality(quality, cx);
- }))
+ .when(self.project_ready(), |button| {
+ button.on_click(cx.listener(move |this, _, _window, cx| {
+ this.set_preview_quality(quality, cx);
+ }))
+ })
}))
}
@@ -8413,10 +8964,33 @@ impl EditorWindow {
.overflow_hidden()
.bg(Hsla::from(theme.editor.card))
.child(body)
+ .children(
+ (!self.project_ready() && self.latest_frame.is_some()).then(|| {
+ div()
+ .absolute()
+ .bottom(px(12.))
+ .left(px(12.))
+ .px(px(10.))
+ .py(px(6.))
+ .rounded(px(6.))
+ .bg(Hsla::from(theme.editor.card))
+ .text_size(px(12.))
+ .text_color(Hsla::from(theme.editor.text_2))
+ .child(if self.preparing_consumer.is_some() {
+ "Preparing recording…"
+ } else {
+ "Opening editor…"
+ })
+ }),
+ )
// `CanvasElementsOverlay` + `SnapGuidesOverlay`
// (`Player.tsx:636-643`), both mounted inside the letterbox
// wrapper and only while a frame exists.
- .children(self.render_canvas_overlay(cx))
+ .children(if self.project_ready() {
+ self.render_canvas_overlay(cx)
+ } else {
+ None
+ })
}
/// `EditorErrorScreen` -- what a bundle that will not open shows instead of
@@ -8546,7 +9120,7 @@ impl EditorWindow {
// (`Player.tsx:359-365`) -- the clock reads the *hover* time when there
// is one, which is what makes it a readout for the ghost playhead.
let current = self.view.preview_time.unwrap_or(self.playhead).max(0.0);
- let live = self.transport.is_some();
+ let live = self.transport.is_some() || self.preparing_controls_ready();
// `{!editorState.playing || isAtEnd() ? <IconCapPlay/> :
// <IconCapPause/>}` (`Player.tsx:388-392`).
let icon = if !self.playing || self.is_at_end() {
@@ -8606,7 +9180,11 @@ impl EditorWindow {
.text_color(Hsla::from(editor.text_3))
.child(SharedString::from(format!(
" / {}",
- timeline::format_time(total)
+ if total > 0.0 {
+ timeline::format_time(total)
+ } else {
+ "--:--".into()
+ }
)))
})),
)
@@ -8649,6 +9227,7 @@ impl EditorWindow {
.icon_size(px(12.))
.color(Hsla::from(editor.card))
.filled(Hsla::from(editor.text_1), None)
+ .disabled(!live)
.hover_bg(Hsla::from(crate::theme::mix(
editor.text_1,
editor.card,
@@ -8679,6 +9258,7 @@ impl EditorWindow {
ui::EditorButton::plain(&theme, "transport-split")
.left_icon("icons/scissors.svg")
.tooltip(&theme, "Toggle Split")
+ .disabled(!self.project_ready())
.pressed(self.split_mode)
.on_click(cx.listener(|this, _, window, cx| {
this.toggle_split_mode(cx);
@@ -8734,6 +9314,30 @@ impl EditorWindow {
cx: &mut Context<Self>,
) -> impl IntoElement {
let theme = self.theme;
+ if !self.project_ready() {
+ return div()
+ .size_full()
+ .child(timeline::render_preparing_timeline(
+ &theme,
+ &self.timeline,
+ self.view,
+ viewport_width,
+ self.preparing_presentation
+ .as_ref()
+ .map(|presentation| &presentation.progress),
+ ))
+ .when(self.preparing_controls_ready(), |timeline| {
+ timeline.on_mouse_down(
+ MouseButton::Left,
+ cx.listener(move |this, event: &MouseDownEvent, _window, cx| {
+ let time = this.time_at(f32::from(event.position.x), viewport_width);
+ this.seek_to_time(time, cx);
+ cx.stop_propagation();
+ }),
+ )
+ })
+ .into_any_element();
+ }
let content_width = timeline::content_width(viewport_width);
let live = self.transport.is_some();
@@ -8895,6 +9499,7 @@ impl EditorWindow {
as f32;
x.is_finite().then(|| render_split_preview(&theme, x, true))
}))
+ .into_any_element()
}
/// The 26px header strip (`TL/index.tsx:1220-1245`): the ruler, the "Add
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index a3b6abe96..6771d8b12 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -30,6 +30,7 @@ mod editor_export;
#[cfg(target_os = "linux")]
mod editor_modal;
mod editor_panels;
+mod editor_preparing;
mod editor_sidebar;
mod editor_tabs;
mod editor_timeline;
@@ -505,7 +506,16 @@ fn main() {
});
})
.detach();
- #[cfg(not(target_os = "macos"))]
+ #[cfg(target_os = "windows")]
+ cx.spawn(async move |_| {
+ if let Some(native) = native_main
+ && let Err(error) = platform::install_main_window_frame_policy(&native)
+ {
+ tracing::warn!(%error, "could not install Main window frame policy");
+ }
+ })
+ .detach();
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
let _ = native_main;
// `CAP_GPUI_DEBUG_LIGHTS=1`: poll the main window's style mask and
diff --git a/apps/desktop-gpui/src/platform/windows.rs b/apps/desktop-gpui/src/platform/windows.rs
index d7e81fbff..9e3bed11b 100644
--- a/apps/desktop-gpui/src/platform/windows.rs
+++ b/apps/desktop-gpui/src/platform/windows.rs
@@ -16,6 +16,7 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{
use super::{ForcedAppearance, MaterialKind, PanelBehavior};
mod capture_exclusion;
+mod hidden_frame;
#[derive(Clone, Copy)]
pub struct NativeWindow(isize);
@@ -63,6 +64,10 @@ pub fn native_window(window: &Window) -> Option<NativeWindow> {
native_handle(window).map(NativeWindow)
}
+pub fn install_main_window_frame_policy(native: &NativeWindow) -> std::io::Result<()> {
+ hidden_frame::install(native.hwnd())
+}
+
#[link(name = "dwmapi")]
unsafe extern "system" {
fn DwmSetWindowAttribute(hwnd: HWND, attribute: u32, value: *const c_void, size: u32) -> i32;
diff --git a/apps/desktop-gpui/src/platform/windows/hidden_frame.rs b/apps/desktop-gpui/src/platform/windows/hidden_frame.rs
new file mode 100644
index 000000000..22585035c
--- /dev/null
+++ b/apps/desktop-gpui/src/platform/windows/hidden_frame.rs
@@ -0,0 +1,134 @@
+use std::ffi::c_void;
+use std::io::{self, Write};
+
+use windows_sys::Win32::Foundation::{GetLastError, HWND, LPARAM, LRESULT, SetLastError, WPARAM};
+use windows_sys::Win32::System::Threading::GetCurrentThreadId;
+use windows_sys::Win32::UI::Shell::{
+ DefSubclassProc, GetWindowSubclass, RemoveWindowSubclass, SetWindowSubclass,
+};
+use windows_sys::Win32::UI::WindowsAndMessaging::{
+ GetWindowThreadProcessId, IsWindowVisible, SWP_SHOWWINDOW, WINDOWPOS, WM_NCDESTROY,
+ WM_SHOWWINDOW, WM_WINDOWPOSCHANGED, WM_WINDOWPOSCHANGING,
+};
+
+const SUBCLASS_ID: usize = 0x4341_5046;
+const KNOWN: usize = 1;
+const DISABLED: usize = 2;
+const UPDATING: usize = 4;
+const DWMWA_NCRENDERING_POLICY: u32 = 2;
+const DWMNCRP_USEWINDOWSTYLE: u32 = 0;
+const DWMNCRP_DISABLED: u32 = 1;
+
+#[link(name = "dwmapi")]
+unsafe extern "system" {
+ fn DwmSetWindowAttribute(hwnd: HWND, attribute: u32, value: *const c_void, size: u32) -> i32;
+}
+
+pub fn install(hwnd: HWND) -> io::Result<()> {
+ let owner = unsafe { GetWindowThreadProcessId(hwnd, std::ptr::null_mut()) };
+ if owner == 0 || owner != unsafe { GetCurrentThreadId() } {
+ return Err(io::Error::other(
+ "Main frame policy must be installed on the window's owning thread",
+ ));
+ }
+ if state(hwnd).is_none() {
+ write_state(hwnd, 0)?;
+ }
+ reconcile(hwnd)
+}
+
+fn state(hwnd: HWND) -> Option<usize> {
+ let mut state = 0;
+ let found = unsafe { GetWindowSubclass(hwnd, Some(subclass), SUBCLASS_ID, &mut state) };
+ (found != 0).then_some(state)
+}
+
+fn write_state(hwnd: HWND, state: usize) -> io::Result<()> {
+ if unsafe { SetWindowSubclass(hwnd, Some(subclass), SUBCLASS_ID, state) } == 0 {
+ return Err(io::Error::other("could not update Main frame subclass"));
+ }
+ Ok(())
+}
+
+fn apply_policy(hwnd: HWND, disabled: bool) -> io::Result<()> {
+ let Some(previous) = state(hwnd) else {
+ return Ok(());
+ };
+ let desired = KNOWN | if disabled { DISABLED } else { 0 };
+ if previous & UPDATING != 0 || previous == desired {
+ return Ok(());
+ }
+ let updating = previous | UPDATING;
+ write_state(hwnd, updating)?;
+ let policy = if disabled {
+ DWMNCRP_DISABLED
+ } else {
+ DWMNCRP_USEWINDOWSTYLE
+ };
+ // A native frame can remain visible after Main hides; visible windows retain normal DWM policy.
+ let result = unsafe {
+ DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_NCRENDERING_POLICY,
+ std::ptr::addr_of!(policy).cast(),
+ std::mem::size_of_val(&policy) as u32,
+ )
+ };
+ if state(hwnd) == Some(updating) {
+ write_state(hwnd, if result >= 0 { desired } else { previous })?;
+ }
+ if result < 0 {
+ return Err(io::Error::other(format!(
+ "Main frame DWM policy {policy} failed: HRESULT {result:#010x}"
+ )));
+ }
+ Ok(())
+}
+
+fn reconcile(hwnd: HWND) -> io::Result<()> {
+ if state(hwnd).is_none() {
+ return Ok(());
+ }
+ apply_policy(hwnd, unsafe { IsWindowVisible(hwnd) } == 0)
+}
+
+fn report(result: io::Result<()>) {
+ if let Err(error) = result {
+ let _ = writeln!(io::stderr().lock(), "Cap Main frame policy: {error}");
+ }
+}
+
+unsafe extern "system" fn subclass(
+ hwnd: HWND,
+ message: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+ _subclass_id: usize,
+ _reference_data: usize,
+) -> LRESULT {
+ let incoming_error = unsafe { GetLastError() };
+ if message == WM_NCDESTROY {
+ if unsafe { RemoveWindowSubclass(hwnd, Some(subclass), SUBCLASS_ID) } == 0 {
+ report(Err(io::Error::other(
+ "could not remove Main frame subclass",
+ )));
+ }
+ unsafe { SetLastError(incoming_error) };
+ return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
+ }
+ let showing = message == WM_SHOWWINDOW && wparam != 0
+ || matches!(message, WM_WINDOWPOSCHANGING | WM_WINDOWPOSCHANGED)
+ && lparam != 0
+ && unsafe { (*(lparam as *const WINDOWPOS)).flags } & SWP_SHOWWINDOW != 0;
+ if showing {
+ report(apply_policy(hwnd, false));
+ }
+ unsafe { SetLastError(incoming_error) };
+ let result = unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
+ let forwarded_error = unsafe { GetLastError() };
+ if message == WM_WINDOWPOSCHANGED {
+ report(reconcile(hwnd));
+ }
+ unsafe { SetLastError(forwarded_error) };
+ result
+}
diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs
index f840fe054..120d7e9ff 100644
--- a/apps/desktop-gpui/src/recording.rs
+++ b/apps/desktop-gpui/src/recording.rs
@@ -15,6 +15,7 @@ use anyhow::{Context as _, anyhow};
use cap_recording::{
feeds::{camera, camera::CameraFeed, microphone, microphone::MicrophoneFeed},
instant_recording,
+ recovery::{PreparingStudioJob, PreparingStudioObserver, RecoveryManager},
sources::screen_capture::ScreenCaptureTarget,
studio_recording,
};
@@ -409,22 +410,34 @@ async fn run_instant_operation<T>(
async fn finalize_studio(
completed: studio_recording::CompletedRecording,
capture_target: ScreenCaptureTarget,
+ progress: Option<StudioFinalizationPublisher>,
) -> anyhow::Result<PathBuf> {
+ let started = std::time::Instant::now();
let project_path = completed.project_path.clone();
let needs_remux = matches!(
completed.meta.status(),
cap_project::StudioRecordingStatus::NeedsRemux
);
- tokio::task::spawn_blocking(move || {
+ let completed = tokio::task::spawn_blocking(move || {
if needs_remux {
ensure_finalization_storage(&project_path)?;
}
- cap_recording::recovery::RecoveryManager::remux_if_needed(&project_path)
- .map_err(anyhow::Error::from)
+ let preparing = progress
+ .as_ref()
+ .and_then(|progress| progress.claim_preparing(&completed));
+ let result = match preparing {
+ Some(job) => RecoveryManager::remux_stopped_with_preparing(&completed, job),
+ None => RecoveryManager::remux_if_needed(&project_path),
+ };
+ result.map(|_| completed).map_err(anyhow::Error::from)
})
.await
.context("studio finalize task")?
.context("studio finalize")?;
+ tracing::info!(
+ elapsed_ms = started.elapsed().as_secs_f64() * 1000.0,
+ "Studio stop remux complete"
+ );
// Everything `handle_recording_finish` does after the remux,
// in its order: the first-frame JPEG the library's card is
@@ -433,9 +446,14 @@ async fn finalize_studio(
// recording that is already on disk, so both only warn.
let project_path = completed.project_path.clone();
tokio::task::spawn_blocking(move || {
+ let thumbnail_started = std::time::Instant::now();
if let Some(display_path) = studio_display_path(&project_path) {
write_bundle_thumbnail(&project_path, &display_path);
}
+ tracing::info!(
+ elapsed_ms = thumbnail_started.elapsed().as_secs_f64() * 1000.0,
+ "Studio stop thumbnail complete"
+ );
apply_camera_blur_to_project_config(&project_path, current_camera_blur());
let library = serde_json::from_value(serde_json::Value::Object(
crate::store::store_section("animated_gradients"),
@@ -517,6 +535,182 @@ where
pub(crate) type CaptureStopFuture =
std::pin::Pin<Box<dyn Future<Output = (bool, anyhow::Result<PathBuf>)> + Send>>;
+#[derive(Clone, Default)]
+struct StudioFinalizationState {
+ capture_stopped: bool,
+ preparing_decided: bool,
+ preparing: Option<PreparingStudioObserver>,
+ result: Option<Result<(), String>>,
+}
+
+#[derive(Clone)]
+pub(crate) struct StudioFinalization {
+ state: tokio::sync::watch::Receiver<StudioFinalizationState>,
+}
+
+#[derive(Clone)]
+pub(crate) struct StudioFinalizationPublisher {
+ state: tokio::sync::watch::Sender<StudioFinalizationState>,
+ target: Arc<StudioFinalizationTarget>,
+}
+
+struct StudioFinalizationTarget {
+ project_path: PathBuf,
+ generation: u64,
+}
+
+impl StudioFinalization {
+ pub(crate) fn channel(
+ project_path: PathBuf,
+ generation: u64,
+ ) -> (StudioFinalizationPublisher, Self) {
+ let (state, receiver) = tokio::sync::watch::channel(StudioFinalizationState::default());
+ (
+ StudioFinalizationPublisher {
+ state,
+ target: Arc::new(StudioFinalizationTarget {
+ project_path,
+ generation,
+ }),
+ },
+ Self { state: receiver },
+ )
+ }
+
+ pub(crate) fn same_job(&self, other: &Self) -> bool {
+ self.state.same_channel(&other.state)
+ }
+
+ pub(crate) fn matches_preparing_identity(
+ &self,
+ identity: &cap_recording::recovery::PreparingStudioIdentity,
+ ) -> bool {
+ let observer = self.state.borrow().preparing.clone();
+ observer.is_some_and(|observer| {
+ observer.identity().same_job(identity)
+ && matches!(
+ observer.latest(),
+ cap_recording::recovery::PreparingStudioState::Available(_)
+ )
+ })
+ }
+
+ pub(crate) fn is_finalizing(&self) -> bool {
+ let state = self.state.borrow();
+ state.capture_stopped && state.result.is_none()
+ }
+
+ pub(crate) fn allows_preparing_continuation(
+ &self,
+ identity: &cap_recording::recovery::PreparingStudioIdentity,
+ ) -> bool {
+ let state = self.state.borrow();
+ state.capture_stopped
+ && state.result.as_ref().is_none_or(Result::is_ok)
+ && identity.publication_succeeded()
+ && state
+ .preparing
+ .as_ref()
+ .is_some_and(|observer| observer.identity().same_job(identity))
+ }
+
+ pub(crate) async fn wait_for_capture(&self) -> bool {
+ let mut state = self.state.clone();
+ loop {
+ {
+ let current = state.borrow_and_update();
+ if current.capture_stopped {
+ return true;
+ }
+ if current.result.is_some() {
+ return false;
+ }
+ }
+ if state.changed().await.is_err() {
+ return false;
+ }
+ }
+ }
+
+ pub(crate) async fn wait_for_preparing(&self) -> Option<PreparingStudioObserver> {
+ let mut state = self.state.clone();
+ loop {
+ {
+ let current = state.borrow_and_update();
+ if current.preparing_decided || current.result.is_some() {
+ return current.preparing.clone();
+ }
+ }
+ if state.changed().await.is_err() {
+ return None;
+ }
+ }
+ }
+
+ pub(crate) async fn wait(&self) -> Result<(), String> {
+ let mut state = self.state.clone();
+ loop {
+ if let Some(result) = state.borrow_and_update().result.clone() {
+ return result;
+ }
+ state.changed().await.map_err(|_| {
+ "Recording finalization ended without a result. Your files were retained."
+ .to_string()
+ })?;
+ }
+ }
+}
+
+impl StudioFinalizationPublisher {
+ fn claim_preparing(
+ &self,
+ completed: &studio_recording::CompletedRecording,
+ ) -> Option<PreparingStudioJob> {
+ self.claim_preparing_with(completed, PreparingStudioJob::claim)
+ }
+
+ fn claim_preparing_with(
+ &self,
+ completed: &studio_recording::CompletedRecording,
+ claim: impl FnOnce(
+ &studio_recording::CompletedRecording,
+ u64,
+ ) -> Option<(PreparingStudioJob, PreparingStudioObserver)>,
+ ) -> Option<PreparingStudioJob> {
+ let mut job = None;
+ self.state.send_if_modified(|state| {
+ if !state.capture_stopped || state.preparing_decided || state.result.is_some() {
+ return false;
+ }
+ state.preparing_decided = true;
+ if completed.project_path == self.target.project_path
+ && let Some((claimed, observer)) = claim(completed, self.target.generation)
+ {
+ state.preparing = Some(observer);
+ job = Some(claimed);
+ }
+ true
+ });
+ job
+ }
+
+ fn capture_stopped(&self) {
+ tracing::info!("Studio capture shutdown acknowledged; finalization starting");
+ self.state.send_modify(|state| state.capture_stopped = true);
+ }
+
+ fn complete(&self, result: &anyhow::Result<PathBuf>) {
+ self.state.send_modify(|state| {
+ state.result = Some(
+ result
+ .as_ref()
+ .map(|_| ())
+ .map_err(|error| format!("{error:#}")),
+ );
+ });
+ }
+}
+
#[cfg(any(windows, test))]
async fn finish_windows_startup_setup<T>(
setup: anyhow::Result<T>,
@@ -626,29 +820,42 @@ impl ActiveRecording {
}
#[cfg(target_os = "linux")]
- pub fn clean_studio_stop_handle(&self) -> Option<CaptureStopFuture> {
+ pub(crate) fn clean_studio_stop_handle(
+ &self,
+ progress: Option<StudioFinalizationPublisher>,
+ ) -> Option<CaptureStopFuture> {
let Handle::Studio(handle) = &self.handle else {
return None;
};
let handle = handle.clone();
Some(Box::pin(async move {
let capture_target = handle.capture_target.clone();
- finish_studio_after_join(handle.stop_with_report(), |completed| {
- finalize_studio(completed, capture_target)
+ let result = finish_studio_after_join(handle.stop_with_report(), |completed| {
+ if let Some(progress) = &progress {
+ progress.capture_stopped();
+ }
+ finalize_studio(completed, capture_target, progress.clone())
})
- .await
+ .await;
+ if let Some(progress) = progress {
+ progress.complete(&result.1);
+ }
+ result
}))
}
#[cfg(any(target_os = "macos", windows))]
- pub fn clean_studio_stop_handle(&self) -> Option<CaptureStopFuture> {
+ pub(crate) fn clean_studio_stop_handle(
+ &self,
+ progress: Option<StudioFinalizationPublisher>,
+ ) -> Option<CaptureStopFuture> {
let Handle::Studio(handle) = &self.handle else {
return None;
};
let handle = handle.clone();
Some(Box::pin(async move {
let capture_target = handle.capture_target.clone();
- finish_after_capture_stop(
+ let result = finish_after_capture_stop(
async move {
let outcome = handle.stop_with_outcome().await;
(
@@ -656,9 +863,18 @@ impl ActiveRecording {
outcome.result.map_err(anyhow::Error::msg),
)
},
- |completed| finalize_studio(completed, capture_target),
+ |completed| {
+ if let Some(progress) = &progress {
+ progress.capture_stopped();
+ }
+ finalize_studio(completed, capture_target, progress.clone())
+ },
)
- .await
+ .await;
+ if let Some(progress) = progress {
+ progress.complete(&result.1);
+ }
+ result
}))
}
@@ -917,7 +1133,7 @@ impl ActiveRecording {
Handle::Studio(handle) => {
let capture_target = handle.capture_target.clone();
let completed = handle.stop().await?;
- finalize_studio(completed, capture_target).await
+ finalize_studio(completed, capture_target, None).await
}
Handle::Instant(handle) => {
let result = async {
@@ -1196,6 +1412,30 @@ fn write_bundle_thumbnail(project_dir: &std::path::Path, source_video: &std::pat
}
}
+pub(crate) fn preparing_presentation(
+ project: &cap_project::ProjectConfiguration,
+) -> Result<cap_project::ProjectConfiguration, String> {
+ let library = serde_json::from_value(serde_json::Value::Object(crate::store::store_section(
+ "animated_gradients",
+ )))
+ .map_err(|error| format!("Preparing appearance preferences did not parse: {error}"))?;
+ preparing_presentation_for(project, current_camera_blur(), &library)
+}
+
+fn preparing_presentation_for(
+ project: &cap_project::ProjectConfiguration,
+ blur: crate::store::BlurMode,
+ library: &cap_project::AnimatedGradientLibrary,
+) -> Result<cap_project::ProjectConfiguration, String> {
+ if blur != crate::store::BlurMode::Off || project.camera.background_blur.is_active() {
+ return Err("Camera blur requires ordinary editor loading".into());
+ }
+ if library.selected && library.last_used.is_some() {
+ return Err("Animated-gradient preferences require ordinary editor loading".into());
+ }
+ Ok(project.clone())
+}
+
/// The camera preview bubble's current blur mode.
///
/// `handle_recording_finish` reads the *live* preview state
@@ -3171,6 +3411,282 @@ mod capture_stop_contract_tests {
}
}
+#[cfg(test)]
+mod studio_finalization_tests {
+ use super::*;
+
+ fn channel() -> (StudioFinalizationPublisher, StudioFinalization) {
+ StudioFinalization::channel(PathBuf::from("project.cap"), 42)
+ }
+
+ fn completed_without_receipt(path: &str) -> studio_recording::CompletedRecording {
+ studio_recording::CompletedRecording {
+ project_path: PathBuf::from(path),
+ meta: serde_json::from_value(serde_json::json!({
+ "segments": [{
+ "display": { "path": "content/segments/segment-0/display", "fps": 30, "start_time": 0.0 }
+ }],
+ "status": { "status": "NeedsRemux" }
+ }))
+ .unwrap(),
+ cursor_data: Default::default(),
+ clean_stopped: None,
+ }
+ }
+
+ #[tokio::test]
+ async fn editor_waits_for_complete_finalization_after_capture_acknowledgement() {
+ let (publisher, finalization) = channel();
+ assert!(!finalization.is_finalizing());
+ assert!(finalization.wait_for_capture().now_or_never().is_none());
+ assert!(finalization.wait().now_or_never().is_none());
+ publisher.capture_stopped();
+ assert!(finalization.wait_for_capture().await);
+ assert!(finalization.is_finalizing());
+ assert!(finalization.wait().now_or_never().is_none());
+ publisher.complete(&Ok(PathBuf::from("project.cap")));
+ finalization.wait().await.unwrap();
+ assert!(!finalization.is_finalizing());
+ }
+
+ #[tokio::test]
+ async fn completion_before_subscription_is_retained_for_close_and_reopen() {
+ let (publisher, finalization) = channel();
+ publisher.capture_stopped();
+ publisher.complete(&Ok(PathBuf::from("project.cap")));
+ drop(publisher);
+ assert!(finalization.wait_for_capture().await);
+ finalization.wait().await.unwrap();
+ finalization.clone().wait().await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn stop_failure_never_opens_a_preparing_editor() {
+ let (publisher, finalization) = channel();
+ publisher.complete(&Err(anyhow!("capture stop unconfirmed")));
+ assert!(!finalization.wait_for_capture().await);
+ assert!(!finalization.is_finalizing());
+ assert!(
+ finalization
+ .wait()
+ .await
+ .unwrap_err()
+ .contains("unconfirmed")
+ );
+ }
+
+ #[tokio::test]
+ async fn finalization_failure_remains_an_error_after_capture_stops() {
+ let (publisher, finalization) = channel();
+ publisher.capture_stopped();
+ publisher.complete(&Err(anyhow!("media validation failed")));
+ assert!(finalization.wait_for_capture().await);
+ assert!(!finalization.is_finalizing());
+ assert_eq!(
+ finalization.wait().await.unwrap_err(),
+ "media validation failed"
+ );
+ }
+
+ #[tokio::test]
+ async fn lost_finalizer_cannot_leave_the_loading_shell_waiting_forever() {
+ for capture_stopped in [false, true] {
+ let (publisher, finalization) = channel();
+ if capture_stopped {
+ publisher.capture_stopped();
+ }
+ drop(publisher);
+ assert_eq!(finalization.wait_for_capture().await, capture_stopped);
+ assert!(
+ finalization
+ .wait()
+ .await
+ .unwrap_err()
+ .contains("files were retained")
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn closing_every_editor_waiter_does_not_cancel_retained_finalization() {
+ let (publisher, finalization) = channel();
+ let (release, released) = tokio::sync::oneshot::channel();
+ let task = tokio::spawn(async move {
+ let result = finish_after_capture_stop(async { (true, Ok(())) }, |()| async {
+ publisher.capture_stopped();
+ released.await.unwrap();
+ Ok(PathBuf::from("project.cap"))
+ })
+ .await;
+ publisher.complete(&result.1);
+ result
+ });
+ assert!(finalization.wait_for_capture().await);
+ drop(finalization);
+ release.send(()).unwrap();
+ let (stopped, result) = task.await.unwrap();
+ assert!(stopped);
+ assert_eq!(result.unwrap(), PathBuf::from("project.cap"));
+ }
+
+ #[tokio::test]
+ async fn finalizer_panic_publishes_failure_without_losing_capture_acknowledgement() {
+ let (publisher, finalization) = channel();
+ let result = finish_after_capture_stop(async { (true, Ok(())) }, |()| async {
+ publisher.capture_stopped();
+ panic!("finalizer failed");
+ })
+ .await;
+ publisher.complete(&result.1);
+ assert!(result.0);
+ assert!(finalization.wait_for_capture().await);
+ assert!(
+ finalization
+ .wait()
+ .await
+ .unwrap_err()
+ .contains("after capture stopped")
+ );
+ }
+
+ #[tokio::test]
+ async fn capture_acknowledgement_does_not_imply_preparing_sources() {
+ let (publisher, finalization) = channel();
+ publisher.capture_stopped();
+ assert!(finalization.wait_for_capture().await);
+ assert!(finalization.wait_for_preparing().now_or_never().is_none());
+ publisher.complete(&Ok(PathBuf::from("project.cap")));
+ assert!(finalization.wait_for_preparing().await.is_none());
+ finalization.wait().await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn declined_receipt_does_not_finish_post_finalize_work() {
+ let (publisher, finalization) = channel();
+ publisher.capture_stopped();
+ assert!(
+ publisher
+ .claim_preparing(&completed_without_receipt("project.cap"))
+ .is_none()
+ );
+ assert!(finalization.wait_for_preparing().await.is_none());
+ assert!(finalization.is_finalizing());
+ assert!(finalization.wait().now_or_never().is_none());
+ publisher.complete(&Err(anyhow!("post-finalize task failed")));
+ assert_eq!(
+ finalization.wait().await.unwrap_err(),
+ "post-finalize task failed"
+ );
+ }
+
+ #[tokio::test]
+ async fn preparing_admission_requires_capture_acknowledgement() {
+ let (publisher, finalization) = channel();
+ assert!(
+ publisher
+ .claim_preparing_with(&completed_without_receipt("project.cap"), |_, _| panic!(
+ "Capture must be acknowledged before the receipt is claimed"
+ ),)
+ .is_none()
+ );
+ assert!(!publisher.state.borrow().preparing_decided);
+ assert!(finalization.wait_for_preparing().now_or_never().is_none());
+ publisher.complete(&Err(anyhow!("capture stop failed")));
+ assert!(finalization.wait_for_preparing().await.is_none());
+ assert!(!finalization.wait_for_capture().await);
+ }
+
+ #[tokio::test]
+ async fn wrong_project_declines_preview_without_changing_finalization_result() {
+ let (publisher, finalization) = channel();
+ publisher.capture_stopped();
+ assert!(
+ publisher
+ .claim_preparing_with(&completed_without_receipt("other.cap"), |_, _| panic!(
+ "A different project cannot claim this publisher's receipt"
+ ),)
+ .is_none()
+ );
+ assert!(publisher.state.borrow().preparing_decided);
+ assert!(finalization.wait_for_preparing().await.is_none());
+ assert!(finalization.is_finalizing());
+ publisher.complete(&Ok(PathBuf::from("project.cap")));
+ finalization.wait().await.unwrap();
+ }
+
+ #[test]
+ fn completed_and_duplicate_attempts_cannot_reopen_preparing_admission() {
+ let (publisher, _) = channel();
+ publisher.capture_stopped();
+ let observed_generation = std::cell::Cell::new(None);
+ assert!(
+ publisher
+ .claim_preparing_with(
+ &completed_without_receipt("project.cap"),
+ |_, generation| {
+ observed_generation.set(Some(generation));
+ None
+ },
+ )
+ .is_none()
+ );
+ assert_eq!(observed_generation.get(), Some(42));
+ assert!(publisher.state.borrow().preparing_decided);
+ let cloned = publisher.clone();
+ assert!(
+ cloned
+ .claim_preparing_with(&completed_without_receipt("project.cap"), |_, _| panic!(
+ "A duplicate finalizer cannot claim a second receipt"
+ ),)
+ .is_none()
+ );
+ publisher.complete(&Ok(PathBuf::from("project.cap")));
+ assert!(
+ cloned
+ .claim_preparing_with(&completed_without_receipt("project.cap"), |_, _| panic!(
+ "A completed finalizer cannot reopen preview admission"
+ ),)
+ .is_none()
+ );
+ assert_eq!(publisher.target.generation, 42);
+ assert_eq!(publisher.target.project_path, PathBuf::from("project.cap"));
+ assert!(Arc::ptr_eq(&publisher.target, &cloned.target));
+ }
+
+ #[test]
+ fn completed_finalization_cannot_mint_a_late_preparing_job() {
+ let (publisher, _) = channel();
+ publisher.capture_stopped();
+ publisher.complete(&Ok(PathBuf::from("project.cap")));
+ assert!(!publisher.state.borrow().preparing_decided);
+ assert!(
+ publisher
+ .claim_preparing_with(&completed_without_receipt("project.cap"), |_, _| panic!(
+ "Completed finalization cannot claim a first late receipt"
+ ),)
+ .is_none()
+ );
+ assert!(!publisher.state.borrow().preparing_decided);
+ }
+
+ #[tokio::test]
+ async fn lost_publisher_releases_preparing_waiters_without_success() {
+ let (publisher, finalization) = channel();
+ publisher.capture_stopped();
+ drop(publisher);
+ assert!(finalization.wait_for_preparing().await.is_none());
+ assert!(finalization.wait().await.is_err());
+ }
+
+ #[test]
+ fn readiness_identity_does_not_confuse_retries_or_later_recordings() {
+ let (_, first) = channel();
+ let (_, second) = channel();
+ assert!(first.same_job(&first.clone()));
+ assert!(!first.same_job(&second));
+ }
+}
+
#[cfg(all(test, target_os = "linux"))]
mod instant_lifecycle_tests {
use super::*;
@@ -3745,3 +4261,48 @@ mod recording_owned_feed_tests {
assert!(app_stopped);
}
}
+
+#[cfg(test)]
+mod preparing_presentation_tests {
+ use super::*;
+
+ #[test]
+ fn supported_preparing_presentation_preserves_every_config_value() {
+ let project = cap_project::ProjectConfiguration::default();
+ let shown = preparing_presentation_for(
+ &project,
+ crate::store::BlurMode::Off,
+ &cap_project::AnimatedGradientLibrary::default(),
+ )
+ .unwrap();
+ assert_eq!(
+ serde_json::to_value(shown).unwrap(),
+ serde_json::to_value(project).unwrap()
+ );
+ }
+
+ #[test]
+ fn live_blur_and_selected_gradient_decline_without_mutating_stopped_config() {
+ let project = cap_project::ProjectConfiguration::default();
+ let original = serde_json::to_value(&project).unwrap();
+ for blur in [crate::store::BlurMode::Light, crate::store::BlurMode::Heavy] {
+ assert!(
+ preparing_presentation_for(
+ &project,
+ blur,
+ &cap_project::AnimatedGradientLibrary::default(),
+ )
+ .is_err()
+ );
+ }
+ let library = cap_project::AnimatedGradientLibrary {
+ selected: true,
+ last_used: Some(cap_project::AnimatedGradientConfig::default()),
+ ..Default::default()
+ };
+ assert!(
+ preparing_presentation_for(&project, crate::store::BlurMode::Off, &library).is_err()
+ );
+ assert_eq!(serde_json::to_value(project).unwrap(), original);
+ }
+}
diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs
index 791fd0697..adae83be5 100644
--- a/apps/desktop-gpui/src/session.rs
+++ b/apps/desktop-gpui/src/session.rs
@@ -23,6 +23,49 @@ pub enum Phase {
Stopping,
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum StudioEditorPresentation<I = gpui::WindowId> {
+ Pending,
+ Attempted,
+ Opened(I),
+ Dismissed,
+}
+
+impl<I: PartialEq> StudioEditorPresentation<I> {
+ pub(crate) fn suppresses_completion_open(&self) -> bool {
+ matches!(self, Self::Opened(_) | Self::Dismissed)
+ }
+
+ pub(crate) fn closed(&mut self, window: I) {
+ if matches!(self, Self::Opened(current) if *current == window) {
+ *self = Self::Dismissed;
+ }
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct PreparingStudioEditor {
+ generation: u64,
+ pub(crate) project_path: std::path::PathBuf,
+ pub(crate) finalization: recording::StudioFinalization,
+ pub(crate) capture_stopped: bool,
+ pub(crate) presentation: StudioEditorPresentation,
+}
+
+fn prepares_studio_editor(
+ mode: Option<recording::RecordingMode>,
+ low_storage: bool,
+ recording_failed: bool,
+ editor_target: bool,
+ open_editor: bool,
+) -> bool {
+ mode == Some(recording::RecordingMode::Studio)
+ && !low_storage
+ && !recording_failed
+ && !editor_target
+ && open_editor
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CountdownAdvance {
Ignore,
@@ -367,6 +410,7 @@ pub struct RecordingSession {
/// Taken by the phase observer to honour `postStudioRecordingBehaviour`
/// (`openEditor` by default) the way the Tauri app does.
pub finished_studio: Option<std::path::PathBuf>,
+ preparing_studio_editor: Option<PreparingStudioEditor>,
/// `EditorRecordingTarget` (`src-tauri/src/windows.rs:3679-3697`): the
/// open editor project a "Record a new clip" capture must land back in.
/// Set by the editor's record modal (`setEditorRecordingTarget`,
@@ -416,6 +460,7 @@ impl RecordingSession {
controls_open: false,
mic_muted: false,
finished_studio: None,
+ preparing_studio_editor: None,
editor_recording_target: None,
started_at: None,
paused_accum: Duration::ZERO,
@@ -553,6 +598,29 @@ impl RecordingSession {
self.countdown_remaining
}
+ pub(crate) fn preparing_studio_editor(&self) -> Option<&PreparingStudioEditor> {
+ self.preparing_studio_editor
+ .as_ref()
+ .filter(|pending| pending.generation == self.recording_generation)
+ }
+
+ pub(crate) fn preparing_studio_editor_mut(&mut self) -> Option<&mut PreparingStudioEditor> {
+ self.preparing_studio_editor
+ .as_mut()
+ .filter(|pending| pending.generation == self.recording_generation)
+ }
+
+ pub(crate) fn take_preparing_studio_editor(&mut self) -> Option<PreparingStudioEditor> {
+ self.preparing_studio_editor.take()
+ }
+
+ pub(crate) fn capture_stopped_for_editor(&self) -> bool {
+ self.phase == Phase::Stopping
+ && self
+ .preparing_studio_editor()
+ .is_some_and(|pending| pending.capture_stopped)
+ }
+
pub fn start(&mut self, config: StartConfig, cx: &mut Context<Self>) {
if self.phase != Phase::Idle {
return;
@@ -564,6 +632,7 @@ impl RecordingSession {
self.storage_monitor = None;
self.failure_monitor = None;
self.recording_generation = self.recording_generation.wrapping_add(1);
+ self.preparing_studio_editor = None;
let generation = self.recording_generation;
let countdown = crate::store::GeneralSettings::load()
.recording_countdown
@@ -947,18 +1016,35 @@ impl RecordingSession {
let separator = if link.contains('?') { '&' } else { '?' };
cx.open_url(&format!("{link}{separator}recordingStopped=1"));
}
+ let studio_project_path = active.project_dir.clone();
+ let (studio_progress, studio_finalization) = if prepares_studio_editor(
+ self.mode(),
+ low_storage,
+ recording_failed,
+ self.editor_recording_target.is_some(),
+ crate::store::GeneralSettings::load().post_studio_recording_behaviour
+ == crate::store::PostStudioBehaviour::OpenEditor,
+ ) {
+ let (publisher, finalization) = recording::StudioFinalization::channel(
+ studio_project_path.clone(),
+ self.recording_generation,
+ );
+ (Some(publisher), Some(finalization))
+ } else {
+ (None, None)
+ };
#[cfg(target_os = "linux")]
let retained_stop = active
.instant_stop_handle(low_storage || recording_failed, recording_failed)
- .or_else(|| active.clean_studio_stop_handle());
+ .or_else(|| active.clean_studio_stop_handle(studio_progress));
#[cfg(windows)]
let retained_stop = recording_failed
.then(|| active.failed_stop_handle())
- .or_else(|| active.clean_studio_stop_handle());
+ .or_else(|| active.clean_studio_stop_handle(studio_progress));
#[cfg(target_os = "macos")]
let retained_stop = recording_failed
.then(|| active.failed_stop_handle())
- .or_else(|| active.clean_studio_stop_handle());
+ .or_else(|| active.clean_studio_stop_handle(studio_progress));
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
let retained_stop: Option<recording::CaptureStopFuture> = None;
let retains_active = retained_stop.is_some();
@@ -977,9 +1063,42 @@ impl RecordingSession {
self.stopped_elapsed = Some(self.elapsed());
self.pause_control.cancel_for_stop();
self.phase = Phase::Stopping;
+ self.preparing_studio_editor =
+ studio_finalization.map(|finalization| PreparingStudioEditor {
+ generation: self.recording_generation,
+ project_path: studio_project_path,
+ finalization,
+ capture_stopped: false,
+ presentation: StudioEditorPresentation::Pending,
+ });
cx.notify();
let task = gpui_tokio::Tokio::spawn(cx, stop_future);
+ if let Some(pending) = self.preparing_studio_editor.clone() {
+ let finalization = pending.finalization.clone();
+ let captured =
+ gpui_tokio::Tokio::spawn(cx, async move { finalization.wait_for_capture().await });
+ #[cfg(target_os = "linux")]
+ let capture_ticket = stop_ticket.clone();
+ cx.spawn(async move |this, cx| {
+ if !matches!(captured.await, Ok(true)) {
+ return;
+ }
+ this.update(cx, |this, cx| {
+ #[cfg(target_os = "linux")]
+ if !capture_ticket.is_current(this.phase, this.recording_generation, this.terminal_operation, this.recording_owner().as_ref(), retains_active) { return; }
+ #[cfg(not(target_os = "linux"))]
+ if this.recording_generation != pending.generation || this.phase != Phase::Stopping { return; }
+ if let Some(current) = this.preparing_studio_editor_mut()
+ && current.finalization.same_job(&pending.finalization)
+ {
+ current.capture_stopped = true;
+ tracing::info!(path = %current.project_path.display(), "Studio capture stopped; editor preparation can begin");
+ cx.notify();
+ }
+ }).ok();
+ }).detach();
+ }
cx.spawn(async move |this, cx| {
let result = task.await;
this.update(cx, |this, cx| {
@@ -992,6 +1111,7 @@ impl RecordingSession {
Err(_) => !retains_active,
};
if !capture_stopped {
+ this.preparing_studio_editor = None;
let error = match result {
Ok((_, Err(error))) => format!("{error:#}"),
Err(error) => format!("Stop task failed: {error}"),
@@ -2300,3 +2420,55 @@ mod pause_control_tests {
assert!(!polled.load(std::sync::atomic::Ordering::SeqCst));
}
}
+
+#[cfg(test)]
+mod studio_editor_presentation_tests {
+ use super::*;
+
+ #[test]
+ fn early_editor_only_applies_to_normal_studio_stops_with_open_editor_preference() {
+ for mode in [
+ None,
+ Some(recording::RecordingMode::Instant),
+ Some(recording::RecordingMode::Studio),
+ ] {
+ for flags in 0..16 {
+ let low_storage = flags & 1 != 0;
+ let failed = flags & 2 != 0;
+ let editor_target = flags & 4 != 0;
+ let open_editor = flags & 8 != 0;
+ let expected = mode == Some(recording::RecordingMode::Studio) && flags == 8;
+ assert_eq!(
+ prepares_studio_editor(mode, low_storage, failed, editor_target, open_editor),
+ expected
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn unsuccessful_or_raced_early_window_creation_keeps_normal_completion_open() {
+ assert!(!StudioEditorPresentation::<u32>::Pending.suppresses_completion_open());
+ assert!(!StudioEditorPresentation::<u32>::Attempted.suppresses_completion_open());
+ }
+
+ #[test]
+ fn closing_a_preparing_editor_suppresses_completion_reopening() {
+ let mut state = StudioEditorPresentation::Opened(1);
+ assert!(state.suppresses_completion_open());
+ state.closed(1);
+ assert_eq!(state, StudioEditorPresentation::Dismissed);
+ assert!(state.suppresses_completion_open());
+ }
+
+ #[test]
+ fn explicit_reopening_retains_the_new_window_when_the_old_close_arrives() {
+ let mut state = StudioEditorPresentation::Opened(1);
+ state.closed(1);
+ state = StudioEditorPresentation::Opened(2);
+ state.closed(1);
+ assert_eq!(state, StudioEditorPresentation::Opened(2));
+ state.closed(2);
+ assert_eq!(state, StudioEditorPresentation::Dismissed);
+ }
+}
diff --git a/apps/desktop-gpui/src/upload.rs b/apps/desktop-gpui/src/upload.rs
index f186f10c9..95f4f2e1e 100644
--- a/apps/desktop-gpui/src/upload.rs
+++ b/apps/desktop-gpui/src/upload.rs
@@ -1183,11 +1183,23 @@ async fn upload_exported_video_inner(
.map_err(|error| format!("Failed to persist upload state: {error}"))?;
match checked_upload_step(&cancel, || {
- upload_video(&s3_config.id, &file_path, &metadata, progress, &cancel)
+ upload_video(
+ &s3_config.id,
+ &file_path,
+ &metadata,
+ progress,
+ &cancel,
+ meta.sharing.is_some(),
+ )
})
.await
{
Ok((link, object_identity)) => {
+ let link = meta
+ .sharing
+ .as_ref()
+ .map(|sharing| sharing.link.clone())
+ .unwrap_or(link);
meta.sharing = Some(SharingMeta {
link: link.clone(),
id: s3_config.id.clone(),
@@ -1333,6 +1345,7 @@ async fn upload_video(
metadata: &VideoMeta,
progress: impl Fn(f64),
cancel: &AtomicBool,
+ replace_existing: bool,
) -> Result<(String, Option<String>), AuthApiError> {
let initiate = checked_upload_step(cancel, || multipart_initiate(video_id)).await?;
let is_drive = is_google_drive_upload(initiate.provider.as_deref(), &initiate.upload_id);
@@ -1349,7 +1362,13 @@ async fn upload_video(
return Err(AuthApiError::Other("Export cancelled".into()));
}
let completed_identity = checked_upload_step(cancel, || {
- multipart_complete(video_id, &initiate.upload_id, &parts, Some(metadata))
+ multipart_complete(
+ video_id,
+ &initiate.upload_id,
+ &parts,
+ Some(metadata),
+ replace_existing,
+ )
})
.await?;
progress(1.0);
@@ -1453,11 +1472,13 @@ async fn multipart_complete(
upload_id: &str,
parts: &[UploadedPart],
meta: Option<&VideoMeta>,
+ replace_existing: bool,
) -> Result<Option<String>, AuthApiError> {
let mut body = json!({
"videoId": video_id,
"uploadId": upload_id,
"parts": parts,
+ "replaceExisting": replace_existing,
});
if let Some(meta) = meta
&& let Value::Object(object) = &mut body
diff --git a/apps/desktop/scripts/stop-editor-performance.md b/apps/desktop/scripts/stop-editor-performance.md
new file mode 100644
index 000000000..48b51e0a8
--- /dev/null
+++ b/apps/desktop/scripts/stop-editor-performance.md
@@ -0,0 +1,712 @@
+# Stop recording to usable editor
+
+Status on 2026-09-10: the user stopped further testing and requested sandbox shutdown and PR publication with the remaining gaps recorded. This is **not** an all-tests-passed result. GPUI v4 native suites passed on macOS (993), Linux (1,052) and Windows (970), with two existing ignores each and passing compilation checks. macOS passed 161 editor tests, 597 recording/recovery tests, 470 Tauri tests plus binding generation; desktop frontend 473, web frontend 3,047 and tooling 64 tests passed, with both frontend TypeScript checks passing. Linux root library/integration scopes, 536 Tauri function tests and three canonical executions passed. Windows completed 1,314 scoped library tests across eight crates; its remaining protocol tests, Tauri, muxer, integration, explicit GPU, canonical, hardware and strict-lint scopes were not run after the capacity guard stopped the lane. Strict GPUI and Linux export Clippy retain unchanged baseline findings. Linux ordinary static-library packaging failed for lack of disk space despite passing direct main-binary function tests. Active test sandboxes were stopped after evidence retention. Cleanup of older stalled restore requests is recorded separately and is not claimed complete here.
+
+The candidate now keeps eligible preparing playback alive after successful publication while ordinary loading completes, then lets the ordinary editor adopt the existing audio generation and consumed-audio clock. Native function tests cover that ownership path, completed PCM reuse, cancellation and stale-candidate disposal. Current application Stop-to-first-audible timing and physically uninterrupted audio/image handoff remain unproven. The user will test the application manually after automated verification. Earlier screenshots and benchmarks below apply to their recorded source snapshots; no new UI run or expanded two-hour benchmark was performed for this final verification.
+
+## Acceptance criteria
+
+Measure from the actual Stop action to capture shutdown, the first presented editor frame, first audible playback, and a successful seek near the end. A window or spinner appearing is not editor readiness.
+
+The earlier under-500-ms p95 target is retained as historical context, not an achieved measurement or the current optimization priority. The current goal is immediate editor feedback with truthful media readiness, including multi-hour recordings. Track capture frame drops, A/V alignment, audio sample counts, output quality, CPU, memory, and disk activity alongside latency. No finalizer percentage or elapsed-time animation may stand in for a confirmed playable prefix.
+
+## Measurements on 2026-09-09
+
+The experiments below record successive source snapshots from September 9–10. “Current” or “final” within a historical stage refers to that stage. Later implementation and verification updates are listed at the end; earlier counts and timings are not added to the final results.
+
+Evidence is retained locally in `.git/stop-editor-20260909`. Originals and disposable benchmark copies are separate. No customer recordings were modified.
+
+The GPUI runs used actual macOS screen capture at 3024 by 1964 and 60 fps. The native microphone was the MacBook Pro Microphone. The five-minute run also enabled system audio.
+
+| Native GPUI baseline | Capture pipelines stopped | Stop to first editor frame |
+| ------------------------------------------------ | --------------------------: | -------------------------: |
+| 15 seconds, screen | Not separately instrumented | 1,001.7 ms |
+| 60 seconds, screen and microphone | 38.9 ms | 1,552.9 ms |
+| 300 seconds, screen, microphone and system audio | 122.7 ms | 6,013.5 ms |
+
+A native 60-second candidate recording reached the first editor frame in 937.9 ms, with capture pipelines stopped in 59.1 ms. These native runs captured changing foreground content and are flow observations, not controlled paired percentage comparisons. GPUI's frame marker observes delivery to the editor, not a measured display scanout.
+
+The native Tauri screen-only driver measured 1,686.6 ms baseline and 1,684.7 ms candidate from Stop to a rendered, visible canvas followed by two animation frames. Stop command completion was 139.9 ms and 177.3 ms respectively; neither value represents editor readiness. These are separate 15-second recordings using the root workspace's unoptimized debug build, so they are not release timings and are not comparable to the GPUI build profile.
+
+A Tauri candidate run with both microphone and system audio also completed recording and opened a rendered editor. Its 15-second debug run measured 2,622.0 ms to the presented-frame observer. This exercises the preserved-AAC path in Tauri, but has no matched native audio baseline.
+
+The controlled comparison replays identical preserved recording bytes through `RecoveryManager::remux_if_needed`, alternating baseline and candidate order. Each table entry is the median of three runs. Both executable versions use the GPUI development workspace's optimized dependencies. These are component benchmarks, not packaged release or full Stop-to-editor benchmarks.
+
+| Shared finalization fixture | Baseline | Candidate | Reduction |
+| --------------------------------------------- | ----------: | ----------: | --------: |
+| Native screen recording, 14.9 seconds | 548.1 ms | 534.2 ms | 2.6% |
+| Native screen and microphone, 60 seconds | 1,177.9 ms | 850.5 ms | 27.8% |
+| Two-hour replay, video and AAC audio, 2.40 GB | 47,616.9 ms | 19,499.9 ms | 59.0% |
+
+The two-hour fixture contains actual encoded screen and microphone media replayed to two-hour timestamps. It is not a two-hour capture or hardware soak. Its video is 1280 by 832 at 30 fps. It excludes long cursor and keyboard histories. Three samples do not establish p95 or p99 performance.
+
+An earlier overlapping run reported 18.1 seconds inside finalization and 19.6 seconds for the whole component call. Use the later alternating comparison above for the candidate assessment.
+
+## Initial candidate changes, September 9
+
+- Preserve single-track AAC media by remuxing it to M4A instead of decoding it and encoding it again as Ogg. Detect the actual codec; old files with misleading extensions retain the existing conversion path.
+- On macOS, attempt an independent copy-on-write staging clone, then use the existing exclusive copy fallback. This is not a hard link. Other operating systems retain the copy path.
+- Hash separate files with at most one additional scoped worker when the recovery inputs total at least 32 MiB and multiple CPUs are available. Keep full byte hashes, directory entries, symlink rejection, and the serial fallback if a worker cannot be created.
+- Reuse the editor audio resampler's output allocation across packets. Restore the requested sample capacity for every conversion and flush; keep the same decoder, resampling configuration, samples, and range behaviour.
+- Read fragmented video through a seekable concatenated input when creating a new finalized output. Avoid writing and rereading a recording-sized temporary aggregate. Existing destinations retain the original aggregate path because they can alias an input.
+- Add stage timing and opt-in native benchmark drivers. Retain source snapshots, staged validation, source rechecks, synchronization, transactional publication, and preserved originals.
+
+The recovery unit suite passed 58 tests. The integration suite passed 50 tests, with one existing ignored test. Added coverage verifies decoded AAC samples, microphone/system-audio offsets and device metadata, preserved original bytes, independent cloned files, exclusive destination creation, and large-file changes with restored timestamps. The audio unit suite passed 42 tests, including bit-exact comparisons against fresh resampling buffers at 16, 44.1, 48 and 96 kHz with one, two and six source channels and varying packet sizes. These results do not establish platform or release parity.
+
+Scoped Rust checks passed for `cap-audio`, `cap-recording`, `cap-desktop`, and `cap-desktop-gpui`. Rust formatting and the benchmark JavaScript's Biome check passed. Biome did not process Markdown, so this document was checked manually. Native baseline/candidate Tauri builds and the GPUI candidate build completed.
+
+## Further matched optimization benchmarks
+
+The bounded hashing experiment compares the preceding AAC/clone candidate with the same candidate plus concurrent hashing. Each result is the median of three alternating runs on identical preserved bytes, with builds and capture runs stopped. Evidence is in `optimization-stage-2/results.json`.
+
+| Shared finalization fixture | Previous candidate | Concurrent hashing | Reduction |
+| ---------------------------------------- | -----------------: | -----------------: | --------: |
+| Native screen recording, 14.9 seconds | 559.6 ms | 528.0 ms | 5.6% |
+| Native screen and microphone, 60 seconds | 950.4 ms | 843.5 ms | 11.2% |
+| Two-hour replay, video and AAC audio | 19,943.9 ms | 15,329.0 ms | 23.1% |
+
+An instrumented long run still spent about 1.87 seconds validating staged inputs, 4.13 seconds finalizing video, and 1.81 seconds validating output tracks. Those validations remain. The entire component call took 15.58 seconds in that run. These results do not demonstrate duration-independent stopping or p95 performance.
+
+The resampler allocation experiment compares identical audio bytes through the full production audio loader, using five alternating runs per variant. Hashing the decoded samples happens after the timed load. Every before/after run matched both decoded byte count and SHA-256. Evidence is in `optimization-stage-3/results.json`.
+
+| Full audio loading | Fresh buffers | Reused buffers | Reduction |
+| ---------------------- | ------------: | -------------: | --------: |
+| Native AAC, 60 seconds | 19.47 ms | 17.97 ms | 7.7% |
+| Legacy Ogg, 60 seconds | 56.29 ms | 55.02 ms | 2.2% |
+| AAC replay, two hours | 2,063.26 ms | 1,988.66 ms | 3.6% |
+
+The long track still allocates 1,382,703,104 bytes for decoded samples. Buffer reuse reduces temporary allocation work; it does not implement bounded audio loading. The full decoded SHA-256 for that track was `5c5c67688b348b9e4d0e54a42e5021c630a7ab8c49c078c892d620e8f7fcd8c9` in both variants.
+
+The combined candidate completed fresh native screen, microphone and system-audio recordings in GPUI and Tauri. GPUI's 60-second run stopped its capture pipelines in 120.3 ms and delivered the first editor frame in 1,254.5 ms. Its five-second playback run reported 300 frames at 59.8 fps with zero dropped frames. Tauri's 15-second run reported stop-command completion in 329.2 ms and a rendered-editor marker at 2,081.6 ms. These are individual development-build flow checks, with changing capture content and different build profiles; they do not establish a matched native speedup or p95.
+
+## Avoiding the temporary combined video
+
+The finalized output remains the same progressive MP4. The clean finalization path now supplies the original fragment bytes through FFmpeg's seekable custom-input interface instead of writing an intermediate concatenated file. The reader uses a 64 KiB buffer and at most two source file handles during a file transition. It retains read failures even if the demuxer subsequently reports EOF. Custom I/O lifetime and buffer ownership follow the [FFmpeg example](https://ffmpeg.org/doxygen/trunk/avio_read_callback_8c-example.html).
+
+Existing output files retain the previous implementation. This preserves overwrites where the output aliases an input, including hard links; opening that destination directly while reading fragments could otherwise truncate its own input. Interrupted-recording recovery retains its established full-validation path.
+
+The final candidate, including the overwrite fallback, was compared with the previous concurrent-hashing candidate using three alternating runs per fixture. Temporary benchmark copies were removed after each completed subprocess; the original fixtures, logs and binaries remain. The last long candidate output was retained for native playback verification. Evidence is in `optimization-stage-4/guarded-results.json`.
+
+| Shared finalization fixture | Previous candidate | Seekable fragment input | Reduction |
+| ---------------------------------------- | -----------------: | ----------------------: | --------: |
+| Native screen recording, 14.9 seconds | 528.35 ms | 489.48 ms | 7.4% |
+| Native screen and microphone, 60 seconds | 763.30 ms | 678.32 ms | 11.1% |
+| Two-hour replay, video and AAC audio | 15,245.86 ms | 13,593.52 ms | 10.8% |
+
+These remain component medians in development builds, not p95 or full Stop-to-editor measurements. All three final media sets matched the preceding candidate byte for byte in a retained comparison, including the complete MP4 containers. Recording metadata and project configuration also matched. Evidence is in `optimization-stage-4/media-equivalence.json` and `metadata-equivalence.json`.
+
+The encoder suite passed 112 tests, including concatenated read/seek equivalence, large seek offsets, truncated and missing fragments, sticky I/O failures, exact packets/timestamps, and existing-output aliases. Scoped clippy passed with warnings denied. Recovery checks passed 58 unit tests and 50 integration tests, with one existing ignored integration test. Root and GPUI application checks and native builds passed.
+
+With the final candidate, a fresh native 60-second GPUI recording with microphone and system audio stopped its capture pipelines in 110.45 ms and delivered the first editor frame in 923.81 ms. Playback from an explicit 30-second seek reported 300 frames at 60.0 fps with zero dropped frames. A native Tauri recording with the same track types, lasting 15 seconds, reported stop-command completion in 285.06 ms and a rendered-editor marker at 1,686.22 ms in its unoptimized debug build. The retained two-hour output also reopened in GPUI, sought explicitly to 7,194.5 seconds, and played for five seconds at 60.0 fps with zero dropped frames. These are individual native flow observations, not controlled percentage comparisons or p95 measurements. Evidence is in `optimization-stage-4/native-results.json`.
+
+The guarded candidate's retained two-hour media files, recording metadata and project configuration also matched the prior candidate byte for byte. See `optimization-stage-4/guarded-equivalence.json`.
+
+One native driver run initially reused the stage 3 GPUI stdout filename. The completed new log was moved to stage 4, and the original stage 3 events were recovered from the independently written daily diagnostic log. This recovered excerpt is named `optimization-stage-3/gpui-mic-system-60.diagnostic.log`; provenance and the distinction from the overwritten stdout stream are recorded in `optimization-stage-4/log-recovery-provenance.json`. Subsequent native log creation is exclusive. Recording media was unaffected.
+
+## Direct media experiment
+
+A separate two-hour fragmented MP4 was created from the replay's encoded video without re-encoding. Compressed video payload SHA-256 matched the progressive input:
+
+`b194eecf662b211a05c0f55724ad31a2425cb1d1d3dca172e4760add6234a95a`
+
+The production decoder was then opened directly on that file:
+
+| Decoder on macOS | Probe and first frame | Seek at 3,600 seconds | Seek at 7,199 seconds |
+| ---------------------- | --------------------: | --------------------: | --------------------: |
+| AVAssetReader hardware | 440.4 ms | 46.6 ms | 25.6 ms |
+| FFmpeg hardware | 163.9 ms | 51.7 ms | 21.8 ms |
+
+Neither required a post-recording remux for reading. This tests already-created media and existing decoders, not a new recorder, editor UI presentation, crash recovery, Windows Media Foundation, or Linux hardware/software decoding.
+
+The same fragmented two-hour file was also opened in the actual GPUI editor and played for five seconds. The app reported 301 rendered frames, 60.0 fps, and zero dropped frames. Audio output and the microphone waveform loaded. The initial `CAP_GPUI_AUTO_SEEK=0.999` run was incorrectly interpreted as a seek near the end of the recording: that driver targets the visible timeline viewport, which can show only the beginning of a long recording. It proves native playback but not native tail playback. The direct decoder and trim/export experiments use explicit timestamps and are unaffected by this correction.
+
+The corrected driver explicitly sought to 7,194.5 seconds, then played for five seconds in the native GPUI editor. Both the progressive output from the concurrent-hashing candidate and the fragmented media experiment reported 300 frames at 59.9 fps with zero dropped frames. Logs confirm the exact requested time. Evidence is in `optimization-stage-3/native-tail-results.json`; this verifies tail playback on macOS, not a two-hour native capture or a p95 latency.
+
+The current Rust exporter successfully rendered a three-second trim from the preserved-AAC candidate and another from 7,195–7,198 seconds of the fragmented two-hour project. Each output contained 90 H.264 frames and a three-second AAC track. Both outputs fully decoded without errors. This is short trim/export coverage, not a complete multi-hour export or visual/aural equivalence test.
+
+After the resampler change, both trims were exported again with the rebuilt exporter and identical settings. Full decoded video and audio SHA-256 hashes matched the preceding candidate's exports in both cases, with no decode errors. Evidence is in `optimization-stage-3/export-validation.json`.
+
+Full audio loading still took approximately 2.05 seconds and the process reached approximately 1.46 GB RSS. A trial using the existing range decoder failed a sample-count comparison near the end of the long replay. Range decoding is not enabled for recorded-track playback by this change. Timestamp discontinuities, AAC priming/padding, and resampling alignment must be resolved before introducing bounded audio loading.
+
+The two-second audio-window experiment took approximately 5 ms per window and used 384 KB of decoded samples, but middle and end windows did not match the full reference on the replay. The same experiment matched every sample at the beginning, middle and end of the original native 60-second AAC track, at 1.2–1.5 ms per window. This distinguishes feasibility from correctness across timestamp discontinuities; it is not a passing long-recording result.
+
+## Longer-term implementation direction
+
+These are design goals, not a claim that arbitrary indexed seeking, bounded total PCM storage or the full recording matrix has been implemented and verified.
+
+The accepted experience is to open the editor as soon as capture has safely stopped and make the beginning playable while remaining preparation continues. A subtle timeline boundary should represent the actual contiguous range ready across display, camera, microphone and system audio, accounting for track offsets. Progress must not be estimated from elapsed time. Playback reaching the boundary must wait without losing audio, advancing the media clock, or presenting incomplete output as complete. Seeking into an unprepared range should prioritize that range or show preparation while preserving the requested position. Full export and recovery requirements still apply.
+
+Produce durable, indexed, editor-readable media during capture. Keep the original encoded media in stable locations. On a clean stop, drain every requested track, flush the remaining media and event tails, commit the final index and project metadata, and open the editor directly on those originals. Whole-recording copying, hashing, transcoding, and remuxing must not remain prerequisites to editing.
+
+Use bounded audio decoding with a small look-ahead buffer and an index that preserves the current sample timeline. Seeking must work anywhere in a long recording without decoding everything before it. Failure to load requested audio must not become a silent successful playback result.
+
+Build cursor/keyboard indexes, thumbnails, and waveform data incrementally. The current stop path serializes complete cursor histories, so the media-only two-hour replay is insufficient to prove that Stop is independent of duration. GPU resources and the editor shell can be prepared during recording; this must be measured for capture contention and frame drops.
+
+Keep clean-stop publication separate from interrupted-recording recovery. A failed drain or incomplete tail must retain the existing failed/recoverable state. Old recording formats continue through their established reader and recovery paths. No crash-recovery validation is removed to obtain a faster timing.
+
+Background jobs must use immutable inputs and must not rename, replace, or delete media underneath an open editor or export. Closing or reopening the app must preserve both the recording and saved edits. Optional consolidation for external compatibility can operate on a separate output when required.
+
+## Progressive audio feasibility
+
+The existing sequential `AudioStream` decoder was compared with the current full `AudioData` decoder over the native 60-second AAC track, its legacy Ogg output, and the two-hour AAC replay. Every chunk's channel count, cumulative sample position and sample bits matched the full reference through EOF. The two-hour decoded SHA-256 remains `5c5c67688b348b9e4d0e54a42e5021c630a7ab8c49c078c892d620e8f7fcd8c9`.
+
+Across three runs, the median time to open and decode the first 250 ms was 0.61 ms for native AAC, 0.74 ms for legacy Ogg, and 4.43 ms for the two-hour AAC replay. The largest returned chunk was 48,000 bytes for these mono tracks. These are warm component observations: full decoding ran first in each process, and sample comparison/hash work is excluded from the accumulated streaming decode time. They do not measure the audio device, editor startup, cold storage, or a production progressive playback path. Evidence is in `progressive-audio-probe/results.json`.
+
+Use `CAP_BENCH_STREAM_AUDIO=1 CAP_BENCH_FULL_AUDIO_ONLY=1` with the audio readiness driver to reproduce this comparison. This sequential decoder avoids the timestamp-to-sample seek mismatch found by the earlier range experiment. It does not yet provide arbitrary seeking or a bounded editor cache. Existing export code also uses `AudioStream`; at this feasibility stage, editor playback still waited for whole-track `AudioLoader` completion.
+
+The same three fixtures were also tested on native Linux, three runs each. Every streamed sample matched the full decoder on that platform. Median first-chunk times were 0.82 ms for native AAC, 1.02 ms for legacy Ogg and 12.31 ms for the two-hour replay, with the same 48,000-byte maximum chunk size. These use the same warm component methodology and do not establish editor startup time. Decoded sample hashes differ between macOS and Linux builds; equivalence is checked against each platform's own full decoder. Linux evidence is in `daytona/long-audio-results.json`.
+
+## Direct fragmented-video decoding
+
+The FFmpeg directory reader previously read every fragment into one allocation, wrote a temporary combined file, and opened that file. It now owns the same seekable virtual input already used by remuxing. Opening retains paths, lengths and one active file handle instead of copying all encoded media. Custom I/O failures remain errors through packet reads and seeks, including when FFmpeg interprets a truncated input as EOF. The input context is destroyed before its custom I/O buffer and callback state.
+
+Shared video metadata loading also accepts fragment directories. On macOS, directories select the existing FFmpeg hardware decoder directly; ordinary files retain their existing AVAssetReader selection. Ordinary project readiness, failure and recovery guards are unchanged. At this stage, direct reading was available, but neither editor yet opened unfinished recordings or moved finalization into the background.
+
+Matched debug-profile decoder runs alternated old and new readers, three runs per variant and fixture. macOS tested both software and actual VideoToolbox decoding; Linux tested software decoding. Each run compared 30 decoded frames at the beginning, middle, near the end and after a backward seek. Visible pixel bytes, timestamps, frame counts and requested hardware selection matched in all 36 macOS runs and all 12 Linux runs. This is sampled frame equivalence, not a complete two-hour decode comparison. A separate generated multi-fragment recording test compares every returned frame and timestamp through EOF and after four seeks.
+
+| Platform and fixture | Decoder | Old first frame median | Direct first frame median | Old / direct peak RSS median |
+| ----------------------------------- | ------------ | ---------------------: | ------------------------: | ---------------------------: |
+| macOS, native screen 15 seconds | Software | 106.31 ms | 64.93 ms | 124.86 / 73.60 MB |
+| macOS, native screen 15 seconds | VideoToolbox | 135.26 ms | 125.55 ms | 156.04 / 103.79 MB |
+| macOS, native microphone 60 seconds | Software | 238.71 ms | 69.34 ms | 205.52 / 71.55 MB |
+| macOS, native microphone 60 seconds | VideoToolbox | 269.64 ms | 130.43 ms | 236.54 / 104.12 MB |
+| macOS, two-hour replay | Software | 1,916.36 ms | 123.47 ms | 2,307.05 / 57.29 MB |
+| macOS, two-hour replay | VideoToolbox | 1,463.52 ms | 190.70 ms | 2,319.83 / 67.99 MB |
+| Linux, native screen 15 seconds | Software | 136.11 ms | 105.14 ms | Not measured |
+| Linux, native microphone 60 seconds | Software | 183.55 ms | 109.91 ms | Not measured |
+
+Timing starts before decoder construction and ends at the first decoded frame, excluding frame hashing. Inputs are warm and builds finish before measurement; three runs do not establish p95 or cold-storage performance. Memory uses decimal MB. Linux two-hour video decoding and Linux hardware decoding were not measured in this comparison.
+
+With the final shared metadata/decoder integration, the GPUI media-readiness driver also read the original fragment directories directly. Metadata loading plus decoder setup plus first frame took 171.80 ms for the 15-second recording, 171.79 ms for the 60-second recording and 264.44 ms for the two-hour replay. All four seek requests returned frames in each case, and durations matched the finalized-file controls. These are single component runs, without an editor window, GPU composition, audio readiness or Stop. Ordinary finalized-file controls continued selecting AVAssetReader hardware decoding.
+
+Evidence is retained in `optimization-stage-5/macos-results.json`, `optimization-stage-5/macos-shared-media-results.json`, and `daytona/stage5/`, with build logs, source manifests and binary hashes. The matched decoder binaries precede the helper's public visibility change and shared metadata integration; the shared-media driver and final checks include those additions.
+
+Final macOS validation passed 114 encoder/remux tests, two decoder tests and 235 rendering tests. Linux passed 118 encoder/remux tests, two decoder tests and 209 rendering tests. Each rendering suite retained five existing ignored tests. Scoped checks and all-targets Clippy with denied warnings passed on both platforms using the repository's Rust 1.88 toolchain; the GPUI dependency check and shared-media driver build also passed using stable Rust. Linux initially lacked the Clippy component; it was installed before the successful run. A separate stable-Rust Clippy attempt reported newly introduced lints in five unchanged encoder tests, so that toolchain result is retained separately from the passing pinned-toolchain checks.
+
+The final macOS binary also finalized another two-hour disposable project in 13,609 ms. Its complete video, AAC audio, recording metadata and project configuration were byte-identical to the preceding guarded candidate. This confirms the shared reader ownership change preserves those outputs; it is a single regression run, not evidence of further finalization speedup. Evidence is in `optimization-stage-5/finalization-replay-2h.json`.
+
+## Required regression matrix
+
+Run the same fixture and native-action drivers in Tauri and GPUI on macOS Intel/Apple Silicon, Windows hardware/software decoder configurations, and Linux X11/Wayland with the supported capture and decoder paths.
+
+Cover short, 5-minute, 1-hour, 2-hour and 8-hour recordings; screen-only, webcam, microphone and system audio; pause/resume, device changes and dropped-input gaps; first and last frames, A/V sync, sample counts, trim/export/reopen; and repeated stop/start cycles.
+
+Inject interruption at media flush, index persistence and metadata publication. Also cover encoder errors, truncated media, a full disk, unavailable output storage, and app close/reopen while ancillary work is running. Originals and diagnostics must survive every failure. Exercise Windows file-sharing restrictions on actual Windows.
+
+Use matched release-equivalent builds, fixed visible capture content, identical settings, repeated cold and warm runs, and concurrent capture-load measurements. Record exact revisions and binary hashes. Any quality, correctness, recovery, or supported-platform regression blocks enabling the new path.
+
+## Daytona function validation
+
+macOS validation ran alongside the Daytona work using the local Apple Silicon build and locked dependencies with Rust stable 1.98.1. The first eight suites passed 864 tests with zero failures: encoder/remux (112), audio (42), recording (477), recovery integration (50), Instant Mode scenarios (61), editor (70), export (32) and GPUI recording/stop (20). There were three existing ignored tests. The project suite added 126 passes, and the A/V matrix added four passing test functions. The first matrix run reported 41 passing scenarios, but one random scenario skipped its video timing check after a 1.19-second runner stall; its audio check passed. A same-seed repeat also skipped that video check after a 1.10-second runner stall, with all other checks passing. Thus 40 scenarios have complete checks and one has audio-only verification. These skipped checks are not counted as verified video behavior; both reports remain retained. Full logs and commands are retained in `macos-function-validation/`. Platform-conditional tests account for differing macOS and Linux suite counts.
+
+The Linux candidate ran on Debian 13 x86_64 in a Daytona container with 4 vCPUs, 8 GiB RAM and a 10 GiB writable filesystem. The source archive contains HEAD `0c403be8a57f7ba4de67140273708a392c8b4050` plus the local candidate; every source file was hashed before upload. Tests used Rust 1.88.0, the committed dependency lockfile, and the repository's FFmpeg/native dependencies installed by `scripts/setup.js`. Debug symbols and incremental compilation were disabled to fit the sandbox. These are native Linux function tests, not UI, physical capture, or release latency tests.
+
+| Suite | Passed | Failed | Ignored |
+| ----------------------------------------- | -----: | -----: | ------: |
+| Encoder/remux library | 116 | 0 | 0 |
+| Audio library | 42 | 0 | 0 |
+| Project library | 126 | 0 | 0 |
+| Recording library on container filesystem | 629 | 3 | 2 |
+| Recovery integration | 50 | 0 | 1 |
+| Instant Mode scenarios | 61 | 0 | 0 |
+| Editor library | 71 | 0 | 0 |
+| Export library | 32 | 0 | 0 |
+| A/V sync matrix tests | 4 | 0 | 0 |
+| Transactional recovery subset on tmpfs | 28 | 0 | 0 |
+
+The A/V matrix reported 41 of 41 scenarios passing with no skipped scenarios. Do not add the tmpfs subset to the other rows as if it contained distinct tests.
+
+Three interrupted-publication/rollback cases failed in the candidate's initial recording-library run. Rebuilding with the five modified shared source files replaced by their unchanged HEAD versions also produced recovery failures, although the failing cases varied. Temporary diagnostic instrumentation captured a directory's reported size changing from 21 to 29 during rename; its entry names, file metadata and Unix identities matched. The existing receipt digest includes directory size, so reconciliation conservatively rejected the state and retained the files. The same candidate transactional group passed all 28 tests on tmpfs. No production guard was relaxed to obtain that pass. At that snapshot, the container-filesystem issue remained an inherited compatibility limitation, not a fully green suite or a reason to omit the failures. A later guarded recovery-stamp fix is recorded in the final verification section. Candidate source hashes were checked after both baseline comparison and temporary instrumentation were restored.
+
+The native 15-second screen and 60-second microphone recordings were then finalized on Linux using matched aggregate-input and virtual-input binaries. All other candidate optimizations stayed identical. Builds completed before measurement, the variant order alternated, and each fixture ran three times per variant. All 12 runs succeeded with byte-identical finalized video, audio, recording metadata and project configuration. Each retained original segment tree also matched its input hash manifest, and the source fixtures stayed unchanged.
+
+| Linux finalization fixture | Aggregate input median | Virtual input median |
+| ----------------------------- | ---------------------: | -------------------: |
+| Native screen, 15 seconds | 745.10 ms | 723.92 ms |
+| Native microphone, 60 seconds | 1,089.72 ms | 1,068.34 ms |
+
+These are modest observed component improvements on a container with warm inputs, using debug-profile builds with debug symbols disabled. Three runs do not establish p95 or a statistically reliable speedup. They exclude capture stop, editor rendering and playback, and do not measure Linux two-hour finalization. Full output hashes, binary hashes, logs and restored source hashes are retained in `daytona/finalization/`.
+
+Windows creation initially returned a tier-access denial through the API and authenticated dashboard despite the earlier support-confirmed grant. Access subsequently became available on September 10, and the user requested parallel validation on all three systems. The earlier errors and Linux function evidence remain under `daytona/`; the new Windows results are recorded below.
+
+## Shared fixture matrix and progressive audio, September 10
+
+Three platform agents ran concurrently. All used the same immutable unfinished `.cap` inputs, reconstructed from a common chunk archive and verified by path, byte length and SHA-256 before testing. Finalization operated on separate disposable copies.
+
+| Canonical input | Files | Bytes |
+| ----------------------------- | ----: | ------------: |
+| Native screen, 15 seconds | 19 | 46,099,193 |
+| Native microphone, 60 seconds | 40 | 121,129,994 |
+| Two-hour encoded replay | 3,388 | 2,396,017,929 |
+
+The final shared runtime candidate is `stage6-32768-track-mixer-v3`. Each platform verified all 4,208 source hashes in `platform-matrix-20260910/candidate-v3-manifest.json`. Its overlay archive SHA-256 is `4c6ca640b2879dbebde40d22cbee12c34e6b299345fbac2b9db600618969b61b`. Earlier v2 media runs remain applicable to the unchanged finalizer and decoder. V3 changes only defensive integer arithmetic in the mixer; affected suites and audio hash checks were rerun on every platform. Subsequent benchmark-driver, documentation and GPUI shell changes are separate from this frozen runtime identity.
+
+### Runtime changes and correctness
+
+Recorded audio now decodes sequentially into immutable blocks of 32,768 sample frames. Consumers can request a ready window while full-track consumers await a separate completion notification. Completion reuses the blocks without making another full PCM copy. Waveforms iterate those same samples in their original order. The normal playback path still awaits complete recorded audio, so these window results do not yet establish early audible playback.
+
+The common mixer now handles one track at a time, hoists unchanged gain/channel calculations out of the per-sample loop, and reads contiguous slices where available. It retains the original track accumulation order, offsets, stereo modes and clamp behavior. A comparison against the original algorithm covered 3,024 cases and 2,007,936 output bytes on macOS and Linux. All matched exactly. A separate extreme-cursor probe found an overflow in the slice fast path; v3 fixes it with checked arithmetic and retains the original silent result. The regression test runs on all three systems.
+
+The macOS codec-failure matrix compared empty files, header prefixes, half truncation, final-byte and final-1,024-byte truncation, and a payload-bit change for both native AAC and legacy Ogg. All 12 old/new cases agreed: six successful pairs with identical full decoded samples, and six matching failure pairs. Original inputs stayed unchanged.
+
+| Final v3 affected suites | Audio | Editor | Export | Failed |
+| ------------------------ | ----: | -----: | -----: | -----: |
+| macOS | 51 | 70 | 32 | 0 |
+| Linux | 51 | 71 | 32 | 0 |
+| Windows | 55 | 70 | 30 | 0 |
+
+Scoped checks and all-targets, no-dependency Clippy passed for the affected shared crates on all three systems. The Windows native matrix totals 1,187 distinct passing tests with zero failures and eight existing ignored tests, including unchanged v2 encoder, decoder, project, recording, recovery, Instant and rendering suites. Windows used Server 2025 x64, Rust 1.88, MSVC and the repository's native dependencies. These headless results do not test physical Windows capture, a GPU decoder or its desktop UI. The Linux dependency-lint and container-filesystem failures described above remain separate unresolved baseline limitations.
+
+### Matched audio benchmarks
+
+Both sides use the same current-thread Tokio runtime and include worker startup and completion notification in their decode timer. The baseline reproduces the old `spawn_blocking` plus `Arc`/watch loader. Runtime construction, full PCM hashing and mixing happen outside the decode timer. Each mixing repetition has a `black_box` barrier. The corrected shared evidence harness SHA-256 is `bf526600f10feccf2186d186309ffb6cea2d7b42ea0d96e7ef6e6c98c96082d1`.
+
+These are three alternating pairs using development builds with optimization level 2. macOS retains debug symbols; Linux and Windows omit them. Compare each platform against its own baseline. Older direct-main-thread baseline measurements and unoptimized Linux measurements are retained for provenance but are not substituted into this comparison.
+
+| Two-hour AAC component | macOS | Linux | Windows |
+| ----------------------------------- | ----------: | ----------: | ----------: |
+| Old background loader, entire track | 1,943.59 ms | 3,287.10 ms | 2,526.91 ms |
+| Block loader, entire track | 1,956.39 ms | 3,241.20 ms | 2,432.86 ms |
+| First 250 ms of audio available | 4.97 ms | 16.35 ms | 13.57 ms |
+
+Every paired full PCM count/hash and mixed-output hash matched within its platform. The entire macOS decode was 0.66% slower in this small sample. Peak process RSS was 1,422.43 MB before and 1,434.35 MB after, an observed increase of 11.93 MB. The roughly 1.38 GB decoded source still remains resident; this is not bounded-memory loading. A 48,000-frame block experiment increased RSS by about 45 MB and was rejected. The extra 11.93 MB peak RSS is an explicitly accepted tradeoff. The full-decode timing difference remains visible; neither result is presented as proof of zero regressions.
+
+On native AAC, the original renderer versus the new block renderer mixed 60 seconds in 7.20 versus 1.21 ms on macOS, over five alternating pairs. On Linux the equivalent two-hour-source experiment measured 28.25 versus 1.80 ms over three pairs. Both matched original PCM and mixed-output hashes. The macOS evidence embeds the original helper in the driver; Linux rebuilds the original function in the library, so their ratios are not cross-platform comparisons. With the same optimized renderer on both storage types, blocks have a small access cost: 1.14 versus 1.23 ms on macOS and 1.72 versus 1.83 ms on Linux.
+
+Windows ran all 18 audio comparisons over native AAC, legacy Ogg and the long AAC replay with exact full PCM and mixed-output matches. Its short full-load medians were 24.71 versus 24.11 ms for AAC and 68.53 versus 67.49 ms for Ogg; first decoded windows arrived at 3.42 and 2.96 ms. Its baseline library restores the original mixer body, matching the Linux original-renderer method. Mixing 60 seconds from the long track measured 25.67 versus 1.42 ms, outside the decode timer. Windows process peak memory and CPU were not collected; decoded-buffer size is not a substitute for those metrics.
+
+### Full project media checks
+
+The updated Linux matrix ran 18 paired decoder probes across all three inputs. Decoded frame pixels and timestamps, including middle and tail seeks, matched. First-frame medians for aggregate versus direct input were 137.30 versus 105.08 ms for 15 seconds, 193.86 versus 111.62 ms for 60 seconds, and 2,665.91 versus 112.35 ms for two hours. These builds used the root workspace's unoptimized development profile; they exclude stop, GPU rendering and presentation.
+
+Twelve paired Linux short-project finalizations succeeded with exact output and retained-source checks. The two-hour candidate finalized in 13,317.68 ms on Linux and 14,388.35 ms on macOS in single regression runs. Each retained all 3,386 original segment files exactly. Published video, audio, project configuration and recording metadata matched across these platforms. All public cursor images/events and keyboard files were included; unordered JSON object keys were compared semantically where serialization order differed. There is no new matched two-hour Linux finalization baseline in this matrix.
+
+The finalized two-hour recording also played in the native macOS GPUI editor after an explicit seek to 7,194.5 seconds: 300 frames over five seconds at 59.8 fps, with zero dropped, skipped or starved frames. Logs confirm the real MacBook Pro Speakers output and no mute override. Audible A/V offset was not independently measured.
+
+Windows passed all 18 paired software-decoder probes and all 14 finalization runs. It used a two-vCPU VM and the unoptimized root development profile. First-frame medians were 188.95 versus 93.14 ms for 15 seconds, 315.83 versus 96.61 ms for 60 seconds, and 7,188.98 versus 628.15 ms for two hours. The three long candidate observations ranged from 190.19 to 650.28 ms, so the median alone must not be used as a latency guarantee.
+
+Windows short finalization medians were 945.44 versus 926.54 ms for 15 seconds and 1,414.75 versus 1,247.67 ms for 60 seconds. Its single long pair measured 42,940.06 versus 38,389.64 ms. All paired published segment bytes and parsed metadata/configuration matched; original segment files and original metadata/configuration remained exact. Supplementary untimed checks also compared every public output against macOS, including cursor images and normalized metadata/configuration, for all three fixtures. The long result reinforces that finalization is still too slow to gate a responsive editor.
+
+Evidence is retained in `macos-validation-20260910/`, `daytona/linux-validation-20260910/` and `windows-validation-20260910/`.
+
+The next integration must preserve source reads across publication, gate editor writes during publication, and prevent the audio/video clock from advancing past unprepared samples. No source validation, finalization requirement or recovery guard has been removed to get the component timings above.
+
+### Rejected Windows preview ownership proposal
+
+An evidence-only source-directory lease synchronized file opens with directory relocation. All five standalone tests passed on macOS and Linux, but Windows passed four and rejected the held-handle relocation with `ERROR_ACCESS_DENIED (5)`. The current FFmpeg `AudioStream` likewise blocked parent-directory rename while open, continued to produce exact samples, and released the restriction when dropped. Explicit `FILE_SHARE_DELETE` did not fix the directory rename, although renaming an individual shared file worked.
+
+This agrees with Microsoft's documented restriction on renaming a directory containing open files. The replacement-file POSIX flag does not establish a workaround for that directory rule. See [FILE_RENAME_INFORMATION](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information). The prototype was never integrated into the application. Its failure rejects that proposed mechanism; it does not change the passing v3 media results. Production publication semantics remain unchanged.
+
+The next design must either keep preview sources in a stable location throughout publication or explicitly release every affected reader while preserving buffered playback and exact decoder state. A path redirect alone is insufficient. Evidence includes `optimization-stage-7/source-lease-probe.rs`, the per-platform results, and Windows `rename-probe.log`/`source-lease-tests.log`.
+
+A second standalone prototype registers cached file handles with the source owner. Before relocating the directory, it closes all registered handles under an exclusive source lock; subsequent reads reopen at the preserved byte position. The identical `revocable-source-probe.rs`, SHA-256 `d62a69df330dff6d1fba36bf37e453f429552422c7a5245efed85dc15f3f8008`, passed all seven tests on macOS, Windows and Linux with Rust 1.88, optimization level 2, overflow checks and denied unused results. Coverage includes four simultaneous readers through 600 moves, successful and failed publication, rollback, seek positions, and changed-length rejection. This supports the filesystem mechanism only. FFmpeg/AVIO integration, exact decoded-output comparisons, publication latency and playback buffering are still required.
+
+## GPUI early loading shell
+
+This early shell change opened the existing `Loading project...` editor after a successful, generation-matched capture acknowledgement. `Phase::Stopping` and its detached task still own finalization and shutdown. Linux first completes the existing capture-visibility restoration protocol. At this shell-only stage, preflight, media readers, editing and saving remained behind successful full finalization, including the existing thumbnail and project configuration work.
+
+Presentation is tracked by recording generation, finalization job and actual window ID. Closing a preparing editor suppresses automatic reopening; explicitly reopening it uses the same readiness gate. Completion races and window-creation failures retain the existing fallback. Failed tracks, low storage, Instant recordings, non-editor preferences and in-editor recording targets keep their existing paths.
+
+The review found and fixed a camera-preview cleanup omission in the initial shell change. Finalization completion now parks the feed even though it no longer reopens or refocuses the editor. GPUI's binary test target also exposed a Stage6 test compilation regression: the waveform refactor removed a constant still used by two tests. The constant is restored inside the test module; runtime audio remains unchanged.
+
+macOS GPUI package check and 128 targeted tests passed: recording 45, session 15, app windows 26, timeline 42. Native extraction harnesses ran the same relevant production function bodies with scaffolding on Linux (35 passed) and Windows (22 passed plus check). They cover readiness, dismissal/reopen, stop outcomes, terminal ownership and restoration acknowledgements. They do not execute a real GPUI observer, compositor or typed capture device. Full native GPUI checks outside macOS were still pending at this shell-only stage; later frozen app suites are recorded below.
+
+Strict stable-toolchain GPUI Clippy with tests reported 30 issues in other code regions, including new `chunks_exact` recommendations and existing documentation/argument-count issues. No warning was suppressed, and no passing full-application Clippy result is claimed. The scoped shared-runtime checks described above remain separate.
+
+The first native shell attempt caught a panic in newly added timing instrumentation: `request_animation_frame` is invalid outside GPUI's render phases. That run is rejected and its isolated source and logs retained. A disposable copy recovered successfully, preserving all 36 original source files exactly and producing a complete decodable video. The instrumentation now uses the supported `window.refresh` call.
+
+A fresh native macOS run captured a synthetic AppKit window for 60 seconds at 60 fps, then used the ordinary Stop and editor playback paths. Microphone and system audio capture were disabled. The binary SHA-256 is `c98f054a08334e029801e94d5de1e07915caf994434d2f820d69a54e0dee994b`.
+
+| Milestone after Stop | Elapsed time |
+| ------------------------------ | -----------: |
+| Capture shutdown acknowledged | 37.41 ms |
+| Editor shell created | 49.68 ms |
+| First frame-cycle upper bound | 62.60 ms |
+| Finalization completed | 317.51 ms |
+| Project validated | 323.68 ms |
+| Editor instance created | 1,130.83 ms |
+| First recording frame received | 1,180.02 ms |
+
+Playback delivered 301 frames over five seconds at 60.1 fps with zero drops. Full video decoding passed, metadata and configuration parsed, and all 36 originals totaling 13,576,177 bytes were retained. The screenshot shows the existing loading editor with editing/export gated by `project_ready`; recording controls have closed.
+
+This is one native flow, not a matched old/new comparison or a p95 result. The two-frame callback gives a frame-cycle upper bound, not a compositor scanout timestamp. Default audio output was enabled, but this screen-only recording does not verify audible A/V synchronization. The early shell is visible quickly; playable content still waits for finalization and editor setup. Evidence and exact source hashes are in `optimization-stage-7/gpui-shell/implementation-manifest.json`, `native-stop-fixed/verification.json` and `interrupted-recovery-verification.json`.
+
+## Managed source input and publication
+
+The Stage8 input keeps FFmpeg decoder state while the finalizer moves original segments. It closes registered file handles under the source owner lock, then reopens them at their preserved byte positions. Each file retains its identity, length and modification-time checks; ordinary file readers retain their existing paths. Cancellation callbacks run outside that lock. This mechanism is still an optional API; the preparing editor does not use it yet.
+
+Frozen `native-io-v1` passed 190 native media-library tests on macOS, 194 on Linux and 190 on Windows, with scoped check and strict Clippy. Native AAC60, legacy Ogg60 and AAC2h matched every decoded sample through publication, failed moves and rollback. All three canonical video fixtures matched decoded pixels and timestamps, including tail seeks, while the managed decoder stayed alive. macOS included actual VideoToolbox; Windows and Linux used software decoding. Original canonical files remained byte-exact. These component tests do not establish synchronized preparing-editor playback.
+
+The first video timings had a cache-preparation asymmetry: the reference was hash-read before construction, while the disposable candidate copy was only hash-read afterward. Those results remain in the evidence but cannot isolate API overhead. Corrected probes hash-read both inputs outside the timer, use the same probe with both library versions, and balance which decoder opens first. Native hardware cold-start and warm-start samples remain separate.
+
+The v2 reader registers at most 64 files per lock acquisition, sharing repeated parent checks inside each batch while preserving every file snapshot and all reopen checks. On Linux with optimization level 2 and four balanced repetitions, corrected two-hour managed constructor-to-first-frame median improved from 194.21 to 163.22 ms. The ordinary control stayed at 113.43 versus 115.67 ms. Short managed medians were 100.30 versus 101.01 ms for 15 seconds and 108.28 versus 106.29 ms for 60 seconds. These are warm-input component timings, not Stop latency or a p95 result. The measured cancellation response after a separate thread requested cancellation was below 0.72 ms with batching, versus below 0.03 ms before batching.
+
+The optional managed finalizer changes only the original-segment move and its rollback. Its exclusive recovery lock refuses a pending publication receipt without reconciling it behind active readers. Existing publication checks, original hashes, staging, configuration and metadata commit order remain unchanged. Six new tests cover a live 61-second audio decoder through actual finalization, successful publication, every failed publication rename, failed rollback, the wrong project source and interrupted-publication handoff. At this stage, all preview decoder workers had to acknowledge shutdown before ordinary receipt reconciliation or the ordinary editor took ownership. The later successful-publication handoff adds an explicit continuation path for already-admitted readers. Native v2 validation is complete, with the platform limitations below retained.
+
+macOS v2 passed 260 native tests (64 recovery, 54 audio, 139 encoder and 3 video), scoped checks and strict all-target Clippy. Its 48 balanced constructor trials and six full video lifecycles included software and actual VideoToolbox. Full audio samples, video pixels/timestamps and all 3,447 canonical fixture files matched. The two-hour software managed constructor-to-first-frame median improved from 195.29 to 166.78 ms. VideoToolbox opened first improved from 270.41 to 248.19 ms; opened second improved from 206.60 to 165.71 ms. These hardware strata must remain separate.
+
+Linux v2 passed its audio, encoder and video suites; recovery passed 64/64 on tmpfs and 61/64 on the sandbox root filesystem. The root-filesystem failures are triggered by a pre-existing publication receipt guard: a directory allocation size changes from 21 to 29 bytes during rename while its identity, times and recursive children remain unchanged. The original repository HEAD has byte-identical guard functions, and its retained baseline also fails interrupted-publication cases on that filesystem. The new managed handoff test exposes the same guard. No check was relaxed at that stage; this was then an unresolved filesystem-specific recovery limitation, not a clean all-filesystem sign-off. The subsequent guarded stamp fix has its own native results below. Detailed provenance is in `managed-recovery-linux/receipt-guard-provenance.json`.
+
+Windows v2 passed 255 native tests (60 recovery, 58 audio, 131 encoder and 6 video), all four scoped crate checks, media all-target Clippy and recording library Clippy. Full-target recording Clippy hits an unchanged `items_after_test_module` finding in `capture_pipeline.rs`, verified byte-identical to HEAD. The three full video lifecycles and three full audio comparisons passed; the two-hour audio contained 345,675,776 exact samples. All canonical inputs and 4,212 frozen source files remained unchanged.
+
+Windows used one prepared copy per fixture, with both complete input trees hash-verified before and after each batch of eight fresh processes. The same probe and root dev profile (Rust 1.88 MSVC, optimization level 0, debug info 0) ran both runtime versions, balancing library and decoder-opening order. Four repetitions per variant gave managed constructor-to-first-frame medians of 115.52 to 92.21 ms (15 seconds), 130.84 to 113.90 ms (60 seconds), and 479.31 to 363.15 ms (two hours). The two-hour ordinary control varied from 217.18 to 246.64 ms, so cache and small-sample qualifications remain material. These numbers cannot be compared directly with macOS/Linux optimization-level-2 timings. Windows cancellation request-to-return was 0.696–0.911 ms with batching versus 0.048–0.057 ms before; the maximum callback interval was 1.898 ms. This measures input-constructor cancellation, not full worker shutdown. Evidence: `windows-validation-20260910/stage8-managed-recovery-v2/{terminal,prepared-timing-summary,cancellation-results}.json`.
+
+Evidence: `optimization-stage-8/native-io-v1-manifest.json`, `native-io-macos/summary.json`, `native-linux-io/`, `enc-input-v2/`, `managed-recovery-v2-manifest.json`, `managed-recovery-v2-macos/summary.json`, `managed-recovery-linux/linux-stage8-summary.json`, and the native Windows results. At that snapshot, the separate early-editor and progressive-playback contracts described remaining integration work; later sections record their implementation.
+
+### Editor startup diagnostic
+
+The startup driver can now profile stages in a fresh process before normal startup (`--profile-stages-only`) and separately measure font preparation (`--prewarm-fonts`). A missing first preview frame now fails the driver instead of contributing an infinite value that was excluded from summaries.
+
+One initial stage profile took 882.3 ms, including a remaining renderer-layer wait of 663.5 ms. A subsequent ordinary process took 118.3 ms without font prewarming. Four balanced fresh-process comparisons on the same finalized 60-second project measured constructor-to-first-preview medians of 137.15 ms ordinarily and 134.45 ms with fonts prepared beforehand; that separate font preparation took about 12 ms. OS and driver caches were not reset. This does not establish fonts as the initial delay's cause, so no production font-prewarm change was accepted. These measurements exclude Stop, finalization, UI presentation and playback. Evidence: `optimization-stage-8/font-startup/summary.json`.
+
+## Managed decoder worker and lifetime
+
+Stage9 adds an optional managed decoder worker around the shared existing FFmpeg frame-selection loop. Startup returns an owner before waiting for readiness. Cancellation wakes the worker; `stop_and_wait` acknowledges an actual native thread join after its decoder, custom input and cached frames are dropped. Managed decode/seek errors are terminal, and cancelled readiness or shutdown waiters retain cleanup ownership. Ordinary decoder entrypoints preserve their existing frame, cache, offset, hardware fallback and VFR hold behavior.
+
+`RelocatableSource::new_with_owner` retains an external lifetime guard through every source clone and reader. Reader field drop order closes cached files before releasing the last guard. Seven tests include Windows exclusive file opens inside the guard destructor, which would fail if handles remained open. Recording-owned recovery-lock binding was still pending at this stage; this generic source API did not connect the preparing editor by itself. Metadata extraction now exposes the same existing `Video::from_input` and `Audio::from_input` calculations for an already-open input, preserving ordinary path behavior.
+
+The frozen seven-file overlay is `optimization-stage-9/managed-worker-v1-overlay.tar.gz`, SHA-256 `7845c712628f9ad99f8d9bc882bc14e3c1bf1d2539f9c1d4e863bd4b958a18a2`. Both Cargo locks were regenerated by Cargo with no package version, source or checksum drift; only rendering dependency edges changed.
+
+- macOS: 518 tests passed, five existing rendering tests ignored; formatting, six scoped crate checks and strict all-target Clippy passed. The actual worker matched ordinary software and VideoToolbox pixels through a three-second PTS gap, a 0.25-second handle offset, repeated publication and forward/backward/tail/cache requests. Logs confirm hardware was actually used.
+- Windows: 486 tests passed, five existing rendering tests ignored; scoped checks, media/rendering all-target Clippy and recording library Clippy passed. All owner-lifetime, interruptible-constructor and managed-worker cases passed, including the Windows exclusive-sharing teardown assertion. The inherited recording all-target lint remains documented above. Source and canonical fixture hashes match; the owned VM was stopped with caches and evidence preserved.
+- Linux: 431 media/worker tests passed, five existing rendering tests ignored; scoped check and strict all-target Clippy passed. Recovery remained 61/64 on the root filesystem and 64/64 on tmpfs, with the same three documented pre-existing receipt-guard cases. Native Rust formatting also passed after installing the pinned component. Final source and binary provenance is retained in `optimization-stage-9/native-linux/linux-stage9-summary.json`; both owned Linux sandboxes are stopped with their files and caches preserved.
+
+The first missing-fragment test used an incorrect hard-coded target: 9.5 seconds was intact media, while macOS's deleted last fragment began at 9.8 seconds. That failure is retained. The corrected test derives its target from the packet's physical fragment position, PTS and actual renderer frame mapping, and independently asserts the underlying ENOENT/EIO. It then checks terminal decode/seek failure, the same error on a later frame-zero request, and the shutdown acknowledgement. Linux's encoded fragment boundary differs, validating the need for packet-based targeting.
+
+Evidence: `optimization-stage-9/native-macos/summary.json`, `windows-validation-20260910/stage9-summary.json`, `optimization-stage-9/native-linux/`, and `optimization-stage-9/missing-fragment/`. This stage verifies functions and worker lifetimes; it adds no new Stop-to-editor latency or p95 claim. The recording-owned source observer, restricted editor projection and synchronized progressive playback remain to be connected and validated.
+
+## Recording-owned preparing sources
+
+Stage10 adds a private, single-use clean-stop receipt and a retained observer for read-only source access during finalization. Receipt eligibility is bounded and does not change persisted recording data or make a successful Stop fail. The projection checks the exact stopped metadata/configuration, fragment inventory, required tracks, diagnostics and cursor assets. Unsupported layouts fall back to ordinary finalization. Its source readers retain the real recovery lock, follow owned publication/rollback moves, and are revoked when finalization ends. In the Stage10 snapshot, already-running readers still had to be cancelled, joined and dropped before ordinary reconciliation.
+
+The production application did not consume this observer in the initial Stage10 snapshot. The full initial source snapshot, staging, validation, source rechecks, synchronization and transactional publication remain in their existing order. Moving availability ahead of the first snapshot would permit previewing one version of a source while finalization accepts a later version; that reorder was rejected during review. Existing renderer construction also has configuration-loading fallbacks that cannot be used by a restricted preparing preview.
+
+Frozen v1 native validation used identical source hashes and canonical recordings:
+
+| Platform | Recording tests | Native canonical preparing coverage |
+| -------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| macOS | 90 recovery and 8 receipt tests passed | All four video requests on each short fixture; all 2,883,584 microphone frames on the 60-second fixture matched exactly |
+| Windows | 85 recovery and 8 receipt tests passed | All four video requests on each short fixture; the same complete microphone sample count matched exactly |
+| Linux | 90 recovery and 8 receipt tests passed on tmpfs | Two video requests on the 15-second fixture and three on the 60-second fixture before finalization ended; the complete microphone sample count matched exactly |
+
+Every observed video frame was compared against an independently finalized MP4 through the same software decoder. Final public media bytes, normalized metadata/configuration, retained originals and canonical inputs matched. The actual recovery lock could be reacquired after worker teardown. Linux's remaining video requests were cancelled at finalization completion and are recorded as unobserved, not passed early-preview coverage. These fixed-order functional probes do not measure Stop-to-editor latency, audible playback, speedup or p95.
+
+Scoped compiler and formatting checks passed. macOS passed strict recording Clippy across all targets and a standalone GPUI check. Windows retained its inherited all-target lint qualification while the scoped strict gates passed. Linux strict library/tests Clippy passed; its all-target example failure is byte-identical to HEAD. On the Linux sandbox's regular root filesystem, five existing interrupted-publication receipt cases failed, while the identical binary passed all 90 recovery tests on tmpfs. The exact test bodies and receipt guards are byte-identical to HEAD; this run does not establish a new five-failure baseline or remove that platform qualification.
+
+The original two-hour canonical recording finalized successfully on all three systems, preserving its sources and producing all four finalized-file reference frames. It then declined the test receipt before preparing playback began: its explicit empty `cursors` object deserializes as the legacy cursor representation. A live Stop holds the current representation and its writer omits that empty field. The v1 failure and zero long preparing coverage remain recorded. Test-only v2 removes that one empty field through the actual writer on both disposable comparison copies, verifies unchanged typed metadata/configuration and every media/sidecar byte, and retains a separate hash-linked legacy control. Four new tests passed natively on each platform; they verify the transformation and reject nonempty legacy cursors or unknown fields without writes. No production validation predicate changed.
+
+The normalized two-hour v2 probes passed on all three platforms. Each compared all four requested video seeks (0, 3600, 7194.5 and 1 seconds) against an independently finalized MP4 and all 345,675,776 audio frames bit-for-bit through EOF. Published media, normalized documents, retained originals and canonical hashes matched. Actual worker joins, source release and recovery-lock reacquisition passed. macOS and Linux also produced identical visible pixel hashes and published media/document bytes.
+
+These unoptimized, ordinary-first functional runs are not performance comparisons: source availability was observed at 15,592.17 ms on macOS, 948.55 ms on Linux and 1,546.92 ms on Windows; first returned video frames were at 16,141.58, 1,145.54 and 2,580.97 ms respectively. Cache state, hardware and concurrent preview work differ. No rendered editor frame, audible synchronization, product Stop latency or p95 is established. The full source snapshot still precedes availability; removing that protection has not been accepted.
+
+V2 evidence is retained in `optimization-stage-10/native-macos/assessment-v2-long.json`, `optimization-stage-10/native-linux-v2/assessment-v2-long.json`, and `windows-validation-20260910/stage10/summary-v2.json`. Both Windows test executables and the macOS/Linux v2 executables are retained. The Windows archive contains 1,032 size/hash-verified members, and its owned sandbox is stopped with source, fixtures, outputs and cache preserved.
+
+Evidence: `optimization-stage-10/native-macos/assessment-v1.json`, `windows-validation-20260910/stage10/`, `optimization-stage-10/native-linux/linux-stage10-v1-summary.json`, `optimization-stage-10/canonical-probe-v2/`, and `optimization-stage-10/early-availability-review/`. The original macOS v1 test executable was overwritten by its test-only rebuild; its binary hash, dependency hashes, source snapshot and raw results remain, but that exact executable was not separately retained.
+
+## Owned preparing frame controller
+
+Stage11 adds a separate, read-only frame controller to `cap-editor`. It returns a lifecycle owner before setup awaits; a retained stop handle waits for its actual Tokio task and all native decoder threads. The controller reuses ordinary segment timing, cursor smoothing, zoom uniforms, frame layout and immediate render methods. It never constructs an ordinary `EditorInstance` or loads/writes project configuration. Unsupported presentation, unresolved calibration offsets or inconsistent metadata decline preparation.
+
+Requests are coalesced into one latest pending frame with one decode/render in flight. Lazy initialization is cancelled only when the entire preview stops; an obsolete scrub cannot cancel its decoder. Completed render output is checked for frame number, dimensions and request sequence before delivery. The ordinary three-attempt render retry policy is retained, with ordinary `get_frames` behavior on retry. Source/decoder/cursor errors remain terminal. At most two display/camera segment pairs stay open; eviction waits for actual teardown, and late failures are retained rather than lost with an evicted worker.
+
+Frozen cursor assets share immutable image bytes and retain the ordinary SVG/PNG priority and image-format selection. Existing file loaders delegate to the same new cursor-reader and keyboard-byte parsers; no ordinary parsing or fallback order changed. Keyboard-enabled presentation and camera background blur currently require ordinary loading. The Stage11 validated bundle has no app consumer; the subsequent Stage12 integration is described separately below.
+
+The corrected common v2 candidate passed the native scoped gates on all three systems:
+
+| Platform | Editor | Project | Rendering | Total passed | Existing ignored |
+| -------------- | -----: | ------: | --------: | -----------: | ---------------: |
+| macOS arm64 | 82 | 130 | 266 | 478 | 5 |
+| Linux x86_64 | 83 | 130 | 239 | 452 | 5 |
+| Windows x86_64 | 82 | 129 | 239 | 450 | 5 |
+
+Formatting, scoped checks and strict all-target Clippy passed. macOS scoped checks also include Tauri and GPUI. The project/rendering results carry forward from v1 because all runtime sources are byte-identical; v2 changes only the native fixture duration and reruns the complete editor suite on every system. Linux uses Mesa llvmpipe through Vulkan; a separate probe of the same production adapter factory selected Microsoft Basic Render Driver through DX12 on Windows. This is software-sandbox coverage on Windows/Linux, not proof across physical GPUs.
+
+The four-second v1 fixture failed before rendering on Linux and Windows: their libx264 encoder produced two fragments, below the test's required three. V2 generates three existing encoder GOPs (currently six seconds), preserving every assertion and requested frame time. All four composed cases then executed and passed on all three systems. The original failures remain recorded. Clippy also caught a test fixture initialization style issue; it was corrected and rerun. Controller tests caught a readiness notification race that could mask the original initialization error with cancellation; the final implementation retains the actual error.
+
+Four composed native tests compare visible RGBA pixels and frame layouts against independently finalized ordinary media. They cover PNG/SVG cursors with explicitly changing cursor samples, nonidentity zoom, independently encoded display/camera with distinct FPS and timing offsets, forward/backward/tail seeks, source relocation, three-clip eviction/reopening and a callback panic followed by native joins and source-owner release. Four additional deterministic native-thread tests cover failure while idle or after a returned frame and dropped terminal waiters, with release barriers proving both joins. These synthetic component tests do not measure Stop latency, audio synchronization, physical multi-clip capture, UI presentation or p95. Hardware decoding is requested but not asserted by the controller test API; the composed comparison uses RGBA. The original shared `.cap` fixtures remain unchanged.
+
+The frozen 15-file v2 bundle is `optimization-stage-11/preparing-controller-v2-overlay.tar.gz`, SHA-256 `78114380b3fba19df63a50e5a177f8c66fbbd1a1fc29397084e6a829e3382e60`; its manifest is `ef1b93c9a4c9c87b5b71a955a504a71d950a4c6dc8fa86bde44b931b6ab0e26b`. Evidence: `optimization-stage-11/native-combined-macos-v2/assessment.json`, `optimization-stage-11/native-linux/assessment-v2.json`, `windows-validation-20260910/stage11/`, `native-preview-macos/summary.json`, and `managed-terminal-tests/`. Exact v1/v2 editor executables are preserved. Stage11's helper compares collected visible bytes, dimensions and layout, but equal truncation of both buffers is not independently excluded by a byte-count assertion. No truncation was observed. Stage12 adds explicit complete-buffer length and stride assertions.
+
+## GPUI preparing image integration
+
+Stage12 connects the recording-owned observer to a GPUI loading window. The consumer requests the composed first image, checks the current recording attempt and window identity before delivery, and retains actual task and native decoder completion across close/reopen. Ordinary project loading waits for every retained consumer for that project. Closing a preview does not cancel recording finalization. The image remains read-only: playback, editing and export still require the ordinary ready editor. Progressive synchronized playback and a playable-range UI remain unfinished.
+
+The GPUI adapter preserves stopped configuration and uses the same initial clip-calibration calculation as ordinary loading. Current camera blur and selected animated-gradient preferences decline this early image. Keyboard presentation still declines; merely recording a keyboard sidecar does not, because GPUI ordinary rendering requires an explicitly configured keyboard overlay. The raw files remain available unchanged to ordinary loading and later user actions.
+
+The frozen Stage12 shared-core native matrix is complete, with the Linux filesystem qualification below. These scoped function and synthetic composed-frame tests exclude app consumers. Platform-specific tests account for the different totals; each platform also retains one ignored manual canonical probe.
+
+| Native platform | Editor | Recovery | Receipt | Passing total |
+| ----------------------------------------- | -----: | -------: | ------: | ------------: |
+| macOS | 88 | 101 | 8 | 197 |
+| Linux, same recording executable on tmpfs | 87 | 101 | 8 | 196 |
+| Windows | 86 | 96 | 8 | 190 |
+
+Linux recovery on the regular container filesystem passed 98 tests and failed three with `Conflicting recovery publication state; all files retained`; the same executable passed all 101 on tmpfs. Two failing test bodies and the relevant receipt guards are byte-identical to repository HEAD. The third test was introduced during Stage8 and already exposed the same rootfs limitation there; it is not an inherited HEAD test. The failure names and exact provenance are retained in `native-linux/receipt-source-provenance.json`. This remains a qualified result, not a clean Linux rootfs gate.
+
+Scoped format/check gates passed on all three platforms. Strict recording Clippy passed for lib/tests on macOS and Linux, and lib on Windows; editor all-target Clippy passed on all three. Seven new public-finalizer paired cases cover output/error parity and observed preview admission or decline, and three initial-calibration tests passed. Native composed cases include cursor assets, camera, zoom, relocation, three-clip eviction/reopen, keyboard-sidecar behavior and actual cleanup after callback panic. Full dimensions, stride and buffer length are checked before pixel comparison. macOS also asserts the ordinary AVAssetReader backend and actual BGRA surface parity. Linux ran the cases on software llvmpipe/Vulkan; there is no discrete Windows GPU claim.
+
+All 17 frozen overlay members, 26 Linux runtime members and 82 Windows evidence archive members were independently verified against their SHA256/size manifests, along with the exact retained macOS editor executable. Windows canonical fixtures matched before/after; Linux's three retained audio components matched, and its canonical media sandbox was not resumed. Linux and Windows build VMs were stopped with artifacts retained. Evidence and exact executable/source identities are aggregated in `.git/stop-editor-20260909/optimization-stage-12/native-summary.json`. The later Tauri dependency entry and renderer diagnostics are separate from this frozen source.
+
+On macOS, 39 targeted GPUI lifecycle, finalization, presentation and capture-stop tests also passed. The app compiles with the current stable toolchain. Strict GPUI all-target Clippy reports 28 unique inherited findings: each diagnostic context was checked against HEAD `0c403be8a57f7ba4de67140273708a392c8b4050`. This is a qualified gate, not a clean whole-app Clippy result. Evidence is under `native-gpui-macos/` and `gpui-consumer-review/clippy-provenance.json`.
+
+Four actual GPUI runs used matched builds in baseline/candidate/candidate/baseline order, each recording the same synthetic window scenario for about 60 seconds at 2560×1504. Each row is a distinct recording. Times below are milliseconds from the app's Stop marker; the ordinary-frame column records receipt by the ordinary editor.
+
+| Run | Capture stopped | Loading shell | Early composed image | Next app cycle for early image | Finalization finished | Ordinary first frame |
+| ------------ | --------------: | ------------: | -------------------: | -----------------------------: | --------------------: | -------------------: |
+| 01 baseline | 37.9 | 50.5 | — | — | 300.3 | 1,067.7 |
+| 02 candidate | 46.1 | 60.6 | No early image | — | 298.0 | 878.1 |
+| 03 candidate | 43.7 | 58.7 | 185.3 | 190.4 | 287.0 | 332.2 |
+| 04 baseline | 49.2 | 61.6 | — | — | 291.9 | 383.2 |
+
+Only one of two candidate runs produced an early image. In run02, sources were available at 64.0 ms, but finalization ended before renderer readiness. The ordinary path proceeded after retained preview cleanup and preflight, reaching its validation marker at 814.5 ms; that interval is not an isolated cleanup measurement. Run03 produced the image at 185.3 ms and reached the next app cycle at 190.4 ms. The app-cycle marker does not independently prove external compositor presentation. Different initialization costs and only two observations per variant prevent p95, significance or universal speedup claims. No two-hour app timing or audio synchronization was measured.
+
+All four runs finalized, sought and played for about five seconds with zero dropped frames in the app logs. Complete post-run decoding compared every published frame and PTS against that run's retained original fragments: all 14,380 matched. Cursor/keyboard sidecars remained byte-identical, and all 192 retained project files were rehashed against the audit manifests. Configuration changes were limited to ordinary duration calibration (at most 4.5 microseconds in these runs); metadata changed only completion status and display path. The audit compares each recording to its own original, not media across runs. Raw results and matched-source/binary provenance are in `gpui-native-stop/summary.json`.
+
+The Tauri consumer is now applied. Its earlier complete native library run passed 446 tests; after the presentation extraction, nine new configuration/adapter-guard tests passed and the 61-test recording scope passed, including five of those nine. These counts must not be added as independent runs or described as a latest full 455-test run. Tauri Rust format/check and strict lib/tests Clippy passed, two command bindings were generated, six frontend files passed Biome, ten lease/socket tests passed, and desktop TypeScript checking passed. Tauri conservatively declines recorded camera and raw keyboard inputs: ordinary Tauri loading automatically creates keyboard presentation from raw events. The new parity tests establish configuration and guard behavior; subsequent genuine Tauri capture evidence and its remaining handoff issue are described below.
+
+A subsequent Tauri change stops an abandoned admission after its response receiver disappears, joining the owned transport without waiting for or cancelling recording finalization. Its ten-test native consumer scope passed, including the new pending-finalization case; formatting, scoped check and strict lib/tests Clippy also passed. The 15-file consumer snapshot is retained in `tauri-applied-v2/manifest.json`. These scoped runs overlap earlier tests.
+
+The opt-in native Tauri pixel/DOM capture harness subsequently passed formatting, scoped check and strict lib/tests Clippy. Its exact retained macOS library executable passed all 459 tests, including three frame-capture/fixture-selection tests. The first launch failed before tests because the nested artifact directory lacked its required Frameworks path; an owned Frameworks symlink fixed the layout, and the same executable then passed. This is harness and library validation; the two native WebView diagnostics below follow this suite. The fresh static frontend build succeeded with all 326 inspected source/config hashes unchanged, and its 693-file public output is retained. Evidence is in `tauri-native-preparation/harness/native-v2.json` and `tauri-native-preparation/frontend-result.json`.
+
+Two subsequent native Tauri diagnostic captures, 15 and 120 seconds, finalized successfully. All 895 and 7,169 decoded frames respectively matched each run's own retained source fragments in pixels and PTS; project/source trees were unchanged during verification. Both captured ordinary RGBA frame zero, but neither produced preparing RGBA or a visible preparing canvas. The parity verifier correctly reports incomplete. DOM observations therefore do not establish a seamless preview handoff. These unoptimized debug runs are functional diagnostics, not release latency benchmarks. The private log override passed its three native tests and scoped binary check/strict Clippy; normal log paths are unchanged. Evidence: `tauri-native-run/verification-matrix.json` and both `untimed*/benchmark.json` results.
+
+Source tracing explains the missing Tauri admission: `clean_capture::prepare` returns `None` on macOS/Windows, but the new preparing finalizer required the resulting Linux-only generation to be present. A correction giving actual recording finalizations their own checked, monotonically allocated identity is now applied; formatting, scoped check, strict Tauri lib/tests Clippy and all 461 native library tests passed, including allocation, duplicate, exhaustion and stale/recovery admission cases. The updated native executable then passed a genuine 120-second capture: preparing and ordinary frame zero matched all 3,358,368 visible RGBA bytes, dimensions and layout, and both canvases were observed visible. All 7,157 published frames and PTS matched the retained original fragments; all 66 original files were retained and the project tree stayed unchanged during audit. Generic crash-recovery requests, genuine clean-stop receipts, source ownership, current-attempt checks and failure handling remain guarded. Evidence is in `tauri-native-run/untimed-120s-v2/`.
+
+The corrected capture observed a live preparing canvas, then its retained image, then the ordinary canvas without a sampled blank state. A remaining size transient prevents a seamless-handoff claim: the preparing image measured 787.11 by 462 CSS pixels, the first ordinary image grew to 803 by 471.31, and it settled back after about 103 ms. The first visible preparing sample was approximately 725.7 ms after Stop; the benchmark ordinary-frame marker was 1,606.7 ms. These are unoptimized, instrumented functional observations, not release or p95 results, and DOM samples do not independently establish compositor presentation. The 569 native source, 326 frontend source/config and 693 embedded asset hashes remained unchanged through this capture.
+
+A further 120-second native layout diagnostic reproduced the transient and established its immediate cause. At first ordinary visibility, the actual container was already 835 by 494 pixels and all parent, toolbar and timeline geometry was at its final size. The accepted canvas alone retained 803 by 471.31 dimensions for 109 ms before settling to 787.11 by 462. The preparing/ordinary frame-zero pixels matched exactly again; all 7,171 published frames and PTS matched their original fragments, and all 26,930,830 original source bytes were retained. Native/frontend/asset hashes and owned-process shutdown passed. The additional bounded DOM geometry instrumentation makes this an untimed functional diagnostic. Evidence: `tauri-native-run/native-v3-assessment.json` and `untimed-120s-layout-v3/layout-analysis.json`.
+
+The first sizing fix passed 17 related frontend tests and desktop TypeScript, but its actual 120-second native v4 capture still showed the same 109 ms size transient. It therefore failed the intended visual outcome. Preparing and ordinary frame-zero pixels matched all 3,358,368 visible bytes; all 7,092 published video frames and PTS matched their retained originals, and all 26,559,920 original bytes remained unchanged. Source, binary, embedded assets and shutdown checks passed. The next refinement keeps initial geometry eager through one animation-frame remeasurement, preserving later 100 ms resize debouncing and cancelling pending work on teardown. Its subsequent native verification is recorded below. Evidence: `tauri-native-run/native-v4-assessment.json` and `tauri-initial-bounds-fix/first-paint-refinement/`.
+
+The refined v5 candidate passed 21 related frontend tests, desktop TypeScript and the private static/native builds. Its genuine 120-second capture used identical preparing and first ordinary bounds of 787.109375 by 462 pixels, with no later canvas-size transition in the following 1,001 ms of bounded DOM observations. Frame-zero RGBA parity passed. All 7,068 published video frames and PTS matched retained originals, all 26,426,138 original source bytes remained intact, the project tree stayed unchanged during verification, and owned processes shut down after finalization. This establishes the intended sizing outcome for this native case; it remains an unoptimized, instrumented functional check, with no audio/camera or external compositor/p95 claim. Evidence: `tauri-native-run/untimed-120s-bounds-v5/layout-analysis.json`, `parity.json` and `verification.json`.
+
+Fresh Windows validation of the current 1,356-file source freeze passed 770 native tests, with six existing/manual tests ignored. The native adapter was Microsoft Basic Render Driver through DX12. Scoped checks and strict encoder/audio/video/project/rendering/editor Clippy passed. Recording library Clippy passed; its test target retains an inherited `items_after_test_module` finding in a file byte-identical to HEAD. Both canonical 15-second screen and 60-second microphone probes passed: four video requests per recording matched independently finalized media, all 2,883,584 microphone PCM frames matched bit-for-bit through EOF, outputs/documents matched, originals stayed unchanged, and source release plus lock reacquisition passed. These are opt0 function diagnostics, not app latency or p95 evidence. Tauri compilation encountered compiler allocation failures with two jobs; the one-job native library check and test executable build later passed, but the storage reserve prevented that test execution. Expanded two-hour validation is paused under the narrower editor goal. Evidence: `platform-capacity/windows-fresh/current-shared-short-assessment.json`.
+
+Fresh Linux validation of the same source freeze passed 782 unique native tests, with the same six existing/manual tests ignored. The adapter was Mesa llvmpipe through Vulkan. Scoped formatting, checks and strict Clippy passed. All 101 recovery cases passed on the default root filesystem and again with the same binary on tmpfs; the duplicate run is excluded from the total. All three previously failing filesystem cases explicitly passed in both scopes. An initial receipt filter matched no tests and is retained as non-evidence; the corrected filter passed all eight intended cases. The 73-file evidence archive was downloaded and every member verified. Canonical integration runs remain separate from these unit fixtures. Evidence: `platform-capacity/linux-fresh/native-evidence/assessment.json`.
+
+The current Linux standard canonical 15-second and 60-second probes subsequently passed publication, retained-source, cancellation, actual-join and recovery-lock checks. All 2,883,584 microphone PCM frames matched bit-for-bit through EOF. Preparing video coverage was partial: finalization ended after two of four requested screen seeks and three of four microphone-recording seeks. Every returned frame matched its independently finalized software reference; the remaining requests were cancelled. No delay was added to force those requests to complete, and these results do not establish four-seek canonical parity. Evidence: `platform-capacity/linux-fresh/canonical-short-evidence/assessment.json`.
+
+A separate eight-file renderer diagnostic patch was applied after the frozen native matrix and matched GPUI runs. Its format/check, strict rendering all-target Clippy and 15 preparing-preview tests passed on macOS. A fresh 15-second native capture reached the ordinary first frame at 388.02 ms and played 300 frames at 60.0 fps with zero reported drops. All 895 decoded frames and PTS matched its retained originals; sidecars and source hashes were preserved. It produced no early image: finalization ended at 236.94 ms while preparing layer construction continued until 319.72 ms.
+
+That diagnostic measured 83.74 ms for managed decoder readiness, 4.09 ms for graphics constants and 176.42 ms for layer construction. The largest layer costs were the shared compositing pipeline (70.77 ms), first font-system scan (54.38 ms) and image layer (32.84 ms). These nested, instrumented timings identify work to investigate; they are not independent hardware timings or a matched speedup. No rendering phases occurred before Stop in this process. The exact diagnostic binary and 564 source hashes are retained under `renderer-readiness-diagnostics/summary.json`. No font warmup or initialization optimization has been accepted, and these later diagnostics do not change the provenance of the four reported timings. The instant, playable-editor goal is still in progress.
+
+An experimental follow-up omits the image/text/caption/keyboard layer bundle only for the checked preparing renderer. Existing ordinary constructors retain the complete bundle and original preparation/render order. Unsupported project or prepared-text inputs produce an explicit error before restricted rendering. On macOS, all 88 editor and 269 rendering library tests passed, with five existing rendering tests ignored; scoped checks also covered export and Tauri, and strict editor/rendering all-target Clippy passed after removing four unused imports from the extraction. Two additional native tests now pass on Apple M4 Max/Metal: ordinary image, text, caption and keyboard output remains visible, full/restricted frame-zero pixels and layout match, and late unsupported inputs leave the GPU target unchanged. Seven existing native preparing-preview tests also passed. The first boundary-test attempt used a segmented-text-only inspection method on ordinary batched text; that test assertion was corrected while retaining its rendered-pixel check, and both attempts are preserved under `preparing-overlay-boundary/native-macos/`. A fresh matched comparison is recorded below. No cross-platform or speedup acceptance is inferred from this local experiment; skipping early initialization can defer costs to ordinary loading.
+
+A fresh GPUI comparison isolates the optional overlay bundle change: both variants already include the preparing consumer and renderer diagnostics. Both opt2 executables were built from the same isolated source paths, with equal dependency profiles, features, locks, external inputs and assets. Only the documented four-path renderer/editor delta differs. Post-matrix source, binary and harness verification passed before any replay-test additions; an unused Tauri scaffold change in the original checkout is separately recorded and excluded from the GPUI dependency graph.
+
+| Fresh run | Early composed image | Early image app cycle | Recording finished | Ordinary first frame |
+| ------------------------- | -------------------: | --------------------: | -----------------: | -------------------: |
+| 01 full layers | No early image | — | 295.6 ms | 368.0 ms |
+| 02 omitted overlay layers | No early image | — | 282.4 ms | 849.7 ms |
+| 03 omitted overlay layers | 177.3 ms | 183.3 ms | 295.5 ms | 349.8 ms |
+| 04 full layers | 184.3 ms | 190.4 ms | 298.1 ms | 340.6 ms |
+
+The 849.7 ms observation remains part of the result. Its preparing layer construction took 523.6 ms, dominated by several GPU pipeline constructors; none of the omitted overlay constructors ran. Finalization safely relocated the source and ended the job, but ordinary loading waited for the retained preparing task to return from synchronous construction and join its native workers. Ordinary validation occurred at 681.3 ms. The logs establish this ordering, not the precise worker-exit timestamp or shader-cache causality. Both variants completed five seconds of ordinary playback with zero reported dropped frames. All 14,379 published frames and PTS matched their respective retained original fragments (3,595, 3,594, 3,595 and 3,595 frames); sidecars and all project trees remained unchanged during verification. Separate same-source composition replays subsequently passed for all four recordings on Apple M4 Max/Metal with FFmpeg hardware decoding: every visible pixel, dimensions, stride and layout matched the ordinary full renderer at frame zero. Decoder workers joined, and project/source trees stayed unchanged. These replays use a retained pinned Rust 1.88 opt0 test executable, separately qualified from the stable opt2 measured apps. The initial nonmember-workspace failure and paused rebuild are retained; neither changes the measured binaries or their completed source audit. These recordings contain no cursor motion, so motion coverage belongs to the earlier dedicated native tests. This four-observation matrix establishes neither a reliable speedup nor p95. Exact phases and provenance are under `preparing-overlay-benchmark/phase-assessment.json` and `source-after-matrix.json`.
+
+A separate optimized macOS diagnostic over the immutable two-hour canonical input completed successfully. It uses the public preparing path, a test-only clean-stop receipt on a validated writer-normalized copy, and the current restricted preparing renderer. The exact three runtime source hashes match its retained build manifest; the earlier description of this binary as using full layers was incorrect. T0 precedes finalizer worker spawn; source-copy/hash/projection preflight warms the input before T0. It does not execute native recorder shutdown, app presentation or audible playback.
+
+| Two-hour diagnostic milestone | Time from T0 |
+| ------------------------------------ | -----------: |
+| Preparing sources observed available | 1,166.0 ms |
+| First composed RGBA frame | 2,443.6 ms |
+| Preparing finalization returned | 12,441.6 ms |
+| Preview native workers joined | 12,444.2 ms |
+
+All first-frame pixels and layout matched the ordinary finalized-media compositor; published media bytes and normalized documents matched the ordinary run. Canonical originals, source/native/binary identities and lock availability after joins were verified. This diagnostic did not repeat PCM decoding; complete PCM comparison belongs to the earlier Stage10 evidence. Its subsequent ordinary finalization measured 11,560.5 ms, but this one ordered pair, with different concurrent work and warmed state, is not a matched no-regression performance result.
+
+Initial analysis consumed 397.7 ms, including 307.8 ms for 3,383 fragment-duration probes, all returning None. Initial whole-source snapshotting consumed 676.2 ms; hash groups contained 1.273 and 1.123 GB, so gross group imbalance does not explain the delay. Projection took 91.4 ms, primarily repeated completeness checks. After availability, managed decoder startup took 604.8 ms, graphics constants 91.4 ms, retained preparing layers 567.0 ms and RGBA output 12.1 ms. Nested/overlapping phases must not be summed as isolated costs. The next optimizations must preserve the existing integrity checks and duration fallback behavior. Raw common-origin phases, exact build qualification and results are in `two-hour-composed-diagnostic/isolated-preparation/evidence/two-hour-run-v2/assessment.json`. This single optimized function diagnostic establishes neither actual two-hour Stop/UI latency nor p95, and the instant/playable-editor goal remains incomplete.
+
+## Drivers
+
+From `apps/desktop-gpui`, build the drivers with `cargo build --example studio-finalization-benchmark --example media-readiness-benchmark --example audio-readiness-benchmark`. The finalization driver takes a disposable unfinished Studio project; it mutates that copy. The readiness drivers take media paths and are read-only. The audio driver's default mode reproduces the old background loader; `CAP_BENCH_PROGRESSIVE_AUDIO=1` selects the block loader. Both emit their execution and timing methodology. `CAP_BENCH_MIX_AUDIO=1` adds a current-renderer comparison with a barrier after every repetition. Hashing and mixing remain outside the decode timer.
+
+`CAP_BENCH_FULL_AUDIO_ONLY=1` skips the range experiment. Without it, the driver exits unsuccessfully if decoded ranges differ from the full-track reference. `CAP_BENCH_STREAM_AUDIO=1` also checks every sequential chunk against that reference. Preserve failed range experiments as failures; the known two-hour timestamp-seeking mismatch must not be mistaken for passing progressive-window coverage. Progressive windows use sequential sample positions instead.
+
+The debug Tauri driver is enabled by `CAP_STOP_EDITOR_BENCHMARK_OUTPUT`, with `CAP_STOP_BENCH_SECONDS`, optional `CAP_STOP_BENCH_MIC`, and optional `CAP_STOP_BENCH_SYSTEM_AUDIO`. Use an isolated app identifier and recordings directory. Its injected editor observer waits for a completed render in the existing frame statistics, a visible editor canvas, and two animation frames. A timeout is a failed benchmark, not a successful editor-open measurement. The initial observer only watched worker messages and missed Tauri's direct-canvas renderer; that incomplete run is excluded.
+
+Existing GPUI drivers include `CAP_GPUI_AUTO_RECORD=studio:60`, `CAP_GPUI_AUTO_NO_MIC=1`, `CAP_GPUI_AUTO_SYSTEM_AUDIO=1`, `CAP_GPUI_AUTO_EDITOR`, and `CAP_GPUI_AUTO_PLAYBACK`. `CAP_GPUI_AUTO_SEEK` targets a fraction of the visible timeline viewport. The new `CAP_GPUI_AUTO_SEEK_TIME=7194.5` targets seconds into the recording and logs the clamped time passed to the ordinary seek method. Use explicit time for long-recording tail checks. Keep app data and recordings isolated from the user's library.
+
+## Preparing playback integration on 2026-09-10
+
+The active goal was narrowed and resumed through the app: immediate editor presentation, equivalent early footage, actual playable-range feedback, and retained preview/playhead/playing intent through ordinary-editor handoff. Main was subsequently synchronized to `284ae24a79bd0813743f51e6219d11ae0042d38f`, preserving the local candidate and all evidence. Neither the goal nor native screenshot acceptance is complete.
+
+The shared preparing controller uses actual composed frames and completed required audio to admit a contiguous playable range. It freezes at that range, retains the latest seek response, cancels abandoned audio-start requests, and joins media workers before handing a take-once completed PCM cache to the ordinary loader. Required audio that cannot be proven equivalent keeps playback unavailable. Cached metadata permits only the finalizer's existing clearing of audio gap summaries; it cannot relabel paths, devices or start times.
+
+The Tauri backend now exposes window/epoch/job-scoped state and playback commands, publishes actual status changes, and includes the joined snapshot in the ordinary editor response. Closing a window releases preparing audio after cleanup. A replacement preparing request retires the previous session after its join. The frontend owns resuming ordinary playback after its target frame is actually drawn; that integration and user-intent supersession are still being validated.
+
+Tauri audio admission uses the ordinary timing-repair calculation against the projected final metadata and an actual bounded recording-log snapshot. Only cleanly stopped audio writers can reach this path. A missing log matches ordinary loading; unreadable, changing, nonregular, invalid UTF-8 or over-4-MiB logs conservatively defer required audio to ordinary loading. Preserved M4A requires the same AAC/no-video probe as finalization; transcodes and changed filenames are not admitted. These conservative limits must not be presented as universal early audible playback.
+
+The latest combined macOS editor library suite passed all 116 tests, including full PCM equality through gap-cleared handoff, corrupt-audio refusal, composed image equality, source release, rename and cancellation of an old playback handle without stopping its replacement. Current scoped Tauri compilation and all 16 preparing adapter/audio/lifecycle tests passed, as did 14 tests selected by the finalization filter. Shared editor strict all-target Clippy passed. The filtered runs overlap; their counts must not be summed into a unique platform total. GPUI scoped compilation and 165 focused preparing, recording, session, window and timeline tests passed. The final Tauri frontend passed 86 tests across eight files and desktop TypeScript. Scoped Biome passed for the initial 25 handwritten files and the six-file transcript/clip correction. Those panels now use the same ownership queue; recording/import waits for an acknowledged pause and declines a superseded request. Guarded handoff starts return a receipt for their exact playback handle; late cleanup cannot stop a newer ordinary playback. The queue retains ownership during failure cleanup and transfers ownership after successful handoff.
+
+Windows passed 68 native audio tests with the shared 60-second fixture: 64 shared tests plus four existing Windows latency tests. All decoded samples and EOF matched. The older wrapper expected 64 and flagged the count despite the native executable exiting successfully; that wrapper result and the corrected source-qualified count are both retained.
+
+The initial Linux/Windows screenshot builds use a retained source-v1 snapshot plus an explicitly recorded Clone correction and required real build assets. They predate the final controller integration. Linux Tauri completed an actual 15-second X11 capture and opened its ordinary editor; that short run did not present a preparing frame. The first external desktop-video recorder failed because it inherited the app's native-library search path. A corrected run produced a verified actual desktop video and editor screenshot; the user accepted Linux and requested no further Linux screenshots. Linux GPUI also built successfully from its qualified seed source. Both owned Linux VMs are stopped with source, media and build evidence retained.
+
+Windows GPUI genuinely opens the preparing editor. Its capture also exposed a persistent outline matching the hidden main window, and a white/washed-out preview. The initial rendering failures are retained; their runtime-layout cause and corrected results are recorded below. An independently invoked native export-preview reproduced washed-out output before GPUI presentation and then exited with an access violation during or after teardown; its generated JPEG does not make that diagnostic successful. The original recording media and project remain unchanged. A fresh real Stop reproduced the outline with 772 native trace records: the main window was hidden 26 seconds before editor creation, with no later show event, move/resize loop or held mouse button at editor creation. Show/hide clears the artifact diagnostically, but that does not establish a production fix.
+
+The integrated macOS GPUI build uses a separate 2,326-file hash-verified snapshot because concurrent crop changes invalidated the preceding shared-checkout build's provenance. That preceding binary was retained and never launched. A genuine 60-second capture opened the shell on the next presentation cycle at 88 ms. Finalization finished at 199 ms before preparing rendering returned a frame, so the early-play hook did not run. Ordinary playback rendered 299 frames over five seconds at 59.8 fps with zero drops. This proves immediate chrome and ordinary fallback for that run, not playback during processing. All 3,594 decoded frames and PTS matched retained fragments, cursor/keyboard sidecars matched byte-for-byte and the full project tree remained unchanged during verification.
+
+The new Tauri frontend and native builds are source- and asset-hash qualified. The initial native launch exited before recording because newly merged startup code honors the shared GPUI preference even for a private Tauri identifier. It preserved the user's running GPUI. An explicit debug Stop-benchmark-only branch now skips that startup selector and its shared marker handling; release behavior and user settings are unchanged. The failed launch remains recorded.
+
+The subsequent actual 120-second Tauri run preserved all 7,131 decoded frames and PTS, sidecars and 19,106,595 bytes of original media. Stop returned at 172 ms and the ordinary frontend frame event arrived at 1,549 ms. Actual UI Space playback and native screenshots confirmed about 60 fps, with 603 rendered frames, zero skips and no starvation in the observed interval. Preparing correctly declined because recorded clicks require late ordinary auto-zoom settings; this is ordinary fallback proof, not early-frame or playback-handoff proof.
+
+The final 86-test frontend rebuilt in 26.5 seconds with all 345 source hashes unchanged and 696 retained assets. Its native build also includes the explicit handoff start-frame selection after awaited music loading, so late old playhead events cannot change the approved target. A genuine 15-second Stop smoke on that build returned at 194 ms and delivered the ordinary frontend frame event at 577 ms. Actual full playback and replay from the end passed; the replay screenshot shows 0:03.01. All 899 published decoded frames and PTS matched retained originals, and the source/project audit passed. These single debug runs use different recordings and are not a performance comparison.
+
+A broader Tauri library run passed 468 tests and failed the existing upload scheduling assertion at 78.3 ms versus its 50 ms threshold. The entire upload file is byte-identical to current main. The isolated recheck through Cargo passed without source or threshold changes. A preceding direct-binary recheck lacked Cargo's runtime library paths and executed no tests; its loader failure is retained. The final serial run passed all 469 tests in 6.64 seconds. These concurrency and runtime-path qualifications remain with the broad gate.
+
+Windows Tauri's first launch failed the private logger's canonical-path guard; the next exposed a frontendDist Windows-drive URL interpretation issue. Both failures are retained. A relative asset path to the same 693 verified seed assets fixed the configuration; the unchanged-source native rebuild passed in 90 seconds. Its genuine 59.59-second recording opened the editor and actual Play advanced to 0:27.56 before pausing. The captured region was covered by the GPUI editor, so the recording contains that window. The native desktop video retains both the initial disabled editor chrome and the completed editor. Finalization took about 397 ms and the ordinary preview arrived about 3.8 seconds after editor document start; no preparing frame was observed. This remains a seed-build run, not validation of the latest progressive handoff. Current Windows function validation is being refreshed against the final common source manifest; the refreshed Linux results follow below. Storage, software-GPU, build-profile and source-version limitations remain explicit; no screenshot is a release performance result or a zero-regression guarantee.
+
+Evidence is under `optimization-stage-13/preparing-playback-combined`, `tauri-playback-integration`, `tauri-audio-admission`, `gpui-playback-integration`, and `linux-native-ui`, with Windows artifacts under `optimization-stage-12/windows-native-ui`.
+
+The standalone absolute-color diagnostic uses the exact existing native rendering libraries and does not edit production source. On both macOS and Windows, known RGBA bars survive GPU upload/readback, identity compositing and full composition exactly at all 24 sampled interiors. CPU YUV conversion matches the scalar reference; GPU conversion differs by at most one channel unit. The exact Windows recording software-decodes and composites in normal color on both systems, with actual native workers joined. A second diagnostic loads the original project configuration and isolates shadow and screen motion blur: all four variants render in normal color on both platforms, at the same 1168-by-702 output geometry as the failed export. Native CPU YUV and scalar RGBA outputs match byte-for-byte. These probes explicitly force software decoding and omit real cursor sidecars and recording timing metadata; the ordinary Windows decoder fallback is still under investigation. Earlier preparing-versus-ordinary equality alone cannot rule out both paths sharing a color bug. Evidence: `optimization-stage-13/windows-color-diagnostic/`, `windows-color-diagnostic-v4/`, and `optimization-stage-12/windows-native-ui/color-probe-v3/` and `color-probe-v4/`.
+
+The outline's scoped native diagnostic replays also remain separate from product verification. A temporary hook on the task-owned GPUI main thread invoked the actual content-affinity setter and nonclient activation pair; both succeeded, preserved hidden state and produced byte-identical before/after desktop images. The hook was removed after each operation. The native affinity getter succeeded and confirmed zero. Hidden-window paint and forced GPUI repaint messages also failed to reproduce the border. These negative results do not justify a visibility, theme or affinity patch; the real editor-opening transition remains under investigation.
+
+The final Linux v3 source snapshot verified all 2,331 file hashes before and after native validation. The shared library scope passed 531 unique tests: audio 63, rendering 244, editor 115, recovery 101 and receipt 8; five existing rendering tests stayed ignored. The final Tauri library executable passed 528 tests with zero failures, filtering only the binding-writing export test to preserve frozen source. This gives 1,059 unique shared and Tauri library passes, excluding overlapping filtered runs and the separate native fixture cases. The same recovery binary also passed all 101 tests on tmpfs; that duplicate run is not added to the total.
+
+Linux's matched 15- and 60-second canonical runs compared every observed video frame against independently finalized software-decoded media. Actual end-of-stream cancelled outstanding later seek requests: the observed requests were 0 and 7 seconds on the short fixture, and 0, 30 and 58 seconds on the longer fixture. All 2,883,584 audio frames matched bit-for-bit through EOF. Required worker joins, source release, output/configuration checks and all 59 original files (167,229,187 bytes) passed. The actual renderer selected llvmpipe through Vulkan. These are native function results, not additional UI screenshots or physical-GPU coverage.
+
+Scoped Linux compilation and strict shared Clippy passed. Tauri strict Clippy exposed one equivalent optional-value condition, rewritten with `is_none_or`; macOS formatting and scoped Tauri compilation then passed, as did the current Linux scoped Tauri check. The remaining three Tauri Clippy warnings are in the upload file, whose full bytes match current HEAD. Initial storage failures and reserve stops are retained separately from source/test failures. The final native Tauri build succeeded after audited removal of obsolete or duplicated owned compiler artifacts. Evidence: `optimization-stage-13/current-linux-functions/` and `native-current-v2/`.
+
+The next color probe kept managed decoders alive through rendering, then awaited their actual joins. On macOS, software YUV420p and native VideoToolbox NV12 produced identical corresponding composed output. On Windows, both requested hardware settings resolved to FFmpeg software decoding; both produced identical normal-color output and clean joins. A further ordinary-factory diagnostic creates the renderer before the decoder, matching export initialization order. On macOS, actual AVAssetReader texture-backed NV12 and the FFmpeg VideoToolbox path again produce identical corresponding PNGs. Ordinary handles expose no join API, so those runs record handle drop without claiming a worker join. Their initial standalone dynamic-library loader failures are retained; actual tests passed with the verified native-library search path. All these probes still omit actual cursor sidecars and recording timing metadata. Evidence: `windows-color-diagnostic-v5/`, `windows-color-diagnostic-v6/` and the Windows `color-probe-v5/` directory.
+
+The additional same-thread Windows affinity replay verified successful hidden-window transitions from 0 to 17 to 0, with an unconditional final restore to 0 and successful removal of every temporary hook. All desktop captures remained byte-identical. Repeated hides and genuine reopen-from-Recents also stayed clear. Those probes used an expanded main window and do not rule out the original compact recording-to-editor sequence. The visible outline was still unresolved at this probe stage; the later Main-frame module and its source-qualified native checks are recorded below.
+
+The compact visible-affinity sequence later reproduced the exact outline: enabling exclusion while visible, hiding, then repeated hidden clears changed exactly 3,048 pixels along the original client rectangle. A matched comparison with `DwmFlush` remained clear in its immediate captures, but a later capture showed the outline again. This leaves delayed composition and inspection ordering unresolved. The same run exposed a safety issue with a proposed read-before-write guard: the hidden getter returned success and zero, while the subsequently visible window still reported exclusion enabled. That guard was rejected before any production edit. Removing the new early clear also needs an early-close check because the preparing editor can re-show the protected main window before finalization reaches Idle.
+
+The actual Windows exporter was run again on two disposable copies differing only in `cursor.hide`. Both native processes exited successfully, but both images were incorrect: the original remained washed out, while the hidden-cursor variant had white and green/magenta corruption. Hiding the cursor does not establish or fix the cause. The ordinary-factory v6 diagnostic then rendered normal output on Windows with both default MediaFoundation-failure-to-FFmpeg fallback and forced FFmpeg. Both resolved to software YUV420p and produced equal decoded/output bytes. The full-library v7 probe uses actual recording metadata and sidecars through `cap_export::preview::render_preview`; both macOS and Windows processes passed and rendered normal color, with equal corresponding outputs for both decoder preferences. All input and disposable-project bytes remained unchanged. Evidence: `same-thread-window-probe-v3/`, `same-thread-window-probe-v4/`, `gpui-export-cursor-ab-v3/`, `color-probe-v6/`, `color-probe-v7/`, and `optimization-stage-13/windows-color-diagnostic-v7/`.
+
+The shader runtime layout explains the color discrepancy. The production Windows renderer selects bundled DXC only when both `dxcompiler.dll` and `dxil.dll` are beside the executable, or beside its parent when the executable directory is named `deps`. The retained test executables, standalone GPUI output and retained CLI directory lacked that pair; they loaded FXC. The successful v7 diagnostic had the pair and loaded DXC. Copying the exact verified runtime pair beside the unchanged executables corrected the isolated overlay, cursor/ripple and editor PNG tests. Full corrected rendering passed 244 tests with five existing ignored tests; full corrected editor passed all 114 tests. Together with audio 67, recovery 96 and receipts 8, this gives 529 unique current Windows shared library passes. All 2,331 frozen source hashes and retained executable hashes remained unchanged. The original two rendering and five editor failures remain recorded as runtime-layout failures, rather than being erased or weakened. The actual adapter is Microsoft Basic Render Driver through DX12, not a physical GPU. Evidence: `optimization-stage-13/native-current-windows-v3/`.
+
+The same runtime correction restored full-color native GPUI playback in the unchanged app. Module receipts and the app log confirm the exact adjacent DXC/DXIL libraries were loaded. Real Play/Pause advanced the original footage from 0:37 through 1:04. The retained core-playback snapshot reports 3,489 rendered frames, one skipped frame and zero starvation; GPUI paint submission on this software desktop was about 4.6 fps, so this is not a visible 60 fps claim. That ordinary reopen was outline-free because the main window had been shown and hidden during reopening. It does not prove the Stop outline is fixed. The unchanged CLI also returns a correctly colored JPEG after the runtime correction, but still exits with `0xc0000005`; that diagnostic remains failed. Evidence: `optimization-stage-12/windows-native-ui/runtime-module-audit-v1/`, `runtime-module-audit-v2/` and `gpui-dxc-playback-v1/`.
+
+A further real 19.017-second Stop reproduced the outline using only real input, desktop video and a subsequent desktop capture, with no window-state queries, hooks or DWM probes during the flow. Capture stop took 81.8 ms and remux 134.1 ms; the 837 captured frames and originals were retained. These are single diagnostic observations, not performance comparisons. Separate compact-window replays reproduced the outline after either one actual hidden affinity clear or two back-to-back clears. Duplicate-clear removal alone is therefore not a demonstrated fix. No production window-style, visibility or affinity change has been applied. Evidence: `gpui-native-v7/`, `same-thread-window-probe-v6a/` and `same-thread-window-probe-v7b/`.
+
+An additional native GPUI Stop with DXC loaded retained the same desktop outline over correctly colored footage. App logs confirm a manual Stop and a validated 23.767-second recording with 1,030 frames; the initially observed 0:04 was the paused playhead, not automatic recording termination. Capture shutdown took 78.94 ms and remux 152.86 ms. A subsequent hidden-Main `SetWindowPos` using `SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE` returned success, but the before, 600 ms and six-second desktop captures remained byte-identical. A frame refresh alone does not fix the outline. The outline extends outside the video preview on the actual desktop; it is not merely a border painted into the displayed footage. Evidence: `gpui-dxc-stop-v1/` and `hidden-frame-changed-v1/`.
+
+The current Windows canonical 15- and 60-second cases subsequently passed all eight requested video comparisons against independently finalized software references. All 2,883,584 microphone audio frames matched bit-for-bit through EOF; the separate managed-audio EOF test also passed. Actual worker joins, source release, lock reacquisition, outputs, configuration and original-file audits passed. The 2,331 source hashes and retained test executables remained unchanged. These are functional equivalence results; they do not turn the unresolved outline or CLI exit failure into passes. Windows Tauri scoped compilation and strict library/test Clippy subsequently passed; native library test execution remains separate under the recorded storage limit. Evidence: `optimization-stage-13/native-current-windows-v3/`.
+
+The requested upstream Zed review is pinned to `86b2cf96623a12ae3f524c3780b6bcce4443ed23`. Its complete inspected Windows backend has no capture-affinity calls or `SW_HIDE`; application hide is empty, while minimize and destruction use separate paths. Cap's local GPUI working patch adds native caption/edge styles and custom client insets absent from both current upstream and the July 19 fork ancestor. Both default to DirectComposition. These findings identify a Cap-specific frame/lifecycle difference, not an upstream workaround already proven for this recording flow. Primary sources: [Zed window styles](https://github.com/zed-industries/zed/blob/86b2cf96623a12ae3f524c3780b6bcce4443ed23/crates/gpui_windows/src/window.rs#L471-L494) and [Windows application hide](https://github.com/zed-industries/zed/blob/86b2cf96623a12ae3f524c3780b6bcce4443ed23/crates/gpui_windows/src/platform.rs#L592-L599). Exact source snapshots, hashes, comparisons and the unapplied diagnostic-only frame patch are under `optimization-stage-13/zed-upstream-comparison/`.
+
+A fresh native run with the existing `GPUI_DISABLE_DIRECT_COMPOSITION=1` setting initially appeared outline-free. The later desktop capture instead showed the entire hidden main client region as a solid white rectangle. Floating controls also lost transparency, producing black rectangles in this recording. This alternative is rejected: it changes the artifact and introduces visible capture differences. It does not fix the settled result, and no production rendering mode was changed.
+
+The matched fresh default process restored normal composition and reproduced the outline. A subsequent reversible test on only the idle hidden Main cleared `WS_CAPTION`; Windows automatically cleared only the associated `WS_EX_WINDOWEDGE` bit. With a frame refresh, the outline disappeared while visibility, bounds and composition stayed unchanged. Restoring the exact original styles restored the outline. Both cleared captures matched each other byte-for-byte; the before and both restored captures also matched byte-for-byte. The first attempt stopped on that native coupled-style change and restored the baseline before a corrected diagnostic explicitly recognized it. This proves the visible artifact depends on the native caption/edge representation, but does not yet prove its trigger or justify changing visible-window appearance. No product source was changed. Evidence: `optimization-stage-12/windows-native-ui/hidden-frame-style-v1/` and `hidden-frame-style-v2/`.
+
+Current Windows scoped compilation for the shared audio, rendering, editor and recording crates passed. Strict library/test Clippy retained a Windows-only `items_after_test_module` finding in `capture_pipeline.rs`, whose full bytes match HEAD and the frozen manifest (`fdee8cb040177fe55cda42e7b595361d6becb87b955e5c8836ba1e0e99c07e7a`). It is recorded as an inherited lint qualification; the file and lint threshold were left unchanged. Tauri scoped compilation and strict library/test Clippy also passed. The native Tauri test run remains a separate gate.
+
+A bounded native API observer then captured an actual 21.550-second GPUI recording and manual Stop that reproduced the outline. Its 11 committed records contained eight `DefWindowProcW(WM_NCACTIVATE)` calls before recording start and none at Stop. Their common caller and varying message parameters do not identify them as Cap’s synthetic theme redraw pair. All three affinity writes requested zero: one at start and two at Stop. The active Virtual Display Driver explains the existing streamed-display exclusion bypass. The two Stop clears were about 0.870 ms apart. Successful API returns with stale last-error values were not treated as failures. The observer’s warmed disposable-window test preserved return values and last-error behavior; teardown restored exact import pointers and protections with zero dropped or in-flight records. Its inert pinned module was removed by safely exiting the owned idle process. This rules out an observed direct theme redraw at Stop in this run; no speculative theme guard was applied. Evidence: `optimization-stage-12/windows-native-ui/api-observer-gpui-v2/`.
+
+A subsequent hidden-Main nonclient policy experiment returned `S_OK` for `DWMNCRP_DISABLED` and removed the outline. Immediate and six-second captures matched byte-for-byte. Restoring `DWMNCRP_USEWINDOWSTYLE` returned `S_OK`, re-enabled nonclient rendering and restored a capture byte-identical to the baseline. Process/window identity, styles, extended styles, visibility, iconic state and outer bounds remained exact across all captures; client bounds were not recorded in this probe. The later restored capture differs and is retained. The original raw policy enum was not readable: restoring `USEWINDOWSTYLE` follows the source-default inference, and the owned idle process subsequently exited to clear diagnostic state. This proves the policy can remove the observed artifact without changing window styles. It does not yet validate automatic hide/show handling, visible appearance or a production fix. Evidence: `optimization-stage-12/windows-native-ui/hidden-nc-policy-v1/`.
+
+The resulting local GPUI candidate installs a native subclass on only the Main window. It restores the normal nonclient policy before show-related default handling, reconciles actual visibility after `WM_WINDOWPOSCHANGED`, and removes its subclass before forwarding destruction. It retains styles, bounds, capture-affinity calls and default message handling. Review removed a premature post-`WM_SHOWWINDOW` reconciliation and added show restoration before forwarding `WM_WINDOWPOSCHANGED` when earlier notification is suppressed. The shared GPUI fork is unchanged. The exact Windows module is `623fd5404020c0eeb63038bf29fd2922cad205826ee39a97dda25662e3f2f082`; macOS GPUI workspace formatting and scoped compilation passed with source/lock hashes unchanged. Those checks exclude Windows code paths; exact-module native Windows validation is pending. Evidence: `optimization-stage-13/windows-hidden-frame-production/`.
+
+The current Windows Tauri test binary initially failed before the Rust harness with loader status `0xc0000139`. Its missing Common Controls activation manifest caused this fixture-runtime failure. An external manifest did not resolve it. A retained derivative with the exact `tauri-build` application manifest embedded by Microsoft’s resource tool launched successfully; all original executable code/data sections and the untouched original executable were retained and verified. That run passed 437 tests and failed eight at the same closed-listener timeout helper. Four independently bound-and-closed Windows loopback ports correctly returned `WSAECONNREFUSED` after 2.003–2.019 seconds, beyond the helper’s two-second deadline; a fresh-process targeted rerun reproduced the timeout. The resulting test-only change allows five seconds on Windows, retains two seconds elsewhere, and preserves the required connection failure and retry logic. It changes no production listener behavior. Root workspace formatting and Tauri compilation passed with the edited source hash unchanged. Native targeted and full-suite reruns are pending; original loader and timeout failures remain retained. Evidence: `optimization-stage-13/native-current-windows-v3/loopback-report.json` and `frame-ws-test-deadline/`.
+
+The Windows Tauri test-only v4 rerun subsequently passed all eight formerly failing cases individually and all 445 library tests in the full suite, with only binding generation filtered. Combined with the 529 shared tests, this is 974 unique Windows library passes; the eight canonical video comparisons and 2,883,584 PCM EOF frames are separate integration evidence. All 2,331 source hashes in the frozen shared/Tauri v4 scope remained exact. This scope does not include the later GPUI Main-frame candidate, whose native checks are separate. No production behavior or assertion condition was changed to obtain this result.
+
+The exact GPUI Main-frame module passed a disposable native Windows test covering already-hidden and visible installation, duplicate installation, wrong-thread rejection, minimize/restore/maximize/move/resize, outer/client rectangle and style parity, forwarded message results/last-error state, and subclass removal before forwarding destruction. Explicit `SW_SHOWNORMAL` and `SWP_NOSENDCHANGING` cases confirmed restoration before underlying show handling. The initial standalone executable lacked Common Controls activation and failed before `main`; the retained v2 used the exact existing GPUI application manifest, compiled without diagnostics and passed. The production GPUI dependency already enables that manifest, so no application manifest change is required. Actual GPUI recording/Stop testing of this exact module is the next gate. Evidence: `optimization-stage-13/windows-hidden-frame-harness-v2/native-smoke-v2/`.
+
+The first actual GPUI recording with the exact Main-frame module passed the previously failing Stop transition. Installation occurred while Main was visible, before recording hid it and before the existing Stop affinity calls. The temporary installation hook was removed before capture. The 28.185-second recording opened a correctly colored editor with no Main outline in either the immediate image or the pure settled desktop capture; a later observation remained clear after three minutes. Direct native measurements kept the original outer rectangle `[339,164,685,605]`, client rectangle `[347,165,677,597]`, caption and extended style bits, while the hidden noniconic Main reported nonclient rendering disabled. Closing the editor restored a normally framed visible Main. The launcher’s first attempt failed on a PowerShell argument cast before sending any installation command; that failure and successful cleanup were retained before correction. This is a native app diagnostic using the earlier GPUI executable plus the exact new module, not a rebuilt current-controller app. Further lifecycle and current-app build verification remain pending. Evidence: `optimization-stage-13/windows-hidden-frame-harness-v2/native-gpui-v1/`; screenshots: `optimization-stage-12/windows-native-ui/gpui-input-HiddenFrame07-desktop.png` and `pure-capture-HiddenFrameSettled01-desktop.png`.
+
+## Main-frame lifecycle and remaining audio readiness work
+
+The exact Windows Main-frame module passed a second genuine manual Stop after editor reopen, compact/expanded layout changes, minimize/restore, caption movement and a System-to-Dark-to-System theme round trip. Both the immediate and 55-second settled repeat screenshots remained free of the Main outline. Visible framing, styles, outer/client bounds and normal restoration were preserved. The two task-owned recordings contain 1,691 and 1,412 independently decoded video frames with no FFprobe failure. They were screen-only recordings, so this is window lifecycle and recording-integrity evidence, not A/V or progressive-playback proof. The owned GPUI process exited normally, removing the diagnostic module. Actual Main fullscreen behavior remains untested; the compact/expanded button is a layout toggle. Full receipts are under `optimization-stage-13/windows-hidden-frame-harness-v2/ASSESSMENT.txt`.
+
+The audio goal audit found two separate constraints. GPUI had required an absent timing log and zero timing repairs, whereas the ordinary editor and Tauri accept valid timing data. GPUI now uses the same bounded regular-file/UTF-8/4-MiB log snapshot reader as Tauri and derives ordinary repairs from expected finalized metadata. Existing source paths, preserved AAC/container checks, cancellation and required-track semantics are unchanged. Scoped format/check and six native focused tests pass. The copied log reader is byte-identical to Tauri. Tests cover missing/valid/invalid logs, nonzero timing repairs, immutable snapshots and symlink refusal; no actual early-play app handoff is claimed. Evidence: `optimization-stage-13/gpui-audio-timing-admission/assessment.json`.
+
+The larger remaining constraint is in the shared playback controller: each required audio track must reach successful decoded EOF before its entire clip is admitted. A two-hour clip therefore cannot currently reveal a within-clip playable prefix. The initial video image is independent of that audio gate. The ordinary loader discards an audio track on a later decode error; earlier valid samples cannot be unheard, so partial playback must retain explicit failure handling rather than pretend the tail was validated. Neither a file hash nor packet-only preflight proves complete audio decoding. The full source audit and actual-app evidence boundaries are retained under `optimization-stage-13/preparing-audio-goal-audit/`.
+
+A bounded input API is now prepared in `cap-audio`: a nonblocking window read distinguishes pending samples, known absence, successful completed audio and errors. Pending windows report only the source-frame range they actually retain; they never claim EOF or advertise additional uncopied blocks as playable. PCM blocks are shared by Arc, and the ordinary full-track decoder/result path is unchanged. A separate review caught and corrected a race between successful result publication and sender closure. Tests exercise publication, dropped/error producers, short tails, empty/large ranges, exact sample mixing across block boundaries, and retained-block ownership. The reviewed API passed macOS formatting, scoped Cargo check, strict scoped Clippy and 69 default library tests. The separately requested matched 60-second fixture EOF test also passed, giving 70 unique audio test passes; its original 1,230,339-byte input SHA remained unchanged. Those are function checks, not Stop-to-editor benchmarks or Linux/Windows validation of this latest delta. Evidence: `optimization-stage-13/preparing-audio-windows-v1/assessment.json`. This remains input-side groundwork: the production playback controller still uses its completed-audio gate. Connecting a bounded output producer, deriving readiness from genuinely rendered output, preserving the output resampler across growth and proving the actual playing handoff are outstanding.
+
+Current Windows app compilation is held until this shared audio scope settles, to avoid rebuilding stale sources. The exact validated frontend assets and both app build plans are retained. The old Windows function VM is stopped. The Tauri build plan uses an explicitly documented isolated output-type-only manifest adjustment to avoid redundant static/CDylib artifacts in the constrained VM; that debug UI proof will not establish packaged-release or performance equivalence. No recording source, accepted fixture or application manifest in the shared checkout was changed for capacity preparation.
+
+One scoped unchanged-CLI diagnostic under ProcDump produced a valid full-color 1,168-by-702 JPEG and an observed CLI process exit code of zero. No unhandled exception dump was produced. Two first-chance COM exceptions were handled during the known Media Foundation-to-FFmpeg fallback. The executable, source project and intended adjacent shader DLL hashes were unchanged. This single non-reproduction does not resolve the previously intermittent exit-time access violation, and no crash stack or live module inventory was captured. An earlier attempt failed before rendering because ProcDump changed JSON argument quoting; an argv-only probe established the corrected transport before this run. Both attempts remain retained under `optimization-stage-12/windows-native-ui/cli-unhandled-dump-v1/` and `cli-unhandled-dump-v2/`.
+
+## Partial audio playback integration
+
+The shared preparing controller now admits a growing audio prefix within a single recording clip. A separate mixer checks every required source range before producing samples, retains ordinary calibrated offsets, timing repairs, gain and stereo mixing, and permits trailing silence only after successful EOF. Its output producer preserves the resampler across pending input and uses a bounded two-second ring. Ordinary editor mixing and output-buffer selection remain unchanged. Tests compare nonzero output samples with the ordinary path at 44.1 and 48 kHz, across channel layouts, sample formats, fractional seeks, preroll and the long-recording output mode.
+
+The callback starts with a zero consumption allowance. The controller installs the combined audio/video playable prefix before playback and grows that allowance on the same source generation. Unavailable samples produce hardware silence without advancing the media clock or acknowledging playback. Timestamped consumed spans account for queued latency and starvation; video follows the reported audible position. The last displayed image and its snapshot position remain separate from that live clock. One headless test starts before synthetic EOF, consumes exactly 4,800 frames under the initial prefix, verifies silent callbacks while held, then compares all 70,000 frames after growth without replacing the source. This is real output-control and callback execution using synthetic decoded input, not a new capture benchmark.
+
+Independent review corrected failed-stream retirement, post-spawn error ownership, initial latency pre-skipping and cleanup ownership after a timeout. A failed device stream is retired on the control thread because a stopped callback cannot process a removal command. Healthy streams retain generation-specific removal so a stale preparing request cannot stop an ordinary replacement. Output cleanup observes both actual producer-thread completion and callback-source removal. The controller retains its ticket until cleanup succeeds. Test-only construction errors and a weak silence-only long-mode fixture were corrected; failed attempts remain in the evidence.
+
+The final partial-audio snapshot before the successful-publication handoff passed 143 macOS Rust 1.88.0 editor tests after the cleanup ownership correction. The audio suite passed 69 default tests, and the separately requested matched 60-second native AAC fixture passed comparison through decoded EOF. Its original 1,230,339-byte SHA remains `05f898aca4373a8678a3487766858e2a97cdcdd72d101f54a6980440460da808`. Formatting, scoped compilation and strict Clippy for both libraries and their tests passed. Repeated and overlapping focused suites are not additional unique passes. Receipts and before/after source manifests are under `optimization-stage-13/preparing-audio-output-v1/`; independent reviews are under `preparing-audio-stream-retirement/` and `preparing-partial-audio-clock/`.
+
+Those partial-audio checks did not establish native application Stop-to-first-audible timing, Windows/Linux parity or uninterrupted ordinary-editor handoff. In that snapshot, an incomplete managed source was cancelled/joined and decoded again by ordinary loading; only completed tracks crossed the cache boundary. That implementation limitation motivated the successful-publication handoff below. Device-buffered audio cannot be retracted merely by removing a callback source. Windows retains its existing zero-latency estimate; the pinned CPAL WASAPI playback timestamp is not sufficient evidence for changing that policy. Physical endpoint/loopback timing and actual application presentation remain separate from function-test coverage.
+
+## Successful-publication playback handoff
+
+The final candidate records successful publication without reopening source admission: the observer still ends and rejects new leases. A controller that was already admitted for the same successful job can keep its existing readers and audio output alive while preparation finishes and ordinary loading reuses completed PCM. Recovery-lock ownership stays with the original readers until actual cleanup joins release them. Failure, close and supersession continue to stop and join owned work.
+
+The ordinary candidate commits adoption only against a matching presented frame and current playback intent. It then follows the existing consumed-audio clock and audio generation. Pause or seek can invalidate and replace a pending candidate, and cleanup of an uncommitted or stale candidate cannot shut down its predecessor or successor. Existing explicit ordinary pause/seek/restart paths stop and join the adopted owner before installing a replacement source.
+
+The GPUI v4 callback also permits new frames from the already-admitted, same-job preparing session after successful publication; failure, cancellation and supersession still reject delivery. Its added admission regression test is included in the three GPUI v4 suites.
+
+The macOS editor suite below includes native fixture and headless output tests for PCM reuse, candidate disposal, moving-frame handoff, cancellation and panic completion. These tests do not measure a physical audio endpoint or prove that a real application window presents an uninterrupted, aligned audio/image transition.
+
+## Current automated verification before manual testing
+
+The rows below distinguish completed native test scopes from checks left unrun when the user ended automated testing and requested PR publication. GPUI uses the matching v4 source on macOS, Linux and Windows. Root Rust inputs are unchanged across the v2–v4 source manifests; subsequent deltas are the GPUI fixes and generated Tauri bindings. The older three-platform table remains historical evidence and is not added to these counts.
+
+| Scope | Result | Qualification |
+| ----------------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| macOS editor library | 161 passed | Native handoff and headless audio ownership tests included |
+| macOS recording/recovery | 597 passed | 535 library, 12 real-subprocess muxer and 50 recovery integration tests; three library ignores and one external-fixture integration ignore |
+| macOS Tauri | 470 passed, plus one binding-generator test | Generated bindings were then used by frontend validation |
+| macOS GPUI v4 | 993 passed | Two existing picker/screenshot benchmark tests ignored; all-target compilation passed |
+| Linux GPUI v4 | 1,052 passed | Two existing ignores; native compilation and source/runtime/binary integrity checks passed |
+| Windows GPUI v4 | 970 passed | Two existing ignores; native compilation and source/runtime/binary integrity checks passed |
+| Desktop frontend | 473 passed in 47 files | Final generated bindings included; TypeScript passed |
+| Web frontend | 3,047 passed, 28 skipped | 219 passing test files and six skipped files; TypeScript passed |
+| Tooling | 64 passed | Separate function-test scope |
+| Linux root libraries | Listed suites passed | Audio 69, editor 160, encoder 150, video decoder eight, project 130, rendering 244, recording 690, export 32 and muxer protocol seven |
+| Linux integration follow-up | Enabled requested scopes passed | Real muxer/OOP, recovery, sync, pipeline, rendering and synthetic scopes passed; three explicit GPU correctness tests and the separate 60-second audio EOF case passed |
+| Windows shared libraries | 1,314 passed | Audio 73, editor 159, encoder 138, decoder 11, project 129, rendering 244, recording 530 and export 30; nine default-suite ignores |
+| Linux Tauri library | 530 passed | Binding writer filtered; native library/bin check and strict library/test/bin Clippy passed |
+| Linux Tauri main binary | Six passed | Exact main source and 107 unchanged dependency artifacts; direct compiler invocation after ordinary Cargo staticlib packaging exhausted disk |
+| Linux canonical follow-up | Three executions passed | 15-/60-second recording scenarios plus the separate audio EOF case; this repeats the earlier audio EOF test and is not three additional unique unit tests |
+| Windows remaining root/Tauri scopes | **Not run; testing stopped** | Protocol check passed; protocol tests, Tauri, muxer, integrations, explicit GPU, canonical, hardware and remaining strict gates are incomplete |
+
+The final macOS editor and Tauri all-target strict Clippy gate passed, as did recording library/test strict Clippy. Strict GPUI Clippy did **not** pass on any of the three platforms. macOS v4 emitted 28 diagnostic blocks representing 27 distinct primary spans, including one repeated crop diagnostic. All 27 match v3; three additional unchanged `editor_frame0` spans from the v3 JSON were not emitted in the v4 text and are not classified as resolved. Linux emitted 23 errors and Windows 28. Every emitted primary excerpt and surrounding context was verified unchanged against HEAD and the initial adopted source. Linux's platform-specific `explicit_auto_deref` and Windows' `infallible_destructuring_match` also match that baseline. No new diagnostic context was found, and no suppression was added. Passing tests and compilation do not convert these strict-lint failures into green gates. Linux export strict Clippy also retains two test-only baseline diagnostics: an irrefutable `let` pattern on Linux and `field_reassign_with_default`. Their entire source files match HEAD and the initial adopted snapshot. No later strict export pass supersedes that receipt.
+
+The Linux integration follow-up passed nine muxer unit tests, 12 OOP tests, 50 recovery integrations, four sync tests, 61 instant-mode scenarios, five segmented-pipeline tests, two rendering integration tests and 28 synthetic tests. Three offscreen GPU tests and one audio EOF case were executed separately from their default suites. Empty platform targets, hardware exclusions and external-fixture/benchmark ignores are not counted as executed tests. The follow-up initially stopped on an unsuccessful 15-second canonical finalization probe (`exit 101`). A fresh native lane subsequently passed both the 15- and 60-second canonical recording scenarios and repeated the audio EOF test using the exact retained current binaries. Original fixtures, sources, native inputs and executable hashes remained unchanged. The first failed attempt remains evidence; the later result establishes successful retry execution, without claiming a cause for the first failure or complete seek-frame coverage from the summary alone. The repeated audio case is not an additional unique pass. Windows remaining root and Tauri scopes were not run before the user stopped further testing.
+
+Linux Tauri has 536 executed function-test passes in total: 530 from its normal Cargo-built library harness and six from the main-binary harness. The ordinary Cargo binary-test build failed while creating `libcap_desktop_lib.a` with `ENOSPC`. The six main tests then passed using a reconstructed direct Rust 1.88 invocation, the exact main source and 107 unchanged dependency artifacts, including the completed ordinary Rust library output. No source or Cargo manifest was changed. Strict Tauri Clippy subsequently passed for library, tests and binary targets. This closes those function-test scopes; the ordinary static-library packaging build remains failed and is not relabelled as a successful standard Cargo or release-package build.
+
+The Windows shared-library total comprises 232 unchanged-source passes inherited from the preceding VM (audio 73 and editor 159) and 1,082 newly executed passes (encoder 138, video decoder 11, project 129, rendering 244, recording 530 and export 30). The inherited suites were not rerun or counted twice. Their strict audio/editor gates had passed. The new protocol compilation check passed, but its test build did not start: the lane stopped at the 1.6-GB preflight with 1,581,453,312 bytes free. The remaining protocol tests, Tauri, muxer, integrations, explicit GPU correctness cases, canonical fixtures, hardware cases and remaining strict Clippy gates were not run for this final scope. The user then explicitly ended testing; older successful runs do not fill these gaps. Source, runtime, fixture and executable integrity checks passed at the stop. All eight executables and 50 logs are retained; the overall shared-phase receipt remains `passed: false` because the requested phase was incomplete.
+
+The earlier empty-output muxer crashes and filesystem-sensitive recovery failure retain their original failure evidence. Their focused Linux/Windows fix snapshots are historical; the current Linux recording library and real OOP/recovery results above provide later matching-root-source coverage. Current Windows recording-library passes do not complete the unrun real-helper/integration scopes; the older 27-test fix snapshot remains qualified historical evidence.
+
+Counts describe their listed scopes, not globally unique tests across operating systems. Earlier editor runs, focused frontend subsets, previous platform totals and repeated retries are not additional passes. Canonical 15-/60-second fixture scenarios remain separate from unit counts. No final-candidate physical audio-endpoint timing, continuous handoff UI test, new capture benchmark or expanded two-hour run is claimed. Manual testing should use a fresh candidate and include playback while preparation finishes, seeking, pausing and closing/reopening the editor.
+
+Current receipts are under `.git/codex-build/session-support/01a08773-a817-7de1-988e-ab9078f33c12/`: `macos-final-editor-v2-tests`, `macos-final-recording-tests`, `macos-final-tauri-tests`, `macos-final-tauri-bindings`, `macos-final-gpui-tests-v4`, their check/Clippy results, `gpui-clippy-v4-baseline-comparison.json`, `gpui-v4-platform-clippy-triage-v1/assessment.json`, `final-source-v2/linux-root-progress.json`, the captured `resume-progress-v1/{linux-root,linux-root-latest,windows-root-latest,linux-tauri-latest}.json` receipts, `linux-tauri-replacement-v1/linux-tauri-canonical-v1-latest.json`, `linux-tauri-main-test-v1/{progress,clippy-progress}.json`, `linux-tauri-bin-triage-v1/assessment.json`, `linux-export-clippy-triage-v1/assessment.json`, `windows-root-replacement-v1/shared-progress.json`, `windows-shared-retained-v1/receipt.json`, `windows-inherited-root-retained-v1/receipt.json`, `desktop-tests-final-bindings-v1.log`, `web-tests-postreview.log`, `tooling-tests.log`, and the final frontend typecheck logs. Interpret mutable polling filenames using the hashes retained with this report candidate. Further platform testing was stopped at the user’s request. Active test sandboxes were stopped and task resource removal was requested after local evidence retention. Three older restore requests rejected stop/delete because the provider reports a state change in progress; cleanup remains qualified until those requests are cleared. Receipts are in `final-sandbox-shutdown-v2/` and `final-sandbox-cleanup-v1/`; the earlier stopped-sandbox statement applies only to its historical run.
+
+### Earlier partial-audio verification snapshot, September 10
+
+In the earlier frozen partial-audio snapshot, the enabled app suites passed on all three operating systems. That broader run was not all green; its failures motivated the later fixes:
+
+| Platform | Tauri app suite | GPUI app suite | Broader native results |
+| -------- | ----------------------------------: | -------------: | -------------------------------------------------------------------- |
+| macOS | 468 passed, plus binding generation | 992 passed | 2,854 passed, zero failures |
+| Windows | 445 passed | 969 passed | 2,880 reported passes, three empty-output muxer failures |
+| Linux | 528 passed | 1,051 passed | 3,099 passed on the normal filesystem, four failures described below |
+
+Counts are per platform and selected native suites, not globally unique tests across operating systems. Repeated checks are not additional passes. Windows' reported passes include one loopback test that returned early because no output device existed; this is not physical loopback proof. Two canonical recording scenarios per operating system are recorded separately from the table. The explicitly requested ignored audio-EOF test is included once in each native total. Manual device, benchmark and external-fixture ignores remain documented in the individual receipts.
+
+That verification-only phase changed no production source or test assertions. The common 2,337-input source archive has SHA-256 `7f82cd885259e9100e1fa32e5a54ab2597015e21029bf99d6c78029c97d1794d`; its manifest has SHA-256 `4a5b7ebb67f54e6e22678488a9592d6fc51f6953cdd42f36de199baf31021e4a`. macOS additionally requires 24 platform-specific source files, and both app test setups require two exact committed MP4 fixtures. The Windows root-workspace source manifest differs only in GPUI-specific files, which the separate Windows GPUI gate for that snapshot covered. Later unrelated sharing/reupload and development-launcher edits in the shared checkout are excluded. These results apply only to that frozen candidate. The subsequent combined build adopts additional sharing/reupload and launcher changes as well as the recovery, muxer and handoff fixes.
+
+The desktop frontend passed all 460 tests across 47 files, TypeScript compilation and Biome on all 40 frozen touched frontend files. Another 28 packaging-function tests passed on macOS; they are not native Linux execution. Scoped native compilation and formatting passed. Strict editor/audio library-and-test Clippy passed on all three platforms. Linux Tauri strict Clippy in that earlier snapshot reported three existing findings in unchanged `upload.rs`: unused `SegmentUploader::spawn`, unused `Control::complete`, and a redundant `Bytes` conversion. The binding-writing test was filtered on Windows/Linux and explicitly executed on the isolated macOS copy; generated bindings were byte-identical.
+
+Both preserved 15- and 60-second `.cap` fixtures were replayed on every platform. macOS and Windows observed all eight requested video frames and matched their independent ordinary-finalized references exactly. Linux observed five of eight requests before finalization ended the preparing session; every observed frame matched, but three cancelled requests are not frame-equivalence coverage. All three platforms matched every one of the 2,883,584 decoded audio frames through EOF on the 60-second fixture. Source, published-media, normalized-document, lock and worker-join checks passed. Original fixture hashes stayed unchanged. These are functional comparisons, not display-latency or audible-endpoint measurements.
+
+The three OOP muxer failures in that earlier Windows/Linux run were `respawning_subprocess_reports_clean_exit_when_no_crash`, `subprocess_spawns_and_finishes_cleanly_without_packets`, and `subprocess_survives_finish_after_init_only`. Actual packet-producing muxer tests passed in that run. The helper, protocol, calling OOP module, integration tests and all 89 transitive helper lock entries matched HEAD `284ae24a79bd0813743f51e6219d11ae0042d38f` before the later fix. The standalone Windows initialize/start/finish replay with no packets also crashed before the fix. Its minidump places exception `0xC0000094` inside the loaded `avformat-61.dll` at offset `0x4c8f2`. Native disassembly divides the byte-position-derived numerator by zero immediately before formatting representation bandwidth, matching FFmpeg 7.1's unguarded final DASH bitrate calculation ([pinned source](https://github.com/FFmpeg/FFmpeg/blob/n7.1/libavformat/dashenc.c#L834)). The small dump omits the divisor's heap page and has no complete symbolized internal stack; zero numerator registers rule out quotient overflow. Linux's Rust wrapper reports a non-successful child exit without retaining the signal. macOS passes all nine OOP tests with an ARM64 helper loading FFmpeg 7.1 / libavformat 61.7.100; that does not clear the failing x86 platform cases. No trailer, bitrate, library or assertion was changed during that diagnostic phase. The subsequent reviewed helper fix and added regression tests have their own passing native receipts above.
+
+The fourth failure in that earlier normal-filesystem Linux run was `recovery::transactional_recovery_tests::interrupted_rollback_reconciles_and_relaunches_at_every_rename_boundary`. That library suite reported 685 passes and one failure on the sandbox root filesystem. On tmpfs, that rollback test passes, while two executable-launch tests fail because the mount is noexec. Across these controls, 686 distinct recording-library tests pass, making 3,100 distinct passing names across all documented Linux filesystem scopes; this union is not a green normal-filesystem run. The retained older executable and current executable each reproduce the root-filesystem failure in all three alternating runs. Before the fix, the stamp, reconciliation function and failing test matched HEAD. A separate four-rename diagnostic reproduced directory size changing from 42 to 54 bytes without content or timestamp changes on rootfs; tmpfs remained stable. This supports an existing filesystem-sensitive guard but does not capture the exact differing field in the failed journal. No receipt format or recovery validation was changed during that diagnostic phase. The later guarded stamp fix was independently tested on the normal filesystem, as recorded above.
+
+Setup corrections are retained separately from product failures. Windows hardware compatibility passed its complete 13-test enabled suite in the existing Administrator desktop session, with seven hardware-specific ignores; the original SYSTEM/session-0 capture-support failure remains in the logs. Linux GPUI passed one complete 1,051-test invocation using the original Cargo test executable name and a stable, task-owned Xvfb display. Initial display/reset and renamed-executable failures are retained. The virtual display was stopped afterward; no application UI or screenshots were produced. Three explicitly executed offscreen GPU correctness tests passed per platform; Windows used WARP and Linux used llvmpipe, so this does not establish physical-GPU coverage. Linux's final 32-test export suite passed with the frozen root Rust 1.88 graph and unchanged source/lock, after downloading one already-pinned development dependency.
+
+That snapshot supplied source-bound regression evidence and concrete failures, not packaged-release clearance or a no-regressions guarantee. The final candidate now implements the successful-publication handoff, but its physical audible transition and application presentation remain unverified.
+
+Receipts live under `optimization-stage-13/current-macos-automated-v2/`, `native-partial-audio-windows-v1/extended-assessment.json`, `windows-gpui-automated-v1/`, `partial-audio-linux-v1/`, `partial-audio-gpui-linux-v1/`, `windows-integration-failure-audit/`, and `current-frontend-tests/`. Sources, original media, exact native executables, failed attempts and diagnostic evidence are retained.
+
+All four sandboxes used for that historical test run were stopped normally after evidence verification. The older sandbox with a pending restore remains archived with a requested start; its 60-minute idle-stop and auto-archive policies were verified, and auto-delete is disabled. That receipt recorded no remaining test process at the time; it is not a current operational-state claim. The consolidated historical receipt is `optimization-stage-13/automated-test-handoff-final.json`.
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 8e3205312..4794ea308 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -106,6 +106,7 @@ cap-fail = { version = "0.1.0", path = "../../../crates/fail" }
tokio-stream = { version = "0.1.17", features = ["sync"] }
md5 = "0.7.0"
tokio-util = "0.7.15"
+tokio-tungstenite = "=0.24.0"
wgpu.workspace = true
pollster = "0.4"
bytemuck = "1.23.1"
diff --git a/apps/desktop/src-tauri/src/api.rs b/apps/desktop/src-tauri/src/api.rs
index 1aa56dfd6..94c20abc2 100644
--- a/apps/desktop/src-tauri/src/api.rs
+++ b/apps/desktop/src-tauri/src/api.rs
@@ -126,6 +126,7 @@ pub async fn upload_multipart_complete(
upload_id: &str,
parts: &[UploadedPart],
meta: Option<S3VideoMeta>,
+ replace_existing: bool,
) -> Result<Option<String>, AuthedApiError> {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
@@ -135,6 +136,7 @@ pub async fn upload_multipart_complete(
parts: &'a [UploadedPart],
#[serde(flatten)]
meta: Option<S3VideoMeta>,
+ replace_existing: bool,
}
#[derive(Deserialize)]
@@ -154,6 +156,7 @@ pub async fn upload_multipart_complete(
upload_id,
parts,
meta,
+ replace_existing,
})
})
.await
diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/audio.rs
index 7c717bd22..deaa05a1e 100644
--- a/apps/desktop/src-tauri/src/audio.rs
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -1,4 +1,4 @@
-use cap_audio::AudioData;
+use cap_audio::DecodedAudio;
fn play_audio(bytes: &'static [u8]) {
use rodio::{Decoder, OutputStream, Sink};
@@ -39,33 +39,6 @@ impl AppSounds {
}
}
-pub fn get_waveform(audio: &AudioData) -> Vec<f32> {
- const CHUNK_SIZE: usize = (cap_audio::AudioData::SAMPLE_RATE as usize) / 10; // ~100ms
-
- let channels = audio.channels() as usize;
- let samples = audio.samples();
- let mut waveform = Vec::new();
-
- let mut i = 0;
- while i < samples.len() {
- let end = (i + CHUNK_SIZE * channels).min(samples.len());
- let mut sum = 0.0f32;
- for s in &samples[i..end] {
- sum += s.abs();
- }
- let avg = if end > i { sum / (end - i) as f32 } else { 0.0 };
- waveform.push(avg);
- i += CHUNK_SIZE * channels;
- }
-
- // Convert to absolute dBFS (0 dBFS = digital full scale)
- for v in waveform.iter_mut() {
- *v = if *v > 0.0 {
- 20.0 * v.log10() // Absolute dBFS relative to 1.0
- } else {
- -60.0 // Set silence to -60dBFS instead of -∞ for practical use
- };
- }
-
- waveform
+pub fn get_waveform(audio: &DecodedAudio) -> Vec<f32> {
+ cap_audio::waveform_peaks(audio.sample_slices().flatten(), audio.channels())
}
diff --git a/apps/desktop/src-tauri/src/editor_preparing.rs b/apps/desktop/src-tauri/src/editor_preparing.rs
new file mode 100644
index 000000000..d3a910418
--- /dev/null
+++ b/apps/desktop/src-tauri/src/editor_preparing.rs
@@ -0,0 +1,1395 @@
+use std::{
+ collections::HashMap,
+ io::{self, BufReader, Read},
+ panic::AssertUnwindSafe,
+ path::{Path, PathBuf},
+ str::FromStr,
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::Duration,
+};
+
+use cap_editor::{
+ EditorFrameFormat, PreparingEditorProgress, PreparingPlaybackController, PreparingPlaybackExit,
+ PreparingPlaybackOptions, PreparingPlaybackSession, PreparingPlaybackSnapshot,
+ PreparingPlaybackState, PreparingPlaybackStopHandle, PreparingPreviewInput,
+ PreparingPreviewOptions, PreparingPreviewSegment,
+};
+use cap_project::{CursorEvents, ProjectConfiguration};
+use cap_recording::recovery::{
+ PreparingSidecarKind, PreparingStudioSources, PreparingStudioState, PreparingVideoTrack,
+};
+use cap_rendering::{FrozenRecordedCursorAssets, ManagedSegmentVideoInput, ManagedVideoTrackInput};
+use futures::{
+ FutureExt,
+ future::{BoxFuture, Shared},
+};
+use serde::Serialize;
+use specta::Type;
+use tauri::{AppHandle, Manager, Window};
+use tauri_specta::Event;
+use tokio::sync::{oneshot, watch};
+
+use crate::frame_ws::{OwnedWatchFrameWs, WSFrame};
+use crate::{
+ FinalizationProject, FinalizingRecordings,
+ preparing_finalization::FinalizationPreparing,
+ windows::{CapWindowId, EditorWindowIds},
+};
+
+mod audio;
+
+const MAX_CURSOR_BYTES: u64 = 256 * 1024 * 1024;
+
+#[derive(Clone, Debug, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct PreparingEditorSeed {
+ title: String,
+ tracks: Vec<String>,
+}
+
+#[derive(Clone, Debug, Serialize, Type, tauri_specta::Event)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct PreparingEditorChanged {
+ request_epoch: u32,
+ job_id: String,
+ sequence: u32,
+ fps: u32,
+ progress: PreparingEditorProgress,
+ playback: PreparingPlaybackState,
+ seed: PreparingEditorSeed,
+}
+
+#[derive(Default)]
+struct PlaybackBinding {
+ latest: Option<PreparingEditorChanged>,
+ controller: Option<PreparingPlaybackController>,
+ audio_output: Option<Arc<cap_editor::AudioOutput>>,
+ exit: Option<PreparingPlaybackExit>,
+ handoff: Option<cap_editor::PreparingPlaybackHandoff>,
+}
+
+#[derive(Clone)]
+struct RetainedJoin(Shared<BoxFuture<'static, Result<(), String>>>);
+
+impl RetainedJoin {
+ fn new(task: tokio::task::JoinHandle<Result<(), String>>) -> Self {
+ let completion = async move {
+ task.await
+ .map_err(|error| format!("Preparing cleanup task failed: {error}"))?
+ }
+ .boxed()
+ .shared();
+ let retained = completion.clone();
+ drop(tokio::spawn(async move {
+ let _ = retained.await;
+ }));
+ Self(completion)
+ }
+
+ async fn wait(&self) -> Result<(), String> {
+ self.0.clone().await
+ }
+ fn succeeded(&self) -> bool {
+ self.0.peek().is_some_and(Result::is_ok)
+ }
+}
+
+struct ConsumerControl {
+ window_ids: EditorWindowIds,
+ window_id: u32,
+ request_epoch: u32,
+ path: PathBuf,
+ finalization: FinalizationPreparing,
+ cancelled: watch::Sender<bool>,
+ accepts_frames: AtomicBool,
+ playback: Mutex<PlaybackBinding>,
+ publish: Option<Box<dyn Fn(PreparingEditorChanged) + Send + Sync>>,
+}
+
+impl ConsumerControl {
+ fn cancel(&self) {
+ if let Some(handoff) = &self.playback.lock().unwrap().handoff {
+ handoff.cancel();
+ }
+ self.accepts_frames.store(false, Ordering::Release);
+ self.cancelled.send_replace(true);
+ }
+
+ fn is_active(&self) -> bool {
+ !*self.cancelled.borrow()
+ && self
+ .window_ids
+ .ids
+ .lock()
+ .unwrap()
+ .iter()
+ .any(|(path, id)| *id == self.window_id && path == &self.path)
+ && (self.finalization.is_pending() || self.finalization.allows_preparing_continuation())
+ }
+
+ fn publish_snapshot(&self, snapshot: &PreparingPlaybackSnapshot) {
+ let update = {
+ let mut binding = self.playback.lock().unwrap();
+ let Some(latest) = binding.latest.as_mut() else {
+ return;
+ };
+ latest.sequence = latest.sequence.saturating_add(1);
+ latest.progress = snapshot.progress.clone();
+ latest.playback = snapshot.playback;
+ latest.clone()
+ };
+ if let Some(publish) = &self.publish {
+ publish(update);
+ }
+ }
+
+ fn accepts(&self) -> bool {
+ self.accepts_frames.load(Ordering::Acquire) && self.is_active()
+ }
+
+ fn retire_playback(&self) {
+ let output = {
+ let mut binding = self.playback.lock().unwrap();
+ binding.controller = None;
+ binding.exit = None;
+ if let Some(handoff) = binding.handoff.take() {
+ handoff.cancel();
+ }
+ binding.audio_output.take()
+ };
+ if let Some(output) = output {
+ output.shutdown();
+ }
+ }
+}
+
+struct Entry {
+ control: Arc<ConsumerControl>,
+ joined: RetainedJoin,
+}
+
+#[derive(Default)]
+struct ProjectConsumers {
+ ordinary_loading: bool,
+ entries: Vec<Entry>,
+}
+
+#[derive(Default)]
+struct Registry {
+ projects: HashMap<PathBuf, ProjectConsumers>,
+ epochs: HashMap<u32, u32>,
+}
+
+#[derive(Clone, Default)]
+pub(crate) struct PreparingConsumers(Arc<Mutex<Registry>>);
+
+impl PreparingConsumers {
+ pub(crate) async fn dispose_all(&self) -> Result<(), String> {
+ let paths = {
+ let registry = self.0.lock().unwrap();
+ for project in registry.projects.values() {
+ for entry in &project.entries {
+ entry.control.cancel();
+ }
+ }
+ registry.projects.keys().cloned().collect::<Vec<_>>()
+ };
+ let mut failure = None;
+ for path in paths {
+ if let Err(error) = self.before_ordinary_loading(&path).await {
+ failure.get_or_insert(error);
+ }
+ }
+ for project in self.0.lock().unwrap().projects.values() {
+ for entry in &project.entries {
+ entry.control.retire_playback();
+ }
+ }
+ failure.map_or(Ok(()), Err)
+ }
+
+ pub(crate) fn cancel_window(&self, window_id: u32, epoch: Option<u32>) {
+ let registry = self.0.lock().unwrap();
+ let mut closed = Vec::new();
+ for project in registry.projects.values() {
+ for entry in &project.entries {
+ if entry.control.window_id == window_id
+ && epoch.is_none_or(|epoch| entry.control.request_epoch == epoch)
+ {
+ let adopted = epoch.is_some()
+ && entry
+ .control
+ .playback
+ .lock()
+ .unwrap()
+ .handoff
+ .as_ref()
+ .is_some_and(|handoff| handoff.committed());
+ if adopted {
+ entry.control.accepts_frames.store(false, Ordering::Release);
+ entry.control.cancelled.send_replace(true);
+ } else {
+ entry.control.cancel();
+ }
+ if epoch.is_none() {
+ closed.push((entry.control.clone(), entry.joined.clone()));
+ }
+ }
+ }
+ }
+ drop(registry);
+ if !closed.is_empty() {
+ let registry = self.clone();
+ drop(tokio::spawn(async move {
+ for (control, joined) in closed {
+ let _ = joined.wait().await;
+ control.retire_playback();
+ }
+ for project in registry.0.lock().unwrap().projects.values_mut() {
+ project.entries.retain(|entry| {
+ entry.control.window_id != window_id || !entry.joined.succeeded()
+ });
+ }
+ }));
+ }
+ }
+
+ fn control_for_window(
+ &self,
+ window_id: u32,
+ epoch: Option<u32>,
+ ) -> Option<Arc<ConsumerControl>> {
+ self.0
+ .lock()
+ .unwrap()
+ .projects
+ .values()
+ .flat_map(|project| &project.entries)
+ .filter(|entry| {
+ entry.control.window_id == window_id
+ && epoch.is_none_or(|epoch| entry.control.request_epoch == epoch)
+ })
+ .max_by_key(|entry| entry.control.request_epoch)
+ .map(|entry| entry.control.clone())
+ }
+
+ pub(crate) fn snapshot_for_window(&self, window_id: u32) -> Option<PreparingEditorChanged> {
+ self.control_for_window(window_id, None)?
+ .playback
+ .lock()
+ .unwrap()
+ .latest
+ .clone()
+ }
+
+ pub(crate) async fn take_startup(
+ &self,
+ path: &Path,
+ ) -> Result<
+ (
+ Arc<cap_editor::AudioOutput>,
+ cap_editor::EditorStartupInputs,
+ Option<cap_editor::PreparingPlaybackHandoff>,
+ ),
+ String,
+ > {
+ let latest = {
+ let registry = self.0.lock().unwrap();
+ registry.projects.get(path).and_then(|project| {
+ project
+ .entries
+ .iter()
+ .filter(|entry| {
+ entry.joined.succeeded()
+ || (entry.control.is_active()
+ && entry.control.finalization.allows_preparing_continuation())
+ })
+ .max_by_key(|entry| entry.control.request_epoch)
+ .map(|entry| (entry.control.clone(), entry.joined.clone()))
+ })
+ };
+ if let Some((control, joined)) = latest {
+ let handoff = control.playback.lock().unwrap().handoff.clone();
+ let mut completed_audio = None;
+ let mut continuing = None;
+ if let Some(handoff) = handoff {
+ match handoff.take_completed_audio().await {
+ Ok(audio) => {
+ completed_audio = Some(audio);
+ continuing = Some(handoff);
+ }
+ Err(_) => {
+ control.cancel();
+ joined.wait().await?;
+ }
+ }
+ }
+ let mut binding = control.playback.lock().unwrap();
+ if completed_audio.is_none() {
+ completed_audio = binding
+ .exit
+ .take()
+ .and_then(|exit| exit.take_completed_audio());
+ }
+ let output = binding
+ .audio_output
+ .take()
+ .unwrap_or_else(|| Arc::new(cap_editor::AudioOutput::new()));
+ return Ok((
+ output,
+ cap_editor::EditorStartupInputs {
+ recordings: None,
+ completed_audio,
+ },
+ continuing,
+ ));
+ }
+ Ok((
+ Arc::new(cap_editor::AudioOutput::new()),
+ cap_editor::EditorStartupInputs::default(),
+ None,
+ ))
+ }
+
+ pub(crate) async fn before_ordinary_loading(&self, path: &Path) -> Result<(), String> {
+ let pending = {
+ let mut registry = self.0.lock().unwrap();
+ let project = registry.projects.entry(path.to_path_buf()).or_default();
+ project.ordinary_loading = true;
+ project
+ .entries
+ .iter()
+ .filter_map(|entry| {
+ if entry.control.is_active()
+ && entry.control.finalization.allows_preparing_continuation()
+ && entry.control.playback.lock().unwrap().handoff.is_some()
+ {
+ return None;
+ }
+ entry.control.cancel();
+ Some(entry.joined.clone())
+ })
+ .collect::<Vec<_>>()
+ };
+ let mut failure = None;
+ for joined in pending {
+ if let Err(error) = joined.wait().await {
+ failure.get_or_insert(error);
+ }
+ }
+ failure.map_or(Ok(()), Err)
+ }
+}
+
+#[tauri::command]
+#[specta::specta]
+pub(crate) async fn create_preparing_editor_frame(
+ window: Window,
+ request_epoch: u32,
+) -> Result<Option<String>, String> {
+ let CapWindowId::Editor { id } =
+ CapWindowId::from_str(window.label()).map_err(|error| error.to_string())?
+ else {
+ return Err("Invalid editor window".into());
+ };
+ let app = window.app_handle();
+ let window_ids = EditorWindowIds::get(app);
+ let path = window_ids
+ .ids
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|(_, current)| *current == id)
+ .map(|(path, _)| path.clone())
+ .ok_or("Editor window is closed")?;
+ let project = FinalizationProject::observe(path.clone()).await?;
+ if path != project.work_path() {
+ return Ok(None);
+ }
+ let Some(finalization) = app
+ .state::<FinalizingRecordings>()
+ .preparing_for_project(&project)
+ else {
+ return Ok(None);
+ };
+ let registry = app.state::<PreparingConsumers>().inner().clone();
+ let (response, result) = oneshot::channel();
+ {
+ let ids = window_ids.ids.lock().unwrap();
+ if !ids
+ .iter()
+ .any(|(registered, current)| *current == id && registered == &path)
+ {
+ return Ok(None);
+ }
+ let mut registry = registry.0.lock().unwrap();
+ if request_epoch == 0
+ || registry
+ .epochs
+ .get(&id)
+ .is_some_and(|epoch| *epoch >= request_epoch)
+ {
+ return Ok(None);
+ }
+ registry.epochs.insert(id, request_epoch);
+ let project = registry.projects.entry(path.clone()).or_default();
+ if project.ordinary_loading || !finalization.is_pending() {
+ return Ok(None);
+ }
+ project.entries.retain(|entry| !entry.joined.succeeded());
+ let previous = project
+ .entries
+ .iter()
+ .map(|entry| {
+ entry.control.cancel();
+ (entry.joined.clone(), entry.control.clone())
+ })
+ .collect();
+ let control = Arc::new(ConsumerControl {
+ window_ids: window_ids.clone(),
+ window_id: id,
+ request_epoch,
+ path,
+ finalization,
+ cancelled: watch::channel(false).0,
+ accepts_frames: AtomicBool::new(false),
+ playback: Mutex::default(),
+ publish: Some(Box::new({
+ let window = window.clone();
+ move |snapshot| {
+ let _ = snapshot.emit_to(&window, window.label());
+ }
+ })),
+ });
+ let runner = Runner {
+ control: control.clone(),
+ previous,
+ response: Some(response),
+ transport: None,
+ stop: None,
+ frames: watch::channel(None).0,
+ };
+ let joined = RetainedJoin::new(tokio::spawn(runner.run()));
+ project.entries.push(Entry { control, joined });
+ }
+ result
+ .await
+ .map_err(|error| format!("Preparing frame admission failed: {error}"))
+}
+
+#[tauri::command]
+#[specta::specta]
+pub(crate) async fn stop_preparing_editor_frame(
+ window: Window,
+ request_epoch: u32,
+) -> Result<(), String> {
+ let CapWindowId::Editor { id } =
+ CapWindowId::from_str(window.label()).map_err(|error| error.to_string())?
+ else {
+ return Err("Invalid editor window".into());
+ };
+ window
+ .app_handle()
+ .state::<PreparingConsumers>()
+ .cancel_window(id, Some(request_epoch));
+ Ok(())
+}
+
+fn editor_window_id(window: &Window) -> Result<u32, String> {
+ match CapWindowId::from_str(window.label()).map_err(|error| error.to_string())? {
+ CapWindowId::Editor { id } => Ok(id),
+ _ => Err("Invalid editor window".into()),
+ }
+}
+
+#[tauri::command]
+#[specta::specta]
+pub(crate) fn get_preparing_editor_state(
+ window: Window,
+ request_epoch: u32,
+) -> Result<Option<PreparingEditorChanged>, String> {
+ let id = editor_window_id(&window)?;
+ let state = window.state::<PreparingConsumers>();
+ Ok(state
+ .control_for_window(id, Some(request_epoch))
+ .and_then(|control| control.playback.lock().unwrap().latest.clone()))
+}
+
+fn playback_controller(
+ window: &Window,
+ request_epoch: u32,
+ job_id: &str,
+) -> Result<PreparingPlaybackController, String> {
+ let id = editor_window_id(window)?;
+ let control = window
+ .state::<PreparingConsumers>()
+ .control_for_window(id, Some(request_epoch))
+ .ok_or("Preparing editor is closed")?;
+ {
+ let binding = control.playback.lock().unwrap();
+ if binding
+ .latest
+ .as_ref()
+ .is_none_or(|latest| latest.job_id != job_id)
+ {
+ return Err("Preparing editor identity changed".into());
+ }
+ if binding
+ .handoff
+ .as_ref()
+ .is_some_and(|handoff| handoff.committed())
+ {
+ return Err("Preparing playback has been adopted".into());
+ }
+ }
+ if !control.is_active() {
+ return Err("Preparing editor has ended".into());
+ }
+ let binding = control.playback.lock().unwrap();
+ binding
+ .controller
+ .clone()
+ .ok_or_else(|| "Preparing playback is not available".into())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub(crate) async fn seek_preparing_editor(
+ window: Window,
+ request_epoch: u32,
+ job_id: String,
+ seconds: f64,
+) -> Result<(), String> {
+ playback_controller(&window, request_epoch, &job_id)?
+ .seek(seconds)
+ .await
+}
+
+#[tauri::command]
+#[specta::specta]
+pub(crate) async fn set_preparing_editor_playing(
+ window: Window,
+ request_epoch: u32,
+ job_id: String,
+ playing: bool,
+) -> Result<(), String> {
+ playback_controller(&window, request_epoch, &job_id)?
+ .set_playing(playing)
+ .await
+}
+
+pub(crate) async fn join_before_ordinary(app: &AppHandle, path: &Path) -> Result<(), String> {
+ app.state::<PreparingConsumers>()
+ .inner()
+ .clone()
+ .before_ordinary_loading(path)
+ .await
+}
+
+struct Runner {
+ control: Arc<ConsumerControl>,
+ previous: Vec<(RetainedJoin, Arc<ConsumerControl>)>,
+ response: Option<oneshot::Sender<Option<String>>>,
+ transport: Option<OwnedWatchFrameWs>,
+ stop: Option<PreparingPlaybackStopHandle>,
+ frames: watch::Sender<Option<Arc<WSFrame>>>,
+}
+
+impl Runner {
+ async fn run(mut self) -> Result<(), String> {
+ let result = AssertUnwindSafe(self.run_inner()).catch_unwind().await;
+ let adopted = matches!(&result, Ok(Ok(())))
+ && self
+ .control
+ .playback
+ .lock()
+ .unwrap()
+ .handoff
+ .as_ref()
+ .is_some_and(|handoff| handoff.committed());
+ if adopted {
+ self.control.accepts_frames.store(false, Ordering::Release);
+ self.control.cancelled.send_replace(true);
+ self.stop = None;
+ } else {
+ self.control.cancel();
+ }
+ self.frames.send_replace(None);
+ if let Some(response) = self.response.take() {
+ let _ = response.send(None);
+ }
+ let mut failure = match result {
+ Ok(Ok(())) => None,
+ Ok(Err(error)) => {
+ tracing::debug!(%error, "Tauri preparing preview declined");
+ None
+ }
+ Err(_) => {
+ tracing::warn!("Tauri preparing adapter panicked");
+ None
+ }
+ };
+ if let Some(stop) = &self.stop {
+ stop.cancel();
+ }
+ if let Some(transport) = self.transport.take()
+ && let Err(error) = transport.stop_and_wait().await
+ {
+ failure.get_or_insert(error);
+ }
+ if let Some(stop) = self.stop.take() {
+ let exit = stop.stop_and_wait().await;
+ self.control.publish_snapshot(&exit.snapshot);
+ if exit.cleanup_failed {
+ failure.get_or_insert_with(|| {
+ exit.error
+ .clone()
+ .unwrap_or_else(|| "Preparing media cleanup failed".into())
+ });
+ }
+ let mut binding = self.control.playback.lock().unwrap();
+ binding.controller = None;
+ binding.exit = Some(exit);
+ }
+ failure.map_or(Ok(()), Err)
+ }
+
+ async fn run_inner(&mut self) -> Result<(), String> {
+ for (previous, control) in &self.previous {
+ let result = previous.wait().await;
+ control.retire_playback();
+ result?;
+ }
+ if !self.control.is_active() {
+ return Ok(());
+ }
+ let control = self.control.clone();
+ let transport = crate::frame_ws::create_owned_watch_frame_ws(
+ self.frames.subscribe(),
+ Arc::new(move || control.accepts()),
+ )
+ .await?;
+ let url = transport.url.clone();
+ self.transport = Some(transport);
+ if let Some(response) = self.response.take()
+ && response.send(Some(url)).is_err()
+ {
+ return Ok(());
+ }
+ let mut cancel = self.control.cancelled.subscribe();
+ if *cancel.borrow() {
+ return Ok(());
+ }
+ let observer = tokio::select! {
+ biased;
+ _ = cancel.changed() => return Ok(()),
+ observer = self.control.finalization.wait_for_preparing() => observer,
+ };
+ let Some(mut observer) = observer else {
+ return Ok(());
+ };
+ let presentation = tokio::select! {
+ biased;
+ _ = cancel.changed() => return Ok(()),
+ presentation = self.control.finalization.wait_for_presentation() => presentation,
+ };
+ let Some(presentation) = presentation else {
+ return Ok(());
+ };
+ let sources = loop {
+ match observer.latest() {
+ PreparingStudioState::Available(sources) => break sources,
+ PreparingStudioState::Unavailable(error) => return Err(error),
+ PreparingStudioState::Ended => return Ok(()),
+ PreparingStudioState::Waiting => {}
+ }
+ tokio::select! {
+ biased;
+ _ = cancel.changed() => return Ok(()),
+ _ = observer.changed() => {},
+ }
+ };
+ let control = self.control.clone();
+ let job_id = sources.identity().job_id().to_string();
+ let (input, audio) =
+ tokio::task::spawn_blocking(move || adapt(sources, &control, &presentation))
+ .await
+ .map_err(|error| format!("Preparing adapter join failed: {error}"))??;
+ if !self.control.is_active()
+ || !matches!(observer.latest(), PreparingStudioState::Available(_))
+ {
+ return Ok(());
+ }
+ let control = self.control.clone();
+ let frame_observer = observer.clone();
+ let frames = self.frames.clone();
+ let mut tracks = vec!["display".to_string()];
+ if let Some(cap_project::StudioRecordingMeta::MultipleSegments { inner }) =
+ input.recording_meta.studio_meta()
+ {
+ if inner
+ .segments
+ .iter()
+ .any(|segment| segment.camera.is_some())
+ {
+ tracks.push("camera".into());
+ }
+ if inner.segments.iter().any(|segment| segment.mic.is_some()) {
+ tracks.push("microphone".into());
+ }
+ if inner
+ .segments
+ .iter()
+ .any(|segment| segment.system_audio.is_some())
+ {
+ tracks.push("systemAudio".into());
+ }
+ }
+ let audio_output = Arc::new(cap_editor::AudioOutput::new());
+ {
+ let mut binding = self.control.playback.lock().unwrap();
+ binding.audio_output = Some(audio_output.clone());
+ binding.latest = Some(PreparingEditorChanged {
+ request_epoch: self.control.request_epoch,
+ job_id,
+ sequence: 0,
+ fps: crate::EDITOR_PREVIEW_FPS,
+ progress: PreparingEditorProgress::default(),
+ playback: PreparingPlaybackState::default(),
+ seed: PreparingEditorSeed {
+ title: input.recording_meta.pretty_name.clone(),
+ tracks,
+ },
+ });
+ }
+ self.control.accepts_frames.store(true, Ordering::Release);
+ let session = PreparingPlaybackSession::spawn_with_expected_metadata(
+ input,
+ audio.tracks,
+ PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions {
+ use_hardware_decoding: !cfg!(target_os = "windows"),
+ frame_format: EditorFrameFormat::Rgba,
+ },
+ fps: crate::EDITOR_PREVIEW_FPS,
+ resolution: crate::default_editor_preview_resolution(),
+ },
+ audio_output,
+ Box::new(move |_, output, _| {
+ if control.accepts()
+ && (matches!(frame_observer.latest(), PreparingStudioState::Available(_))
+ || control.finalization.allows_preparing_continuation())
+ && let Some(frame) = crate::editor_window::frame_for_websocket(output)
+ {
+ #[cfg(debug_assertions)]
+ crate::stop_editor_benchmark::capture_ws_frame(
+ crate::stop_editor_benchmark::CaptureKind::Preparing,
+ &control.path,
+ &frame,
+ );
+ frames.send_replace(Some(Arc::new(frame)));
+ }
+ }),
+ audio.expected_metadata,
+ )?;
+ self.stop = Some(session.stop_handle());
+ let handoff = session.handoff_handle();
+ {
+ let mut binding = self.control.playback.lock().unwrap();
+ binding.controller = Some(session.controller());
+ binding.handoff = Some(handoff.clone());
+ }
+ let mut updates = session.updates();
+ self.control
+ .publish_snapshot(&updates.borrow_and_update().clone());
+ let mut health = tokio::time::interval(Duration::from_millis(50));
+ let mut observing = true;
+ loop {
+ tokio::select! {
+ biased;
+ _ = cancel.changed() => return Ok(()),
+ _ = handoff.wait_committed() => return Ok(()),
+ state = observer.changed(), if observing => {
+ if !matches!(state, PreparingStudioState::Available(_)) {
+ if !self.control.finalization.allows_preparing_continuation() { return Ok(()); }
+ observing = false;
+ }
+ },
+ changed = updates.changed() => {
+ if changed.is_err() { return Ok(()); }
+ let snapshot = updates.borrow_and_update().clone();
+ self.control.publish_snapshot(&snapshot);
+ if snapshot.progress.phase != cap_editor::PreparingEditorPhase::Preparing {
+ return Ok(());
+ }
+ },
+ _ = health.tick() => {
+ if !self.control.is_active() { return Ok(()); }
+ if self.transport.as_ref().is_some_and(OwnedWatchFrameWs::is_finished) {
+ return Ok(());
+ }
+
+ },
+ }
+ }
+ }
+}
+
+fn ensure_preparing_stopped_layout(
+ timeline: &cap_project::TimelineConfiguration,
+ studio: &cap_project::StudioRecordingMeta,
+) -> Result<(), String> {
+ if timeline.segments.len() != 1 || studio.display_notch().is_some() {
+ Err("Tauri preparing requires one screen segment without a recorded notch".into())
+ } else {
+ Ok(())
+ }
+}
+
+pub(crate) fn project_from_preparing_presentation(
+ presentation: &ProjectConfiguration,
+ stopped_timeline: &cap_project::TimelineConfiguration,
+) -> ProjectConfiguration {
+ let mut project = presentation.clone();
+ project.timeline = Some(crate::recording::recording_timeline(
+ stopped_timeline.segments.clone(),
+ Vec::new(),
+ ));
+ project
+}
+
+fn ensure_preparing_track_presentation<'a>(
+ tracks: impl IntoIterator<Item = (Option<&'a cap_project::VideoMeta>, Option<&'a Path>)>,
+) -> Result<(), String> {
+ if tracks
+ .into_iter()
+ .any(|(camera, keyboard)| camera.is_some() || keyboard.is_some())
+ {
+ Err("Camera and keyboard presentation require ordinary editor loading".into())
+ } else {
+ Ok(())
+ }
+}
+
+fn ensure_preparing_cursor_presentation(cursor: &CursorEvents) -> Result<(), String> {
+ if cursor.clicks.is_empty() {
+ Ok(())
+ } else {
+ Err("Recorded clicks require late ordinary auto-zoom settings".into())
+ }
+}
+
+fn adapt(
+ sources: Arc<PreparingStudioSources>,
+ control: &Arc<ConsumerControl>,
+ presentation: &ProjectConfiguration,
+) -> Result<(PreparingPreviewInput, audio::AudioAdaptation), String> {
+ let ended = || "Preparing sources ended".to_string();
+ let live = sources.live().ok_or_else(ended)?;
+ let recording_meta = live.metadata().ok_or_else(ended)?.clone();
+ let studio = recording_meta.studio_meta().ok_or_else(ended)?;
+
+ let timeline = live
+ .configuration()
+ .ok_or_else(ended)?
+ .timeline
+ .as_ref()
+ .ok_or("Missing stopped timeline")?;
+ ensure_preparing_stopped_layout(timeline, studio)?;
+ let mut project = project_from_preparing_presentation(presentation, timeline);
+ if project.clips.is_empty() {
+ project.clips =
+ cap_editor::initial_clip_configuration(&recording_meta.project_path, studio);
+ }
+ let descriptors = live.segments().ok_or_else(ended)?;
+ ensure_preparing_track_presentation(descriptors.iter().map(|segment| {
+ (
+ segment
+ .camera()
+ .map(cap_recording::recovery::PreparingVideoInput::metadata),
+ segment.keyboard_path(),
+ )
+ }))?;
+ let pointer_ids = studio.pointer_cursor_ids();
+ let mut segments = Vec::with_capacity(descriptors.len());
+ let mut cursor_budget = MAX_CURSOR_BYTES;
+ for descriptor in descriptors {
+ if *control.cancelled.borrow() || sources.live().is_none() {
+ return Err(ended());
+ }
+ let display = live
+ .video(descriptor.index(), PreparingVideoTrack::Display)
+ .ok_or_else(ended)?;
+ let (source, paths) = display.input().ok_or_else(ended)?;
+ let display = ManagedVideoTrackInput::new(source.clone(), paths.to_vec())
+ .map_err(|error| error.to_string())?;
+ let camera = if descriptor.camera().is_some() {
+ let camera = live
+ .video(descriptor.index(), PreparingVideoTrack::Camera)
+ .ok_or_else(ended)?;
+ let (source, paths) = camera.input().ok_or_else(ended)?;
+ Some(
+ ManagedVideoTrackInput::new(source.clone(), paths.to_vec())
+ .map_err(|error| error.to_string())?,
+ )
+ } else {
+ None
+ };
+ let mut cursor = if descriptor.cursor_path().is_some() {
+ let cursor = live
+ .sidecar(descriptor.index(), PreparingSidecarKind::Cursor)
+ .ok_or_else(ended)?;
+ let (source, path) = cursor.input().ok_or_else(ended)?;
+ let reader = source.reader(path).map_err(|error| error.to_string())?;
+ let mut reader = BufReader::new(CheckedCursorReader {
+ reader,
+ is_live: || !*control.cancelled.borrow() && sources.live().is_some(),
+ remaining: cursor_budget,
+ });
+ let cursor = CursorEvents::load_from_reader(&mut reader)?;
+ cursor_budget = reader.get_ref().remaining;
+ cursor
+ } else {
+ CursorEvents::default()
+ };
+ ensure_preparing_cursor_presentation(&cursor)?;
+ cursor.stabilize_short_lived_cursor_shapes(
+ (!pointer_ids.is_empty()).then_some(&pointer_ids),
+ cap_project::cursor::SHORT_CURSOR_SHAPE_DEBOUNCE_MS,
+ );
+ segments.push(PreparingPreviewSegment {
+ video: ManagedSegmentVideoInput::new(
+ descriptor.index() as usize,
+ studio,
+ display,
+ camera,
+ )
+ .map_err(|error| error.to_string())?,
+ cursor: Arc::new(cursor),
+ });
+ }
+ let images = descriptors
+ .first()
+ .ok_or_else(ended)?
+ .cursor_images()
+ .iter()
+ .map(|asset| {
+ (
+ asset.id().to_string(),
+ asset.metadata().clone(),
+ Arc::<[u8]>::from(asset.bytes()),
+ )
+ });
+ let cursor_assets =
+ FrozenRecordedCursorAssets::new(images).map_err(|error| error.to_string())?;
+ if *control.cancelled.borrow() || sources.live().is_none() {
+ return Err(ended());
+ }
+ let audio = audio::adapt_audio(&sources, &recording_meta, control)?;
+ Ok((
+ PreparingPreviewInput {
+ recording_meta,
+ project,
+ segments,
+ cursor_assets,
+ },
+ audio,
+ ))
+}
+
+struct CheckedCursorReader<R, F> {
+ reader: R,
+ is_live: F,
+ remaining: u64,
+}
+
+impl<R: Read, F: Fn() -> bool> Read for CheckedCursorReader<R, F> {
+ fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
+ if output.is_empty() {
+ return Ok(0);
+ }
+ if !(self.is_live)() {
+ return Err(io::Error::other("Preparing sources ended"));
+ }
+ if self.remaining == 0 {
+ let mut next = [0];
+ return if self.reader.read(&mut next)? == 0 {
+ Ok(0)
+ } else {
+ Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Cursor sidecar exceeds preparing limit",
+ ))
+ };
+ }
+ let length = output.len().min(self.remaining as usize);
+ let count = self.reader.read(&mut output[..length])?;
+ self.remaining -= count as u64;
+ Ok(count)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::FinalizationAccess;
+
+ fn control(
+ path: &Path,
+ window_id: u32,
+ epoch: u32,
+ ) -> (crate::FinalizationToken, Arc<ConsumerControl>) {
+ let project =
+ FinalizationProject::capture(path.to_path_buf(), FinalizationAccess::Write).unwrap();
+ let finalizations = FinalizingRecordings::default();
+ let token = finalizations.start_finalizing(project).unwrap();
+ let window_ids = EditorWindowIds::default();
+ window_ids
+ .ids
+ .lock()
+ .unwrap()
+ .push((path.to_path_buf(), window_id));
+ let control = Arc::new(ConsumerControl {
+ window_ids,
+ window_id,
+ request_epoch: epoch,
+ path: path.to_path_buf(),
+ finalization: token.preparing(),
+ cancelled: watch::channel(false).0,
+ accepts_frames: AtomicBool::new(true),
+ playback: Mutex::default(),
+ publish: None,
+ });
+ (token, control)
+ }
+
+ #[tokio::test]
+ async fn abandoned_admission_joins_transport_without_waiting_for_finalization() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().canonicalize().unwrap();
+ let (token, control) = control(&path, 1, 1);
+ let (response, receiver) = oneshot::channel();
+ drop(receiver);
+ let runner = Runner {
+ control: control.clone(),
+ previous: Vec::new(),
+ response: Some(response),
+ transport: None,
+ stop: None,
+ frames: watch::channel(None).0,
+ };
+ tokio::time::timeout(Duration::from_secs(2), runner.run())
+ .await
+ .expect("Abandoned admission waited for recording finalization")
+ .unwrap();
+ assert!(!control.is_active());
+ assert!(control.finalization.is_pending());
+ token.finish(Ok(()));
+ }
+
+ #[tokio::test]
+ async fn loading_barrier_cancels_and_joins_even_when_the_first_waiter_is_dropped() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().canonicalize().unwrap();
+ let (_token, control) = control(&path, 1, 1);
+ let (release, receiver) = oneshot::channel();
+ let (completed, mut completion) = watch::channel(false);
+ let joined = RetainedJoin::new(tokio::spawn(async move {
+ receiver.await.unwrap();
+ completed.send_replace(true);
+ Ok(())
+ }));
+ let registry = PreparingConsumers::default();
+ registry
+ .0
+ .lock()
+ .unwrap()
+ .projects
+ .entry(path.clone())
+ .or_default()
+ .entries
+ .push(Entry {
+ control: control.clone(),
+ joined: joined.clone(),
+ });
+ let waiter = {
+ let registry = registry.clone();
+ let path = path.clone();
+ tokio::spawn(async move { registry.before_ordinary_loading(&path).await })
+ };
+ while !*control.cancelled.borrow() {
+ tokio::task::yield_now().await;
+ }
+ assert!(!waiter.is_finished());
+ assert!(registry.0.lock().unwrap().projects[&path].ordinary_loading);
+ waiter.abort();
+ assert!(waiter.await.unwrap_err().is_cancelled());
+ release.send(()).unwrap();
+ completion.wait_for(|done| *done).await.unwrap();
+ joined.wait().await.unwrap();
+ registry.before_ordinary_loading(&path).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn replacement_admission_retires_previous_audio_after_join() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().canonicalize().unwrap();
+ let (_previous_token, previous) = control(&path, 1, 1);
+ let (_next_token, next) = control(&path, 1, 2);
+ let output = Arc::new(cap_editor::AudioOutput::new());
+ let retained = Arc::downgrade(&output);
+ previous.playback.lock().unwrap().audio_output = Some(output);
+ let (release, receiver) = oneshot::channel();
+ let joined = RetainedJoin::new(tokio::spawn(async move {
+ receiver.await.unwrap();
+ Ok(())
+ }));
+ let (response, receiver) = oneshot::channel();
+ drop(receiver);
+ let runner = Runner {
+ control: next,
+ previous: vec![(joined, previous)],
+ response: Some(response),
+ transport: None,
+ stop: None,
+ frames: watch::channel(None).0,
+ };
+ let task = tokio::spawn(runner.run());
+ tokio::task::yield_now().await;
+ assert!(retained.upgrade().is_some());
+ assert!(!task.is_finished());
+ release.send(()).unwrap();
+ tokio::time::timeout(Duration::from_secs(2), task)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ assert!(retained.upgrade().is_none());
+ }
+
+ #[tokio::test]
+ async fn failed_cleanup_remains_a_barrier_on_reopen_and_retry() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().canonicalize().unwrap();
+ let (_token, control) = control(&path, 1, 1);
+ let joined = RetainedJoin::new(tokio::spawn(async {
+ panic!("injected owned cleanup failure");
+ }));
+ let registry = PreparingConsumers::default();
+ registry
+ .0
+ .lock()
+ .unwrap()
+ .projects
+ .entry(path.clone())
+ .or_default()
+ .entries
+ .push(Entry { control, joined });
+ let first = registry.before_ordinary_loading(&path).await.unwrap_err();
+ let next = registry.before_ordinary_loading(&path).await.unwrap_err();
+ assert_eq!(first, next);
+ assert_eq!(registry.0.lock().unwrap().projects[&path].entries.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn closed_window_retires_audio_only_after_owned_cleanup_finishes() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().canonicalize().unwrap();
+ let (_token, control) = control(&path, 3, 1);
+ let output = Arc::new(cap_editor::AudioOutput::new());
+ let retained = Arc::downgrade(&output);
+ control.playback.lock().unwrap().audio_output = Some(output);
+ let (release, receiver) = oneshot::channel();
+ let joined = RetainedJoin::new(tokio::spawn(async move {
+ receiver.await.unwrap();
+ Ok(())
+ }));
+ let registry = PreparingConsumers::default();
+ registry
+ .0
+ .lock()
+ .unwrap()
+ .projects
+ .entry(path.clone())
+ .or_default()
+ .entries
+ .push(Entry {
+ control: control.clone(),
+ joined,
+ });
+ registry.cancel_window(3, None);
+ tokio::task::yield_now().await;
+ assert!(retained.upgrade().is_some());
+ assert!(!control.is_active());
+ release.send(()).unwrap();
+ tokio::time::timeout(Duration::from_secs(2), async {
+ loop {
+ if registry.0.lock().unwrap().projects[&path]
+ .entries
+ .is_empty()
+ {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ assert!(retained.upgrade().is_none());
+ }
+
+ #[tokio::test]
+ async fn old_frontend_stop_does_not_cancel_a_new_window_request() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().canonicalize().unwrap();
+ let (_token, control) = control(&path, 8, 2);
+ let registry = PreparingConsumers::default();
+ let joined = RetainedJoin::new(tokio::spawn(async { Ok(()) }));
+ registry
+ .0
+ .lock()
+ .unwrap()
+ .projects
+ .entry(path)
+ .or_default()
+ .entries
+ .push(Entry {
+ control: control.clone(),
+ joined,
+ });
+ registry.cancel_window(8, Some(1));
+ registry.cancel_window(7, None);
+ assert!(control.accepts());
+ registry.cancel_window(8, Some(2));
+ assert!(!control.accepts());
+ }
+
+ #[test]
+ fn native_registration_and_finalization_both_guard_frame_delivery() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().canonicalize().unwrap();
+ let (token, control) = control(&path, 1, 1);
+ assert!(control.accepts());
+ control.window_ids.ids.lock().unwrap().clear();
+ assert!(!control.accepts());
+ control.window_ids.ids.lock().unwrap().push((path, 2));
+ assert!(!control.accepts());
+ token.finish(Ok(()));
+ assert!(!control.is_active());
+ }
+
+ #[test]
+ fn cancelled_cursor_parse_terminates_without_retrying_interrupted_reads() {
+ let mut reader = CheckedCursorReader {
+ reader: std::io::Cursor::new([1, 2]),
+ is_live: || false,
+ remaining: 2,
+ };
+ let error = reader.read(&mut [0; 1]).unwrap_err();
+ assert_ne!(error.kind(), std::io::ErrorKind::Interrupted);
+ assert_eq!(reader.reader.position(), 0);
+ }
+}
+
+#[cfg(test)]
+mod presentation_guard_tests {
+ use super::*;
+
+ fn camera() -> cap_project::VideoMeta {
+ serde_json::from_value(serde_json::json!({
+ "path": "camera", "fps": 24, "start_time": 0.125
+ }))
+ .unwrap()
+ }
+
+ #[test]
+ fn screen_only_descriptors_pass_but_any_recorded_camera_is_declined() {
+ let camera = camera();
+ ensure_preparing_track_presentation([(None, None)]).unwrap();
+ for tracks in [
+ vec![(Some(&camera), None)],
+ vec![(None, None), (Some(&camera), None)],
+ ] {
+ assert_eq!(
+ ensure_preparing_track_presentation(tracks).unwrap_err(),
+ "Camera and keyboard presentation require ordinary editor loading"
+ );
+ }
+ }
+
+ #[test]
+ fn keyboard_sidecars_decline_even_without_a_camera_or_visible_overlay() {
+ for path in [Path::new("keyboard.json"), Path::new("keyboard.msgpack")] {
+ assert_eq!(
+ ensure_preparing_track_presentation([(None, Some(path))]).unwrap_err(),
+ "Camera and keyboard presentation require ordinary editor loading"
+ );
+ }
+ }
+
+ #[test]
+ fn click_up_and_click_down_both_decline_but_pointer_movement_alone_passes() {
+ let mut cursor = CursorEvents::default();
+ cursor.moves.push(cap_project::CursorMoveEvent {
+ active_modifiers: Vec::new(),
+ cursor_id: "arrow".into(),
+ time_ms: 0.0,
+ x: 0.2,
+ y: 0.8,
+ });
+ ensure_preparing_cursor_presentation(&cursor).unwrap();
+ for down in [false, true] {
+ cursor.clicks = vec![cap_project::CursorClickEvent {
+ active_modifiers: Vec::new(),
+ cursor_num: 0,
+ cursor_id: "arrow".into(),
+ time_ms: 0.0,
+ down,
+ }];
+ assert_eq!(
+ ensure_preparing_cursor_presentation(&cursor).unwrap_err(),
+ "Recorded clicks require late ordinary auto-zoom settings"
+ );
+ }
+ }
+ #[test]
+ fn stopped_layout_rejects_multiple_or_missing_segments_and_recorded_notches() {
+ let segment = cap_project::TimelineSegment {
+ recording_clip: 0,
+ start: 0.0,
+ end: 6.0,
+ timescale: 1.0,
+ name: None,
+ speed_audio_mode: None,
+ };
+ for notch in [
+ None,
+ Some(cap_project::DisplayNotch {
+ x: 0.4,
+ width: 0.2,
+ height: 0.03,
+ }),
+ ] {
+ let metadata: cap_project::RecordingMeta = serde_json::from_value(serde_json::json!({
+ "pretty_name": "Tauri presentation metadata", "sharing": null,
+ "segments": [{"display": {"path": "display", "fps": 30, "start_time": 0.0}, "display_notch": notch}]
+ })).unwrap();
+ for count in [0, 1, 2] {
+ let timeline =
+ crate::recording::recording_timeline(vec![segment.clone(); count], Vec::new());
+ let result =
+ ensure_preparing_stopped_layout(&timeline, metadata.studio_meta().unwrap());
+ assert_eq!(result.is_ok(), count == 1 && notch.is_none());
+ if let Err(error) = result {
+ assert_eq!(
+ error,
+ "Tauri preparing requires one screen segment without a recorded notch"
+ );
+ }
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/editor_preparing/audio.rs b/apps/desktop/src-tauri/src/editor_preparing/audio.rs
new file mode 100644
index 000000000..0a58e3d73
--- /dev/null
+++ b/apps/desktop/src-tauri/src/editor_preparing/audio.rs
@@ -0,0 +1,226 @@
+use super::*;
+use cap_editor::PreparingAudioSegmentInput;
+use cap_project::{AudioMeta, RecordingMeta, StudioRecordingMeta};
+use cap_recording::recovery::PreparingAudioTrack;
+
+const MAX_AUDIO_TIMING_LOG_BYTES: u64 = 4 * 1024 * 1024;
+
+pub(super) struct AudioAdaptation {
+ pub(super) tracks: Vec<PreparingAudioSegmentInput>,
+ pub(super) expected_metadata: RecordingMeta,
+}
+
+pub(super) fn adapt_audio(
+ sources: &Arc<PreparingStudioSources>,
+ metadata: &RecordingMeta,
+ control: &Arc<ConsumerControl>,
+) -> Result<AudioAdaptation, String> {
+ let mut expected_metadata = metadata.clone();
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut expected_metadata.inner else {
+ return Err("Preparing audio requires Studio metadata".into());
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ return Err("Preparing audio requires stopped segments".into());
+ };
+ for segment in &mut inner.segments {
+ for audio in [&mut segment.mic, &mut segment.system_audio]
+ .into_iter()
+ .flatten()
+ {
+ audio.gap_summary = None;
+ }
+ }
+ let expected_meta = expected_metadata
+ .studio_meta()
+ .ok_or("Preparing Studio metadata ended")?;
+ // Clean Stop joins the synchronous writers of timing-repair lines; finalization can still append unrelated log events.
+ let timing_log = read_timing_log(
+ &metadata.project_path.join("recording-logs.log"),
+ MAX_AUDIO_TIMING_LOG_BYTES,
+ );
+ let timing_eligible = timing_log.is_ok();
+ if let Err(error) = &timing_log {
+ tracing::debug!(%error, "Preparing audio timing requires ordinary loading");
+ }
+ let timing_log = timing_log.ok().flatten();
+ let repairs = cap_editor::segment_audio_timing_repairs(expected_meta, timing_log.as_deref());
+ let live = sources.live().ok_or("Preparing audio sources ended")?;
+ let descriptors = live.segments().ok_or("Preparing audio sources ended")?;
+ let mut tracks = Vec::with_capacity(descriptors.len());
+ for (index, descriptor) in descriptors.iter().enumerate() {
+ let repair = *repairs
+ .get(index)
+ .ok_or("Preparing audio timing layout changed")?;
+ let track = |kind, stem| {
+ if !timing_eligible {
+ return None;
+ }
+ let lease = live.audio(descriptor.index(), kind)?;
+ let metadata = lease.metadata()?;
+ let (source, path) = lease.input()?;
+ if !preserved_audio_path(metadata, path, stem) {
+ return None;
+ }
+ if path.extension().is_some_and(|extension| extension == "m4a") {
+ let control = control.clone();
+ let sources = sources.clone();
+ let input = cap_enc_ffmpeg::SegmentedInput::open_relocatable_interruptible(
+ source,
+ [path],
+ Arc::new(move || *control.cancelled.borrow() || sources.live().is_none()),
+ )
+ .ok()?;
+ if input
+ .input()
+ .streams()
+ .best(ffmpeg::media::Type::Video)
+ .is_some()
+ || !input
+ .input()
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .is_some_and(|stream| stream.parameters().id() == ffmpeg::codec::Id::AAC)
+ {
+ return None;
+ }
+ }
+ cap_audio::ManagedAudioInput::new(source.clone(), path.to_path_buf()).ok()
+ };
+ tracks.push(PreparingAudioSegmentInput {
+ mic: track(PreparingAudioTrack::Mic, "audio-input"),
+ system_audio: track(PreparingAudioTrack::SystemAudio, "system_audio"),
+ timing_repair: repair,
+ });
+ if *control.cancelled.borrow() || sources.live().is_none() {
+ return Err("Preparing audio sources ended".into());
+ }
+ }
+ Ok(AudioAdaptation {
+ tracks,
+ expected_metadata,
+ })
+}
+
+fn read_timing_log(path: &Path, limit: u64) -> Result<Option<String>, String> {
+ let initial = match std::fs::symlink_metadata(path) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(format!("Preparing audio timing log metadata: {error}")),
+ };
+ if !initial.is_file() || initial.len() > limit {
+ return Err("Preparing audio timing log is not a bounded regular file".into());
+ }
+ let file = std::fs::File::open(path)
+ .map_err(|error| format!("Preparing audio timing log open: {error}"))?;
+ let opened = file.metadata().map_err(|error| error.to_string())?;
+ if !opened.is_file()
+ || opened.len() != initial.len()
+ || opened.modified().ok() != initial.modified().ok()
+ {
+ return Err("Preparing audio timing log changed before reading".into());
+ }
+ let mut bytes = String::with_capacity(opened.len() as usize);
+ let mut bounded = file.take(limit.saturating_add(1));
+ bounded
+ .read_to_string(&mut bytes)
+ .map_err(|error| format!("Preparing audio timing log read: {error}"))?;
+ let finished = bounded
+ .get_ref()
+ .metadata()
+ .map_err(|error| error.to_string())?;
+ if bytes.len() as u64 != opened.len()
+ || finished.len() != opened.len()
+ || finished.modified().ok() != opened.modified().ok()
+ {
+ return Err("Preparing audio timing log changed while reading".into());
+ }
+ Ok(Some(bytes))
+}
+
+fn preserved_audio_path(metadata: &AudioMeta, relative: &Path, stem: &str) -> bool {
+ let expected = Path::new("content/segments").join(relative);
+ if Path::new(metadata.path.as_str()) != expected {
+ return false;
+ }
+ ["m4a", "ogg"].into_iter().any(|extension| {
+ relative
+ .file_name()
+ .is_some_and(|name| name == format!("{stem}.{extension}").as_str())
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn timing_snapshot_preserves_utf8_and_distinguishes_absence_from_ineligible() {
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("recording-logs.log");
+ assert_eq!(read_timing_log(&path, 100).unwrap(), None);
+ let text = "微phone segment{index=0}:mic-out: Dropping overlapping audio frame frame_count=1 overlap_ms=100\n";
+ std::fs::write(&path, text).unwrap();
+ assert_eq!(
+ read_timing_log(&path, text.len() as u64)
+ .unwrap()
+ .as_deref(),
+ Some(text)
+ );
+ assert!(read_timing_log(&path, text.len() as u64 - 1).is_err());
+ std::fs::write(&path, [0xff, 0xfe]).unwrap();
+ assert!(read_timing_log(&path, 100).is_err());
+ assert!(read_timing_log(root.path(), 100).is_err());
+ }
+
+ #[test]
+ fn oversized_timing_log_is_declined_without_reading_its_payload() {
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("recording-logs.log");
+ let file = std::fs::File::create(&path).unwrap();
+ file.set_len(MAX_AUDIO_TIMING_LOG_BYTES + 1).unwrap();
+ assert!(read_timing_log(&path, MAX_AUDIO_TIMING_LOG_BYTES).is_err());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn timing_log_symlink_is_ineligible() {
+ let root = tempfile::tempdir().unwrap();
+ let target = root.path().join("target.log");
+ let path = root.path().join("recording-logs.log");
+ std::fs::write(&target, "retained").unwrap();
+ std::os::unix::fs::symlink(&target, &path).unwrap();
+ assert!(read_timing_log(&path, 100).is_err());
+ }
+
+ #[test]
+ fn audio_admission_requires_the_unchanged_final_path_and_container_name() {
+ let metadata = |path: &str| AudioMeta {
+ path: path.into(),
+ start_time: Some(0.0),
+ device_id: None,
+ gap_summary: None,
+ };
+ for extension in ["m4a", "ogg"] {
+ let relative = PathBuf::from(format!("segment-0/audio-input.{extension}"));
+ let meta = metadata(&format!("content/segments/{}", relative.display()));
+ assert!(preserved_audio_path(&meta, &relative, "audio-input"));
+ assert!(!preserved_audio_path(&meta, &relative, "system_audio"));
+ }
+ for path in [
+ "segment-0/audio-input.mp3",
+ "segment-0/audio-input/audio.m4a",
+ "segment-0/audio-input.M4A",
+ ] {
+ assert!(!preserved_audio_path(
+ &metadata(&format!("content/segments/{path}")),
+ Path::new(path),
+ "audio-input"
+ ));
+ }
+ assert!(!preserved_audio_path(
+ &metadata("content/segments/other/audio-input.m4a"),
+ Path::new("segment-0/audio-input.m4a"),
+ "audio-input"
+ ));
+ }
+}
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index 2b9da332a..8def29c52 100644
--- a/apps/desktop/src-tauri/src/editor_window.rs
+++ b/apps/desktop/src-tauri/src/editor_window.rs
@@ -30,37 +30,8 @@ fn make_frame_callback(
frame_tx: watch::Sender<Option<Arc<WSFrame>>>,
) -> cap_editor::EditorFrameCallback {
Box::new(move |output, layout| {
- let ws_frame = match output {
- cap_editor::EditorFrameOutput::Nv12(frame) => {
- let ws_format = match frame.format {
- GpuOutputFormat::Nv12 => WSFrameFormat::Nv12 { full_range: false },
- GpuOutputFormat::Rgba => WSFrameFormat::Rgba,
- };
- WSFrame {
- data: Arc::new(frame.data.into_vec()),
- width: frame.width,
- height: frame.height,
- stride: frame.y_stride,
- frame_number: frame.frame_number,
- target_time_ns: frame.target_time_ns,
- format: ws_format,
- created_at: Instant::now(),
- }
- }
- cap_editor::EditorFrameOutput::Rgba(frame) => WSFrame {
- data: frame.data,
- width: frame.width,
- height: frame.height,
- stride: frame.padded_bytes_per_row,
- frame_number: frame.frame_number,
- target_time_ns: frame.target_time_ns,
- format: WSFrameFormat::Rgba,
- created_at: Instant::now(),
- },
- // The Tauri editor transports frames over a websocket, so it never
- // requests the gpui-only zero-copy surface format.
- #[cfg(target_os = "macos")]
- cap_editor::EditorFrameOutput::Surface(_) => return,
+ let Some(ws_frame) = frame_for_websocket(output) else {
+ return;
};
let _ = frame_tx.send(Some(std::sync::Arc::new(ws_frame)));
@@ -71,8 +42,47 @@ fn make_frame_callback(
})
}
+pub(crate) fn frame_for_websocket(output: cap_editor::EditorFrameOutput) -> Option<WSFrame> {
+ let frame = match output {
+ cap_editor::EditorFrameOutput::Nv12(frame) => {
+ let ws_format = match frame.format {
+ GpuOutputFormat::Nv12 => WSFrameFormat::Nv12 { full_range: false },
+ GpuOutputFormat::Rgba => WSFrameFormat::Rgba,
+ };
+ WSFrame {
+ data: Arc::new(frame.data.into_vec()),
+ width: frame.width,
+ height: frame.height,
+ stride: frame.y_stride,
+ frame_number: frame.frame_number,
+ target_time_ns: frame.target_time_ns,
+ format: ws_format,
+ created_at: Instant::now(),
+ }
+ }
+ cap_editor::EditorFrameOutput::Rgba(frame) => WSFrame {
+ data: frame.data,
+ width: frame.width,
+ height: frame.height,
+ stride: frame.padded_bytes_per_row,
+ frame_number: frame.frame_number,
+ target_time_ns: frame.target_time_ns,
+ format: WSFrameFormat::Rgba,
+ created_at: Instant::now(),
+ },
+ // The Tauri editor transports frames over a websocket, so it never
+ // requests the gpui-only zero-copy surface format.
+ #[cfg(target_os = "macos")]
+ cap_editor::EditorFrameOutput::Surface(_) => return None,
+ };
+ Some(frame)
+}
+
pub struct EditorInstance {
inner: Arc<cap_editor::EditorInstance>,
+ pub instance_id: uuid::Uuid,
+ handoff_playback: tokio::sync::Mutex<Option<(uuid::Uuid, cap_editor::PlaybackHandle)>>,
+ disposed: std::sync::atomic::AtomicBool,
pub ws_port: u16,
pub ws_shutdown_token: CancellationToken,
app_handle: AppHandle,
@@ -160,11 +170,82 @@ async fn do_prewarm(app: AppHandle, path: PathBuf) -> Result<Arc<EditorInstance>
let instance = Arc::new(EditorInstance {
inner,
+ instance_id: uuid::Uuid::new_v4(),
+ handoff_playback: Default::default(),
+ disposed: Default::default(),
+ ws_port,
+ ws_shutdown_token,
+ app_handle: app,
+ render_frame_event_id,
+ });
+ ws_guard.disarm();
+ Ok(instance)
+}
+
+async fn recreate_preparing_instance(
+ app: AppHandle,
+ previous: &Arc<EditorInstance>,
+) -> Result<Arc<EditorInstance>, String> {
+ let (frame_tx, frame_rx) = watch::channel(None);
+ let (ws_port, ws_shutdown_token) = create_watch_frame_ws(frame_rx, Default::default()).await;
+ let ws_guard = ws_shutdown_token.clone().drop_guard();
+ let state_app = app.clone();
+ let inner = previous
+ .inner
+ .recreate_preparing_candidate(
+ move |state| {
+ let _ = crate::EditorStateChanged::new(state).emit(&state_app);
+ },
+ make_frame_callback(app.clone(), frame_tx),
+ cap_editor::EditorFrameFormat::Rgba,
+ )
+ .await?;
+ let render_frame_event_id = crate::RenderFrameEvent::listen_any(&app, {
+ let preview_tx = inner.preview_tx.clone();
+ move |event| {
+ preview_tx.send_modify(|request| {
+ *request = Some((
+ event.payload.frame_number,
+ event.payload.fps,
+ event.payload.resolution_base,
+ ))
+ });
+ }
+ });
+ let instance = Arc::new(EditorInstance {
+ inner,
+ instance_id: uuid::Uuid::new_v4(),
+ handoff_playback: Default::default(),
+ disposed: Default::default(),
ws_port,
ws_shutdown_token,
app_handle: app,
render_frame_event_id,
});
+ let fps = crate::EDITOR_PREVIEW_FPS;
+ let resolution = crate::default_editor_preview_resolution();
+ let started = match instance
+ .inner
+ .start_preparing_handoff(fps, resolution)
+ .await
+ {
+ Ok(started) => started,
+ Err(error) => {
+ instance.dispose().await;
+ return Err(format!("Preparing handoff start failed: {error:?}"));
+ }
+ };
+ if !started {
+ let frame = instance
+ .inner
+ .preparing_adoption()
+ .and_then(|adoption| adoption.frame_number(fps))
+ .unwrap_or(0);
+ instance
+ .inner
+ .preview_tx
+ .send_modify(|request| *request = Some((frame, fps, resolution)));
+ }
ws_guard.disarm();
Ok(instance)
}
@@ -319,11 +400,104 @@ impl PendingEditorInstances {
impl EditorInstance {
pub async fn dispose(&self) {
+ self.disposed.store(true, Ordering::Release);
+ let mut handoff = self.handoff_playback.lock().await;
+ if let Some((_, playback)) = handoff.take() {
+ playback.stop();
+ }
self.inner.dispose().await;
self.ws_shutdown_token.cancel();
self.app_handle.unlisten(self.render_frame_event_id);
}
+
+ fn validate_handoff(&self, expected: &str) -> Result<(), String> {
+ if expected != self.instance_id.to_string() || self.disposed.load(Ordering::Acquire) {
+ Err("The handoff editor instance has ended".into())
+ } else {
+ Ok(())
+ }
+ }
+
+ pub(crate) fn commit_preparing_frame(
+ &self,
+ expected: &str,
+ frame: u32,
+ fps: u32,
+ ) -> Result<bool, String> {
+ self.validate_handoff(expected)?;
+ if self
+ .inner
+ .preparing_adoption()
+ .is_some_and(|adoption| adoption.is_owner())
+ {
+ return Ok(true);
+ }
+ if self
+ .inner
+ .preparing_adoption()
+ .is_some_and(|adoption| adoption.invalidated())
+ {
+ return Err("Preparing handoff candidate was superseded".into());
+ }
+ Ok(self
+ .inner
+ .preparing_adoption()
+ .is_none_or(|adoption| adoption.try_commit(frame, fps)))
+ }
+
+ pub(crate) async fn start_handoff_playback(
+ &self,
+ expected: &str,
+ frame_number: u32,
+ fps: u32,
+ resolution: cap_project::XY<u32>,
+ ) -> Result<String, String> {
+ let mut handoff = self.handoff_playback.lock().await;
+ self.validate_handoff(expected)?;
+ if self
+ .inner
+ .preparing_adoption()
+ .is_some_and(|adoption| adoption.is_owner())
+ && let Some(playback) = self.inner.state.lock().await.playback_task.clone()
+ {
+ let playback_id = uuid::Uuid::new_v4();
+ *handoff = Some((playback_id, playback));
+ return Ok(playback_id.to_string());
+ }
+ self.inner
+ .modify_and_emit_state(|state| state.playhead_position = frame_number)
+ .await;
+ let playback = self
+ .inner
+ .start_playback_with_handle(fps, resolution, Some(frame_number))
+ .await
+ .map_err(|error| format!("The handoff playback could not start: {error:?}"))?;
+ if let Err(error) = self.validate_handoff(expected) {
+ playback.stop();
+ return Err(error);
+ }
+ let playback_id = uuid::Uuid::new_v4();
+ *handoff = Some((playback_id, playback));
+ Ok(playback_id.to_string())
+ }
+
+ pub(crate) async fn stop_handoff_playback(
+ &self,
+ expected: &str,
+ playback_id: &str,
+ ) -> Result<(), String> {
+ let mut handoff = self.handoff_playback.lock().await;
+ self.validate_handoff(expected)?;
+ if handoff
+ .as_ref()
+ .is_some_and(|(id, _)| id.to_string() == playback_id)
+ && let Some((_, playback)) = handoff.take()
+ {
+ playback.stop();
+ }
+ Ok(())
+ }
}
impl Drop for EditorInstance {
@@ -451,7 +625,22 @@ impl EditorInstances {
if let Some(instance) =
with_registered_editor(&window_ids, id, || instances.get(window.label()).cloned())?
{
- return Ok(instance);
+ if !instance
+ .inner
+ .preparing_adoption()
+ .is_some_and(|adoption| adoption.invalidated())
+ {
+ return Ok(instance);
+ }
+ let replacement =
+ recreate_preparing_instance(window.app_handle().clone(), &instance).await?;
+ if let Err(error) = with_registered_editor(&window_ids, id, || ()) {
+ replacement.dispose().await;
+ return Err(error);
+ }
+ let _ = instances.insert(window.label().to_string(), replacement.clone());
+ instance.dispose().await;
+ return Ok(replacement);
}
let requested_at = Instant::now();
@@ -493,6 +682,9 @@ impl EditorInstances {
.await?;
let instance = Arc::new(EditorInstance {
inner,
+ instance_id: uuid::Uuid::new_v4(),
+ handoff_playback: Default::default(),
+ disposed: Default::default(),
ws_port,
ws_shutdown_token,
app_handle,
diff --git a/apps/desktop/src-tauri/src/frame_ws.rs b/apps/desktop/src-tauri/src/frame_ws.rs
index 33d05b8a9..24220b826 100644
--- a/apps/desktop/src-tauri/src/frame_ws.rs
+++ b/apps/desktop/src-tauri/src/frame_ws.rs
@@ -668,7 +668,9 @@ mod shutdown_tests {
}
async fn assert_listener_closed(port: u16) {
- tokio::time::timeout(Duration::from_secs(2), async {
+ // Windows can take just over two seconds to report a refused loopback connection.
+ let timeout = Duration::from_secs(if cfg!(windows) { 5 } else { 2 });
+ tokio::time::timeout(timeout, async {
while TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
@@ -936,3 +938,223 @@ mod shutdown_tests {
assert_listener_closed(port).await;
}
}
+
+pub(crate) struct OwnedWatchFrameWs {
+ pub(crate) url: String,
+ shutdown: CancellationToken,
+ task: Option<tokio::task::JoinHandle<Result<(), String>>>,
+}
+
+impl OwnedWatchFrameWs {
+ pub(crate) fn is_finished(&self) -> bool {
+ self.task
+ .as_ref()
+ .is_none_or(tokio::task::JoinHandle::is_finished)
+ }
+
+ pub(crate) async fn stop_and_wait(mut self) -> Result<(), String> {
+ self.shutdown.cancel();
+ self.task
+ .take()
+ .ok_or_else(|| "Preparing frame transport already joined".to_string())?
+ .await
+ .map_err(|error| format!("Preparing frame transport join failed: {error}"))?
+ }
+}
+
+impl Drop for OwnedWatchFrameWs {
+ fn drop(&mut self) {
+ self.shutdown.cancel();
+ }
+}
+
+pub(crate) async fn create_owned_watch_frame_ws(
+ frame_rx: watch::Receiver<Option<Arc<WSFrame>>>,
+ accepts: Arc<dyn Fn() -> bool + Send + Sync>,
+) -> Result<OwnedWatchFrameWs, String> {
+ use futures::{SinkExt, StreamExt};
+ use tokio_tungstenite::tungstenite::Message;
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .map_err(|error| error.to_string())?;
+ let port = listener
+ .local_addr()
+ .map_err(|error| error.to_string())?
+ .port();
+ let route = format!("/{}", uuid::Uuid::new_v4());
+ let url = format!("ws://127.0.0.1:{port}{route}");
+ let shutdown = CancellationToken::new();
+ let cancelled = shutdown.clone();
+ let task = tokio::spawn(async move {
+ let mut connections = tokio::task::JoinSet::new();
+ let mut failure = None;
+ loop {
+ tokio::select! {
+ biased;
+ _ = cancelled.cancelled() => break,
+ joined = connections.join_next(), if !connections.is_empty() => {
+ if let Some(Err(error)) = joined {
+ failure = Some(format!("Preparing frame connection join failed: {error}"));
+ break;
+ }
+ }
+ accepted = listener.accept() => {
+ let (stream, _) = match accepted {
+ Ok(value) => value,
+ Err(error) => {
+ tracing::debug!(%error, "Preparing frame transport accept stopped");
+ break;
+ }
+ };
+ if connections.len() >= 8 {
+ drop(stream);
+ continue;
+ }
+ let expected = route.clone();
+ let mut frames = frame_rx.clone();
+ let accepts = accepts.clone();
+ let cancelled = cancelled.clone();
+ connections.spawn(async move {
+ let exchange = async move {
+ let Ok(mut socket) = tokio_tungstenite::accept_hdr_async(
+ stream,
+ move |request: &tokio_tungstenite::tungstenite::handshake::server::Request, response| {
+ if request.uri().path() == expected && request.uri().query().is_none() {
+ Ok(response)
+ } else {
+ Err(tokio_tungstenite::tungstenite::http::Response::builder().status(404).body(None).unwrap())
+ }
+ },
+ ).await else { return; };
+ loop {
+ let frame = frames.borrow_and_update().clone();
+ if let Some(frame) = frame
+ && accepts()
+ && socket.send(Message::Binary(pack_ws_frame(&frame))).await.is_err()
+ {
+ return;
+ }
+ tokio::select! {
+ changed = frames.changed() => if changed.is_err() { return; },
+ message = socket.next() => match message {
+ None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return,
+ _ => {}
+ }
+ }
+ }
+ };
+ tokio::select! {
+ biased;
+ _ = cancelled.cancelled() => {},
+ _ = exchange => {},
+ }
+ });
+ }
+ }
+ }
+ cancelled.cancel();
+ drop(listener);
+ while let Some(joined) = connections.join_next().await {
+ if let Err(error) = joined {
+ failure.get_or_insert_with(|| {
+ format!("Preparing frame connection join failed: {error}")
+ });
+ }
+ }
+ failure.map_or(Ok(()), Err)
+ });
+ Ok(OwnedWatchFrameWs {
+ url,
+ shutdown,
+ task: Some(task),
+ })
+}
+
+#[cfg(test)]
+mod owned_preparing_tests {
+ use super::*;
+ use futures::StreamExt;
+ use tokio::io::AsyncWriteExt;
+
+ #[tokio::test]
+ async fn owned_transport_joins_incomplete_handshake_and_releases_port() {
+ let (_frames, rx) = watch::channel(None);
+ let server = create_owned_watch_frame_ws(rx, Arc::new(|| true))
+ .await
+ .unwrap();
+ let address = server
+ .url
+ .strip_prefix("ws://")
+ .unwrap()
+ .split('/')
+ .next()
+ .unwrap()
+ .to_string();
+ let mut client = tokio::net::TcpStream::connect(&address).await.unwrap();
+ client.write_all(b"GET / HTTP/1.1\r\n").await.unwrap();
+ tokio::task::yield_now().await;
+ tokio::time::timeout(std::time::Duration::from_secs(2), server.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ let listener = tokio::net::TcpListener::bind(address).await.unwrap();
+ drop(listener);
+ }
+
+ #[tokio::test]
+ async fn owned_transport_keeps_exact_frame_encoding_and_joins_live_client() {
+ let frame = Arc::new(WSFrame {
+ data: Arc::new(vec![1, 2, 3, 4]),
+ width: 1,
+ height: 1,
+ stride: 4,
+ frame_number: 0,
+ target_time_ns: 0,
+ format: WSFrameFormat::Rgba,
+ created_at: Instant::now(),
+ });
+ let weak = Arc::downgrade(&frame);
+ let expected = pack_ws_frame(&frame);
+ let (frames, rx) = watch::channel(Some(frame));
+ let server = create_owned_watch_frame_ws(rx, Arc::new(|| true))
+ .await
+ .unwrap();
+ let (mut socket, _) = tokio_tungstenite::connect_async(&server.url).await.unwrap();
+ assert_eq!(socket.next().await.unwrap().unwrap().into_data(), expected);
+ tokio::time::timeout(std::time::Duration::from_secs(2), server.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ drop(frames);
+ assert!(weak.upgrade().is_none());
+ }
+
+ #[tokio::test]
+ async fn owned_transport_cancellation_joins_stalled_large_frame_send() {
+ let frame = Arc::new(WSFrame {
+ data: Arc::new(vec![1; 16 * 1024 * 1024]),
+ width: 2048,
+ height: 2048,
+ stride: 8192,
+ frame_number: 0,
+ target_time_ns: 0,
+ format: WSFrameFormat::Rgba,
+ created_at: Instant::now(),
+ });
+ let weak = Arc::downgrade(&frame);
+ let (frames, rx) = watch::channel(Some(frame));
+ let server = create_owned_watch_frame_ws(rx, Arc::new(|| true))
+ .await
+ .unwrap();
+ let (socket, _) = tokio_tungstenite::connect_async(&server.url).await.unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ tokio::time::timeout(std::time::Duration::from_secs(2), server.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ drop(socket);
+ drop(frames);
+ assert!(weak.upgrade().is_none());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/gpui_app.rs b/apps/desktop/src-tauri/src/gpui_app.rs
index 0157c31fe..f01c87bf9 100644
--- a/apps/desktop/src-tauri/src/gpui_app.rs
+++ b/apps/desktop/src-tauri/src/gpui_app.rs
@@ -968,6 +968,10 @@ pub async fn switch_to_gpui_app(app: AppHandle) -> Result<(), String> {
///
/// `true` means the caller must exit before any window is created.
pub fn redirect_at_startup_if_enabled(app: &AppHandle) -> Result<bool, String> {
+ #[cfg(debug_assertions)]
+ if crate::stop_editor_benchmark::enabled() {
+ return Ok(false);
+ }
let update_handoff = handle_update_handoff(app);
let redirect = !update_handoff && redirect_decision(app)?;
if !redirect {
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 751f027c4..17447ba4a 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -17,6 +17,7 @@ mod clip_thumbnails;
mod crash_sentinel;
mod deeplink_actions;
mod diagnostics;
+mod editor_preparing;
mod editor_window;
mod exit_shutdown;
mod export;
@@ -39,6 +40,7 @@ mod permissions;
mod picker_benchmark;
mod platform;
mod power_observer;
+mod preparing_finalization;
mod presets;
mod recording;
mod recording_settings;
@@ -46,6 +48,8 @@ mod recording_telemetry;
mod recordings_locations;
mod recovery;
mod screenshot_editor;
+#[cfg(debug_assertions)]
+mod stop_editor_benchmark;
mod target_select_overlay;
mod telemetry;
mod thumbnails;
@@ -159,6 +163,7 @@ const MAX_SETTLED_FINALIZATIONS: usize = 32;
struct FinalizingRecordingsMap {
attempts: std::collections::HashMap<ProjectObjectId, Arc<FinalizationAttempt>>,
settled: std::collections::VecDeque<(ProjectObjectId, String)>,
+ last_preparing_generation: u64,
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -172,6 +177,10 @@ struct FinalizationAttempt {
origin: FinalizationOrigin,
project: Arc<FinalizationProject>,
result: watch::Sender<FinalizationResult>,
+ preparing_generation: Option<u64>,
+ preparing_presentation:
+ watch::Sender<Option<Result<Arc<cap_project::ProjectConfiguration>, String>>>,
+ preparing: watch::Sender<preparing_finalization::PreparingFinalizationState>,
}
pub(crate) struct FinalizationToken {
@@ -974,6 +983,7 @@ impl FinalizingRecordings {
project: Arc<FinalizationProject>,
retry_failed: bool,
origin: FinalizationOrigin,
+ preparing_requested: bool,
) -> Result<FinalizationRequest, String> {
if project.access != FinalizationAccess::Write {
return Err("Recording directory was not admitted for recovery.".into());
@@ -991,11 +1001,23 @@ impl FinalizingRecordings {
{
return Ok(FinalizationRequest::Existing(attempt.result.subscribe()));
}
+ let preparing_generation = if preparing_requested
+ && origin == FinalizationOrigin::Recording
+ && let Some(generation) = recordings.last_preparing_generation.checked_add(1)
+ {
+ recordings.last_preparing_generation = generation;
+ Some(generation)
+ } else {
+ None
+ };
let attempt = Arc::new(FinalizationAttempt {
id: uuid::Uuid::new_v4().to_string(),
origin,
project,
result: watch::channel(None).0,
+ preparing_generation,
+ preparing_presentation: watch::channel(None).0,
+ preparing: watch::channel(Default::default()).0,
});
recordings
.settled
@@ -1013,8 +1035,9 @@ impl FinalizingRecordings {
&self,
project: Arc<FinalizationProject>,
origin: FinalizationOrigin,
+ preparing_requested: bool,
) -> Result<FinalizationToken, String> {
- match self.request(project, true, origin)? {
+ match self.request(project, true, origin, preparing_requested)? {
FinalizationRequest::Started(token) => Ok(token),
FinalizationRequest::Existing(_) => Err(
"This recording is already being prepared. Please wait for it to finish.".into(),
@@ -1026,14 +1049,14 @@ impl FinalizingRecordings {
&self,
project: Arc<FinalizationProject>,
) -> Result<FinalizationToken, String> {
- self.start_with_origin(project, FinalizationOrigin::Recording)
+ self.start_with_origin(project, FinalizationOrigin::Recording, true)
}
pub(crate) fn start_recovering(
&self,
project: Arc<FinalizationProject>,
) -> Result<FinalizationToken, String> {
- self.start_with_origin(project, FinalizationOrigin::Recovery)
+ self.start_with_origin(project, FinalizationOrigin::Recovery, false)
}
pub(crate) async fn recovery_success(&self, path: &Path) -> Result<Option<String>, String> {
@@ -3376,6 +3399,17 @@ async fn cleanup_app_resources_for_exit(app: &AppHandle) {
fake_window::cancel_all_fake_window_listeners(app);
close_target_select_overlays(app);
+ let preparing = app
+ .state::<editor_preparing::PreparingConsumers>()
+ .inner()
+ .clone();
+ let _ = await_exit_step(
+ "dispose_preparing_editor_frames",
+ APP_EXIT_STEP_TIMEOUT,
+ preparing.dispose_all(),
+ )
+ .await;
+
let app_for_pending_editors = app.clone();
let _ = await_exit_step(
"dispose_pending_editor_instances",
@@ -4672,10 +4706,50 @@ async fn stop_playback(editor_instance: WindowEditorInstance) -> Result<(), Stri
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+async fn commit_editor_preparing_frame(
+ editor_instance: WindowEditorInstance,
+ instance_id: String,
+ frame_number: u32,
+ fps: u32,
+) -> Result<bool, String> {
+ editor_instance.commit_preparing_frame(&instance_id, frame_number, fps)
+}
+
+#[tauri::command]
+#[specta::specta]
+async fn start_editor_handoff_playback(
+ editor_instance: WindowEditorInstance,
+ instance_id: String,
+ frame_number: u32,
+ fps: u32,
+ resolution_base: XY<u32>,
+) -> Result<String, String> {
+ editor_instance
+ .start_handoff_playback(&instance_id, frame_number, fps, resolution_base)
+ .await
+}
+
+#[tauri::command]
+#[specta::specta]
+async fn stop_editor_handoff_playback(
+ editor_instance: WindowEditorInstance,
+ instance_id: String,
+ playback_id: String,
+) -> Result<(), String> {
+ editor_instance
+ .stop_handoff_playback(&instance_id, &playback_id)
+ .await
+}
+
#[derive(Serialize, Type, Debug)]
#[serde(rename_all = "camelCase")]
struct SerializedEditorInstance {
+ instance_id: String,
+ preparing_playback: bool,
frames_socket_url: String,
+ preparing_snapshot: Option<editor_preparing::PreparingEditorChanged>,
recording_duration: f64,
saved_project_config: ProjectConfiguration,
recordings: Arc<ProjectRecordingsMeta>,
@@ -4709,6 +4783,11 @@ async fn create_editor_instance(window: Window) -> Result<SerializedEditorInstan
let editor_instance = EditorInstances::get_or_create(&window, path).await?;
Ok(SerializedEditorInstance {
+ instance_id: editor_instance.instance_id.to_string(),
+ preparing_playback: editor_instance.preparing_adoption().is_some(),
+ preparing_snapshot: window
+ .state::<editor_preparing::PreparingConsumers>()
+ .snapshot_for_window(id),
frames_socket_url: format!("ws://localhost:{}", editor_instance.ws_port),
recording_duration: editor_instance.recordings.duration(),
saved_project_config: {
@@ -5107,13 +5186,17 @@ async fn upload_exported_video(
channel.send(UploadProgress { progress: 0.0 }).ok();
+ let existing_video_id = upload::reusable_video_id(meta.sharing.as_ref(), meta.upload.as_ref());
let s3_config = match async {
let video_id = match mode {
UploadMode::Initial { pre_created_video } => {
- if let Some(pre_created) = pre_created_video {
+ if let Some(video_id) = existing_video_id.clone() {
+ Some(video_id)
+ } else if let Some(pre_created) = pre_created_video {
return Ok(pre_created.config);
+ } else {
+ None
}
- None
}
UploadMode::Reupload => {
let Some(sharing) = meta.sharing.clone() else {
@@ -5142,6 +5225,13 @@ async fn upload_exported_video(
Err(err) => return Err(err.to_string()),
};
+ if existing_video_id
+ .as_ref()
+ .is_some_and(|video_id| *video_id != s3_config.id)
+ {
+ return Err("Server did not preserve the existing share link".into());
+ }
+
let screenshot_path = meta.project_path.join("screenshots/display.jpg");
meta.upload = Some(UploadMeta::SinglePartUpload {
video_id: s3_config.id.clone(),
@@ -5150,15 +5240,14 @@ async fn upload_exported_video(
recording_dir: path.clone(),
});
meta.save_for_project()
- .map_err(|e| error!("Failed to save recording meta: {e}"))
- .ok();
+ .map_err(|error| format!("Failed to persist upload state: {error}"))?;
match upload_video(
&app,
s3_config.id.clone(),
file_path,
screenshot_path,
- metadata,
+ meta.sharing.is_some(),
Some(channel.clone()),
)
.await
@@ -5166,24 +5255,29 @@ async fn upload_exported_video(
Ok(uploaded_video) => {
channel.send(UploadProgress { progress: 1.0 }).ok();
+ let link = meta
+ .sharing
+ .as_ref()
+ .map(|sharing| sharing.link.clone())
+ .unwrap_or(uploaded_video.link);
+
meta.upload = Some(UploadMeta::Complete);
meta.sharing = Some(SharingMeta {
- link: uploaded_video.link.clone(),
+ link: link.clone(),
id: uploaded_video.id.clone(),
content_hash: None,
});
meta.save_for_project()
- .map_err(|e| error!("Failed to save recording meta: {e}"))
- .ok();
+ .map_err(|error| format!("Failed to persist sharing state: {error}"))?;
let _ = app
.state::<ArcLock<ClipboardContext>>()
.write()
.await
- .set_text(uploaded_video.link.clone());
+ .set_text(link.clone());
NotificationType::ShareableLinkCopied.send(&app);
- Ok(UploadResult::Success(uploaded_video.link))
+ Ok(UploadResult::Success(link))
}
Err(AuthedApiError::UpgradeRequired) => Ok(UploadResult::UpgradeRequired),
Err(e) => {
@@ -6631,6 +6725,11 @@ fn specta_builder() -> tauri_specta::Builder {
open_file_path,
get_video_metadata,
create_editor_instance,
+ editor_preparing::create_preparing_editor_frame,
+ editor_preparing::get_preparing_editor_state,
+ editor_preparing::seek_preparing_editor,
+ editor_preparing::set_preparing_editor_playing,
+ editor_preparing::stop_preparing_editor_frame,
get_editor_project_path,
get_mic_waveforms,
get_system_audio_waveforms,
@@ -6639,6 +6738,9 @@ fn specta_builder() -> tauri_specta::Builder {
audio_library::import_audio_track_file,
start_playback,
stop_playback,
+ commit_editor_preparing_frame,
+ start_editor_handoff_playback,
+ stop_editor_handoff_playback,
set_playhead_position,
set_project_config,
update_project_config_in_memory,
@@ -6745,6 +6847,7 @@ fn specta_builder() -> tauri_specta::Builder {
NewScreenshotAdded,
RenderFrameEvent,
EditorStateChanged,
+ editor_preparing::PreparingEditorChanged,
FrameLayoutEvent,
CurrentRecordingChanged,
RecordingStarted,
@@ -7043,6 +7146,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
app.manage(http_client::RetryableHttpClient::default());
app.manage(PendingScreenshots::default());
app.manage(FinalizingRecordings::default());
+ app.manage(editor_preparing::PreparingConsumers::default());
app.manage(updates::UpdatesState::default());
updates::spawn_background_loop(app.clone());
@@ -7211,6 +7315,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
app.state::<MainWindowReadyState>().set_ready(true);
tracing::info!("Main window frontend ready");
#[cfg(debug_assertions)]
+ stop_editor_benchmark::run(app.clone());
+ #[cfg(debug_assertions)]
picker_benchmark::run(app.clone());
gpu_context::prewarm_gpu();
tokio::task::spawn_blocking(cap_rendering::prewarm_fonts);
@@ -8282,6 +8388,8 @@ fn retire_project_window(window: &Window, window_id: &CapWindowId) {
let app = window.app_handle();
match window_id {
CapWindowId::Editor { id } => {
+ app.state::<editor_preparing::PreparingConsumers>()
+ .cancel_window(*id, None);
let window_ids = EditorWindowIds::get(app);
match window_ids.ids.lock() {
Ok(mut ids) => ids.retain(|(_, current_id)| current_id != id),
@@ -8574,19 +8682,47 @@ async fn create_editor_instance_impl(
is_software_adapter: shared.is_software_adapter,
});
+ #[cfg(debug_assertions)]
+ let frame_cb: cap_editor::EditorFrameCallback =
+ if stop_editor_benchmark::frame_capture_requested() {
+ let capture_path = path.clone();
+ let mut frame_cb = frame_cb;
+ Box::new(move |output, layout| {
+ stop_editor_benchmark::capture_output(
+ stop_editor_benchmark::CaptureKind::Ordinary,
+ &capture_path,
+ &output,
+ );
+ frame_cb(output, layout);
+ })
+ } else {
+ frame_cb
+ };
+
+ let (audio_output, startup, live_handoff) = app
+ .state::<editor_preparing::PreparingConsumers>()
+ .take_startup(&path)
+ .await?;
let instance = {
let app = app.clone();
- EditorInstance::new(
+ EditorInstance::new_with_startup_inputs(
path,
move |state| {
let _ = EditorStateChanged::new(state).emit(&app);
},
frame_cb,
shared_device,
+ cap_editor::EditorFrameFormat::Rgba,
+ audio_output,
+ startup,
)
.await?
};
+ if let Some(handoff) = &live_handoff {
+ instance.install_preparing_handoff(handoff).await?;
+ }
+
let event_id = RenderFrameEvent::listen_any(&app, {
let preview_tx = instance.preview_tx.clone();
move |e| {
@@ -8600,21 +8736,73 @@ async fn create_editor_instance_impl(
}
});
- instance
- .preview_tx
- .send_modify(|v| *v = Some((0, EDITOR_PREVIEW_FPS, default_editor_preview_resolution())));
+ let started = match instance
+ .start_preparing_handoff(EDITOR_PREVIEW_FPS, default_editor_preview_resolution())
+ .await
+ {
+ Ok(started) => started,
+ Err(error) => {
+ app.unlisten(event_id);
+ let cleanup_failed = if let Some(handoff) = &live_handoff {
+ handoff.stop_and_wait().await.cleanup_failed
+ } else {
+ false
+ };
+ instance.dispose().await;
+ return Err(if cleanup_failed {
+ format!(
+ "Preparing handoff start failed: {error:?}; preparing playback cleanup failed"
+ )
+ } else {
+ format!("Preparing handoff start failed: {error:?}")
+ });
+ }
+ };
+ if !started {
+ let frame = instance
+ .preparing_adoption()
+ .and_then(|adoption| adoption.frame_number(EDITOR_PREVIEW_FPS))
+ .unwrap_or(0);
+ instance.preview_tx.send_modify(|v| {
+ *v = Some((
+ frame,
+ EDITOR_PREVIEW_FPS,
+ default_editor_preview_resolution(),
+ ))
+ });
+ }
Ok((instance, event_id))
}
pub(crate) async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Result<(), String> {
+ let result = wait_for_recording_ready_inner(app, path).await;
+ if result.is_err() {
+ let cleanup = editor_preparing::join_before_ordinary(app, path).await;
+ return result.and(cleanup);
+ }
+ result
+}
+
+async fn await_finalization_before_ordinary(
+ app: &AppHandle,
+ path: &Path,
+ result: watch::Receiver<FinalizationResult>,
+) -> Result<(), String> {
+ let finalization = await_finalization_result(result).await;
+ let cleanup = editor_preparing::join_before_ordinary(app, path).await;
+ finalization.and(cleanup)
+}
+
+async fn wait_for_recording_ready_inner(app: &AppHandle, path: &Path) -> Result<(), String> {
+ let display_path = path;
let project = FinalizationProject::observe(path.to_path_buf()).await?;
let path = project.work_path();
let finalizing_state = app.state::<FinalizingRecordings>();
if let Some(result) = finalizing_state.is_finalizing(&project) {
info!("Recording is being finalized, waiting for completion...");
- await_finalization_result(result).await?;
+ await_finalization_before_ordinary(app, display_path, result).await?;
project.validate_async().await?;
info!("Recording finalization completed");
let meta = RecordingMeta::load_for_project(path)
@@ -8625,6 +8813,8 @@ pub(crate) async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Re
return Ok(());
}
+ editor_preparing::join_before_ordinary(app, display_path).await?;
+
let meta = match RecordingMeta::load_for_project(path) {
Ok(meta) => meta,
Err(e) => {
@@ -8649,7 +8839,7 @@ pub(crate) async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Re
project.validate_async().await?;
if let Some(result) = finalizing_state.is_finalizing(&project) {
- await_finalization_result(result).await?;
+ await_finalization_before_ordinary(app, display_path, result).await?;
break;
}
@@ -8676,7 +8866,7 @@ pub(crate) async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Re
project.validate_async().await?;
if let Some(result) = finalizing_state.is_finalizing(&project) {
- await_finalization_result(result).await?;
+ await_finalization_before_ordinary(app, display_path, result).await?;
project.validate_async().await?;
}
@@ -8697,11 +8887,13 @@ pub(crate) async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Re
"Recording directory changed before recovery",
));
}
- match finalizing_state.request(work_project, false, FinalizationOrigin::Recording)? {
+ match finalizing_state.request(work_project, false, FinalizationOrigin::Recording, false)? {
FinalizationRequest::Started(token) => {
run_finalization_worker(token, recording::remux_fragmented_recording).await?;
}
- FinalizationRequest::Existing(result) => await_finalization_result(result).await?,
+ FinalizationRequest::Existing(result) => {
+ await_finalization_before_ordinary(app, display_path, result).await?
+ }
}
project.validate_async().await?;
info!("Crash recovery remux completed");
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index b3113b658..7ae1d7052 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -100,6 +100,24 @@ fn main() {
.join("so.cap.desktop")
.join("logs");
+ #[cfg(debug_assertions)]
+ let path = match (
+ std::env::var_os("CAP_STOP_EDITOR_BENCHMARK_OUTPUT"),
+ std::env::var_os("CAP_STOP_BENCH_LOG_DIR"),
+ ) {
+ (Some(output), Some(directory)) => match create_benchmark_log_directory(
+ std::path::Path::new(&output),
+ std::path::Path::new(&directory),
+ ) {
+ Ok(directory) => directory,
+ Err(error) => {
+ eprintln!("Invalid private benchmark log directory: {error}");
+ std::process::exit(2);
+ }
+ },
+ _ => path,
+ };
+
path
};
@@ -246,6 +264,66 @@ fn create_log_appender(
}
}
+#[cfg(debug_assertions)]
+fn create_benchmark_log_directory(
+ output: &std::path::Path,
+ directory: &std::path::Path,
+) -> std::io::Result<std::path::PathBuf> {
+ use std::{io, path::Component};
+
+ if !output.is_absolute()
+ || !directory.is_absolute()
+ || output == directory
+ || [output, directory].into_iter().any(|path| {
+ path.components().any(|component| {
+ !matches!(
+ component,
+ Component::Prefix(_) | Component::RootDir | Component::Normal(_)
+ )
+ })
+ })
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Benchmark paths must be distinct absolute paths without traversal",
+ ));
+ }
+ let parent = directory.parent().ok_or_else(|| {
+ io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Benchmark log directory has no parent",
+ )
+ })?;
+ if output.parent() != Some(parent) || parent.canonicalize()? != parent || !parent.is_dir() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Benchmark output and logs must share an existing canonical parent",
+ ));
+ }
+ for path in [output, directory] {
+ match std::fs::symlink_metadata(path) {
+ Ok(_) => {
+ return Err(io::Error::new(
+ io::ErrorKind::AlreadyExists,
+ "Benchmark output and log paths must be new",
+ ));
+ }
+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error),
+ }
+ }
+ let builder = std::fs::DirBuilder::new();
+ #[cfg(unix)]
+ let builder = {
+ use std::os::unix::fs::DirBuilderExt;
+ let mut builder = builder;
+ builder.mode(0o700);
+ builder
+ };
+ builder.create(directory)?;
+ Ok(directory.to_path_buf())
+}
+
fn install_panic_hook(logs_dir: std::path::PathBuf) {
let prev = std::panic::take_hook();
let panics_log = logs_dir.join("panics.log");
@@ -384,3 +462,78 @@ mod logging_tests {
assert!(create_log_appender(&directory.0, "other.log").is_some());
}
}
+
+#[cfg(all(test, debug_assertions))]
+mod benchmark_log_directory_tests {
+ use super::create_benchmark_log_directory;
+
+ #[test]
+ fn benchmark_logs_use_a_new_private_sibling_without_creating_output() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().canonicalize().unwrap();
+ let output = root.join("benchmark.json");
+ let logs = root.join("logs");
+ assert_eq!(
+ create_benchmark_log_directory(&output, &logs).unwrap(),
+ logs
+ );
+ assert!(logs.is_dir());
+ assert!(!output.exists());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(logs.metadata().unwrap().permissions().mode() & 0o777, 0o700);
+ }
+ }
+
+ #[test]
+ fn existing_or_foreign_benchmark_paths_are_preserved() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().canonicalize().unwrap();
+ let output = root.join("benchmark.json");
+ let logs = root.join("logs");
+ std::fs::write(&output, "retained evidence").unwrap();
+ assert!(create_benchmark_log_directory(&output, &logs).is_err());
+ assert_eq!(
+ std::fs::read_to_string(&output).unwrap(),
+ "retained evidence"
+ );
+ assert!(!logs.exists());
+ std::fs::create_dir(&logs).unwrap();
+ assert!(create_benchmark_log_directory(&root.join("new.json"), &logs).is_err());
+ assert!(
+ create_benchmark_log_directory(&root.join("new.json"), &root.join("other/logs"))
+ .is_err()
+ );
+ assert!(
+ create_benchmark_log_directory(
+ std::path::Path::new("relative.json"),
+ &root.join("fresh")
+ )
+ .is_err()
+ );
+ assert!(
+ create_benchmark_log_directory(&root.join("new.json"), &root.join("nested/../fresh"))
+ .is_err()
+ );
+ assert!(!root.join("fresh").exists());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlinked_benchmark_parents_are_rejected_without_writes() {
+ use std::os::unix::fs::symlink;
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().canonicalize().unwrap();
+ let actual = root.join("actual");
+ let alias = root.join("alias");
+ std::fs::create_dir(&actual).unwrap();
+ symlink(&actual, &alias).unwrap();
+ assert!(
+ create_benchmark_log_directory(&alias.join("result.json"), &alias.join("logs"))
+ .is_err()
+ );
+ assert!(!actual.join("logs").exists());
+ assert!(!actual.join("result.json").exists());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/preparing_finalization.rs b/apps/desktop/src-tauri/src/preparing_finalization.rs
new file mode 100644
index 000000000..31abc24de
--- /dev/null
+++ b/apps/desktop/src-tauri/src/preparing_finalization.rs
@@ -0,0 +1,588 @@
+use super::{
+ FinalizationAttempt, FinalizationOrigin, FinalizationProject, FinalizationToken,
+ FinalizingRecordings, FinalizingRecordingsMap,
+};
+use cap_recording::{
+ recovery::{PreparingStudioJob, PreparingStudioObserver},
+ studio_recording::CompletedRecording,
+};
+use std::sync::{Arc, Mutex};
+
+#[derive(Clone, Default)]
+pub(super) enum PreparingFinalizationState {
+ #[default]
+ Waiting,
+ Declined,
+ Offered(PreparingStudioObserver),
+}
+
+#[derive(Clone)]
+pub(crate) struct FinalizationPreparing {
+ recordings: Arc<Mutex<FinalizingRecordingsMap>>,
+ attempt: Arc<FinalizationAttempt>,
+}
+
+impl FinalizationToken {
+ pub(crate) fn preparing(&self) -> FinalizationPreparing {
+ FinalizationPreparing {
+ recordings: self.recordings.clone(),
+ attempt: self.attempt.clone(),
+ }
+ }
+}
+
+impl FinalizingRecordings {
+ pub(crate) fn preparing_for_project(
+ &self,
+ project: &FinalizationProject,
+ ) -> Option<FinalizationPreparing> {
+ let recordings = self.recordings.lock().unwrap();
+ let attempt = recordings.attempts.get(&project.identity)?;
+ if attempt.origin != FinalizationOrigin::Recording || attempt.result.borrow().is_some() {
+ return None;
+ }
+ Some(FinalizationPreparing {
+ recordings: self.recordings.clone(),
+ attempt: attempt.clone(),
+ })
+ }
+}
+
+impl FinalizationPreparing {
+ pub(crate) fn allows_preparing_continuation(&self) -> bool {
+ let recordings = self.recordings.lock().unwrap();
+ self.attempt.origin == FinalizationOrigin::Recording
+ && recordings
+ .attempts
+ .get(&self.attempt.project.identity)
+ .map_or_else(
+ || matches!(&*self.attempt.result.borrow(), Some(Ok(()))),
+ |current| Arc::ptr_eq(current, &self.attempt),
+ )
+ && self
+ .attempt
+ .result
+ .borrow()
+ .as_ref()
+ .is_none_or(Result::is_ok)
+ && matches!(&*self.attempt.preparing.borrow(), PreparingFinalizationState::Offered(observer) if observer.publication_succeeded())
+ }
+
+ pub(crate) fn is_pending(&self) -> bool {
+ self.is_current(&self.recordings.lock().unwrap())
+ }
+
+ pub(crate) fn set_presentation(
+ &self,
+ presentation: Result<cap_project::ProjectConfiguration, String>,
+ ) {
+ let recordings = self.recordings.lock().unwrap();
+ if self.is_current(&recordings) {
+ self.attempt
+ .preparing_presentation
+ .send_if_modified(|state| {
+ if state.is_some() {
+ return false;
+ }
+ *state = Some(presentation.map(Arc::new));
+ true
+ });
+ }
+ }
+
+ pub(crate) async fn wait_for_presentation(
+ &self,
+ ) -> Option<Arc<cap_project::ProjectConfiguration>> {
+ let mut presentation = self.attempt.preparing_presentation.subscribe();
+ let mut result = self.attempt.result.subscribe();
+ loop {
+ let state = {
+ let recordings = self.recordings.lock().unwrap();
+ if !self.is_current(&recordings) {
+ return None;
+ }
+ presentation.borrow_and_update().clone()
+ };
+ if let Some(state) = state {
+ return state.ok();
+ }
+ tokio::select! {
+ changed = presentation.changed() => if changed.is_err() { return None; },
+ changed = result.changed() => if changed.is_err() { return None; },
+ }
+ }
+ }
+
+ #[cfg(test)]
+ fn same_attempt(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.attempt, &other.attempt)
+ }
+
+ fn is_current(&self, recordings: &FinalizingRecordingsMap) -> bool {
+ self.attempt.origin == FinalizationOrigin::Recording
+ && recordings
+ .attempts
+ .get(&self.attempt.project.identity)
+ .is_some_and(|current| Arc::ptr_eq(current, &self.attempt))
+ && self.attempt.result.borrow().is_none()
+ }
+
+ pub(crate) fn claim(&self, completed: &CompletedRecording) -> Option<PreparingStudioJob> {
+ self.claim_with(completed, PreparingStudioJob::claim)
+ }
+
+ fn claim_with(
+ &self,
+ completed: &CompletedRecording,
+ claim: impl FnOnce(
+ &CompletedRecording,
+ u64,
+ ) -> Option<(PreparingStudioJob, PreparingStudioObserver)>,
+ ) -> Option<PreparingStudioJob> {
+ let paths_match = completed.project_path == self.attempt.project.display_path()
+ && self.attempt.project.display_path() == self.attempt.project.work_path();
+ let directory_valid = paths_match
+ && self.attempt.preparing_generation.is_some()
+ && self.attempt.project.validate().is_ok();
+ let recordings = self.recordings.lock().unwrap();
+ if !self.is_current(&recordings) {
+ return None;
+ }
+ let mut job = None;
+ self.attempt.preparing.send_if_modified(|state| {
+ if !matches!(state, PreparingFinalizationState::Waiting) {
+ return false;
+ }
+ *state = PreparingFinalizationState::Declined;
+ if directory_valid
+ && let Some(generation) = self.attempt.preparing_generation
+ && let Some((claimed, observer)) = claim(completed, generation)
+ {
+ job = Some(claimed);
+ *state = PreparingFinalizationState::Offered(observer);
+ }
+ true
+ });
+ job
+ }
+
+ pub(crate) async fn wait_for_preparing(&self) -> Option<PreparingStudioObserver> {
+ let mut preparing = self.attempt.preparing.subscribe();
+ let mut result = self.attempt.result.subscribe();
+ loop {
+ let state = {
+ let recordings = self.recordings.lock().unwrap();
+ if !self.is_current(&recordings) {
+ return None;
+ }
+ preparing.borrow_and_update().clone()
+ };
+ match state {
+ PreparingFinalizationState::Waiting => {}
+ PreparingFinalizationState::Declined => return None,
+ PreparingFinalizationState::Offered(observer) => return Some(observer),
+ }
+ tokio::select! {
+ changed = preparing.changed() => if changed.is_err() { return None; },
+ changed = result.changed() => if changed.is_err() { return None; },
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{FinalizationAccess, await_finalization_result, has_pending_finalizations};
+ use cap_project::RecordingMeta;
+ use std::path::Path;
+ use std::time::Duration;
+
+ fn project() -> (tempfile::TempDir, Arc<FinalizationProject>) {
+ let directory = tempfile::tempdir().unwrap();
+ let project = FinalizationProject::capture(
+ directory.path().canonicalize().unwrap(),
+ FinalizationAccess::Write,
+ )
+ .unwrap();
+ (directory, project)
+ }
+
+ async fn wait_for_preparing(
+ preparing: &FinalizationPreparing,
+ ) -> Option<PreparingStudioObserver> {
+ tokio::time::timeout(Duration::from_secs(1), preparing.wait_for_preparing())
+ .await
+ .unwrap()
+ }
+
+ fn completed_without_receipt(path: &Path) -> CompletedRecording {
+ let metadata: RecordingMeta = serde_json::from_value(serde_json::json!({
+ "pretty_name": "Preparing finalization test", "sharing": null,
+ "segments": [{"display": {"path": "content/segments/segment-0/display", "fps": 30}}],
+ "status": {"status": "NeedsRemux"}
+ }))
+ .unwrap();
+ CompletedRecording {
+ project_path: path.to_path_buf(),
+ meta: metadata.studio_meta().unwrap().clone(),
+ cursor_data: Default::default(),
+ clean_stopped: None,
+ }
+ }
+
+ #[tokio::test]
+ async fn declined_receipt_is_not_finalization_success() {
+ let (_directory, project) = project();
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project.clone()).unwrap();
+ let preparing = recordings.preparing_for_project(&project).unwrap();
+ assert!(preparing.same_attempt(&token.preparing()));
+ assert!(
+ preparing
+ .claim(&completed_without_receipt(project.display_path()))
+ .is_none()
+ );
+ assert!(wait_for_preparing(&preparing).await.is_none());
+ assert!(has_pending_finalizations(
+ &recordings.recordings.lock().unwrap()
+ ));
+ let result = token.attempt.result.subscribe();
+ token.finish(Err("configuration write failed".into()));
+ assert!(
+ await_finalization_result(result)
+ .await
+ .unwrap_err()
+ .contains("configuration write failed")
+ );
+ assert!(recordings.preparing_for_project(&project).is_none());
+ }
+
+ #[tokio::test]
+ async fn completion_before_admission_does_not_invoke_claim() {
+ let (_directory, project) = project();
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project.clone()).unwrap();
+ let preparing = token.preparing();
+ token.finish(Ok(()));
+ assert!(
+ preparing
+ .claim_with(
+ &completed_without_receipt(project.display_path()),
+ |_, _| panic!("Completed attempts cannot claim")
+ )
+ .is_none()
+ );
+ assert!(wait_for_preparing(&preparing).await.is_none());
+ assert!(!has_pending_finalizations(
+ &recordings.recordings.lock().unwrap()
+ ));
+ }
+
+ #[tokio::test]
+ async fn failed_retry_has_a_new_attempt_and_rejects_stale_claims() {
+ let (_directory, project) = project();
+ let recordings = FinalizingRecordings::default();
+ let first = recordings.start_finalizing(project.clone()).unwrap();
+ assert_eq!(first.attempt.preparing_generation, Some(1));
+ let stale = first.preparing();
+ first.finish(Err("first failure".into()));
+ let second = recordings.start_finalizing(project.clone()).unwrap();
+ assert_eq!(second.attempt.preparing_generation, Some(2));
+ let current = second.preparing();
+ assert!(!stale.same_attempt(&current));
+ assert!(
+ stale
+ .claim_with(
+ &completed_without_receipt(project.display_path()),
+ |_, _| panic!("Stale attempts cannot claim")
+ )
+ .is_none()
+ );
+ assert!(wait_for_preparing(&stale).await.is_none());
+ assert!(
+ tokio::time::timeout(Duration::from_millis(20), current.wait_for_preparing())
+ .await
+ .is_err()
+ );
+ second.finish(Ok(()));
+ assert!(wait_for_preparing(&current).await.is_none());
+ }
+
+ #[tokio::test]
+ async fn token_drop_wakes_pending_observer_and_preserves_interrupted_error() {
+ let (_directory, project) = project();
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project).unwrap();
+ let preparing = token.preparing();
+ let result = token.attempt.result.subscribe();
+ assert!(
+ tokio::time::timeout(Duration::from_millis(20), preparing.wait_for_preparing())
+ .await
+ .is_err()
+ );
+ drop(token);
+ assert!(
+ tokio::time::timeout(Duration::from_secs(1), preparing.wait_for_preparing())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ await_finalization_result(result)
+ .await
+ .unwrap_err()
+ .contains("interrupted")
+ );
+ }
+
+ #[test]
+ fn native_recording_attempt_allocates_generation_without_capture_coordinator() {
+ let (_directory, project) = project();
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project.clone()).unwrap();
+ let preparing = token.preparing();
+ let clone = preparing.clone();
+ let completed = completed_without_receipt(project.display_path());
+ let called = std::cell::Cell::new(false);
+ assert!(
+ preparing
+ .claim_with(&completed, |actual, generation| {
+ called.set(true);
+ assert_eq!(actual.project_path, project.display_path());
+ assert_eq!(generation, 1);
+ None
+ })
+ .is_none()
+ );
+ assert!(called.get());
+ assert!(
+ clone
+ .claim_with(&completed, |_, _| panic!(
+ "Duplicate admission cannot claim"
+ ))
+ .is_none()
+ );
+ assert!(token.attempt.result.borrow().is_none());
+ token.finish(Ok(()));
+ }
+
+ #[test]
+ fn lazy_open_and_recovery_origin_never_allocate_or_invoke_claim() {
+ let (_directory, project) = project();
+ for (origin, preparing_requested) in [
+ (FinalizationOrigin::Recording, false),
+ (FinalizationOrigin::Recovery, true),
+ ] {
+ let recordings = FinalizingRecordings::default();
+ let token = recordings
+ .start_with_origin(project.clone(), origin, preparing_requested)
+ .unwrap();
+ assert!(
+ token
+ .preparing()
+ .claim_with(
+ &completed_without_receipt(project.display_path()),
+ |_, _| panic!("Ineligible finalization cannot claim")
+ )
+ .is_none()
+ );
+ assert_eq!(
+ recordings
+ .recordings
+ .lock()
+ .unwrap()
+ .last_preparing_generation,
+ 0
+ );
+ if origin == FinalizationOrigin::Recovery {
+ assert!(recordings.preparing_for_project(&project).is_none());
+ }
+ token.finish(Ok(()));
+ }
+ }
+
+ #[test]
+ fn duplicate_finalization_keeps_the_original_attempt_generation() {
+ let (_directory, project) = project();
+ let recordings = FinalizingRecordings::default();
+ let first = recordings.start_finalizing(project.clone()).unwrap();
+ assert!(recordings.start_finalizing(project.clone()).is_err());
+ let existing = recordings
+ .request(project.clone(), false, FinalizationOrigin::Recording, false)
+ .unwrap();
+ assert!(matches!(existing, crate::FinalizationRequest::Existing(_)));
+ assert_eq!(first.attempt.preparing_generation, Some(1));
+ assert_eq!(
+ recordings
+ .recordings
+ .lock()
+ .unwrap()
+ .last_preparing_generation,
+ 1
+ );
+ assert!(
+ first
+ .preparing()
+ .same_attempt(&recordings.preparing_for_project(&project).unwrap())
+ );
+ first.finish(Err("retained retry".into()));
+ let next = recordings.start_finalizing(project).unwrap();
+ assert_eq!(next.attempt.preparing_generation, Some(2));
+ next.finish(Ok(()));
+ }
+
+ #[tokio::test]
+ async fn generation_exhaustion_declines_preview_and_preserves_finalization() {
+ let (_directory, project) = project();
+ let recordings = FinalizingRecordings::default();
+ recordings
+ .recordings
+ .lock()
+ .unwrap()
+ .last_preparing_generation = u64::MAX - 1;
+ let last = recordings.start_finalizing(project.clone()).unwrap();
+ assert_eq!(last.attempt.preparing_generation, Some(u64::MAX));
+ last.finish(Err("retained retry".into()));
+ let exhausted = recordings.start_finalizing(project.clone()).unwrap();
+ assert_eq!(exhausted.attempt.preparing_generation, None);
+ assert_eq!(
+ recordings
+ .recordings
+ .lock()
+ .unwrap()
+ .last_preparing_generation,
+ u64::MAX
+ );
+ let preparing = exhausted.preparing();
+ assert!(
+ preparing
+ .claim_with(
+ &completed_without_receipt(project.display_path()),
+ |_, _| { panic!("An exhausted sequence cannot claim") }
+ )
+ .is_none()
+ );
+ assert!(wait_for_preparing(&preparing).await.is_none());
+ assert!(has_pending_finalizations(
+ &recordings.recordings.lock().unwrap()
+ ));
+ let result = exhausted.attempt.result.subscribe();
+ exhausted.finish(Ok(()));
+ assert_eq!(await_finalization_result(result).await, Ok(()));
+ assert!(!has_pending_finalizations(
+ &recordings.recordings.lock().unwrap()
+ ));
+ }
+
+ #[test]
+ fn a_different_stopped_project_never_invokes_claim() {
+ let (_directory, project) = project();
+ let other = tempfile::tempdir().unwrap();
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project).unwrap();
+ assert!(
+ token
+ .preparing()
+ .claim_with(&completed_without_receipt(other.path()), |_, _| panic!(
+ "Wrong project cannot claim"
+ ))
+ .is_none()
+ );
+ token.finish(Ok(()));
+ }
+
+ #[test]
+ fn canonical_alias_declines_without_rewriting_the_stopped_path() {
+ let directory = tempfile::tempdir().unwrap();
+ std::fs::create_dir(directory.path().join("alias")).unwrap();
+ std::fs::create_dir(directory.path().join("project")).unwrap();
+ let display = directory.path().join("alias/../project");
+ let project =
+ FinalizationProject::capture(display.clone(), FinalizationAccess::Write).unwrap();
+ assert_ne!(project.display_path(), project.work_path());
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project).unwrap();
+ let completed = completed_without_receipt(&display);
+ assert!(
+ token
+ .preparing()
+ .claim_with(&completed, |_, _| panic!(
+ "Alias must not rebind a clean receipt"
+ ))
+ .is_none()
+ );
+ assert_eq!(completed.project_path, display);
+ token.finish(Ok(()));
+ }
+
+ #[test]
+ fn replaced_directory_declines_before_claim() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("project");
+ let moved = directory.path().join("moved");
+ std::fs::create_dir(&original).unwrap();
+ let project = FinalizationProject::capture(
+ original.canonicalize().unwrap(),
+ FinalizationAccess::Write,
+ )
+ .unwrap();
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project.clone()).unwrap();
+ std::fs::rename(&original, &moved).unwrap();
+ std::fs::create_dir(&original).unwrap();
+ assert!(
+ token
+ .preparing()
+ .claim_with(
+ &completed_without_receipt(project.display_path()),
+ |_, _| panic!("Replaced directory cannot claim")
+ )
+ .is_none()
+ );
+ assert!(token.attempt.result.borrow().is_none());
+ token.finish(Err("directory replaced".into()));
+ }
+
+ #[tokio::test]
+ async fn missing_fragments_keep_the_existing_error_and_do_not_claim() {
+ let (_directory, project) = project();
+ let sentinel = project.work_path().join("retained-original.bin");
+ std::fs::write(&sentinel, b"retain original bytes").unwrap();
+ let completed = completed_without_receipt(project.display_path());
+ let recordings = FinalizingRecordings::default();
+ let token = recordings.start_finalizing(project.clone()).unwrap();
+ let preparing = token.preparing();
+ let ordinary = crate::recording::remux_fragmented_recording_with_trigger(
+ project.work_path(),
+ project.display_path(),
+ "recording_stop",
+ None,
+ );
+ let candidate = crate::recording::remux_fragmented_recording_with_preparing(
+ project.work_path(),
+ project.display_path(),
+ "recording_stop",
+ None,
+ Some((&preparing, &completed)),
+ );
+ assert_eq!(candidate, ordinary);
+ assert_eq!(
+ candidate.as_ref().unwrap_err(),
+ "Could not find fragments to remux"
+ );
+ assert!(matches!(
+ *token.attempt.preparing.borrow(),
+ PreparingFinalizationState::Waiting
+ ));
+ assert_eq!(std::fs::read(sentinel).unwrap(), b"retain original bytes");
+ assert!(
+ !project
+ .work_path()
+ .join(crate::recording::FRAGMENTED_EXPORT_FFMPEG_MARKER)
+ .exists()
+ );
+ token.finish(candidate);
+ assert!(wait_for_preparing(&preparing).await.is_none());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 2a3a17887..2123769b9 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -5927,6 +5927,7 @@ async fn handle_recording_finish(
recording,
default_preset,
Some(capture_target),
+ finalization.preparing(),
)
.await;
@@ -5975,6 +5976,7 @@ async fn handle_recording_finish(
project_path: recording.project_path,
meta: updated_studio_meta.clone(),
cursor_data: recording.cursor_data,
+ clean_stopped: None,
},
&recordings,
PresetsStore::get_default_preset(app)?.map(|p| p.config),
@@ -6164,21 +6166,28 @@ async fn finalize_studio_recording(
recording: cap_recording::studio_recording::CompletedRecording,
default_preset: Option<ProjectConfiguration>,
capture_target: Option<ScreenCaptureTarget>,
+ preparing: crate::preparing_finalization::FinalizationPreparing,
) -> Result<(), String> {
info!("Starting background finalization for recording");
project.validate_async().await?;
+ preparing.set_presentation(preparing_presentation_snapshot(
+ default_preset.as_ref(),
+ capture_target.as_ref(),
+ ));
let recording_dir = project.work_path().to_path_buf();
let screenshots_dir = recording_dir.join("screenshots");
let display_path = project.display_path().to_path_buf();
let recording_dir_for_remux = recording_dir.clone();
let app_for_remux = app.clone();
- let remux_result = tokio::task::spawn_blocking(move || {
- remux_fragmented_recording_with_trigger(
+ let (remux_result, recording) = tokio::task::spawn_blocking(move || {
+ let result = remux_fragmented_recording_with_preparing(
&recording_dir_for_remux,
&display_path,
"recording_stop",
Some(&app_for_remux),
- )
+ Some((&preparing, &recording)),
+ );
+ (result, recording)
})
.await
.map_err(|e| format!("Recording finalization task panicked: {e}"))?;
@@ -6220,6 +6229,7 @@ async fn finalize_studio_recording(
project_path: recording.project_path,
meta: updated_studio_meta,
cursor_data: recording.cursor_data,
+ clean_stopped: None,
},
&recordings,
default_preset,
@@ -6421,24 +6431,7 @@ fn project_config_from_recording(
let camera_preview_manager = CameraPreviewManager::new(app);
if let Ok(camera_preview_state) = camera_preview_manager.get_state() {
- match camera_preview_state.shape {
- CameraPreviewShape::Round => {
- config.camera.shape = CameraShape::Square;
- config.camera.rounding = 100.0;
- }
- CameraPreviewShape::Square => {
- config.camera.shape = CameraShape::Square;
- config.camera.rounding = 25.0;
- }
- CameraPreviewShape::Full => {
- config.camera.shape = CameraShape::Source;
- config.camera.rounding = 25.0;
- }
- }
-
- config.camera.background_blur = cap_project::BackgroundBlurConfig {
- mode: camera_preview_state.background_blur,
- };
+ apply_recording_camera_preview_state(&mut config, &camera_preview_state);
}
let timeline_segments = recordings
@@ -6478,8 +6471,17 @@ fn project_config_from_recording(
});
}
- config.timeline = Some(TimelineConfiguration {
- segments: timeline_segments,
+ config.timeline = Some(recording_timeline(timeline_segments, zoom_segments));
+
+ config
+}
+
+pub(crate) fn recording_timeline(
+ segments: Vec<TimelineSegment>,
+ zoom_segments: Vec<ZoomSegment>,
+) -> TimelineConfiguration {
+ TimelineConfiguration {
+ segments,
transitions: Vec::new(),
zoom_segments,
scene_segments: Vec::new(),
@@ -6491,9 +6493,31 @@ fn project_config_from_recording(
keyboard_segments: Vec::new(),
audio_segments: Vec::new(),
camera3d_segments: Vec::new(),
- });
+ }
+}
- config
+fn apply_recording_camera_preview_state(
+ config: &mut ProjectConfiguration,
+ camera_preview_state: &crate::camera::CameraPreviewState,
+) {
+ match camera_preview_state.shape {
+ CameraPreviewShape::Round => {
+ config.camera.shape = CameraShape::Square;
+ config.camera.rounding = 100.0;
+ }
+ CameraPreviewShape::Square => {
+ config.camera.shape = CameraShape::Square;
+ config.camera.rounding = 25.0;
+ }
+ CameraPreviewShape::Full => {
+ config.camera.shape = CameraShape::Source;
+ config.camera.rounding = 25.0;
+ }
+ }
+
+ config.camera.background_blur = cap_project::BackgroundBlurConfig {
+ mode: camera_preview_state.background_blur,
+ };
}
fn should_enable_notch_overlay(
@@ -6661,6 +6685,19 @@ pub fn remux_fragmented_recording_with_trigger(
display_path: &Path,
trigger: &'static str,
app: Option<&AppHandle>,
+) -> Result<(), String> {
+ remux_fragmented_recording_with_preparing(recording_dir, display_path, trigger, app, None)
+}
+
+pub(crate) fn remux_fragmented_recording_with_preparing(
+ recording_dir: &Path,
+ display_path: &Path,
+ trigger: &'static str,
+ app: Option<&AppHandle>,
+ preparing: Option<(
+ &crate::preparing_finalization::FinalizationPreparing,
+ &studio_recording::CompletedRecording,
+ )>,
) -> Result<(), String> {
crate::recovery::ensure_finalization_storage(recording_dir, display_path)?;
let incomplete_recording = RecoveryManager::inspect_recording(recording_dir);
@@ -6669,7 +6706,10 @@ pub fn remux_fragmented_recording_with_trigger(
let normal_stop = trigger == "recording_stop";
let validation_start = std::time::Instant::now();
let outcome = if normal_stop {
- RecoveryManager::finalize(&recording)
+ match preparing.and_then(|(publisher, completed)| publisher.claim(completed)) {
+ Some(job) => RecoveryManager::finalize_with_preparing(&recording, job),
+ None => RecoveryManager::finalize(&recording),
+ }
} else {
RecoveryManager::recover(&recording)
};
@@ -9505,6 +9545,7 @@ mod studio_joined_completion_tests {
},
},
cursor_data: Default::default(),
+ clean_stopped: None,
}),
}
},
@@ -9758,3 +9799,335 @@ mod studio_capture_control_tests {
}
}
}
+
+pub(crate) fn preparing_presentation_snapshot(
+ preset: Option<&ProjectConfiguration>,
+ capture_target: Option<&ScreenCaptureTarget>,
+) -> Result<ProjectConfiguration, String> {
+ let mut config = preset
+ .cloned()
+ .ok_or("Default presentation requires ordinary finalization")?;
+ if matches!(capture_target, None | Some(ScreenCaptureTarget::CameraOnly))
+ || !matches!(
+ config.background.source,
+ cap_project::BackgroundSource::Color { .. }
+ | cap_project::BackgroundSource::Gradient {
+ animated: None | Some(false),
+ ..
+ }
+ )
+ || config.background.notch.is_some()
+ {
+ return Err("Presentation requires ordinary finalization".into());
+ }
+ config.cursor.size = cap_project::CursorConfiguration::default().size;
+ apply_screen_recording_presentation_defaults(&mut config, capture_target, false, None);
+ Ok(config)
+}
+
+#[cfg(test)]
+mod preparing_presentation_tests {
+ use super::*;
+
+ #[test]
+ fn preparing_never_guesses_default_wallpaper_or_animated_background() {
+ assert!(preparing_presentation_snapshot(None, None).is_err());
+ let config = ProjectConfiguration::default();
+ assert!(preparing_presentation_snapshot(Some(&config), None).is_err());
+ assert!(
+ preparing_presentation_snapshot(Some(&config), Some(&ScreenCaptureTarget::CameraOnly))
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn static_preset_defaults_match_the_existing_screen_defaults() {
+ let target = ScreenCaptureTarget::Display {
+ id: "1".parse().unwrap(),
+ };
+ let mut config = ProjectConfiguration::default();
+ config.cursor.size = 173;
+ config.background.padding = 0.0;
+ config.background.rounding = 0.0;
+ let projected = preparing_presentation_snapshot(Some(&config), Some(&target)).unwrap();
+ let mut ordinary = config;
+ ordinary.cursor.size = cap_project::CursorConfiguration::default().size;
+ apply_screen_recording_presentation_defaults(&mut ordinary, Some(&target), false, None);
+ assert_eq!(
+ serde_json::to_value(projected).unwrap(),
+ serde_json::to_value(ordinary).unwrap()
+ );
+ }
+}
+
+#[cfg(test)]
+mod preparing_presentation_parity_tests {
+ use super::*;
+ use cap_project::{BackgroundSource, ClipConfiguration, ClipOffsets, ScreenMovementSpring};
+
+ fn value(config: &ProjectConfiguration) -> serde_json::Value {
+ serde_json::to_value(config).unwrap()
+ }
+
+ fn targets() -> Vec<ScreenCaptureTarget> {
+ vec![
+ ScreenCaptureTarget::Display {
+ id: "1".parse().unwrap(),
+ },
+ ScreenCaptureTarget::Window {
+ id: "1".parse().unwrap(),
+ },
+ ScreenCaptureTarget::Area {
+ screen: "1".parse().unwrap(),
+ bounds: scap_targets::bounds::LogicalBounds::new(
+ scap_targets::bounds::LogicalPosition::new(10.0, 20.0),
+ scap_targets::bounds::LogicalSize::new(320.0, 240.0),
+ ),
+ },
+ ]
+ }
+
+ fn one_segment(end: f64) -> Vec<TimelineSegment> {
+ vec![TimelineSegment {
+ recording_clip: 0,
+ start: 0.0,
+ end,
+ timescale: 1.0,
+ name: None,
+ speed_audio_mode: None,
+ }]
+ }
+
+ fn preset() -> ProjectConfiguration {
+ ProjectConfiguration::default()
+ }
+
+ fn ordinary_static_projection(
+ preset: &ProjectConfiguration,
+ target: &ScreenCaptureTarget,
+ segments: Vec<TimelineSegment>,
+ ) -> ProjectConfiguration {
+ let mut config = preset.clone();
+ config.cursor.size = cap_project::CursorConfiguration::default().size;
+ apply_screen_recording_presentation_defaults(&mut config, Some(target), false, None);
+ apply_recording_camera_preview_state(
+ &mut config,
+ &crate::camera::CameraPreviewState::default(),
+ );
+ config.timeline = Some(recording_timeline(segments, Vec::new()));
+ config
+ }
+
+ #[test]
+ fn static_color_projection_preserves_preset_and_matches_ordinary_screen_defaults() {
+ for target in targets() {
+ let mut preset = preset();
+ preset.cursor.size = 173;
+ preset.background.padding = 0.0;
+ preset.background.rounding = 0.0;
+ preset.background.source = BackgroundSource::Color {
+ value: [32, 64, 128],
+ alpha: 160,
+ };
+ preset.screen_movement_spring = ScreenMovementSpring {
+ stiffness: 120.0,
+ damping: 14.0,
+ mass: 1.0,
+ };
+ let original = value(&preset);
+ let snapshot = preparing_presentation_snapshot(Some(&preset), Some(&target)).unwrap();
+ let stopped = recording_timeline(one_segment(6.0), Vec::new());
+ let projected =
+ crate::editor_preparing::project_from_preparing_presentation(&snapshot, &stopped);
+ let ordinary = ordinary_static_projection(&preset, &target, one_segment(6.0));
+ assert_eq!(value(&projected), value(&ordinary));
+ assert_eq!(value(&preset), original);
+ assert_eq!(projected.background.padding, 10.0);
+ assert_eq!(
+ projected.background.rounding,
+ if matches!(target, ScreenCaptureTarget::Area { .. }) {
+ 0.0
+ } else {
+ 7.5
+ }
+ );
+ assert_eq!(
+ projected.cursor.size,
+ cap_project::CursorConfiguration::default().size
+ );
+ assert_eq!(
+ serde_json::to_value(projected.screen_movement_spring).unwrap(),
+ serde_json::to_value(ScreenMovementSpring::default()).unwrap()
+ );
+ assert!(matches!(
+ projected.background.source,
+ BackgroundSource::Color {
+ value: [32, 64, 128],
+ alpha: 160
+ }
+ ));
+ }
+ }
+
+ #[test]
+ fn static_gradients_preserve_explicit_presentation_values_for_each_screen_target() {
+ for target in targets() {
+ for animated in [None, Some(false)] {
+ let mut preset = preset();
+ preset.background.padding = 23.0;
+ preset.background.rounding = 11.0;
+ preset.background.source = BackgroundSource::Gradient {
+ from: [17, 41, 65],
+ to: [193, 211, 227],
+ angle: 217,
+ noise_intensity: Some(0.125),
+ noise_scale: Some(1.5),
+ animated,
+ animation_speed: Some(0.25),
+ };
+ preset.screen_movement_spring = ScreenMovementSpring {
+ stiffness: 150.0,
+ damping: 22.0,
+ mass: 0.8,
+ };
+ let snapshot =
+ preparing_presentation_snapshot(Some(&preset), Some(&target)).unwrap();
+ let stopped = recording_timeline(one_segment(6.0), Vec::new());
+ let projected = crate::editor_preparing::project_from_preparing_presentation(
+ &snapshot, &stopped,
+ );
+ assert_eq!(
+ value(&projected),
+ value(&ordinary_static_projection(
+ &preset,
+ &target,
+ one_segment(6.0)
+ ))
+ );
+ assert_eq!(projected.background.padding, 23.0);
+ assert_eq!(projected.background.rounding, 11.0);
+ assert_eq!(
+ serde_json::to_value(&projected.background.source).unwrap(),
+ serde_json::to_value(&preset.background.source).unwrap()
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn unresolved_and_late_presentation_inputs_are_declined_without_mutating_presets() {
+ let target = targets().remove(0);
+ assert!(preparing_presentation_snapshot(None, Some(&target)).is_err());
+ let mut preset = preset();
+ for source in [
+ BackgroundSource::Wallpaper {
+ path: Some("wallpaper.jpg".into()),
+ },
+ BackgroundSource::Image {
+ path: Some("image.png".into()),
+ },
+ BackgroundSource::AnimatedGradient {
+ config: Default::default(),
+ },
+ BackgroundSource::Gradient {
+ from: [0, 0, 0],
+ to: [255, 255, 255],
+ angle: 90,
+ noise_intensity: None,
+ noise_scale: None,
+ animated: Some(true),
+ animation_speed: None,
+ },
+ ] {
+ preset.background.source = source;
+ let original = value(&preset);
+ assert!(preparing_presentation_snapshot(Some(&preset), Some(&target)).is_err());
+ assert_eq!(value(&preset), original);
+ }
+ preset.background.source = BackgroundSource::default();
+ for enabled in [false, true] {
+ preset.background.notch = Some(cap_project::NotchConfiguration {
+ enabled,
+ ..Default::default()
+ });
+ assert!(preparing_presentation_snapshot(Some(&preset), Some(&target)).is_err());
+ }
+ preset.background.notch = None;
+ assert!(preparing_presentation_snapshot(Some(&preset), None).is_err());
+ assert!(
+ preparing_presentation_snapshot(Some(&preset), Some(&ScreenCaptureTarget::CameraOnly))
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn stopped_timeline_replaces_preset_edits_but_keeps_explicit_clip_offsets() {
+ let target = targets().remove(0);
+ let mut preset = preset();
+ preset.clips = vec![ClipConfiguration {
+ index: 0,
+ offsets: ClipOffsets {
+ camera: 0.125,
+ mic: -0.25,
+ system_audio: 0.0625,
+ },
+ offsets_auto_calculated: false,
+ }];
+ let old_zoom: ZoomSegment = serde_json::from_value(serde_json::json!({
+ "start": 1.0, "end": 4.0, "amount": 2.0, "mode": "auto"
+ }))
+ .unwrap();
+ preset.timeline = Some(recording_timeline(one_segment(2.0), vec![old_zoom]));
+ let snapshot = preparing_presentation_snapshot(Some(&preset), Some(&target)).unwrap();
+ let stopped = recording_timeline(one_segment(6.0), Vec::new());
+ let projected =
+ crate::editor_preparing::project_from_preparing_presentation(&snapshot, &stopped);
+ let ordinary = ordinary_static_projection(&preset, &target, one_segment(6.0));
+ assert_eq!(value(&projected), value(&ordinary));
+ let timeline = projected.timeline.as_ref().unwrap();
+ assert_eq!(timeline.segments.len(), 1);
+ assert_eq!(timeline.segments[0].end, 6.0);
+ assert!(timeline.zoom_segments.is_empty());
+ assert_eq!(
+ serde_json::to_value(&projected.clips).unwrap(),
+ serde_json::to_value(&preset.clips).unwrap()
+ );
+ assert_eq!(preset.timeline.as_ref().unwrap().segments[0].end, 2.0);
+ assert_eq!(preset.timeline.as_ref().unwrap().zoom_segments.len(), 1);
+ }
+
+ #[test]
+ fn ordinary_late_camera_state_changes_only_the_three_existing_camera_fields() {
+ for (shape, expected_shape, rounding) in [
+ (CameraPreviewShape::Round, CameraShape::Square, 100.0),
+ (CameraPreviewShape::Square, CameraShape::Square, 25.0),
+ (CameraPreviewShape::Full, CameraShape::Source, 25.0),
+ ] {
+ for blur in [
+ cap_project::BackgroundBlurMode::Off,
+ cap_project::BackgroundBlurMode::Light,
+ cap_project::BackgroundBlurMode::Heavy,
+ ] {
+ let mut config = preset();
+ config.camera.size = 41.0;
+ config.camera.mirror = true;
+ let mut expected = config.clone();
+ expected.camera.shape = expected_shape;
+ expected.camera.rounding = rounding;
+ expected.camera.background_blur.mode = blur;
+ apply_recording_camera_preview_state(
+ &mut config,
+ &crate::camera::CameraPreviewState {
+ size: 99.0,
+ shape: shape.clone(),
+ mirrored: false,
+ background_blur: blur,
+ },
+ );
+ assert_eq!(value(&config), value(&expected));
+ assert_eq!(config.camera.size, 41.0);
+ assert!(config.camera.mirror);
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/stop-editor-benchmark.js b/apps/desktop/src-tauri/src/stop-editor-benchmark.js
new file mode 100644
index 000000000..7f991f5f8
--- /dev/null
+++ b/apps/desktop/src-tauri/src/stop-editor-benchmark.js
@@ -0,0 +1,30 @@
+(() => {
+ let reported = false;
+ const report = () => {
+ if (reported) return;
+ reported = true;
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ void window.__TAURI_INTERNALS__.invoke("plugin:event|emit", {
+ event: "cap-stop-benchmark-frame",
+ payload: {},
+ });
+ });
+ });
+ };
+ const deadline = performance.now() + 180_000;
+ const observe = () => {
+ const canvas = document.getElementById("canvas");
+ const stats = window.__capFpsStats?.();
+ if (
+ stats?.renderCount > 0 &&
+ canvas?.width > 0 &&
+ getComputedStyle(canvas).visibility === "visible"
+ ) {
+ report();
+ } else if (performance.now() < deadline) {
+ requestAnimationFrame(observe);
+ }
+ };
+ requestAnimationFrame(observe);
+})();
diff --git a/apps/desktop/src-tauri/src/stop-editor-parity-dom.js b/apps/desktop/src-tauri/src/stop-editor-parity-dom.js
new file mode 100644
index 000000000..3900ad501
--- /dev/null
+++ b/apps/desktop/src-tauri/src/stop-editor-parity-dom.js
@@ -0,0 +1,214 @@
+(() => {
+ const ids = new WeakMap();
+ let nextId = 1;
+ let sequence = 0;
+ let lastState = "";
+ let previousPreparingIds = [];
+ let firstOrdinaryVisibleAt;
+ const started = performance.now();
+ const deadline = started + 180_000;
+ const idFor = (element) => {
+ if (!ids.has(element)) ids.set(element, nextId++);
+ return ids.get(element);
+ };
+ const describe = (canvas) => {
+ const rect = canvas.getBoundingClientRect();
+ let ancestorsVisible = true;
+ for (let element = canvas; element; element = element.parentElement) {
+ const style = getComputedStyle(element);
+ if (
+ style.display === "none" ||
+ style.visibility !== "visible" ||
+ Number(style.opacity) === 0
+ ) {
+ ancestorsVisible = false;
+ break;
+ }
+ }
+ return {
+ id: idFor(canvas),
+ connected: canvas.isConnected,
+ width: canvas.width,
+ height: canvas.height,
+ bounds: {
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ },
+ visible:
+ ancestorsVisible &&
+ canvas.width > 0 &&
+ canvas.height > 0 &&
+ rect.width > 0 &&
+ rect.height > 0 &&
+ rect.bottom > 0 &&
+ rect.right > 0 &&
+ rect.top < innerHeight &&
+ rect.left < innerWidth,
+ };
+ };
+ const geometry = (element) => {
+ if (!element) return null;
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return {
+ id: idFor(element),
+ connected: element.isConnected,
+ bounds: {
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ },
+ inline: {
+ width: element.style.width,
+ height: element.style.height,
+ minHeight: element.style.minHeight,
+ },
+ computed: {
+ width: style.width,
+ height: style.height,
+ minHeight: style.minHeight,
+ maxHeight: style.maxHeight,
+ display: style.display,
+ visibility: style.visibility,
+ flex: style.flex,
+ flexDirection: style.flexDirection,
+ gap: style.gap,
+ paddingTop: style.paddingTop,
+ paddingBottom: style.paddingBottom,
+ },
+ };
+ };
+ const ordinaryLayout = (canvas) => {
+ if (!canvas) return null;
+ const ancestors = [];
+ for (
+ let element = canvas.parentElement;
+ element && ancestors.length < 10;
+ element = element.parentElement
+ ) {
+ ancestors.push(element);
+ }
+ const [wrapper, visibilityLayer, container, player, card, row, layout] =
+ ancestors;
+ const timelineSeparator = document.querySelector(
+ '[role="separator"][aria-label="Resize timeline height"]',
+ );
+ const timeline = timelineSeparator?.parentElement;
+ const sourceStructureMatches = Boolean(
+ container?.parentElement === player &&
+ player?.children.length === 3 &&
+ player?.children[1] === container &&
+ timeline?.parentElement === layout &&
+ row?.nextElementSibling === timeline,
+ );
+ return {
+ sourceStructureMatches,
+ canvas: geometry(canvas),
+ ancestors: ancestors.map(geometry),
+ roles: sourceStructureMatches
+ ? {
+ wrapper: idFor(wrapper),
+ visibilityLayer: idFor(visibilityLayer),
+ container: idFor(container),
+ player: idFor(player),
+ card: idFor(card),
+ row: idFor(row),
+ layout: idFor(layout),
+ }
+ : null,
+ topToolbar: sourceStructureMatches
+ ? geometry(container.previousElementSibling)
+ : null,
+ bottomToolbar: sourceStructureMatches
+ ? geometry(container.nextElementSibling)
+ : null,
+ timeline: geometry(timeline),
+ };
+ };
+ const emit = (value) => {
+ void window.__TAURI_INTERNALS__
+ .invoke("plugin:event|emit", {
+ event: "cap-stop-benchmark-dom",
+ payload: value,
+ })
+ .catch(() => {});
+ };
+ const sample = () => {
+ const now = performance.now();
+ const preparing = Array.from(
+ document.querySelectorAll(
+ 'canvas[aria-label="Recording preview while the editor prepares"]',
+ ),
+ ).map((canvas) => {
+ const siblings = Array.from(canvas.parentElement.children).filter(
+ (element) => element.tagName === "CANVAS",
+ );
+ return {
+ ...describe(canvas),
+ role: siblings.indexOf(canvas) === 1 ? "retained" : "live",
+ };
+ });
+ const ordinaryCanvas = document.getElementById("canvas");
+ const ordinary = ordinaryCanvas ? describe(ordinaryCanvas) : null;
+ const stats = window.__capFpsStats?.();
+ const ordinaryRenderedVisible = Boolean(
+ ordinary?.visible && stats?.renderCount > 0,
+ );
+ if (ordinaryRenderedVisible && firstOrdinaryVisibleAt === undefined) {
+ firstOrdinaryVisibleAt = now;
+ }
+ const state = {
+ preparing,
+ ordinary,
+ ordinaryLayout: ordinaryLayout(ordinaryCanvas),
+ ordinaryRenderedVisible,
+ documentVisibility: document.visibilityState,
+ viewport: {
+ width: innerWidth,
+ height: innerHeight,
+ dpr: devicePixelRatio,
+ },
+ };
+ const serialized = JSON.stringify(state);
+ if (serialized !== lastState) {
+ const currentIds = preparing.map((canvas) => canvas.id);
+ emit({
+ sequence: sequence++,
+ timeOriginMs: performance.timeOrigin,
+ elapsedMs: now - started,
+ observation: "canvas_state",
+ preparingSubtreesDetached: previousPreparingIds.filter(
+ (id) => !currentIds.includes(id),
+ ),
+ state,
+ });
+ previousPreparingIds = currentIds;
+ lastState = serialized;
+ }
+ if (
+ now < deadline &&
+ sequence < 512 &&
+ (firstOrdinaryVisibleAt === undefined ||
+ now - firstOrdinaryVisibleAt < 1000)
+ ) {
+ requestAnimationFrame(sample);
+ } else {
+ emit({
+ sequence: sequence++,
+ timeOriginMs: performance.timeOrigin,
+ elapsedMs: now - started,
+ observation: "complete",
+ reason:
+ firstOrdinaryVisibleAt !== undefined
+ ? "ordinary_visible_settled"
+ : now >= deadline
+ ? "deadline"
+ : "observation_limit",
+ });
+ }
+ };
+ requestAnimationFrame(sample);
+})();
diff --git a/apps/desktop/src-tauri/src/stop_editor_benchmark.rs b/apps/desktop/src-tauri/src/stop_editor_benchmark.rs
new file mode 100644
index 000000000..b8c11c198
--- /dev/null
+++ b/apps/desktop/src-tauri/src/stop_editor_benchmark.rs
@@ -0,0 +1,472 @@
+use std::{
+ path::{Path, PathBuf},
+ sync::{
+ Arc, Mutex, OnceLock,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::{Duration, Instant},
+};
+
+use tauri::{Listener, Manager};
+use tokio::sync::RwLock;
+
+pub const SCRIPT: &str = include_str!("stop-editor-benchmark.js");
+pub const DOM_SCRIPT: &str = include_str!("stop-editor-parity-dom.js");
+static FRAME_CAPTURE: OnceLock<Mutex<FrameCapture>> = OnceLock::new();
+static STARTED: AtomicBool = AtomicBool::new(false);
+
+pub fn enabled() -> bool {
+ std::env::var_os("CAP_STOP_EDITOR_BENCHMARK_OUTPUT").is_some()
+}
+
+pub fn run(app: tauri::AppHandle) {
+ let Some(output) = std::env::var_os("CAP_STOP_EDITOR_BENCHMARK_OUTPUT") else {
+ return;
+ };
+ if STARTED.swap(true, Ordering::SeqCst) {
+ return;
+ }
+ tokio::spawn(async move {
+ let result = measure(&app).await;
+ let mut value = match result {
+ Ok(value) => value,
+ Err(error) => serde_json::json!({ "error": error }),
+ };
+ match finish_frame_capture() {
+ Ok(Some(capture)) => value["frameCapture"] = capture,
+ Ok(None) => {}
+ Err(error) => {
+ value["frameCapture"] =
+ serde_json::json!({ "status": "incomplete", "error": error })
+ }
+ }
+ if let Err(error) = std::fs::write(output, value.to_string()) {
+ tracing::error!(%error, "Could not write Stop benchmark results");
+ }
+ });
+}
+
+async fn measure(app: &tauri::AppHandle) -> Result<serde_json::Value, String> {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ let state = app.state::<Arc<RwLock<crate::App>>>();
+ crate::set_mic_input(
+ app.clone(),
+ state.clone(),
+ std::env::var("CAP_STOP_BENCH_MIC").ok(),
+ )
+ .await?;
+ let capture_target = benchmark_capture_target()?;
+ let action = crate::recording::start_recording(
+ app.clone(),
+ state.clone(),
+ crate::recording::StartRecordingInputs {
+ capture_target,
+ capture_system_audio: std::env::var_os("CAP_STOP_BENCH_SYSTEM_AUDIO").is_some(),
+ mode: cap_recording::RecordingMode::Studio,
+ organization_id: None,
+ },
+ )
+ .await?;
+ if !matches!(action, crate::recording::RecordingAction::Started) {
+ return Err("Benchmark recording did not start".into());
+ }
+ let seconds = std::env::var("CAP_STOP_BENCH_SECONDS")
+ .ok()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(15);
+ tokio::time::sleep(Duration::from_secs(seconds)).await;
+ let project = state
+ .read()
+ .await
+ .current_recording()
+ .map(|recording| recording.recording_dir().clone());
+ if let Err(error) = arm_frame_capture(app, project.as_deref()) {
+ let cleanup = crate::recording::stop_recording(app.clone(), state.clone()).await;
+ return Err(match cleanup {
+ Ok(()) => error,
+ Err(cleanup_error) => format!("{error}; recording stop also failed: {cleanup_error}"),
+ });
+ }
+ let dom_capture = DomCapture::start(app);
+ let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
+ let listener = app.listen_any("cap-stop-benchmark-frame", move |_| {
+ let _ = sender.send(Instant::now());
+ });
+ let started = Instant::now();
+ tracing::info!("Stop editor benchmark stop requested");
+ let stopped = crate::recording::stop_recording(app.clone(), state).await;
+ let stop_ms = started.elapsed().as_secs_f64() * 1000.0;
+ if let Err(error) = stopped {
+ app.unlisten(listener);
+ return Err(error);
+ }
+ let frame = tokio::time::timeout(Duration::from_secs(180), receiver.recv()).await;
+ app.unlisten(listener);
+ let frame = frame
+ .map_err(|error| error.to_string())?
+ .ok_or("Editor frame channel closed")?;
+ let mut result = serde_json::json!({
+ "project": project,
+ "recordingSeconds": seconds,
+ "stopCommandMs": stop_ms,
+ "editorFrameMs": frame.saturating_duration_since(started).as_secs_f64() * 1000.0,
+ });
+ if let Some(dom_capture) = dom_capture {
+ result["domObservations"] = dom_capture.finish().await;
+ }
+ Ok(result)
+}
+
+fn benchmark_capture_target() -> Result<cap_recording::screen_capture::ScreenCaptureTarget, String>
+{
+ use cap_recording::screen_capture::ScreenCaptureTarget;
+ if std::env::var_os("CAP_STOP_BENCH_FIXTURE_WINDOW").is_none() {
+ return Ok(ScreenCaptureTarget::Display {
+ id: scap_targets::Display::primary().id(),
+ });
+ }
+ let window = select_exact_fixture(
+ scap_targets::Window::list()
+ .into_iter()
+ .map(|window| (window, window.name())),
+ )?;
+ Ok(ScreenCaptureTarget::Window { id: window.id() })
+}
+
+fn select_exact_fixture<T>(
+ windows: impl Iterator<Item = (T, Option<String>)>,
+) -> Result<T, String> {
+ let mut matching =
+ windows.filter(|(_, name)| name.as_deref() == Some("Cap Stop benchmark fixture"));
+ let window = matching
+ .next()
+ .ok_or("Exact benchmark fixture window is absent")?
+ .0;
+ if matching.next().is_some() {
+ return Err("Exact benchmark fixture window is ambiguous".into());
+ }
+ Ok(window)
+}
+
+pub fn frame_capture_requested() -> bool {
+ enabled() && std::env::var_os("CAP_STOP_BENCH_FRAME_DIR").is_some()
+}
+
+pub fn dom_capture_requested() -> bool {
+ enabled() && std::env::var_os("CAP_STOP_BENCH_DOM_CAPTURE").is_some()
+}
+
+#[derive(Clone, Copy)]
+pub enum CaptureKind {
+ Preparing,
+ Ordinary,
+}
+
+struct CapturedFrame {
+ data: Arc<Vec<u8>>,
+ width: u32,
+ height: u32,
+ stride: u32,
+ frame_number: u32,
+ target_time_ns: u64,
+}
+
+struct FrameCapture {
+ directory: PathBuf,
+ project: PathBuf,
+ preparing: Option<CapturedFrame>,
+ ordinary: Option<CapturedFrame>,
+ closed: bool,
+}
+
+impl FrameCapture {
+ fn record(&mut self, kind: CaptureKind, project: &Path, frame: CapturedFrame) {
+ if self.closed || self.project != project {
+ return;
+ }
+ let slot = match kind {
+ CaptureKind::Preparing => &mut self.preparing,
+ CaptureKind::Ordinary => &mut self.ordinary,
+ };
+ if slot.is_none() {
+ *slot = Some(frame);
+ }
+ }
+}
+
+fn arm_frame_capture(app: &tauri::AppHandle, project: Option<&Path>) -> Result<(), String> {
+ let Some(directory) = std::env::var_os("CAP_STOP_BENCH_FRAME_DIR") else {
+ return Ok(());
+ };
+ if !app
+ .config()
+ .identifier
+ .starts_with("so.cap.desktop.stop-editor-benchmark.")
+ {
+ return Err("Frame capture requires a private benchmark app identifier".into());
+ }
+ let directory = PathBuf::from(directory);
+ if !directory.is_absolute() {
+ return Err("Frame capture directory must be absolute".into());
+ }
+ let project = project
+ .ok_or("Frame capture has no active recording project")?
+ .to_path_buf();
+ std::fs::create_dir(&directory).map_err(|error| error.to_string())?;
+ FRAME_CAPTURE
+ .set(Mutex::new(FrameCapture {
+ directory,
+ project,
+ preparing: None,
+ ordinary: None,
+ closed: false,
+ }))
+ .map_err(|_| "Frame capture was already armed".to_string())
+}
+
+pub fn capture_output(kind: CaptureKind, project: &Path, output: &cap_editor::EditorFrameOutput) {
+ let Some(capture) = FRAME_CAPTURE.get() else {
+ return;
+ };
+ let cap_editor::EditorFrameOutput::Rgba(frame) = output else {
+ return;
+ };
+ capture
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .record(
+ kind,
+ project,
+ CapturedFrame {
+ data: frame.data.clone(),
+ width: frame.width,
+ height: frame.height,
+ stride: frame.padded_bytes_per_row,
+ frame_number: frame.frame_number,
+ target_time_ns: frame.target_time_ns,
+ },
+ );
+}
+
+pub fn capture_ws_frame(kind: CaptureKind, project: &Path, frame: &crate::frame_ws::WSFrame) {
+ let Some(capture) = FRAME_CAPTURE.get() else {
+ return;
+ };
+ if frame.format != crate::frame_ws::WSFrameFormat::Rgba {
+ return;
+ }
+ capture
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .record(
+ kind,
+ project,
+ CapturedFrame {
+ data: frame.data.clone(),
+ width: frame.width,
+ height: frame.height,
+ stride: frame.stride,
+ frame_number: frame.frame_number,
+ target_time_ns: frame.target_time_ns,
+ },
+ );
+}
+
+fn write_captured_frame(
+ directory: &Path,
+ name: &str,
+ frame: CapturedFrame,
+) -> Result<serde_json::Value, String> {
+ let row_bytes = frame
+ .width
+ .checked_mul(4)
+ .ok_or("Captured frame row overflow")?;
+ let expected_bytes = (frame.stride as usize)
+ .checked_mul(frame.height as usize)
+ .ok_or("Captured frame length overflow")?;
+ if frame.width == 0
+ || frame.height == 0
+ || frame.stride < row_bytes
+ || frame.data.len() != expected_bytes
+ {
+ return Err("Captured frame has an incomplete RGBA buffer".into());
+ }
+ let file = directory.join(format!("{name}.rgba"));
+ std::fs::write(&file, frame.data.as_slice()).map_err(|error| error.to_string())?;
+ Ok(serde_json::json!({
+ "file": file,
+ "format": "rgba",
+ "width": frame.width,
+ "height": frame.height,
+ "stride": frame.stride,
+ "frameNumber": frame.frame_number,
+ "targetTimeNs": frame.target_time_ns,
+ "bytes": expected_bytes,
+ }))
+}
+
+fn finish_frame_capture() -> Result<Option<serde_json::Value>, String> {
+ let Some(capture) = FRAME_CAPTURE.get() else {
+ return Ok(None);
+ };
+ let (directory, project, preparing, ordinary) = {
+ let mut capture = capture
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ capture.closed = true;
+ (
+ capture.directory.clone(),
+ capture.project.clone(),
+ capture.preparing.take(),
+ capture.ordinary.take(),
+ )
+ };
+ let mut frames = serde_json::Map::new();
+ for (name, frame) in [("preparing", preparing), ("ordinary", ordinary)] {
+ if let Some(frame) = frame {
+ let _ = frames.insert(
+ name.to_string(),
+ write_captured_frame(&directory, name, frame)?,
+ );
+ }
+ }
+ let value = serde_json::json!({
+ "status": if frames.len() == 2 { "captured_uncompared" } else { "incomplete" },
+ "project": project,
+ "frames": frames,
+ "timingQualification": "Separate untimed parity capture; renderer callback bytes are not external compositor proof",
+ });
+ std::fs::write(directory.join("frames.json"), value.to_string())
+ .map_err(|error| error.to_string())?;
+ Ok(Some(value))
+}
+
+struct DomCapture {
+ app: tauri::AppHandle,
+ listener: tauri::EventId,
+ observations: Arc<Mutex<Vec<serde_json::Value>>>,
+}
+
+impl DomCapture {
+ fn start(app: &tauri::AppHandle) -> Option<Self> {
+ if !dom_capture_requested() {
+ return None;
+ }
+ let observations = Arc::new(Mutex::new(Vec::new()));
+ let captured = observations.clone();
+ let listener = app.listen_any("cap-stop-benchmark-dom", move |event| {
+ if let Ok(value) = serde_json::from_str(event.payload()) {
+ let mut observations = captured
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if observations.len() < 1024 {
+ observations.push(value);
+ }
+ }
+ });
+ Some(Self {
+ app: app.clone(),
+ listener,
+ observations,
+ })
+ }
+
+ async fn finish(self) -> serde_json::Value {
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ let observations = self
+ .observations
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone();
+ serde_json::json!(observations)
+ }
+}
+
+impl Drop for DomCapture {
+ fn drop(&mut self) {
+ self.app.unlisten(self.listener);
+ }
+}
+
+#[cfg(test)]
+mod parity_capture_tests {
+ use super::*;
+
+ fn frame(value: u8) -> CapturedFrame {
+ CapturedFrame {
+ data: Arc::new(vec![value; 8]),
+ width: 2,
+ height: 1,
+ stride: 8,
+ frame_number: 0,
+ target_time_ns: 0,
+ }
+ }
+
+ #[test]
+ fn exact_fixture_selection_rejects_missing_and_ambiguous_titles() {
+ assert!(select_exact_fixture(std::iter::empty::<(u8, Option<String>)>()).is_err());
+ assert_eq!(
+ select_exact_fixture(
+ [
+ (1, Some("Cap Stop benchmark fixture".into())),
+ (2, Some("Cap Stop benchmark fixture extra".into()))
+ ]
+ .into_iter()
+ )
+ .unwrap(),
+ 1
+ );
+ assert!(
+ select_exact_fixture(
+ [
+ (1, Some("Cap Stop benchmark fixture".into())),
+ (2, Some("Cap Stop benchmark fixture".into()))
+ ]
+ .into_iter()
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn first_frames_are_bound_to_project_and_capture_closure() {
+ let project = PathBuf::from("owned.cap");
+ let mut capture = FrameCapture {
+ directory: PathBuf::new(),
+ project: project.clone(),
+ preparing: None,
+ ordinary: None,
+ closed: false,
+ };
+ capture.record(CaptureKind::Preparing, Path::new("other.cap"), frame(1));
+ assert!(capture.preparing.is_none());
+ capture.record(CaptureKind::Preparing, &project, frame(2));
+ capture.record(CaptureKind::Preparing, &project, frame(3));
+ capture.record(CaptureKind::Ordinary, &project, frame(4));
+ assert_eq!(capture.preparing.as_ref().unwrap().data.as_slice(), &[2; 8]);
+ assert_eq!(capture.ordinary.as_ref().unwrap().data.as_slice(), &[4; 8]);
+ capture.closed = true;
+ capture.ordinary = None;
+ capture.record(CaptureKind::Ordinary, &project, frame(5));
+ assert!(capture.ordinary.is_none());
+ }
+
+ #[test]
+ fn rgba_capture_rejects_truncation_and_preserves_full_padded_rows() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut truncated = frame(1);
+ truncated.data = Arc::new(vec![1; 7]);
+ assert!(write_captured_frame(directory.path(), "truncated", truncated).is_err());
+ assert!(!directory.path().join("truncated.rgba").exists());
+ let mut padded = frame(2);
+ padded.stride = 12;
+ padded.data = Arc::new(vec![2; 12]);
+ let metadata = write_captured_frame(directory.path(), "padded", padded).unwrap();
+ assert_eq!(metadata["bytes"], 12);
+ assert_eq!(
+ std::fs::read(directory.path().join("padded.rgba")).unwrap(),
+ vec![2; 12]
+ );
+ }
+}
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index b35ff9552..62df36486 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -226,13 +226,29 @@ fn content_type_for_upload_subpath(subpath: &str) -> &'static str {
}
}
+pub fn reusable_video_id(
+ sharing: Option<&cap_project::SharingMeta>,
+ upload: Option<&cap_project::UploadMeta>,
+) -> Option<String> {
+ sharing
+ .map(|sharing| sharing.id.clone())
+ .or_else(|| match upload {
+ Some(cap_project::UploadMeta::SinglePartUpload { video_id, .. })
+ | Some(cap_project::UploadMeta::SegmentUpload { video_id, .. })
+ | Some(cap_project::UploadMeta::MultipartUpload { video_id, .. }) => {
+ Some(video_id.clone())
+ }
+ _ => None,
+ })
+}
+
#[instrument(skip(app, channel, file_path, screenshot_path))]
pub async fn upload_video(
app: &AppHandle,
video_id: String,
file_path: PathBuf,
screenshot_path: PathBuf,
- meta: S3VideoMeta,
+ replace_existing: bool,
channel: Option<Channel<UploadProgress>>,
) -> Result<UploadedItem, AuthedApiError> {
let _active_upload = ActiveUploadGuard::new(&ACTIVE_UPLOADS);
@@ -291,9 +307,15 @@ pub async fn upload_video(
.map_err(|e| error!("Failed to get video metadata: {e}"))
.ok();
- let completed_identity =
- api::upload_multipart_complete(app, &video_id, &upload_id, &parts, metadata.clone())
- .await?;
+ let completed_identity = api::upload_multipart_complete(
+ app,
+ &video_id,
+ &upload_id,
+ &parts,
+ metadata.clone(),
+ replace_existing,
+ )
+ .await?;
let object_identity = if is_drive_upload {
parts
.iter()
@@ -758,9 +780,15 @@ impl InstantMultipartUpload {
let duration = metadata.duration_in_secs;
let metadata = Some(metadata);
session.wait_ready().await?;
- let completed_identity =
- api::upload_multipart_complete(&app, &video_id, &upload_id, &parts, metadata.clone())
- .await?;
+ let completed_identity = api::upload_multipart_complete(
+ &app,
+ &video_id,
+ &upload_id,
+ &parts,
+ metadata.clone(),
+ false,
+ )
+ .await?;
let object_identity = if is_drive_upload {
parts
.iter()
@@ -1046,6 +1074,7 @@ impl PresignedUrlCache {
}
impl SegmentUploader {
+ #[cfg(not(target_os = "linux"))]
pub(crate) fn spawn(
app: AppHandle,
segment_rx: std::sync::mpsc::Receiver<
@@ -2717,6 +2746,42 @@ mod tests {
use std::io::Write;
use std::sync::atomic::{AtomicU32, Ordering};
+ #[test]
+ fn reupload_keeps_sharing_identity_after_completion_or_failure() {
+ let sharing = cap_project::SharingMeta {
+ id: "existing-video".into(),
+ link: "https://cap.link/existing-video".into(),
+ content_hash: None,
+ };
+ for upload in [
+ None,
+ Some(cap_project::UploadMeta::Complete),
+ Some(cap_project::UploadMeta::Failed {
+ error: "offline".into(),
+ }),
+ ] {
+ assert_eq!(
+ reusable_video_id(Some(&sharing), upload.as_ref()).as_deref(),
+ Some("existing-video")
+ );
+ }
+ }
+
+ #[test]
+ fn retry_keeps_the_reserved_identity_until_sharing_is_saved() {
+ let upload = cap_project::UploadMeta::SinglePartUpload {
+ video_id: "reserved-video".into(),
+ file_path: "output.mp4".into(),
+ screenshot_path: "display.jpg".into(),
+ recording_dir: "recording.cap".into(),
+ };
+ assert_eq!(
+ reusable_video_id(None, Some(&upload)).as_deref(),
+ Some("reserved-video")
+ );
+ assert_eq!(reusable_video_id(None, None), None);
+ }
+
#[test]
fn active_upload_guards_track_overlapping_sessions() {
let active = AtomicUsize::new(0);
@@ -3648,13 +3713,6 @@ pub(crate) mod strict_instant {
result
}
- async fn complete<T, F>(&self, complete: impl FnOnce() -> F) -> Result<(), AuthedApiError>
- where
- F: Future<Output = Result<T, AuthedApiError>>,
- {
- self.step(complete).await.map(drop)
- }
-
async fn permission(&self) -> Result<(), AuthedApiError> {
let mut decision = self.0.decision.subscribe();
loop {
@@ -4248,6 +4306,7 @@ pub(crate) mod strict_instant {
&upload.upload_id,
&parts,
Some(metadata),
+ false,
)
})
.await?;
@@ -4386,7 +4445,7 @@ pub(crate) mod strict_instant {
part_number: info.part_number,
offset: info.offset,
total_size: info.total_size,
- chunk: bytes.into(),
+ chunk: bytes,
})
})
.await?,
@@ -4787,24 +4846,24 @@ pub(crate) mod strict_instant {
std::fs::remove_dir_all(dir).unwrap();
}
#[tokio::test]
- async fn strict_multipart_complete_maps_optional_success_and_retains_errors_and_late_revocation()
+ async fn strict_multipart_completion_step_retains_optional_success_errors_and_late_revocation()
{
let (control, permission) = Control::new();
permission.grant().unwrap();
- let result: Result<(), AuthedApiError> = control
- .complete(|| async { Ok(Some("synthetic-location".to_string())) })
+ let result: Result<Option<String>, AuthedApiError> = control
+ .step(|| async { Ok(Some("synthetic-location".to_string())) })
.await;
- result.unwrap();
+ assert_eq!(result.unwrap().as_deref(), Some("synthetic-location"));
assert!(
control
- .complete(|| async {
+ .step(|| async {
Err::<Option<String>, _>("required completion failed".into())
})
.await
.is_err()
);
let (release, released) = tokio::sync::oneshot::channel();
- let future = control.complete(|| async {
+ let future = control.step(|| async {
released.await.unwrap();
Ok(Some("late-location".to_string()))
});
diff --git a/apps/desktop/src-tauri/src/upload/lifecycle.rs b/apps/desktop/src-tauri/src/upload/lifecycle.rs
index c4f294007..9e1f5df78 100644
--- a/apps/desktop/src-tauri/src/upload/lifecycle.rs
+++ b/apps/desktop/src-tauri/src/upload/lifecycle.rs
@@ -786,7 +786,8 @@ pub(crate) async fn resume_existing(
video_id.clone(),
file_path,
screenshot_path,
- metadata,
+ meta.sharing.is_some()
+ && matches!(meta.inner, cap_project::RecordingMetaInner::Studio(_)),
None,
)
.await?;
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index c0a166342..4753fa10e 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -2193,11 +2193,23 @@ impl ShowCapWindow {
PendingEditorInstances::start_prewarm(app, _id.label(), project_path.clone()).await;
- let window = self
+ let builder = self
.window_builder_with_id(app, "/editor", &_id, _id.label())
.maximizable(true)
- .focused(true)
- .build()?;
+ .focused(true);
+ #[cfg(debug_assertions)]
+ let builder = if crate::stop_editor_benchmark::enabled() {
+ builder.initialization_script(crate::stop_editor_benchmark::SCRIPT)
+ } else {
+ builder
+ };
+ #[cfg(debug_assertions)]
+ let builder = if crate::stop_editor_benchmark::dom_capture_requested() {
+ builder.initialization_script(crate::stop_editor_benchmark::DOM_SCRIPT)
+ } else {
+ builder
+ };
+ let window = builder.build()?;
if let Some(opening) = project_opening.as_mut() {
opening.own_window(&window);
}
diff --git a/apps/desktop/src/components/Cropper.tsx b/apps/desktop/src/components/Cropper.tsx
index 57462ee48..411eeb3df 100644
--- a/apps/desktop/src/components/Cropper.tsx
+++ b/apps/desktop/src/components/Cropper.tsx
@@ -24,6 +24,8 @@ import { Transition } from "solid-transition-group";
import { createKeyDownSignal } from "~/utils/events";
import { commands } from "~/utils/tauri";
+import { alignCrop, type CropGuides } from "./crop-alignment";
+import "./cropper.css";
export interface CropBounds {
x: number;
y: number;
@@ -247,6 +249,8 @@ export function Cropper(
snapToRatioEnabled?: boolean;
useBackdropFilter?: boolean;
allowLightMode?: boolean;
+ appearance?: "editor";
+ snapToAlignmentEnabled?: boolean;
}>,
) {
let containerRef: HTMLDivElement | undefined;
@@ -285,6 +289,11 @@ export function Cropper(
) & { hoveringHandle: HandleSide | null }
>({ drag: null, hoveringHandle: null });
+ const [alignmentGuides, setAlignmentGuides] = createSignal<CropGuides>({
+ x: null,
+ y: null,
+ });
+
const resizing = () =>
mouseState.drag === "handle" || mouseState.drag === "overlay";
const cursorStyle = () => {
@@ -666,6 +675,12 @@ export function Cropper(
newY = clamp(newY, 0, containerRect.height - currentBounds.height);
currentBounds = moveBounds(currentBounds, newX, newY);
+ const aligned =
+ props.snapToAlignmentEnabled && !e.shiftKey
+ ? alignCrop(currentBounds, containerSize())
+ : { bounds: currentBounds, guides: { x: null, y: null } };
+ currentBounds = aligned.bounds;
+ setAlignmentGuides(aligned.guides);
setRawBounds(currentBounds);
if (!isAnimating()) setDisplayRawBounds(currentBounds);
@@ -699,6 +714,7 @@ export function Cropper(
if (target.hasPointerCapture?.(pointerId)) {
target.releasePointerCapture(pointerId);
}
+ setAlignmentGuides({ x: null, y: null });
onEnd();
activePointerSessionDispose = undefined;
dispose();
@@ -799,6 +815,7 @@ export function Cropper(
e: PointerEvent,
context: ResizeSessionState,
) {
+ const previousSnappedRatio = aspectState.snapped;
const pointX = e.clientX - context.containerRect.left;
const pointY = e.clientY - context.containerRect.top;
@@ -851,9 +868,6 @@ export function Cropper(
options,
);
nextBounds = bounds;
- if (snappedRatio && !aspectState.snapped) {
- triggerHaptic();
- }
setAspectState("snapped", snappedRatio);
}
@@ -863,8 +877,39 @@ export function Cropper(
containerSize().y,
);
- setRawBounds(finalBounds);
- if (!isAnimating()) setDisplayRawBounds(finalBounds);
+ let alignedBounds = finalBounds;
+ setAlignmentGuides({ x: null, y: null });
+ if (props.snapToAlignmentEnabled && !e.shiftKey) {
+ const { movable } = context.activeHandle;
+ const start = context.startBounds;
+ const centered = context.isAltMode && ratioValue === null;
+ const aligned = alignCrop(finalBounds, containerSize(), {
+ origin: {
+ x: centered
+ ? 0.5
+ : pointX < start.x + (movable.left ? start.width : 0)
+ ? 1
+ : 0,
+ y: centered
+ ? 0.5
+ : pointY < start.y + (movable.top ? start.height : 0)
+ ? 1
+ : 0,
+ },
+ axes: {
+ x: movable.left || movable.right,
+ y: movable.top || movable.bottom,
+ },
+ ratio: ratioValue,
+ });
+ alignedBounds = aligned.bounds;
+ setAlignmentGuides(aligned.guides);
+ if (aligned.guides.x !== null || aligned.guides.y !== null)
+ setAspectState("snapped", null);
+ }
+ if (aspectState.snapped && !previousSnappedRatio) triggerHaptic();
+ setRawBounds(alignedBounds);
+ if (!isAnimating()) setDisplayRawBounds(alignedBounds);
}
function onHandleDoubleClick(handle: HandleSide, e: MouseEvent) {
@@ -1087,6 +1132,7 @@ export function Cropper(
<div
ref={containerRef}
class="relative w-full h-full select-none overscroll-contain focus:outline-hidden touch-none"
+ classList={{ "cropper-editor": props.appearance === "editor" }}
style={{
cursor: cursorStyle() ?? (props.aspectRatio ? "default" : "crosshair"),
}}
@@ -1132,11 +1178,30 @@ export function Cropper(
<div ref={occBottomRef} class="bottom-0" />
</div>
+ <For each={["x", "y"] as const}>
+ {(axis) => (
+ <Show
+ when={mouseState.drag !== null && alignmentGuides()[axis] !== null}
+ >
+ <div
+ aria-hidden="true"
+ class="cropper-alignment-guide"
+ data-axis={axis}
+ style={
+ axis === "x"
+ ? { left: `${alignmentGuides().x}px` }
+ : { top: `${alignmentGuides().y}px` }
+ }
+ />
+ </Show>
+ )}
+ </For>
+
{/* Crop region container */}
<div class="size-full">
<div
ref={regionRef}
- class="absolute top-0 left-0 z-30 size-36 border border-white/50"
+ class="cropper-region absolute top-0 left-0 z-30 size-36 border border-white/50"
style={{
cursor: cursorStyle() ?? "grab",
}}
@@ -1166,7 +1231,7 @@ export function Cropper(
exitToClass="opacity-0"
>
<Show when={mouseState.drag !== null}>
- <div class="pointer-events-none *:absolute *:border-white/40">
+ <div class="cropper-thirds pointer-events-none *:absolute *:border-white/40">
<div class="left-0 w-full border-t border-b pointer-events-none h-[calc(100%/3)] top-[calc(100%/3)]" />
<div class="top-0 h-full border-l border-r pointer-events-none w-[calc(100%/3)] left-[calc(100%/3)]" />
</div>
@@ -1178,7 +1243,7 @@ export function Cropper(
handle.isCorner ? (
<button
type="button"
- class="fixed z-50 flex h-[30px] w-[30px] focus:ring-0 outline-hidden"
+ class="cropper-corner fixed z-50 flex h-[30px] w-[30px] focus:ring-0 outline-hidden"
tabIndex={-1}
classList={{ "opacity-0": mouseState.drag === "overlay" }}
style={{
@@ -1221,7 +1286,10 @@ export function Cropper(
...(handle.y === "t"
? { top: "9px" }
: { bottom: "9px" }),
- filter: `drop-shadow(${handle.x === "l" ? "-3px" : "3px"} ${handle.y === "t" ? "-3px" : "3px"} 5px rgba(0, 0, 0, 0.3))`,
+ filter:
+ props.appearance === "editor"
+ ? undefined
+ : `drop-shadow(${handle.x === "l" ? "-3px" : "3px"} ${handle.y === "t" ? "-3px" : "3px"} 5px rgba(0, 0, 0, 0.3))`,
}}
>
<path
@@ -1240,7 +1308,8 @@ export function Cropper(
) : (
<button
type="button"
- class="absolute focus:outline-hidden focus:ring-0 outline-hidden"
+ class="cropper-edge absolute focus:outline-hidden focus:ring-0 outline-hidden"
+ data-direction={handle.direction}
tabIndex={-1}
style={{
visibility:
@@ -1251,7 +1320,8 @@ export function Cropper(
...(handle.x === "l"
? {
left: "-1px",
- width: "10px",
+ width:
+ props.appearance === "editor" ? "18px" : "10px",
top: "10px",
bottom: "10px",
transform: "translateX(-50%)",
@@ -1259,7 +1329,8 @@ export function Cropper(
: handle.x === "r"
? {
right: "-1px",
- width: "10px",
+ width:
+ props.appearance === "editor" ? "18px" : "10px",
top: "10px",
bottom: "10px",
transform: "translateX(50%)",
@@ -1267,14 +1338,16 @@ export function Cropper(
: handle.y === "t"
? {
top: "-1px",
- height: "10px",
+ height:
+ props.appearance === "editor" ? "18px" : "10px",
left: "10px",
right: "10px",
transform: "translateY(-50%)",
}
: {
bottom: "-1px",
- height: "10px",
+ height:
+ props.appearance === "editor" ? "18px" : "10px",
left: "10px",
right: "10px",
transform: "translateY(50%)",
@@ -1287,7 +1360,11 @@ export function Cropper(
onPointerDown={[onHandlePointerDown, handle]}
aria-label={`Resize ${handle.direction}`}
aria-describedby="cropper-aspect"
- />
+ >
+ <Show when={props.appearance === "editor"}>
+ <span class="cropper-edge-grip" />
+ </Show>
+ </button>
)
}
</For>
diff --git a/apps/desktop/src/components/crop-alignment.test.ts b/apps/desktop/src/components/crop-alignment.test.ts
new file mode 100644
index 000000000..190ae525c
--- /dev/null
+++ b/apps/desktop/src/components/crop-alignment.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+import { alignCrop } from "./crop-alignment";
+
+describe("crop alignment", () => {
+ it("centers a moved crop on both axes", () => {
+ const result = alignCrop(
+ { x: 253, y: 197, width: 300, height: 200 },
+ { x: 800, y: 600 },
+ );
+ expect(result.bounds).toEqual({ x: 250, y: 200, width: 300, height: 200 });
+ expect(result.guides).toEqual({ x: 400, y: 300 });
+ });
+ it("snaps a resize to the halfway line", () => {
+ const result = alignCrop(
+ { x: 80, y: 70, width: 317, height: 180 },
+ { x: 800, y: 600 },
+ { origin: { x: 0, y: 0 }, axes: { x: true, y: false }, ratio: null },
+ );
+ expect(result.bounds).toEqual({ x: 80, y: 70, width: 320, height: 180 });
+ expect(result.guides).toEqual({ x: 400, y: null });
+ });
+ it("keeps the opposite corner fixed", () => {
+ const result = alignCrop(
+ { x: 197, y: 153, width: 343, height: 237 },
+ { x: 800, y: 600 },
+ { origin: { x: 1, y: 1 }, axes: { x: true, y: true }, ratio: null },
+ );
+ expect(result.bounds).toEqual({ x: 200, y: 150, width: 340, height: 240 });
+ expect(result.guides).toEqual({ x: 200, y: 150 });
+ });
+ it("keeps alt resizing centered", () => {
+ const result = alignCrop(
+ { x: 163, y: 85, width: 234, height: 190 },
+ { x: 800, y: 600 },
+ { origin: { x: 0.5, y: 0.5 }, axes: { x: true, y: false }, ratio: null },
+ );
+ expect(result.bounds).toEqual({ x: 160, y: 85, width: 240, height: 190 });
+ expect(result.guides).toEqual({ x: 400, y: null });
+ });
+ it("preserves a locked ratio", () => {
+ const result = alignCrop(
+ { x: 80, y: 70, width: 317, height: 158.5 },
+ { x: 800, y: 600 },
+ { origin: { x: 0, y: 0 }, axes: { x: true, y: true }, ratio: 2 },
+ );
+ expect(result.bounds).toEqual({ x: 80, y: 70, width: 320, height: 160 });
+ expect(result.guides).toEqual({ x: 400, y: null });
+ });
+ it("releases beyond six display pixels", () => {
+ const result = alignCrop(
+ { x: 263, y: 217, width: 300, height: 200 },
+ { x: 800, y: 600 },
+ );
+ expect(result.bounds).toEqual({ x: 263, y: 217, width: 300, height: 200 });
+ expect(result.guides).toEqual({ x: null, y: null });
+ });
+ it("never collapses a tiny crop", () => {
+ const result = alignCrop(
+ { x: 400, y: 300, width: 3, height: 3 },
+ { x: 800, y: 600 },
+ { origin: { x: 0, y: 0 }, axes: { x: true, y: true }, ratio: null },
+ );
+ expect(result.bounds).toEqual({ x: 400, y: 300, width: 3, height: 3 });
+ expect(result.guides).toEqual({ x: null, y: null });
+ });
+ it("snaps to the image boundary", () => {
+ const result = alignCrop(
+ { x: 3, y: 91, width: 318, height: 217 },
+ { x: 800, y: 600 },
+ );
+ expect(result.bounds).toEqual({ x: 0, y: 91, width: 318, height: 217 });
+ expect(result.guides).toEqual({ x: 0, y: null });
+ });
+});
diff --git a/apps/desktop/src/components/crop-alignment.ts b/apps/desktop/src/components/crop-alignment.ts
new file mode 100644
index 000000000..aa89ade19
--- /dev/null
+++ b/apps/desktop/src/components/crop-alignment.ts
@@ -0,0 +1,76 @@
+import type { CropBounds } from "./Cropper";
+
+type Vec2 = { x: number; y: number };
+export type CropGuides = { x: number | null; y: number | null };
+export type CropResizeAlignment = {
+ origin: Vec2;
+ axes: { x: boolean; y: boolean };
+ ratio: number | null;
+};
+const TARGETS = [0.5, 0, 1, 0.25, 0.75];
+const THRESHOLD = 6;
+
+export function alignCrop(
+ bounds: CropBounds,
+ container: Vec2,
+ resize?: CropResizeAlignment,
+): { bounds: CropBounds; guides: CropGuides } {
+ let next = { ...bounds };
+ const guides: CropGuides = { x: null, y: null };
+ let bestRatioDistance = Number.POSITIVE_INFINITY;
+ for (const axis of ["x", "y"] as const) {
+ if (resize && !resize.axes[axis]) continue;
+ const size = axis === "x" ? "width" : "height";
+ const base = resize?.ratio ? bounds : next;
+ let bestDistance = THRESHOLD + 1;
+ let candidate = base;
+ let guide: number | null = null;
+ const anchors = resize ? [0, 1] : [0.5, 0, 1];
+ for (const target of TARGETS) {
+ for (const anchor of anchors) {
+ if (resize && anchor === resize.origin[axis]) continue;
+ const line = target * container[axis];
+ const delta = line - (base[axis] + base[size] * anchor);
+ const distance = Math.abs(delta);
+ if (distance > THRESHOLD || distance >= bestDistance) continue;
+ const proposed = { ...base };
+ if (resize) {
+ proposed[size] += delta / (anchor - resize.origin[axis]);
+ if (resize.ratio) {
+ if (axis === "x") proposed.height = proposed.width / resize.ratio;
+ else proposed.width = proposed.height * resize.ratio;
+ }
+ proposed.x += (base.width - proposed.width) * resize.origin.x;
+ proposed.y += (base.height - proposed.height) * resize.origin.y;
+ } else {
+ proposed[axis] += delta;
+ }
+ if (
+ proposed.width < 1 ||
+ proposed.height < 1 ||
+ proposed.x < -0.001 ||
+ proposed.y < -0.001 ||
+ proposed.x + proposed.width > container.x + 0.001 ||
+ proposed.y + proposed.height > container.y + 0.001
+ )
+ continue;
+ candidate = proposed;
+ guide = line;
+ bestDistance = distance;
+ }
+ }
+ if (resize?.ratio) {
+ if (guide !== null && bestDistance < bestRatioDistance) {
+ next = candidate;
+ guides.x = null;
+ guides.y = null;
+ guides[axis] = guide;
+ bestRatioDistance = bestDistance;
+ }
+ } else {
+ next = candidate;
+ guides[axis] = guide;
+ }
+ }
+ return { bounds: next, guides };
+}
diff --git a/apps/desktop/src/components/cropper.css b/apps/desktop/src/components/cropper.css
new file mode 100644
index 000000000..651dc512e
--- /dev/null
+++ b/apps/desktop/src/components/cropper.css
@@ -0,0 +1,62 @@
+.cropper-editor .cropper-region {
+ border-color: white;
+ box-shadow:
+ 0 0 0 1px #111827,
+ inset 0 0 0 1px #111827;
+}
+
+.cropper-editor .cropper-corner svg {
+ filter: drop-shadow(1px 0 0 #111827) drop-shadow(-1px 0 0 #111827)
+ drop-shadow(0 1px 0 #111827) drop-shadow(0 -1px 0 #111827);
+ min-width: 12px;
+ min-height: 12px;
+}
+
+.cropper-editor .cropper-edge {
+ z-index: 20;
+}
+
+.cropper-edge-grip {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ width: 26px;
+ height: 7px;
+ transform: translate(-50%, -50%);
+ border: 1px solid #111827;
+ border-radius: 3px;
+ background: white;
+ box-shadow: 0 1px 3px #0006;
+ pointer-events: none;
+}
+
+.cropper-edge[data-direction="e"] .cropper-edge-grip,
+.cropper-edge[data-direction="w"] .cropper-edge-grip {
+ width: 7px;
+ height: 26px;
+}
+
+.cropper-editor .cropper-thirds > div {
+ border-color: #111827cc;
+ filter: drop-shadow(1px 1px 0 #fff);
+}
+
+.cropper-alignment-guide {
+ position: absolute;
+ z-index: 40;
+ pointer-events: none;
+ background: #d946ef;
+ box-shadow: 0 0 0 1px #fff9;
+}
+
+.cropper-alignment-guide[data-axis="x"] {
+ top: 0;
+ width: 1px;
+ height: 100%;
+}
+
+.cropper-alignment-guide[data-axis="y"] {
+ left: 0;
+ height: 1px;
+ width: 100%;
+}
diff --git a/apps/desktop/src/routes/editor/ClipsSidebar.tsx b/apps/desktop/src/routes/editor/ClipsSidebar.tsx
index 549f926e5..734bdab33 100644
--- a/apps/desktop/src/routes/editor/ClipsSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ClipsSidebar.tsx
@@ -62,6 +62,7 @@ import {
import { type EditorTimelineSegment, useEditorContext } from "./context";
import { getExistingRecordingPickerOptions } from "./existing-recording-picker";
import { rippleKeyboardTrack } from "./keyboard-timing";
+import { routeEditorPlaybackIntent } from "./playback-intent-routing";
import { scaleKeyframeTimes } from "./three-d";
import { effectiveToOutput, holdWindows } from "./timeline-holds";
import { Input } from "./ui";
@@ -272,6 +273,7 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
editorState,
setEditorState,
setDialog,
+ requestHandoffPlayback,
} = useEditorContext();
const { rawOptions, setOptions } = useRecordingOptions();
@@ -431,23 +433,33 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
if (hiddenForPicker) void showEditorWindow(false).catch(() => {});
});
+ const pauseForProjectChange = () =>
+ routeEditorPlaybackIntent(
+ requestHandoffPlayback,
+ { playing: false },
+ async () => {
+ if (editorState.playing) {
+ await commands.stopPlayback();
+ setEditorState("playing", false);
+ }
+ },
+ );
+
const beginEditorRecording = async () => {
closeRecord();
- if (editorState.playing) {
- await commands.stopPlayback();
- setEditorState("playing", false);
- }
+ if (!(await pauseForProjectChange())) return false;
if (previousMode === null) previousMode = rawOptions.mode;
setOptions("mode", "studio");
await commands.setRecordingMode("studio");
await flushProjectConfig();
await commands.setEditorRecordingTarget(editorInstance.path);
+ return true;
};
const openTargetMode = async (mode: RecordingTargetMode) => {
setDisplayMenuOpen(false);
setWindowMenuOpen(false);
- await beginEditorRecording();
+ if (!(await beginEditorRecording())) return;
if (mode === "camera") {
setOptions(
@@ -468,7 +480,7 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
reconcile({ variant: "display", id: target.id }),
);
setDisplayMenuOpen(false);
- await beginEditorRecording();
+ if (!(await beginEditorRecording())) return;
await commands.openTargetSelectOverlays(
{ variant: "display", id: target.id },
null,
@@ -484,7 +496,7 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
reconcile({ variant: "window", id: target.id }),
);
setWindowMenuOpen(false);
- await beginEditorRecording();
+ if (!(await beginEditorRecording())) return;
await commands.openTargetSelectOverlays(
{ variant: "window", id: target.id },
null,
@@ -505,9 +517,10 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
setImporting(true);
const toastId = toast.loading("Importing clip…");
try {
- if (editorState.playing) {
- await commands.stopPlayback();
- setEditorState("playing", false);
+ if (!(await pauseForProjectChange())) {
+ toast.dismiss(toastId);
+ setImporting(false);
+ return;
}
await flushProjectConfig();
const count = await commands.addExistingRecordingToEditor(sourcePath);
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 9ae5a3c9f..721bfb843 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -56,6 +56,7 @@ import { EditorSkeleton } from "./editor-skeleton";
import { Header, type TitleSaveRegistration } from "./Header";
import { ImportProgress } from "./ImportProgress";
import { PlayerContent } from "./Player";
+import { usePreparingEditor } from "./preparing-editor-context";
import { Timeline } from "./Timeline";
import { Dialog, DialogContent, EditorButton, Input, Subfield } from "./ui";
@@ -397,6 +398,8 @@ function Inner(props: {
previewResolutionBase,
dialog,
exportState,
+ requestHandoffPlayback,
+ handoffPlaybackPending,
} = useEditorContext();
const registerEditorSave = (
@@ -430,6 +433,11 @@ function Inner(props: {
const appendRecordedClip = async (recordingPath: string) => {
const toastId = toast.loading("Adding clip…");
try {
+ const pending = requestHandoffPlayback(false);
+ if (pending && !(await pending)) {
+ toast.dismiss(toastId);
+ return;
+ }
if (editorState.playing) {
await commands.stopPlayback();
setEditorState("playing", false);
@@ -634,6 +642,7 @@ function Inner(props: {
);
createTauriEventListener(events.editorStateChanged, (payload) => {
+ if (handoffPlaybackPending()) return;
throttledRenderFrame.clear();
trailingRenderFrame.clear();
setEditorState("playbackTime", payload.playhead_position / FPS);
@@ -641,13 +650,19 @@ function Inner(props: {
let skipRenderFrameForConfigUpdate = false;
+ const preparing = usePreparingEditor();
+ const requestedFrame = (time: number) => {
+ const frameNumber = Math.max(Math.floor(time * FPS), 0);
+ return preparing?.requestOrdinaryFrame(frameNumber) ?? frameNumber;
+ };
+
const emitRenderFrame = (time: number) => {
if (skipRenderFrameForConfigUpdate) {
return;
}
if (!editorState.playing) {
events.renderFrameEvent.emit({
- frame_number: Math.max(Math.floor(time * FPS), 0),
+ frame_number: requestedFrame(time),
fps: FPS,
resolution_base: previewResolutionBase(),
});
@@ -707,7 +722,7 @@ function Inner(props: {
const doConfigUpdate = (time: number) => {
pendingPreviewConfigUpdate = {
config: getPreviewProjectConfig(project, editorState),
- frameNumber: Math.max(Math.floor(time * FPS), 0),
+ frameNumber: requestedFrame(time),
resolutionBase: previewResolutionBase(),
};
void flushPreviewConfigUpdate();
@@ -951,7 +966,7 @@ function Dialogs() {
contentClass={(() => {
const d = dialog();
if ("type" in d && d.type === "export") return "max-w-[740px]";
- if ("type" in d && d.type === "crop") return "max-w-[1180px]";
+ if ("type" in d && d.type === "crop") return "max-w-[1440px]";
return "";
})()}
open={isDialogType()}
@@ -1121,8 +1136,6 @@ function Dialogs() {
let cropperRef: CropperRef | undefined;
let previewCanvas: HTMLCanvasElement | undefined;
const [crop, setCrop] = createSignal(CROP_ZERO);
- const [cropInteracting, setCropInteracting] =
- createSignal(false);
const [aspect, setAspect] = createSignal<Ratio | null>(null);
const [frameUrl, setFrameUrl] = createSignal<string | null>(
@@ -1172,8 +1185,8 @@ function Dialogs() {
const boxSize = createMemo(() => {
const { w: vw, h: vh } = viewport();
const ratio = display.width / display.height;
- const maxW = Math.min(vw * 0.4, 520);
- const maxH = Math.min(vh * 0.5, 520);
+ const maxW = Math.max(120, Math.min(vw - 164, 1280)) * 0.68;
+ const maxH = Math.max(100, Math.min(vh - 280, 760));
let w = maxW;
let h = w / ratio;
if (h > maxH) {
@@ -1469,20 +1482,19 @@ function Dialogs() {
Crop area
</span>
<div
- class="overflow-hidden relative rounded-xl border shadow-sm border-gray-3 bg-gray-3"
+ class="relative rounded-xl border p-4 shadow-sm border-gray-5 bg-gray-3"
style={{
- width: `${boxSize().w}px`,
- height: `${boxSize().h}px`,
+ width: `${boxSize().w + 32}px`,
+ height: `${boxSize().h + 32}px`,
}}
>
<div
- class="w-full h-full transition-opacity duration-200"
+ class="relative w-full h-full transition-opacity duration-200"
classList={{ "opacity-0": !frameLoaded() }}
>
<Cropper
ref={cropperRef}
onCropChange={setCrop}
- onInteraction={setCropInteracting}
aspectRatio={aspect() ?? undefined}
targetSize={{
x: display.width,
@@ -1492,6 +1504,8 @@ function Dialogs() {
snapToRatioEnabled={snapToRatio()}
useBackdropFilter={true}
allowLightMode={true}
+ appearance="editor"
+ snapToAlignmentEnabled={true}
onContextMenu={(e) =>
showCropOptionsMenu(e, true)
}
@@ -1514,29 +1528,6 @@ function Dialogs() {
}
/>
</Cropper>
- <Show
- when={
- cropInteracting() &&
- crop().width > 0 &&
- crop().height > 0
- }
- >
- <div
- aria-hidden="true"
- class="absolute z-40 border pointer-events-none border-black/90 shadow-[0_0_0_1px_rgba(255,255,255,0.9)]"
- style={{
- left: `${(crop().x / display.width) * 100}%`,
- top: `${(crop().y / display.height) * 100}%`,
- width: `${(crop().width / display.width) * 100}%`,
- height: `${(crop().height / display.height) * 100}%`,
- }}
- >
- <div class="absolute left-0 top-[calc(100%/3)] w-full h-px bg-black/90 shadow-[0_1px_0_rgba(255,255,255,0.9)]" />
- <div class="absolute left-0 top-[calc(200%/3)] w-full h-px bg-black/90 shadow-[0_1px_0_rgba(255,255,255,0.9)]" />
- <div class="absolute top-0 left-[calc(100%/3)] w-px h-full bg-black/90 shadow-[1px_0_0_rgba(255,255,255,0.9)]" />
- <div class="absolute top-0 left-[calc(200%/3)] w-px h-full bg-black/90 shadow-[1px_0_0_rgba(255,255,255,0.9)]" />
- </div>
- </Show>
</div>
<Show when={!frameLoaded()}>
<div class="flex absolute inset-0 z-40 flex-col gap-3 justify-center items-center bg-gray-3">
@@ -1574,8 +1565,8 @@ function Dialogs() {
<div
class="flex overflow-hidden relative justify-center items-center rounded-xl border shadow-sm border-gray-3 bg-gray-3"
style={{
- width: `${boxSize().w}px`,
- height: `${boxSize().h}px`,
+ width: `${Math.round(boxSize().w * 0.44)}px`,
+ height: `${boxSize().h + 32}px`,
}}
>
<canvas
@@ -1593,6 +1584,26 @@ function Dialogs() {
</div>
</div>
</div>
+ <div class="flex items-center justify-between gap-3 pt-4 text-xs text-gray-11">
+ <span>
+ Drag to move · Snap to center, halves and quarters ·
+ Hold Shift to skip snapping
+ </span>
+ <EditorButton
+ onClick={() => {
+ const bounds = crop();
+ cropperRef?.animateTo({
+ ...bounds,
+ x: Math.round((display.width - bounds.width) / 2),
+ y: Math.round(
+ (display.height - bounds.height) / 2,
+ ),
+ });
+ }}
+ >
+ Center crop
+ </EditorButton>
+ </div>
</Dialog.Content>
<Dialog.Footer>
<Show when={!cropTargetValid()}>
diff --git a/apps/desktop/src/routes/editor/ExportPage.tsx b/apps/desktop/src/routes/editor/ExportPage.tsx
index b68ff35bf..5ee82e2bf 100644
--- a/apps/desktop/src/routes/editor/ExportPage.tsx
+++ b/apps/desktop/src/routes/editor/ExportPage.tsx
@@ -161,6 +161,7 @@ function buildExportSettings(
export function ExportPage() {
const {
+ dialog,
setDialog,
editorInstance,
editorState,
@@ -173,6 +174,7 @@ export function ExportPage() {
} = useEditorContext();
const projectPath = editorInstance.path;
+ const [reuploading, setReuploading] = createSignal(false);
const auth = authStore.createQuery();
const organizationSelection = createSelectedOrganization();
@@ -207,6 +209,14 @@ export function ExportPage() {
}),
{ name: "export_settings" },
);
+ const initialDialog = dialog();
+ if (
+ "type" in initialDialog &&
+ initialDialog.type === "export" &&
+ initialDialog.destination
+ ) {
+ setSettings("exportTo", initialDialog.destination);
+ }
const VALID_COMPRESSIONS: ExportCompression[] = [
"Maximum",
@@ -731,6 +741,8 @@ export function ExportPage() {
const releaseExportSession = await beginExportSessionGuard();
try {
setExportState(reconcile({ action: "upload", type: "starting" }));
+ await refetchMeta();
+ setReuploading(!!meta().sharing);
const existingAuth = await authStore.get();
if (!existingAuth) createSignInMutation();
@@ -782,7 +794,7 @@ export function ExportPage() {
projectPath,
"Reupload",
uploadChannel,
- settings.organizationId ?? null,
+ null,
)
: await commands.uploadExportedVideo(
projectPath,
@@ -1038,7 +1050,11 @@ export function ExportPage() {
isSelected() ? "text-gray-12" : "text-gray-10",
)}
/>
- <span class="text-xs font-medium">{option.label}</span>
+ <span class="text-xs font-medium">
+ {option.value === "link" && meta().sharing
+ ? "Reupload"
+ : option.label}
+ </span>
</button>
);
@@ -1051,10 +1067,34 @@ export function ExportPage() {
</For>
</div>
+ <Show when={settings.exportTo === "link" && meta().sharing}>
+ {(sharing) => (
+ <div class="mt-3 p-3 rounded-lg bg-blue-3 border border-blue-5 space-y-1.5">
+ <p class="text-sm font-medium text-gray-12">
+ Update your existing link
+ </p>
+ <p class="text-xs text-gray-11">
+ Reupload replaces the video at this link with your latest
+ edit. Everyone with the link will see the updated version.
+ </p>
+ <a
+ class="block text-xs text-blue-11 truncate"
+ href={sharing().link}
+ target="_blank"
+ rel="noreferrer"
+ >
+ {sharing().link}
+ </a>
+ </div>
+ )}
+ </Show>
+
<Suspense>
<Show
when={
- settings.exportTo === "link" && organisations().length > 1
+ settings.exportTo === "link" &&
+ !meta().sharing &&
+ organisations().length > 1
}
>
<button
@@ -1499,7 +1539,9 @@ export function ExportPage() {
{settings.exportTo === "link" && (
<>
<IconCapLink class="size-5" />
- Export to Link
+ {meta().sharing
+ ? "Reupload to same link"
+ : "Create shareable link"}
</>
)}
</Button>
@@ -1659,7 +1701,11 @@ export function ExportPage() {
>
{(uploading) => (
<ActiveExport
- heading="Uploading"
+ heading={
+ reuploading()
+ ? "Reuploading to your link"
+ : "Uploading"
+ }
percent={uploading.progress}
/>
)}
@@ -1686,8 +1732,16 @@ export function ExportPage() {
</Match>
<Match when={uploadState.type === "done"}>
<CompletedExport
- title="Upload complete"
- subtitle="Your Cap has been uploaded successfully"
+ title={
+ reuploading()
+ ? "Reupload complete"
+ : "Upload complete"
+ }
+ subtitle={
+ reuploading()
+ ? "Your latest edit is ready at the same link"
+ : "Your Cap has been uploaded successfully"
+ }
/>
</Match>
</Switch>
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index 94b519d12..2a4efd9d1 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -60,7 +60,6 @@ export function Header(props: { registerTitleSave: RegisterTitleSave }) {
meta,
exportState,
setExportState,
- customDomain,
editorState,
setEditorState,
} = useEditorContext();
@@ -219,9 +218,7 @@ export function Header(props: { registerTitleSave: RegisterTitleSave }) {
</span>
</EditorButton>
</Show>
- <Show when={customDomain.data}>
- <ShareButton />
- </Show>
+ <ShareButton />
<button
type="button"
class={cx(
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 931184654..92e396c57 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -29,6 +29,12 @@ import { FrameButton } from "./FrameButton";
import { ImageOverlay } from "./image-overlay";
import { MaskOverlay } from "./MaskOverlay";
import { PerformanceOverlay } from "./PerformanceOverlay";
+import { usePreparingEditor } from "./preparing-editor-context";
+import { PreparingFrame } from "./preparing-frame";
+import {
+ createPreviewBoundsReaction,
+ createPreviewBoundsUpdater,
+} from "./preview-bounds";
import { SplitScreenOverlay } from "./SplitScreenOverlay";
import { TextOverlay } from "./TextOverlay";
import { EditorButton, Slider } from "./ui";
@@ -53,6 +59,9 @@ export function PlayerContent(props: { compactness?: number }) {
previewResolutionBase,
previewQuality,
setPreviewQuality,
+ playbackIntent,
+ requestHandoffPlayback,
+ handoffPlaybackPending,
} = useEditorContext();
const previewOptions = [
@@ -182,6 +191,11 @@ export function PlayerContent(props: { compactness?: number }) {
}),
},
});
+ const pending = requestHandoffPlayback(false);
+ if (pending) {
+ await pending;
+ return;
+ }
await commands.stopPlayback();
setEditorState("playing", false);
};
@@ -189,7 +203,7 @@ export function PlayerContent(props: { compactness?: number }) {
const handlePreviewQualityChange = async (quality: EditorPreviewQuality) => {
if (quality === previewQuality()) return;
- const wasPlaying = editorState.playing;
+ const wasPlaying = playbackIntent();
const currentFrame = Math.max(
Math.floor(editorState.playbackTime * FPS),
0,
@@ -198,6 +212,11 @@ export function PlayerContent(props: { compactness?: number }) {
setPreviewQuality(quality);
if (!wasPlaying) return;
+ const pending = requestHandoffPlayback(true);
+ if (pending) {
+ await pending;
+ return;
+ }
try {
await commands.stopPlayback();
@@ -212,13 +231,23 @@ export function PlayerContent(props: { compactness?: number }) {
};
createEffect(() => {
- if (isAtEnd() && editorState.playing) {
+ if (isAtEnd() && playbackIntent()) {
+ const pending = requestHandoffPlayback(false);
+ if (pending) return;
commands.stopPlayback();
setEditorState("playing", false);
}
});
const handlePlayPauseClick = async () => {
+ const pending = requestHandoffPlayback(
+ isAtEnd() || !playbackIntent(),
+ isAtEnd() ? 0 : undefined,
+ );
+ if (pending) {
+ await pending;
+ return;
+ }
try {
if (isAtEnd()) {
await commands.stopPlayback();
@@ -283,10 +312,11 @@ export function PlayerContent(props: { compactness?: number }) {
handler: async () => {
const prevTime = editorState.previewTime;
- if (!editorState.playing) {
+ if (!playbackIntent()) {
if (prevTime !== null) setEditorState("playbackTime", prevTime);
- await commands.seekTo(Math.floor(editorState.playbackTime * FPS));
+ if (!handoffPlaybackPending())
+ await commands.seekTo(Math.floor(editorState.playbackTime * FPS));
}
await handlePlayPauseClick();
@@ -367,6 +397,12 @@ export function PlayerContent(props: { compactness?: number }) {
type="button"
class="text-ed-text-2 transition-opacity hover:opacity-70 will-change-[opacity]"
onClick={async () => {
+ const pending = requestHandoffPlayback(false, 0);
+ if (pending) {
+ editorState.timeline.transform.setPosition(0);
+ await pending;
+ return;
+ }
await commands.stopPlayback();
setEditorState("playing", false);
setEditorState("playbackTime", 0);
@@ -381,7 +417,7 @@ export function PlayerContent(props: { compactness?: number }) {
onClick={handlePlayPauseClick}
class="flex justify-center items-center rounded-full transition-opacity size-8 bg-ed-text-1 text-ed-card hover:opacity-90"
>
- {!editorState.playing || isAtEnd() ? (
+ {!playbackIntent() || isAtEnd() ? (
<IconCapPlay class="size-3" />
) : (
<IconCapPause class="size-3" />
@@ -392,6 +428,11 @@ export function PlayerContent(props: { compactness?: number }) {
type="button"
class="text-ed-text-2 transition-opacity hover:opacity-70 will-change-[opacity]"
onClick={async () => {
+ const pending = requestHandoffPlayback(false, totalDuration());
+ if (pending) {
+ await pending;
+ return;
+ }
await commands.stopPlayback();
setEditorState("playing", false);
setEditorState("playbackTime", totalDuration());
@@ -483,10 +524,27 @@ const gridStyle = {
};
function PreviewCanvas() {
- const { latestFrame, canvasControls, performanceMode, setPerformanceMode } =
- useEditorContext();
+ const preparing = usePreparingEditor();
+ const {
+ latestFrame,
+ canvasControls,
+ performanceMode,
+ setPerformanceMode,
+ editorState,
+ } = useEditorContext();
const hasRenderedFrame = () => canvasControls()?.hasRenderedFrame() ?? false;
+ createEffect(
+ on(
+ () => editorState.playing,
+ (playing) => {
+ preparing?.setOrdinaryAdvancing(
+ playing,
+ Math.max(Math.floor(editorState.playbackTime * FPS), 0),
+ );
+ },
+ ),
+ );
const handleContextMenu = async (e: MouseEvent) => {
e.preventDefault();
@@ -502,7 +560,7 @@ function PreviewCanvas() {
menu.popup();
};
- const canvasInitializedRef = { current: false };
+ let initializedCanvas: HTMLCanvasElement | undefined;
const [canvasRef, setCanvasRef] = createSignal<HTMLCanvasElement | null>(
null,
);
@@ -521,24 +579,34 @@ function PreviewCanvas() {
100,
);
- // Only react to real container-size changes. Reading debouncedBounds()
+ const boundsUpdater = createPreviewBoundsUpdater({
+ current: () => untrack(debouncedBounds),
+ measure: () => {
+ const container = canvasContainerRef();
+ if (!container?.isConnected) return;
+ const { width, height } = container.getBoundingClientRect();
+ return { width, height, connected: container.isConnected };
+ },
+ commit: setDebouncedBounds,
+ defer: ({ width, height }) => updateDebouncedBounds(width, height),
+ cancel: updateDebouncedBounds.clear,
+ requestFrame: (callback) => requestAnimationFrame(callback),
+ cancelFrame: (id) => cancelAnimationFrame(id),
+ });
+
+ // Only track container-size and frame-availability changes. Reading debouncedBounds()
// reactively here would resubscribe the effect to its own debounced write:
// the trailing setter rewrites debouncedBounds with a fresh object every
// 100ms, which would re-run this effect and re-arm the timer forever,
// spinning the whole preview graph at ~10Hz while the editor sits idle.
- createEffect(
- on(
- () => [containerBounds.width ?? 0, containerBounds.height ?? 0] as const,
- ([width, height]) => {
- const current = untrack(debouncedBounds);
- if (current.width === 0 && current.height === 0) {
- setDebouncedBounds({ width, height });
- } else {
- updateDebouncedBounds(width, height);
- }
- },
- ),
- );
+ const hasFrame = createPreviewBoundsReaction({
+ bounds: () => ({
+ width: containerBounds.width ?? 0,
+ height: containerBounds.height ?? 0,
+ }),
+ hasFrame: () => !!latestFrame(),
+ updater: boundsUpdater,
+ });
createEffect(() => {
const canvas = canvasRef();
@@ -546,16 +614,16 @@ function PreviewCanvas() {
console.warn("[Player] Canvas init effect", {
hasCanvas: !!canvas,
hasControls: !!controls,
- alreadyInit: canvasInitializedRef.current,
+ alreadyInit: initializedCanvas === canvas,
});
- if (canvasInitializedRef.current || !canvas || !controls) return;
+ if (!canvas || !controls || initializedCanvas === canvas) return;
console.warn("[Player] Initializing canvas", {
canvasId: canvas.id,
isConnected: canvas.isConnected,
});
controls.initDirectCanvas(canvas);
- canvasInitializedRef.current = true;
+ initializedCanvas = canvas;
console.warn("[Player] Canvas initialized successfully");
});
@@ -596,7 +664,12 @@ function PreviewCanvas() {
return { width, height };
};
- const hasFrame = () => !!latestFrame();
+ createEffect(() => {
+ const frame = latestFrame();
+ if (frame && hasRenderedFrame()) {
+ preparing?.acknowledgeOrdinaryFrame(frame, size());
+ }
+ });
return (
<div
@@ -606,6 +679,11 @@ function PreviewCanvas() {
onContextMenu={handleContextMenu}
>
<CaptionsRegenerateBadge class="absolute top-3 right-3 z-20" />
+ <Show when={preparing?.model.rendered() && !preparing?.ordinaryReady()}>
+ <div class="absolute inset-0 flex items-center justify-center p-4 z-10 pointer-events-none">
+ <PreparingFrame fallback={false} />
+ </div>
+ </Show>
<div
class="flex overflow-hidden absolute inset-0 justify-center items-center h-full"
style={{ visibility: hasFrame() ? "visible" : "hidden" }}
@@ -618,18 +696,22 @@ function PreviewCanvas() {
contain: "strict",
}}
>
- <canvas
- class="rounded-md shadow-[0_12px_32px_-8px_rgba(0,0,0,0.35),0_0_0_0.5px_rgba(0,0,0,0.12)]"
- style={{
- width: `${size().width}px`,
- height: `${size().height}px`,
- "image-rendering": "auto",
- "background-color": "#000000",
- ...(hasRenderedFrame() ? gridStyle : {}),
- }}
- ref={setCanvasRef}
- id="canvas"
- />
+ <Show when={canvasControls()} keyed>
+ {(_controls) => (
+ <canvas
+ class="rounded-md shadow-[0_12px_32px_-8px_rgba(0,0,0,0.35),0_0_0_0.5px_rgba(0,0,0,0.12)]"
+ style={{
+ width: `${size().width}px`,
+ height: `${size().height}px`,
+ "image-rendering": "auto",
+ "background-color": "#000000",
+ ...(hasRenderedFrame() ? gridStyle : {}),
+ }}
+ ref={setCanvasRef}
+ id="canvas"
+ />
+ )}
+ </Show>
<Show when={hasFrame()}>
<CanvasElementsOverlay size={size()} />
<div class="absolute inset-0 isolate pointer-events-none">
diff --git a/apps/desktop/src/routes/editor/ShareButton.tsx b/apps/desktop/src/routes/editor/ShareButton.tsx
index 8a1207c0c..2e1424d72 100644
--- a/apps/desktop/src/routes/editor/ShareButton.tsx
+++ b/apps/desktop/src/routes/editor/ShareButton.tsx
@@ -1,19 +1,9 @@
import { Select as KSelect } from "@kobalte/core/select";
-import { createMutation } from "@tanstack/solid-query";
-import { Channel } from "@tauri-apps/api/core";
-import { createSignal, onCleanup, Show } from "solid-js";
-import { createStore, produce, reconcile } from "solid-js/store";
+import { createSignal, Show } from "solid-js";
import Tooltip from "~/components/Tooltip";
-import { createProgressBar } from "~/routes/editor/utils";
-import { authStore } from "~/store";
-import { exportVideo } from "~/utils/export";
-import { commands, type UploadProgress } from "~/utils/tauri";
import IconLucideExternalLink from "~icons/lucide/external-link";
import { useEditorContext } from "./context";
-import { RESOLUTION_OPTIONS } from "./Header";
import {
- Dialog,
- DialogContent,
EditorButton,
MenuItem,
MenuItemList,
@@ -23,156 +13,18 @@ import {
function ShareButton() {
const {
- editorInstance,
meta,
+ project,
customDomain,
- editorState,
setEditorState,
- flushProjectConfig,
+ setDialog,
+ exportState,
+ setExportState,
} = useEditorContext();
- const projectPath = editorInstance.path;
- let disposed = false;
- onCleanup(() => {
- disposed = true;
- });
-
- const upload = createMutation(() => ({
- mutationFn: async () => {
- setUploadState({ type: "idle" });
-
- if (!navigator.onLine) {
- await commands.globalMessageDialog(
- "You appear to be offline. Please check your internet connection and try again.",
- );
- return;
- }
-
- console.log("Starting upload process...");
-
- // Check authentication first
- const existingAuth = await authStore.get();
- if (!existingAuth) {
- throw new Error("You need to sign in to share recordings");
- }
-
- const metadata = await commands.getVideoMetadata(projectPath);
- const plan = await commands.checkUpgradedAndUpdate();
- const canShare = {
- allowed: plan || metadata.duration < 300,
- reason: !plan && metadata.duration >= 300 ? "upgrade_required" : null,
- };
-
- if (!canShare.allowed) {
- if (canShare.reason === "upgrade_required") {
- await commands.showWindow("Upgrade");
- throw new Error(
- "Upgrade required to share recordings longer than 5 minutes",
- );
- }
- }
-
- await flushProjectConfig();
- if (disposed) return;
-
- const uploadChannel = new Channel<UploadProgress>((progress) => {
- console.log("Upload progress:", progress);
- setUploadState(
- produce((state) => {
- if (state.type !== "uploading") return;
-
- state.progress = Math.round(progress.progress * 100);
- }),
- );
- });
-
- setUploadState({ type: "starting" });
-
- // Setup progress listener before starting upload
-
- console.log("Starting actual upload...");
-
- await exportVideo(
- projectPath,
- {
- format: "Mp4",
- fps: 30,
- resolution_base: {
- x: RESOLUTION_OPTIONS._1080p.width,
- y: RESOLUTION_OPTIONS._1080p.height,
- },
- compression: "Web",
- custom_bpp: null,
- },
- (msg) => {
- setUploadState(
- reconcile({
- type: "rendering",
- renderedFrames: msg.renderedCount,
- totalFrames: msg.totalFrames,
- }),
- );
- },
- );
-
- setUploadState({ type: "uploading", progress: 0 });
-
- // Now proceed with upload
- const result = meta().sharing
- ? await commands.uploadExportedVideo(
- projectPath,
- "Reupload",
- uploadChannel,
- null,
- )
- : await commands.uploadExportedVideo(
- projectPath,
- {
- Initial: { pre_created_video: null },
- },
- uploadChannel,
- null,
- );
-
- if (result === "NotAuthenticated") {
- throw new Error("You need to sign in to share recordings");
- } else if (result === "PlanCheckFailed")
- throw new Error("Failed to verify your subscription status");
- else if (result === "UpgradeRequired")
- throw new Error("This feature requires an upgraded plan");
-
- setUploadState({ type: "link-copied" });
-
- return result;
- },
- onError: (error) => {
- if (disposed) return;
- console.error(error);
- commands.globalMessageDialog(
- error instanceof Error ? error.message : "Failed to upload recording",
- );
- },
- onSettled() {
- setTimeout(() => {
- setUploadState({ type: "idle" });
- upload.reset();
- }, 2000);
- },
- }));
-
- const [uploadState, setUploadState] = createStore<
- | { type: "idle" }
- | { type: "starting" }
- | { type: "rendering"; renderedFrames: number; totalFrames: number }
- | { type: "uploading"; progress: number }
- | { type: "link-copied" }
- >({ type: "idle" });
-
- createProgressBar(() => {
- if (uploadState.type === "starting") return 0;
- if (uploadState.type === "rendering")
- return (uploadState.renderedFrames / uploadState.totalFrames) * 100;
- if (uploadState.type === "uploading") return uploadState.progress;
- });
+ const hasTransparentBackground = () => {
+ const source = project.background.source;
+ return source.type === "color" && (source.alpha ?? 255) < 255;
+ };
return (
<div class="relative">
@@ -180,31 +32,25 @@ function ShareButton() {
{(sharing) => {
const normalUrl = () => new URL(sharing().link);
const customUrl = () =>
- customDomain.data?.custom_domain
- ? new URL(
- `${customDomain.data?.custom_domain}/s/${meta().sharing?.id}`,
- )
+ customDomain.data?.custom_domain &&
+ customDomain.data?.domain_verified
+ ? new URL(`${customDomain.data.custom_domain}/s/${sharing().id}`)
: null;
-
- const normalLink = `${normalUrl().host}${normalUrl().pathname}`;
- const customLink = `${customUrl()?.host}${customUrl()?.pathname}`;
-
- const copyLinks = {
- normal: sharing().link,
- custom: customUrl()?.href,
+ const [preferCustom, setPreferCustom] = createSignal(true);
+ const selectedUrl = () =>
+ (preferCustom() && customUrl()) || normalUrl();
+ const normalLink = () => `${normalUrl().host}${normalUrl().pathname}`;
+ const customLink = () => {
+ const url = customUrl();
+ return url ? `${url.host}${url.pathname}` : normalLink();
};
-
- const [linkToDisplay, setLinkToDisplay] = createSignal<string | null>(
- customDomain.data?.custom_domain &&
- customDomain.data?.domain_verified
- ? customLink
- : normalLink,
- );
+ const linkToDisplay = () =>
+ `${selectedUrl().host}${selectedUrl().pathname}`;
const [copyPressed, setCopyPressed] = createSignal(false);
const copyLink = () => {
- navigator.clipboard.writeText(linkToDisplay() || sharing().link);
+ navigator.clipboard.writeText(selectedUrl().href);
setCopyPressed(true);
setTimeout(() => {
setCopyPressed(false);
@@ -214,33 +60,31 @@ function ShareButton() {
return (
<div class="flex gap-1 items-center">
<EditorButton
- disabled={upload.isPending}
+ class="h-[30px] px-3 text-ed-accent bg-ed-accent/10 border border-ed-accent/25 hover:bg-ed-accent/20"
+ disabled={hasTransparentBackground()}
tooltipText={
- upload.isPending ? "Reuploading video" : "Reupload video"
+ hasTransparentBackground()
+ ? "Share links require a background without transparency"
+ : "Upload your latest edit to the same link"
}
onClick={() => {
- if (editorState.timeline.selection) {
- setEditorState("timeline", "selection", null);
- return;
- }
- upload.mutate();
+ setEditorState("timeline", "selection", null);
+ if (exportState.type === "done")
+ setExportState({ type: "idle" });
+ setDialog({
+ type: "export",
+ open: true,
+ destination: "link",
+ });
}}
- leftIcon={
- upload.isPending ? (
- <IconLucideLoaderCircle class="animate-spin" />
- ) : (
- <IconLucideRotateCcw />
- )
- }
- />
+ leftIcon={<IconCapUpload />}
+ >
+ Reupload
+ </EditorButton>
<Tooltip content="Open link">
<div class="flex flex-row gap-1.5 items-center px-2.5 h-7 rounded-[7px] transition-colors duration-100 bg-ed-ctl hover:bg-ed-ctl-hover">
<a
- href={
- linkToDisplay() === customLink
- ? copyLinks.custom
- : copyLinks.normal
- }
+ href={selectedUrl().href}
target="_blank"
rel="noreferrer"
title={linkToDisplay() ?? "Open link"}
@@ -252,7 +96,6 @@ function ShareButton() {
</span>
<IconLucideExternalLink class="hidden size-4 text-ed-text-2 max-[1400px]:block" />
</a>
- {/** Dropdown */}
<Show
when={
customDomain.data?.custom_domain &&
@@ -262,8 +105,10 @@ function ShareButton() {
<Tooltip content="Select link">
<KSelect
value={linkToDisplay()}
- onChange={(value) => value && setLinkToDisplay(value)}
- options={[customLink, normalLink].filter(
+ onChange={(value) =>
+ value && setPreferCustom(value === customLink())
+ }
+ options={[customLink(), normalLink()].filter(
(link) => link !== linkToDisplay(),
)}
multiple={false}
@@ -299,7 +144,6 @@ function ShareButton() {
</KSelect>
</Tooltip>
</Show>
- {/** Copy button */}
<Tooltip content="Copy link">
<div
class="flex justify-center items-center transition-colors duration-200 rounded-md size-5 text-ed-text-2 bg-ed-ctl-hover hover:bg-ed-ctl-active"
@@ -318,48 +162,6 @@ function ShareButton() {
);
}}
</Show>
- <Dialog.Root open={!upload.isIdle}>
- <DialogContent
- title={"Reupload Recording"}
- confirm={null}
- close={null}
- class="text-gray-12 dark:text-gray-12"
- >
- <div class="w-[80%] text-center mx-auto relative z-10 space-y-6 py-4">
- <div class="w-full bg-gray-3 rounded-full h-2.5 mb-2">
- <div
- class="bg-blue-9 h-2.5 rounded-full"
- style={{
- width: `${
- uploadState.type === "uploading"
- ? uploadState.progress
- : uploadState.type === "link-copied"
- ? 100
- : uploadState.type === "rendering"
- ? Math.min(
- (uploadState.renderedFrames /
- uploadState.totalFrames) *
- 100,
- 100,
- )
- : 0
- }%`,
- }}
- />
- </div>
-
- <p class="relative z-10 mt-3 text-xs text-white">
- {uploadState.type === "idle" || uploadState.type === "starting"
- ? "Preparing to render..."
- : uploadState.type === "rendering"
- ? `Rendering video (${uploadState.renderedFrames}/${uploadState.totalFrames} frames)`
- : uploadState.type === "uploading"
- ? `Uploading - ${Math.floor(uploadState.progress)}%`
- : "Link copied to clipboard!"}
- </p>
- </div>
- </DialogContent>
- </Dialog.Root>
</div>
);
}
diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx
index 37ddb8ad2..93ba285b6 100644
--- a/apps/desktop/src/routes/editor/Timeline/index.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx
@@ -205,6 +205,8 @@ export function Timeline(props: {
meta,
previewResolutionBase,
canvasControls,
+ playbackIntent,
+ requestHandoffPlayback,
} = useEditorContext();
const duration = () => editorInstance.recordingDuration;
@@ -1016,6 +1018,11 @@ export function Timeline(props: {
}
async function seekPlayheadTo(newTime: number) {
+ const pending = requestHandoffPlayback(playbackIntent(), newTime);
+ if (pending) {
+ await pending;
+ return;
+ }
// If playing, some backends require restart to seek reliably
if (editorState.playing) {
try {
@@ -1322,7 +1329,7 @@ export function Timeline(props: {
}}
onMouseMove={(e) => {
const metrics = getTimelineContentMetrics();
- if (editorState.playing) return;
+ if (playbackIntent()) return;
if (!metrics || metrics.width <= 0) return;
const offsetX = e.clientX - metrics.left;
if (offsetX < 0 || offsetX > metrics.width) {
@@ -1393,7 +1400,7 @@ export function Timeline(props: {
</div>
<Show
when={
- !editorState.playing &&
+ !playbackIntent() &&
editorState.previewTime !== null &&
editorState.timeline.splitPreview === null
? { time: editorState.previewTime }
diff --git a/apps/desktop/src/routes/editor/Timeline/playback-follow.test.ts b/apps/desktop/src/routes/editor/Timeline/playback-follow.test.ts
index 1b3fa282c..da4170ea0 100644
--- a/apps/desktop/src/routes/editor/Timeline/playback-follow.test.ts
+++ b/apps/desktop/src/routes/editor/Timeline/playback-follow.test.ts
@@ -2,6 +2,50 @@ import { describe, expect, it } from "vitest";
import { PlaybackFollow } from "./playback-follow";
describe("timeline playback following", () => {
+ it("starts from a visible playhead without jumping, then follows at playback speed", () => {
+ for (const start of [28.1, 29, 30]) {
+ const follow = new PlaybackFollow();
+ const viewport = { position: 20, zoom: 10 };
+ for (let frame = 0; frame <= 120; frame++) {
+ const elapsed = frame / 60;
+ viewport.position = follow.update(
+ viewport,
+ start + elapsed,
+ 60,
+ elapsed * 1000,
+ false,
+ );
+ expect(viewport.position).toBeCloseTo(20 + elapsed);
+ }
+ }
+ });
+
+ it("preserves a visible playhead after pausing and seeking", () => {
+ const follow = new PlaybackFollow();
+ follow.update({ position: 0, zoom: 10 }, 8, 60, 0, false);
+ follow.reset();
+ const viewport = { position: 20, zoom: 10 };
+ expect(follow.update(viewport, 29, 60, 100, false)).toBe(20);
+ expect(follow.update(viewport, 29.1, 60, 200, false)).toBeCloseTo(20.1);
+ });
+
+ it("preserves manual trailing space when playback is already visible", () => {
+ const follow = new PlaybackFollow();
+ const viewport = { position: 54, zoom: 10 };
+ for (const time of [55, 58, 60]) {
+ expect(follow.update(viewport, time, 60, time * 1000, false)).toBe(54);
+ }
+ });
+
+ it("resumes after manual panning without pulling a visible playhead backward", () => {
+ const follow = new PlaybackFollow();
+ follow.update({ position: 0, zoom: 10 }, 8, 60, 0, false);
+ const viewport = { position: 1, zoom: 10 };
+ expect(follow.update(viewport, 9, 60, 100, false)).toBe(1);
+ expect(follow.update(viewport, 10, 60, 1100, false)).toBe(1);
+ expect(follow.update(viewport, 10.1, 60, 1200, false)).toBeCloseTo(1.1);
+ });
+
it("leaves the viewport still until the playhead reaches the follow point", () => {
const follow = new PlaybackFollow();
const viewport = { position: 0, zoom: 10 };
diff --git a/apps/desktop/src/routes/editor/Timeline/playback-follow.ts b/apps/desktop/src/routes/editor/Timeline/playback-follow.ts
index 96e0e5a07..a01566741 100644
--- a/apps/desktop/src/routes/editor/Timeline/playback-follow.ts
+++ b/apps/desktop/src/routes/editor/Timeline/playback-follow.ts
@@ -6,10 +6,12 @@ type Viewport = {
export class PlaybackFollow {
private previous: Viewport | undefined;
private resumeAt = 0;
+ private followOffset: number | undefined;
reset() {
this.previous = undefined;
this.resumeAt = 0;
+ this.followOffset = undefined;
}
update(
@@ -26,6 +28,7 @@ export class PlaybackFollow {
(this.previous.position !== position || this.previous.zoom !== zoom))
) {
this.resumeAt = now + 1000;
+ this.followOffset = undefined;
}
let next = position;
if (
@@ -37,12 +40,19 @@ export class PlaybackFollow {
zoom > 0 &&
duration > 0
) {
+ this.followOffset ??=
+ playhead >= position && playhead <= position + zoom
+ ? Math.max(zoom * 0.8, playhead - position)
+ : zoom * 0.8;
if (playhead < position) {
next = playhead - zoom * 0.2;
- } else if (playhead > position + zoom * 0.8) {
- next = playhead - zoom * 0.8;
+ } else if (playhead > position + this.followOffset) {
+ next = playhead - this.followOffset;
}
- next = Math.min(Math.max(next, 0), Math.max(duration - zoom, 0));
+ next = Math.min(
+ Math.max(next, 0),
+ Math.max(duration - zoom, position, 0),
+ );
}
this.previous = { position: next, zoom };
return next;
diff --git a/apps/desktop/src/routes/editor/TranscriptPage.tsx b/apps/desktop/src/routes/editor/TranscriptPage.tsx
index acc73e952..738f64078 100644
--- a/apps/desktop/src/routes/editor/TranscriptPage.tsx
+++ b/apps/desktop/src/routes/editor/TranscriptPage.tsx
@@ -34,6 +34,7 @@ import {
rangeIntersectsClipTransition,
} from "./clip-transitions";
import { FPS, useEditorContext } from "./context";
+import { routeEditorPlaybackIntent } from "./playback-intent-routing";
import { rippleDeleteAllTracks } from "./timeline-utils";
function formatTimePrecise(secs: number) {
@@ -73,6 +74,8 @@ export function TranscriptPanel() {
meta,
totalDuration,
previewResolutionBase,
+ playbackIntent,
+ requestHandoffPlayback,
} = useEditorContext();
const recordingSegments = () => editorInstance.recordings.segments;
@@ -300,12 +303,19 @@ export function TranscriptPanel() {
project.timeline?.textSegments,
);
if (outputTime === null) return;
- if (editorState.playing) {
- await commands.stopPlayback();
- setEditorState("playing", false);
- }
- const frame = Math.max(Math.floor(outputTime * FPS), 0);
- await commands.seekTo(frame);
+ const accepted = await routeEditorPlaybackIntent(
+ requestHandoffPlayback,
+ { playing: false, seconds: outputTime },
+ async () => {
+ if (editorState.playing) {
+ await commands.stopPlayback();
+ setEditorState("playing", false);
+ }
+ const frame = Math.max(Math.floor(outputTime * FPS), 0);
+ await commands.seekTo(frame);
+ },
+ );
+ if (!accepted) return;
batch(() => {
setEditorState("previewTime", null);
setEditorState("playbackTime", outputTime);
@@ -460,21 +470,30 @@ export function TranscriptPanel() {
const handlePlayPause = async () => {
try {
- if (isAtEnd()) {
- await commands.stopPlayback();
- setEditorState("playbackTime", 0);
- await commands.seekTo(0);
- await commands.startPlayback(FPS, previewResolutionBase());
- setEditorState("playing", true);
- } else if (editorState.playing) {
- await commands.stopPlayback();
- setEditorState("playing", false);
- } else {
- await commands.seekTo(Math.floor(editorState.playbackTime * FPS));
- await commands.startPlayback(FPS, previewResolutionBase());
- setEditorState("playing", true);
- }
- if (editorState.playing) setEditorState("previewTime", null);
+ await routeEditorPlaybackIntent(
+ requestHandoffPlayback,
+ {
+ playing: isAtEnd() || !playbackIntent(),
+ seconds: isAtEnd() ? 0 : editorState.playbackTime,
+ },
+ async () => {
+ if (isAtEnd()) {
+ await commands.stopPlayback();
+ setEditorState("playbackTime", 0);
+ await commands.seekTo(0);
+ await commands.startPlayback(FPS, previewResolutionBase());
+ setEditorState("playing", true);
+ } else if (editorState.playing) {
+ await commands.stopPlayback();
+ setEditorState("playing", false);
+ } else {
+ await commands.seekTo(Math.floor(editorState.playbackTime * FPS));
+ await commands.startPlayback(FPS, previewResolutionBase());
+ setEditorState("playing", true);
+ }
+ if (editorState.playing) setEditorState("previewTime", null);
+ },
+ );
} catch (error) {
console.error("Error handling play/pause:", error);
setEditorState("playing", false);
@@ -482,16 +501,18 @@ export function TranscriptPanel() {
};
createEffect(() => {
- if (isAtEnd() && editorState.playing) {
- void commands
- .stopPlayback()
- .then(() => {
- setEditorState("playing", false);
- })
- .catch((error) => {
- console.error("Error stopping playback:", error);
+ if (isAtEnd() && playbackIntent()) {
+ void routeEditorPlaybackIntent(
+ requestHandoffPlayback,
+ { playing: false },
+ async () => {
+ await commands.stopPlayback();
setEditorState("playing", false);
- });
+ },
+ ).catch((error) => {
+ console.error("Error stopping playback:", error);
+ setEditorState("playing", false);
+ });
}
});
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 1509c89cd..1a92ec274 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -87,6 +87,8 @@ import {
splitKeyboardSegment,
} from "./keyboard-timing";
import type { MaskSegment } from "./masks";
+import { usePreparingEditor } from "./preparing-editor-context";
+import { createPreparingPlaybackHandoff } from "./preparing-playback-handoff";
import { createProjectConfigSave } from "./project-config-save";
import type { SnapGuide } from "./snapping";
import {
@@ -141,7 +143,7 @@ export type ModalDialog =
};
export type LayoutMode =
- | { type: "export" }
+ | { type: "export"; destination?: "link" }
| { type: "transcript" }
| { type: "clips" };
@@ -1587,18 +1589,6 @@ export const [EditorContextProvider, useBaseEditorContext] =
: undefined,
);
- createEffect(
- on(
- () => editorState.playing,
- (active) => {
- if (!active)
- commands.setPlayheadPosition(
- Math.floor(editorState.playbackTime * FPS),
- );
- },
- ),
- );
-
const totalDuration = () =>
project.timeline
? clipTimelineDuration(
@@ -1651,11 +1641,12 @@ export const [EditorContextProvider, useBaseEditorContext] =
const initialCamera3DTrackVisible =
(project.timeline?.camera3dSegments?.length ?? 0) > 0;
+ const preparing = usePreparingEditor();
const [editorState, setEditorState] = createStore({
styleEditIndex: null as number | null,
importingImage: false,
previewTime: null as number | null,
- playbackTime: 0,
+ playbackTime: preparing?.handoffTarget()?.playback.playheadSeconds ?? 0,
playing: false,
// On-canvas selection of the screen recording / camera boxes.
// Kept separate from timeline.selection, which drives the sidebar
@@ -2091,8 +2082,162 @@ export const [EditorContextProvider, useBaseEditorContext] =
),
);
+ const [handoffIntent, setHandoffIntent] = createSignal({
+ playing: false,
+ active: false,
+ });
+ let playbackHandoff:
+ | ReturnType<typeof createPreparingPlaybackHandoff>
+ | undefined;
+ createEffect(
+ on(
+ () => props.editorInstance.instanceId,
+ (instanceId) => {
+ playbackHandoff?.dispose();
+ const initial = preparing?.handoffTarget();
+ let playbackId: string | undefined;
+ playbackHandoff = initial
+ ? createPreparingPlaybackHandoff({
+ initial: {
+ frameNumber: initial.frameNumber,
+ playing: initial.playback.playing,
+ },
+ start: async (frameNumber) => {
+ playbackId = await commands.startEditorHandoffPlayback(
+ instanceId,
+ frameNumber,
+ FPS,
+ previewResolutionBase(),
+ );
+ },
+ stop: async () => {
+ const current = playbackId;
+ playbackId = undefined;
+ if (current)
+ await commands.stopEditorHandoffPlayback(
+ instanceId,
+ current,
+ );
+ },
+ changed: (intent, active) =>
+ setHandoffIntent({ playing: intent.playing, active }),
+ settled: (intent) => {
+ playbackId = undefined;
+ setEditorState("playing", intent.playing);
+ },
+ failed: (error) => {
+ setEditorState("playing", false);
+ console.error("Failed to resume editor playback:", error);
+ },
+ })
+ : undefined;
+ setHandoffIntent({
+ playing: initial?.playback.playing ?? false,
+ active: !!initial,
+ });
+ preparing?.setPlaybackHandoff(playbackHandoff);
+ },
+ ),
+ );
+ createEffect(
+ on(
+ () => editorState.playing,
+ (active) => {
+ if (!active && !playbackHandoff?.active())
+ commands.setPlayheadPosition(
+ Math.floor(editorState.playbackTime * FPS),
+ );
+ },
+ ),
+ );
+
+ onCleanup(() => {
+ playbackHandoff?.dispose();
+ preparing?.setPlaybackHandoff(undefined);
+ });
+ const playbackIntent = () =>
+ handoffIntent().active ? handoffIntent().playing : editorState.playing;
+ let preparingCommand: Promise<boolean> = Promise.resolve(true);
+ let preparingCommandRevision = 0;
+ let cancelPreparingCommand: (() => void) | undefined;
+ onCleanup(() => {
+ preparingCommandRevision++;
+ cancelPreparingCommand?.();
+ });
+ createEffect(() => {
+ if (
+ props.editorInstance.preparingPlayback &&
+ !preparing?.ordinaryReady()
+ ) {
+ const playback = preparing?.model.playback();
+ if (playback)
+ setEditorState("playbackTime", playback.playheadSeconds);
+ }
+ });
+ const requestHandoffPlayback = (playing: boolean, seconds?: number) => {
+ const progressive =
+ props.editorInstance.preparingPlayback && !preparing?.ordinaryReady();
+ if (!progressive && !playbackHandoff?.active()) return undefined;
+ const bounded = Math.max(
+ 0,
+ Math.min(seconds ?? editorState.playbackTime, totalDuration()),
+ );
+ const frameNumber =
+ preparing?.requestOrdinaryFrame(Math.floor(bounded * FPS), true) ??
+ Math.floor(bounded * FPS);
+ setEditorState("playbackTime", bounded);
+ setEditorState("previewTime", null);
+ if (!progressive || !preparing)
+ return playbackHandoff?.request({ frameNumber, playing });
+ const revision = ++preparingCommandRevision;
+ cancelPreparingCommand?.();
+ const cancelled = new Promise<false>((resolve) => {
+ cancelPreparingCommand = () => resolve(false);
+ });
+ const releaseFrames = preparing.holdOrdinaryFrames();
+ setHandoffIntent({ playing, active: true });
+ preparingCommand = preparingCommand
+ .catch(() => false)
+ .then(async () => {
+ if (revision !== preparingCommandRevision) return false;
+ const model = preparing.model;
+ let accepted = seconds === undefined || (await model.seek(bounded));
+ if (revision !== preparingCommandRevision) return false;
+ if (accepted) accepted = await model.setPlaying(playing);
+ if (revision !== preparingCommandRevision) return false;
+ if (accepted) {
+ await preparing.retryCandidate();
+ return revision === preparingCommandRevision;
+ }
+ if (model.commandError() !== "Preparing playback has been adopted")
+ return false;
+ await commands.stopPlayback();
+ if (revision !== preparingCommandRevision) return false;
+ await commands.seekTo(frameNumber);
+ if (revision !== preparingCommandRevision) return false;
+ const pending = playbackHandoff?.request({ frameNumber, playing });
+ releaseFrames();
+ events.renderFrameEvent.emit({
+ frame_number: frameNumber,
+ fps: FPS,
+ resolution_base: previewResolutionBase(),
+ });
+ const settled = await Promise.race([pending, cancelled]);
+ return revision === preparingCommandRevision && (settled ?? false);
+ })
+ .finally(() => {
+ releaseFrames();
+ if (revision === preparingCommandRevision)
+ cancelPreparingCommand = undefined;
+ });
+ return preparingCommand;
+ };
+
return {
...editorInstanceContext,
+ playbackIntent,
+ handoffPlaybackPending: () => handoffIntent().active,
+ requestHandoffPlayback,
meta() {
return props.meta();
},
@@ -2196,6 +2341,7 @@ function transformMeta({ pretty_name, ...rawMeta }: RecordingMeta) {
export type TransformedMeta = ReturnType<typeof transformMeta>;
const createEditorInstanceContext = () => {
+ const preparing = usePreparingEditor();
const [latestFrame, setLatestFrame] = createLazySignal<FrameData>();
// Rendered display/camera placement of the latest preview frame, emitted
@@ -2211,8 +2357,14 @@ const createEditorInstanceContext = () => {
const [performanceMode, setPerformanceMode] = createSignal(false);
let disposeWorkerReadyEffect: (() => void) | undefined;
+ let activeInstanceId: string | undefined;
+ let closeSocket: (() => void) | undefined;
+ let alive = true;
onCleanup(() => {
+ alive = false;
+ activeInstanceId = undefined;
+ closeSocket?.();
disposeWorkerReadyEffect?.();
canvasControls()?.dispose();
});
@@ -2254,19 +2406,37 @@ const createEditorInstanceContext = () => {
console.log("[Editor] Editor instance created, setting up WebSocket");
+ const instanceId = instance.instanceId;
+ if (!alive) return instance;
+ activeInstanceId = instanceId;
+ closeSocket?.();
+ disposeWorkerReadyEffect?.();
+ canvasControls()?.dispose();
+ preparing?.acceptSnapshot(instance.preparingSnapshot);
const requestFrame = () => {
+ if (!alive || activeInstanceId !== instanceId) return;
events.renderFrameEvent.emit({
- frame_number: 0,
+ frame_number: preparing?.handoffRequestedFrame() ?? 0,
fps: FPS,
resolution_base: getPreviewResolution(DEFAULT_PREVIEW_QUALITY),
});
};
+ preparing?.beginHandoff(FPS, instance.recordingDuration, {
+ instanceId,
+ fps: FPS,
+ progressive: instance.preparingPlayback,
+ retry: async () => refetchEditorInstance(),
+ requestFrame,
+ });
const [ws, _wsConnected, workerReady, controls] = createImageDataWS(
instance.framesSocketUrl,
- setLatestFrame,
+ (frame) => {
+ if (alive && activeInstanceId === instanceId) setLatestFrame(frame);
+ },
requestFrame,
);
+ closeSocket = () => ws.close();
setCanvasControls(controls);
@@ -2278,11 +2448,13 @@ const createEditorInstanceContext = () => {
});
ws.addEventListener("open", () => {
+ if (!alive || activeInstanceId !== instanceId) return;
setIsConnected(true);
requestFrame();
});
ws.addEventListener("close", () => {
+ if (!alive || activeInstanceId !== instanceId) return;
setIsConnected(false);
});
diff --git a/apps/desktop/src/routes/editor/editor-skeleton.tsx b/apps/desktop/src/routes/editor/editor-skeleton.tsx
index a3ab1f23e..c2a04c2f4 100644
--- a/apps/desktop/src/routes/editor/editor-skeleton.tsx
+++ b/apps/desktop/src/routes/editor/editor-skeleton.tsx
@@ -1,203 +1,217 @@
import { type as ostype } from "@tauri-apps/plugin-os";
-import { cx } from "cva";
+import { For, Show } from "solid-js";
+import CaptionControlsMacOS from "~/components/titlebar/controls/CaptionControlsMacOS";
import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";
+import { usePreparingEditorModel } from "./preparing-editor-context";
+import {
+ type PreparingEditorModel,
+ preparingTime,
+} from "./preparing-editor-model";
+import { PreparingFrame } from "./preparing-frame";
+import { PreparingTimeline } from "./preparing-timeline";
-const MIN_PLAYER_HEIGHT = 320;
-const TIMELINE_SKELETON_HEIGHT = 22 + 26 + 4 + 2 * 44 + 6;
+const DISABLED_CONTROL =
+ "h-7 px-2 rounded-[7px] text-xs text-ed-text-3 disabled:opacity-50 disabled:cursor-default";
-function SkeletonPulse(props: { class?: string }) {
- return (
- <div class={cx("animate-pulse rounded-sm bg-ed-ctl-hover", props.class)} />
- );
-}
-
-function HeaderSkeleton() {
+function PreparingHeader(props: { model: PreparingEditorModel }) {
return (
<div
data-tauri-drag-region
- class="flex relative flex-row items-center w-full h-13 pr-3"
+ class="flex relative shrink-0 flex-row items-center w-full h-13 pr-3 max-[900px]:grid max-[900px]:grid-cols-1 max-[900px]:grid-rows-[36px_36px] max-[900px]:h-[72px] max-[900px]:pr-2"
>
<div
data-tauri-drag-region
- class="flex flex-row flex-1 gap-1.5 items-center h-full"
+ class="flex flex-row flex-1 min-w-0 items-center h-full"
>
- {ostype() === "macos" && <div class="h-full w-[92px] shrink-0" />}
+ {ostype() === "macos" && (
+ <div data-tauri-drag-region class="h-full w-[92px] shrink-0" />
+ )}
+ {ostype() === "linux" && (
+ <CaptionControlsMacOS class="mr-1 ml-3 shrink-0" />
+ )}
{ostype() === "windows" && <div class="w-3 shrink-0" />}
- <SkeletonPulse class="h-4 w-40" />
- <SkeletonPulse class="h-4 w-7" />
- <SkeletonPulse class="ml-1.5 size-7 rounded-[7px]" />
- <SkeletonPulse class="size-7 rounded-[7px]" />
+ <span class="truncate text-[13px] font-medium">
+ {props.model.seed().title || "Recording"}
+ </span>
+ <span class="ml-1.5 text-[13px] text-ed-text-3">.cap</span>
+ <div class="flex gap-1 ml-3">
+ <button
+ type="button"
+ disabled
+ class={DISABLED_CONTROL}
+ aria-label="Undo"
+ >
+ ↶
+ </button>
+ <button
+ type="button"
+ disabled
+ class={DISABLED_CONTROL}
+ aria-label="Redo"
+ >
+ ↷
+ </button>
+ </div>
<div data-tauri-drag-region class="flex-1 h-full" />
</div>
- <div class="flex flex-row gap-1 items-center">
- <SkeletonPulse class="size-7 rounded-[7px]" />
- <SkeletonPulse class="size-7 rounded-[7px]" />
- <SkeletonPulse class="mx-1.5 w-px h-4" />
- <SkeletonPulse class="h-7 w-20 rounded-[7px]" />
- <SkeletonPulse class="h-7 w-16 rounded-[7px]" />
- <SkeletonPulse class="ml-1.5 h-[30px] w-[92px] rounded-lg" />
+ <div class="flex gap-1 items-center justify-end max-[900px]:pr-1">
+ <button type="button" disabled class={DISABLED_CONTROL}>
+ Presets
+ </button>
+ <button type="button" disabled class={DISABLED_CONTROL}>
+ Clips
+ </button>
+ <button
+ type="button"
+ disabled
+ class="ml-1.5 h-[30px] px-3.5 rounded-lg bg-ed-accent/40 text-white/70 text-[13px] font-medium"
+ title="Available when your recording is ready to edit"
+ >
+ Export
+ </button>
</div>
- {ostype() === "windows" && <CaptionControlsWindows11 class="shrink-0" />}
+ {ostype() === "windows" && (
+ <CaptionControlsWindows11 class="shrink-0 max-[900px]:absolute max-[900px]:top-0 max-[900px]:right-0" />
+ )}
</div>
);
}
-function PlayerSkeleton() {
+function PreparingPlayer(props: { model: PreparingEditorModel }) {
return (
<div class="flex flex-col flex-1 min-w-0 rounded-xl bg-ed-card shadow-ed-card overflow-hidden">
<div class="flex flex-row items-center px-3 h-11 shrink-0">
<div class="flex flex-row flex-1 gap-0.5 items-center">
- <SkeletonPulse class="h-7 w-16 rounded-[7px]" />
- <SkeletonPulse class="h-7 w-16 rounded-[7px]" />
- <SkeletonPulse class="h-7 w-20 rounded-[7px]" />
- </div>
- <div class="flex flex-row gap-2 items-center">
- <SkeletonPulse class="h-3 w-12" />
- <SkeletonPulse class="h-7 w-40 rounded-lg" />
- </div>
+ <button type="button" disabled class={DISABLED_CONTROL}>
+ Aspect ratio
+ </button>
+ <button type="button" disabled class={DISABLED_CONTROL}>
+ Captions
+ </button>
+ </div>
+ <span class="text-[11px] text-ed-text-3">Preview</span>
</div>
<div class="relative flex flex-1 min-h-0 justify-center items-center p-4">
- <div class="flex justify-center items-center w-full max-w-[85%] rounded-md aspect-video bg-ed-ctl">
- <div class="animate-spin opacity-60">
- <IconCapLogo class="size-16 text-ed-text-3" />
- </div>
- </div>
+ <PreparingFrame />
</div>
<div class="flex flex-row items-center px-3.5 h-12 shrink-0">
- <div class="flex flex-row flex-1 items-center">
- <SkeletonPulse class="h-4 w-24" />
- </div>
- <div class="flex flex-row gap-3.5 items-center">
- <SkeletonPulse class="size-3.5 rounded-sm" />
- <SkeletonPulse class="size-8 rounded-full" />
- <SkeletonPulse class="size-3.5 rounded-sm" />
- </div>
- <div class="flex flex-row flex-1 gap-0.5 justify-end items-center">
- <SkeletonPulse class="size-7 rounded-[7px]" />
- <SkeletonPulse class="mx-1.5 w-px h-4" />
- <SkeletonPulse class="size-7 rounded-[7px]" />
- <SkeletonPulse class="mx-1 w-[72px] h-[3px] rounded-full" />
- <SkeletonPulse class="size-7 rounded-[7px]" />
+ <div class="flex-1 tabular-nums text-[11px] text-ed-text-3">
+ {preparingTime(props.model.playback().playheadSeconds)}
+ <Show when={props.model.timeline().totalDuration}>
+ {(duration) => <span> / {preparingTime(duration())}</span>}
+ </Show>
+ </div>
+ <div class="flex gap-3.5 items-center">
+ <button
+ type="button"
+ aria-label="Go to beginning"
+ disabled={!props.model.canPlay()}
+ class={DISABLED_CONTROL}
+ onClick={() => void props.model.seek(0)}
+ >
+ ↤
+ </button>
+ <button
+ type="button"
+ aria-label={props.model.playback().playing ? "Pause" : "Play"}
+ disabled={!props.model.canPlay()}
+ class="flex items-center justify-center size-8 rounded-full bg-ed-ctl-hover text-ed-text-1 disabled:opacity-40"
+ onClick={() =>
+ void props.model.setPlaying(!props.model.playback().playing)
+ }
+ >
+ <Show
+ when={props.model.playback().playing}
+ fallback={<IconCapPlay class="size-3" />}
+ >
+ <IconCapPause class="size-3" />
+ </Show>
+ </button>
+ <button
+ type="button"
+ aria-label="Go to playable end"
+ disabled={!props.model.canPlay()}
+ class={DISABLED_CONTROL}
+ onClick={() =>
+ void props.model.seek(props.model.timeline().playableUntil)
+ }
+ >
+ ↦
+ </button>
+ </div>
+ <div class="flex-1 text-right text-[11px] text-ed-text-3" role="status">
+ {props.model.playback().buffering ? "Preparing playback" : ""}
</div>
</div>
</div>
);
}
-function SidebarSkeleton() {
+function PreparingSidebar() {
return (
<div class="flex flex-col min-h-0 w-104 min-w-104 flex-none overflow-hidden rounded-xl bg-ed-card shadow-ed-card">
- <div class="flex flex-row justify-around items-center px-2.5 h-[46px] border-b border-ed-line shrink-0">
- <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
- <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
- <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
- <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
- <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
- <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
- </div>
- <div class="flex flex-col flex-1 gap-3.5 px-4 pt-3.5 pb-4 overflow-hidden">
- <div class="flex justify-between items-center h-5">
- <SkeletonPulse class="h-3 w-20" />
- <SkeletonPulse class="h-5 w-12 rounded-md" />
- </div>
- <SkeletonPulse class="h-[30px] w-full rounded-lg" />
- <div class="flex gap-1">
- <SkeletonPulse class="h-6 w-16 rounded-[7px]" />
- <SkeletonPulse class="h-6 w-12 rounded-[7px]" />
- <SkeletonPulse class="h-6 w-12 rounded-[7px]" />
- <SkeletonPulse class="h-6 w-14 rounded-[7px]" />
- </div>
- <div class="grid grid-cols-6 gap-1.5">
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- <SkeletonPulse class="h-[34px] rounded-md" />
- </div>
- <div class="h-px w-full bg-ed-line" />
- <SkeletonPulse class="h-3 w-14" />
- <div class="flex items-center gap-3 h-[34px]">
- <SkeletonPulse class="h-3.5 w-16" />
- <SkeletonPulse class="flex-1 h-[3px] rounded-full" />
- <SkeletonPulse class="h-3 w-8" />
- </div>
- <div class="flex items-center gap-3 h-[34px]">
- <SkeletonPulse class="h-3.5 w-14" />
- <SkeletonPulse class="flex-1 h-[3px] rounded-full" />
- <SkeletonPulse class="h-3 w-8" />
- </div>
- <div class="flex items-center justify-between h-[34px]">
- <SkeletonPulse class="h-3.5 w-16" />
- <SkeletonPulse class="h-5 w-[34px] rounded-full" />
- </div>
+ <div class="flex justify-around items-center px-2.5 h-[46px] border-b border-ed-line shrink-0">
+ <For each={["Background", "Camera", "Audio", "Cursor", "Keyboard"]}>
+ {(name) => (
+ <button
+ type="button"
+ disabled
+ class="px-1 text-[10px] text-ed-text-3 opacity-50"
+ >
+ {name}
+ </button>
+ )}
+ </For>
</div>
- </div>
- );
-}
-
-function TimelineTrackSkeleton() {
- return (
- <div class="flex items-center h-11 rounded-lg bg-ed-ctl">
- <div class="flex gap-1.5 items-center pl-2 w-[104px] shrink-0">
- <SkeletonPulse class="size-[22px] rounded-md" />
- <SkeletonPulse class="h-3 w-10" />
- </div>
- <SkeletonPulse class="flex-1 h-full rounded-r-lg" />
- </div>
- );
-}
-
-function TimelineSkeleton() {
- return (
- <div class="flex flex-col h-full rounded-xl bg-ed-card shadow-ed-card overflow-hidden px-3 pt-2.5 pb-3">
- <div class="flex items-end h-[26px] shrink-0">
- <div class="w-[104px] pl-1 shrink-0">
- <SkeletonPulse class="h-6 w-[88px] rounded-md" />
- </div>
- <div class="flex flex-1 gap-[92px] items-end pb-2.5">
- <SkeletonPulse class="h-2.5 w-7" />
- <SkeletonPulse class="h-2.5 w-7" />
- <SkeletonPulse class="h-2.5 w-7" />
- <SkeletonPulse class="h-2.5 w-7" />
- <SkeletonPulse class="h-2.5 w-7" />
- <SkeletonPulse class="h-2.5 w-7" />
- </div>
- </div>
- <div class="flex flex-col gap-1.5 mt-1">
- <TimelineTrackSkeleton />
- <TimelineTrackSkeleton />
+ <div class="flex flex-col gap-5 px-4 py-4">
+ <div>
+ <h2 class="text-[12px] font-medium text-ed-text-2">Background</h2>
+ <p class="mt-2 text-[12px] text-ed-text-3">
+ Your recording’s appearance is being prepared.
+ </p>
+ </div>
+ <div class="h-px bg-ed-line" />
+ <For each={["Padding", "Rounding", "Shadow"]}>
+ {(name) => (
+ <div class="flex items-center justify-between h-[34px] text-[12px] text-ed-text-3">
+ <span>{name}</span>
+ <span class="text-[11px]">Available when ready</span>
+ </div>
+ )}
+ </For>
+ <p class="text-[11px] text-ed-text-3">
+ Editing and export will be available when preparation finishes.
+ </p>
</div>
</div>
);
}
export function EditorSkeleton() {
+ const model = usePreparingEditorModel();
return (
- <div class="flex flex-col flex-1 min-h-0">
- <HeaderSkeleton />
+ <div
+ class="flex flex-col flex-1 min-h-0"
+ aria-label="Recording editor"
+ data-preparing-editor
+ >
+ <PreparingHeader model={model} />
<div
data-tauri-drag-region
class="flex overflow-y-hidden flex-col flex-1 gap-2 pb-2 w-full min-h-0 leading-5"
>
<div
class="flex overflow-y-hidden flex-row flex-1 min-h-0 gap-2 px-2"
- style={{ "min-height": `${MIN_PLAYER_HEIGHT}px` }}
+ style={{ "min-height": "320px" }}
>
- <PlayerSkeleton />
- <SidebarSkeleton />
+ <PreparingPlayer model={model} />
+ <PreparingSidebar />
</div>
<div
class="flex-none min-h-0 px-2 overflow-hidden"
- style={{ height: `${TIMELINE_SKELETON_HEIGHT}px` }}
+ style={{ height: "146px" }}
>
- <TimelineSkeleton />
+ <PreparingTimeline model={model} />
</div>
</div>
</div>
diff --git a/apps/desktop/src/routes/editor/index.tsx b/apps/desktop/src/routes/editor/index.tsx
index 7044a4e68..2d7ea67e4 100644
--- a/apps/desktop/src/routes/editor/index.tsx
+++ b/apps/desktop/src/routes/editor/index.tsx
@@ -6,6 +6,7 @@ import { generalSettingsStore } from "~/store";
import { commands } from "~/utils/tauri";
import { Editor } from "./Editor";
import { EditorSkeleton } from "./editor-skeleton";
+import { PreparingEditorProvider } from "./preparing-editor-context";
export default function () {
const generalSettings = generalSettingsStore.createQuery();
@@ -51,9 +52,11 @@ export default function () {
) && "bg-transparent-window",
)}
>
- <Suspense fallback={<EditorSkeleton />}>
- <Editor />
- </Suspense>
+ <PreparingEditorProvider>
+ <Suspense fallback={<EditorSkeleton />}>
+ <Editor />
+ </Suspense>
+ </PreparingEditorProvider>
</div>
);
}
diff --git a/apps/desktop/src/routes/editor/playback-intent-routing.test.ts b/apps/desktop/src/routes/editor/playback-intent-routing.test.ts
new file mode 100644
index 000000000..f1ce5515f
--- /dev/null
+++ b/apps/desktop/src/routes/editor/playback-intent-routing.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, it, vi } from "vitest";
+import { routeEditorPlaybackIntent } from "./playback-intent-routing";
+import { createPreparingPlaybackHandoff } from "./preparing-playback-handoff";
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((complete) => {
+ resolve = complete;
+ });
+ return { promise, resolve };
+}
+
+function harness() {
+ const started = deferred();
+ const stopped = deferred();
+ const start = vi.fn(async (_frameNumber: number) => {});
+ start.mockImplementationOnce(() => started.promise);
+ const stop = vi.fn(() => stopped.promise);
+ const settled = vi.fn();
+ const handoff = createPreparingPlaybackHandoff({
+ initial: { frameNumber: 600, playing: true },
+ start,
+ stop,
+ changed: vi.fn(),
+ settled,
+ failed: vi.fn(),
+ });
+ const request = (playing: boolean, seconds = 20) =>
+ handoff.request({ frameNumber: Math.floor(seconds * 30), playing });
+ const ordinary = vi.fn(async () => {});
+ return { handoff, request, ordinary, started, stopped, start, stop, settled };
+}
+
+async function flush() {
+ for (let i = 0; i < 8; i++) await Promise.resolve();
+}
+
+describe("panel playback intent routing", () => {
+ it("transcript word seek stops a pending resume and waits for the new actual frame", async () => {
+ const value = harness();
+ value.handoff.acknowledge(600);
+ const seek = routeEditorPlaybackIntent(
+ value.request,
+ { playing: false, seconds: 7 },
+ value.ordinary,
+ );
+ value.started.resolve();
+ await flush();
+ expect(value.stop).toHaveBeenCalledTimes(1);
+ expect(value.ordinary).not.toHaveBeenCalled();
+ value.stopped.resolve();
+ await flush();
+ expect(value.settled).not.toHaveBeenCalled();
+ value.handoff.acknowledge(210);
+ expect(await seek).toBe(true);
+ expect(value.settled.mock.calls).toEqual([
+ [{ frameNumber: 210, playing: false }],
+ ]);
+ expect(value.start).toHaveBeenCalledTimes(1);
+ value.handoff.dispose();
+ });
+
+ it("record or import cannot continue before captured playback has actually stopped", async () => {
+ const value = harness();
+ const mutate = vi.fn();
+ value.handoff.acknowledge(600);
+ const change = routeEditorPlaybackIntent(
+ value.request,
+ { playing: false },
+ value.ordinary,
+ ).then((accepted) => {
+ if (accepted) mutate();
+ });
+ value.started.resolve();
+ await flush();
+ expect(mutate).not.toHaveBeenCalled();
+ expect(value.ordinary).not.toHaveBeenCalled();
+ value.stopped.resolve();
+ await change;
+ expect(mutate).toHaveBeenCalledTimes(1);
+ value.handoff.dispose();
+ });
+
+ it("a newer transcript Play supersedes an import pause without invoking ordinary commands", async () => {
+ const value = harness();
+ const pause = routeEditorPlaybackIntent(
+ value.request,
+ { playing: false },
+ value.ordinary,
+ );
+ const play = routeEditorPlaybackIntent(
+ value.request,
+ { playing: true },
+ value.ordinary,
+ );
+ expect(await pause).toBe(false);
+ value.handoff.acknowledge(600);
+ value.started.resolve();
+ expect(await play).toBe(true);
+ expect(value.ordinary).not.toHaveBeenCalled();
+ value.handoff.dispose();
+ });
+
+ it("owner disposal declines queued record/import and never falls through to ordinary playback", async () => {
+ const value = harness();
+ const pause = routeEditorPlaybackIntent(
+ value.request,
+ { playing: false },
+ value.ordinary,
+ );
+ value.handoff.dispose();
+ expect(await pause).toBe(false);
+ expect(value.start).not.toHaveBeenCalled();
+ expect(value.ordinary).not.toHaveBeenCalled();
+ });
+
+ it("transcript replay requests frame zero through the queue at the actual end", async () => {
+ const value = harness();
+ const replay = routeEditorPlaybackIntent(
+ value.request,
+ { playing: true, seconds: 0 },
+ value.ordinary,
+ );
+ value.handoff.acknowledge(600);
+ expect(value.start).not.toHaveBeenCalled();
+ value.handoff.acknowledge(0);
+ value.started.resolve();
+ expect(await replay).toBe(true);
+ expect(value.start.mock.calls).toEqual([[0]]);
+ expect(value.ordinary).not.toHaveBeenCalled();
+ value.handoff.dispose();
+ });
+
+ it("ordinary behavior keeps its command order and completes only after its own acknowledgement", async () => {
+ const stopped = deferred();
+ const calls: string[] = [];
+ const routed = routeEditorPlaybackIntent(
+ () => undefined,
+ { playing: false, seconds: 7 },
+ async () => {
+ calls.push("stop");
+ await stopped.promise;
+ calls.push("seek");
+ },
+ );
+ expect(calls).toEqual(["stop"]);
+ stopped.resolve();
+ expect(await routed).toBe(true);
+ expect(calls).toEqual(["stop", "seek"]);
+ });
+
+ it("ordinary stop failures reject rather than admitting a project mutation", async () => {
+ await expect(
+ routeEditorPlaybackIntent(
+ () => undefined,
+ { playing: false },
+ async () => {
+ throw new Error("stop failed");
+ },
+ ),
+ ).rejects.toThrow("stop failed");
+ });
+});
diff --git a/apps/desktop/src/routes/editor/playback-intent-routing.ts b/apps/desktop/src/routes/editor/playback-intent-routing.ts
new file mode 100644
index 000000000..d39a5074e
--- /dev/null
+++ b/apps/desktop/src/routes/editor/playback-intent-routing.ts
@@ -0,0 +1,14 @@
+export type RequestHandoffPlayback = (
+ playing: boolean,
+ seconds?: number,
+) => Promise<boolean> | undefined;
+
+export function routeEditorPlaybackIntent(
+ request: RequestHandoffPlayback,
+ intent: { playing: boolean; seconds?: number },
+ ordinary: () => Promise<void>,
+): Promise<boolean> {
+ const pending = request(intent.playing, intent.seconds);
+ if (pending) return pending;
+ return ordinary().then(() => true);
+}
diff --git a/apps/desktop/src/routes/editor/preparing-editor-context.tsx b/apps/desktop/src/routes/editor/preparing-editor-context.tsx
new file mode 100644
index 000000000..0e964fac4
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-editor-context.tsx
@@ -0,0 +1,264 @@
+import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
+import {
+ createContext,
+ createEffect,
+ createSignal,
+ getOwner,
+ onCleanup,
+ onMount,
+ type ParentProps,
+ runWithOwner,
+ useContext,
+} from "solid-js";
+import type { FrameData } from "~/utils/socket";
+import { commands, events } from "~/utils/tauri";
+import {
+ createPreparingEditorModel,
+ type PreparingEditorModel,
+} from "./preparing-editor-model";
+import { createPreparingEditorSubscription } from "./preparing-editor-subscription";
+import { createPreparingFrameLease } from "./preparing-frame-lease";
+import { attachPreparingFrameTransport } from "./preparing-frame-transport";
+import { createPreparingHandoff } from "./preparing-handoff";
+import type { createPreparingPlaybackHandoff } from "./preparing-playback-handoff";
+
+function createPreparingEditorSession() {
+ const model = createPreparingEditorModel();
+ const handoff = createPreparingHandoff();
+ const owner = getOwner();
+ let alive = true;
+ let candidate:
+ | {
+ instanceId: string;
+ fps: number;
+ progressive: boolean;
+ retry: () => Promise<unknown>;
+ requestFrame: () => void;
+ }
+ | undefined;
+ let refreshing: Promise<unknown> | undefined;
+ const retryCandidate = () => {
+ if (!candidate || refreshing || !alive) return refreshing;
+ handoff.invalidatePending();
+ playbackHandoff?.dispose();
+ refreshing = candidate.retry().finally(() => {
+ refreshing = undefined;
+ });
+ return refreshing;
+ };
+ let playbackHandoff:
+ | ReturnType<typeof createPreparingPlaybackHandoff>
+ | undefined;
+ const [canvases, setCanvases] = createSignal<{
+ active: HTMLCanvasElement;
+ retained: HTMLCanvasElement;
+ }>();
+ const [retained, setRetained] = createSignal(false);
+ const [ordinaryReady, setOrdinaryReady] = createSignal(false);
+ const lease = createPreparingFrameLease({
+ start: async (epoch) => {
+ const url = await commands.createPreparingEditorFrame(epoch);
+ await subscription.refresh();
+ return url;
+ },
+ stop: (epoch) => commands.stopPreparingEditorFrame(epoch),
+ ended: (hasRetainedFrame) => setRetained(hasRetainedFrame),
+ attach: (url, isActive) => {
+ const pair = canvases();
+ if (!pair) throw new Error("Preparing canvas owner is unavailable");
+ const transport = runWithOwner(owner, () =>
+ attachPreparingFrameTransport({
+ url,
+ canvas: pair.active,
+ retainedCanvas: pair.retained,
+ isActive,
+ onRendered: model.setRendered,
+ onTerminal: () => lease.finish(),
+ }),
+ );
+ if (!transport) throw new Error("Preparing frame owner ended");
+ return transport;
+ },
+ });
+ const subscription = createPreparingEditorSubscription({
+ requestEpoch: lease.requestEpoch,
+ model,
+ listen: (accept) =>
+ events
+ .preparingEditorChanged(getCurrentWebviewWindow())
+ .listen(({ payload }) => accept(payload)),
+ getState: () => commands.getPreparingEditorState(lease.requestEpoch),
+ controller: (jobId) => ({
+ seek: async (seconds) => {
+ await commands.seekPreparingEditor(lease.requestEpoch, jobId, seconds);
+ },
+ setPlaying: async (playing) => {
+ await commands.setPreparingEditorPlaying(
+ lease.requestEpoch,
+ jobId,
+ playing,
+ );
+ },
+ }),
+ });
+ onMount(() => {
+ const active = document.createElement("canvas");
+ const preserved = document.createElement("canvas");
+ for (const canvas of [active, preserved]) {
+ canvas.className =
+ "absolute max-w-full max-h-full object-contain rounded-md";
+ canvas.setAttribute(
+ "aria-label",
+ "Recording preview while the editor prepares",
+ );
+ }
+ setCanvases({ active, retained: preserved });
+ void subscription.listen().then(async (ready) => {
+ if (ready) {
+ await lease.start();
+ if (!lease.isActive()) subscription.stopListening();
+ } else lease.close();
+ });
+ });
+ createEffect(() => {
+ const pair = canvases();
+ if (!pair) return;
+ pair.active.classList.toggle(
+ "invisible",
+ !model.rendered() || retained() || ordinaryReady(),
+ );
+ pair.retained.classList.toggle("invisible", !retained() || ordinaryReady());
+ });
+ onCleanup(() => {
+ alive = false;
+ handoff.invalidatePending();
+ subscription.dispose();
+ lease.close();
+ model.dispose();
+ const pair = canvases();
+ pair?.active.remove();
+ pair?.retained.remove();
+ });
+ return {
+ model,
+ canvases,
+ retained,
+ ordinaryReady,
+ acceptSnapshot: subscription.accept,
+ beginHandoff(
+ fps: number,
+ recordingDuration: number,
+ value: NonNullable<typeof candidate>,
+ ) {
+ candidate = value;
+ const target = handoff.begin(
+ model.playback(),
+ fps,
+ recordingDuration,
+ value.instanceId,
+ );
+ if (target && value.progressive)
+ handoff.setAdvancing(target.playback.playing, target.frameNumber);
+ return target;
+ },
+ retryCandidate,
+ invalidatePending: handoff.invalidatePending,
+ holdOrdinaryFrames() {
+ const release = handoff.holdFrames();
+ return () => {
+ if (release() && alive) candidate?.requestFrame();
+ };
+ },
+ handoffTarget: handoff.target,
+ handoffRequestedFrame: handoff.requestedFrame,
+ setPlaybackHandoff(value: typeof playbackHandoff) {
+ playbackHandoff = value;
+ },
+ requestOrdinaryFrame(frameNumber: number, explicit = false) {
+ if (
+ !explicit &&
+ candidate?.progressive &&
+ !ordinaryReady() &&
+ model.playback().playing
+ )
+ return frameNumber;
+ const actual = handoff.requestFrame(
+ frameNumber,
+ playbackHandoff?.active(),
+ );
+ playbackHandoff?.retarget(actual);
+ return actual;
+ },
+ setOrdinaryAdvancing(playing: boolean, frameNumber: number) {
+ if (candidate?.progressive && !ordinaryReady()) return;
+ handoff.setAdvancing(playing, frameNumber);
+ },
+ acknowledgeOrdinaryFrame(
+ frame: FrameData,
+ bounds: { width: number; height: number },
+ ) {
+ const current = candidate;
+ const frameNumber = frame.renderedFrame?.frameNumber;
+ if (!alive || !current || frameNumber === undefined) return;
+ if (ordinaryReady()) {
+ if (handoff.matches(frame, bounds))
+ playbackHandoff?.acknowledge(frameNumber);
+ return;
+ }
+ const pending = handoff.commitFrame(frame, bounds, () =>
+ current.progressive
+ ? commands.commitEditorPreparingFrame(
+ current.instanceId,
+ frameNumber,
+ current.fps,
+ )
+ : Promise.resolve(true),
+ );
+ void pending
+ ?.then((accepted) => {
+ if (!alive || candidate !== current) return;
+ if (!accepted) {
+ current.requestFrame();
+ return;
+ }
+ playbackHandoff?.acknowledge(frameNumber, current.progressive);
+ setOrdinaryReady(true);
+ lease.close();
+ })
+ .catch((error: unknown) => {
+ if (!alive || candidate !== current) return;
+ if (String(error) === "Preparing handoff candidate was superseded") {
+ void retryCandidate()?.catch((cause: unknown) =>
+ console.error("Failed to replace preparing editor:", cause),
+ );
+ } else {
+ console.error("Failed to accept preparing editor frame:", error);
+ }
+ });
+ },
+ };
+}
+
+const PreparingEditorContext =
+ createContext<ReturnType<typeof createPreparingEditorSession>>();
+
+export function PreparingEditorProvider(props: ParentProps) {
+ const session = createPreparingEditorSession();
+ return (
+ <PreparingEditorContext.Provider value={session}>
+ {props.children}
+ </PreparingEditorContext.Provider>
+ );
+}
+
+export function usePreparingEditor() {
+ return useContext(PreparingEditorContext);
+}
+
+export function usePreparingEditorModel(): PreparingEditorModel {
+ const session = usePreparingEditor();
+ if (session) return session.model;
+ const model = createPreparingEditorModel();
+ onCleanup(() => model.dispose());
+ return model;
+}
diff --git a/apps/desktop/src/routes/editor/preparing-editor-model.test.ts b/apps/desktop/src/routes/editor/preparing-editor-model.test.ts
new file mode 100644
index 000000000..3dd6ac197
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-editor-model.test.ts
@@ -0,0 +1,294 @@
+import { createRoot } from "solid-js";
+import { describe, expect, it, vi } from "vitest";
+import {
+ createPreparingEditorModel,
+ type PreparingEditorSnapshot,
+ preparingTime,
+ preparingTimeline,
+} from "./preparing-editor-model";
+
+vi.mock("solid-js", () =>
+ vi.importActual<typeof import("solid-js")>("solid-js/dist/solid.js"),
+);
+
+const identity = { requestEpoch: 17, jobId: "actual-finalization-job" };
+function snapshot(sequence = 0): PreparingEditorSnapshot {
+ return {
+ ...identity,
+ sequence,
+ progress: {
+ totalDuration: 120,
+ playableUntil: 20,
+ previewAvailable: true,
+ phase: "preparing",
+ },
+ playback: { playheadSeconds: 0, playing: false, buffering: false },
+ };
+}
+
+function harness() {
+ let cleanup = () => {};
+ const model = createRoot((dispose) => {
+ cleanup = dispose;
+ return createPreparingEditorModel();
+ });
+ const controller = {
+ seek: vi.fn(async (_seconds: number) => {}),
+ setPlaying: vi.fn(async (_playing: boolean) => {}),
+ };
+ expect(model.bind(identity, controller, 60)).toBe(true);
+ return {
+ model,
+ controller,
+ dispose() {
+ model.dispose();
+ cleanup();
+ },
+ };
+}
+
+describe("preparing editor confirmed readiness", () => {
+ it("starts without an invented duration, playable prefix or controller action", async () => {
+ const value = harness();
+ expect(value.model.timeline()).toEqual({
+ totalDuration: null,
+ playableUntil: 0,
+ fraction: null,
+ });
+ expect(await value.model.seek(10)).toBe(false);
+ expect(await value.model.setPlaying(true)).toBe(false);
+ expect(value.controller.seek).not.toHaveBeenCalled();
+ value.dispose();
+ });
+
+ it("keeps an actual first image independent from audio playback readiness", async () => {
+ const value = harness();
+ const next = snapshot();
+ next.progress.playableUntil = 0;
+ value.model.accept(next);
+ value.model.setRendered(true);
+ expect(value.model.rendered()).toBe(true);
+ expect(value.model.canPlay()).toBe(false);
+ expect(await value.model.setPlaying(true)).toBe(false);
+ value.dispose();
+ });
+
+ it("rejects foreign, duplicate and out-of-order updates before changing the frontier", () => {
+ const value = harness();
+ expect(value.model.accept(snapshot(2))).toBe(true);
+ for (const next of [
+ snapshot(2),
+ snapshot(1),
+ { ...snapshot(3), jobId: "other" },
+ { ...snapshot(3), requestEpoch: 18 },
+ ]) {
+ next.progress.playableUntil = 120;
+ expect(value.model.accept(next)).toBe(false);
+ }
+ expect(value.model.timeline().playableUntil).toBe(20);
+ expect(
+ value.model.bind(
+ { ...identity, jobId: "replacement" },
+ value.controller,
+ 60,
+ ),
+ ).toBe(false);
+ value.dispose();
+ });
+
+ it("clamps actual seek requests to the confirmed prefix without optimistic state", async () => {
+ const value = harness();
+ value.model.accept(snapshot());
+ value.model.setRendered(true);
+ expect(await value.model.seek(90)).toBe(true);
+ expect(value.controller.seek).toHaveBeenCalledWith(1199 / 60);
+ expect(value.model.playback().playheadSeconds).toBe(0);
+ expect(await value.model.setPlaying(true)).toBe(true);
+ expect(value.model.playback().playing).toBe(false);
+ for (const invalid of [Number.NaN, Number.POSITIVE_INFINITY, -1]) {
+ expect(await value.model.seek(invalid)).toBe(false);
+ }
+ expect(value.controller.seek).toHaveBeenCalledTimes(1);
+ value.dispose();
+ });
+
+ it("revokes playback on a later failure while retaining the displayed image", async () => {
+ const value = harness();
+ value.model.accept(snapshot());
+ value.model.setRendered(true);
+ const failed = snapshot(1);
+ failed.progress.phase = "unavailable";
+ value.model.accept(failed);
+ expect(value.model.timeline().playableUntil).toBe(0);
+ expect(value.model.rendered()).toBe(true);
+ expect(await value.model.setPlaying(true)).toBe(false);
+ value.dispose();
+ });
+
+ it("keeps unknown duration unscaled and without claimed playability", () => {
+ const value = snapshot().progress;
+ value.totalDuration = null;
+ expect(preparingTimeline(value)).toEqual({
+ totalDuration: null,
+ playableUntil: 0,
+ fraction: null,
+ });
+ value.totalDuration = 5;
+ expect(preparingTimeline(value).fraction).toBe(1);
+ });
+
+ it("holds the backend playhead and playing intent during handoff without accepting new commands", async () => {
+ const value = harness();
+ const next = snapshot();
+ next.progress.phase = "handoff";
+ next.playback = { playheadSeconds: 12.75, playing: true, buffering: false };
+ value.model.accept(next);
+ value.model.setRendered(true);
+ expect(value.model.playback()).toEqual(next.playback);
+ expect(await value.model.seek(2)).toBe(false);
+ expect(await value.model.setPlaying(true)).toBe(false);
+ value.dispose();
+ });
+
+ it("fails closed for invalid confirmed data and never retains earlier playability", () => {
+ const value = harness();
+ value.model.accept(snapshot());
+ value.model.setRendered(true);
+ const invalid = snapshot(1);
+ invalid.progress.totalDuration = Number.NaN;
+ expect(value.model.accept(invalid)).toBe(false);
+ expect(value.model.progress().phase).toBe("unavailable");
+ expect(value.model.canPlay()).toBe(false);
+ expect(value.model.timeline().playableUntil).toBe(0);
+ value.dispose();
+ });
+
+ it("does not publish a late command error after the window owner is disposed", async () => {
+ const value = harness();
+ let reject!: (error: Error) => void;
+ value.controller.seek.mockImplementation(
+ () =>
+ new Promise<void>((_, fail) => {
+ reject = fail;
+ }),
+ );
+ value.model.accept(snapshot());
+ value.model.setRendered(true);
+ const pending = value.model.seek(3);
+ expect(value.model.commandPending()).toBe(true);
+ expect(await value.model.seek(4)).toBe(false);
+ value.dispose();
+ reject(new Error("window closed"));
+ expect(await pending).toBe(false);
+ expect(value.model.commandError()).toBeUndefined();
+ expect(value.model.accept(snapshot(3))).toBe(false);
+ });
+
+ it("copies readonly seed data instead of retaining a mutable external tracks array", () => {
+ const value = harness();
+ const tracks: ("display" | "camera")[] = ["display"];
+ value.model.accept({
+ ...snapshot(),
+ seed: { title: "My recording", tracks },
+ });
+ tracks.push("camera");
+ expect(value.model.seed().tracks).toEqual(["display"]);
+ value.dispose();
+ });
+
+ it.each([null, 0, 10])(
+ "rejects a positive prefix inconsistent with duration %s",
+ (duration) => {
+ const value = harness();
+ const next = snapshot();
+ next.progress.totalDuration = duration;
+ value.model.setRendered(true);
+ expect(value.model.accept(next)).toBe(false);
+ expect(value.model.canPlay()).toBe(false);
+ expect(value.model.timeline().playableUntil).toBe(0);
+ value.dispose();
+ },
+ );
+
+ it.each([20, 20.001, 1 / 120])(
+ "seeks to an actual frame strictly before exclusive prefix %s",
+ async (prefix) => {
+ const value = harness();
+ const next = snapshot();
+ next.progress.playableUntil = prefix;
+ value.model.accept(next);
+ value.model.setRendered(true);
+ expect(await value.model.seek(prefix)).toBe(true);
+ const target = value.controller.seek.mock.calls[0][0];
+ expect(target).toBeLessThan(prefix);
+ expect(target * 60).toBeCloseTo(Math.ceil(prefix * 60) - 1);
+ value.dispose();
+ },
+ );
+
+ it.each([120, 119.95])(
+ "replays from zero at completed recording end %s",
+ async (playheadSeconds) => {
+ const value = harness();
+ const next = snapshot();
+ next.progress.playableUntil = 120;
+ next.playback.playheadSeconds = playheadSeconds;
+ value.model.accept(next);
+ value.model.setRendered(true);
+ expect(await value.model.setPlaying(true)).toBe(true);
+ expect(value.controller.seek).toHaveBeenCalledWith(0);
+ expect(value.controller.seek.mock.invocationCallOrder[0]).toBeLessThan(
+ value.controller.setPlaying.mock.invocationCallOrder[0],
+ );
+ value.dispose();
+ },
+ );
+
+ it("does not rewind at an incomplete playable frontier", async () => {
+ const value = harness();
+ const next = snapshot();
+ next.playback.playheadSeconds = 19.95;
+ value.model.accept(next);
+ value.model.setRendered(true);
+ expect(await value.model.setPlaying(true)).toBe(true);
+ expect(value.controller.seek).not.toHaveBeenCalled();
+ value.dispose();
+ });
+
+ it("does not start after a replay seek if handoff or disposal wins", async () => {
+ for (const end of ["handoff", "dispose"]) {
+ const value = harness();
+ let finish!: () => void;
+ value.controller.seek.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const next = snapshot();
+ next.progress.playableUntil = 120;
+ next.playback.playheadSeconds = 120;
+ value.model.accept(next);
+ value.model.setRendered(true);
+ const pending = value.model.setPlaying(true);
+ expect(value.model.commandPending()).toBe(true);
+ if (end === "dispose") value.dispose();
+ else
+ value.model.accept({
+ ...next,
+ sequence: 1,
+ progress: { ...next.progress, phase: "handoff" },
+ });
+ finish();
+ expect(await pending).toBe(false);
+ expect(value.controller.setPlaying).not.toHaveBeenCalled();
+ if (end !== "dispose") value.dispose();
+ }
+ });
+
+ it("formats long recording times without wrapping hours or displaying invalid numbers", () => {
+ expect(preparingTime(7200.99)).toBe("2:00:00");
+ expect(preparingTime(3661)).toBe("1:01:01");
+ expect(preparingTime(Number.NaN)).toBe("0:00");
+ });
+});
diff --git a/apps/desktop/src/routes/editor/preparing-editor-model.ts b/apps/desktop/src/routes/editor/preparing-editor-model.ts
new file mode 100644
index 000000000..9d2803a6a
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-editor-model.ts
@@ -0,0 +1,250 @@
+import { batch, createMemo, createSignal } from "solid-js";
+
+import type {
+ PreparingEditorProgress,
+ PreparingPlaybackState,
+} from "~/utils/tauri";
+
+export type {
+ PreparingEditorProgress,
+ PreparingPlaybackState,
+} from "~/utils/tauri";
+
+export type PreparingEditorSeed = {
+ title?: string;
+ tracks?: readonly ("display" | "camera" | "microphone" | "systemAudio")[];
+};
+
+export type PreparingEditorIdentity = {
+ requestEpoch: number;
+ jobId: string;
+};
+
+export type PreparingEditorSnapshot = PreparingEditorIdentity & {
+ sequence: number;
+ progress: PreparingEditorProgress;
+ playback: PreparingPlaybackState;
+ seed?: PreparingEditorSeed;
+};
+
+export type PreparingEditorController = {
+ seek: (seconds: number) => Promise<void>;
+ setPlaying: (playing: boolean) => Promise<void>;
+};
+
+export function preparingTimeline(progress: PreparingEditorProgress) {
+ const duration = progress.totalDuration;
+ const totalDuration =
+ duration !== null && Number.isFinite(duration) && duration > 0
+ ? duration
+ : null;
+ const confirmed = Number.isFinite(progress.playableUntil)
+ ? Math.max(0, progress.playableUntil)
+ : 0;
+ const playableUntil =
+ progress.phase === "unavailable" || totalDuration === null
+ ? 0
+ : Math.min(confirmed, totalDuration);
+ return {
+ totalDuration,
+ playableUntil,
+ fraction: totalDuration === null ? null : playableUntil / totalDuration,
+ };
+}
+
+export function preparingTime(seconds: number) {
+ const whole = Math.floor(Math.max(0, Number.isFinite(seconds) ? seconds : 0));
+ const hours = Math.floor(whole / 3600);
+ const minutes = Math.floor((whole % 3600) / 60);
+ const remainder = (whole % 60).toString().padStart(2, "0");
+ return hours > 0
+ ? `${hours}:${minutes.toString().padStart(2, "0")}:${remainder}`
+ : `${minutes}:${remainder}`;
+}
+
+function sameIdentity(
+ left: PreparingEditorIdentity | undefined,
+ right: PreparingEditorIdentity,
+) {
+ return (
+ left?.requestEpoch === right.requestEpoch && left.jobId === right.jobId
+ );
+}
+
+const waitingProgress = (): PreparingEditorProgress => ({
+ totalDuration: null,
+ playableUntil: 0,
+ previewAvailable: false,
+ phase: "preparing",
+});
+const waitingPlayback = (): PreparingPlaybackState => ({
+ playheadSeconds: 0,
+ playing: false,
+ buffering: false,
+});
+
+export function createPreparingEditorModel() {
+ const [progress, setProgress] = createSignal(waitingProgress());
+ const [playback, setPlayback] = createSignal(waitingPlayback());
+ const [seed, setSeed] = createSignal<PreparingEditorSeed>({});
+ const [controller, setController] = createSignal<PreparingEditorController>();
+ const [commandPending, setCommandPending] = createSignal(false);
+ const [commandError, setCommandError] = createSignal<string>();
+ const [rendered, setRendered] = createSignal(false);
+ let identity: PreparingEditorIdentity | undefined;
+ let sequence = -1;
+ let disposed = false;
+ let binding = 0;
+ let framesPerSecond = 0;
+ const timeline = createMemo(() => preparingTimeline(progress()));
+ const canPlay = createMemo(
+ () =>
+ !!controller() &&
+ progress().phase === "preparing" &&
+ progress().previewAvailable &&
+ rendered() &&
+ timeline().playableUntil > 0 &&
+ !commandPending(),
+ );
+ const execute = async (
+ operation: (value: PreparingEditorController) => Promise<void>,
+ ) => {
+ const current = controller();
+ if (!canPlay() || !current || disposed) return false;
+ const requestBinding = binding;
+ setCommandPending(true);
+ setCommandError(undefined);
+ try {
+ await operation(current);
+ return (
+ requestBinding === binding &&
+ !disposed &&
+ progress().phase === "preparing"
+ );
+ } catch (error) {
+ if (requestBinding === binding && !disposed) {
+ setCommandError(error instanceof Error ? error.message : String(error));
+ }
+ return false;
+ } finally {
+ if (requestBinding === binding && !disposed) setCommandPending(false);
+ }
+ };
+ return {
+ progress,
+ playback,
+ seed,
+ timeline,
+ canPlay,
+ commandPending,
+ commandError,
+ rendered,
+ setRendered,
+ bind(
+ next: PreparingEditorIdentity,
+ nextController: PreparingEditorController,
+ fps: number,
+ ) {
+ if (
+ disposed ||
+ !Number.isSafeInteger(fps) ||
+ fps <= 0 ||
+ fps > 0xffffffff ||
+ !Number.isSafeInteger(next.requestEpoch) ||
+ next.requestEpoch <= 0 ||
+ !next.jobId ||
+ identity
+ ) {
+ return false;
+ }
+ identity = { ...next };
+ framesPerSecond = fps;
+ binding++;
+ setController(() => nextController);
+ return true;
+ },
+ accept(snapshot: PreparingEditorSnapshot) {
+ if (
+ disposed ||
+ !sameIdentity(identity, snapshot) ||
+ !Number.isSafeInteger(snapshot.sequence) ||
+ snapshot.sequence <= sequence
+ ) {
+ return false;
+ }
+ sequence = snapshot.sequence;
+ const next = snapshot.progress;
+ const position = snapshot.playback;
+ if (
+ (next.totalDuration !== null &&
+ (!Number.isFinite(next.totalDuration) || next.totalDuration < 0)) ||
+ !Number.isFinite(next.playableUntil) ||
+ next.playableUntil < 0 ||
+ (next.totalDuration === null && next.playableUntil > 0) ||
+ (next.totalDuration !== null &&
+ next.playableUntil > next.totalDuration) ||
+ !Number.isFinite(position.playheadSeconds) ||
+ position.playheadSeconds < 0
+ ) {
+ batch(() => {
+ setProgress({ ...waitingProgress(), phase: "unavailable" });
+ setPlayback(waitingPlayback());
+ });
+ return false;
+ }
+ batch(() => {
+ setProgress({ ...next });
+ setPlayback({ ...position });
+ if (snapshot.seed) {
+ setSeed({
+ title: snapshot.seed.title,
+ tracks: snapshot.seed.tracks && [...snapshot.seed.tracks],
+ });
+ }
+ });
+ return true;
+ },
+ seek(seconds: number) {
+ if (!Number.isFinite(seconds) || seconds < 0)
+ return Promise.resolve(false);
+ const finalFrame =
+ Math.ceil(timeline().playableUntil * framesPerSecond) - 1;
+ if (
+ !Number.isSafeInteger(finalFrame) ||
+ finalFrame < 0 ||
+ finalFrame > 0xffffffff
+ )
+ return Promise.resolve(false);
+ const targetFrame = Math.min(
+ Math.floor(seconds * framesPerSecond),
+ finalFrame,
+ );
+ return execute((value) => value.seek(targetFrame / framesPerSecond));
+ },
+ setPlaying(playing: boolean) {
+ return execute(async (value) => {
+ const current = timeline();
+ if (
+ playing &&
+ current.totalDuration !== null &&
+ current.playableUntil === current.totalDuration &&
+ current.totalDuration - playback().playheadSeconds <= 0.1
+ ) {
+ await value.seek(0);
+ if (disposed || progress().phase !== "preparing") return;
+ }
+ await value.setPlaying(playing);
+ });
+ },
+ dispose() {
+ disposed = true;
+ binding++;
+ setController(undefined);
+ setCommandPending(false);
+ },
+ };
+}
+
+export type PreparingEditorModel = ReturnType<
+ typeof createPreparingEditorModel
+>;
diff --git a/apps/desktop/src/routes/editor/preparing-editor-subscription.test.ts b/apps/desktop/src/routes/editor/preparing-editor-subscription.test.ts
new file mode 100644
index 000000000..e4024bb4f
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-editor-subscription.test.ts
@@ -0,0 +1,198 @@
+import { createRoot } from "solid-js";
+import { describe, expect, it, vi } from "vitest";
+import type { PreparingEditorChanged } from "~/utils/tauri";
+import { createPreparingEditorModel } from "./preparing-editor-model";
+import { createPreparingEditorSubscription } from "./preparing-editor-subscription";
+
+vi.mock("solid-js", () =>
+ vi.importActual<typeof import("solid-js")>("solid-js/dist/solid.js"),
+);
+
+function state(sequence = 1): PreparingEditorChanged {
+ return {
+ requestEpoch: 19,
+ jobId: "current-job",
+ sequence,
+ fps: 30,
+ progress: {
+ totalDuration: 120,
+ playableUntil: 20,
+ previewAvailable: true,
+ phase: "preparing",
+ },
+ playback: { playheadSeconds: 0, playing: false, buffering: false },
+ seed: { title: "Recording", tracks: ["display"] },
+ };
+}
+
+function harness() {
+ let disposeOwner = () => {};
+ const model = createRoot((dispose) => {
+ disposeOwner = dispose;
+ return createPreparingEditorModel();
+ });
+ const unlisten = vi.fn();
+ let emit = (_snapshot: PreparingEditorChanged) => {};
+ const listen = vi.fn(async (accept: typeof emit): Promise<() => void> => {
+ emit = accept;
+ return unlisten;
+ });
+ const getState = vi.fn(
+ async (): Promise<PreparingEditorChanged | null> => state(),
+ );
+ const seek = vi.fn(async (_seconds: number) => {});
+ const subscription = createPreparingEditorSubscription({
+ requestEpoch: 19,
+ model,
+ listen,
+ getState,
+ controller: () => ({ seek, setPlaying: async () => {} }),
+ });
+ return {
+ model,
+ subscription,
+ listen,
+ unlisten,
+ getState,
+ seek,
+ emit: (value: PreparingEditorChanged) => emit(value),
+ dispose() {
+ subscription.dispose();
+ model.dispose();
+ disposeOwner();
+ },
+ };
+}
+
+describe("preparing editor native subscription", () => {
+ it("uses the actual bound FPS and accepts only this request epoch", async () => {
+ const value = harness();
+ await value.subscription.listen();
+ value.emit({ ...state(), requestEpoch: 18 });
+ expect(value.model.progress().totalDuration).toBeNull();
+ value.emit(state());
+ value.model.setRendered(true);
+ expect(await value.model.seek(20)).toBe(true);
+ expect(value.seek).toHaveBeenCalledWith(599 / 30);
+ value.dispose();
+ });
+
+ it("catches an offer before URL attachment without reverting a newer event", async () => {
+ const value = harness();
+ await value.subscription.listen();
+ const latest = state(3);
+ latest.progress.playableUntil = 40;
+ value.emit(latest);
+ expect(await value.subscription.refresh()).toBe(false);
+ expect(value.model.timeline().playableUntil).toBe(40);
+ value.dispose();
+ });
+
+ it("loads the retained native state when the offer precedes the event listener", async () => {
+ const value = harness();
+ await value.subscription.listen();
+ expect(await value.subscription.refresh()).toBe(true);
+ expect(value.model.timeline().playableUntil).toBe(20);
+ value.dispose();
+ });
+
+ it("never rebinds to another job or FPS after admission", async () => {
+ const value = harness();
+ await value.subscription.listen();
+ value.emit(state());
+ value.emit({ ...state(2), jobId: "stale-job" });
+ value.emit({ ...state(3), fps: 60 });
+ expect(value.model.progress()).toEqual(state().progress);
+ expect(
+ value.subscription.accept({
+ ...state(4),
+ progress: { ...state().progress, phase: "handoff" },
+ }),
+ ).toBe(true);
+ value.dispose();
+ });
+
+ it("consumes the joined final snapshot before ordinary handoff without waiting for events", () => {
+ const value = harness();
+ const final = state(8);
+ final.progress.phase = "handoff";
+ final.playback = { playheadSeconds: 19.5, playing: true, buffering: false };
+ expect(value.subscription.accept(final)).toBe(true);
+ expect(value.model.playback()).toEqual(final.playback);
+ expect(value.model.canPlay()).toBe(false);
+ value.dispose();
+ });
+
+ it("narrows native track names without adding undeclared tracks", () => {
+ const value = harness();
+ const next = state();
+ next.seed.tracks = ["display", "future-track", "microphone"];
+ value.subscription.accept(next);
+ expect(value.model.seed().tracks).toEqual(["display", "microphone"]);
+ value.dispose();
+ });
+
+ it("cleans a listener that resolves after the window owner closes", async () => {
+ const value = harness();
+ let resolve!: (cleanup: () => void) => void;
+ value.listen.mockImplementation(
+ () =>
+ new Promise((ready) => {
+ resolve = ready;
+ }),
+ );
+ const pending = value.subscription.listen();
+ value.dispose();
+ resolve(value.unlisten);
+ expect(await pending).toBe(false);
+ expect(value.unlisten).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores a late retained-state response after the window owner closes", async () => {
+ const value = harness();
+ let resolve!: (snapshot: PreparingEditorChanged) => void;
+ value.getState.mockImplementation(
+ () =>
+ new Promise((ready) => {
+ resolve = ready;
+ }),
+ );
+ const pending = value.subscription.refresh();
+ value.dispose();
+ resolve(state());
+ expect(await pending).toBe(false);
+ expect(value.model.progress().totalDuration).toBeNull();
+ });
+
+ it("does not create duplicate listeners and cleans successful registration once", async () => {
+ const value = harness();
+ expect(await value.subscription.listen()).toBe(true);
+ expect(await value.subscription.listen()).toBe(true);
+ expect(value.listen).toHaveBeenCalledTimes(1);
+ value.dispose();
+ value.subscription.dispose();
+ expect(value.unlisten).toHaveBeenCalledTimes(1);
+ });
+
+ it("declines a listener setup failure without starting a transport", async () => {
+ const value = harness();
+ value.listen.mockRejectedValue(new Error("window ended"));
+ expect(await value.subscription.listen()).toBe(false);
+ expect(value.getState).not.toHaveBeenCalled();
+ expect(value.model.canPlay()).toBe(false);
+ value.dispose();
+ });
+ it("releases the native listener after failed admission but accepts the joined synchronous snapshot", async () => {
+ const value = harness();
+ await value.subscription.listen();
+ value.subscription.stopListening();
+ expect(value.unlisten).toHaveBeenCalledTimes(1);
+ const final = state(2);
+ final.progress.phase = "handoff";
+ final.playback.playheadSeconds = 12;
+ expect(value.subscription.accept(final)).toBe(true);
+ expect(value.model.playback().playheadSeconds).toBe(12);
+ value.dispose();
+ expect(value.unlisten).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/routes/editor/preparing-editor-subscription.ts b/apps/desktop/src/routes/editor/preparing-editor-subscription.ts
new file mode 100644
index 000000000..14f46a653
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-editor-subscription.ts
@@ -0,0 +1,90 @@
+import type { PreparingEditorChanged } from "~/utils/tauri";
+import type {
+ PreparingEditorController,
+ PreparingEditorModel,
+ PreparingEditorSeed,
+} from "./preparing-editor-model";
+
+function supportedTrack(
+ track: string,
+): track is NonNullable<PreparingEditorSeed["tracks"]>[number] {
+ return (
+ track === "display" ||
+ track === "camera" ||
+ track === "microphone" ||
+ track === "systemAudio"
+ );
+}
+
+export function createPreparingEditorSubscription(options: {
+ requestEpoch: number;
+ model: PreparingEditorModel;
+ listen: (
+ accept: (snapshot: PreparingEditorChanged) => void,
+ ) => Promise<() => void>;
+ getState: () => Promise<PreparingEditorChanged | null>;
+ controller: (jobId: string) => PreparingEditorController;
+}) {
+ let active = true;
+ let listening: Promise<boolean> | undefined;
+ let unlisten: (() => void) | undefined;
+ let binding: { jobId: string; fps: number } | undefined;
+ const accept = (snapshot: PreparingEditorChanged | null) => {
+ if (!active || !snapshot || snapshot.requestEpoch !== options.requestEpoch)
+ return false;
+ if (!binding) {
+ if (
+ !options.model.bind(
+ snapshot,
+ options.controller(snapshot.jobId),
+ snapshot.fps,
+ )
+ )
+ return false;
+ binding = { jobId: snapshot.jobId, fps: snapshot.fps };
+ }
+ if (snapshot.jobId !== binding.jobId || snapshot.fps !== binding.fps)
+ return false;
+ return options.model.accept({
+ ...snapshot,
+ seed: {
+ title: snapshot.seed.title,
+ tracks: snapshot.seed.tracks.filter(supportedTrack),
+ },
+ });
+ };
+ return {
+ accept,
+ listen() {
+ listening ??= options
+ .listen(accept)
+ .then((cleanup) => {
+ if (!active) {
+ cleanup();
+ return false;
+ }
+ unlisten = cleanup;
+ return true;
+ })
+ .catch(() => false);
+ return listening;
+ },
+ async refresh() {
+ if (!active) return false;
+ try {
+ return accept(await options.getState());
+ } catch {
+ return false;
+ }
+ },
+ stopListening() {
+ unlisten?.();
+ unlisten = undefined;
+ },
+ dispose() {
+ active = false;
+ unlisten?.();
+ unlisten = undefined;
+ },
+ };
+}
diff --git a/apps/desktop/src/routes/editor/preparing-frame-lease.test.ts b/apps/desktop/src/routes/editor/preparing-frame-lease.test.ts
new file mode 100644
index 000000000..5933c0df5
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-frame-lease.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it, vi } from "vitest";
+import { createPreparingFrameLease } from "./preparing-frame-lease";
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { resolve, promise };
+}
+
+describe("preparing frame lease", () => {
+ it("retires late admission after unmount without attaching its socket", async () => {
+ const admission = deferred<string | null>();
+ const start = vi.fn((_epoch: number) => admission.promise);
+ const stop = vi.fn(async (_epoch: number) => {});
+ const attach = vi.fn(() => ({ dispose() {} }));
+ const lease = createPreparingFrameLease({
+ start,
+ stop,
+ attach,
+ ended() {},
+ });
+ const pending = lease.start();
+ lease.close();
+ admission.resolve("ws://old");
+ await pending;
+ expect(attach).not.toHaveBeenCalled();
+ expect(stop.mock.calls).toEqual([
+ [start.mock.calls[0][0]],
+ [start.mock.calls[0][0]],
+ ]);
+ });
+
+ it("keeps old cleanup and late frames scoped when a new skeleton mounts", async () => {
+ const epochs: number[] = [];
+ const stopped: number[] = [];
+ const accepts: Array<() => boolean> = [];
+ const dispose = vi.fn();
+ const options = {
+ start: async (epoch: number) => {
+ epochs.push(epoch);
+ return "ws://owned";
+ },
+ stop: async (epoch: number) => {
+ stopped.push(epoch);
+ },
+ attach: (_url: string, isActive: () => boolean) => {
+ accepts.push(isActive);
+ return { dispose };
+ },
+ ended() {},
+ };
+ const old = createPreparingFrameLease(options);
+ await old.start();
+ old.close();
+ const next = createPreparingFrameLease(options);
+ await next.start();
+ old.close();
+ expect(accepts.map((accept) => accept())).toEqual([false, true]);
+ expect(stopped).toEqual([epochs[0]]);
+ expect(epochs[1]).toBeGreaterThan(epochs[0]);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ next.close();
+ });
+
+ it("disposes a connection whose attach synchronously closes the owner", async () => {
+ const dispose = vi.fn();
+ const stop = vi.fn(async (_epoch: number) => {});
+ const lease = createPreparingFrameLease({
+ start: async () => "ws://owned",
+ stop,
+ attach: () => {
+ lease.close();
+ return { dispose };
+ },
+ ended() {},
+ });
+ await lease.start();
+ expect(lease.isActive()).toBe(false);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(stop).toHaveBeenCalledTimes(1);
+ });
+
+ it("decline and command failure keep the existing skeleton and retire once", async () => {
+ for (const start of [
+ async () => null,
+ async () => {
+ throw new Error("closed");
+ },
+ ]) {
+ const ended = vi.fn();
+ const stop = vi.fn(async (_epoch: number) => {});
+ const attach = vi.fn(() => ({ dispose() {} }));
+ const lease = createPreparingFrameLease({ start, stop, attach, ended });
+ await lease.start();
+ await lease.start();
+ lease.close();
+ expect(attach).not.toHaveBeenCalled();
+ expect(ended).toHaveBeenCalledTimes(1);
+ expect(stop).toHaveBeenCalledTimes(1);
+ }
+ });
+ it("holds a displayed first frame before disposal and keeps the spinner when no frame arrived", async () => {
+ for (const frameArrived of [true, false]) {
+ const calls: string[] = [];
+ const ended = vi.fn();
+ const lease = createPreparingFrameLease({
+ start: async () => "ws://owned",
+ stop: async () => {},
+ attach: () => ({
+ preserveFrame() {
+ calls.push("preserve");
+ return frameArrived;
+ },
+ dispose() {
+ calls.push("dispose");
+ },
+ }),
+ ended,
+ });
+ await lease.start();
+ lease.finish();
+ expect(calls).toEqual(["preserve", "dispose"]);
+ expect(ended).toHaveBeenCalledWith(frameArrived);
+ expect(lease.isActive()).toBe(false);
+ lease.close();
+ expect(ended).toHaveBeenCalledTimes(1);
+ }
+ });
+});
diff --git a/apps/desktop/src/routes/editor/preparing-frame-lease.ts b/apps/desktop/src/routes/editor/preparing-frame-lease.ts
new file mode 100644
index 000000000..fe5a793fa
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-frame-lease.ts
@@ -0,0 +1,60 @@
+let nextEpoch = 0;
+
+type PreparingTransport = {
+ dispose: () => void;
+ preserveFrame?: () => boolean;
+};
+
+export function createPreparingFrameLease(options: {
+ start: (epoch: number) => Promise<string | null>;
+ stop: (epoch: number) => Promise<unknown>;
+ attach: (url: string, isActive: () => boolean) => PreparingTransport;
+ ended: (retainedFrame: boolean) => void;
+}) {
+ const epoch = ++nextEpoch;
+ let active = true;
+ let started = false;
+ let transport: PreparingTransport | undefined;
+ const stop = () => {
+ void options.stop(epoch).catch(() => {});
+ };
+ const terminate = (preserveFrame: boolean) => {
+ if (!active) return;
+ active = false;
+ let retainedFrame = false;
+ try {
+ retainedFrame = preserveFrame && (transport?.preserveFrame?.() ?? false);
+ } catch {}
+ transport?.dispose();
+ transport = undefined;
+ options.ended(retainedFrame);
+ stop();
+ };
+ const close = () => terminate(false);
+ return {
+ requestEpoch: epoch,
+ isActive: () => active,
+ close,
+ finish: () => terminate(true),
+ async start() {
+ if (started || !active) return;
+ started = true;
+ try {
+ const url = await options.start(epoch);
+ if (!active) {
+ stop();
+ return;
+ }
+ if (!url) {
+ close();
+ return;
+ }
+ const attached = options.attach(url, () => active);
+ if (active) transport = attached;
+ else attached.dispose();
+ } catch {
+ close();
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/routes/editor/preparing-frame-transport.test.ts b/apps/desktop/src/routes/editor/preparing-frame-transport.test.ts
new file mode 100644
index 000000000..9f1cbd781
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-frame-transport.test.ts
@@ -0,0 +1,285 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createPreparingFrameLease } from "~/routes/editor/preparing-frame-lease";
+import { createImageDataWS } from "~/utils/socket";
+import { attachPreparingFrameTransport } from "./preparing-frame-transport";
+
+const sockets = vi.hoisted(() => {
+ class Socket extends EventTarget {
+ static readonly CONNECTING = 0;
+ static readonly OPEN = 1;
+ static readonly CLOSING = 2;
+ static readonly CLOSED = 3;
+ static instances: Socket[] = [];
+ readyState = Socket.OPEN;
+ binaryType = "blob";
+ onmessage: ((event: { data: ArrayBuffer }) => void) | null = null;
+ constructor(readonly url: string) {
+ super();
+ Socket.instances.push(this);
+ }
+ close() {
+ if (this.readyState === Socket.CLOSED) return;
+ this.readyState = Socket.CLOSED;
+ this.dispatchEvent(new Event("close"));
+ }
+ fail() {
+ this.dispatchEvent(new Event("error"));
+ }
+ frame(bytes: ArrayBuffer) {
+ this.onmessage?.({ data: bytes });
+ }
+ }
+ return { Socket };
+});
+
+vi.mock("@solid-primitives/websocket", () => ({
+ createWS: (url: string) => new sockets.Socket(url),
+}));
+vi.mock("~/utils/frame-worker?worker", () => ({
+ default: class {
+ constructor() {
+ throw new Error(
+ "The first-frame direct canvas must not allocate a worker",
+ );
+ }
+ },
+}));
+vi.mock("~/utils/stride-correction-worker?worker", () => ({
+ default: class {
+ constructor() {
+ throw new Error(
+ "The tightly packed native test frame needs no stride worker",
+ );
+ }
+ },
+}));
+
+class Pixels {
+ readonly data: Uint8ClampedArray;
+ constructor(
+ readonly width: number,
+ readonly height: number,
+ ) {
+ this.data = new Uint8ClampedArray(width * height * 4);
+ }
+}
+
+class Canvas {
+ width = 0;
+ height = 0;
+ isConnected = true;
+ pixels: number[] = [];
+ getContext() {
+ return {
+ putImageData: (image: Pixels) => {
+ this.pixels = Array.from(image.data);
+ },
+ };
+ }
+ asElement() {
+ return this as unknown as HTMLCanvasElement;
+ }
+}
+
+const rgba = [29, 61, 127, 255];
+let scheduled: Map<number, FrameRequestCallback>;
+let nextFrame: number;
+
+function packedFrame(pixels = rgba, frameNumber = 0, targetTimeNs = 0n) {
+ const buffer = new ArrayBuffer(rgba.length + 24);
+ new Uint8Array(buffer).set(pixels);
+ const metadata = new DataView(buffer, rgba.length, 24);
+ metadata.setUint32(0, 4, true);
+ metadata.setUint32(4, 1, true);
+ metadata.setUint32(8, 1, true);
+ metadata.setUint32(12, frameNumber, true);
+ metadata.setBigUint64(16, targetTimeNs, true);
+ return buffer;
+}
+
+function renderScheduledFrame() {
+ const callbacks = Array.from(scheduled.values());
+ scheduled.clear();
+ for (const callback of callbacks) callback(performance.now());
+}
+
+async function mount() {
+ const canvas = new Canvas();
+ const retainedCanvas = new Canvas();
+ const rendered = vi.fn();
+ const frame = vi.fn();
+ const ended = vi.fn();
+ const stop = vi.fn(async (_epoch: number) => {});
+ const lease = createPreparingFrameLease({
+ start: async () => "ws://127.0.0.1/owned",
+ stop,
+ ended,
+ attach: (url, isActive) =>
+ attachPreparingFrameTransport({
+ url,
+ canvas: canvas.asElement(),
+ retainedCanvas: retainedCanvas.asElement(),
+ isActive,
+ onRendered: rendered,
+ onFrame: frame,
+ onTerminal: () => lease.finish(),
+ }),
+ });
+ await lease.start();
+ const socket = sockets.Socket.instances.at(-1);
+ if (!socket)
+ throw new Error("Expected the actual socket utility to create a websocket");
+ return {
+ canvas,
+ retainedCanvas,
+ rendered,
+ frame,
+ ended,
+ stop,
+ lease,
+ socket,
+ };
+}
+
+beforeEach(() => {
+ sockets.Socket.instances = [];
+ scheduled = new Map();
+ nextFrame = 0;
+ vi.stubGlobal("WebSocket", sockets.Socket);
+ vi.stubGlobal("ImageData", Pixels);
+ vi.stubGlobal("navigator", {});
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ const id = ++nextFrame;
+ scheduled.set(id, callback);
+ return id;
+ });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => scheduled.delete(id));
+});
+
+afterEach(() => {
+ for (const socket of sockets.Socket.instances) socket.close();
+ vi.unstubAllGlobals();
+});
+
+describe("preparing transport with the actual socket utility", () => {
+ it("demonstrates that a later terminal listener cannot copy the disposed socket frame", () => {
+ const canvas = new Canvas();
+ const retainedCanvas = new Canvas();
+ const [socket, , , controls] = createImageDataWS(
+ "ws://old-order",
+ () => {},
+ );
+ controls.initDirectCanvas(canvas.asElement());
+ let copied: boolean | undefined;
+ socket.addEventListener("close", () => {
+ copied = controls.drawLatestFrameToCanvas(retainedCanvas.asElement());
+ });
+ const source = sockets.Socket.instances[0];
+ source.frame(packedFrame());
+ renderScheduledFrame();
+ expect(canvas.pixels).toEqual(rgba);
+ source.close();
+ expect(copied).toBe(false);
+ expect(retainedCanvas.pixels).toEqual([]);
+ });
+
+ it.each(["close", "error"] as const)(
+ "retains exact displayed pixels through earlier socket %s cleanup",
+ async (event) => {
+ const mounted = await mount();
+ mounted.socket.frame(packedFrame());
+ expect(mounted.rendered).not.toHaveBeenCalled();
+ renderScheduledFrame();
+ expect(mounted.canvas.pixels).toEqual(rgba);
+ expect(mounted.retainedCanvas.pixels).toEqual(rgba);
+ expect(mounted.rendered).toHaveBeenLastCalledWith(true);
+ if (event === "close") mounted.socket.close();
+ else mounted.socket.fail();
+ expect(mounted.ended).toHaveBeenCalledWith(true);
+ expect(mounted.retainedCanvas.pixels).toEqual(rgba);
+ expect(mounted.lease.isActive()).toBe(false);
+ expect(mounted.stop).toHaveBeenCalledTimes(1);
+ mounted.lease.close();
+ expect(mounted.stop).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("acknowledges the exact nonzero RGBA identity only after the scheduled pixels render", async () => {
+ const mounted = await mount();
+ mounted.socket.frame(packedFrame(rgba, 315, 10_500_000_000n));
+ expect(mounted.frame).not.toHaveBeenCalled();
+ renderScheduledFrame();
+ expect(mounted.frame).toHaveBeenLastCalledWith({
+ width: 1,
+ height: 1,
+ renderedFrame: { frameNumber: 315, targetTimeNs: 10_500_000_000n },
+ });
+ mounted.lease.close();
+ });
+
+ it("carries exact NV12 identity through the actual fallback draw", async () => {
+ const mounted = await mount();
+ const buffer = new ArrayBuffer(6 + 28);
+ new Uint8Array(buffer).set([16, 16, 16, 16, 128, 128]);
+ const metadata = new DataView(buffer, 6, 28);
+ metadata.setUint32(0, 2, true);
+ metadata.setUint32(4, 2, true);
+ metadata.setUint32(8, 2, true);
+ metadata.setUint32(12, 216000, true);
+ metadata.setBigUint64(16, 7_200_000_000_000n, true);
+ metadata.setUint32(24, 0x4e563132, true);
+ mounted.socket.frame(buffer);
+ expect(mounted.frame).not.toHaveBeenCalled();
+ renderScheduledFrame();
+ expect(mounted.frame).toHaveBeenLastCalledWith({
+ width: 2,
+ height: 2,
+ renderedFrame: { frameNumber: 216000, targetTimeNs: 7_200_000_000_000n },
+ });
+ expect(mounted.canvas.pixels).toEqual([
+ 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255,
+ ]);
+ mounted.lease.close();
+ });
+
+ it("retains the latest displayed frame rather than the first frame when playback ends", async () => {
+ const mounted = await mount();
+ mounted.socket.frame(packedFrame());
+ renderScheduledFrame();
+ const later = [200, 151, 80, 255];
+ mounted.socket.frame(packedFrame(later));
+ renderScheduledFrame();
+ expect(mounted.canvas.pixels).toEqual(later);
+ expect(mounted.retainedCanvas.pixels).toEqual(rgba);
+ mounted.socket.close();
+ expect(mounted.retainedCanvas.pixels).toEqual(later);
+ expect(mounted.ended).toHaveBeenCalledWith(true);
+ });
+
+ it("keeps the ordinary spinner when finalization ends before a queued frame renders", async () => {
+ const mounted = await mount();
+ mounted.socket.frame(packedFrame());
+ expect(scheduled.size).toBe(1);
+ mounted.socket.close();
+ renderScheduledFrame();
+ expect(mounted.rendered).not.toHaveBeenCalled();
+ expect(mounted.ended).toHaveBeenCalledWith(false);
+ expect(mounted.retainedCanvas.pixels).toEqual([]);
+ });
+
+ it("cannot attach old pixels to a new lease after the first skeleton unmounts", async () => {
+ const old = await mount();
+ old.socket.frame(packedFrame());
+ old.lease.close();
+ const next = await mount();
+ renderScheduledFrame();
+ expect(old.rendered).not.toHaveBeenCalled();
+ expect(old.retainedCanvas.pixels).toEqual([]);
+ expect(next.retainedCanvas.pixels).toEqual([]);
+ expect(next.lease.isActive()).toBe(true);
+ next.socket.frame(packedFrame());
+ renderScheduledFrame();
+ expect(next.retainedCanvas.pixels).toEqual(rgba);
+ next.lease.close();
+ });
+});
diff --git a/apps/desktop/src/routes/editor/preparing-frame-transport.ts b/apps/desktop/src/routes/editor/preparing-frame-transport.ts
new file mode 100644
index 000000000..2f165f431
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-frame-transport.ts
@@ -0,0 +1,47 @@
+import { createImageDataWS, type FrameData } from "~/utils/socket";
+
+export function attachPreparingFrameTransport(options: {
+ url: string;
+ canvas: HTMLCanvasElement;
+ retainedCanvas: HTMLCanvasElement;
+ isActive: () => boolean;
+ onRendered: (rendered: boolean) => void;
+ onFrame?: (frame: FrameData) => void;
+ onTerminal: () => void;
+}) {
+ let preservedFrame = false;
+ const [socket, , , controls] = createImageDataWS(
+ options.url,
+ (frame) => {
+ if (!options.isActive()) return;
+ const rendered = controls.hasRenderedFrame();
+ if (rendered && !preservedFrame) {
+ preservedFrame = controls.drawLatestFrameToCanvas(
+ options.retainedCanvas,
+ );
+ }
+ options.onRendered(rendered);
+ if (frame.renderedFrame) options.onFrame?.(frame);
+ },
+ undefined,
+ { retainLastFrameOnDispose: options.retainedCanvas },
+ );
+ controls.initDirectCanvas(options.canvas);
+ const close = () => options.onTerminal();
+ socket.addEventListener("close", close);
+ socket.addEventListener("error", close);
+ return {
+ preserveFrame() {
+ return (
+ controls.drawLatestFrameToCanvas(options.retainedCanvas) ||
+ preservedFrame
+ );
+ },
+ dispose() {
+ socket.removeEventListener("close", close);
+ socket.removeEventListener("error", close);
+ controls.dispose();
+ socket.close();
+ },
+ };
+}
diff --git a/apps/desktop/src/routes/editor/preparing-frame.tsx b/apps/desktop/src/routes/editor/preparing-frame.tsx
new file mode 100644
index 000000000..ca8699bbd
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-frame.tsx
@@ -0,0 +1,35 @@
+import { createEffect, onCleanup, Show } from "solid-js";
+import { usePreparingEditor } from "./preparing-editor-context";
+
+export function PreparingFrame(props: { fallback?: boolean } = {}) {
+ const session = usePreparingEditor();
+ let host!: HTMLDivElement;
+ createEffect(() => {
+ const pair = session?.canvases();
+ if (!pair) return;
+ host.append(pair.active, pair.retained);
+ onCleanup(() => {
+ if (pair.active.parentElement === host) pair.active.remove();
+ if (pair.retained.parentElement === host) pair.retained.remove();
+ });
+ });
+ return (
+ <div
+ ref={host}
+ class="relative flex items-center justify-center w-full h-full min-h-0"
+ >
+ <Show
+ when={
+ props.fallback !== false &&
+ !session?.model.rendered() &&
+ !session?.retained()
+ }
+ >
+ <div class="flex flex-col gap-3 justify-center items-center w-full max-w-[85%] rounded-md aspect-video bg-ed-ctl">
+ <IconCapLogo class="size-12 text-ed-text-3 opacity-50" />
+ <span class="text-xs text-ed-text-3">Preparing your recording</span>
+ </div>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/preparing-handoff.test.ts b/apps/desktop/src/routes/editor/preparing-handoff.test.ts
new file mode 100644
index 000000000..ad28c6938
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-handoff.test.ts
@@ -0,0 +1,494 @@
+import { describe, expect, it, vi } from "vitest";
+import type { FrameData } from "~/utils/socket";
+import { createPreparingHandoff } from "./preparing-handoff";
+import { createPreparingPlaybackHandoff } from "./preparing-playback-handoff";
+
+function deferred() {
+ let resolve!: (value: boolean) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<boolean>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+const position = { playheadSeconds: 10.5, playing: true, buffering: false };
+const bounds = { width: 787, height: 462 };
+function frame(frameNumber: number): FrameData {
+ return {
+ width: 1196,
+ height: 702,
+ renderedFrame: { frameNumber, targetTimeNs: 10_500_000_000n },
+ };
+}
+
+describe("preparing frame handoff", () => {
+ it("freezes the nonzero target and retains playing intent across later progress", () => {
+ const handoff = createPreparingHandoff();
+ expect(handoff.begin(position, 30)).toEqual({
+ frameNumber: 315,
+ playback: position,
+ });
+ position.playheadSeconds = 11;
+ expect(handoff.begin(position, 30)?.frameNumber).toBe(315);
+ expect(handoff.target()?.playback).toEqual({
+ playheadSeconds: 10.5,
+ playing: true,
+ buffering: false,
+ });
+ position.playheadSeconds = 10.5;
+ });
+
+ it.each([
+ { duration: 120, fps: 30, expected: 3599 },
+ { duration: 120.01, fps: 30, expected: 3600 },
+ { duration: 0.01, fps: 30, expected: 0 },
+ ])(
+ "keeps an end playhead separate from the last valid image at $duration seconds",
+ ({ duration, fps, expected }) => {
+ const handoff = createPreparingHandoff();
+ const end = {
+ playheadSeconds: duration,
+ playing: false,
+ buffering: false,
+ };
+ expect(handoff.begin(end, fps, duration)).toEqual({
+ frameNumber: expected,
+ playback: end,
+ });
+ expect(handoff.accept(frame(Math.ceil(duration * fps)), bounds)).toBe(
+ false,
+ );
+ expect(handoff.accept(frame(expected), bounds)).toBe(true);
+ },
+ );
+
+ it("rejects queued, stale and differently targeted frames even if an earlier frame rendered", () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30);
+ expect(handoff.accept({ width: 1196, height: 702 }, bounds)).toBe(false);
+ expect(handoff.accept(frame(0), bounds)).toBe(false);
+ expect(handoff.accept(frame(314), bounds)).toBe(false);
+ expect(handoff.accept(frame(315), bounds)).toBe(true);
+ expect(handoff.accept(frame(315), bounds)).toBe(false);
+ });
+
+ it("does not remove retained footage before positive actual output bounds exist", () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30);
+ for (const invalid of [
+ { width: 0, height: 462 },
+ { width: 787, height: Number.NaN },
+ { width: -1, height: 462 },
+ ]) {
+ expect(handoff.accept(frame(315), invalid)).toBe(false);
+ }
+ expect(handoff.accept(frame(315), bounds)).toBe(true);
+ });
+
+ it("replaces the pending target when an ordinary scrub supersedes initial handoff", () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30, 120);
+ expect(handoff.requestFrame(45)).toBe(45);
+ expect(handoff.accept(frame(315), bounds)).toBe(false);
+ expect(handoff.accept(frame(45), bounds)).toBe(true);
+ expect(handoff.target()?.playback.playheadSeconds).toBe(10.5);
+ expect(handoff.requestFrame(3600)).toBe(3600);
+ });
+
+ it("keeps the first ordinary end request clamped without changing later ordinary behavior", () => {
+ const handoff = createPreparingHandoff();
+ expect(handoff.requestFrame(3600)).toBe(3600);
+ handoff.begin({ ...position, playheadSeconds: 120 }, 30, 120);
+ expect(handoff.requestFrame(3600)).toBe(3599);
+ expect(handoff.requestedFrame()).toBe(3599);
+ expect(handoff.accept(frame(3599), bounds)).toBe(true);
+ expect(handoff.requestFrame(3600)).toBe(3600);
+ });
+
+ it("accepts a real advancing ordinary frame when playback skips its starting frame", () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30, 120);
+ handoff.setAdvancing(true, 315);
+ expect(handoff.accept(frame(314), bounds)).toBe(false);
+ expect(handoff.accept(frame(3600), bounds)).toBe(false);
+ expect(handoff.accept(frame(319), bounds)).toBe(true);
+ });
+
+ it("returns to an exact paused frame after playback changes before replacement", () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30, 120);
+ handoff.setAdvancing(true, 315);
+ handoff.setAdvancing(false, 340);
+ expect(handoff.accept(frame(339), bounds)).toBe(false);
+ expect(handoff.accept(frame(341), bounds)).toBe(false);
+ expect(handoff.accept(frame(340), bounds)).toBe(true);
+ });
+
+ it("keeps unknown or unrepresentable targets out of the frame replacement latch", () => {
+ const handoff = createPreparingHandoff();
+ for (const fps of [0, Number.NaN, Number.POSITIVE_INFINITY])
+ expect(handoff.begin(position, fps)).toBeUndefined();
+ expect(
+ handoff.begin({ ...position, playheadSeconds: 1e15 }, 30),
+ ).toBeUndefined();
+ expect(handoff.accept(frame(0), bounds)).toBe(false);
+ expect(
+ handoff.begin({ ...position, playheadSeconds: 0 }, 30)?.frameNumber,
+ ).toBe(0);
+ });
+ it("uses final recording duration for both actual frame and displayed position", () => {
+ const handoff = createPreparingHandoff();
+ const target = handoff.begin(
+ { playheadSeconds: 10.05, playing: false, buffering: false },
+ 60,
+ 10,
+ );
+ expect(target?.frameNumber).toBe(599);
+ expect(target?.playback.playheadSeconds).toBe(10);
+ });
+ it("continues exact frame checks for a newer seek while playback start is pending after image handoff", () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30, 120);
+ expect(handoff.accept(frame(315), bounds)).toBe(true);
+ handoff.requestFrame(60, true);
+ expect(handoff.matches(frame(315), bounds)).toBe(false);
+ expect(handoff.matches(frame(60), { width: 0, height: 462 })).toBe(false);
+ expect(handoff.matches(frame(60), bounds)).toBe(true);
+ expect(handoff.accept(frame(60), bounds)).toBe(false);
+ });
+});
+
+describe("preparing frame approval", () => {
+ it("holds a late native commit until an adopted pause receives its next presented frame", async () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30, 120, "first");
+ handoff.setAdvancing(true, 315);
+ const nativeCommit = deferred();
+ const nativePause = deferred();
+ const fallbackReady = deferred();
+ const start = vi.fn(async () => {});
+ const stop = vi.fn(async () => {});
+ const stopNativePlayback = vi.fn(async () => {});
+ const changed = vi.fn();
+ const settled = vi.fn();
+ const failed = vi.fn();
+ const playback = createPreparingPlaybackHandoff({
+ initial: { frameNumber: 315, playing: true },
+ start,
+ stop,
+ changed,
+ settled,
+ failed,
+ });
+ const approval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => nativeCommit.promise,
+ );
+ if (!approval) throw new Error("Initial frame did not request approval");
+ const oldSettlement = approval.then((accepted) => {
+ if (accepted) playback.acknowledge(315, true);
+ return accepted;
+ });
+ const releaseFrames = handoff.holdFrames();
+ const pause = nativePause.promise.catch(async (error: unknown) => {
+ expect(error).toEqual(new Error("Preparing playback has been adopted"));
+ await stopNativePlayback();
+ handoff.requestFrame(315, true);
+ const pending = playback.request({ frameNumber: 315, playing: false });
+ if (!pending) throw new Error("Pause lost its pending playback owner");
+ releaseFrames();
+ fallbackReady.resolve(true);
+ return pending;
+ });
+ const blockedApproval = vi.fn(async () => true);
+ expect(
+ handoff.commitFrame(frame(316), bounds, blockedApproval),
+ ).toBeUndefined();
+ expect(blockedApproval).not.toHaveBeenCalled();
+ nativeCommit.resolve(true);
+ expect(await oldSettlement).toBe(false);
+ expect(playback.active()).toBe(true);
+ expect(start).not.toHaveBeenCalled();
+ expect(settled).not.toHaveBeenCalled();
+ nativePause.reject(new Error("Preparing playback has been adopted"));
+ expect(await fallbackReady.promise).toBe(true);
+ expect(playback.intent()).toEqual({ frameNumber: 315, playing: false });
+ expect(settled).not.toHaveBeenCalled();
+ expect(
+ await handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBe(true);
+ playback.acknowledge(315, true);
+ expect(await pause).toBe(true);
+ expect(settled).toHaveBeenCalledTimes(1);
+ expect(settled).toHaveBeenCalledWith({
+ frameNumber: 315,
+ playing: false,
+ });
+ expect(changed).toHaveBeenLastCalledWith(
+ { frameNumber: 315, playing: false },
+ false,
+ );
+ expect(playback.active()).toBe(false);
+ expect(start).not.toHaveBeenCalled();
+ expect(stop).not.toHaveBeenCalled();
+ expect(stopNativePlayback).toHaveBeenCalledTimes(1);
+ expect(failed).not.toHaveBeenCalled();
+ });
+
+ it("keeps overlapping holds across replacement and ignores duplicate releases", async () => {
+ const handoff = createPreparingHandoff();
+ handoff.begin(position, 30, 120, "first");
+ const original = deferred();
+ const oldApproval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => original.promise,
+ );
+ expect(oldApproval).toBeDefined();
+ const releaseFirst = handoff.holdFrames();
+ const releaseSecond = handoff.holdFrames();
+ handoff.begin({ ...position, playheadSeconds: 2 }, 30, 120, "second");
+ const blockedApproval = vi.fn(async () => true);
+ expect(
+ handoff.commitFrame(frame(60), bounds, blockedApproval),
+ ).toBeUndefined();
+ expect(releaseFirst()).toBe(true);
+ expect(releaseFirst()).toBe(false);
+ expect(
+ handoff.commitFrame(frame(60), bounds, blockedApproval),
+ ).toBeUndefined();
+ original.resolve(true);
+ expect(await oldApproval).toBe(false);
+ expect(
+ handoff.commitFrame(frame(60), bounds, blockedApproval),
+ ).toBeUndefined();
+ expect(blockedApproval).not.toHaveBeenCalled();
+ expect(releaseSecond()).toBe(true);
+ const replacement = deferred();
+ const newApproval = handoff.commitFrame(
+ frame(60),
+ bounds,
+ () => replacement.promise,
+ );
+ expect(newApproval).toBeDefined();
+ expect(releaseFirst()).toBe(false);
+ expect(releaseSecond()).toBe(false);
+ replacement.resolve(true);
+ expect(await newApproval).toBe(true);
+ });
+
+ it("resets a completed latch only for a different supplied identity", async () => {
+ const handoff = createPreparingHandoff();
+ const initial = handoff.begin(position, 30, 120, "first");
+ expect(
+ await handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBe(true);
+ const later = { ...position, playheadSeconds: 12 };
+ expect(handoff.begin(later, 60, 60, "first")).toBe(initial);
+ expect(handoff.begin(later, 60, 60)).toBe(initial);
+ expect(
+ handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBeUndefined();
+ expect(handoff.begin(later, 30, 120, "second")?.frameNumber).toBe(360);
+ expect(
+ await handoff.commitFrame(frame(360), bounds, async () => true),
+ ).toBe(true);
+ });
+
+ it("rejects a late positive ACK without clearing the new identity's pending approval", async () => {
+ const handoff = createPreparingHandoff();
+ const first = deferred();
+ const second = deferred();
+ handoff.begin(position, 30, 120, "first");
+ const oldApproval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => first.promise,
+ );
+ handoff.begin({ ...position, playheadSeconds: 2 }, 30, 120, "second");
+ const newApproval = handoff.commitFrame(
+ frame(60),
+ bounds,
+ () => second.promise,
+ );
+ expect(newApproval).toBeDefined();
+ first.resolve(true);
+ expect(await oldApproval).toBe(false);
+ const duplicate = vi.fn(async () => true);
+ expect(handoff.commitFrame(frame(60), bounds, duplicate)).toBeUndefined();
+ expect(duplicate).not.toHaveBeenCalled();
+ second.resolve(true);
+ expect(await newApproval).toBe(true);
+ });
+
+ it("invalidates pending approval when a scrub changes the expected frame", async () => {
+ const handoff = createPreparingHandoff();
+ const acknowledgement = deferred();
+ handoff.begin(position, 30, 120, "first");
+ const approval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => acknowledgement.promise,
+ );
+ handoff.requestFrame(45);
+ acknowledgement.resolve(true);
+ expect(await approval).toBe(false);
+ expect(handoff.matches(frame(45), bounds)).toBe(true);
+ expect(await handoff.commitFrame(frame(45), bounds, async () => true)).toBe(
+ true,
+ );
+ });
+
+ it("invalidates a pending playing-frame ACK when pause keeps the same target", async () => {
+ const handoff = createPreparingHandoff();
+ const acknowledgement = deferred();
+ handoff.begin(position, 30, 120, "first");
+ handoff.setAdvancing(true, 315);
+ const approval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => acknowledgement.promise,
+ );
+ handoff.setAdvancing(false, 315);
+ acknowledgement.resolve(true);
+ expect(await approval).toBe(false);
+ expect(
+ await handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBe(true);
+ });
+
+ it("invalidates a same-frame pause ACK without changing the target or completed latch", async () => {
+ const handoff = createPreparingHandoff();
+ const first = deferred();
+ const second = deferred();
+ const initial = handoff.begin(position, 30, 120, "first");
+ const oldApproval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => first.promise,
+ );
+ handoff.invalidatePending();
+ expect(handoff.target()).toBe(initial);
+ expect(handoff.requestedFrame()).toBe(315);
+ const newApproval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => second.promise,
+ );
+ expect(newApproval).toBeDefined();
+ first.resolve(true);
+ expect(await oldApproval).toBe(false);
+ expect(
+ handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBeUndefined();
+ second.resolve(true);
+ expect(await newApproval).toBe(true);
+ handoff.invalidatePending();
+ expect(handoff.target()).toBe(initial);
+ expect(
+ handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBeUndefined();
+ });
+
+ it("requires matching visible bounds and leaves a rejected approval retryable", async () => {
+ const handoff = createPreparingHandoff();
+ const approve = vi.fn(async () => false);
+ expect(handoff.commitFrame(frame(315), bounds, approve)).toBeUndefined();
+ handoff.begin(position, 30, 120, "first");
+ for (const invalid of [
+ { width: 0, height: 462 },
+ { width: 787, height: Number.NaN },
+ { width: -1, height: 462 },
+ ]) {
+ expect(handoff.commitFrame(frame(315), invalid, approve)).toBeUndefined();
+ }
+ expect(handoff.commitFrame(frame(0), bounds, approve)).toBeUndefined();
+ expect(approve).not.toHaveBeenCalled();
+ expect(await handoff.commitFrame(frame(315), bounds, approve)).toBe(false);
+ expect(approve).toHaveBeenCalledTimes(1);
+ expect(
+ await handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBe(true);
+ });
+
+ it("keeps one approval pending through same-frame and same-identity updates", async () => {
+ const handoff = createPreparingHandoff();
+ const acknowledgement = deferred();
+ const approve = vi.fn(() => acknowledgement.promise);
+ const initial = handoff.begin(position, 30, 120, "first");
+ const approval = handoff.commitFrame(frame(315), bounds, approve);
+ handoff.requestFrame(315);
+ handoff.setAdvancing(false, 315);
+ expect(
+ handoff.begin({ ...position, playheadSeconds: 15 }, 30, 120, "first"),
+ ).toBe(initial);
+ expect(handoff.commitFrame(frame(315), bounds, approve)).toBeUndefined();
+ expect(approve).toHaveBeenCalledTimes(1);
+ acknowledgement.resolve(true);
+ expect(await approval).toBe(true);
+ });
+
+ it("commits a valid advancing frame once and rejects a duplicate completion", async () => {
+ const handoff = createPreparingHandoff();
+ const approve = vi.fn(async () => true);
+ handoff.begin(position, 30, 120, "first");
+ handoff.setAdvancing(true, 315);
+ for (const invalid of [Number.NaN, 315.5, Number.POSITIVE_INFINITY]) {
+ expect(
+ handoff.commitFrame(frame(invalid), bounds, approve),
+ ).toBeUndefined();
+ }
+ expect(handoff.commitFrame(frame(314), bounds, approve)).toBeUndefined();
+ expect(handoff.commitFrame(frame(3600), bounds, approve)).toBeUndefined();
+ expect(await handoff.commitFrame(frame(319), bounds, approve)).toBe(true);
+ expect(handoff.commitFrame(frame(320), bounds, approve)).toBeUndefined();
+ expect(handoff.accept(frame(320), bounds)).toBe(false);
+ expect(approve).toHaveBeenCalledTimes(1);
+ });
+
+ it("propagates a current rejection and clears its pending slot for retry", async () => {
+ const handoff = createPreparingHandoff();
+ const acknowledgement = deferred();
+ const error = new Error("backend rejected instance");
+ handoff.begin(position, 30, 120, "first");
+ const approval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => acknowledgement.promise,
+ );
+ const rejected = expect(approval).rejects.toBe(error);
+ acknowledgement.reject(error);
+ await rejected;
+ expect(
+ await handoff.commitFrame(frame(315), bounds, async () => true),
+ ).toBe(true);
+ });
+
+ it("turns a superseded rejection into false without poisoning the new identity", async () => {
+ const handoff = createPreparingHandoff();
+ const first = deferred();
+ const second = deferred();
+ handoff.begin(position, 30, 120, "first");
+ const oldApproval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => first.promise,
+ );
+ handoff.begin(position, 30, 120, "second");
+ const newApproval = handoff.commitFrame(
+ frame(315),
+ bounds,
+ () => second.promise,
+ );
+ first.reject(new Error("old instance ended"));
+ expect(await oldApproval).toBe(false);
+ const duplicate = vi.fn(async () => true);
+ expect(handoff.commitFrame(frame(315), bounds, duplicate)).toBeUndefined();
+ expect(duplicate).not.toHaveBeenCalled();
+ second.resolve(true);
+ expect(await newApproval).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/routes/editor/preparing-handoff.ts b/apps/desktop/src/routes/editor/preparing-handoff.ts
new file mode 100644
index 000000000..888abb2ee
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-handoff.ts
@@ -0,0 +1,180 @@
+import type { FrameData } from "~/utils/socket";
+import type { PreparingPlaybackState } from "./preparing-editor-model";
+
+export function createPreparingHandoff() {
+ let target:
+ | { frameNumber: number; playback: PreparingPlaybackState }
+ | undefined;
+ let complete = false;
+ let identity: string | undefined;
+ let revision = 0;
+ let pending: symbol | undefined;
+ const holds = new Set<symbol>();
+ let expectedFrame: number | undefined;
+ let advancing = false;
+ let finalFrame: number | null = null;
+ const matches = (
+ frame: FrameData,
+ bounds: { width: number; height: number },
+ ) => {
+ if (
+ !target ||
+ expectedFrame === undefined ||
+ frame.renderedFrame === undefined ||
+ (advancing
+ ? frame.renderedFrame.frameNumber < expectedFrame ||
+ (finalFrame !== null && frame.renderedFrame.frameNumber > finalFrame)
+ : frame.renderedFrame.frameNumber !== expectedFrame) ||
+ !Number.isFinite(frame.width) ||
+ !Number.isFinite(frame.height) ||
+ frame.width <= 0 ||
+ frame.height <= 0 ||
+ !Number.isFinite(bounds.width) ||
+ !Number.isFinite(bounds.height) ||
+ bounds.width <= 0 ||
+ bounds.height <= 0
+ ) {
+ return false;
+ }
+ return true;
+ };
+ return {
+ begin(
+ playback: PreparingPlaybackState,
+ fps: number,
+ totalDuration: number | null = null,
+ nextIdentity?: string,
+ ) {
+ if (nextIdentity !== undefined && nextIdentity !== identity) {
+ identity = nextIdentity;
+ revision += 1;
+ pending = undefined;
+ complete = false;
+ target = undefined;
+ expectedFrame = undefined;
+ advancing = false;
+ finalFrame = null;
+ }
+ if (target) return target;
+ const requested = Math.floor(playback.playheadSeconds * fps);
+ const lastFrame =
+ totalDuration !== null &&
+ Number.isFinite(totalDuration) &&
+ totalDuration > 0
+ ? Math.max(0, Math.ceil(totalDuration * fps) - 1)
+ : null;
+ const frameNumber =
+ lastFrame === null ? requested : Math.min(requested, lastFrame);
+ if (
+ !Number.isFinite(fps) ||
+ fps <= 0 ||
+ !Number.isSafeInteger(frameNumber) ||
+ frameNumber < 0 ||
+ frameNumber > 0xffffffff
+ ) {
+ return undefined;
+ }
+ target = {
+ frameNumber,
+ playback: {
+ ...playback,
+ playheadSeconds:
+ lastFrame === null
+ ? playback.playheadSeconds
+ : Math.min(playback.playheadSeconds, totalDuration ?? 0),
+ },
+ };
+ expectedFrame = frameNumber;
+ finalFrame = lastFrame;
+ return target;
+ },
+ target: () => target,
+ requestedFrame: () => expectedFrame,
+ requestFrame(frameNumber: number, pendingPlayback = false) {
+ if (!target || (complete && !pendingPlayback)) return frameNumber;
+ const bounded =
+ finalFrame === null ? frameNumber : Math.min(frameNumber, finalFrame);
+ if (!Number.isSafeInteger(bounded) || bounded < 0 || bounded > 0xffffffff)
+ return frameNumber;
+ if (expectedFrame !== bounded || advancing) revision += 1;
+ expectedFrame = bounded;
+ advancing = false;
+ return bounded;
+ },
+ setAdvancing(playing: boolean, startFrame: number) {
+ if (
+ !target ||
+ complete ||
+ !Number.isSafeInteger(startFrame) ||
+ startFrame < 0
+ )
+ return;
+ const bounded =
+ finalFrame === null ? startFrame : Math.min(startFrame, finalFrame);
+ if (expectedFrame !== bounded || advancing !== playing) revision += 1;
+ expectedFrame = bounded;
+ advancing = playing;
+ },
+ invalidatePending() {
+ revision += 1;
+ pending = undefined;
+ },
+ holdFrames() {
+ const hold = Symbol();
+ holds.add(hold);
+ revision += 1;
+ pending = undefined;
+ return () => holds.delete(hold);
+ },
+ commitFrame(
+ frame: FrameData,
+ bounds: { width: number; height: number },
+ approve: () => Promise<boolean>,
+ ): Promise<boolean> | undefined {
+ const rendered = frame.renderedFrame?.frameNumber;
+ if (
+ complete ||
+ holds.size > 0 ||
+ pending ||
+ rendered === undefined ||
+ !Number.isSafeInteger(rendered) ||
+ rendered < 0 ||
+ rendered > 0xffffffff ||
+ !matches(frame, bounds)
+ )
+ return undefined;
+ const token = Symbol();
+ const requestedRevision = revision;
+ const requestedIdentity = identity;
+ const requestedTarget = target;
+ const requestedFrame = expectedFrame;
+ pending = token;
+ const current = () =>
+ !complete &&
+ pending === token &&
+ revision === requestedRevision &&
+ identity === requestedIdentity &&
+ target === requestedTarget &&
+ expectedFrame === requestedFrame;
+ return (async () => {
+ try {
+ const approved = await approve();
+ if (approved !== true || !current()) return false;
+ complete = true;
+ return true;
+ } catch (error) {
+ if (!current()) return false;
+ throw error;
+ } finally {
+ if (pending === token) pending = undefined;
+ }
+ })();
+ },
+ accept(frame: FrameData, bounds: { width: number; height: number }) {
+ if (complete || !matches(frame, bounds)) return false;
+ complete = true;
+ return true;
+ },
+ matches,
+ };
+}
diff --git a/apps/desktop/src/routes/editor/preparing-playback-handoff.test.ts b/apps/desktop/src/routes/editor/preparing-playback-handoff.test.ts
new file mode 100644
index 000000000..69320f80e
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-playback-handoff.test.ts
@@ -0,0 +1,184 @@
+import { describe, expect, it, vi } from "vitest";
+import { createPreparingPlaybackHandoff } from "./preparing-playback-handoff";
+
+function deferred() {
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<void>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+function harness() {
+ const firstStart = deferred();
+ const start = vi.fn(async (_frame: number) => {});
+ start.mockImplementationOnce(() => firstStart.promise);
+ const stop = vi.fn(async () => {});
+ const changed = vi.fn();
+ const settled = vi.fn();
+ const failed = vi.fn();
+ const handoff = createPreparingPlaybackHandoff({
+ initial: { frameNumber: 600, playing: true },
+ start,
+ stop,
+ changed,
+ settled,
+ failed,
+ });
+ return { handoff, firstStart, start, stop, changed, settled, failed };
+}
+
+const flush = async () => {
+ for (let i = 0; i < 8; i++) await Promise.resolve();
+};
+
+describe("ordinary playback handoff ordering", () => {
+ it("uses the actually presented moving frame after native adoption", async () => {
+ const value = harness();
+ value.handoff.acknowledge(612, true);
+ expect(value.start.mock.calls).toEqual([[612]]);
+ value.firstStart.resolve();
+ await flush();
+ expect(value.settled.mock.calls).toEqual([
+ [{ frameNumber: 612, playing: true }],
+ ]);
+ value.handoff.dispose();
+ expect(value.stop).not.toHaveBeenCalled();
+ });
+
+ it("starts only after the actual retained target frame is acknowledged", async () => {
+ const value = harness();
+ value.handoff.acknowledge(0);
+ expect(value.start).not.toHaveBeenCalled();
+ value.handoff.acknowledge(600);
+ expect(value.start.mock.calls).toEqual([[600]]);
+ value.firstStart.resolve();
+ await flush();
+ expect(value.settled.mock.calls).toEqual([
+ [{ frameNumber: 600, playing: true }],
+ ]);
+ expect(value.handoff.active()).toBe(false);
+ value.handoff.dispose();
+ });
+
+ it("a later pause wins even when the native start acknowledgement is deferred", async () => {
+ const value = harness();
+ value.handoff.acknowledge(600);
+ const pause = value.handoff.request({ frameNumber: 600, playing: false });
+ value.firstStart.resolve();
+ expect(await pause).toBe(true);
+ expect(value.stop).toHaveBeenCalledTimes(1);
+ expect(value.settled.mock.calls).toEqual([
+ [{ frameNumber: 600, playing: false }],
+ ]);
+ value.handoff.dispose();
+ });
+
+ it("a new seek keeps playing intent and waits for that new frame before starting", async () => {
+ const value = harness();
+ value.handoff.retarget(1200);
+ value.handoff.acknowledge(600);
+ expect(value.start).not.toHaveBeenCalled();
+ expect(value.handoff.intent().playing).toBe(true);
+ value.handoff.acknowledge(1200);
+ expect(value.start.mock.calls).toEqual([[1200]]);
+ value.firstStart.resolve();
+ await flush();
+ value.handoff.dispose();
+ });
+
+ it("coalesces newer seeks while an old start is in flight without replaying intermediate targets", async () => {
+ const value = harness();
+ value.handoff.acknowledge(600);
+ const skipped = value.handoff.request({ frameNumber: 900, playing: true });
+ const latest = value.handoff.request({ frameNumber: 1200, playing: true });
+ expect(await skipped).toBe(false);
+ value.firstStart.resolve();
+ await flush();
+ expect(value.stop).toHaveBeenCalledTimes(1);
+ expect(value.start).toHaveBeenCalledTimes(1);
+ value.handoff.acknowledge(1200);
+ expect(await latest).toBe(true);
+ expect(value.start.mock.calls).toEqual([[600], [1200]]);
+ value.handoff.dispose();
+ });
+
+ it("same-frame color or layout updates do not erase playing intent or rearm a started request", async () => {
+ const value = harness();
+ value.handoff.acknowledge(600);
+ value.handoff.retarget(600);
+ value.firstStart.resolve();
+ await flush();
+ expect(value.start).toHaveBeenCalledTimes(1);
+ expect(value.settled.mock.calls).toEqual([
+ [{ frameNumber: 600, playing: true }],
+ ]);
+ value.handoff.dispose();
+ });
+
+ it("stops the captured native instance after a start resolves following owner disposal", async () => {
+ const value = harness();
+ value.handoff.acknowledge(600);
+ value.handoff.dispose();
+ value.firstStart.resolve();
+ await flush();
+ expect(value.stop).toHaveBeenCalledTimes(1);
+ expect(value.settled).not.toHaveBeenCalled();
+ expect(
+ value.handoff.request({ frameNumber: 0, playing: true }),
+ ).toBeUndefined();
+ });
+
+ it("disposal before the frame acknowledgement never starts playback", async () => {
+ const value = harness();
+ value.handoff.dispose();
+ value.handoff.acknowledge(600);
+ await flush();
+ expect(value.start).not.toHaveBeenCalled();
+ expect(value.stop).not.toHaveBeenCalled();
+ });
+
+ it("a failed native start is cleaned up and never published as playing", async () => {
+ const value = harness();
+ value.handoff.acknowledge(600);
+ value.firstStart.reject(new Error("native start failed"));
+ await flush();
+ expect(value.stop).toHaveBeenCalledTimes(1);
+ expect(value.failed).toHaveBeenCalledTimes(1);
+ expect(value.settled).not.toHaveBeenCalled();
+ value.handoff.dispose();
+ });
+ it("keeps a newer Play in the owned queue until failed-start cleanup has actually completed", async () => {
+ const value = harness();
+ const cleanup = deferred();
+ value.stop.mockImplementationOnce(() => cleanup.promise);
+ value.handoff.acknowledge(600);
+ value.firstStart.reject(new Error("start failed"));
+ await flush();
+ expect(value.stop).toHaveBeenCalledTimes(1);
+ expect(value.handoff.active()).toBe(true);
+ const newer = value.handoff.request({ frameNumber: 600, playing: true });
+ expect(newer).toBeDefined();
+ expect(value.start).toHaveBeenCalledTimes(1);
+ cleanup.resolve();
+ expect(await newer).toBe(true);
+ expect(value.start.mock.calls).toEqual([[600], [600]]);
+ expect(value.stop).toHaveBeenCalledTimes(1);
+ expect(value.settled.mock.calls).toEqual([
+ [{ frameNumber: 600, playing: true }],
+ ]);
+ value.handoff.dispose();
+ });
+ it("transfers a settled playback to ordinary ownership instead of stopping it on later handoff disposal", async () => {
+ const value = harness();
+ value.handoff.acknowledge(600);
+ value.firstStart.resolve();
+ await flush();
+ expect(value.handoff.active()).toBe(false);
+ value.handoff.dispose();
+ await flush();
+ expect(value.stop).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/routes/editor/preparing-playback-handoff.ts b/apps/desktop/src/routes/editor/preparing-playback-handoff.ts
new file mode 100644
index 000000000..cb6c90a20
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-playback-handoff.ts
@@ -0,0 +1,119 @@
+export type HandoffPlaybackIntent = { frameNumber: number; playing: boolean };
+
+export function createPreparingPlaybackHandoff(options: {
+ initial: HandoffPlaybackIntent;
+ start: (frameNumber: number) => Promise<void>;
+ stop: () => Promise<void>;
+ changed: (intent: HandoffPlaybackIntent, active: boolean) => void;
+ settled: (intent: HandoffPlaybackIntent) => void;
+ failed: (error: unknown) => void;
+}) {
+ let intent = { ...options.initial };
+ let active = true;
+ let alive = true;
+ let ready = false;
+ let running = false;
+ let revision = 0;
+ let startAttempted = false;
+ let resolve: ((accepted: boolean) => void) | undefined;
+
+ const drain = async () => {
+ if (running || !active || !ready || !alive) return;
+ running = true;
+ let failedRevision: number | undefined;
+ let operationRevision = revision;
+ try {
+ while (alive && active && ready) {
+ const version = revision;
+ operationRevision = version;
+ const current = { ...intent };
+ if (startAttempted) {
+ await options.stop();
+ startAttempted = false;
+ }
+ if (!alive || version !== revision) continue;
+ if (current.playing) {
+ startAttempted = true;
+ await options.start(current.frameNumber);
+ }
+ if (!alive || version !== revision) continue;
+ active = false;
+ startAttempted = false;
+ options.changed(current, false);
+ options.settled(current);
+ resolve?.(true);
+ resolve = undefined;
+ }
+ } catch (error) {
+ failedRevision = operationRevision;
+ if (alive) options.failed(error);
+ } finally {
+ if (
+ (failedRevision !== undefined || !alive || (active && !ready)) &&
+ startAttempted
+ ) {
+ try {
+ await options.stop();
+ } catch (error) {
+ if (alive) options.failed(error);
+ }
+ startAttempted = false;
+ }
+ if (alive && failedRevision === revision) {
+ active = false;
+ options.changed({ ...intent, playing: false }, false);
+ resolve?.(false);
+ resolve = undefined;
+ }
+ running = false;
+ if (alive && active && ready) void drain();
+ }
+ };
+
+ return {
+ active: () => alive && active,
+ intent: () => ({ ...intent }),
+ request(next: HandoffPlaybackIntent) {
+ if (!alive || !active) return undefined;
+ resolve?.(false);
+ const changedFrame = next.frameNumber !== intent.frameNumber;
+ intent = { ...next };
+ revision++;
+ if (changedFrame) ready = false;
+ options.changed(intent, true);
+ const pending = new Promise<boolean>((complete) => {
+ resolve = complete;
+ });
+ void drain();
+ return pending;
+ },
+ retarget(frameNumber: number) {
+ if (!alive || !active || frameNumber === intent.frameNumber) return;
+ resolve?.(false);
+ resolve = undefined;
+ intent = { ...intent, frameNumber };
+ revision++;
+ ready = false;
+ options.changed(intent, true);
+ },
+ acknowledge(frameNumber: number, adopted = false) {
+ if (!alive || !active) return;
+ if (adopted) {
+ intent = { ...intent, frameNumber };
+ } else if (frameNumber !== intent.frameNumber) return;
+ ready = true;
+ void drain();
+ },
+ dispose() {
+ if (!alive) return;
+ alive = false;
+ revision++;
+ resolve?.(false);
+ resolve = undefined;
+ if (!running && startAttempted) {
+ startAttempted = false;
+ void options.stop().catch(() => {});
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/routes/editor/preparing-timeline.tsx b/apps/desktop/src/routes/editor/preparing-timeline.tsx
new file mode 100644
index 000000000..389e3d991
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preparing-timeline.tsx
@@ -0,0 +1,123 @@
+import { For, Show } from "solid-js";
+import {
+ type PreparingEditorModel,
+ preparingTime,
+} from "./preparing-editor-model";
+
+const TRACK_NAMES = {
+ display: "Screen",
+ camera: "Camera",
+ microphone: "Microphone",
+ systemAudio: "System audio",
+};
+
+export function PreparingTimeline(props: { model: PreparingEditorModel }) {
+ const timeline = () => props.model.timeline();
+ const tracks = () => {
+ const declared = props.model.seed().tracks;
+ return declared?.length
+ ? declared.map((track) => TRACK_NAMES[track])
+ : ["Recording"];
+ };
+ const position = () => {
+ const total = timeline().totalDuration;
+ return total === null
+ ? 0
+ : Math.min(1, props.model.playback().playheadSeconds / total);
+ };
+ const status = () => {
+ if (props.model.progress().phase === "unavailable") {
+ return "Your recording will be available when preparation finishes";
+ }
+ if (props.model.progress().phase === "handoff")
+ return "Opening your editor";
+ if (props.model.playback().buffering) return "Preparing the next part";
+ if (timeline().playableUntil > 0) {
+ return `Playable to ${preparingTime(timeline().playableUntil)}`;
+ }
+ return "Preparing playback";
+ };
+ return (
+ <div
+ class="flex flex-col h-full rounded-xl bg-ed-card shadow-ed-card overflow-hidden px-3 pt-2.5 pb-3"
+ aria-label="Recording timeline"
+ >
+ <div class="flex items-end h-[26px] shrink-0">
+ <div class="w-[104px] pl-1 shrink-0 text-[11px] text-ed-text-3">
+ Timeline
+ </div>
+ <div class="flex flex-1 justify-between gap-2 pb-1 text-[10px] tabular-nums text-ed-text-3">
+ <Show
+ when={timeline().totalDuration}
+ fallback={<span>Recording duration is being checked</span>}
+ >
+ {(duration) => (
+ <For each={[0, 0.25, 0.5, 0.75, 1]}>
+ {(fraction) => (
+ <span>{preparingTime(duration() * fraction)}</span>
+ )}
+ </For>
+ )}
+ </Show>
+ </div>
+ </div>
+ <div class="flex flex-col gap-1.5 mt-1 overflow-y-auto min-h-0">
+ <For each={tracks()}>
+ {(track, index) => (
+ <div class="flex items-center h-11 min-h-11 rounded-lg bg-ed-ctl">
+ <div class="pl-2 w-[104px] shrink-0 text-[11px] text-ed-text-2 truncate">
+ {track}
+ </div>
+ <div class="relative flex-1 h-full overflow-hidden rounded-r-lg">
+ <div class="absolute inset-0 bg-ed-ctl-hover opacity-40" />
+ <Show when={timeline().fraction !== null}>
+ <div
+ class="absolute inset-y-0 left-0 bg-ed-accent/25 border-r border-ed-accent/50"
+ style={{ width: `${(timeline().fraction ?? 0) * 100}%` }}
+ />
+ <div
+ class="absolute inset-y-0 right-0 overflow-hidden"
+ style={{ left: `${(timeline().fraction ?? 0) * 100}%` }}
+ >
+ <div class="absolute inset-0 bg-ed-card/40 backdrop-blur-[3px]" />
+ <div class="absolute -left-2 inset-y-0 w-5 bg-ed-card/50 blur-md" />
+ </div>
+ <div
+ class="absolute inset-y-0 w-px bg-ed-text-2 pointer-events-none"
+ style={{ left: `${position() * 100}%` }}
+ />
+ </Show>
+ <Show when={index() === 0}>
+ <span
+ class="absolute inset-0 flex items-center justify-center text-[11px] text-ed-text-3 pointer-events-none"
+ role="status"
+ >
+ {status()}
+ </span>
+ </Show>
+ <input
+ type="range"
+ min="0"
+ max={timeline().totalDuration ?? 0}
+ step="0.001"
+ value={props.model.playback().playheadSeconds}
+ disabled={
+ !props.model.canPlay() || timeline().totalDuration === null
+ }
+ aria-label={`Seek ${track.toLowerCase()}`}
+ aria-valuetext={preparingTime(
+ props.model.playback().playheadSeconds,
+ )}
+ class="absolute inset-0 w-full h-full opacity-0 enabled:cursor-pointer focus-visible:opacity-100"
+ onChange={(event) =>
+ void props.model.seek(event.currentTarget.valueAsNumber)
+ }
+ />
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/preview-bounds.test.ts b/apps/desktop/src/routes/editor/preview-bounds.test.ts
new file mode 100644
index 000000000..d08bc2b62
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preview-bounds.test.ts
@@ -0,0 +1,264 @@
+import { createRoot, createSignal } from "solid-js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ createPreviewBoundsReaction,
+ createPreviewBoundsUpdater,
+ type PreviewBounds,
+} from "./preview-bounds";
+
+vi.mock("solid-js", () =>
+ vi.importActual<typeof import("solid-js")>("solid-js/dist/solid.js"),
+);
+
+function harness() {
+ let current = { width: 0, height: 0 };
+ let measured: (PreviewBounds & { connected: boolean }) | undefined = {
+ width: 835,
+ height: 494,
+ connected: true,
+ };
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const commit = vi.fn((bounds: PreviewBounds) => {
+ current = bounds;
+ });
+ const cancel = vi.fn(() => clearTimeout(timer));
+ const measure = vi.fn(() => measured);
+ const defer = vi.fn((bounds: PreviewBounds) => {
+ cancel();
+ timer = setTimeout(() => commit(bounds), 100);
+ });
+ const frames = new Map<number, () => void>();
+ let frameId = 0;
+ const requestFrame = vi.fn((callback: () => void) => {
+ frames.set(++frameId, callback);
+ return frameId;
+ });
+ const cancelFrame = vi.fn((id: number) => frames.delete(id));
+ const updater = createPreviewBoundsUpdater({
+ current: () => current,
+ measure,
+ commit,
+ defer,
+ cancel,
+ requestFrame,
+ cancelFrame,
+ });
+ return {
+ ...updater,
+ commit,
+ defer,
+ measure,
+ cancel,
+ requestFrame,
+ cancelFrame,
+ frameCount: () => frames.size,
+ flushFrame() {
+ const callbacks = [...frames.values()];
+ frames.clear();
+ for (const callback of callbacks) callback();
+ },
+ current: () => current,
+ setMeasured(value: typeof measured) {
+ measured = value;
+ },
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("preview first-frame bounds", () => {
+ it("flushes the actual first-frame bounds and cancels a stale trailing write", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, false);
+ state.update({ width: 820, height: 520 }, false);
+ expect(vi.getTimerCount()).toBe(1);
+ state.update({ width: 820, height: 520 }, true);
+ expect(state.current()).toEqual({ width: 835, height: 494 });
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(1000);
+ expect(state.commit.mock.calls).toEqual([
+ [{ width: 835, height: 542 }],
+ [{ width: 835, height: 494 }],
+ ]);
+ });
+
+ it("uses connected actual geometry when the frame is already present at mount", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, true);
+ expect(state.current()).toEqual({ width: 835, height: 494 });
+ expect(state.measure).toHaveBeenCalledTimes(1);
+ expect(state.defer).not.toHaveBeenCalled();
+ });
+
+ it("does not consume the first-frame latch for disconnected or invalid geometry", () => {
+ const invalid = [
+ undefined,
+ { width: 835, height: 494, connected: false },
+ { width: 0, height: 494, connected: true },
+ { width: 835, height: -1, connected: true },
+ { width: Number.NaN, height: 494, connected: true },
+ { width: 835, height: Number.POSITIVE_INFINITY, connected: true },
+ ];
+ for (const measured of invalid) {
+ const state = harness();
+ state.setMeasured(measured);
+ state.update({ width: 0, height: 0 }, true);
+ state.setMeasured({ width: 300, height: 600, connected: true });
+ state.update({ width: 300, height: 620 }, true);
+ expect(state.current()).toEqual({ width: 300, height: 600 });
+ expect(state.measure).toHaveBeenCalledTimes(2);
+ state.dispose();
+ }
+ });
+
+ it("keeps later portrait and landscape resize bursts trailing by 100ms", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, true);
+ state.flushFrame();
+ state.update({ width: 300, height: 600 }, true);
+ vi.advanceTimersByTime(75);
+ state.update({ width: 900, height: 400 }, true);
+ vi.advanceTimersByTime(99);
+ expect(state.current()).toEqual({ width: 835, height: 494 });
+ vi.advanceTimersByTime(1);
+ expect(state.current()).toEqual({ width: 900, height: 400 });
+ expect(state.measure).toHaveBeenCalledTimes(2);
+ });
+
+ it("cancels pending work on teardown and ignores later frame or bounds delivery", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, false);
+ state.update({ width: 300, height: 600 }, false);
+ state.dispose();
+ state.update({ width: 900, height: 400 }, true);
+ vi.advanceTimersByTime(1000);
+ expect(state.current()).toEqual({ width: 835, height: 542 });
+ expect(state.measure).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("settles without timer rearming and never repeats the first-frame flush", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, true);
+ state.flushFrame();
+ state.update({ width: 300, height: 600 }, false);
+ state.update({ width: 300, height: 600 }, true);
+ vi.advanceTimersByTime(100);
+ const commits = state.commit.mock.calls.length;
+ vi.advanceTimersByTime(10_000);
+ expect(state.current()).toEqual({ width: 300, height: 600 });
+ expect(state.commit).toHaveBeenCalledTimes(commits);
+ expect(state.measure).toHaveBeenCalledTimes(2);
+ expect(state.requestFrame).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ it("remeasures a same-turn layout change once before sealing initial geometry", () => {
+ const state = harness();
+ state.setMeasured({ width: 835, height: 542, connected: true });
+ state.update({ width: 835, height: 542 }, true);
+ expect(state.current()).toEqual({ width: 835, height: 542 });
+ state.setMeasured({ width: 835, height: 494, connected: true });
+ state.flushFrame();
+ expect(state.current()).toEqual({ width: 835, height: 494 });
+ expect(state.requestFrame).toHaveBeenCalledTimes(1);
+ expect(state.frameCount()).toBe(0);
+ state.update({ width: 900, height: 600 }, true);
+ vi.advanceTimersByTime(99);
+ expect(state.current()).toEqual({ width: 835, height: 494 });
+ vi.advanceTimersByTime(1);
+ expect(state.current()).toEqual({ width: 900, height: 600 });
+ expect(state.requestFrame).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps initial updates eager without scheduling more than one frame", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, true);
+ state.setMeasured({ width: 700, height: 400, connected: true });
+ state.update({ width: 700, height: 420 }, true);
+ expect(state.current()).toEqual({ width: 700, height: 400 });
+ expect(state.defer).not.toHaveBeenCalled();
+ expect(state.requestFrame).toHaveBeenCalledTimes(1);
+ state.flushFrame();
+ vi.advanceTimersByTime(10_000);
+ expect(state.frameCount()).toBe(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("leaves invalid scheduled geometry eligible without a frame polling loop", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, true);
+ state.setMeasured({ width: 0, height: 0, connected: false });
+ state.flushFrame();
+ expect(state.frameCount()).toBe(0);
+ expect(state.requestFrame).toHaveBeenCalledTimes(1);
+ state.setMeasured({ width: 300, height: 600, connected: true });
+ state.update({ width: 300, height: 620 }, true);
+ expect(state.current()).toEqual({ width: 300, height: 600 });
+ expect(state.requestFrame).toHaveBeenCalledTimes(2);
+ state.flushFrame();
+ expect(state.frameCount()).toBe(0);
+ });
+
+ it("cancels the scheduled frame on teardown without permitting a late commit", () => {
+ const state = harness();
+ state.update({ width: 835, height: 542 }, true);
+ const queued = state.requestFrame.mock.calls[0][0];
+ expect(state.frameCount()).toBe(1);
+ state.dispose();
+ expect(state.cancelFrame).toHaveBeenCalledTimes(1);
+ expect(state.frameCount()).toBe(0);
+ state.setMeasured({ width: 900, height: 400, connected: true });
+ queued();
+ state.update({ width: 900, height: 400 }, true);
+ expect(state.current()).toEqual({ width: 835, height: 494 });
+ expect(state.commit).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("preview bounds reactive ownership", () => {
+ it("does not rearm a pending resize for repeated non-null frame objects", () => {
+ const state = harness();
+ const reactive = createRoot((dispose) => {
+ const [bounds, setBounds] = createSignal({ width: 835, height: 542 });
+ const [frame, setFrame] = createSignal<{ index: number } | null>(null);
+ const hasFrame = createPreviewBoundsReaction({
+ bounds,
+ hasFrame: () => frame() !== null,
+ updater: state,
+ });
+ return { setBounds, setFrame, hasFrame, dispose };
+ });
+ expect(state.commit).toHaveBeenCalledTimes(1);
+ expect(state.current()).toEqual({ width: 835, height: 542 });
+ expect(reactive.hasFrame()).toBe(false);
+ reactive.setFrame({ index: 0 });
+ expect(state.current()).toEqual({ width: 835, height: 494 });
+ expect(reactive.hasFrame()).toBe(true);
+ state.flushFrame();
+ reactive.setBounds({ width: 900, height: 600 });
+ for (let index = 1; index <= 10; index++) {
+ vi.advanceTimersByTime(20);
+ reactive.setFrame({ index });
+ }
+ expect(state.defer).toHaveBeenCalledTimes(1);
+ expect(state.current()).toEqual({ width: 900, height: 600 });
+ expect(state.measure).toHaveBeenCalledTimes(2);
+ expect(state.requestFrame).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ reactive.setBounds({ width: 400, height: 800 });
+ expect(vi.getTimerCount()).toBe(1);
+ reactive.dispose();
+ reactive.setBounds({ width: 500, height: 900 });
+ reactive.setFrame(null);
+ vi.advanceTimersByTime(10_000);
+ expect(state.current()).toEqual({ width: 900, height: 600 });
+ expect(state.defer).toHaveBeenCalledTimes(2);
+ expect(state.commit).toHaveBeenCalledTimes(4);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/routes/editor/preview-bounds.ts b/apps/desktop/src/routes/editor/preview-bounds.ts
new file mode 100644
index 000000000..35de0a109
--- /dev/null
+++ b/apps/desktop/src/routes/editor/preview-bounds.ts
@@ -0,0 +1,94 @@
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ on,
+ onCleanup,
+} from "solid-js";
+
+export interface PreviewBounds {
+ width: number;
+ height: number;
+}
+
+export function createPreviewBoundsUpdater(options: {
+ current: () => PreviewBounds;
+ measure: () => (PreviewBounds & { connected: boolean }) | undefined;
+ commit: (bounds: PreviewBounds) => void;
+ defer: (bounds: PreviewBounds) => void;
+ cancel: () => void;
+ requestFrame: (callback: () => void) => number;
+ cancelFrame: (id: number) => void;
+}) {
+ let initialFrameSettled = false;
+ let pendingFrame: number | undefined;
+ let disposed = false;
+
+ function flushMeasuredBounds() {
+ const measured = options.measure();
+ if (
+ !measured?.connected ||
+ !Number.isFinite(measured.width) ||
+ !Number.isFinite(measured.height) ||
+ measured.width <= 0 ||
+ measured.height <= 0
+ ) {
+ return false;
+ }
+ options.cancel();
+ options.commit({ width: measured.width, height: measured.height });
+ return true;
+ }
+
+ return {
+ update(bounds: PreviewBounds, hasFrame: boolean) {
+ if (disposed) return;
+ if (hasFrame && !initialFrameSettled && flushMeasuredBounds()) {
+ if (pendingFrame === undefined) {
+ pendingFrame = options.requestFrame(() => {
+ pendingFrame = undefined;
+ if (!disposed && flushMeasuredBounds()) {
+ initialFrameSettled = true;
+ }
+ });
+ }
+ return;
+ }
+ const current = options.current();
+ if (current.width === 0 && current.height === 0) {
+ options.commit(bounds);
+ } else {
+ options.defer(bounds);
+ }
+ },
+ dispose() {
+ disposed = true;
+ options.cancel();
+ if (pendingFrame !== undefined) {
+ options.cancelFrame(pendingFrame);
+ pendingFrame = undefined;
+ }
+ },
+ };
+}
+
+export function createPreviewBoundsReaction(options: {
+ bounds: Accessor<PreviewBounds>;
+ hasFrame: Accessor<boolean>;
+ updater: ReturnType<typeof createPreviewBoundsUpdater>;
+}) {
+ const hasFrame = createMemo(options.hasFrame);
+ onCleanup(() => options.updater.dispose());
+ createEffect(
+ on(
+ () => {
+ const { width, height } = options.bounds();
+ return [width, height, hasFrame()] as const;
+ },
+ ([width, height, available]) => {
+ options.updater.update({ width, height }, available);
+ },
+ ),
+ );
+ return hasFrame;
+}
diff --git a/apps/desktop/src/utils/frame-identity.ts b/apps/desktop/src/utils/frame-identity.ts
new file mode 100644
index 000000000..dd01d22e1
--- /dev/null
+++ b/apps/desktop/src/utils/frame-identity.ts
@@ -0,0 +1,11 @@
+export type RenderedFrameIdentity = {
+ frameNumber: number;
+ targetTimeNs: bigint;
+};
+
+export function readFrameIdentity(metadata: DataView): RenderedFrameIdentity {
+ return {
+ frameNumber: metadata.getUint32(12, true),
+ targetTimeNs: metadata.getBigUint64(16, true),
+ };
+}
diff --git a/apps/desktop/src/utils/frame-worker.ts b/apps/desktop/src/utils/frame-worker.ts
index 89b773006..271822c32 100644
--- a/apps/desktop/src/utils/frame-worker.ts
+++ b/apps/desktop/src/utils/frame-worker.ts
@@ -47,6 +47,8 @@ interface ReadyMessage {
interface FrameRenderedMessage {
type: "frame-rendered";
+ frameNumber?: number;
+ targetTimeNs?: bigint;
width: number;
height: number;
}
@@ -453,6 +455,8 @@ function renderBorrowedWebGPU(bytes: Uint8Array, release: () => void): boolean {
type: "frame-rendered",
width,
height,
+ frameNumber,
+ targetTimeNs,
} satisfies FrameRenderedMessage);
return true;
@@ -733,6 +737,7 @@ function renderLoop() {
type: "frame-rendered",
width: frame.width,
height: frame.height,
+ ...frame.timing,
} satisfies FrameRenderedMessage);
const shouldContinue =
@@ -792,6 +797,7 @@ function renderLoop() {
type: "frame-rendered",
width: frame.width,
height: frame.height,
+ ...frame.timing,
} satisfies FrameRenderedMessage);
}
diff --git a/apps/desktop/src/utils/socket.ts b/apps/desktop/src/utils/socket.ts
index 1ce9ac75c..5494eff2a 100644
--- a/apps/desktop/src/utils/socket.ts
+++ b/apps/desktop/src/utils/socket.ts
@@ -1,5 +1,9 @@
import { createWS } from "@solid-primitives/websocket";
import { createResource, createSignal } from "solid-js";
+import {
+ type RenderedFrameIdentity,
+ readFrameIdentity,
+} from "./frame-identity";
import FrameWorker from "./frame-worker?worker";
import {
createProducer,
@@ -34,7 +38,7 @@ const NV12_VIDEO_MAGIC = 0x4e563132;
const NV12_FULL_MAGIC = 0x4e563146;
const NV12_METADATA_SIZE = 28;
-type Nv12Metadata = {
+type Nv12Metadata = RenderedFrameIdentity & {
yStride: number;
height: number;
width: number;
@@ -71,6 +75,7 @@ function readNv12Metadata(buffer: ArrayBuffer): Nv12Metadata | null {
height,
width,
fullRange: magic === NV12_FULL_MAGIC,
+ ...readFrameIdentity(meta),
};
}
@@ -199,6 +204,7 @@ export type FrameData = {
width: number;
height: number;
bitmap?: ImageBitmap | null;
+ renderedFrame?: RenderedFrameIdentity;
};
export type CanvasControls = {
@@ -214,6 +220,7 @@ export type CanvasControls = {
export type ImageDataWSOptions = {
powerPreference?: GPUPowerPreference;
+ retainLastFrameOnDispose?: HTMLCanvasElement;
};
interface ReadyMessage {
@@ -222,6 +229,8 @@ interface ReadyMessage {
interface FrameRenderedMessage {
type: "frame-rendered";
+ frameNumber?: number;
+ targetTimeNs?: bigint;
width: number;
height: number;
}
@@ -372,6 +381,13 @@ export function createImageDataWS(
function cleanup() {
if (isCleanedUp) return;
+ if (options.retainLastFrameOnDispose) {
+ try {
+ canvasControls.drawLatestFrameToCanvas(
+ options.retainLastFrameOnDispose,
+ );
+ } catch {}
+ }
isCleanedUp = true;
ws.onmessage = null;
@@ -489,7 +505,14 @@ export function createImageDataWS(
timing,
receivedAt,
);
- onmessage({ width, height });
+ onmessage({
+ width,
+ height,
+ renderedFrame: {
+ frameNumber: metadata.frameNumber,
+ targetTimeNs: metadata.targetTimeNs,
+ },
+ });
}
}
@@ -544,7 +567,7 @@ export function createImageDataWS(
timing,
receivedAt,
);
- onmessage({ width, height });
+ onmessage({ width, height, renderedFrame: readFrameIdentity(meta) });
}
}
@@ -564,6 +587,7 @@ export function createImageDataWS(
height: number,
yStride: number,
fullRange: boolean,
+ identity: RenderedFrameIdentity,
receivedAt?: number,
) {
if (!directCanvas || !directCtx) return;
@@ -602,7 +626,7 @@ export function createImageDataWS(
undefined,
receivedAt,
);
- onmessage({ width, height });
+ onmessage({ width, height, renderedFrame: identity });
}
function renderPendingFrameCanvas2D() {
@@ -628,6 +652,10 @@ export function createImageDataWS(
height,
yStride,
fullRange,
+ {
+ frameNumber: metadata.frameNumber,
+ targetTimeNs: metadata.targetTimeNs,
+ },
receivedAt,
);
}
@@ -680,7 +708,14 @@ export function createImageDataWS(
false,
);
recordRender(performance.now() - renderStart, "canvas2d");
- onmessage({ width, height });
+ onmessage({
+ width,
+ height,
+ renderedFrame: {
+ frameNumber: e.data.frameNumber,
+ targetTimeNs: e.data.targetTimeNs,
+ },
+ });
};
return strideWorker;
}
@@ -747,13 +782,14 @@ export function createImageDataWS(
undefined,
receivedAt,
);
- onmessage({ width, height });
+ onmessage({ width, height, renderedFrame: readFrameIdentity(meta) });
return;
}
ensureStrideWorker().postMessage(
{
type: "correct-stride",
+ ...readFrameIdentity(meta),
buffer,
strideBytes,
width,
@@ -1024,7 +1060,17 @@ export function createImageDataWS(
if (!hasRenderedFrame()) {
setHasRenderedFrame(true);
}
- onmessage({ width, height });
+ onmessage({
+ width,
+ height,
+ renderedFrame:
+ e.data.frameNumber !== undefined && e.data.targetTimeNs !== undefined
+ ? {
+ frameNumber: e.data.frameNumber,
+ targetTimeNs: e.data.targetTimeNs,
+ }
+ : undefined,
+ });
recordRender(0, "worker");
if (isProcessingSharedFrame) {
isProcessingSharedFrame = false;
diff --git a/apps/desktop/src/utils/stride-correction-worker.ts b/apps/desktop/src/utils/stride-correction-worker.ts
index b98a355bd..432744f77 100644
--- a/apps/desktop/src/utils/stride-correction-worker.ts
+++ b/apps/desktop/src/utils/stride-correction-worker.ts
@@ -1,4 +1,6 @@
-interface StrideCorrectionRequest {
+import type { RenderedFrameIdentity } from "./frame-identity";
+
+interface StrideCorrectionRequest extends RenderedFrameIdentity {
type: "correct-stride";
buffer: ArrayBuffer;
strideBytes: number;
@@ -6,7 +8,7 @@ interface StrideCorrectionRequest {
height: number;
}
-interface StrideCorrectionResponse {
+interface StrideCorrectionResponse extends RenderedFrameIdentity {
type: "corrected";
buffer: ArrayBuffer;
width: number;
@@ -24,7 +26,8 @@ let correctionBufferSize = 0;
self.onmessage = (e: MessageEvent<StrideCorrectionRequest>) => {
if (e.data.type !== "correct-stride") return;
- const { buffer, strideBytes, width, height } = e.data;
+ const { buffer, strideBytes, width, height, frameNumber, targetTimeNs } =
+ e.data;
const expectedRowBytes = width * 4;
const expectedLength = expectedRowBytes * height;
@@ -46,6 +49,8 @@ self.onmessage = (e: MessageEvent<StrideCorrectionRequest>) => {
const result = correctionBuffer.slice(0, expectedLength);
const response: StrideCorrectionResponse = {
type: "corrected",
+ frameNumber,
+ targetTimeNs,
buffer: result.buffer,
width,
height,
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index f070f4294..69c9d0543 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -217,6 +217,21 @@ async getVideoMetadata(path: string) : Promise<VideoRecordingMetadata> {
async createEditorInstance() : Promise<SerializedEditorInstance> {
return await TAURI_INVOKE("create_editor_instance");
},
+async createPreparingEditorFrame(requestEpoch: number) : Promise<string | null> {
+ return await TAURI_INVOKE("create_preparing_editor_frame", { requestEpoch });
+},
+async getPreparingEditorState(requestEpoch: number) : Promise<PreparingEditorChanged | null> {
+ return await TAURI_INVOKE("get_preparing_editor_state", { requestEpoch });
+},
+async seekPreparingEditor(requestEpoch: number, jobId: string, seconds: number) : Promise<null> {
+ return await TAURI_INVOKE("seek_preparing_editor", { requestEpoch, jobId, seconds });
+},
+async setPreparingEditorPlaying(requestEpoch: number, jobId: string, playing: boolean) : Promise<null> {
+ return await TAURI_INVOKE("set_preparing_editor_playing", { requestEpoch, jobId, playing });
+},
+async stopPreparingEditorFrame(requestEpoch: number) : Promise<null> {
+ return await TAURI_INVOKE("stop_preparing_editor_frame", { requestEpoch });
+},
async getEditorProjectPath() : Promise<string> {
return await TAURI_INVOKE("get_editor_project_path");
},
@@ -241,6 +256,15 @@ async startPlayback(fps: number, resolutionBase: XY<number>) : Promise<null> {
async stopPlayback() : Promise<null> {
return await TAURI_INVOKE("stop_playback");
},
+async commitEditorPreparingFrame(instanceId: string, frameNumber: number, fps: number) : Promise<boolean> {
+ return await TAURI_INVOKE("commit_editor_preparing_frame", { instanceId, frameNumber, fps });
+},
+async startEditorHandoffPlayback(instanceId: string, frameNumber: number, fps: number, resolutionBase: XY<number>) : Promise<string> {
+ return await TAURI_INVOKE("start_editor_handoff_playback", { instanceId, frameNumber, fps, resolutionBase });
+},
+async stopEditorHandoffPlayback(instanceId: string, playbackId: string) : Promise<null> {
+ return await TAURI_INVOKE("stop_editor_handoff_playback", { instanceId, playbackId });
+},
async setPlayheadPosition(frameNumber: number) : Promise<null> {
return await TAURI_INVOKE("set_playhead_position", { frameNumber });
},
@@ -556,6 +580,7 @@ newNotification: NewNotification,
newScreenshotAdded: NewScreenshotAdded,
newStudioRecordingAdded: NewStudioRecordingAdded,
onEscapePress: OnEscapePress,
+preparingEditorChanged: PreparingEditorChanged,
recordingDeleted: RecordingDeleted,
recordingEvent: RecordingEvent,
recordingOptionsChanged: RecordingOptionsChanged,
@@ -589,6 +614,7 @@ newNotification: "new-notification",
newScreenshotAdded: "new-screenshot-added",
newStudioRecordingAdded: "new-studio-recording-added",
onEscapePress: "on-escape-press",
+preparingEditorChanged: "preparing-editor-changed",
recordingDeleted: "recording-deleted",
recordingEvent: "recording-event",
recordingOptionsChanged: "recording-options-changed",
@@ -1132,6 +1158,11 @@ export type Plan = { upgraded: boolean; manual: boolean; last_checked: number }
export type Platform = "MacOS" | "Windows" | "Linux"
export type PostDeletionBehaviour = "doNothing" | "reopenRecordingWindow"
export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay"
+export type PreparingEditorChanged = { requestEpoch: number; jobId: string; sequence: number; fps: number; progress: PreparingEditorProgress; playback: PreparingPlaybackState; seed: PreparingEditorSeed }
+export type PreparingEditorPhase = "preparing" | "handoff" | "unavailable" | "ready"
+export type PreparingEditorProgress = { totalDuration: number | null; playableUntil: number; previewAvailable: boolean; phase: PreparingEditorPhase }
+export type PreparingEditorSeed = { title: string; tracks: string[] }
+export type PreparingPlaybackState = { playheadSeconds: number; playing: boolean; buffering: boolean }
export type Preset = { name: string; config: ProjectConfiguration }
export type PresetsStore = { presets: Preset[]; default: number | null }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline: TimelineConfiguration | null; overlayOrder: OverlayTrack[]; captions: CaptionsData | null; keyboard: KeyboardData | null; clips: ClipConfiguration[]; annotations: Annotation[]; screenMotionBlur?: number; screenMovementSpring?: ScreenMovementSpring;
@@ -1200,7 +1231,7 @@ export type ScreenshotProjectExport = { imageBytes: number[]; config: ProjectCon
export type ScreenshotProjectShareState = { config: ProjectConfiguration; sharing: ScreenshotSharingState | null }
export type ScreenshotSharingState = { link: string; contentHash: string | null }
export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audio | null; system_audio: Audio | null }
-export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string;
+export type SerializedEditorInstance = { instanceId: string; preparingPlayback: boolean; framesSocketUrl: string; preparingSnapshot: PreparingEditorChanged | null; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string;
/**
* Notch geometry the overlay uses when the project sets no manual
* placement: this recording's own measurements where the recorder took
diff --git a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
index caa36c364..6ad4da52f 100644
--- a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
@@ -1,4 +1,5 @@
import type { VideoEditSpec } from "@cap/database/types";
+import { User, Video } from "@cap/web-domain";
import { Effect, Option } from "effect";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -74,6 +75,7 @@ import {
getVideoReplaceUploadUrl,
invalidateVideoCache,
} from "@/actions/admin/replace-video";
+import { prepareDesktopReupload } from "@/lib/desktop-reupload";
import { saveMetadataAndComplete } from "@/workflows/admin-reprocess-video";
import {
saveEditResultAndComplete,
@@ -245,6 +247,44 @@ beforeEach(() => {
afterEach(() => vi.unstubAllGlobals());
+describe("desktop reupload publication", () => {
+ const original = () => ({
+ id: Video.VideoId.make(video.id),
+ ownerId: User.UserId.make(video.ownerId),
+ bucketId: Option.none(),
+ storageIntegrationId: Option.none(),
+ });
+
+ it("replaces processed playback and stale AI while preserving the link's other metadata", async () => {
+ video.source.audioLevelOutputKey =
+ "user/video/.recording/outputs/old-audio.mp4";
+ video.metadata.editProcessing = { token: "old-edit" };
+ const tx = createClient() as unknown as Parameters<
+ typeof prepareDesktopReupload
+ >[0];
+ const replacement = await prepareDesktopReupload(tx, original());
+ expect(replacement).toEqual({
+ source: { type: "desktopMP4" },
+ metadata: { customCreatedAt: "2020-01-01T00:00:00Z" },
+ transcriptionStatus: null,
+ });
+ expect(video.source.outputKey).toBeDefined();
+ expect(events).toEqual(["retire-job", "lock-video"]);
+ });
+
+ it("rejects publication if storage changed during upload", async () => {
+ const snapshot = original();
+ video.bucket = "different-bucket";
+ const tx = createClient() as unknown as Parameters<
+ typeof prepareDesktopReupload
+ >[0];
+ await expect(prepareDesktopReupload(tx, snapshot)).rejects.toThrow(
+ "storage changed",
+ );
+ expect(updates).toEqual([]);
+ });
+});
+
describe("edited recording publication", () => {
it.each(["reprocess", "replace"])(
"clears a browser audio derivative after %s",
diff --git a/apps/web/__tests__/unit/multipart-presign.test.ts b/apps/web/__tests__/unit/multipart-presign.test.ts
index d847d0946..b66b4c81f 100644
--- a/apps/web/__tests__/unit/multipart-presign.test.ts
+++ b/apps/web/__tests__/unit/multipart-presign.test.ts
@@ -1,10 +1,21 @@
import { Effect, Option } from "effect";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
getOwnedById: vi.fn(),
storage: vi.fn(),
sign: vi.fn(),
+ database: vi.fn(),
+ prepareReplacement: vi.fn(),
+ invalidate: vi.fn(),
+ head: vi.fn(),
+ queueTranscription: vi.fn(),
+ shouldQueueTranscription: vi.fn(),
+}));
+vi.mock("@cap/env", () => ({ serverEnv: () => ({}) }));
+vi.mock("@/lib/desktop-reupload", () => ({
+ prepareDesktopReupload: mocks.prepareReplacement,
+ invalidateReuploadedVideo: mocks.invalidate,
}));
vi.mock("@cap/web-backend", async () => {
const { Context, Layer } = await import("effect");
@@ -36,16 +47,23 @@ vi.mock("@/lib/server", async () => {
getOwnedById: mocks.getOwnedById,
}),
),
+ Effect.provide(
+ Layer.succeed(Context.GenericTag("test/Database"), {
+ use: (callback: (client: unknown) => Promise<unknown>) =>
+ Effect.tryPromise(() => callback(mocks.database())),
+ }),
+ ),
) as Effect.Effect<unknown>,
),
};
});
vi.mock("@/lib/google-drive-storage-quota", () => ({
- invalidateGoogleDriveStorageQuotaCache: vi.fn(),
+ invalidateGoogleDriveStorageQuotaCache: vi.fn(async () => {}),
}));
vi.mock("@/lib/queue-video-transcription", () => ({
- queueVideoTranscription: vi.fn(),
- shouldQueueTranscriptionAfterMultipartComplete: vi.fn(),
+ queueVideoTranscription: mocks.queueTranscription,
+ shouldQueueTranscriptionAfterMultipartComplete:
+ mocks.shouldQueueTranscription,
}));
vi.mock("@/lib/video-processing", () => ({
startVideoProcessingWorkflow: vi.fn(),
@@ -104,3 +122,174 @@ describe("multipart presign ownership failures", () => {
});
});
});
+
+describe("desktop reupload completion", () => {
+ let events: string[];
+ let updates: Record<string, unknown>[];
+ beforeEach(() => {
+ vi.clearAllMocks();
+ events = [];
+ updates = [];
+ const client = {
+ transaction: async (run: (tx: unknown) => Promise<void>) => run(client),
+ update: () => ({
+ set: (values: Record<string, unknown>) => ({
+ where: async () => {
+ updates.push(values);
+ events.push("publish");
+ },
+ }),
+ }),
+ delete: () => ({
+ where: async () => {
+ events.push("delete-upload");
+ },
+ }),
+ };
+ mocks.database.mockReturnValue(client);
+ mocks.getOwnedById.mockReturnValue(
+ Effect.succeed(
+ Option.some([
+ {
+ id: "video",
+ ownerId: "owner",
+ source: { type: "desktopMP4", outputKey: "old.mp4" },
+ bucketId: Option.none(),
+ storageIntegrationId: Option.none(),
+ },
+ ]),
+ ),
+ );
+ mocks.storage.mockReturnValue(
+ Effect.succeed([
+ {
+ provider: "s3",
+ bucketName: "bucket",
+ multipart: {
+ complete: () =>
+ Effect.sync(() => {
+ events.push("complete");
+ return { ETag: "new-video" };
+ }),
+ },
+ headObject: mocks.head,
+ copyObject: () =>
+ Effect.succeed({ CopyObjectResult: { ETag: "new-video" } }),
+ },
+ ]),
+ );
+ mocks.head.mockReturnValue(
+ Effect.succeed({ ETag: "new-video", ContentLength: 100 }),
+ );
+ mocks.prepareReplacement.mockImplementation(async () => {
+ events.push("retire");
+ return { source: { type: "desktopMP4" }, transcriptionStatus: null };
+ });
+ mocks.invalidate.mockImplementation(async () => {
+ events.push("invalidate");
+ });
+ mocks.shouldQueueTranscription.mockReturnValue(false);
+ mocks.queueTranscription.mockResolvedValue({ success: true });
+ });
+
+ const complete = (replaceExisting?: boolean) =>
+ app.request("/complete", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoId: "video",
+ uploadId: "upload",
+ parts: [{ partNumber: 1, etag: "part", size: 100 }],
+ durationInSecs: 5,
+ replaceExisting,
+ }),
+ });
+
+ it("publishes the new canonical bytes at the existing link before invalidating playback", async () => {
+ const response = await complete(true);
+ expect(response.status).toBe(200);
+ expect(events).toEqual([
+ "complete",
+ "retire",
+ "publish",
+ "delete-upload",
+ "invalidate",
+ ]);
+ expect(mocks.storage).toHaveBeenCalledWith(expect.anything(), {
+ resolvePublishedOutput: false,
+ });
+ expect(updates[0]).toMatchObject({
+ source: { type: "desktopMP4" },
+ transcriptionStatus: null,
+ });
+ });
+
+ it("keeps a committed reupload successful when cache invalidation fails", async () => {
+ mocks.invalidate.mockImplementationOnce(async () => {
+ events.push("invalidate");
+ throw new Error("CloudFront temporarily unavailable");
+ });
+ mocks.shouldQueueTranscription.mockReturnValue(true);
+ mocks.queueTranscription.mockImplementationOnce(async () => {
+ events.push("transcribe");
+ return { success: true };
+ });
+
+ const response = await complete(true);
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({
+ success: true,
+ objectIdentity: "new-video",
+ });
+ expect(events).toEqual([
+ "complete",
+ "retire",
+ "publish",
+ "delete-upload",
+ "invalidate",
+ "transcribe",
+ ]);
+ expect(updates).toHaveLength(1);
+ expect(mocks.queueTranscription).toHaveBeenCalledExactlyOnceWith("video");
+ });
+
+ it.each([false, undefined])(
+ "keeps first uploads on the existing recording completion path: %s",
+ async (replaceExisting) => {
+ const response = await complete(replaceExisting);
+ expect(response.status).toBe(200);
+ expect(mocks.prepareReplacement).not.toHaveBeenCalled();
+ expect(mocks.invalidate).not.toHaveBeenCalled();
+ expect(updates[0]).not.toHaveProperty("source");
+ },
+ );
+ it("does not publish an empty or mismatched replacement", async () => {
+ mocks.head.mockReturnValue(
+ Effect.succeed({ ETag: "old-video", ContentLength: 0 }),
+ );
+ const response = await complete(true);
+ expect(response.status).toBe(500);
+ expect(mocks.prepareReplacement).not.toHaveBeenCalled();
+ expect(mocks.invalidate).not.toHaveBeenCalled();
+ expect(updates).toEqual([]);
+ });
+
+ it("does not replace playback when storage completion fails", async () => {
+ mocks.storage.mockReturnValue(
+ Effect.succeed([
+ {
+ provider: "s3",
+ bucketName: "bucket",
+ multipart: {
+ complete: () => Effect.fail(new Error("upload failed")),
+ },
+ },
+ ]),
+ );
+ const response = await complete(true);
+ expect(response.status).toBe(500);
+ expect(mocks.prepareReplacement).not.toHaveBeenCalled();
+ expect(updates).toEqual([]);
+ });
+});
diff --git a/apps/web/app/api/upload/[...route]/multipart.ts b/apps/web/app/api/upload/[...route]/multipart.ts
index 75df27c9e..4f5797d5d 100644
--- a/apps/web/app/api/upload/[...route]/multipart.ts
+++ b/apps/web/app/api/upload/[...route]/multipart.ts
@@ -16,6 +16,10 @@ import { Effect, Option, Schedule } from "effect";
import { Hono, type MiddlewareHandler } from "hono";
import { z } from "zod";
import { withAuth } from "@/app/api/utils";
+import {
+ invalidateReuploadedVideo,
+ prepareDesktopReupload,
+} from "@/lib/desktop-reupload";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import {
queueVideoTranscription,
@@ -309,6 +313,7 @@ app.post(
width: stringOrNumberOptional,
height: stringOrNumberOptional,
fps: stringOrNumberOptional,
+ replaceExisting: z.boolean().optional(),
})
.and(
z.union([
@@ -328,6 +333,8 @@ app.post(
const fileKey = getMultipartFileKey(user.id, body);
const subpath = getSubpath(body) ?? "result.mp4";
+ const replacesVideo =
+ body.replaceExisting === true && subpath === "result.mp4";
const videoIdFromFileKey = fileKey.split("/")[1];
const videoIdRaw = "videoId" in body ? body.videoId : videoIdFromFileKey;
@@ -409,7 +416,9 @@ app.post(
}
return yield* Effect.gen(function* () {
- const [bucket] = yield* Storage.getAccessForVideo(video);
+ const [bucket] = yield* Storage.getAccessForVideo(video, {
+ resolvePublishedOutput: false,
+ });
const { result, formattedParts } = yield* Effect.gen(function* () {
console.log(
@@ -479,6 +488,15 @@ app.post(
console.log(`Complete response: ${JSON.stringify(result, null, 2)}`);
yield* bucket.headObject(fileKey).pipe(
+ Effect.tap((head) =>
+ replacesVideo &&
+ (!head.ContentLength ||
+ (result.ETag && head.ETag !== result.ETag))
+ ? Effect.fail(
+ new Error("Reuploaded video could not be verified"),
+ )
+ : Effect.void,
+ ),
Effect.tap((headResult) =>
Effect.log(
`Object verification successful: ContentType=${headResult.ContentType}, ContentLength=${headResult.ContentLength}`,
@@ -489,7 +507,11 @@ app.post(
schedule: Schedule.exponential("50 millis"),
}),
Effect.catchAll((headError) =>
- Effect.logError(`Warning: Unable to verify object: ${headError}`),
+ replacesVideo
+ ? Effect.fail(headError)
+ : Effect.logError(
+ `Warning: Unable to verify object: ${headError}`,
+ ),
),
);
@@ -577,33 +599,50 @@ app.post(
}
yield* db.use((db) =>
- db.transaction(() =>
- Promise.all([
- db
- .update(Db.videos)
- .set({
- duration: updateIfDefined(
- body.durationInSecs,
- Db.videos.duration,
- ),
- width: updateIfDefined(body.width, Db.videos.width),
- height: updateIfDefined(body.height, Db.videos.height),
- fps: updateIfDefined(body.fps, Db.videos.fps),
- })
- .where(
- and(
- eq(Db.videos.id, Video.VideoId.make(videoId)),
- eq(Db.videos.ownerId, user.id),
- ),
+ db.transaction(async (tx) => {
+ const replacement = replacesVideo
+ ? await prepareDesktopReupload(tx, video)
+ : {};
+ await tx
+ .update(Db.videos)
+ .set({
+ ...replacement,
+ duration: updateIfDefined(
+ body.durationInSecs,
+ Db.videos.duration,
),
- db
- .delete(Db.videoUploads)
- .where(
- eq(Db.videoUploads.videoId, Video.VideoId.make(videoId)),
+ width: updateIfDefined(body.width, Db.videos.width),
+ height: updateIfDefined(body.height, Db.videos.height),
+ fps: updateIfDefined(body.fps, Db.videos.fps),
+ })
+ .where(
+ and(
+ eq(Db.videos.id, Video.VideoId.make(videoId)),
+ eq(Db.videos.ownerId, user.id),
),
- ]),
- ),
+ );
+ await tx
+ .delete(Db.videoUploads)
+ .where(
+ eq(Db.videoUploads.videoId, Video.VideoId.make(videoId)),
+ );
+ }),
);
+ if (replacesVideo) {
+ yield* Effect.tryPromise(() =>
+ invalidateReuploadedVideo(video),
+ ).pipe(
+ Effect.catchAll((error) =>
+ Effect.logWarning(
+ "Published reupload cache invalidation failed",
+ {
+ videoId,
+ error,
+ },
+ ),
+ ),
+ );
+ }
const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
let mediaProcessingPending = false;
diff --git a/apps/web/lib/desktop-reupload.ts b/apps/web/lib/desktop-reupload.ts
new file mode 100644
index 000000000..cd7a5139f
--- /dev/null
+++ b/apps/web/lib/desktop-reupload.ts
@@ -0,0 +1,85 @@
+import {
+ CloudFrontClient,
+ CreateInvalidationCommand,
+} from "@aws-sdk/client-cloudfront";
+import type { db } from "@cap/database";
+import { videos } from "@cap/database/schema";
+import { serverEnv } from "@cap/env";
+import { AwsCredentials } from "@cap/web-backend";
+import type { Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { Effect, Option } from "effect";
+import { retireDesktopRecordingJobForOutputReplacement } from "@/lib/desktop-recording-jobs";
+import { runPromise } from "@/lib/server";
+
+type ReuploadedVideo = Pick<
+ Video.Video,
+ "id" | "ownerId" | "bucketId" | "storageIntegrationId"
+>;
+
+export async function prepareDesktopReupload(
+ tx: Parameters<Parameters<ReturnType<typeof db>["transaction"]>[0]>[0],
+ video: ReuploadedVideo,
+) {
+ await retireDesktopRecordingJobForOutputReplacement(tx, {
+ videoId: video.id,
+ userId: video.ownerId,
+ });
+ const [locked] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, video.id))
+ .for("update");
+ if (
+ !locked ||
+ locked.ownerId !== video.ownerId ||
+ locked.bucket !== Option.getOrNull(video.bucketId) ||
+ locked.storageIntegrationId !== Option.getOrNull(video.storageIntegrationId)
+ ) {
+ throw new Error("Recording storage changed during reupload");
+ }
+ const metadata = { ...(locked.metadata ?? {}) };
+ delete metadata.desktopRecordingUpload;
+ delete metadata.summary;
+ delete metadata.chapters;
+ delete metadata.aiGenerationStatus;
+ Reflect.deleteProperty(metadata, "editProcessing");
+ Reflect.deleteProperty(metadata, "completedVideoEdit");
+ return {
+ source:
+ locked.source.type === "webMP4"
+ ? { type: "webMP4" as const }
+ : { type: "desktopMP4" as const },
+ metadata,
+ transcriptionStatus: null,
+ };
+}
+
+export async function invalidateReuploadedVideo(video: ReuploadedVideo) {
+ if (
+ Option.isSome(video.bucketId) ||
+ Option.isSome(video.storageIntegrationId)
+ )
+ return;
+ const distributionId = serverEnv().CAP_CLOUDFRONT_DISTRIBUTION_ID;
+ if (!distributionId) return;
+ const client = new CloudFrontClient({
+ region: serverEnv().CAP_AWS_REGION || "us-east-1",
+ credentials: await runPromise(
+ Effect.map(AwsCredentials, (value) => value.credentials),
+ ),
+ });
+ try {
+ await client.send(
+ new CreateInvalidationCommand({
+ DistributionId: distributionId,
+ InvalidationBatch: {
+ CallerReference: crypto.randomUUID(),
+ Paths: { Quantity: 1, Items: [`/${video.ownerId}/${video.id}/*`] },
+ },
+ }),
+ );
+ } finally {
+ client.destroy();
+ }
+}
diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml
index 55b9c9e2b..e0aa1b7ec 100644
--- a/crates/audio/Cargo.toml
+++ b/crates/audio/Cargo.toml
@@ -3,8 +3,11 @@ name = "cap-audio"
version = "0.1.0"
edition = "2024"
+[features]
+test-support = []
[dependencies]
+cap-enc-ffmpeg = { path = "../enc-ffmpeg" }
ffmpeg = { workspace = true }
cpal = { workspace = true }
tokio.workspace = true
diff --git a/crates/audio/examples/relocatable-audio-probe.rs b/crates/audio/examples/relocatable-audio-probe.rs
new file mode 100644
index 000000000..8cc9bd87c
--- /dev/null
+++ b/crates/audio/examples/relocatable-audio-probe.rs
@@ -0,0 +1,139 @@
+use cap_audio::{AudioData, AudioStream, ChunkRead};
+use cap_enc_ffmpeg::RelocatableSource;
+use std::{
+ error::Error,
+ fs, io,
+ path::{Path, PathBuf},
+ sync::{Arc, atomic::AtomicBool},
+ time::Instant,
+};
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let input = std::env::args_os()
+ .nth(1)
+ .map(PathBuf::from)
+ .ok_or_else(|| io::Error::other("Expected one audio file path"))?;
+ ffmpeg::init()?;
+ let reference = AudioData::from_file(&input).map_err(io::Error::other)?;
+ let directory = tempfile::tempdir()?;
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ fs::create_dir(&original)?;
+ let relative = input
+ .file_name()
+ .map(Path::new)
+ .ok_or_else(|| io::Error::other("Missing audio file name"))?;
+ fs::copy(&input, original.join(relative))?;
+ let source = RelocatableSource::new(original.clone())?;
+ let started = Instant::now();
+ let mut stream =
+ AudioStream::open_relocatable(&source, [relative], Arc::new(AtomicBool::new(false)))?;
+ let mut compared_frames = 0;
+ let mut first_window_ms = None;
+ let mut relocations = Vec::new();
+ let mut move_index = 0;
+ let mut root_is_original = true;
+ let thresholds = [
+ 0,
+ reference.sample_count() / 4,
+ reference.sample_count() / 2,
+ reference.sample_count() * 3 / 4,
+ ];
+ let mut failed_move_verified = false;
+ loop {
+ match stream.read_chunk(12_000)? {
+ ChunkRead::Chunk(chunk) => {
+ first_window_ms.get_or_insert_with(|| started.elapsed().as_secs_f64() * 1_000.0);
+ if chunk.source_start_sample as usize != compared_frames
+ || chunk.channels != reference.channels()
+ {
+ return Err(io::Error::other("Audio frame position or channels differ").into());
+ }
+ let sample_offset = compared_frames * usize::from(reference.channels());
+ let expected = reference
+ .samples()
+ .get(sample_offset..sample_offset + chunk.samples.len())
+ .ok_or_else(|| io::Error::other("Decoded output exceeds reference"))?;
+ for (index, (actual, expected)) in chunk.samples.iter().zip(expected).enumerate() {
+ if actual.to_bits() != expected.to_bits() {
+ return Err(io::Error::other(format!(
+ "Decoded sample differs at {}",
+ sample_offset + index
+ ))
+ .into());
+ }
+ }
+ compared_frames += chunk.samples.len() / usize::from(reference.channels());
+ if move_index < thresholds.len() && compared_frames >= thresholds[move_index] {
+ let target = if root_is_original {
+ &retained
+ } else {
+ &original
+ };
+ let move_started = Instant::now();
+ source.relocate(target.clone())?;
+ relocations.push(move_started.elapsed().as_secs_f64() * 1_000.0);
+ root_is_original = !root_is_original;
+ move_index += 1;
+ if move_index == 1 {
+ if source
+ .relocate(directory.path().join("missing/target"))
+ .is_ok()
+ {
+ return Err(io::Error::other(
+ "Injected relocation unexpectedly succeeded",
+ )
+ .into());
+ }
+ failed_move_verified = true;
+ fs::create_dir(&original)?;
+ fs::write(original.join(relative), b"published output")?;
+ if fs::read(original.join(relative))? != b"published output" {
+ return Err(
+ io::Error::other("Ordinary output path was redirected").into()
+ );
+ }
+ fs::remove_file(original.join(relative))?;
+ fs::remove_dir(&original)?;
+ }
+ }
+ }
+ ChunkRead::Eof { next_sample } => {
+ if next_sample as usize != reference.sample_count()
+ || compared_frames != reference.sample_count()
+ {
+ return Err(io::Error::other("Decoded EOF differs from reference").into());
+ }
+ break;
+ }
+ }
+ }
+ let validation_ms = started.elapsed().as_secs_f64() * 1_000.0;
+ let source_path = if root_is_original {
+ original.join(relative)
+ } else {
+ retained.join(relative)
+ };
+ if fs::read(source_path)? != fs::read(&input)? {
+ return Err(io::Error::other("Retained source bytes changed").into());
+ }
+ if stream.validate_to_end()? as usize != compared_frames {
+ return Err(io::Error::other("Repeated EOF changed").into());
+ }
+ println!(
+ "{}",
+ serde_json::json!({
+ "input": input,
+ "channels": reference.channels(),
+ "comparedFrames": compared_frames,
+ "everyDecodedSampleBitMatches": true,
+ "retainedSourceExact": true,
+ "failedRelocationPreservedReader": failed_move_verified,
+ "relocationMs": relocations,
+ "first250msWindowMs": first_window_ms,
+ "validationMs": validation_ms,
+ "method": "Single managed decoder remains alive through publication and rollback; full reference decode occurs before timing. Validation time includes exact PCM comparisons and relocation. This is not a Stop-to-editor benchmark."
+ })
+ );
+ Ok(())
+}
diff --git a/crates/audio/src/audio_data.rs b/crates/audio/src/audio_data.rs
index 490188e68..1d025b321 100644
--- a/crates/audio/src/audio_data.rs
+++ b/crates/audio/src/audio_data.rs
@@ -98,6 +98,7 @@ impl AudioData {
}
let mut decoded_frame = ffmpeg::frame::Audio::empty();
+ let mut resampler_output = ResamplerOutput::new();
let mut samples = Vec::new();
let mut resampled_samples = Vec::new();
let mut next_source_sample = if sought { None } else { Some(0usize) };
@@ -117,7 +118,12 @@ impl AudioData {
while decoder.receive_frame(&mut decoded_frame).is_ok() {
if range.is_none() {
- run_resampler(&mut resampler, &decoded_frame, &mut samples)?;
+ run_resampler(
+ &mut resampler,
+ &decoded_frame,
+ &mut resampler_output,
+ &mut samples,
+ )?;
continue;
}
@@ -138,7 +144,12 @@ impl AudioData {
}
resampled_samples.clear();
- run_resampler(&mut resampler, &decoded_frame, &mut resampled_samples)?;
+ run_resampler(
+ &mut resampler,
+ &decoded_frame,
+ &mut resampler_output,
+ &mut resampled_samples,
+ )?;
complete = append_sample_window(
&mut samples,
&resampled_samples,
@@ -158,12 +169,22 @@ impl AudioData {
while decoder.receive_frame(&mut decoded_frame).is_ok() {
if range.is_none() {
- run_resampler(&mut resampler, &decoded_frame, &mut samples)?;
+ run_resampler(
+ &mut resampler,
+ &decoded_frame,
+ &mut resampler_output,
+ &mut samples,
+ )?;
continue;
}
resampled_samples.clear();
- run_resampler(&mut resampler, &decoded_frame, &mut resampled_samples)?;
+ run_resampler(
+ &mut resampler,
+ &decoded_frame,
+ &mut resampler_output,
+ &mut resampled_samples,
+ )?;
complete = append_sample_window(
&mut samples,
&resampled_samples,
@@ -180,7 +201,11 @@ impl AudioData {
if !complete {
if range.is_some() {
resampled_samples.clear();
- flush_resampler(&mut resampler, &mut resampled_samples)?;
+ flush_resampler(
+ &mut resampler,
+ &mut resampler_output,
+ &mut resampled_samples,
+ )?;
append_sample_window(
&mut samples,
&resampled_samples,
@@ -190,7 +215,7 @@ impl AudioData {
covered_source_end_sample,
);
} else {
- flush_resampler(&mut resampler, &mut samples)?;
+ flush_resampler(&mut resampler, &mut resampler_output, &mut samples)?;
}
}
}
@@ -228,8 +253,8 @@ impl AudioData {
&& source_end_sample <= self.covered_source_end_sample
}
- #[cfg(test)]
- pub(crate) fn from_raw_f32(samples: Vec<f32>, channels: u16) -> Self {
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn from_raw_f32(samples: Vec<f32>, channels: u16) -> Self {
Self {
samples,
channels,
@@ -267,43 +292,95 @@ fn target_channels_for_source(channels: u16) -> u16 {
if channels <= 1 { 1 } else { 2 }
}
+pub(crate) struct ResamplerOutput {
+ frame: FFAudio,
+ capacity: usize,
+}
+
+impl ResamplerOutput {
+ pub(crate) fn new() -> Self {
+ Self {
+ frame: FFAudio::empty(),
+ capacity: 0,
+ }
+ }
+
+ pub(crate) fn prepare(
+ &mut self,
+ resampler: &resampling::Context,
+ capacity: usize,
+ ) -> &mut FFAudio {
+ if capacity > self.capacity {
+ let target = resampler.output();
+ self.frame = FFAudio::new(target.format, capacity, target.channel_layout);
+ self.capacity = capacity;
+ }
+ self.frame.set_samples(capacity);
+ &mut self.frame
+ }
+
+ pub(crate) fn run(
+ &mut self,
+ resampler: &mut resampling::Context,
+ decoded_frame: &FFAudio,
+ ) -> Result<(), String> {
+ let capacity = resample_capacity(resampler, decoded_frame.samples());
+ let frame = self.prepare(resampler, capacity);
+ resampler
+ .run(decoded_frame, frame)
+ .map_err(|error| format!("Run Resampler / {error}"))
+ .map(|_| ())
+ }
+
+ pub(crate) fn samples(&self) -> Result<&[f32], String> {
+ if self.frame.samples() == 0 {
+ return Ok(&[]);
+ }
+ let byte_len = self
+ .frame
+ .samples()
+ .saturating_mul(self.frame.channels() as usize)
+ .saturating_mul(std::mem::size_of::<f32>());
+ self.frame
+ .data(0)
+ .get(..byte_len)
+ .map(|bytes| unsafe { cast_bytes_to_f32_slice(bytes) })
+ .ok_or_else(|| "Resampled frame data shorter than expected".to_string())
+ }
+}
+
fn run_resampler(
resampler: &mut resampling::Context,
decoded_frame: &FFAudio,
+ output: &mut ResamplerOutput,
samples: &mut Vec<f32>,
) -> Result<(), String> {
- let target = *resampler.output();
- let capacity = resample_capacity(resampler, decoded_frame.samples());
- let mut resampled_frame = FFAudio::new(target.format, capacity, target.channel_layout);
-
- resampler
- .run(decoded_frame, &mut resampled_frame)
- .map_err(|e| format!("Run Resampler / {e}"))?;
-
- append_resampled_frame(samples, &resampled_frame)
+ output.run(resampler, decoded_frame)?;
+ samples.extend(output.samples()?);
+ Ok(())
}
fn flush_resampler(
resampler: &mut resampling::Context,
+ output: &mut ResamplerOutput,
samples: &mut Vec<f32>,
) -> Result<(), String> {
for _ in 0..64 {
let Some(delay) = resampler.delay() else {
break;
};
- let target = *resampler.output();
let capacity = delay
.output
.max(1)
.saturating_add(16)
.min(i64::from(i32::MAX)) as usize;
- let mut resampled_frame = FFAudio::new(target.format, capacity, target.channel_layout);
+ let resampled_frame = output.prepare(resampler, capacity);
let remaining = resampler
- .flush(&mut resampled_frame)
+ .flush(resampled_frame)
.map_err(|e| format!("Flush Resampler / {e}"))?;
let output_samples = resampled_frame.samples();
- append_resampled_frame(samples, &resampled_frame)?;
+ append_resampled_frame(samples, resampled_frame)?;
if remaining.is_none() || output_samples == 0 {
break;
@@ -353,6 +430,86 @@ mod tests {
use super::*;
use std::path::Path;
+ #[test]
+ fn reused_resampler_output_matches_fresh_buffers_for_variable_frames() {
+ for source_rate in [16_000, 44_100, 48_000, 96_000] {
+ for channels in [1, 2, 6] {
+ let source_format = avformat::Sample::F32(avformat::sample::Type::Planar);
+ let source_layout = ChannelLayout::default(channels);
+ let output_layout =
+ ChannelLayout::default(i32::from(target_channels_for_source(channels as u16)));
+ let create_resampler = || {
+ let mut options = ffmpeg::Dictionary::new();
+ options.set("filter_size", "128");
+ options.set("cutoff", "0.97");
+ resampling::Context::get_with(
+ source_format,
+ source_layout,
+ source_rate,
+ AudioData::SAMPLE_FORMAT,
+ output_layout,
+ AudioData::SAMPLE_RATE,
+ options,
+ )
+ .unwrap()
+ };
+ let mut reference_resampler = create_resampler();
+ let mut candidate_resampler = create_resampler();
+ let mut reference = Vec::new();
+ let mut candidate = Vec::new();
+ let mut output = ResamplerOutput::new();
+ for (index, count) in [1, 511, 1024, 2048, 37, 960, 3].into_iter().enumerate() {
+ let mut input = FFAudio::new(source_format, count, source_layout);
+ input.set_rate(source_rate);
+ for channel in 0..channels as usize {
+ for (sample_index, sample) in
+ input.plane_mut::<f32>(channel).iter_mut().enumerate()
+ {
+ *sample = ((sample_index * 13 + index * 71 + channel * 3) % 101) as f32
+ / 101.0
+ - 0.5;
+ }
+ }
+ let capacity = resample_capacity(&reference_resampler, count);
+ let mut frame = FFAudio::new(AudioData::SAMPLE_FORMAT, capacity, output_layout);
+ reference_resampler.run(&input, &mut frame).unwrap();
+ append_resampled_frame(&mut reference, &frame).unwrap();
+ run_resampler(
+ &mut candidate_resampler,
+ &input,
+ &mut output,
+ &mut candidate,
+ )
+ .unwrap();
+ }
+ for _ in 0..64 {
+ let Some(delay) = reference_resampler.delay() else {
+ break;
+ };
+ let mut frame = FFAudio::new(
+ AudioData::SAMPLE_FORMAT,
+ delay.output.max(1).saturating_add(16) as usize,
+ output_layout,
+ );
+ let remaining = reference_resampler.flush(&mut frame).unwrap();
+ append_resampled_frame(&mut reference, &frame).unwrap();
+ if remaining.is_none() || frame.samples() == 0 {
+ break;
+ }
+ }
+ flush_resampler(&mut candidate_resampler, &mut output, &mut candidate).unwrap();
+ assert_eq!(candidate.len(), reference.len());
+ assert!(
+ candidate
+ .iter()
+ .zip(&reference)
+ .all(|(actual, expected)| actual.to_bits() == expected.to_bits()),
+ "Resampler samples differ at {source_rate} Hz with {channels} channels"
+ );
+ }
+ }
+ }
+
/// Writes an s16le PCM WAV where channel `c` of every frame carries the constant
/// `amplitudes[c]` (DC). DC survives both resampling and downmix unchanged, so the
/// decoded output's energy is a deterministic function of which channels actually
diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs
index 2d9926518..f267d790a 100644
--- a/crates/audio/src/lib.rs
+++ b/crates/audio/src/lib.rs
@@ -1,6 +1,7 @@
mod audio_data;
mod calibration_store;
mod latency;
+mod progressive;
mod renderer;
mod streaming;
mod sync_analysis;
@@ -9,6 +10,7 @@ mod transcription_timing;
pub use audio_data::*;
pub use calibration_store::*;
pub use latency::*;
+pub use progressive::*;
pub use renderer::*;
pub use streaming::*;
pub use sync_analysis::*;
diff --git a/crates/audio/src/progressive.rs b/crates/audio/src/progressive.rs
new file mode 100644
index 000000000..82ac48b2c
--- /dev/null
+++ b/crates/audio/src/progressive.rs
@@ -0,0 +1,1162 @@
+mod managed;
+pub use managed::*;
+
+#[cfg(feature = "test-support")]
+mod test_support;
+#[cfg(feature = "test-support")]
+pub use test_support::ProgressiveAudioTestProducer;
+
+use crate::{AudioData, AudioSampleSource, AudioStream, ChunkRead};
+use std::{
+ ops::Range,
+ path::PathBuf,
+ sync::{Arc, Mutex, atomic::AtomicBool},
+};
+use tokio::sync::watch;
+
+const BLOCK_FRAMES: usize = 32_768;
+
+pub fn waveform_peaks<'a>(samples: impl Iterator<Item = &'a f32>, channels: u16) -> Vec<f32> {
+ let block_samples = AudioData::SAMPLE_RATE as usize / 10 * usize::from(channels.max(1));
+ let mut peaks = Vec::new();
+ let mut sum = 0.0_f32;
+ let mut count = 0;
+ for sample in samples {
+ sum += sample.abs();
+ count += 1;
+ if count == block_samples {
+ peaks.push(sum / count as f32);
+ sum = 0.0;
+ count = 0;
+ }
+ }
+ if count > 0 {
+ peaks.push(sum / count as f32);
+ }
+ for peak in &mut peaks {
+ *peak = if *peak > 0.0 {
+ 20.0 * peak.log10()
+ } else {
+ -60.0
+ };
+ }
+ peaks
+}
+
+pub struct DecodedAudio {
+ storage: AudioStorage,
+ channels: u16,
+ frames: usize,
+}
+
+enum AudioStorage {
+ Contiguous(Arc<AudioData>),
+ Blocks(Vec<Arc<Vec<f32>>>),
+}
+
+impl DecodedAudio {
+ pub fn channels(&self) -> u16 {
+ self.channels
+ }
+
+ pub fn sample_count(&self) -> usize {
+ self.frames
+ }
+
+ pub fn sample_slices(&self) -> impl Iterator<Item = &[f32]> {
+ let (contiguous, blocks): (Option<&[f32]>, &[Arc<Vec<f32>>]) = match &self.storage {
+ AudioStorage::Contiguous(data) => (Some(data.samples()), &[]),
+ AudioStorage::Blocks(blocks) => (None, blocks),
+ };
+ contiguous
+ .into_iter()
+ .chain(blocks.iter().map(|block| block.as_slice()))
+ }
+}
+
+impl From<Arc<AudioData>> for DecodedAudio {
+ fn from(data: Arc<AudioData>) -> Self {
+ Self {
+ channels: data.channels(),
+ frames: data.sample_count(),
+ storage: AudioStorage::Contiguous(data),
+ }
+ }
+}
+
+impl AudioSampleSource for DecodedAudio {
+ fn channels(&self) -> u16 {
+ self.channels
+ }
+
+ fn sample_count(&self) -> usize {
+ self.frames
+ }
+
+ fn sample(&self, index: usize) -> Option<&f32> {
+ match &self.storage {
+ AudioStorage::Contiguous(data) => data.samples().get(index),
+ AudioStorage::Blocks(blocks) => {
+ let block_samples = BLOCK_FRAMES * usize::from(self.channels);
+ blocks
+ .get(index / block_samples)?
+ .get(index % block_samples)
+ }
+ }
+ }
+
+ fn sample_slice(&self, range: Range<usize>) -> Option<&[f32]> {
+ match &self.storage {
+ AudioStorage::Contiguous(data) => data.sample_slice(range),
+ AudioStorage::Blocks(blocks) => {
+ let block_samples = BLOCK_FRAMES * usize::from(self.channels);
+ let block = range.start / block_samples;
+ let base = block * block_samples;
+ blocks
+ .get(block)?
+ .get(range.start - base..range.end.checked_sub(base)?)
+ }
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct AudioLoadProgress {
+ pub ready_frames: usize,
+ pub channels: Option<u16>,
+ pub complete: bool,
+ pub error: Option<String>,
+}
+
+#[derive(Clone, Default)]
+struct LoadState {
+ progress: AudioLoadProgress,
+ result: Option<LoadResult>,
+}
+
+type LoadResult = Result<Option<Arc<DecodedAudio>>, String>;
+
+#[derive(Default)]
+struct PendingBlocks {
+ blocks: Vec<Arc<Vec<f32>>>,
+ frames: usize,
+ channels: Option<u16>,
+}
+
+impl PendingBlocks {
+ fn append(&mut self, chunk: crate::AudioChunk) -> Result<(), String> {
+ let channels = usize::from(chunk.channels);
+ if channels == 0
+ || self
+ .channels
+ .is_some_and(|previous| previous != chunk.channels)
+ || chunk.source_start_sample != self.frames as u64
+ || chunk.samples.is_empty()
+ || chunk.samples.len() % channels != 0
+ || chunk.samples.len() / channels > BLOCK_FRAMES
+ || self
+ .blocks
+ .last()
+ .is_some_and(|last| last.len() != BLOCK_FRAMES * channels)
+ {
+ return Err("Audio blocks are not contiguous complete sample frames".into());
+ }
+ self.channels = Some(chunk.channels);
+ self.frames = self
+ .frames
+ .checked_add(chunk.samples.len() / channels)
+ .ok_or_else(|| "Decoded audio is too long".to_string())?;
+ self.blocks.push(Arc::new(chunk.samples));
+ Ok(())
+ }
+}
+
+#[derive(Clone)]
+pub struct ProgressiveAudio {
+ rx: watch::Receiver<LoadState>,
+ // Full-track waiters must not wake for each published PCM block.
+ complete: watch::Receiver<Option<LoadResult>>,
+ pending: Arc<Mutex<PendingBlocks>>,
+}
+
+impl ProgressiveAudio {
+ pub fn none() -> Self {
+ Self::ready(None)
+ }
+
+ pub fn ready(audio: Option<Arc<AudioData>>) -> Self {
+ let audio = audio.map(|audio| Arc::new(DecodedAudio::from(audio)));
+ let state = LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: audio.as_ref().map_or(0, |audio| audio.sample_count()),
+ channels: audio.as_ref().map(|audio| audio.channels()),
+ complete: true,
+ error: None,
+ },
+ result: Some(Ok(audio)),
+ };
+ let (_complete_tx, complete) = watch::channel(state.result.clone());
+ let (_tx, rx) = watch::channel(state);
+ Self {
+ rx,
+ complete,
+ pending: Arc::default(),
+ }
+ }
+
+ pub fn from_result(result: Result<Option<Arc<DecodedAudio>>, String>) -> Self {
+ let audio = result.as_ref().ok().and_then(Option::as_ref);
+ let state = LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: audio.map_or(0, |audio| audio.sample_count()),
+ channels: audio.map(|audio| audio.channels()),
+ complete: result.is_ok(),
+ error: result.as_ref().err().cloned(),
+ },
+ result: Some(result),
+ };
+ let (_complete_tx, complete) = watch::channel(state.result.clone());
+ let (_tx, rx) = watch::channel(state);
+ Self {
+ rx,
+ complete,
+ pending: Arc::default(),
+ }
+ }
+
+ pub fn spawn(path: PathBuf, label: String) -> Self {
+ let (tx, rx) = watch::channel(LoadState::default());
+ let (complete_tx, complete) = watch::channel(None);
+ let pending = Arc::new(Mutex::new(PendingBlocks::default()));
+ let producer = pending.clone();
+ tokio::task::spawn_blocking(move || {
+ let result =
+ Self::decode(path, &producer, &tx).map_err(|error| format!("{label} / {error}"));
+ if result.is_err()
+ && let Ok(mut pending) = producer.lock()
+ {
+ pending.blocks.clear();
+ }
+ let mut state = tx.borrow().clone();
+ state.progress.complete = result.is_ok();
+ state.progress.error = result.as_ref().err().cloned();
+ if let Ok(audio) = &result {
+ state.progress.ready_frames = audio.sample_count();
+ state.progress.channels = Some(audio.channels());
+ }
+ state.result = Some(result.map(Some));
+ let result = state.result.clone();
+ tx.send_replace(state);
+ complete_tx.send_replace(result);
+ });
+ Self {
+ rx,
+ complete,
+ pending,
+ }
+ }
+
+ fn decode(
+ path: PathBuf,
+ pending: &Mutex<PendingBlocks>,
+ tx: &watch::Sender<LoadState>,
+ ) -> Result<Arc<DecodedAudio>, String> {
+ let stream = AudioStream::open(&path, Arc::new(AtomicBool::new(false)))
+ .map_err(|error| error.to_string())?;
+ Self::decode_stream(stream, pending, tx)
+ }
+
+ fn decode_stream(
+ mut stream: AudioStream,
+ pending: &Mutex<PendingBlocks>,
+ tx: &watch::Sender<LoadState>,
+ ) -> Result<Arc<DecodedAudio>, String> {
+ loop {
+ if tx.is_closed() {
+ return Err("Audio load no longer has readers".into());
+ }
+ match stream
+ .read_chunk(BLOCK_FRAMES)
+ .map_err(|error| error.to_string())?
+ {
+ ChunkRead::Chunk(chunk) => {
+ let progress = {
+ let mut pending = pending.lock().map_err(|error| error.to_string())?;
+ pending.append(chunk)?;
+ AudioLoadProgress {
+ ready_frames: pending.frames,
+ channels: pending.channels,
+ complete: false,
+ error: None,
+ }
+ };
+ tx.send_replace(LoadState {
+ progress,
+ result: None,
+ });
+ }
+ ChunkRead::Eof { next_sample } => {
+ let mut pending = pending.lock().map_err(|error| error.to_string())?;
+ if next_sample != pending.frames as u64 {
+ return Err("Audio EOF does not match the decoded sample count".into());
+ }
+ return Ok(Arc::new(DecodedAudio {
+ channels: stream.channels(),
+ frames: pending.frames,
+ storage: AudioStorage::Blocks(std::mem::take(&mut pending.blocks)),
+ }));
+ }
+ }
+ }
+ }
+
+ pub fn progress(&self) -> AudioLoadProgress {
+ let mut progress = self.rx.borrow().progress.clone();
+ if !progress.complete && progress.error.is_none() && self.rx.has_changed().is_err() {
+ progress.error = Some("Audio load task was dropped".into());
+ }
+ progress
+ }
+
+ pub async fn get(&self) -> Result<Option<Arc<DecodedAudio>>, String> {
+ let mut rx = self.complete.clone();
+ loop {
+ if let Some(result) = rx.borrow_and_update().clone() {
+ return result;
+ }
+ rx.changed()
+ .await
+ .map_err(|_| "Audio load task was dropped".to_string())?;
+ }
+ }
+
+ pub fn try_window(&self, range: Range<usize>) -> Result<AudioWindowRead, String> {
+ if range.start > range.end {
+ return Err("Invalid audio sample range".into());
+ }
+ let state = {
+ let state = self.rx.borrow();
+ if state.result.is_none()
+ && state.progress.error.is_none()
+ && self.rx.has_changed().is_err()
+ {
+ return Err("Audio load task was dropped".into());
+ }
+ state.clone()
+ };
+ if let Some(result) = state.result {
+ return result
+ .map(|audio| AudioWindowRead::Ready(audio.map(AudioSampleWindow::complete)));
+ }
+ if let Some(error) = state.progress.error {
+ return Err(error);
+ }
+ if range.end > state.progress.ready_frames {
+ return Ok(AudioWindowRead::Pending);
+ }
+ let pending = self.pending.lock().map_err(|error| error.to_string())?;
+ let first_block = range.start / BLOCK_FRAMES;
+ let end_block = range.end.div_ceil(BLOCK_FRAMES);
+ let Some(blocks) = pending.blocks.get(first_block..end_block) else {
+ return Ok(AudioWindowRead::Pending);
+ };
+ let Some(channels) = pending.channels else {
+ return Ok(AudioWindowRead::Pending);
+ };
+ let available =
+ first_block * BLOCK_FRAMES..end_block.saturating_mul(BLOCK_FRAMES).min(pending.frames);
+ Ok(AudioWindowRead::Ready(Some(AudioSampleWindow {
+ storage: WindowStorage::Blocks {
+ first_block,
+ blocks: blocks.to_vec(),
+ },
+ channels,
+ frames: available.end,
+ available,
+ })))
+ }
+
+ pub async fn window(&self, range: Range<usize>) -> Result<Option<AudioSampleWindow>, String> {
+ let mut rx = self.rx.clone();
+ loop {
+ drop(rx.borrow_and_update());
+ if let AudioWindowRead::Ready(window) = self.try_window(range.clone())? {
+ return Ok(window);
+ }
+ rx.changed()
+ .await
+ .map_err(|_| "Audio load task was dropped".to_string())?;
+ }
+ }
+}
+
+pub enum AudioWindowRead {
+ Pending,
+ Ready(Option<AudioSampleWindow>),
+}
+
+// Pending windows use global source indices but retain only available_range;
+// sample_count alone does not establish coverage or EOF for a mixer.
+pub struct AudioSampleWindow {
+ storage: WindowStorage,
+ channels: u16,
+ frames: usize,
+ available: Range<usize>,
+}
+
+enum WindowStorage {
+ Complete(Arc<DecodedAudio>),
+ Blocks {
+ first_block: usize,
+ blocks: Vec<Arc<Vec<f32>>>,
+ },
+}
+
+impl AudioSampleWindow {
+ fn complete(audio: Arc<DecodedAudio>) -> Self {
+ Self {
+ channels: audio.channels(),
+ frames: audio.sample_count(),
+ available: 0..audio.sample_count(),
+ storage: WindowStorage::Complete(audio),
+ }
+ }
+
+ pub fn available_range(&self) -> Range<usize> {
+ self.available.clone()
+ }
+
+ pub fn complete_sample_count(&self) -> Option<usize> {
+ match &self.storage {
+ WindowStorage::Complete(audio) => Some(audio.sample_count()),
+ WindowStorage::Blocks { .. } => None,
+ }
+ }
+}
+
+impl AudioSampleSource for AudioSampleWindow {
+ fn channels(&self) -> u16 {
+ self.channels
+ }
+
+ fn sample_count(&self) -> usize {
+ self.frames
+ }
+
+ fn sample(&self, index: usize) -> Option<&f32> {
+ match &self.storage {
+ WindowStorage::Complete(audio) => audio.sample(index),
+ WindowStorage::Blocks {
+ first_block,
+ blocks,
+ } => {
+ let block_samples = BLOCK_FRAMES * usize::from(self.channels);
+ let block = (index / block_samples).checked_sub(*first_block)?;
+ blocks.get(block)?.get(index % block_samples)
+ }
+ }
+ }
+
+ fn sample_slice(&self, range: Range<usize>) -> Option<&[f32]> {
+ match &self.storage {
+ WindowStorage::Complete(audio) => audio.sample_slice(range),
+ WindowStorage::Blocks {
+ first_block,
+ blocks,
+ } => {
+ let block_samples = BLOCK_FRAMES * usize::from(self.channels);
+ let block = range.start / block_samples;
+ let base = block * block_samples;
+ blocks
+ .get(block.checked_sub(*first_block)?)?
+ .get(range.start - base..range.end.checked_sub(base)?)
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::{io::Write, path::Path, time::Duration};
+
+ fn wave(path: &Path, rate: u32, channels: u16) {
+ let frames = rate * 3 + 17;
+ let bytes = frames * u32::from(channels) * 2;
+ let mut file = std::fs::File::create(path).unwrap();
+ file.write_all(b"RIFF").unwrap();
+ file.write_all(&(bytes + 36).to_le_bytes()).unwrap();
+ file.write_all(b"WAVEfmt ").unwrap();
+ file.write_all(&16_u32.to_le_bytes()).unwrap();
+ file.write_all(&1_u16.to_le_bytes()).unwrap();
+ file.write_all(&channels.to_le_bytes()).unwrap();
+ file.write_all(&rate.to_le_bytes()).unwrap();
+ file.write_all(&(rate * u32::from(channels) * 2).to_le_bytes())
+ .unwrap();
+ file.write_all(&(channels * 2).to_le_bytes()).unwrap();
+ file.write_all(&16_u16.to_le_bytes()).unwrap();
+ file.write_all(b"data").unwrap();
+ file.write_all(&bytes.to_le_bytes()).unwrap();
+ for frame in 0..frames {
+ for channel in 0..channels {
+ let sample = ((frame * 17 + u32::from(channel) * 971) % 60_000) as i32 - 30_000;
+ file.write_all(&(sample as i16).to_le_bytes()).unwrap();
+ }
+ }
+ }
+
+ struct TestProducer {
+ progress: watch::Sender<LoadState>,
+ complete: watch::Sender<Option<LoadResult>>,
+ }
+
+ impl TestProducer {
+ fn send_replace(&self, state: LoadState) {
+ let result = state.result.clone();
+ self.progress.send_replace(state);
+ if result.is_some() {
+ self.complete.send_replace(result);
+ }
+ }
+ }
+
+ fn controlled() -> (ProgressiveAudio, TestProducer) {
+ let (tx, rx) = watch::channel(LoadState::default());
+ let (complete_tx, complete) = watch::channel(None);
+ (
+ ProgressiveAudio {
+ rx,
+ complete,
+ pending: Arc::default(),
+ },
+ TestProducer {
+ progress: tx,
+ complete: complete_tx,
+ },
+ )
+ }
+
+ fn append(loader: &ProgressiveAudio, tx: &TestProducer, frames: usize) {
+ let mut pending = loader.pending.lock().unwrap();
+ let start = pending.frames;
+ pending
+ .append(crate::AudioChunk {
+ source_start_sample: start as u64,
+ channels: 2,
+ samples: (start * 2..(start + frames) * 2)
+ .map(|sample| sample as f32)
+ .collect(),
+ })
+ .unwrap();
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: pending.frames,
+ channels: pending.channels,
+ complete: false,
+ error: None,
+ },
+ result: None,
+ });
+ }
+
+ #[test]
+ fn pending_window_reports_only_retained_blocks_and_never_implies_eof() {
+ let (loader, tx) = controlled();
+ assert!(matches!(
+ loader.try_window(0..100).unwrap(),
+ AudioWindowRead::Pending
+ ));
+ for _ in 0..3 {
+ append(&loader, &tx, BLOCK_FRAMES);
+ }
+ let AudioWindowRead::Ready(Some(window)) = loader
+ .try_window(BLOCK_FRAMES + 17..BLOCK_FRAMES + 117)
+ .unwrap()
+ else {
+ panic!("Published samples were not ready");
+ };
+ assert_eq!(window.available_range(), BLOCK_FRAMES..BLOCK_FRAMES * 2);
+ assert_eq!(window.sample_count(), BLOCK_FRAMES * 2);
+ assert_eq!(window.complete_sample_count(), None);
+ assert!(window.sample(BLOCK_FRAMES * 2 - 1).is_none());
+ assert!(window.sample(BLOCK_FRAMES * 4).is_none());
+ let pending = loader.pending.lock().unwrap();
+ assert_eq!(Arc::strong_count(&pending.blocks[0]), 1);
+ assert_eq!(Arc::strong_count(&pending.blocks[1]), 2);
+ assert_eq!(Arc::strong_count(&pending.blocks[2]), 1);
+ assert!(std::ptr::eq(
+ window.sample(BLOCK_FRAMES * 2).unwrap(),
+ &pending.blocks[1][0]
+ ));
+ drop(pending);
+ append(&loader, &tx, BLOCK_FRAMES);
+ assert_eq!(window.available_range(), BLOCK_FRAMES..BLOCK_FRAMES * 2);
+ assert_eq!(window.sample_count(), BLOCK_FRAMES * 2);
+ assert!(matches!(
+ loader
+ .try_window(BLOCK_FRAMES * 4 - 1..BLOCK_FRAMES * 4 + 1)
+ .unwrap(),
+ AudioWindowRead::Pending
+ ));
+ }
+
+ #[test]
+ fn moving_blocks_to_completion_does_not_publish_a_gap_as_silence() {
+ let (loader, tx) = controlled();
+ append(&loader, &tx, BLOCK_FRAMES);
+ let audio = {
+ let mut pending = loader.pending.lock().unwrap();
+ Arc::new(DecodedAudio {
+ channels: 2,
+ frames: pending.frames,
+ storage: AudioStorage::Blocks(std::mem::take(&mut pending.blocks)),
+ })
+ };
+ assert!(matches!(
+ loader.try_window(0..100).unwrap(),
+ AudioWindowRead::Pending
+ ));
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: BLOCK_FRAMES,
+ channels: Some(2),
+ complete: true,
+ error: None,
+ },
+ result: Some(Ok(Some(audio))),
+ });
+ let AudioWindowRead::Ready(Some(window)) = loader
+ .try_window(BLOCK_FRAMES - 3..BLOCK_FRAMES + 3)
+ .unwrap()
+ else {
+ panic!("Completed samples were not ready");
+ };
+ assert_eq!(window.available_range(), 0..BLOCK_FRAMES);
+ assert_eq!(window.complete_sample_count(), Some(BLOCK_FRAMES));
+ assert_eq!(
+ window.sample(BLOCK_FRAMES * 2 - 1),
+ Some(&((BLOCK_FRAMES * 2 - 1) as f32))
+ );
+ assert!(window.sample(BLOCK_FRAMES * 2).is_none());
+ }
+
+ #[test]
+ fn nonblocking_window_distinguishes_absence_failure_and_dropped_producers() {
+ assert!(matches!(
+ ProgressiveAudio::none().try_window(0..100).unwrap(),
+ AudioWindowRead::Ready(None)
+ ));
+ let (loader, tx) = controlled();
+ append(&loader, &tx, BLOCK_FRAMES);
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ error: Some("corrupt tail".into()),
+ ..loader.progress()
+ },
+ result: Some(Err("corrupt tail".into())),
+ });
+ assert_eq!(
+ loader.try_window(0..100).err().as_deref(),
+ Some("corrupt tail")
+ );
+ let (loader, tx) = controlled();
+ append(&loader, &tx, BLOCK_FRAMES);
+ drop(tx);
+ assert_eq!(
+ loader.try_window(0..100).err().as_deref(),
+ Some("Audio load task was dropped")
+ );
+ assert_eq!(
+ loader
+ .try_window(Range { start: 2, end: 1 })
+ .err()
+ .as_deref(),
+ Some("Invalid audio sample range")
+ );
+ }
+
+ #[test]
+ fn terminal_publication_and_sender_drop_cannot_erase_successful_samples() {
+ let audio = Arc::new(DecodedAudio::from(Arc::new(AudioData::from_raw_f32(
+ vec![0.25, -0.5, 0.75, 1.0],
+ 2,
+ ))));
+ for _ in 0..512 {
+ let (loader, tx) = controlled();
+ let barrier = std::sync::Barrier::new(2);
+ std::thread::scope(|scope| {
+ let barrier = &barrier;
+ let expected = audio.clone();
+ let worker = scope.spawn(move || {
+ barrier.wait();
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: 2,
+ channels: Some(2),
+ complete: true,
+ error: None,
+ },
+ result: Some(Ok(Some(expected))),
+ });
+ });
+ barrier.wait();
+ let window = loop {
+ match loader.try_window(0..2).unwrap() {
+ AudioWindowRead::Pending => std::thread::yield_now(),
+ AudioWindowRead::Ready(Some(window)) => break window,
+ AudioWindowRead::Ready(None) => panic!("Completed audio was lost"),
+ }
+ };
+ worker.join().unwrap();
+ assert_eq!(window.complete_sample_count(), Some(2));
+ assert!(std::ptr::eq(
+ window.sample(0).unwrap(),
+ audio.sample(0).unwrap()
+ ));
+ });
+ }
+ }
+
+ #[test]
+ fn short_pending_tail_and_empty_ranges_do_not_claim_future_samples() {
+ let (loader, tx) = controlled();
+ assert!(matches!(
+ loader.try_window(usize::MAX..usize::MAX).unwrap(),
+ AudioWindowRead::Pending
+ ));
+ append(&loader, &tx, BLOCK_FRAMES);
+ append(&loader, &tx, 17);
+ let AudioWindowRead::Ready(Some(window)) =
+ loader.try_window(BLOCK_FRAMES..BLOCK_FRAMES + 17).unwrap()
+ else {
+ panic!("Published tail samples were not ready");
+ };
+ assert_eq!(window.available_range(), BLOCK_FRAMES..BLOCK_FRAMES + 17);
+ assert_eq!(window.sample_count(), BLOCK_FRAMES + 17);
+ assert_eq!(window.complete_sample_count(), None);
+ assert!(window.sample((BLOCK_FRAMES + 17) * 2).is_none());
+ assert!(matches!(
+ loader.try_window(BLOCK_FRAMES..BLOCK_FRAMES + 18).unwrap(),
+ AudioWindowRead::Pending
+ ));
+ for at in [0, BLOCK_FRAMES] {
+ let AudioWindowRead::Ready(Some(window)) = loader.try_window(at..at).unwrap() else {
+ panic!("Empty published range was not ready");
+ };
+ assert_eq!(window.available_range(), at..at);
+ assert_eq!(window.complete_sample_count(), None);
+ assert!(window.sample(at * 2).is_none());
+ }
+ let complete =
+ ProgressiveAudio::ready(Some(Arc::new(AudioData::from_raw_f32(vec![0.25, -0.5], 2))));
+ for range in [0..0, usize::MAX..usize::MAX, usize::MAX - 1..usize::MAX] {
+ let AudioWindowRead::Ready(Some(window)) = complete.try_window(range).unwrap() else {
+ panic!("Completed source bounds were not ready");
+ };
+ assert_eq!(window.available_range(), 0..1);
+ assert_eq!(window.complete_sample_count(), Some(1));
+ assert!(window.sample(usize::MAX).is_none());
+ }
+ }
+
+ #[test]
+ fn pending_windows_mix_exact_samples_across_blocks_with_offsets_and_stereo_modes() {
+ for channels in [1, 2] {
+ let samples = (0..BLOCK_FRAMES * 3 * usize::from(channels))
+ .map(|index| ((index * 97 % 127) as f32 - 63.0) / 80.0)
+ .collect::<Vec<_>>();
+ let reference = AudioData::from_raw_f32(samples.clone(), channels);
+ let (loader, tx) = controlled();
+ for chunk in samples.chunks(BLOCK_FRAMES * usize::from(channels)) {
+ let mut pending = loader.pending.lock().unwrap();
+ let source_start_sample = pending.frames as u64;
+ pending
+ .append(crate::AudioChunk {
+ source_start_sample,
+ channels,
+ samples: chunk.to_vec(),
+ })
+ .unwrap();
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: pending.frames,
+ channels: pending.channels,
+ complete: false,
+ error: None,
+ },
+ result: None,
+ });
+ }
+ let AudioWindowRead::Ready(Some(window)) = loader
+ .try_window(BLOCK_FRAMES - 100..BLOCK_FRAMES + 700)
+ .unwrap()
+ else {
+ panic!("Published samples were not ready");
+ };
+ assert_eq!(window.complete_sample_count(), None);
+ for (offset, mode) in [(-17, 0), (0, 1), (17, 2)] {
+ let stereo_mode = || match mode {
+ 1 => crate::StereoMode::MonoL,
+ 2 => crate::StereoMode::MonoR,
+ _ => crate::StereoMode::Stereo,
+ };
+ let mut expected = vec![13.0_f32; 1_028];
+ let mut actual = expected.clone();
+ let expected_frames = crate::render_audio(
+ &[crate::AudioRendererTrack {
+ data: &reference,
+ gain: -4.0,
+ stereo_mode: stereo_mode(),
+ offset,
+ }],
+ BLOCK_FRAMES - 50,
+ 512,
+ 2,
+ &mut expected,
+ );
+ let actual_frames = crate::render_audio(
+ &[crate::AudioRendererTrack {
+ data: &window,
+ gain: -4.0,
+ stereo_mode: stereo_mode(),
+ offset,
+ }],
+ BLOCK_FRAMES - 50,
+ 512,
+ 2,
+ &mut actual,
+ );
+ assert_eq!(actual_frames, expected_frames);
+ assert_eq!(
+ actual
+ .iter()
+ .map(|value| value.to_bits())
+ .collect::<Vec<_>>(),
+ expected
+ .iter()
+ .map(|value| value.to_bits())
+ .collect::<Vec<_>>()
+ );
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn blocks_match_full_decode_and_waveforms_for_mono_stereo_and_surround() {
+ let directory = tempfile::tempdir().unwrap();
+ for rate in [16_000, 44_100, 48_000, 96_000] {
+ for channels in [1, 2, 6] {
+ let path = directory.path().join(format!("{rate}-{channels}.wav"));
+ wave(&path, rate, channels);
+ let reference = AudioData::from_file(&path).unwrap();
+ let loader = ProgressiveAudio::spawn(path, "test".into());
+ let first = loader.window(0..480).await.unwrap().unwrap();
+ for index in 0..480 * usize::from(reference.channels()) {
+ assert_eq!(
+ first.sample(index).unwrap().to_bits(),
+ reference.samples()[index].to_bits()
+ );
+ }
+ let audio = loader.get().await.unwrap().unwrap();
+ assert_eq!(audio.channels(), reference.channels());
+ assert_eq!(audio.sample_count(), reference.sample_count());
+ assert_eq!(
+ audio.sample_slices().flatten().count(),
+ reference.samples().len()
+ );
+ for (index, sample) in reference.samples().iter().enumerate() {
+ assert_eq!(
+ audio.sample(index).unwrap().to_bits(),
+ sample.to_bits(),
+ "{rate}/{channels} at {index}"
+ );
+ }
+ assert!(audio.sample(reference.samples().len()).is_none());
+ let expected = reference
+ .samples()
+ .chunks(4_800 * usize::from(reference.channels()))
+ .map(|chunk| {
+ let sum = chunk.iter().fold(0.0_f32, |sum, sample| sum + sample.abs());
+ let average = sum / chunk.len() as f32;
+ if average > 0.0 {
+ 20.0 * average.log10()
+ } else {
+ -60.0
+ }
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ waveform_peaks(audio.sample_slices().flatten(), audio.channels()),
+ expected
+ );
+ for (position, offset, mode) in [
+ (0, -17, 0),
+ (BLOCK_FRAMES - 3, 0, 1),
+ (BLOCK_FRAMES + 7, 11, 2),
+ (reference.sample_count() - 3, 0, 0),
+ ] {
+ let stereo_mode = || match mode {
+ 1 => crate::StereoMode::MonoL,
+ 2 => crate::StereoMode::MonoR,
+ _ => crate::StereoMode::Stereo,
+ };
+ let mut expected = vec![0.0_f32; 1_024];
+ let mut actual = expected.clone();
+ let expected_frames = crate::render_audio(
+ &[crate::AudioRendererTrack {
+ data: &reference,
+ gain: -4.0,
+ stereo_mode: stereo_mode(),
+ offset,
+ }],
+ position,
+ 512,
+ 0,
+ &mut expected,
+ );
+ let actual_frames = crate::render_audio(
+ &[crate::AudioRendererTrack {
+ data: audio.as_ref(),
+ gain: -4.0,
+ stereo_mode: stereo_mode(),
+ offset,
+ }],
+ position,
+ 512,
+ 0,
+ &mut actual,
+ );
+ assert_eq!(actual_frames, expected_frames);
+ assert!(
+ actual
+ .iter()
+ .zip(&expected)
+ .all(|(actual, expected)| actual.to_bits() == expected.to_bits())
+ );
+ }
+ assert_eq!(
+ loader.progress(),
+ AudioLoadProgress {
+ ready_frames: reference.sample_count(),
+ channels: Some(reference.channels()),
+ complete: true,
+ error: None,
+ }
+ );
+ let tail = loader
+ .window(reference.sample_count() - 1..reference.sample_count() + 480)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(tail.sample_count(), reference.sample_count());
+ assert_eq!(
+ tail.sample(reference.samples().len() - 1),
+ reference.samples().last()
+ );
+ assert!(tail.sample(reference.samples().len()).is_none());
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn range_waits_for_every_requested_sample_and_survives_publication_without_copying() {
+ let (loader, tx) = controlled();
+ append(&loader, &tx, BLOCK_FRAMES);
+ let first = loader.window(0..100).await.unwrap().unwrap();
+ assert!(!loader.progress().complete);
+ let mut requested = Box::pin(loader.window(BLOCK_FRAMES - 3..BLOCK_FRAMES + 3));
+ assert!(
+ tokio::time::timeout(Duration::from_millis(10), &mut requested)
+ .await
+ .is_err()
+ );
+ append(&loader, &tx, BLOCK_FRAMES);
+ let second = requested.await.unwrap().unwrap();
+ for index in (BLOCK_FRAMES - 3) * 2..(BLOCK_FRAMES + 3) * 2 {
+ assert_eq!(second.sample(index), Some(&(index as f32)));
+ }
+ let audio = {
+ let mut pending = loader.pending.lock().unwrap();
+ Arc::new(DecodedAudio {
+ channels: 2,
+ frames: pending.frames,
+ storage: AudioStorage::Blocks(std::mem::take(&mut pending.blocks)),
+ })
+ };
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: audio.frames,
+ channels: Some(2),
+ complete: true,
+ error: None,
+ },
+ result: Some(Ok(Some(audio.clone()))),
+ });
+ assert!(std::ptr::eq(
+ first.sample(0).unwrap(),
+ audio.sample(0).unwrap()
+ ));
+ assert!(std::ptr::eq(
+ second.sample(BLOCK_FRAMES * 2).unwrap(),
+ audio.sample(BLOCK_FRAMES * 2).unwrap()
+ ));
+ assert_eq!(
+ loader.get().await.unwrap().unwrap().sample_count(),
+ BLOCK_FRAMES * 2
+ );
+ }
+
+ #[tokio::test]
+ async fn failed_or_dropped_producer_never_becomes_silence_or_success() {
+ let (loader, tx) = controlled();
+ append(&loader, &tx, BLOCK_FRAMES);
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ error: Some("failed source".into()),
+ ..loader.progress()
+ },
+ result: Some(Err("failed source".into())),
+ });
+ assert!(loader.window(0..1).await.is_err());
+ assert!(loader.get().await.is_err());
+ let (loader, tx) = controlled();
+ drop(tx);
+ assert!(loader.progress().error.is_some());
+ assert!(loader.window(0..1).await.is_err());
+ assert!(loader.get().await.is_err());
+ let missing = ProgressiveAudio::spawn(
+ PathBuf::from("/missing-cap-progressive-audio.wav"),
+ "missing".into(),
+ );
+ assert!(missing.get().await.is_err());
+ assert!(missing.progress().error.is_some());
+ assert!(!missing.progress().complete);
+ }
+
+ #[test]
+ fn waiting_for_completion_does_not_wake_for_partial_blocks() {
+ use std::{
+ future::Future,
+ sync::atomic::{AtomicUsize, Ordering},
+ task::{Context, Poll, Wake, Waker},
+ };
+
+ struct WakeCount(AtomicUsize);
+ impl Wake for WakeCount {
+ fn wake(self: Arc<Self>) {
+ self.0.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+
+ let (loader, tx) = controlled();
+ let count = Arc::new(WakeCount(AtomicUsize::new(0)));
+ let waker = Waker::from(count.clone());
+ let mut context = Context::from_waker(&waker);
+ let mut completion = Box::pin(loader.get());
+ assert!(completion.as_mut().poll(&mut context).is_pending());
+ for _ in 0..8 {
+ append(&loader, &tx, BLOCK_FRAMES);
+ }
+ assert_eq!(count.0.load(Ordering::Relaxed), 0);
+ tx.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ error: Some("test failure".into()),
+ ..loader.progress()
+ },
+ result: Some(Err("test failure".into())),
+ });
+ assert_eq!(count.0.load(Ordering::Relaxed), 1);
+ assert!(matches!(
+ completion.as_mut().poll(&mut context),
+ Poll::Ready(Err(_))
+ ));
+ }
+
+ #[tokio::test]
+ async fn absent_and_predecoded_tracks_are_ready_without_a_worker() {
+ let loader = ProgressiveAudio::none();
+ assert!(loader.get().await.unwrap().is_none());
+ assert!(loader.window(0..100).await.unwrap().is_none());
+ assert!(loader.progress().complete);
+ let data = Arc::new(AudioData::from_raw_f32(vec![0.25, -0.5, 0.75, 1.0], 2));
+ let loader = ProgressiveAudio::ready(Some(data.clone()));
+ let audio = loader.get().await.unwrap().unwrap();
+ assert!(std::ptr::eq(audio.sample(0).unwrap(), &data.samples()[0]));
+ assert!(loader.window(Range { start: 2, end: 1 }).await.is_err());
+ }
+
+ #[tokio::test]
+ async fn truncated_inputs_preserve_full_decoders_success_or_failure() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original.wav");
+ wave(&original, 44_100, 2);
+ let bytes = std::fs::read(original).unwrap();
+ for length in [0, 24, 44, 47, 4_097, bytes.len() - 1, bytes.len() - 1_001] {
+ let path = directory.path().join(format!("truncated-{length}.wav"));
+ std::fs::write(&path, &bytes[..length]).unwrap();
+ let reference = AudioData::from_file(&path);
+ let candidate = ProgressiveAudio::spawn(path, "truncated".into())
+ .get()
+ .await;
+ assert_eq!(reference.is_ok(), candidate.is_ok(), "length {length}");
+ if let (Ok(reference), Ok(Some(candidate))) = (reference, candidate) {
+ assert_eq!(reference.sample_count(), candidate.sample_count());
+ for (index, sample) in reference.samples().iter().enumerate() {
+ assert_eq!(
+ candidate.sample(index).unwrap().to_bits(),
+ sample.to_bits(),
+ "length {length} at {index}"
+ );
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn discontinuities_partial_channels_and_short_interior_blocks_are_rejected() {
+ for (start, channels, count) in [
+ (1, 2, 4),
+ (0, 0, 4),
+ (0, 2, 3),
+ (0, 2, 0),
+ (0, 2, BLOCK_FRAMES * 2 + 2),
+ ] {
+ let mut pending = PendingBlocks::default();
+ assert!(
+ pending
+ .append(crate::AudioChunk {
+ source_start_sample: start,
+ channels,
+ samples: vec![0.0; count]
+ })
+ .is_err()
+ );
+ }
+ let mut pending = PendingBlocks::default();
+ pending
+ .append(crate::AudioChunk {
+ source_start_sample: 0,
+ channels: 2,
+ samples: vec![0.0; 8],
+ })
+ .unwrap();
+ assert!(
+ pending
+ .append(crate::AudioChunk {
+ source_start_sample: 4,
+ channels: 2,
+ samples: vec![0.0; 8]
+ })
+ .is_err()
+ );
+ assert!(
+ pending
+ .append(crate::AudioChunk {
+ source_start_sample: 4,
+ channels: 1,
+ samples: vec![0.0; 8]
+ })
+ .is_err()
+ );
+ }
+}
diff --git a/crates/audio/src/progressive/managed.rs b/crates/audio/src/progressive/managed.rs
new file mode 100644
index 000000000..5eb090f67
--- /dev/null
+++ b/crates/audio/src/progressive/managed.rs
@@ -0,0 +1,758 @@
+use super::{DecodedAudio, LoadState, PendingBlocks, ProgressiveAudio};
+use crate::AudioStream;
+use cap_enc_ffmpeg::RelocatableSource;
+use std::{
+ fmt,
+ path::{Component, PathBuf},
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+ thread::JoinHandle,
+};
+use tokio::sync::watch;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ManagedAudioError {
+ InvalidInput,
+ RuntimeUnavailable(String),
+ ThreadSpawn(String),
+}
+
+impl fmt::Display for ManagedAudioError {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::InvalidInput => {
+ formatter.write_str("Managed audio requires a relative file path")
+ }
+ Self::RuntimeUnavailable(error) => write!(formatter, "Managed audio runtime: {error}"),
+ Self::ThreadSpawn(error) => write!(formatter, "Managed audio thread: {error}"),
+ }
+ }
+}
+
+impl std::error::Error for ManagedAudioError {}
+
+pub struct ManagedAudioInput {
+ source: RelocatableSource,
+ relative_path: PathBuf,
+}
+
+impl ManagedAudioInput {
+ pub fn new(
+ source: RelocatableSource,
+ relative_path: PathBuf,
+ ) -> Result<Self, ManagedAudioError> {
+ if relative_path.as_os_str().is_empty()
+ || relative_path
+ .components()
+ .any(|component| !matches!(component, Component::Normal(_)))
+ {
+ return Err(ManagedAudioError::InvalidInput);
+ }
+ Ok(Self {
+ source,
+ relative_path,
+ })
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ManagedAudioTerminal {
+ Complete { frames: usize, channels: u16 },
+ Failed(String),
+ Cancelled,
+ WorkerPanicked,
+}
+
+impl fmt::Display for ManagedAudioTerminal {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Complete { frames, channels } => {
+ write!(
+ formatter,
+ "Managed audio completed: {frames} frames, {channels} channels"
+ )
+ }
+ Self::Failed(error) => formatter.write_str(error),
+ Self::Cancelled => formatter.write_str("Managed audio cancelled"),
+ Self::WorkerPanicked => formatter.write_str("Managed audio worker panicked"),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ManagedAudioExit {
+ pub terminal: ManagedAudioTerminal,
+}
+
+#[derive(Clone, Default)]
+struct ManagedAudioState {
+ terminal: Option<ManagedAudioTerminal>,
+ exit: Option<ManagedAudioExit>,
+}
+
+struct ManagedAudioControl {
+ cancelled: Arc<AtomicBool>,
+ state: watch::Sender<ManagedAudioState>,
+ join: Mutex<Option<JoinHandle<()>>>,
+ runtime: tokio::runtime::Handle,
+}
+
+impl ManagedAudioControl {
+ fn finish(&self, terminal: ManagedAudioTerminal) -> ManagedAudioTerminal {
+ self.state.send_if_modified(|state| {
+ if state.terminal.is_some() {
+ false
+ } else {
+ state.terminal = Some(terminal.clone());
+ true
+ }
+ });
+ self.state.borrow().terminal.clone().unwrap_or(terminal)
+ }
+
+ fn cancel(&self) {
+ self.cancelled.store(true, Ordering::Release);
+ self.finish(ManagedAudioTerminal::Cancelled);
+ }
+
+ fn joined(&self, panicked: bool) {
+ let terminal = self.finish(if panicked {
+ ManagedAudioTerminal::WorkerPanicked
+ } else {
+ ManagedAudioTerminal::Failed("Managed audio worker exited without a result".into())
+ });
+ self.state.send_modify(|state| {
+ state.exit = Some(ManagedAudioExit { terminal });
+ });
+ }
+}
+
+#[derive(Clone)]
+pub struct ManagedAudioStopHandle {
+ control: Arc<ManagedAudioControl>,
+}
+
+impl ManagedAudioStopHandle {
+ pub fn cancel(&self) {
+ self.control.cancel();
+ }
+
+ pub fn terminal(&self) -> Option<ManagedAudioTerminal> {
+ self.control.state.borrow().terminal.clone()
+ }
+
+ pub async fn wait(&self) -> ManagedAudioExit {
+ let join = self
+ .control
+ .join
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take();
+ if let Some(join) = join {
+ let control = self.control.clone();
+ drop(self.control.runtime.spawn_blocking(move || {
+ control.joined(join.join().is_err());
+ }));
+ }
+ let mut state = self.control.state.subscribe();
+ loop {
+ if let Some(exit) = state.borrow_and_update().exit.clone() {
+ return exit;
+ }
+ state
+ .changed()
+ .await
+ .expect("Managed audio owner retains the completion sender");
+ }
+ }
+
+ pub async fn stop_and_wait(&self) -> ManagedAudioExit {
+ self.cancel();
+ self.wait().await
+ }
+}
+
+pub struct ManagedProgressiveAudio {
+ loader: ProgressiveAudio,
+ stop: ManagedAudioStopHandle,
+}
+
+impl ManagedProgressiveAudio {
+ pub fn spawn(input: ManagedAudioInput, label: String) -> Result<Self, ManagedAudioError> {
+ Self::spawn_worker(label, move |pending, progress, cancelled| {
+ let ManagedAudioInput {
+ source,
+ relative_path,
+ } = input;
+ let result =
+ AudioStream::open_relocatable(&source, [relative_path.as_path()], cancelled)
+ .map_err(|error| error.to_string())
+ .and_then(|stream| ProgressiveAudio::decode_stream(stream, pending, progress));
+ drop(source);
+ result
+ })
+ }
+
+ fn spawn_worker(
+ label: String,
+ decode: impl FnOnce(
+ &Mutex<PendingBlocks>,
+ &watch::Sender<LoadState>,
+ Arc<AtomicBool>,
+ ) -> Result<Arc<DecodedAudio>, String>
+ + Send
+ + 'static,
+ ) -> Result<Self, ManagedAudioError> {
+ let runtime = tokio::runtime::Handle::try_current()
+ .map_err(|error| ManagedAudioError::RuntimeUnavailable(error.to_string()))?;
+ let (state, _) = watch::channel(ManagedAudioState::default());
+ let control = Arc::new(ManagedAudioControl {
+ cancelled: Arc::new(AtomicBool::new(false)),
+ state,
+ join: Mutex::new(None),
+ runtime,
+ });
+ let (progress_tx, rx) = watch::channel(LoadState::default());
+ let (complete_tx, complete) = watch::channel(None);
+ let pending = Arc::new(Mutex::new(PendingBlocks::default()));
+ let worker_control = control.clone();
+ let worker_pending = pending.clone();
+ let join = std::thread::Builder::new()
+ .name("cap-managed-audio".into())
+ .spawn(move || {
+ let decoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ decode(
+ &worker_pending,
+ &progress_tx,
+ worker_control.cancelled.clone(),
+ )
+ }));
+ let (result, proposed_terminal) = match decoded {
+ Ok(Ok(audio)) => {
+ let terminal = ManagedAudioTerminal::Complete {
+ frames: audio.sample_count(),
+ channels: audio.channels(),
+ };
+ (Ok(Some(audio)), terminal)
+ }
+ Ok(Err(error)) => {
+ let error = format!("{label} / {error}");
+ (Err(error.clone()), ManagedAudioTerminal::Failed(error))
+ }
+ Err(_) => (
+ Err(ManagedAudioTerminal::WorkerPanicked.to_string()),
+ ManagedAudioTerminal::WorkerPanicked,
+ ),
+ };
+ let terminal = worker_control.finish(proposed_terminal);
+ let result = if matches!(terminal, ManagedAudioTerminal::Complete { .. }) {
+ result
+ } else {
+ Err(terminal.to_string())
+ };
+ if result.is_err()
+ && let Ok(mut pending) = worker_pending.lock()
+ {
+ pending.blocks.clear();
+ }
+ let mut state = progress_tx.borrow().clone();
+ state.progress.complete = result.is_ok();
+ state.progress.error = result.as_ref().err().cloned();
+ if let Ok(Some(audio)) = &result {
+ state.progress.ready_frames = audio.sample_count();
+ state.progress.channels = Some(audio.channels());
+ }
+ state.result = Some(result.clone());
+ progress_tx.send_replace(state);
+ complete_tx.send_replace(Some(result));
+ })
+ .map_err(|error| ManagedAudioError::ThreadSpawn(error.to_string()))?;
+ *control
+ .join
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(join);
+ Ok(Self {
+ loader: ProgressiveAudio {
+ rx,
+ complete,
+ pending,
+ },
+ stop: ManagedAudioStopHandle { control },
+ })
+ }
+
+ pub fn loader(&self) -> &ProgressiveAudio {
+ &self.loader
+ }
+
+ pub fn stop_handle(&self) -> ManagedAudioStopHandle {
+ self.stop.clone()
+ }
+}
+
+impl Drop for ManagedProgressiveAudio {
+ fn drop(&mut self) {
+ self.stop.cancel();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{AudioData, AudioSampleSource, ChunkRead};
+ use std::{io::Write, path::Path, sync::mpsc, time::Duration};
+
+ const TIMEOUT: Duration = Duration::from_secs(5);
+
+ fn wave(path: &Path) {
+ let frames = 100_003_u32;
+ let channels = 2_u16;
+ let bytes = frames * u32::from(channels) * 2;
+ let mut file = std::fs::File::create(path).unwrap();
+ file.write_all(b"RIFF").unwrap();
+ file.write_all(&(bytes + 36).to_le_bytes()).unwrap();
+ file.write_all(b"WAVEfmt ").unwrap();
+ file.write_all(&16_u32.to_le_bytes()).unwrap();
+ file.write_all(&1_u16.to_le_bytes()).unwrap();
+ file.write_all(&channels.to_le_bytes()).unwrap();
+ file.write_all(&48_000_u32.to_le_bytes()).unwrap();
+ file.write_all(&(48_000 * u32::from(channels) * 2).to_le_bytes())
+ .unwrap();
+ file.write_all(&(channels * 2).to_le_bytes()).unwrap();
+ file.write_all(&16_u16.to_le_bytes()).unwrap();
+ file.write_all(b"data").unwrap();
+ file.write_all(&bytes.to_le_bytes()).unwrap();
+ for frame in 0..frames {
+ for channel in 0..channels {
+ let sample = ((frame * 17 + u32::from(channel) * 971) % 60_000) as i32 - 30_000;
+ file.write_all(&(sample as i16).to_le_bytes()).unwrap();
+ }
+ }
+ }
+
+ struct Owner {
+ dropped: Arc<AtomicBool>,
+ gate: Option<(mpsc::Sender<()>, Mutex<mpsc::Receiver<()>>)>,
+ }
+
+ impl Drop for Owner {
+ fn drop(&mut self) {
+ if let Some((entered, release)) = &self.gate {
+ entered.send(()).unwrap();
+ release.lock().unwrap().recv_timeout(TIMEOUT).unwrap();
+ }
+ self.dropped.store(true, Ordering::Release);
+ }
+ }
+
+ fn input(root: &Path, dropped: Arc<AtomicBool>) -> ManagedAudioInput {
+ ManagedAudioInput::new(
+ RelocatableSource::new_with_owner(
+ root.to_path_buf(),
+ Arc::new(Owner {
+ dropped,
+ gate: None,
+ }),
+ )
+ .unwrap(),
+ PathBuf::from("audio.wav"),
+ )
+ .unwrap()
+ }
+
+ fn assert_released(path: &Path) {
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ let file = std::fs::OpenOptions::new()
+ .read(true)
+ .share_mode(0)
+ .open(path)
+ .unwrap();
+ drop(file);
+ }
+ let renamed = path.with_extension("retained.wav");
+ std::fs::rename(path, &renamed).unwrap();
+ std::fs::rename(&renamed, path).unwrap();
+ }
+
+ #[test]
+ fn managed_input_rejects_escaping_and_empty_paths() {
+ let root = tempfile::tempdir().unwrap();
+ for path in ["", ".", "..", "../audio.wav", "folder/../audio.wav"] {
+ assert!(matches!(
+ ManagedAudioInput::new(
+ RelocatableSource::new(root.path().to_path_buf()).unwrap(),
+ PathBuf::from(path),
+ ),
+ Err(ManagedAudioError::InvalidInput)
+ ));
+ }
+ assert!(matches!(
+ ManagedAudioInput::new(
+ RelocatableSource::new(root.path().to_path_buf()).unwrap(),
+ root.path().join("audio.wav"),
+ ),
+ Err(ManagedAudioError::InvalidInput)
+ ));
+ }
+
+ #[tokio::test]
+ async fn managed_pcm_and_eof_match_ordinary_and_completed_handoff_reuses_the_arc() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("audio.wav");
+ wave(&path);
+ let expected = AudioData::from_file(&path).unwrap();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let managed = ManagedProgressiveAudio::spawn(
+ input(directory.path(), dropped.clone()),
+ "managed test".into(),
+ )
+ .unwrap();
+ let stop = managed.stop_handle();
+ let result = tokio::time::timeout(TIMEOUT, managed.loader().get())
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ assert!(dropped.load(Ordering::Acquire));
+ assert_eq!(result.channels(), expected.channels());
+ assert_eq!(result.sample_count(), expected.sample_count());
+ assert!(
+ result
+ .sample_slices()
+ .flatten()
+ .zip(expected.samples())
+ .all(|(actual, expected)| actual.to_bits() == expected.to_bits())
+ );
+ assert!(result.sample(expected.samples().len()).is_none());
+ let handoff = ProgressiveAudio::from_result(Ok(Some(result.clone())));
+ assert!(Arc::ptr_eq(&result, &handoff.get().await.unwrap().unwrap()));
+ let exit = stop.wait().await;
+ assert_eq!(
+ exit.terminal,
+ ManagedAudioTerminal::Complete {
+ frames: expected.sample_count(),
+ channels: expected.channels(),
+ }
+ );
+ assert_released(&path);
+ drop(managed);
+ assert_eq!(stop.wait().await, exit);
+ assert_eq!(handoff.progress().ready_frames, expected.sample_count());
+ }
+
+ #[tokio::test]
+ async fn completed_absence_and_failure_preserve_loader_semantics() {
+ let absent = ProgressiveAudio::from_result(Ok(None));
+ assert_eq!(absent.progress(), ProgressiveAudio::none().progress());
+ assert!(absent.get().await.unwrap().is_none());
+ assert!(absent.window(0..100).await.unwrap().is_none());
+ let failure = ProgressiveAudio::from_result(Err("source failed".into()));
+ assert!(!failure.progress().complete);
+ assert_eq!(failure.progress().ready_frames, 0);
+ assert_eq!(failure.progress().channels, None);
+ assert_eq!(failure.progress().error.as_deref(), Some("source failed"));
+ assert_eq!(failure.get().await.err().as_deref(), Some("source failed"));
+ assert_eq!(
+ failure.window(0..1).await.err().as_deref(),
+ Some("source failed")
+ );
+ }
+
+ #[tokio::test]
+ async fn native_result_waits_for_owner_destruction_and_dropped_join_waiter_does_not_detach() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("audio.wav");
+ wave(&path);
+ let dropped = Arc::new(AtomicBool::new(false));
+ let (entered_tx, entered_rx) = mpsc::channel();
+ let (release_tx, release_rx) = mpsc::channel();
+ let source = RelocatableSource::new_with_owner(
+ directory.path().to_path_buf(),
+ Arc::new(Owner {
+ dropped: dropped.clone(),
+ gate: Some((entered_tx, Mutex::new(release_rx))),
+ }),
+ )
+ .unwrap();
+ let managed = ManagedProgressiveAudio::spawn(
+ ManagedAudioInput::new(source, PathBuf::from("audio.wav")).unwrap(),
+ "owner gate".into(),
+ )
+ .unwrap();
+ entered_rx.recv_timeout(TIMEOUT).unwrap();
+ assert!(!dropped.load(Ordering::Acquire));
+ assert!(!managed.loader().progress().complete);
+ assert!(
+ tokio::time::timeout(Duration::from_millis(10), managed.loader().get())
+ .await
+ .is_err()
+ );
+ let stop = managed.stop_handle();
+ assert!(
+ tokio::time::timeout(Duration::from_millis(10), stop.wait())
+ .await
+ .is_err()
+ );
+ release_tx.send(()).unwrap();
+ assert!(managed.loader().get().await.unwrap().is_some());
+ let exit = tokio::time::timeout(TIMEOUT, stop.wait()).await.unwrap();
+ assert!(matches!(
+ exit.terminal,
+ ManagedAudioTerminal::Complete { .. }
+ ));
+ assert!(dropped.load(Ordering::Acquire));
+ assert_released(&path);
+ }
+
+ #[tokio::test]
+ async fn cancellation_before_native_open_and_after_native_read_joins_and_never_validates() {
+ for read_first in [false, true] {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("audio.wav");
+ wave(&path);
+ let dropped = Arc::new(AtomicBool::new(false));
+ let input = input(directory.path(), dropped.clone());
+ let (entered_tx, entered_rx) = mpsc::channel();
+ let (release_tx, release_rx) = mpsc::channel();
+ let managed = ManagedProgressiveAudio::spawn_worker(
+ "cancelled native".into(),
+ move |pending, progress, cancelled| {
+ if read_first {
+ let mut stream = AudioStream::open_relocatable(
+ &input.source,
+ [input.relative_path.as_path()],
+ cancelled,
+ )
+ .map_err(|error| error.to_string())?;
+ assert!(matches!(stream.read_chunk(7).unwrap(), ChunkRead::Chunk(_)));
+ entered_tx.send(()).unwrap();
+ release_rx.recv_timeout(TIMEOUT).unwrap();
+ let error = stream.read_chunk(7).unwrap_err();
+ assert!(error.is_cancelled());
+ assert_eq!(error.next_sample, 7);
+ Err(error.to_string())
+ } else {
+ entered_tx.send(()).unwrap();
+ release_rx.recv_timeout(TIMEOUT).unwrap();
+ let stream = AudioStream::open_relocatable(
+ &input.source,
+ [input.relative_path.as_path()],
+ cancelled,
+ )
+ .map_err(|error| error.to_string())?;
+ ProgressiveAudio::decode_stream(stream, pending, progress)
+ }
+ },
+ )
+ .unwrap();
+ entered_rx.recv_timeout(TIMEOUT).unwrap();
+ let stop = managed.stop_handle();
+ stop.cancel();
+ assert!(!dropped.load(Ordering::Acquire));
+ release_tx.send(()).unwrap();
+ assert!(managed.loader().get().await.is_err());
+ assert!(!managed.loader().progress().complete);
+ assert_eq!(stop.wait().await.terminal, ManagedAudioTerminal::Cancelled);
+ assert!(dropped.load(Ordering::Acquire));
+ assert_released(&path);
+ }
+ }
+
+ #[tokio::test]
+ async fn dropping_managed_owner_cancels_without_releasing_active_source_early() {
+ let directory = tempfile::tempdir().unwrap();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let input = input(directory.path(), dropped.clone());
+ let (entered_tx, entered_rx) = mpsc::channel();
+ let (release_tx, release_rx) = mpsc::channel();
+ let managed =
+ ManagedProgressiveAudio::spawn_worker("drop owner".into(), move |_, _, cancelled| {
+ entered_tx.send(()).unwrap();
+ release_rx.recv_timeout(TIMEOUT).unwrap();
+ assert!(cancelled.load(Ordering::Acquire));
+ drop(input);
+ Err("cancelled owner".into())
+ })
+ .unwrap();
+ entered_rx.recv_timeout(TIMEOUT).unwrap();
+ let loader = managed.loader().clone();
+ let stop = managed.stop_handle();
+ drop(managed);
+ assert_eq!(stop.terminal(), Some(ManagedAudioTerminal::Cancelled));
+ assert!(!dropped.load(Ordering::Acquire));
+ release_tx.send(()).unwrap();
+ assert!(loader.get().await.is_err());
+ assert_eq!(stop.wait().await.terminal, ManagedAudioTerminal::Cancelled);
+ assert!(dropped.load(Ordering::Acquire));
+ }
+
+ #[tokio::test]
+ async fn native_failure_and_worker_panic_release_sources_and_preserve_errors() {
+ let directory = tempfile::tempdir().unwrap();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let managed = ManagedProgressiveAudio::spawn(
+ input(directory.path(), dropped.clone()),
+ "missing audio".into(),
+ )
+ .unwrap();
+ let error = managed.loader().get().await.err().unwrap();
+ assert!(error.starts_with("missing audio / input-open /"));
+ assert!(dropped.load(Ordering::Acquire));
+ assert_eq!(
+ managed.stop_handle().wait().await.terminal,
+ ManagedAudioTerminal::Failed(error)
+ );
+ let dropped = Arc::new(AtomicBool::new(false));
+ let input = input(directory.path(), dropped.clone());
+ let managed =
+ ManagedProgressiveAudio::spawn_worker("panic audio".into(), move |_, _, _| {
+ let _input = input;
+ panic!("injected managed audio failure");
+ })
+ .unwrap();
+ assert!(managed.loader().get().await.is_err());
+ assert!(dropped.load(Ordering::Acquire));
+ assert_eq!(
+ managed.stop_handle().wait().await.terminal,
+ ManagedAudioTerminal::WorkerPanicked
+ );
+ }
+
+ #[tokio::test]
+ async fn a_native_error_after_valid_pcm_never_becomes_validated_audio() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("audio.wav");
+ wave(&path);
+ std::fs::OpenOptions::new()
+ .write(true)
+ .open(&path)
+ .unwrap()
+ .set_len(44 + (super::super::BLOCK_FRAMES * 4) as u64 + 3)
+ .unwrap();
+ assert!(AudioData::from_file(&path).is_err());
+ let dropped = Arc::new(AtomicBool::new(false));
+ let managed = ManagedProgressiveAudio::spawn(
+ input(directory.path(), dropped.clone()),
+ "late native failure".into(),
+ )
+ .unwrap();
+ assert!(managed.loader().get().await.is_err());
+ let progress = managed.loader().progress();
+ assert!(progress.ready_frames > 0);
+ assert!(!progress.complete);
+ assert!(progress.error.is_some());
+ assert!(managed.loader().window(0..1).await.is_err());
+ assert!(matches!(
+ managed.stop_handle().wait().await.terminal,
+ ManagedAudioTerminal::Failed(_)
+ ));
+ assert!(dropped.load(Ordering::Acquire));
+ assert_released(&path);
+ }
+
+ #[tokio::test]
+ async fn opened_managed_audio_reads_original_bytes_across_source_publication() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ std::fs::create_dir(&original).unwrap();
+ let path = original.join("audio.wav");
+ wave(&path);
+ let expected = AudioData::from_file(&path).unwrap();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let source = RelocatableSource::new_with_owner(
+ original.clone(),
+ Arc::new(Owner {
+ dropped: dropped.clone(),
+ gate: None,
+ }),
+ )
+ .unwrap();
+ let input = ManagedAudioInput::new(source.clone(), PathBuf::from("audio.wav")).unwrap();
+ let (entered_tx, entered_rx) = mpsc::channel();
+ let (release_tx, release_rx) = mpsc::channel();
+ let managed = ManagedProgressiveAudio::spawn_worker(
+ "publication".into(),
+ move |pending, progress, cancelled| {
+ let stream = AudioStream::open_relocatable(
+ &input.source,
+ [input.relative_path.as_path()],
+ cancelled,
+ )
+ .map_err(|error| error.to_string())?;
+ entered_tx.send(()).unwrap();
+ release_rx.recv_timeout(TIMEOUT).unwrap();
+ ProgressiveAudio::decode_stream(stream, pending, progress)
+ },
+ )
+ .unwrap();
+ entered_rx.recv_timeout(TIMEOUT).unwrap();
+ source.relocate(retained.clone()).unwrap();
+ std::fs::create_dir(&original).unwrap();
+ std::fs::write(&path, b"published replacement").unwrap();
+ release_tx.send(()).unwrap();
+ let audio = managed.loader().get().await.unwrap().unwrap();
+ assert_eq!(audio.sample_count(), expected.sample_count());
+ assert!(
+ audio
+ .sample_slices()
+ .flatten()
+ .zip(expected.samples())
+ .all(|(actual, expected)| actual.to_bits() == expected.to_bits())
+ );
+ assert!(matches!(
+ managed.stop_handle().wait().await.terminal,
+ ManagedAudioTerminal::Complete { .. }
+ ));
+ drop(source);
+ assert!(dropped.load(Ordering::Acquire));
+ assert_eq!(std::fs::read(&path).unwrap(), b"published replacement");
+ assert_released(&retained.join("audio.wav"));
+ }
+
+ #[tokio::test]
+ #[ignore = "Requires CAP_MANAGED_AUDIO_FIXTURE_ROOT and CAP_MANAGED_AUDIO_FIXTURE_PATH"]
+ async fn canonical_audio_matches_independent_stream_through_eof() {
+ let root = PathBuf::from(std::env::var_os("CAP_MANAGED_AUDIO_FIXTURE_ROOT").unwrap());
+ let relative = PathBuf::from(std::env::var_os("CAP_MANAGED_AUDIO_FIXTURE_PATH").unwrap());
+ let canonical = root.join(&relative);
+ let managed = ManagedProgressiveAudio::spawn(
+ ManagedAudioInput::new(RelocatableSource::new(root).unwrap(), relative).unwrap(),
+ "canonical audio".into(),
+ )
+ .unwrap();
+ let audio = managed.loader().get().await.unwrap().unwrap();
+ let mut oracle = AudioStream::open(&canonical, Arc::new(AtomicBool::new(false))).unwrap();
+ let mut compared = 0_usize;
+ loop {
+ match oracle.read_chunk(12_000).unwrap() {
+ ChunkRead::Chunk(chunk) => {
+ assert_eq!(chunk.channels, audio.channels());
+ assert_eq!(chunk.source_start_sample as usize, compared);
+ let first = compared * usize::from(chunk.channels);
+ for (index, sample) in chunk.samples.iter().enumerate() {
+ assert_eq!(
+ audio.sample(first + index).unwrap().to_bits(),
+ sample.to_bits()
+ );
+ }
+ compared += chunk.samples.len() / usize::from(chunk.channels);
+ }
+ ChunkRead::Eof { next_sample } => {
+ assert_eq!(next_sample as usize, compared);
+ assert_eq!(audio.sample_count(), compared);
+ break;
+ }
+ }
+ }
+ assert!(compared > 0);
+ assert!(matches!(
+ managed.stop_handle().wait().await.terminal,
+ ManagedAudioTerminal::Complete { .. }
+ ));
+ }
+}
diff --git a/crates/audio/src/progressive/test_support.rs b/crates/audio/src/progressive/test_support.rs
new file mode 100644
index 000000000..849b99721
--- /dev/null
+++ b/crates/audio/src/progressive/test_support.rs
@@ -0,0 +1,91 @@
+use super::{
+ AudioLoadProgress, AudioStorage, DecodedAudio, LoadResult, LoadState, PendingBlocks,
+ ProgressiveAudio,
+};
+use crate::AudioChunk;
+use std::sync::{Arc, Mutex};
+use tokio::sync::watch;
+
+pub struct ProgressiveAudioTestProducer {
+ pending: Arc<Mutex<PendingBlocks>>,
+ progress: watch::Sender<LoadState>,
+ complete: watch::Sender<Option<LoadResult>>,
+}
+
+impl ProgressiveAudioTestProducer {
+ pub fn new() -> (ProgressiveAudio, Self) {
+ let (progress, rx) = watch::channel(LoadState::default());
+ let (complete, complete_rx) = watch::channel(None);
+ let pending = Arc::new(Mutex::new(PendingBlocks::default()));
+ (
+ ProgressiveAudio {
+ rx,
+ complete: complete_rx,
+ pending: pending.clone(),
+ },
+ Self {
+ pending,
+ progress,
+ complete,
+ },
+ )
+ }
+
+ pub fn append(&self, chunk: AudioChunk) -> Result<(), String> {
+ let progress = {
+ let mut pending = self.pending.lock().map_err(|error| error.to_string())?;
+ pending.append(chunk)?;
+ AudioLoadProgress {
+ ready_frames: pending.frames,
+ channels: pending.channels,
+ complete: false,
+ error: None,
+ }
+ };
+ self.progress.send_replace(LoadState {
+ progress,
+ result: None,
+ });
+ Ok(())
+ }
+
+ pub fn finish(self) -> Result<(), String> {
+ let audio = {
+ let mut pending = self.pending.lock().map_err(|error| error.to_string())?;
+ Arc::new(DecodedAudio {
+ channels: pending.channels.ok_or("No published audio channels")?,
+ frames: pending.frames,
+ storage: AudioStorage::Blocks(std::mem::take(&mut pending.blocks)),
+ })
+ };
+ let result = Ok(Some(audio.clone()));
+ self.progress.send_replace(LoadState {
+ progress: AudioLoadProgress {
+ ready_frames: audio.frames,
+ channels: Some(audio.channels),
+ complete: true,
+ error: None,
+ },
+ result: Some(result.clone()),
+ });
+ self.complete.send_replace(Some(result));
+ Ok(())
+ }
+
+ pub fn fail(self, error: String) {
+ self.pending
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .blocks
+ .clear();
+ let mut progress = self.progress.borrow().progress.clone();
+ progress.complete = false;
+ progress.error = Some(error.clone());
+ let result = Err(error);
+ self.progress.send_replace(LoadState {
+ progress,
+ result: Some(result.clone()),
+ });
+ self.complete.send_replace(Some(result));
+ }
+}
diff --git a/crates/audio/src/renderer.rs b/crates/audio/src/renderer.rs
index e6afb8230..fd0226d58 100644
--- a/crates/audio/src/renderer.rs
+++ b/crates/audio/src/renderer.rs
@@ -1,4 +1,5 @@
use crate::AudioData;
+use std::ops::Range;
pub enum StereoMode {
Stereo,
@@ -10,6 +11,9 @@ pub trait AudioSampleSource {
fn channels(&self) -> u16;
fn sample_count(&self) -> usize;
fn sample(&self, index: usize) -> Option<&f32>;
+ fn sample_slice(&self, _range: Range<usize>) -> Option<&[f32]> {
+ None
+ }
}
impl AudioSampleSource for AudioData {
@@ -24,6 +28,10 @@ impl AudioSampleSource for AudioData {
fn sample(&self, index: usize) -> Option<&f32> {
self.samples().get(index)
}
+
+ fn sample_slice(&self, range: Range<usize>) -> Option<&[f32]> {
+ self.samples().get(range)
+ }
}
pub struct AudioRendererTrack<'a, T: AudioSampleSource = AudioData> {
@@ -56,66 +64,88 @@ pub fn render_audio<T: AudioSampleSource>(
.unwrap_or(0),
);
- for i in 0..samples {
- let mut left = 0.0;
- let mut right = 0.0;
-
- for track in tracks {
- let source_index = offset as i128 + i as i128 + track.offset as i128;
- if source_index < 0 {
- continue;
- }
- let Ok(source_index) = usize::try_from(source_index) else {
- continue;
- };
-
- let data = track.data;
- let gain = gain_for_db(track.gain);
-
- if gain == f32::NEG_INFINITY {
- continue;
- }
+ if samples == 0 {
+ return 0;
+ }
+ let out = &mut out[out_offset..out_offset + samples * 2];
+ out.fill(0.0);
- if data.channels() == 1 {
- if let Some(sample) = data.sample(source_index) {
- left += sample * 0.707 * gain;
- right += sample * 0.707 * gain;
- }
- } else if data.channels() == 2 {
- let base_idx = source_index.saturating_mul(2);
- let Some(l_sample) = data.sample(base_idx) else {
- continue;
- };
- let Some(r_sample) = data.sample(base_idx + 1) else {
- continue;
- };
-
- match track.stereo_mode {
- StereoMode::Stereo => {
- left += l_sample * gain;
- right += r_sample * gain;
+ for track in tracks {
+ let gain = gain_for_db(track.gain);
+ if gain == f32::NEG_INFINITY {
+ continue;
+ }
+ let source_start = offset as i128 + track.offset as i128;
+ let skipped = usize::try_from((-source_start).max(0))
+ .unwrap_or(usize::MAX)
+ .min(samples);
+ let Ok(first) = usize::try_from(source_start.max(0)) else {
+ continue;
+ };
+ let count = (samples - skipped).min(track.data.sample_count().saturating_sub(first));
+ if count == 0 {
+ continue;
+ }
+ let output = &mut out[skipped * 2..(skipped + count) * 2];
+ match track.data.channels() {
+ 1 => {
+ if let Some(input) = track.data.sample_slice(first..first + count) {
+ for (sample, frame) in input.iter().zip(output.chunks_exact_mut(2)) {
+ frame[0] += sample * 0.707 * gain;
+ frame[1] += sample * 0.707 * gain;
+ }
+ } else {
+ for (index, frame) in output.chunks_exact_mut(2).enumerate() {
+ if let Some(sample) = track.data.sample(first + index) {
+ frame[0] += sample * 0.707 * gain;
+ frame[1] += sample * 0.707 * gain;
+ }
}
- StereoMode::MonoL => {
- left += l_sample * gain;
- right += l_sample * gain;
+ }
+ }
+ 2 => {
+ let input = first
+ .checked_mul(2)
+ .zip((first + count).checked_mul(2))
+ .and_then(|(start, end)| track.data.sample_slice(start..end));
+ if let Some(input) = input {
+ for (sample, frame) in input.chunks_exact(2).zip(output.chunks_exact_mut(2)) {
+ mix_stereo(sample[0], sample[1], frame, &track.stereo_mode, gain);
}
- StereoMode::MonoR => {
- left += r_sample * gain;
- right += r_sample * gain;
+ } else {
+ for (index, frame) in output.chunks_exact_mut(2).enumerate() {
+ let base = (first + index).saturating_mul(2);
+ let Some(left) = track.data.sample(base) else {
+ continue;
+ };
+ let Some(right) = base.checked_add(1).and_then(|i| track.data.sample(i))
+ else {
+ continue;
+ };
+ mix_stereo(*left, *right, frame, &track.stereo_mode, gain);
}
}
}
+ _ => {}
}
-
- let l = left.clamp(-1.0, 1.0);
- let r = right.clamp(-1.0, 1.0);
- out[out_offset + i * 2] = l;
- out[out_offset + i * 2 + 1] = r;
+ }
+ for sample in out {
+ *sample = sample.clamp(-1.0, 1.0);
}
samples
}
+fn mix_stereo(left: f32, right: f32, frame: &mut [f32], mode: &StereoMode, gain: f32) {
+ let (left, right) = match mode {
+ StereoMode::Stereo => (left, right),
+ StereoMode::MonoL => (left, left),
+ StereoMode::MonoR => (right, right),
+ };
+ frame[0] += left * gain;
+ frame[1] += right * gain;
+}
+
fn gain_for_db(db: f32) -> f32 {
match db {
// Fully mute when at minimum
@@ -131,6 +161,101 @@ fn db_to_linear(db: f32) -> f32 {
mod tests {
use super::*;
+ struct Source<'a> {
+ data: &'a AudioData,
+ slices: bool,
+ }
+
+ #[test]
+ fn empty_stereo_window_at_large_cursor_preserves_silence() {
+ struct EmptyWindow;
+
+ impl AudioSampleSource for EmptyWindow {
+ fn channels(&self) -> u16 {
+ 2
+ }
+
+ fn sample_count(&self) -> usize {
+ usize::MAX
+ }
+
+ fn sample(&self, _index: usize) -> Option<&f32> {
+ None
+ }
+ }
+
+ let mut output = [13.0_f32; 2];
+ let tracks = [AudioRendererTrack {
+ data: &EmptyWindow,
+ gain: 0.0,
+ offset: 0,
+ stereo_mode: StereoMode::Stereo,
+ }];
+ assert_eq!(
+ render_audio(&tracks, usize::MAX / 2 + 1, 1, 0, &mut output),
+ 1
+ );
+ assert_eq!(output, [0.0; 2]);
+ }
+
+ impl AudioSampleSource for Source<'_> {
+ fn channels(&self) -> u16 {
+ self.data.channels()
+ }
+
+ fn sample_count(&self) -> usize {
+ self.data.sample_count()
+ }
+
+ fn sample(&self, index: usize) -> Option<&f32> {
+ self.data.sample(index)
+ }
+
+ fn sample_slice(&self, range: Range<usize>) -> Option<&[f32]> {
+ self.slices.then(|| self.data.sample_slice(range)).flatten()
+ }
+ }
+
+ #[test]
+ fn contiguous_and_indexed_mixing_preserve_sample_bits_and_output_bounds() {
+ let data = [
+ AudioData::from_raw_f32(vec![0.5, -0.75, 0.25, -0.5], 1),
+ AudioData::from_raw_f32(vec![0.25, -0.5, 0.75, 0.125, -0.25, 0.5], 2),
+ AudioData::from_raw_f32(vec![0.5, -0.75, -0.25, 0.25, 0.125, -0.5, 0.25, 0.75], 2),
+ ];
+ let expected = [
+ 1095761920, 1095761920, 1059061760, 3206545408, 1048576000, 1061158912, 1056243188,
+ 3189113880, 3197074670, 1046545956, 1043660276, 1043660276, 3199532532, 3199532532,
+ 1095761920, 1095761920, 1095761920, 1095761920,
+ ];
+ for slices in [false, true] {
+ let sources = data.each_ref().map(|data| Source { data, slices });
+ let tracks = [
+ AudioRendererTrack {
+ data: &sources[0],
+ gain: 0.0,
+ offset: -2,
+ stereo_mode: StereoMode::Stereo,
+ },
+ AudioRendererTrack {
+ data: &sources[1],
+ gain: 0.0,
+ offset: 1,
+ stereo_mode: StereoMode::MonoR,
+ },
+ AudioRendererTrack {
+ data: &sources[2],
+ gain: 0.0,
+ offset: 0,
+ stereo_mode: StereoMode::Stereo,
+ },
+ ];
+ let mut output = [13.0_f32; 18];
+ assert_eq!(render_audio(&tracks, 0, 7, 2, &mut output), 6);
+ assert_eq!(output.map(f32::to_bits), expected);
+ }
+ }
+
fn track(data: &AudioData, offset: isize) -> AudioRendererTrack<'_> {
AudioRendererTrack {
data,
diff --git a/crates/audio/src/streaming.rs b/crates/audio/src/streaming.rs
index 39b0a73ea..830243b97 100644
--- a/crates/audio/src/streaming.rs
+++ b/crates/audio/src/streaming.rs
@@ -1,3 +1,4 @@
+use crate::audio_data::ResamplerOutput;
use ffmpeg::{ChannelLayout, Error, codec, format, frame::Audio, software::resampling};
use std::{
ffi::{CString, c_int, c_void},
@@ -66,21 +67,51 @@ pub enum ChunkRead {
}
pub struct AudioStream {
- input: format::context::Input,
+ input: StreamInput,
decoder: codec::decoder::Audio,
resampler: resampling::Context,
decoded_frame: Audio,
+ resampler_output: ResamplerOutput,
stream_index: usize,
channels: u16,
phase: Phase,
failure: Option<Failure>,
pending: Vec<f32>,
pending_offset: usize,
+ pending_frame: bool,
position: u64,
flush_iterations: usize,
cancellation: Arc<StreamCancellation>,
}
+enum StreamInput {
+ File(format::context::Input),
+ Relocatable(cap_enc_ffmpeg::SegmentedInput),
+}
+
+impl StreamInput {
+ fn input(&self) -> &format::context::Input {
+ match self {
+ Self::File(input) => input,
+ Self::Relocatable(input) => input.input(),
+ }
+ }
+
+ fn read_packet(&mut self, packet: &mut ffmpeg::Packet) -> Result<(), Error> {
+ match self {
+ Self::File(input) => packet.read(input),
+ Self::Relocatable(input) => input.read_packet(packet),
+ }
+ }
+
+ fn io_error(&self) -> Option<&std::io::Error> {
+ match self {
+ Self::File(_) => None,
+ Self::Relocatable(input) => input.io_error(),
+ }
+ }
+}
+
struct StreamCancellation {
user: Arc<AtomicBool>,
abort: Option<Arc<AtomicBool>>,
@@ -124,6 +155,56 @@ impl AudioStream {
fn open_controlled(
path: &Path,
cancellation: StreamCancellation,
+ ) -> Result<Self, AudioStreamError> {
+ Self::open_from(cancellation, |cancellation| {
+ open_input(path, cancellation).map(StreamInput::File)
+ })
+ }
+
+ pub fn open_relocatable<'a>(
+ source: &cap_enc_ffmpeg::RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ user: Arc<AtomicBool>,
+ ) -> Result<Self, AudioStreamError> {
+ Self::open_relocatable_controlled(source, paths, StreamCancellation { user, abort: None })
+ }
+
+ pub fn open_relocatable_with_abort<'a>(
+ source: &cap_enc_ffmpeg::RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ user: Arc<AtomicBool>,
+ abort: Arc<AtomicBool>,
+ ) -> Result<Self, AudioStreamError> {
+ Self::open_relocatable_controlled(
+ source,
+ paths,
+ StreamCancellation {
+ user,
+ abort: Some(abort),
+ },
+ )
+ }
+
+ fn open_relocatable_controlled<'a>(
+ source: &cap_enc_ffmpeg::RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ cancellation: StreamCancellation,
+ ) -> Result<Self, AudioStreamError> {
+ Self::open_from(cancellation, |cancellation| {
+ let cancellation = cancellation.clone();
+ cap_enc_ffmpeg::SegmentedInput::open_relocatable_interruptible(
+ source,
+ paths,
+ Arc::new(move || cancellation.is_cancelled()),
+ )
+ .map(StreamInput::Relocatable)
+ .map_err(|error| error.to_string())
+ })
+ }
+
+ fn open_from(
+ cancellation: StreamCancellation,
+ open: impl FnOnce(&Arc<StreamCancellation>) -> Result<StreamInput, String>,
) -> Result<Self, AudioStreamError> {
let cancellation = Arc::new(cancellation);
let at_open = |stage, detail: String| {
@@ -140,9 +221,9 @@ impl AudioStream {
if cancellation.is_cancelled() {
return Err(cancelled_error(0));
}
- let input =
- open_input(path, &cancellation).map_err(|detail| at_open("input-open", detail))?;
+ let input = open(&cancellation).map_err(|detail| at_open("input-open", detail))?;
let stream = input
+ .input()
.streams()
.best(ffmpeg::media::Type::Audio)
.ok_or_else(|| at_open("stream", "No Stream".to_string()))?;
@@ -179,12 +260,14 @@ impl AudioStream {
decoder,
resampler,
decoded_frame: Audio::empty(),
+ resampler_output: ResamplerOutput::new(),
stream_index,
channels,
phase: Phase::NeedPacket,
failure: None,
pending: Vec::new(),
pending_offset: 0,
+ pending_frame: false,
position: 0,
flush_iterations: 0,
cancellation,
@@ -198,6 +281,14 @@ impl AudioStream {
self.position
}
+ fn pending_samples(&self) -> Result<&[f32], String> {
+ if self.pending_frame {
+ self.resampler_output.samples()
+ } else {
+ Ok(&self.pending)
+ }
+ }
+
pub fn read_chunk(&mut self, max_frames: usize) -> Result<ChunkRead, AudioStreamError> {
if !(1..=MAX_CHUNK_FRAMES).contains(&max_frames) {
return Err(AudioStreamError {
@@ -206,7 +297,7 @@ impl AudioStream {
next_sample: self.position,
});
}
- let max_samples = max_frames * self.channels as usize;
+ let max_samples = max_frames * usize::from(self.channels);
let mut output = Vec::with_capacity(max_samples);
while output.len() < max_samples {
if self.failure.is_none() && self.cancellation.is_cancelled() {
@@ -222,17 +313,21 @@ impl AudioStream {
next_sample: self.position,
});
}
- if self.pending_offset < self.pending.len() {
- let count =
- (max_samples - output.len()).min(self.pending.len() - self.pending_offset);
- output.extend_from_slice(
- &self.pending[self.pending_offset..self.pending_offset + count],
- );
+ let pending = self.pending_samples().map_err(|detail| AudioStreamError {
+ stage: "resample",
+ detail,
+ next_sample: self.position,
+ })?;
+ if self.pending_offset < pending.len() {
+ let count = (max_samples - output.len()).min(pending.len() - self.pending_offset);
+ output
+ .extend_from_slice(&pending[self.pending_offset..self.pending_offset + count]);
self.pending_offset += count;
continue;
}
self.pending.clear();
self.pending_offset = 0;
+ self.pending_frame = false;
if self.failure.is_some() || self.phase == Phase::Complete {
break;
}
@@ -281,7 +376,7 @@ impl AudioStream {
match self.phase {
Phase::NeedPacket => {
let mut packet = ffmpeg::Packet::empty();
- match packet.read(&mut self.input) {
+ match self.input.read_packet(&mut packet) {
Ok(()) => {
if packet.stream() != self.stream_index {
continue;
@@ -299,24 +394,38 @@ impl AudioStream {
})?;
self.phase = Phase::Draining;
}
- Err(_) => continue,
+ Err(_) => {
+ if self.cancellation.is_cancelled() {
+ return Err(Failure {
+ stage: "cancelled",
+ detail: "Audio decoding cancelled".into(),
+ });
+ }
+ if let Some(error) = self.input.io_error() {
+ return Err(Failure {
+ stage: "input-read",
+ detail: error.to_string(),
+ });
+ }
+ continue;
+ }
}
}
Phase::Receiving | Phase::Draining => {
match self.decoder.receive_frame(&mut self.decoded_frame) {
Ok(()) => {
- run_resampler(
- &mut self.resampler,
- &self.decoded_frame,
- &mut self.pending,
- )
- .map_err(|e| Failure {
+ self.resampler_output
+ .run(&mut self.resampler, &self.decoded_frame)
+ .map_err(|e| Failure {
+ stage: "resample",
+ detail: e,
+ })?;
+ self.resampler_output.samples().map_err(|detail| Failure {
stage: "resample",
- detail: e,
+ detail,
})?;
- if !self.pending.is_empty() {
- return Ok(());
- }
+ self.pending_frame = true;
+ return Ok(());
}
Err(_) => {
self.phase = if self.phase == Phase::Draining {
@@ -336,34 +445,27 @@ impl AudioStream {
self.phase = Phase::Complete;
return Ok(());
};
- let target = *self.resampler.output();
let capacity = delay
.output
.max(1)
.saturating_add(16)
.min(i64::from(i32::MAX)) as usize;
- let mut frame = Audio::new(target.format, capacity, target.channel_layout);
- let remaining = self.resampler.flush(&mut frame).map_err(|error| Failure {
+ let frame = self.resampler_output.prepare(&self.resampler, capacity);
+ let remaining = self.resampler.flush(frame).map_err(|error| Failure {
stage: "flush",
detail: format!("Flush Resampler / {error}"),
})?;
let output_samples = frame.samples();
- if output_samples > 0 {
- let byte_len = output_samples
- .saturating_mul(frame.channels() as usize)
- .saturating_mul(std::mem::size_of::<f32>());
- let bytes = frame.data(0).get(..byte_len).ok_or_else(|| Failure {
- stage: "flush",
- detail: "Resampled frame data shorter than expected".to_string(),
- })?;
- self.pending
- .extend(unsafe { crate::cast_bytes_to_f32_slice(bytes) });
- }
+ self.resampler_output.samples().map_err(|detail| Failure {
+ stage: "flush",
+ detail,
+ })?;
+ self.pending_frame = true;
self.flush_iterations += 1;
if remaining.is_none() || output_samples == 0 {
self.phase = Phase::Complete;
}
- if !self.pending.is_empty() || self.phase == Phase::Complete {
+ if output_samples > 0 || self.phase == Phase::Complete {
return Ok(());
}
}
@@ -426,48 +528,6 @@ fn open_input(
}
}
-fn run_resampler(
- resampler: &mut resampling::Context,
- decoded_frame: &Audio,
- samples: &mut Vec<f32>,
-) -> Result<(), String> {
- let target = *resampler.output();
- let capacity = resample_capacity(resampler, decoded_frame.samples());
- let mut frame = Audio::new(target.format, capacity, target.channel_layout);
- resampler
- .run(decoded_frame, &mut frame)
- .map_err(|error| format!("Run Resampler / {error}"))?;
- if frame.samples() == 0 {
- return Ok(());
- }
- let byte_len = frame
- .samples()
- .saturating_mul(frame.channels() as usize)
- .saturating_mul(std::mem::size_of::<f32>());
- let data = frame
- .data(0)
- .get(..byte_len)
- .ok_or_else(|| "Resampled frame data shorter than expected".to_string())?;
- samples.extend(unsafe { crate::cast_bytes_to_f32_slice(data) });
- Ok(())
-}
-
-fn resample_capacity(resampler: &resampling::Context, input_samples: usize) -> usize {
- let src_rate = resampler.input().rate.max(1) as u64;
- let dst_rate = resampler.output().rate.max(1) as u64;
- let pending_output_samples = resampler
- .delay()
- .map(|delay| delay.output.max(0) as u64)
- .unwrap_or(0);
- let resampled_from_input = (input_samples as u64)
- .saturating_mul(dst_rate)
- .div_ceil(src_rate);
- pending_output_samples
- .saturating_add(resampled_from_input)
- .saturating_add(16)
- .min(i32::MAX as u64) as usize
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -616,9 +676,9 @@ mod tests {
let file = pcm_wav(48_000, 1, 1_201);
let cancellation = Arc::new(AtomicBool::new(false));
for _ in 0..32 {
- let mut stream = AudioStream::open(file.path(), cancellation.clone()).unwrap();
+ let stream = AudioStream::open(file.path(), cancellation.clone()).unwrap();
assert_eq!(Arc::strong_count(&cancellation), 2);
- let callback = unsafe { (*stream.input.as_mut_ptr()).interrupt_callback };
+ let callback = unsafe { (*stream.input.input().as_ptr()).interrupt_callback };
assert_eq!(
callback.opaque,
Arc::as_ptr(&stream.cancellation).cast_mut().cast()
@@ -653,7 +713,7 @@ mod tests {
let mut stream =
AudioStream::open_with_abort(file.path(), user.clone(), abort.clone()).unwrap();
assert!(matches!(stream.read_chunk(7).unwrap(), ChunkRead::Chunk(_)));
- let callback = unsafe { (*stream.input.as_mut_ptr()).interrupt_callback };
+ let callback = unsafe { (*stream.input.input().as_ptr()).interrupt_callback };
assert_eq!(unsafe { callback.callback.unwrap()(callback.opaque) }, 0);
let worker_abort = abort.clone();
std::thread::spawn(move || worker_abort.store(true, Ordering::Relaxed))
@@ -690,4 +750,182 @@ mod tests {
}
assert_eq!(stream.validate_to_end().unwrap(), 1_201);
}
+
+ #[test]
+ fn relocatable_audio_preserves_decoder_samples_across_publication_and_rollback() {
+ for (rate, channels) in [(44_100, 1), (48_000, 2), (96_000, 6)] {
+ let file = pcm_wav(rate, channels, 100_003);
+ let reference = crate::AudioData::from_file(file.path()).unwrap();
+ let bytes = std::fs::read(file.path()).unwrap();
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ std::fs::create_dir(&original).unwrap();
+ let paths: Vec<_> = bytes
+ .chunks(32_768)
+ .enumerate()
+ .map(|(index, bytes)| {
+ let path = std::path::PathBuf::from(format!("part-{index:03}.bin"));
+ std::fs::write(original.join(&path), bytes).unwrap();
+ path
+ })
+ .collect();
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let mut stream = AudioStream::open_relocatable(
+ &source,
+ paths.iter().map(std::path::PathBuf::as_path),
+ Arc::new(AtomicBool::new(false)),
+ )
+ .unwrap();
+ let mut samples = Vec::new();
+ let mut chunks = 0;
+ loop {
+ match stream.read_chunk(997).unwrap() {
+ ChunkRead::Chunk(chunk) => {
+ assert_eq!(chunk.channels, reference.channels());
+ assert_eq!(
+ chunk.source_start_sample as usize,
+ samples.len() / usize::from(reference.channels())
+ );
+ samples.extend(chunk.samples);
+ match chunks {
+ 0 => {
+ source.relocate(retained.clone()).unwrap();
+ std::fs::create_dir(&original).unwrap();
+ std::fs::write(original.join(&paths[0]), b"published media")
+ .unwrap();
+ }
+ 1 => {
+ assert!(
+ source
+ .relocate(directory.path().join("missing/target"))
+ .is_err()
+ );
+ }
+ 2 => {
+ assert_eq!(
+ std::fs::read(original.join(&paths[0])).unwrap(),
+ b"published media"
+ );
+ std::fs::remove_file(original.join(&paths[0])).unwrap();
+ std::fs::remove_dir(&original).unwrap();
+ source.relocate(original.clone()).unwrap();
+ }
+ _ => {}
+ }
+ chunks += 1;
+ }
+ ChunkRead::Eof { next_sample } => {
+ assert_eq!(next_sample as usize, reference.sample_count());
+ break;
+ }
+ }
+ }
+ assert!(chunks > 3);
+ assert_eq!(samples.len(), reference.samples().len());
+ assert!(
+ samples
+ .iter()
+ .zip(reference.samples())
+ .all(|(actual, expected)| actual.to_bits() == expected.to_bits())
+ );
+ assert_eq!(
+ stream.validate_to_end().unwrap() as usize,
+ reference.sample_count()
+ );
+ let retained_bytes: Vec<_> = paths
+ .iter()
+ .flat_map(|path| std::fs::read(original.join(path)).unwrap())
+ .collect();
+ assert_eq!(retained_bytes, bytes);
+ }
+ }
+
+ #[test]
+ fn relocatable_audio_cancellation_retains_positions_and_releases_ownership() {
+ let file = pcm_wav(48_000, 2, 100_003);
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ std::fs::create_dir(&original).unwrap();
+ std::fs::copy(file.path(), original.join("audio.wav")).unwrap();
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let user = Arc::new(AtomicBool::new(false));
+ let abort = Arc::new(AtomicBool::new(false));
+ for use_abort in [false, true] {
+ let mut stream = AudioStream::open_relocatable_with_abort(
+ &source,
+ [Path::new("audio.wav")],
+ user.clone(),
+ abort.clone(),
+ )
+ .unwrap();
+ assert_eq!(Arc::strong_count(&user), 2);
+ assert_eq!(Arc::strong_count(&abort), 2);
+ assert!(matches!(stream.read_chunk(7).unwrap(), ChunkRead::Chunk(_)));
+ source.relocate(retained.clone()).unwrap();
+ let flag = if use_abort { &abort } else { &user };
+ flag.store(true, Ordering::Relaxed);
+ let callback = unsafe { (*stream.input.input().as_ptr()).interrupt_callback };
+ assert_eq!(unsafe { callback.callback.unwrap()(callback.opaque) }, 1);
+ let error = stream.read_chunk(48_000).unwrap_err();
+ assert!(error.is_cancelled());
+ assert_eq!(error.next_sample, 7);
+ assert_eq!(stream.position(), 7);
+ flag.store(false, Ordering::Relaxed);
+ assert_eq!(stream.read_chunk(1).unwrap_err(), error);
+ drop(stream);
+ assert_eq!(Arc::strong_count(&user), 1);
+ assert_eq!(Arc::strong_count(&abort), 1);
+ source.relocate(original.clone()).unwrap();
+ }
+ let missing = AudioStream::open_relocatable_with_abort(
+ &source,
+ [Path::new("missing.wav")],
+ user.clone(),
+ abort.clone(),
+ );
+ assert!(missing.is_err());
+ assert_eq!(Arc::strong_count(&user), 1);
+ assert_eq!(Arc::strong_count(&abort), 1);
+ abort.store(true, Ordering::Relaxed);
+ assert!(
+ AudioStream::open_relocatable_with_abort(
+ &source,
+ [Path::new("audio.wav")],
+ user.clone(),
+ abort.clone(),
+ )
+ .err()
+ .unwrap()
+ .is_cancelled()
+ );
+ assert_eq!(Arc::strong_count(&user), 1);
+ assert_eq!(Arc::strong_count(&abort), 1);
+ }
+
+ #[test]
+ fn missing_relocatable_audio_never_spins_or_becomes_clean_eof() {
+ let file = pcm_wav(48_000, 2, 480_003);
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ std::fs::create_dir(&original).unwrap();
+ std::fs::copy(file.path(), original.join("audio.wav")).unwrap();
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original).unwrap();
+ let mut stream = AudioStream::open_relocatable(
+ &source,
+ [Path::new("audio.wav")],
+ Arc::new(AtomicBool::new(false)),
+ )
+ .unwrap();
+ assert!(matches!(stream.read_chunk(7).unwrap(), ChunkRead::Chunk(_)));
+ source.relocate(retained.clone()).unwrap();
+ std::fs::remove_file(retained.join("audio.wav")).unwrap();
+ let error = stream.validate_to_end().unwrap_err();
+ assert_eq!(error.stage, "input-read");
+ assert!(error.next_sample >= 7);
+ assert_eq!(stream.validate_to_end().unwrap_err(), error);
+ assert_eq!(stream.read_chunk(1).unwrap_err(), error);
+ }
}
diff --git a/crates/cap-muxer/src/main.rs b/crates/cap-muxer/src/main.rs
index af74843ed..ca5748e94 100644
--- a/crates/cap-muxer/src/main.rs
+++ b/crates/cap-muxer/src/main.rs
@@ -344,6 +344,11 @@ impl State {
flush_pending_packets(out, self.init_video.as_ref(), self.init_audio.as_ref())?;
}
if let Some(mut out) = self.output.take() {
+ if out.packets_written_video == 0 && out.packets_written_audio == 0 {
+ // FFmpeg 7.1 divides by zero when finalizing an empty DASH manifest;
+ // dropping the initialized context still closes its files and streams.
+ return Ok(());
+ }
out.ctx.write_trailer().map_err(|e| {
let err = anyhow!("write_trailer: {e}");
if classify_io_error(&e) {
@@ -895,6 +900,66 @@ mod tests {
assert_eq!(nominal_audio_duration_input_tb(&init), Some(1_024));
}
+ #[test]
+ fn empty_finish_closes_initialized_files_before_state_is_dropped() {
+ ffmpeg::init().unwrap();
+ let directory = std::env::temp_dir().join(format!(
+ "cap-muxer-empty-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir(&directory).unwrap();
+ let mut state = State::default();
+ handle_frame(
+ &mut state,
+ Frame::InitVideo(InitVideo {
+ codec: "libx264".into(),
+ width: 640,
+ height: 360,
+ frame_rate_num: 30,
+ frame_rate_den: 1,
+ time_base_num: 1,
+ time_base_den: 90_000,
+ extradata: Vec::new(),
+ segment_duration_ms: 2_000,
+ }),
+ )
+ .unwrap();
+ handle_frame(
+ &mut state,
+ Frame::Start(StartParams {
+ output_directory: directory.to_string_lossy().into_owned(),
+ init_segment_name: "init.mp4".into(),
+ media_segment_pattern: "segment_$Number%03d$.m4s".into(),
+ }),
+ )
+ .unwrap();
+ let init_path = directory.join("init.mp4");
+ assert!(init_path.is_file());
+ state.finish().unwrap();
+ for path in [init_path, directory.join("dash_manifest.mpd")] {
+ let mut options = std::fs::OpenOptions::new();
+ options.read(true).write(true);
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ options.share_mode(0);
+ }
+ let file = options.open(&path).unwrap();
+ assert_eq!(file.metadata().unwrap().len(), 0);
+ drop(file);
+ let renamed = path.with_extension("closed");
+ std::fs::rename(&path, &renamed).unwrap();
+ std::fs::rename(&renamed, &path).unwrap();
+ }
+ assert!(!directory.join("dash_manifest.mpd.tmp").exists());
+ state.finish().unwrap();
+ std::fs::remove_dir_all(directory).unwrap();
+ }
+
#[test]
fn cancellation_releases_producer_blocked_by_full_queue() {
let queue = Arc::new(FrameQueue::new(frame_size_hint(&Frame::Finish)));
diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.toml
index 116181b53..072c7bc72 100644
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@ -36,6 +36,7 @@ axum = { version = "0.7.5", features = ["ws"] }
ffmpeg.workspace = true
specta.workspace = true
serde = { workspace = true }
+serde_json = "1.0"
sentry.workspace = true
futures = { workspace = true }
tracing.workspace = true
@@ -50,5 +51,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
windows = { workspace = true, features = ["Win32_Media"] }
[dev-dependencies]
-serde_json = "1.0"
+cap-audio = { path = "../audio", features = ["test-support"] }
+cap-enc-ffmpeg = { path = "../enc-ffmpeg" }
+image = "0.25.2"
tempfile = "3"
diff --git a/crates/editor/examples/editor-startup-benchmark.rs b/crates/editor/examples/editor-startup-benchmark.rs
index 2004b0e82..e4a8b44d4 100644
--- a/crates/editor/examples/editor-startup-benchmark.rs
+++ b/crates/editor/examples/editor-startup-benchmark.rs
@@ -165,6 +165,8 @@ async fn main() {
})
.unwrap_or(0);
let profile_stages = has_flag(&args, "--profile-stages");
+ let profile_stages_only = has_flag(&args, "--profile-stages-only");
+ let prewarm_fonts = has_flag(&args, "--prewarm-fonts");
let resolution_base = cap_project::XY::new(1248, 702);
println!("{}", "=".repeat(64));
@@ -174,6 +176,21 @@ async fn main() {
println!("Runs: {runs}");
println!("Preview frame: {preview_frame}");
println!("Profile stages: {profile_stages}");
+ println!("Profile stages only: {profile_stages_only}");
+ if prewarm_fonts {
+ let started = Instant::now();
+ tokio::task::spawn_blocking(cap_rendering::prewarm_fonts)
+ .await
+ .expect("Font preparation failed");
+ println!(
+ "Font preparation before startup timing: {:.3}ms",
+ started.elapsed().as_secs_f64() * 1000.0
+ );
+ }
+ if profile_stages_only {
+ run_stage_profile(recording_path, runs).await;
+ return;
+ }
let mut values_ms = Vec::with_capacity(runs);
let mut preview_values_ms = Vec::with_capacity(runs);
@@ -204,11 +221,10 @@ async fn main() {
.preview_tx
.send(Some((preview_frame, fps, resolution_base)))
.expect("Failed to request preview frame");
- let preview_elapsed = if frame_rx.recv_timeout(Duration::from_secs(10)).is_ok() {
- preview_start.elapsed().as_secs_f64() * 1000.0
- } else {
- f64::INFINITY
- };
+ frame_rx
+ .recv_timeout(Duration::from_secs(10))
+ .expect("Preview did not produce a frame within 10 seconds");
+ let preview_elapsed = preview_start.elapsed().as_secs_f64() * 1000.0;
preview_values_ms.push(preview_elapsed);
editor.dispose().await;
diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rs
index ad8e79840..8f5c8c354 100644
--- a/crates/editor/src/audio.rs
+++ b/crates/editor/src/audio.rs
@@ -1,7 +1,7 @@
use crate::export_audio::{EXPORT_AUDIO_BLOCK_SAMPLES, ExportAudioError, ExportAudioSources};
use cap_audio::{
- AudioData, AudioRendererTrack, FromSampleBytes, StereoMode, cast_bytes_to_f32_slice,
- cast_f32_slice_to_bytes,
+ AudioData, AudioRendererTrack, DecodedAudio, FromSampleBytes, StereoMode,
+ cast_bytes_to_f32_slice, cast_f32_slice_to_bytes,
};
use cap_media::MediaError;
use cap_media_info::AudioInfo;
@@ -60,7 +60,7 @@ pub struct AudioSegment {
// yeah this is cursed oh well
#[derive(Clone)]
pub struct AudioSegmentTrack {
- data: Arc<AudioData>,
+ data: Arc<DecodedAudio>,
get_gain: fn(&AudioConfiguration) -> f32,
get_stereo_mode: fn(&AudioConfiguration) -> StereoMode,
get_offset: fn(&ClipOffsets) -> f32,
@@ -73,6 +73,20 @@ impl AudioSegmentTrack {
get_gain: fn(&AudioConfiguration) -> f32,
get_stereo_mode: fn(&AudioConfiguration) -> StereoMode,
get_offset: fn(&ClipOffsets) -> f32,
+ ) -> Self {
+ Self::from_decoded(
+ Arc::new(DecodedAudio::from(data)),
+ get_gain,
+ get_stereo_mode,
+ get_offset,
+ )
+ }
+
+ pub fn from_decoded(
+ data: Arc<DecodedAudio>,
+ get_gain: fn(&AudioConfiguration) -> f32,
+ get_stereo_mode: fn(&AudioConfiguration) -> StereoMode,
+ get_offset: fn(&ClipOffsets) -> f32,
) -> Self {
Self {
data,
@@ -88,7 +102,7 @@ impl AudioSegmentTrack {
self
}
- pub fn data(&self) -> &Arc<AudioData> {
+ pub fn data(&self) -> &Arc<DecodedAudio> {
&self.data
}
@@ -1355,6 +1369,68 @@ fn progressive_buffer_bytes(samples: usize) -> usize {
samples.saturating_mul(std::mem::size_of::<u32>())
}
+pub(crate) struct PreparingAudioOutputPolicy {
+ pub render_info: AudioInfo,
+ pub render_start_seconds: f64,
+ pub skip_output_frames: usize,
+ pub convert_from_f32: bool,
+}
+
+pub(crate) fn preparing_audio_output_policy(
+ duration_secs: f64,
+ output_info: AudioInfo,
+ start_playhead_secs: f64,
+) -> Result<PreparingAudioOutputPolicy, String> {
+ if !duration_secs.is_finite()
+ || duration_secs <= 0.0
+ || !start_playhead_secs.is_finite()
+ || start_playhead_secs < 0.0
+ || output_info.sample_rate == 0
+ || output_info.channels == 0
+ {
+ return Err("Preparing audio output timing is invalid".into());
+ }
+ let output_info = output_info.for_ffmpeg_output();
+ let estimated_output_samples =
+ progressive_buffer_samples(duration_secs, output_info.sample_rate, output_info.channels);
+ let convert_from_f32 =
+ progressive_buffer_bytes(estimated_output_samples) <= MAX_PROGRESSIVE_BUFFER_BYTES;
+ let render_start_seconds = if convert_from_f32 {
+ (start_playhead_secs - ProgressiveAudioBuffer::<f32>::START_PREROLL_SECS)
+ .max(0.0)
+ .min(duration_secs)
+ } else {
+ start_playhead_secs
+ };
+ let skip_output_frames = if convert_from_f32 {
+ let index = |seconds| {
+ output_sample_index(
+ seconds,
+ output_info.sample_rate,
+ output_info.channels,
+ estimated_output_samples,
+ ) / output_info.channels
+ };
+ index(start_playhead_secs).saturating_sub(index(render_start_seconds))
+ } else {
+ 0
+ };
+ Ok(PreparingAudioOutputPolicy {
+ render_info: if convert_from_f32 {
+ AudioInfo::new_raw(
+ AudioData::SAMPLE_FORMAT,
+ output_info.sample_rate,
+ output_info.channels as u16,
+ )
+ } else {
+ output_info
+ },
+ render_start_seconds,
+ skip_output_frames,
+ convert_from_f32,
+ })
+}
+
enum PrerenderedAudioBufferMode<T: FromSampleBytes> {
Progressive(ProgressiveAudioBuffer<T>),
Streaming(Box<StreamingAudioBuffer<T>>),
diff --git a/crates/editor/src/audio_output.rs b/crates/editor/src/audio_output.rs
index e5810988e..e6863e534 100644
--- a/crates/editor/src/audio_output.rs
+++ b/crates/editor/src/audio_output.rs
@@ -9,7 +9,7 @@
use std::{
sync::{
- Arc,
+ Arc, Mutex, OnceLock,
atomic::{AtomicBool, AtomicU64, Ordering},
mpsc as std_mpsc,
},
@@ -29,6 +29,10 @@ use tokio::sync::watch;
use tracing::{error, info};
use crate::audio::{AudioSegment, MusicTracks, PrerenderedAudioBuffer};
+use crate::preparing_audio::{
+ PreparingAudioBuffer, PreparingAudioOutputHandle, PreparingAudioOutputSnapshot,
+ PreparingAudioSources,
+};
/// How long to wait for the live callback to acknowledge a newly installed
/// source before reporting "no audio". A running stream acknowledges within
@@ -58,12 +62,257 @@ enum ControlMsg {
generation: u64,
result_tx: std_mpsc::Sender<bool>,
},
+ #[cfg(test)]
+ PreparePlayback {
+ spec: Box<PlaySpec>,
+ generation: u64,
+ request: Arc<PreparingAudioRequest>,
+ },
+ PrepareProgressivePlayback {
+ sources: PreparingAudioSources,
+ start_seconds: f64,
+ generation: u64,
+ installation: PreparingAudioInstallation,
+ },
StopPlayback {
generation: u64,
},
Shutdown,
}
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum PreparingAudioStatus {
+ Pending,
+ AwaitingCallback,
+ Started,
+ Unavailable,
+ Cancelled,
+}
+
+struct PreparingAudioRequest {
+ cancelled: AtomicBool,
+ started: AtomicBool,
+ deadline: Instant,
+ ack_deadline: OnceLock<Instant>,
+ status: watch::Sender<PreparingAudioStatus>,
+ output: Mutex<Option<PreparingAudioOutputHandle>>,
+ installed: watch::Sender<bool>,
+}
+
+impl PreparingAudioRequest {
+ fn new(timeout: Duration) -> Self {
+ Self {
+ cancelled: AtomicBool::new(false),
+ started: AtomicBool::new(false),
+ deadline: Instant::now() + timeout,
+ ack_deadline: OnceLock::new(),
+ status: watch::channel(PreparingAudioStatus::Pending).0,
+ output: Mutex::new(None),
+ installed: watch::channel(true).0,
+ }
+ }
+
+ fn is_cancelled(&self) -> bool {
+ self.cancelled.load(Ordering::Acquire)
+ || (!self.started.load(Ordering::Acquire) && Instant::now() >= self.deadline())
+ }
+
+ fn deadline(&self) -> Instant {
+ self.ack_deadline.get().copied().unwrap_or(self.deadline)
+ }
+
+ fn awaiting_callback(&self) {
+ let _ = self
+ .ack_deadline
+ .set(self.deadline.min(Instant::now() + SOURCE_ACK_TIMEOUT));
+ self.status.send_if_modified(|status| {
+ if *status != PreparingAudioStatus::Pending {
+ return false;
+ }
+ *status = PreparingAudioStatus::AwaitingCallback;
+ true
+ });
+ }
+
+ fn cancel(&self) {
+ self.cancelled.store(true, Ordering::Release);
+ if let Some(output) = self
+ .output
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ {
+ output.cancel();
+ }
+ self.status.send_replace(PreparingAudioStatus::Cancelled);
+ }
+
+ fn complete(&self, started: bool) {
+ self.status.send_if_modified(|status| {
+ if !matches!(
+ status,
+ PreparingAudioStatus::Pending | PreparingAudioStatus::AwaitingCallback
+ ) {
+ return false;
+ }
+ *status = if self.is_cancelled() {
+ PreparingAudioStatus::Cancelled
+ } else if started {
+ self.started.store(true, Ordering::Release);
+ PreparingAudioStatus::Started
+ } else {
+ self.cancelled.store(true, Ordering::Release);
+ PreparingAudioStatus::Unavailable
+ };
+ true
+ });
+ }
+}
+
+struct PreparingAudioInstallation {
+ request: Arc<PreparingAudioRequest>,
+ runtime: tokio::runtime::Handle,
+ playable_until: f64,
+}
+
+impl Drop for PreparingAudioInstallation {
+ fn drop(&mut self) {
+ self.request.installed.send_replace(true);
+ }
+}
+
+pub(crate) struct PreparingAudioPlayTicket {
+ generation: u64,
+ request: Arc<PreparingAudioRequest>,
+ control_tx: std_mpsc::Sender<ControlMsg>,
+}
+
+impl PreparingAudioPlayTicket {
+ pub(crate) fn output_handle(&self) -> Option<PreparingAudioOutputHandle> {
+ self.request
+ .output
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ }
+
+ pub(crate) fn set_playable_until(&self, seconds: f64) -> Result<(), String> {
+ if let Some(output) = self
+ .request
+ .output
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ {
+ output.set_playable_until(seconds)?;
+ }
+ Ok(())
+ }
+
+ pub(crate) fn output_status(&self, now: Instant) -> Option<PreparingAudioOutputSnapshot> {
+ self.request
+ .output
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .map(|output| output.status(now))
+ }
+
+ pub(crate) async fn stop_and_wait(&self) -> Result<(), String> {
+ self.cancel();
+ let mut installed = self.request.installed.subscribe();
+ tokio::time::timeout(PLAY_REQUEST_TIMEOUT, async {
+ while !*installed.borrow_and_update() {
+ installed
+ .changed()
+ .await
+ .map_err(|_| "Preparing audio installation owner ended".to_string())?;
+ }
+ Ok::<_, String>(())
+ })
+ .await
+ .map_err(|_| "Preparing audio installation cleanup timed out".to_string())??;
+ let output = self
+ .request
+ .output
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone();
+ if let Some(output) = output {
+ tokio::time::timeout(PLAY_REQUEST_TIMEOUT, output.stop_and_wait())
+ .await
+ .map_err(|_| "Preparing audio source cleanup timed out".to_string())??;
+ }
+ Ok(())
+ }
+
+ pub(crate) async fn wait_started(&self) -> bool {
+ let mut status = self.request.status.subscribe();
+ loop {
+ let current = *status.borrow_and_update();
+ match current {
+ PreparingAudioStatus::Started if !self.request.is_cancelled() => return true,
+ PreparingAudioStatus::Pending | PreparingAudioStatus::AwaitingCallback => {}
+ _ => {
+ self.cancel();
+ return false;
+ }
+ }
+ if !matches!(
+ tokio::time::timeout_at(self.request.deadline().into(), status.changed()).await,
+ Ok(Ok(()))
+ ) {
+ self.cancel();
+ return false;
+ }
+ }
+ }
+
+ pub(crate) fn cancel(&self) {
+ self.request.cancel();
+ let _ = self.control_tx.send(ControlMsg::StopPlayback {
+ generation: self.generation,
+ });
+ }
+}
+
+impl Drop for PreparingAudioPlayTicket {
+ fn drop(&mut self) {
+ self.cancel();
+ }
+}
+
+enum SourceAcknowledgement {
+ Ordinary(std_mpsc::Sender<()>),
+ Preparing(Arc<PreparingAudioRequest>),
+}
+
+impl SourceAcknowledgement {
+ fn preparing_request(&self) -> Option<Arc<PreparingAudioRequest>> {
+ match self {
+ Self::Ordinary(_) => None,
+ Self::Preparing(request) => Some(request.clone()),
+ }
+ }
+
+ fn consumed(self) {
+ match &self {
+ Self::Ordinary(sender) => {
+ let _ = sender.send(());
+ }
+ Self::Preparing(request) => request.complete(true),
+ }
+ }
+}
+
+impl Drop for SourceAcknowledgement {
+ fn drop(&mut self) {
+ if let Self::Preparing(request) = self {
+ request.complete(false);
+ }
+ }
+}
+
/// Handle to the editor session's shared audio output. Owned by the editor
/// instance; playback sessions attach and detach sources through it.
pub struct AudioOutput {
@@ -162,6 +411,59 @@ impl AudioOutput {
}
}
+ #[cfg(test)]
+ pub(crate) fn prepare_playback(&self, spec: PlaySpec) -> PreparingAudioPlayTicket {
+ let generation = self.next_generation.fetch_add(1, Ordering::Relaxed);
+ let request = Arc::new(PreparingAudioRequest::new(PLAY_REQUEST_TIMEOUT));
+ let ticket = PreparingAudioPlayTicket {
+ generation,
+ request: request.clone(),
+ control_tx: self.control_tx.clone(),
+ };
+ if self
+ .control_tx
+ .send(ControlMsg::PreparePlayback {
+ spec: Box::new(spec),
+ generation,
+ request: request.clone(),
+ })
+ .is_err()
+ {
+ request.complete(false);
+ }
+ ticket
+ }
+
+ pub(crate) fn prepare_progressive_playback(
+ &self,
+ sources: PreparingAudioSources,
+ start_seconds: f64,
+ playable_until: f64,
+ ) -> PreparingAudioPlayTicket {
+ let generation = self.next_generation.fetch_add(1, Ordering::Relaxed);
+ let request = Arc::new(PreparingAudioRequest::new(PLAY_REQUEST_TIMEOUT));
+ request.installed.send_replace(false);
+ let ticket = PreparingAudioPlayTicket {
+ generation,
+ request: request.clone(),
+ control_tx: self.control_tx.clone(),
+ };
+ let command = ControlMsg::PrepareProgressivePlayback {
+ sources,
+ start_seconds,
+ generation,
+ installation: PreparingAudioInstallation {
+ request: request.clone(),
+ runtime: tokio::runtime::Handle::current(),
+ playable_until,
+ },
+ };
+ if self.control_tx.send(command).is_err() {
+ request.complete(false);
+ }
+ ticket
+ }
+
/// Detaches the source installed by the `play` call that returned this
/// generation. A newer source (from a replacing play) is left untouched,
/// so a stale playback shutting down can't cut off its successor.
@@ -186,13 +488,39 @@ impl Drop for AudioOutput {
/// Per-playback state owned by the audio callback.
struct ActiveSource<T: FromSampleBytes> {
generation: u64,
- buffer: PrerenderedAudioBuffer<T>,
+ buffer: ActiveSourceBuffer<T>,
playhead_rx: watch::Receiver<f64>,
- ack: Option<std_mpsc::Sender<()>>,
+ ack: Option<SourceAcknowledgement>,
+ preparing_request: Option<Arc<PreparingAudioRequest>>,
#[cfg(not(target_os = "windows"))]
latency_corrector: LatencyCorrector,
}
+enum ActiveSourceBuffer<T: FromSampleBytes> {
+ Ordinary(PrerenderedAudioBuffer<T>),
+ Preparing(PreparingAudioBuffer<T>),
+}
+
+#[cfg(test)]
+impl<T: FromSampleBytes + cpal::FromSample<f32>> ActiveSourceBuffer<T> {
+ fn current_playhead_secs(&self) -> f64 {
+ let Self::Ordinary(buffer) = self else {
+ panic!("Preparing playback uses its consumed-span clock");
+ };
+ buffer.current_playhead_secs()
+ }
+
+ fn current_audible_playhead(&self, latency_seconds: f64) -> f64 {
+ let Self::Ordinary(buffer) = self else {
+ panic!("Preparing playback uses its consumed-span clock");
+ };
+ buffer.current_audible_playhead(latency_seconds)
+ }
+}
+
+type InstallProgressiveAudio =
+ dyn Fn(PreparingAudioSources, f64, u64, &PreparingAudioInstallation) -> Result<(), String>;
+
enum SourceCommand<T: FromSampleBytes> {
Install(Box<ActiveSource<T>>),
Remove { generation: Option<u64> },
@@ -203,7 +531,8 @@ enum SourceCommand<T: FromSampleBytes> {
struct TypedStreamHandle {
_stream: cpal::Stream,
#[allow(clippy::type_complexity)]
- install: Box<dyn Fn(Box<PlaySpec>, u64, std_mpsc::Sender<()>) -> Result<(), String>>,
+ install: Box<dyn Fn(Box<PlaySpec>, u64, SourceAcknowledgement) -> Result<(), String>>,
+ install_progressive: Box<InstallProgressiveAudio>,
remove: Box<dyn Fn(Option<u64>)>,
}
@@ -230,11 +559,62 @@ fn control_thread(control_rx: std_mpsc::Receiver<ControlMsg>) {
let ok = handle_play(&mut state, spec, generation);
let _ = result_tx.send(ok);
}
- ControlMsg::StopPlayback { generation } => {
- if let Some(s) = &state {
- (s.handle.remove)(Some(generation));
+ #[cfg(test)]
+ ControlMsg::PreparePlayback {
+ spec,
+ generation,
+ request,
+ } => {
+ if request.is_cancelled() || !ensure_stream(&mut state) || request.is_cancelled() {
+ request.complete(false);
+ continue;
+ }
+ let Some(stream) = state.as_ref() else {
+ request.complete(false);
+ continue;
+ };
+ if let Err(error) = (stream.handle.install)(
+ spec,
+ generation,
+ SourceAcknowledgement::Preparing(request.clone()),
+ ) {
+ error!("Failed to install preparing audio source: {error}");
+ request.complete(false);
}
}
+ ControlMsg::PrepareProgressivePlayback {
+ sources,
+ start_seconds,
+ generation,
+ installation,
+ } => {
+ let request = &installation.request;
+ if request.is_cancelled() || !ensure_stream(&mut state) || request.is_cancelled() {
+ request.complete(false);
+ continue;
+ }
+ let Some(stream) = state.as_ref() else {
+ request.complete(false);
+ continue;
+ };
+ if let Err(error) = (stream.handle.install_progressive)(
+ sources,
+ start_seconds,
+ generation,
+ &installation,
+ ) {
+ error!("Failed to install progressive preparing audio: {error}");
+ request.complete(false);
+ }
+ }
+ ControlMsg::StopPlayback { generation } => {
+ stop_stream_state(
+ &mut state,
+ generation,
+ |stream| stream.failed.load(Ordering::Acquire),
+ |stream, generation| (stream.handle.remove)(Some(generation)),
+ );
+ }
ControlMsg::Shutdown => break,
}
}
@@ -242,6 +622,19 @@ fn control_thread(control_rx: std_mpsc::Receiver<ControlMsg>) {
info!("Audio output thread finished");
}
+fn stop_stream_state<S>(
+ state: &mut Option<S>,
+ generation: u64,
+ is_failed: impl FnOnce(&S) -> bool,
+ remove: impl FnOnce(&S, u64),
+) {
+ if state.as_ref().is_some_and(is_failed) {
+ drop(state.take());
+ } else if let Some(stream) = state.as_ref() {
+ remove(stream, generation);
+ }
+}
+
/// Applies pending install/remove commands to the active source. Shared by
/// the live cpal callback and the headless sink.
fn drain_source_commands<T: FromSampleBytes>(
@@ -250,7 +643,15 @@ fn drain_source_commands<T: FromSampleBytes>(
) {
while let Ok(command) = source_rx.try_recv() {
match command {
- SourceCommand::Install(source) => *active = Some(*source),
+ SourceCommand::Install(source) => {
+ if !source
+ .preparing_request
+ .as_ref()
+ .is_some_and(|request| request.is_cancelled())
+ {
+ *active = Some(*source);
+ }
+ }
SourceCommand::Remove { generation } => {
let matches = generation.is_none()
|| active
@@ -263,6 +664,14 @@ fn drain_source_commands<T: FromSampleBytes>(
}
}
}
+ if active.as_ref().is_some_and(|source| {
+ source
+ .preparing_request
+ .as_ref()
+ .is_some_and(|request| request.is_cancelled())
+ }) {
+ *active = None;
+ }
}
/// Renders one output block from the active source: applies the video
@@ -274,22 +683,50 @@ fn render_source_block<T: FromSampleBytes + cpal::FromSample<f32>>(
buffer: &mut [T],
latency_secs: f64,
) {
- if source.playhead_rx.has_changed().unwrap_or(false) {
- let video_playhead = *source.playhead_rx.borrow_and_update();
- let audible_playhead = source.buffer.current_audible_playhead(latency_secs);
- let drift = (video_playhead - audible_playhead).abs();
-
- // Normal frame updates coalesce on this watch too; only audible drift
- // establishes whether the audio needs to move to the latest target.
- if drift > 0.04 {
- source.buffer.set_playhead(video_playhead + latency_secs);
+ if source
+ .preparing_request
+ .as_ref()
+ .is_some_and(|request| request.is_cancelled())
+ {
+ buffer.fill(T::EQUILIBRIUM);
+ return;
+ }
+ match &mut source.buffer {
+ ActiveSourceBuffer::Ordinary(audio) => {
+ if source.playhead_rx.has_changed().unwrap_or(false) {
+ let video_playhead = *source.playhead_rx.borrow_and_update();
+ let audible_playhead = audio.current_audible_playhead(latency_secs);
+ let drift = (video_playhead - audible_playhead).abs();
+
+ if drift > 0.04 {
+ audio.set_playhead(video_playhead + latency_secs);
+ }
+ }
+ audio.fill(buffer);
+ }
+ ActiveSourceBuffer::Preparing(audio) => {
+ if audio.fill(buffer, latency_secs) == 0 {
+ if audio.is_terminal()
+ && let Some(request) = &source.preparing_request
+ {
+ request.complete(false);
+ }
+ return;
+ }
}
}
- source.buffer.fill(buffer);
+ if source
+ .preparing_request
+ .as_ref()
+ .is_some_and(|request| request.is_cancelled())
+ {
+ buffer.fill(T::EQUILIBRIUM);
+ return;
+ }
if let Some(ack) = source.ack.take() {
- let _ = ack.send(());
+ ack.consumed();
}
}
@@ -299,11 +736,18 @@ fn render_source_block<T: FromSampleBytes + cpal::FromSample<f32>>(
fn install_source<T: FromSampleBytes + cpal::FromSample<f32>>(
spec: Box<PlaySpec>,
generation: u64,
- ack: std_mpsc::Sender<()>,
+ ack: SourceAcknowledgement,
output_info: AudioInfo,
use_device_latency_hint: bool,
install_tx: &std_mpsc::Sender<SourceCommand<T>>,
) -> Result<(), String> {
+ let preparing_request = ack.preparing_request();
+ if preparing_request
+ .as_ref()
+ .is_some_and(|request| request.is_cancelled())
+ {
+ return Err("Preparing audio request cancelled".into());
+ }
let PlaySpec {
segments,
music,
@@ -365,12 +809,77 @@ fn install_source<T: FromSampleBytes + cpal::FromSample<f32>>(
// playhead, never leading silence.
buffer.wait_until_ready(PRERENDER_READY_TIMEOUT);
+ if preparing_request
+ .as_ref()
+ .is_some_and(|request| request.is_cancelled())
+ {
+ return Err("Preparing audio request cancelled".into());
+ }
+
+ if let Some(request) = &preparing_request {
+ request.awaiting_callback();
+ }
+
install_tx
.send(SourceCommand::Install(Box::new(ActiveSource {
generation,
- buffer,
+ buffer: ActiveSourceBuffer::Ordinary(buffer),
playhead_rx,
ack: Some(ack),
+ preparing_request,
+ #[cfg(not(target_os = "windows"))]
+ latency_corrector,
+ })))
+ .map_err(|_| "Audio callback channel closed".to_string())
+}
+
+fn install_progressive_source<T: FromSampleBytes + cpal::FromSample<f32>>(
+ sources: PreparingAudioSources,
+ start_seconds: f64,
+ generation: u64,
+ installation: &PreparingAudioInstallation,
+ output_info: AudioInfo,
+ use_device_latency_hint: bool,
+ install_tx: &std_mpsc::Sender<SourceCommand<T>>,
+) -> Result<(), String> {
+ let request = &installation.request;
+ if request.is_cancelled() {
+ return Err("Preparing audio request cancelled".into());
+ }
+ #[cfg(not(target_os = "windows"))]
+ let latency_corrector = LatencyCorrector::new(
+ if use_device_latency_hint {
+ default_output_latency_hint(output_info.sample_rate, output_info.buffer_size)
+ } else {
+ None
+ },
+ LatencyCorrectionConfig::default(),
+ );
+ #[cfg(target_os = "windows")]
+ let _ = use_device_latency_hint;
+ let (buffer, output) = PreparingAudioBuffer::<T>::spawn(
+ sources,
+ output_info,
+ start_seconds,
+ installation.runtime.clone(),
+ )?;
+ *request
+ .output
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(output.clone());
+ output.set_playable_until(installation.playable_until)?;
+ if request.is_cancelled() {
+ return Err("Preparing audio request cancelled".into());
+ }
+ let (_, playhead_rx) = watch::channel(start_seconds);
+ request.awaiting_callback();
+ install_tx
+ .send(SourceCommand::Install(Box::new(ActiveSource {
+ generation,
+ buffer: ActiveSourceBuffer::Preparing(buffer),
+ playhead_rx,
+ ack: Some(SourceAcknowledgement::Preparing(request.clone())),
+ preparing_request: Some(request.clone()),
#[cfg(not(target_os = "windows"))]
latency_corrector,
})))
@@ -443,7 +952,7 @@ fn control_thread_headless(control_rx: std_mpsc::Receiver<ControlMsg>, mut tap:
&& match install_source::<f32>(
spec,
generation,
- ack_tx,
+ SourceAcknowledgement::Ordinary(ack_tx),
output_info,
false,
&source_tx,
@@ -456,6 +965,52 @@ fn control_thread_headless(control_rx: std_mpsc::Receiver<ControlMsg>, mut tap:
};
let _ = result_tx.send(ok);
}
+ #[cfg(test)]
+ ControlMsg::PreparePlayback {
+ spec,
+ generation,
+ request,
+ } => {
+ if request.is_cancelled() || pump.is_none() {
+ request.complete(false);
+ continue;
+ }
+ if let Err(error) = install_source::<f32>(
+ spec,
+ generation,
+ SourceAcknowledgement::Preparing(request.clone()),
+ output_info,
+ false,
+ &source_tx,
+ ) {
+ error!("Failed to install preparing headless audio source: {error}");
+ request.complete(false);
+ }
+ }
+ ControlMsg::PrepareProgressivePlayback {
+ sources,
+ start_seconds,
+ generation,
+ installation,
+ } => {
+ let request = &installation.request;
+ if request.is_cancelled() || pump.is_none() {
+ request.complete(false);
+ continue;
+ }
+ if let Err(error) = install_progressive_source::<f32>(
+ sources,
+ start_seconds,
+ generation,
+ &installation,
+ output_info,
+ false,
+ &source_tx,
+ ) {
+ error!("Failed to install progressive headless audio: {error}");
+ request.complete(false);
+ }
+ }
ControlMsg::StopPlayback { generation } => {
let _ = source_tx.send(SourceCommand::Remove {
generation: Some(generation),
@@ -482,7 +1037,7 @@ fn handle_play(state: &mut Option<StreamState>, spec: Box<PlaySpec>, generation:
};
let (ack_tx, ack_rx) = std_mpsc::channel();
- if let Err(e) = (s.handle.install)(spec, generation, ack_tx) {
+ if let Err(e) = (s.handle.install)(spec, generation, SourceAcknowledgement::Ordinary(ack_tx)) {
error!("Failed to install audio source: {e}");
return false;
}
@@ -620,11 +1175,26 @@ where
let install_tx = source_tx.clone();
let install = Box::new(
- move |spec: Box<PlaySpec>, generation: u64, ack: std_mpsc::Sender<()>| {
+ move |spec: Box<PlaySpec>, generation: u64, ack: SourceAcknowledgement| {
install_source::<T>(spec, generation, ack, output_info, true, &install_tx)
},
);
+ let progressive_tx = source_tx.clone();
+ let install_progressive = Box::new(
+ move |sources, start_seconds, generation, installation: &PreparingAudioInstallation| {
+ install_progressive_source::<T>(
+ sources,
+ start_seconds,
+ generation,
+ installation,
+ output_info,
+ true,
+ &progressive_tx,
+ )
+ },
+ );
+
let remove = Box::new(move |generation: Option<u64>| {
let _ = source_tx.send(SourceCommand::Remove { generation });
});
@@ -632,15 +1202,19 @@ where
Ok(TypedStreamHandle {
_stream: stream,
install,
+ install_progressive,
remove,
})
}
+#[cfg(test)]
+mod native_tests;
+
#[cfg(test)]
mod tests {
use super::*;
- fn source(sample_rate: u32) -> (ActiveSource<f32>, watch::Sender<f64>) {
+ pub(super) fn source(sample_rate: u32) -> (ActiveSource<f32>, watch::Sender<f64>) {
source_with_info(
AudioInfo::new_raw(AudioData::SAMPLE_FORMAT, sample_rate, 2),
false,
@@ -665,7 +1239,7 @@ mod tests {
playhead_rx,
}),
0,
- ack_tx,
+ SourceAcknowledgement::Ordinary(ack_tx),
output_info,
use_device_latency_hint,
&install_tx,
diff --git a/crates/editor/src/audio_output/native_tests.rs b/crates/editor/src/audio_output/native_tests.rs
new file mode 100644
index 000000000..a9e81e7cd
--- /dev/null
+++ b/crates/editor/src/audio_output/native_tests.rs
@@ -0,0 +1,714 @@
+use super::*;
+use std::io::Write;
+
+struct HeadlessControl {
+ output: Arc<AudioOutput>,
+ release: Option<std_mpsc::Sender<()>>,
+ thread: Option<std::thread::JoinHandle<()>>,
+ blocks: flume::Receiver<bool>,
+}
+
+impl HeadlessControl {
+ async fn blocked() -> Self {
+ let (release, blocked) = std_mpsc::channel();
+ let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
+ let (blocks_tx, blocks) = flume::unbounded();
+ let mut entered_tx = Some(entered_tx);
+ let tap = Box::new(move |samples: &[f32], _: Instant| {
+ if let Some(entered) = entered_tx.take() {
+ let _ = entered.send(());
+ let _ = blocked.recv();
+ }
+ let _ = blocks_tx.send(samples.iter().any(|sample| sample.abs() > 0.0001));
+ });
+ let (control_tx, control_rx) = std_mpsc::channel();
+ let thread = std::thread::spawn(move || control_thread_headless(control_rx, tap));
+ let control = Self {
+ output: Arc::new(AudioOutput {
+ control_tx,
+ next_generation: AtomicU64::new(0),
+ }),
+ release: Some(release),
+ thread: Some(thread),
+ blocks,
+ };
+ tokio::time::timeout(Duration::from_secs(2), entered_rx)
+ .await
+ .unwrap()
+ .unwrap();
+ control
+ }
+
+ fn release(&mut self) {
+ if let Some(release) = self.release.take() {
+ let _ = release.send(());
+ }
+ }
+
+ async fn block(&self) -> bool {
+ tokio::time::timeout(Duration::from_secs(2), self.blocks.recv_async())
+ .await
+ .unwrap()
+ .unwrap()
+ }
+
+ async fn join(mut self) {
+ self.release();
+ self.output.shutdown();
+ let thread = self.thread.take().unwrap();
+ tokio::time::timeout(
+ Duration::from_secs(2),
+ tokio::task::spawn_blocking(move || thread.join().unwrap()),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ }
+}
+
+impl Drop for HeadlessControl {
+ fn drop(&mut self) {
+ self.release();
+ self.output.shutdown();
+ }
+}
+
+fn audible_spec() -> PlaySpec {
+ ffmpeg::init().unwrap();
+ let mut file = tempfile::Builder::new().suffix(".wav").tempfile().unwrap();
+ let samples = vec![5000i16; 96_000];
+ let bytes = (samples.len() * 2) as u32;
+ file.write_all(b"RIFF").unwrap();
+ file.write_all(&(36 + bytes).to_le_bytes()).unwrap();
+ file.write_all(b"WAVEfmt ").unwrap();
+ file.write_all(&16u32.to_le_bytes()).unwrap();
+ file.write_all(&1u16.to_le_bytes()).unwrap();
+ file.write_all(&1u16.to_le_bytes()).unwrap();
+ file.write_all(&48_000u32.to_le_bytes()).unwrap();
+ file.write_all(&96_000u32.to_le_bytes()).unwrap();
+ file.write_all(&2u16.to_le_bytes()).unwrap();
+ file.write_all(&16u16.to_le_bytes()).unwrap();
+ file.write_all(b"data").unwrap();
+ file.write_all(&bytes.to_le_bytes()).unwrap();
+ for sample in samples {
+ file.write_all(&sample.to_le_bytes()).unwrap();
+ }
+ file.flush().unwrap();
+ let audio = Arc::new(cap_audio::DecodedAudio::from(Arc::new(
+ AudioData::from_file(file.path()).unwrap(),
+ )));
+ let (_, playhead_rx) = watch::channel(0.0);
+ PlaySpec {
+ segments: vec![crate::audio_segment_from_decoded(
+ Some(audio),
+ None,
+ crate::SegmentAudioTimingRepair::default(),
+ )],
+ music: MusicTracks::new(),
+ project: ProjectConfiguration::default(),
+ duration_secs: 2.0,
+ start_playhead_secs: 0.0,
+ playhead_rx,
+ }
+}
+
+fn ticket_with_timeout(
+ output: &AudioOutput,
+ spec: PlaySpec,
+ timeout: Duration,
+) -> PreparingAudioPlayTicket {
+ let generation = output.next_generation.fetch_add(1, Ordering::Relaxed);
+ let request = Arc::new(PreparingAudioRequest::new(timeout));
+ output
+ .control_tx
+ .send(ControlMsg::PreparePlayback {
+ spec: Box::new(spec),
+ generation,
+ request: request.clone(),
+ })
+ .unwrap();
+ PreparingAudioPlayTicket {
+ generation,
+ request,
+ control_tx: output.control_tx.clone(),
+ }
+}
+
+async fn installed(ticket: &PreparingAudioPlayTicket) {
+ let mut status = ticket.request.status.subscribe();
+ tokio::time::timeout(Duration::from_secs(2), async {
+ while *status.borrow_and_update() == PreparingAudioStatus::Pending {
+ status.changed().await.unwrap();
+ }
+ assert!(*status.borrow() == PreparingAudioStatus::AwaitingCallback);
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn preparing_cancel_wakes_while_control_is_blocked_and_preserves_ordinary_playback() {
+ let spec = audible_spec();
+ let ordinary_spec = audible_spec();
+ let mut control = HeadlessControl::blocked().await;
+ let generation = control
+ .output
+ .next_generation
+ .fetch_add(1, Ordering::Relaxed);
+ let (result_tx, result_rx) = std_mpsc::channel();
+ control
+ .output
+ .control_tx
+ .send(ControlMsg::Play {
+ spec: Box::new(ordinary_spec),
+ generation,
+ result_tx,
+ })
+ .unwrap();
+ let ticket = control.output.prepare_playback(spec);
+ let (started, ()) = tokio::time::timeout(Duration::from_millis(200), async {
+ tokio::join!(ticket.wait_started(), async {
+ tokio::task::yield_now().await;
+ ticket.cancel();
+ })
+ })
+ .await
+ .unwrap();
+ assert!(!started);
+ assert!(ticket.request.is_cancelled());
+ control.release();
+ assert!(
+ tokio::task::spawn_blocking(move || result_rx.recv_timeout(Duration::from_secs(2)))
+ .await
+ .unwrap()
+ .unwrap()
+ );
+ assert!(!control.block().await);
+ assert!(control.block().await);
+ ticket.cancel();
+ drop(ticket);
+ assert!(control.block().await);
+ control.join().await;
+}
+
+#[tokio::test]
+async fn preparing_stale_ticket_does_not_stop_a_newer_ordinary_playback() {
+ let spec = audible_spec();
+ let successor_spec = audible_spec();
+ let mut control = HeadlessControl::blocked().await;
+ let ticket = control.output.prepare_playback(spec);
+ installed(&ticket).await;
+ let output = control.output.clone();
+ let successor = tokio::task::spawn_blocking(move || output.play(successor_spec));
+ control.release();
+ let generation = tokio::time::timeout(Duration::from_secs(2), successor)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ assert!(generation > ticket.generation);
+ ticket.cancel();
+ drop(ticket);
+ assert!(!control.block().await);
+ for _ in 0..4 {
+ assert!(control.block().await);
+ }
+ control.join().await;
+}
+
+#[tokio::test]
+async fn preparing_timeout_cancels_late_callback_install() {
+ let spec = audible_spec();
+ let mut control = HeadlessControl::blocked().await;
+ let ticket = ticket_with_timeout(&control.output, spec, Duration::from_millis(100));
+ installed(&ticket).await;
+ assert!(
+ !tokio::time::timeout(Duration::from_secs(1), ticket.wait_started())
+ .await
+ .unwrap()
+ );
+ assert!(ticket.request.cancelled.load(Ordering::Acquire));
+ control.release();
+ for _ in 0..4 {
+ assert!(!control.block().await);
+ }
+ assert!(!ticket.wait_started().await);
+ control.join().await;
+}
+
+#[tokio::test]
+async fn preparing_ticket_drop_rejects_already_queued_install() {
+ let spec = audible_spec();
+ let mut control = HeadlessControl::blocked().await;
+ let ticket = control.output.prepare_playback(spec);
+ installed(&ticket).await;
+ let request = ticket.request.clone();
+ drop(ticket);
+ assert!(request.is_cancelled());
+ control.release();
+ for _ in 0..4 {
+ assert!(!control.block().await);
+ }
+ control.join().await;
+}
+
+#[tokio::test]
+async fn preparing_cancelled_wait_can_be_retried_while_ticket_is_owned() {
+ let spec = audible_spec();
+ let mut control = HeadlessControl::blocked().await;
+ let ticket = control.output.prepare_playback(spec);
+ installed(&ticket).await;
+ assert!(
+ tokio::time::timeout(Duration::from_millis(10), ticket.wait_started())
+ .await
+ .is_err()
+ );
+ assert!(!ticket.request.is_cancelled());
+ control.release();
+ assert!(ticket.wait_started().await);
+ assert!(!control.block().await);
+ assert!(control.block().await);
+ control.join().await;
+}
+
+#[tokio::test]
+async fn preparing_failed_install_revokes_the_request() {
+ let mut spec = audible_spec();
+ spec.duration_secs = f64::NAN;
+ let mut control = HeadlessControl::blocked().await;
+ let ticket = control.output.prepare_playback(spec);
+ assert!(!ticket.wait_started().await);
+ assert!(ticket.request.cancelled.load(Ordering::Acquire));
+ control.release();
+ assert!(!control.block().await);
+ assert!(!control.block().await);
+ control.join().await;
+}
+
+#[tokio::test]
+async fn preparing_dropped_acknowledgement_wakes_and_cancels_without_waiting_for_timeout() {
+ let request = Arc::new(PreparingAudioRequest::new(PLAY_REQUEST_TIMEOUT));
+ let (control_tx, control_rx) = std_mpsc::channel();
+ let ticket = PreparingAudioPlayTicket {
+ generation: 12,
+ request: request.clone(),
+ control_tx,
+ };
+ let (source_tx, source_rx) = std_mpsc::channel();
+ install_source::<f32>(
+ Box::new(audible_spec()),
+ 12,
+ SourceAcknowledgement::Preparing(request.clone()),
+ AudioInfo::new_raw(AudioData::SAMPLE_FORMAT, 48_000, 2),
+ false,
+ &source_tx,
+ )
+ .unwrap();
+ drop(source_rx.recv().unwrap());
+ assert!(
+ !tokio::time::timeout(Duration::from_millis(200), ticket.wait_started())
+ .await
+ .unwrap()
+ );
+ assert!(request.cancelled.load(Ordering::Acquire));
+ assert!(matches!(
+ control_rx.recv().unwrap(),
+ ControlMsg::StopPlayback { generation: 12 }
+ ));
+}
+
+#[test]
+fn preparing_callback_silences_active_cancelled_source_without_a_remove_command() {
+ let spec = audible_spec();
+ let request = Arc::new(PreparingAudioRequest::new(PLAY_REQUEST_TIMEOUT));
+ let (source_tx, source_rx) = std_mpsc::channel();
+ install_source(
+ Box::new(spec),
+ 12,
+ SourceAcknowledgement::Preparing(request.clone()),
+ AudioInfo::new_raw(AudioData::SAMPLE_FORMAT, 48_000, 2),
+ false,
+ &source_tx,
+ )
+ .unwrap();
+ let SourceCommand::Install(mut source) = source_rx.recv().unwrap() else {
+ panic!("expected installed preparing source");
+ };
+ let mut block = [0.0f32; 1024];
+ render_source_block(&mut source, &mut block, 0.0);
+ assert!(block.iter().any(|sample| sample.abs() > 0.0001));
+ assert!(*request.status.borrow() == PreparingAudioStatus::Started);
+ request.cancel();
+ let before = source.buffer.current_playhead_secs();
+ render_source_block(&mut source, &mut block, 0.0);
+ assert!(block.iter().all(|sample| *sample == 0.0));
+ assert_eq!(source.buffer.current_playhead_secs(), before);
+ request.complete(true);
+ assert!(*request.status.borrow() == PreparingAudioStatus::Cancelled);
+}
+
+#[test]
+fn preparing_expired_install_does_not_replace_an_active_ordinary_source() {
+ let request = Arc::new(PreparingAudioRequest::new(PLAY_REQUEST_TIMEOUT));
+ let (source_tx, source_rx) = std_mpsc::channel();
+ install_source::<f32>(
+ Box::new(audible_spec()),
+ 12,
+ SourceAcknowledgement::Preparing(request.clone()),
+ AudioInfo::new_raw(AudioData::SAMPLE_FORMAT, 48_000, 2),
+ false,
+ &source_tx,
+ )
+ .unwrap();
+ request.cancel();
+ let (mut ordinary, _) = super::tests::source(48_000);
+ ordinary.generation = 13;
+ let mut active = Some(ordinary);
+ source_tx
+ .send(SourceCommand::Remove {
+ generation: Some(12),
+ })
+ .unwrap();
+ drain_source_commands(&mut active, &source_rx);
+ assert_eq!(active.unwrap().generation, 13);
+}
+
+struct RetainedSourceState {
+ failed: AtomicBool,
+ active: Option<ActiveSource<f32>>,
+ commands: std_mpsc::Receiver<SourceCommand<f32>>,
+ send_commands: std_mpsc::Sender<SourceCommand<f32>>,
+ _ownership: Arc<()>,
+}
+
+struct PreparingOwnershipFixture {
+ state: Option<RetainedSourceState>,
+ output: PreparingAudioOutputHandle,
+ producer: cap_audio::ProgressiveAudioTestProducer,
+ project: std::sync::Weak<ProjectConfiguration>,
+ owner: std::sync::Weak<()>,
+}
+
+fn preparing_test_sources(
+ loader: cap_audio::ProgressiveAudio,
+ duration: f64,
+) -> PreparingAudioSources {
+ let project = Arc::new(ProjectConfiguration {
+ timeline: Some(cap_project::TimelineConfiguration {
+ segments: vec![cap_project::TimelineSegment {
+ recording_clip: 0,
+ start: 0.0,
+ end: duration,
+ timescale: 1.0,
+ ..Default::default()
+ }],
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ style_segments: Vec::new(),
+ image_segments: Vec::new(),
+ camera3d_segments: Vec::new(),
+ transitions: Vec::new(),
+ }),
+ clips: vec![cap_project::ClipConfiguration::default()],
+ audio: cap_project::AudioConfiguration {
+ mic_stereo_mode: cap_project::StereoMode::Stereo,
+ ..Default::default()
+ },
+ ..Default::default()
+ });
+ PreparingAudioSources {
+ project,
+ tracks: vec![[Some(loader), None]],
+ required: vec![[true, false]],
+ repairs: vec![crate::SegmentAudioTimingRepair::default()],
+ }
+}
+
+fn pending_preparing_owner(generation: u64) -> PreparingOwnershipFixture {
+ let (loader, producer) = cap_audio::ProgressiveAudioTestProducer::new();
+ let sources = preparing_test_sources(loader, 1.0);
+ let project_weak = Arc::downgrade(&sources.project);
+ let request = Arc::new(PreparingAudioRequest::new(PLAY_REQUEST_TIMEOUT));
+ request.installed.send_replace(false);
+ let installation = PreparingAudioInstallation {
+ request: request.clone(),
+ runtime: tokio::runtime::Handle::current(),
+ playable_until: 0.0,
+ };
+ let (send_commands, commands) = std_mpsc::channel();
+ install_progressive_source::<f32>(
+ sources,
+ 0.0,
+ generation,
+ &installation,
+ AudioInfo::new_raw(AudioData::SAMPLE_FORMAT, 48_000, 2),
+ false,
+ &send_commands,
+ )
+ .unwrap();
+ drop(installation);
+ assert!(*request.installed.borrow());
+ let output = request.output.lock().unwrap().clone().unwrap();
+ let ownership = Arc::new(());
+ let owner = Arc::downgrade(&ownership);
+ PreparingOwnershipFixture {
+ state: Some(RetainedSourceState {
+ failed: AtomicBool::new(false),
+ active: None,
+ commands,
+ send_commands,
+ _ownership: ownership,
+ }),
+ output,
+ producer,
+ project: project_weak,
+ owner,
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn failed_stream_stop_retires_active_and_queued_preparing_owners_without_callbacks() {
+ for active in [false, true] {
+ let mut fixture = pending_preparing_owner(40);
+ let state = fixture.state.as_mut().unwrap();
+ if active {
+ drain_source_commands(&mut state.active, &state.commands);
+ assert_eq!(state.active.as_ref().unwrap().generation, 40);
+ }
+ state.failed.store(true, Ordering::Release);
+ let mut waiting = Box::pin(fixture.output.stop_and_wait());
+ assert!(
+ tokio::time::timeout(Duration::from_millis(20), &mut waiting)
+ .await
+ .is_err()
+ );
+ assert!(fixture.owner.upgrade().is_some());
+ drop(waiting);
+
+ stop_stream_state(
+ &mut fixture.state,
+ 40,
+ |stream| stream.failed.load(Ordering::Acquire),
+ |_, _| panic!("A failed stream cannot acknowledge a removal command"),
+ );
+
+ assert!(fixture.state.is_none());
+ assert!(fixture.owner.upgrade().is_none());
+ tokio::time::timeout(Duration::from_secs(2), fixture.output.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(fixture.project.upgrade().is_none());
+ drop(fixture.producer);
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn healthy_stream_stale_stop_preserves_ordinary_replacement_after_preparing_join() {
+ let mut fixture = pending_preparing_owner(50);
+ let state = fixture.state.as_mut().unwrap();
+ drain_source_commands(&mut state.active, &state.commands);
+ assert_eq!(state.active.as_ref().unwrap().generation, 50);
+ let (mut ordinary, _) = super::tests::source(48_000);
+ ordinary.generation = 51;
+ state
+ .send_commands
+ .send(SourceCommand::Install(Box::new(ordinary)))
+ .unwrap();
+ drain_source_commands(&mut state.active, &state.commands);
+ tokio::time::timeout(Duration::from_secs(2), fixture.output.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(fixture.project.upgrade().is_none());
+
+ stop_stream_state(
+ &mut fixture.state,
+ 50,
+ |stream| stream.failed.load(Ordering::Acquire),
+ |stream, generation| {
+ stream
+ .send_commands
+ .send(SourceCommand::Remove {
+ generation: Some(generation),
+ })
+ .unwrap();
+ },
+ );
+
+ assert!(fixture.owner.upgrade().is_some());
+ let state = fixture.state.as_mut().unwrap();
+ drain_source_commands(&mut state.active, &state.commands);
+ let active = state.active.as_mut().unwrap();
+ assert_eq!(active.generation, 51);
+ assert!(matches!(active.buffer, ActiveSourceBuffer::Ordinary(_)));
+ let before = active.buffer.current_playhead_secs();
+ render_source_block(active, &mut [0.0; 1024], 0.0);
+ assert!(active.buffer.current_playhead_secs() > before);
+ drop(fixture.state.take());
+ assert!(fixture.owner.upgrade().is_none());
+ drop(fixture.producer);
+}
+
+fn publish_audio_frames(
+ producer: &cap_audio::ProgressiveAudioTestProducer,
+ samples: &[f32],
+ frames: std::ops::Range<usize>,
+) {
+ producer
+ .append(cap_audio::AudioChunk {
+ source_start_sample: frames.start as u64,
+ channels: 2,
+ samples: samples[frames.start * 2..frames.end * 2].to_vec(),
+ })
+ .unwrap();
+}
+
+async fn collect_gated_samples(
+ blocks: &flume::Receiver<Vec<f32>>,
+ actual: &mut Vec<f32>,
+ expected: &[f32],
+ limit_frames: usize,
+) {
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while actual.len() < limit_frames * 2 {
+ let block = blocks.recv_async().await.unwrap();
+ for frame in block.chunks_exact(2) {
+ if frame != [0.0, 0.0] {
+ assert!(frame.iter().all(|sample| *sample > 0.0));
+ actual.extend_from_slice(frame);
+ }
+ }
+ assert!(actual.len() <= limit_frames * 2);
+ assert_eq!(actual.as_slice(), &expected[..actual.len()]);
+ }
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn progressive_output_acknowledges_real_pcm_and_grows_the_same_gated_source() {
+ let (blocks_tx, blocks) = flume::unbounded();
+ let (control_tx, control_rx) = std_mpsc::channel();
+ let control = std::thread::spawn(move || {
+ control_thread_headless(
+ control_rx,
+ Box::new(move |samples, _| {
+ let _ = blocks_tx.send(samples.to_vec());
+ }),
+ );
+ });
+ let output = AudioOutput {
+ control_tx,
+ next_generation: AtomicU64::new(0),
+ };
+ let (loader, producer) = cap_audio::ProgressiveAudioTestProducer::new();
+ let sources = preparing_test_sources(loader.clone(), 70_000.0 / 48_000.0);
+ let project = Arc::downgrade(&sources.project);
+ let samples = (0..140_000)
+ .map(|index| (index % 997 + 1) as f32 / 4096.0)
+ .collect::<Vec<_>>();
+ let ticket = output.prepare_progressive_playback(sources, 0.0, 0.1);
+ let generation = ticket.generation;
+ publish_audio_frames(&producer, &samples, 0..32_768);
+ assert!(ticket.wait_started().await);
+ assert!(!loader.progress().complete);
+ let mut actual = Vec::new();
+ collect_gated_samples(&blocks, &mut actual, &samples, 4800).await;
+ for _ in 0..4 {
+ let block = tokio::time::timeout(Duration::from_secs(2), blocks.recv_async())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(block.iter().all(|sample| *sample == 0.0));
+ }
+ let status = ticket.output_status(Instant::now()).unwrap();
+ assert!(status.buffering);
+ assert_eq!(status.playhead_seconds, 0.1);
+ assert!(!status.ended);
+
+ publish_audio_frames(&producer, &samples, 32_768..65_536);
+ publish_audio_frames(&producer, &samples, 65_536..70_000);
+ producer.finish().unwrap();
+ ticket.set_playable_until(70_000.0 / 48_000.0).unwrap();
+ collect_gated_samples(&blocks, &mut actual, &samples, 70_000).await;
+ assert_eq!(actual, samples);
+ assert_eq!(ticket.generation, generation);
+ assert_eq!(
+ output.next_generation.load(Ordering::Acquire),
+ generation + 1
+ );
+ tokio::time::timeout(Duration::from_secs(2), ticket.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(project.upgrade().is_none());
+ output.shutdown();
+ tokio::time::timeout(
+ Duration::from_secs(2),
+ tokio::task::spawn_blocking(move || control.join().unwrap()),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn progressive_output_without_a_prefix_never_acknowledges_and_cancels_cleanly() {
+ let (blocks_tx, blocks) = flume::unbounded();
+ let (control_tx, control_rx) = std_mpsc::channel();
+ let control = std::thread::spawn(move || {
+ control_thread_headless(
+ control_rx,
+ Box::new(move |samples, _| {
+ let _ = blocks_tx.send(samples.iter().any(|sample| *sample != 0.0));
+ }),
+ );
+ });
+ let output = AudioOutput {
+ control_tx,
+ next_generation: AtomicU64::new(0),
+ };
+ let (loader, producer) = cap_audio::ProgressiveAudioTestProducer::new();
+ let sources = preparing_test_sources(loader, 1.0);
+ let project = Arc::downgrade(&sources.project);
+ publish_audio_frames(&producer, &vec![0.25; 65_536], 0..32_768);
+ let ticket = output.prepare_progressive_playback(sources, 0.0, 0.0);
+ installed(&ticket).await;
+ assert!(
+ tokio::time::timeout(Duration::from_millis(50), ticket.wait_started())
+ .await
+ .is_err()
+ );
+ for block in blocks.try_iter() {
+ assert!(!block);
+ }
+ assert!(!ticket.request.started.load(Ordering::Acquire));
+ assert_eq!(
+ ticket
+ .output_status(Instant::now())
+ .unwrap()
+ .playhead_seconds,
+ 0.0
+ );
+ tokio::time::timeout(Duration::from_secs(2), ticket.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(project.upgrade().is_none());
+ drop(producer);
+ output.shutdown();
+ tokio::time::timeout(
+ Duration::from_secs(2),
+ tokio::task::spawn_blocking(move || control.join().unwrap()),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+}
diff --git a/crates/editor/src/completed_audio.rs b/crates/editor/src/completed_audio.rs
new file mode 100644
index 000000000..f4c8d8714
--- /dev/null
+++ b/crates/editor/src/completed_audio.rs
@@ -0,0 +1,302 @@
+use cap_audio::DecodedAudio;
+use cap_project::{AudioGapSummary, AudioMeta, RecordingMeta, StudioRecordingMeta};
+use std::{path::PathBuf, sync::Arc};
+
+#[derive(Clone, Default)]
+pub(crate) struct CompletedAudioSegment {
+ pub(crate) mic: Option<Arc<DecodedAudio>>,
+ pub(crate) system_audio: Option<Arc<DecodedAudio>>,
+}
+
+#[derive(Clone, PartialEq, Eq)]
+struct AudioTrackIdentity {
+ path: String,
+ start_time_bits: Option<u64>,
+ device_id: Option<String>,
+ gap_summary: Option<AudioGapSummary>,
+}
+
+impl From<&AudioMeta> for AudioTrackIdentity {
+ fn from(meta: &AudioMeta) -> Self {
+ Self {
+ path: meta.path.to_string(),
+ start_time_bits: meta.start_time.map(f64::to_bits),
+ device_id: meta.device_id.clone(),
+ gap_summary: meta.gap_summary,
+ }
+ }
+}
+
+#[derive(Clone, PartialEq, Eq)]
+struct SegmentAudioIdentity {
+ mic: Option<AudioTrackIdentity>,
+ system_audio: Option<AudioTrackIdentity>,
+}
+
+fn audio_identities(meta: &StudioRecordingMeta) -> Vec<SegmentAudioIdentity> {
+ match meta {
+ StudioRecordingMeta::SingleSegment { segment } => vec![SegmentAudioIdentity {
+ mic: segment.audio.as_ref().map(Into::into),
+ system_audio: None,
+ }],
+ StudioRecordingMeta::MultipleSegments { inner } => inner
+ .segments
+ .iter()
+ .map(|segment| SegmentAudioIdentity {
+ mic: segment.mic.as_ref().map(Into::into),
+ system_audio: segment.system_audio.as_ref().map(Into::into),
+ })
+ .collect(),
+ }
+}
+
+#[derive(Clone)]
+pub struct CompletedAudioHandoff {
+ project_path: PathBuf,
+ identities: Vec<SegmentAudioIdentity>,
+ segments: Vec<CompletedAudioSegment>,
+}
+
+impl CompletedAudioHandoff {
+ pub(crate) fn from_completed_tracks(
+ source_metadata: &RecordingMeta,
+ expected_finalized_metadata: &RecordingMeta,
+ segments: Vec<CompletedAudioSegment>,
+ ) -> Result<Self, String> {
+ if source_metadata.project_path != expected_finalized_metadata.project_path {
+ return Err("Completed audio belongs to a different project".into());
+ }
+ let source = audio_identities(
+ source_metadata
+ .studio_meta()
+ .ok_or("Completed audio requires Studio metadata")?,
+ );
+ let identities = audio_identities(
+ expected_finalized_metadata
+ .studio_meta()
+ .ok_or("Completed audio requires Studio metadata")?,
+ );
+ if segments.len() != identities.len() || source.len() != identities.len() {
+ return Err("Completed audio segment count changed".into());
+ }
+ for ((completed, expected), original) in segments.iter().zip(&identities).zip(&source) {
+ for (audio, expected, original) in [
+ (&completed.mic, &expected.mic, &original.mic),
+ (
+ &completed.system_audio,
+ &expected.system_audio,
+ &original.system_audio,
+ ),
+ ] {
+ if audio.is_some()
+ && !matches!((original, expected), (Some(original), Some(expected)) if original.path == expected.path)
+ {
+ return Err("Completed audio track path or presence changed".into());
+ }
+ }
+ }
+ Ok(Self {
+ project_path: expected_finalized_metadata.project_path.clone(),
+ identities,
+ segments,
+ })
+ }
+
+ pub(crate) fn into_matching(
+ self,
+ recording_meta: &RecordingMeta,
+ meta: &StudioRecordingMeta,
+ ) -> Option<Vec<CompletedAudioSegment>> {
+ (self.project_path == recording_meta.project_path
+ && self.identities == audio_identities(meta))
+ .then_some(self.segments)
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+ use cap_project::{
+ MultipleSegment, MultipleSegments, RecordingMetaInner, StudioRecordingStatus, VideoMeta,
+ };
+ use std::io::Write;
+
+ pub(crate) fn audio() -> Arc<DecodedAudio> {
+ let mut file = tempfile::Builder::new().suffix(".wav").tempfile().unwrap();
+ let samples: Vec<i16> = (0..2003)
+ .map(|index| ((index * 31) % 12000 - 6000) as i16)
+ .collect();
+ let bytes = (samples.len() * 2) as u32;
+ file.write_all(b"RIFF").unwrap();
+ file.write_all(&(36 + bytes).to_le_bytes()).unwrap();
+ file.write_all(b"WAVEfmt ").unwrap();
+ file.write_all(&16u32.to_le_bytes()).unwrap();
+ file.write_all(&1u16.to_le_bytes()).unwrap();
+ file.write_all(&1u16.to_le_bytes()).unwrap();
+ file.write_all(&48000u32.to_le_bytes()).unwrap();
+ file.write_all(&96000u32.to_le_bytes()).unwrap();
+ file.write_all(&2u16.to_le_bytes()).unwrap();
+ file.write_all(&16u16.to_le_bytes()).unwrap();
+ file.write_all(b"data").unwrap();
+ file.write_all(&bytes.to_le_bytes()).unwrap();
+ for sample in samples {
+ file.write_all(&sample.to_le_bytes()).unwrap();
+ }
+ file.flush().unwrap();
+ Arc::new(DecodedAudio::from(Arc::new(
+ cap_audio::AudioData::from_file(file.path()).unwrap(),
+ )))
+ }
+
+ pub(crate) fn metadata() -> RecordingMeta {
+ RecordingMeta {
+ platform: None,
+ project_path: "fixture.cap".into(),
+ pretty_name: "Audio handoff fixture".into(),
+ sharing: None,
+ upload: None,
+ inner: RecordingMetaInner::Studio(Box::new(StudioRecordingMeta::MultipleSegments {
+ inner: MultipleSegments {
+ segments: (0..2)
+ .map(|index| MultipleSegment {
+ display: VideoMeta {
+ path: format!("content/segments/segment-{index}/display.mp4")
+ .into(),
+ fps: 30,
+ start_time: Some(0.0),
+ device_id: None,
+ },
+ camera: None,
+ mic: Some(AudioMeta {
+ path: format!("content/segments/segment-{index}/audio-input.m4a")
+ .into(),
+ start_time: Some(0.125),
+ device_id: Some("mic".into()),
+ gap_summary: None,
+ }),
+ system_audio: Some(AudioMeta {
+ path: format!("content/segments/segment-{index}/system_audio.ogg")
+ .into(),
+ start_time: Some(-0.25),
+ device_id: None,
+ gap_summary: None,
+ }),
+ cursor: None,
+ keyboard: None,
+ display_notch: None,
+ })
+ .collect(),
+ cursors: Default::default(),
+ status: Some(StudioRecordingStatus::Complete),
+ },
+ })),
+ }
+ }
+
+ pub(crate) fn segments_mut(meta: &mut RecordingMeta) -> &mut Vec<MultipleSegment> {
+ let RecordingMetaInner::Studio(studio) = &mut meta.inner else {
+ panic!()
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!()
+ };
+ &mut inner.segments
+ }
+
+ fn completed(audio: &Arc<DecodedAudio>) -> Vec<CompletedAudioSegment> {
+ vec![
+ CompletedAudioSegment {
+ mic: Some(audio.clone()),
+ system_audio: None,
+ },
+ CompletedAudioSegment::default(),
+ ]
+ }
+
+ #[test]
+ fn completed_cache_preserves_arc_and_sparse_missing_tracks() {
+ let meta = metadata();
+ let audio = audio();
+ let cache =
+ CompletedAudioHandoff::from_completed_tracks(&meta, &meta, completed(&audio)).unwrap();
+ let matched = cache
+ .into_matching(&meta, meta.studio_meta().unwrap())
+ .unwrap();
+ assert!(Arc::ptr_eq(matched[0].mic.as_ref().unwrap(), &audio));
+ assert!(matched[0].system_audio.is_none());
+ assert!(matched[1].mic.is_none());
+ }
+
+ #[test]
+ fn completed_cache_rejects_every_changed_track_identity() {
+ let original = metadata();
+ let audio = audio();
+ for field in [
+ "project", "index", "count", "presence", "path", "start", "device", "gap",
+ ] {
+ let mut actual = original.clone();
+ match field {
+ "project" => actual.project_path = "other.cap".into(),
+ "index" => segments_mut(&mut actual).swap(0, 1),
+ "count" => {
+ assert!(segments_mut(&mut actual).pop().is_some());
+ }
+ "presence" => segments_mut(&mut actual)[0].mic = None,
+ "path" => {
+ segments_mut(&mut actual)[0].mic.as_mut().unwrap().path = "changed.ogg".into()
+ }
+ "start" => {
+ segments_mut(&mut actual)[0]
+ .mic
+ .as_mut()
+ .unwrap()
+ .start_time = Some(0.1250000001)
+ }
+ "device" => segments_mut(&mut actual)[0].mic.as_mut().unwrap().device_id = None,
+ "gap" => {
+ segments_mut(&mut actual)[0]
+ .mic
+ .as_mut()
+ .unwrap()
+ .gap_summary = Some(AudioGapSummary {
+ total_overlap_trimmed_ms: 100,
+ startup_overlap_trimmed_ms: 100,
+ overlap_dropped_frames: 3,
+ startup_overlap_drops: 3,
+ })
+ }
+ _ => unreachable!(),
+ }
+ let cache = CompletedAudioHandoff::from_completed_tracks(
+ &original,
+ &original,
+ completed(&audio),
+ )
+ .unwrap();
+ assert!(
+ cache
+ .into_matching(&actual, actual.studio_meta().unwrap())
+ .is_none(),
+ "{field}"
+ );
+ }
+ }
+
+ #[test]
+ fn completed_pcm_cannot_be_relabelled_as_transcoded_or_absent_track() {
+ let original = metadata();
+ let audio = audio();
+ let mut expected = original.clone();
+ segments_mut(&mut expected)[0].mic.as_mut().unwrap().path =
+ "content/segments/segment-0/audio-input.ogg".into();
+ assert!(
+ CompletedAudioHandoff::from_completed_tracks(&original, &expected, completed(&audio))
+ .is_err()
+ );
+ segments_mut(&mut expected)[0].mic = None;
+ assert!(
+ CompletedAudioHandoff::from_completed_tracks(&original, &expected, completed(&audio))
+ .is_err()
+ );
+ }
+}
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 0529e187a..f4568f7b1 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -1,6 +1,6 @@
+use crate::completed_audio::{CompletedAudioHandoff, CompletedAudioSegment};
use crate::editor;
use crate::playback::{self, PlaybackHandle, PlaybackStartError};
-use cap_audio::AudioData;
use cap_project::StudioRecordingMeta;
use cap_project::{
CursorEvents, ProjectConfiguration, RecordingMeta, RecordingMetaInner, TimelineConfiguration,
@@ -22,12 +22,12 @@ use tokio::sync::{Mutex, watch};
use tokio_util::sync::CancellationToken;
use tracing::warn;
-const PREVIEW_RENDER_MAX_ATTEMPTS: u32 = 3;
-const PREVIEW_RENDER_RETRY_DELAY_MS: u64 = 120;
+pub(super) const PREVIEW_RENDER_MAX_ATTEMPTS: u32 = 3;
+pub(super) const PREVIEW_RENDER_RETRY_DELAY_MS: u64 = 120;
const PREVIEW_CURSOR_CACHE_CAPACITY: usize = 2;
#[derive(Default)]
-struct PreviewCursorCache {
+pub(super) struct PreviewCursorCache {
entries: Vec<PreviewCursorCacheEntry>,
}
@@ -39,7 +39,7 @@ struct PreviewCursorCacheEntry {
}
impl PreviewCursorCache {
- fn get(
+ pub(super) fn get(
&mut self,
recording_clip: u32,
cursor: &Arc<CursorEvents>,
@@ -176,6 +176,8 @@ fn display_video_duration(path: &Path) -> Option<f64> {
}
pub struct EditorInstance {
+ preparing_adoption: std::sync::Mutex<Option<crate::PreparingPlaybackAdoption>>,
+ completed_track_identity: Option<crate::preparing_handoff::CompletedTrackIdentity>,
pub project_path: PathBuf,
pub recordings: Arc<ProjectRecordingsMeta>,
pub renderer: Arc<editor::RendererHandle>,
@@ -274,7 +276,7 @@ impl EditorInstance {
shared_device,
frame_format,
audio_output,
- None,
+ EditorStartupInputs::default(),
)
.await
}
@@ -295,7 +297,31 @@ impl EditorInstance {
shared_device,
frame_format,
audio_output,
- Some(recordings),
+ EditorStartupInputs {
+ recordings: Some(recordings),
+ completed_audio: None,
+ },
+ )
+ .await
+ }
+
+ pub async fn new_with_startup_inputs(
+ project_path: PathBuf,
+ on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,
+ frame_cb: editor::EditorFrameCallback,
+ shared_device: Option<SharedWgpuDevice>,
+ frame_format: editor::EditorFrameFormat,
+ audio_output: Arc<crate::AudioOutput>,
+ inputs: EditorStartupInputs,
+ ) -> Result<Arc<Self>, String> {
+ Self::new_inner(
+ project_path,
+ on_state_change,
+ frame_cb,
+ shared_device,
+ frame_format,
+ audio_output,
+ inputs,
)
.await
}
@@ -307,8 +333,12 @@ impl EditorInstance {
shared_device: Option<SharedWgpuDevice>,
frame_format: editor::EditorFrameFormat,
audio_output: Arc<crate::AudioOutput>,
- preloaded_recordings: Option<Arc<ProjectRecordingsMeta>>,
+ inputs: EditorStartupInputs,
) -> Result<Arc<Self>, String> {
+ let EditorStartupInputs {
+ recordings: preloaded_recordings,
+ completed_audio,
+ } = inputs;
if !project_path.exists() {
return Err(format!("Video path {} not found!", project_path.display()));
}
@@ -409,37 +439,7 @@ impl EditorInstance {
}
if project.clips.is_empty() {
- let calibration_store = load_calibration_store(&recording_meta.project_path);
-
- match meta.as_ref() {
- StudioRecordingMeta::MultipleSegments { inner } => {
- project.clips = inner
- .segments
- .iter()
- .enumerate()
- .map(|(i, segment)| {
- let calibration_offset = get_calibration_offset(
- segment.camera_device_id(),
- segment.mic_device_id(),
- &calibration_store,
- );
- cap_project::ClipConfiguration {
- index: i as u32,
- offsets: segment
- .calculate_audio_offsets_with_calibration(calibration_offset),
- offsets_auto_calculated: true,
- }
- })
- .collect();
- }
- StudioRecordingMeta::SingleSegment { .. } => {
- project.clips = vec![cap_project::ClipConfiguration {
- index: 0,
- offsets: cap_project::ClipOffsets::default(),
- offsets_auto_calculated: false,
- }];
- }
- }
+ project.clips = initial_clip_configuration(&recording_meta.project_path, meta);
if let Err(e) = project.write(&recording_meta.project_path) {
warn!("Failed to save auto-generated clip offsets: {}", e);
@@ -458,10 +458,29 @@ impl EditorInstance {
tracing::info!("Using FFmpeg decoder for editor preview");
}
+ let completed_audio = completed_audio.and_then(|handoff| {
+ let matching = handoff.into_matching(&recording_meta, meta);
+ if matching.is_none() {
+ tracing::debug!("Completed preparing audio did not match finalized metadata; decoding ordinary sources");
+ }
+ matching
+ });
+ let completed_track_identity = completed_audio
+ .as_deref()
+ .map(crate::preparing_handoff::completed_track_identity);
let segments_task = tokio::spawn({
let recording_meta = recording_meta.clone();
let studio_meta = (**meta).clone();
- async move { create_segments(&recording_meta, &studio_meta, force_ffmpeg_for_editor).await }
+ async move {
+ create_segments_with_audio(
+ &recording_meta,
+ &studio_meta,
+ force_ffmpeg_for_editor,
+ true,
+ completed_audio.as_deref(),
+ )
+ .await
+ }
});
// Open the session's audio output stream now (in the background) so
@@ -556,6 +575,8 @@ impl EditorInstance {
let (playback_active_tx, playback_active_rx) = watch::channel(false);
let this = Arc::new(Self {
+ preparing_adoption: std::sync::Mutex::new(None),
+ completed_track_identity,
project_path,
recordings,
renderer,
@@ -586,11 +607,135 @@ impl EditorInstance {
Ok(this)
}
+ pub async fn install_preparing_handoff(
+ &self,
+ handoff: &crate::PreparingPlaybackHandoff,
+ ) -> Result<(), String> {
+ if self.preparing_adoption().is_some() {
+ return Err("Editor already has a preparing candidate".into());
+ }
+ let admission = if self
+ .completed_track_identity
+ .as_ref()
+ .is_some_and(|identity| handoff.matches_completed_audio(identity, &self.audio_output))
+ {
+ handoff.prepare_when_settled().await
+ } else {
+ Err("Preparing audio does not match this editor's completed sources or output".into())
+ };
+ let adoption = match admission {
+ Ok(adoption) => adoption,
+ Err(error) => {
+ let exit = handoff.stop_and_wait().await;
+ self.dispose().await;
+ return Err(if exit.cleanup_failed {
+ format!("{error}; preparing audio ownership could not be released")
+ } else {
+ error
+ });
+ }
+ };
+ *self
+ .preparing_adoption
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(adoption);
+ Ok(())
+ }
+
+ pub fn preparing_adoption(&self) -> Option<crate::PreparingPlaybackAdoption> {
+ self.preparing_adoption
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ }
+
+ pub fn commit_preparing_frame(&self, frame: u32, fps: u32) -> bool {
+ self.preparing_adoption()
+ .is_some_and(|adoption| adoption.try_commit(frame, fps))
+ }
+
+ pub async fn start_preparing_handoff(
+ self: &Arc<Self>,
+ fps: u32,
+ resolution: XY<u32>,
+ ) -> Result<bool, PlaybackStartError> {
+ let Some(adoption) = self.preparing_adoption() else {
+ return Ok(false);
+ };
+ let Some(snapshot) = adoption.snapshot() else {
+ return Ok(false);
+ };
+ if !snapshot.playback.playing {
+ return Ok(false);
+ }
+ let frame = crate::preparing_handoff::presentation_frame(&snapshot, fps);
+ self.start_playback_internal(fps, resolution, Some(frame), Some(adoption))
+ .await?;
+ Ok(true)
+ }
+
+ pub async fn recreate_preparing_candidate(
+ self: &Arc<Self>,
+ on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,
+ frame_cb: editor::EditorFrameCallback,
+ frame_format: editor::EditorFrameFormat,
+ ) -> Result<Arc<Self>, String> {
+ let adoption = self
+ .preparing_adoption()
+ .ok_or("Editor has no preparing candidate")?;
+ if !adoption.invalidated() {
+ return Err("Preparing candidate is still current".into());
+ }
+ self.dispose().await;
+ let adoption = adoption.retry().await?;
+ let project = self.project_config.1.borrow().clone();
+ let layers = editor::start_renderer_layers_creation(&self.render_constants, &project);
+ let layers = editor::finish_renderer_layers_creation(layers).await;
+ let renderer = Arc::new(editor::Renderer::spawn_with_format(
+ self.render_constants.clone(),
+ frame_cb,
+ layers,
+ frame_format,
+ )?);
+ let (preview_tx, preview_rx) = watch::channel(None);
+ let (playback_active, playback_active_rx) = watch::channel(false);
+ let next = Arc::new(Self {
+ preparing_adoption: std::sync::Mutex::new(Some(adoption)),
+ completed_track_identity: self.completed_track_identity.clone(),
+ project_path: self.project_path.clone(),
+ recordings: self.recordings.clone(),
+ renderer,
+ render_constants: self.render_constants.clone(),
+ playback_active,
+ playback_active_rx,
+ playback_epoch: AtomicU64::new(0),
+ state: Arc::new(Mutex::new(EditorState {
+ playhead_position: 0,
+ playback_task: None,
+ preview_task: None,
+ })),
+ on_state_change: Box::new(on_state_change),
+ preview_tx,
+ project_config: self.project_config.clone(),
+ segment_medias: self.segment_medias.clone(),
+ music_cache: self.music_cache.clone(),
+ meta: self.meta.clone(),
+ export_preview_active: AtomicBool::new(false),
+ export_active: AtomicBool::new(false),
+ runtime_handle: self.runtime_handle.clone(),
+ audio_output: self.audio_output.clone(),
+ });
+ next.state.lock().await.preview_task =
+ Some(next.clone().spawn_preview_renderer(preview_rx));
+ Ok(next)
+ }
+
pub fn meta(&self) -> &RecordingMeta {
&self.meta
}
pub async fn dispose(&self) {
+ self.playback_epoch.fetch_add(1, Ordering::SeqCst);
let mut state = self.state.lock().await;
if let Some(handle) = state.playback_task.take() {
@@ -610,7 +755,14 @@ impl EditorInstance {
self.renderer.stop().await;
- self.audio_output.shutdown();
+ let adoption = self.preparing_adoption();
+ let owns_output = adoption.as_ref().is_none_or(|adoption| adoption.is_owner());
+ if let Some(adoption) = adoption {
+ drop(adoption.stop_and_wait().await);
+ }
+ if owns_output {
+ self.audio_output.shutdown();
+ }
tokio::task::yield_now().await;
@@ -641,14 +793,61 @@ impl EditorInstance {
}
pub async fn start_playback(self: &Arc<Self>, fps: u32, resolution_base: XY<u32>) {
+ if let Err(error) = self
+ .start_playback_with_handle(fps, resolution_base, None)
+ .await
+ {
+ warn!(fps, ?error, "Skipping playback start");
+ }
+ }
+
+ pub async fn start_playback_with_handle(
+ self: &Arc<Self>,
+ fps: u32,
+ resolution_base: XY<u32>,
+ start_frame_number: Option<u32>,
+ ) -> Result<PlaybackHandle, PlaybackStartError> {
+ let adoption = self.preparing_adoption();
+ if let Some(adoption) = adoption {
+ if !adoption.is_owner() {
+ return Err(PlaybackStartError::PreparingCandidate);
+ }
+ if adoption
+ .stop_and_wait()
+ .await
+ .is_some_and(|exit| exit.cleanup_failed)
+ {
+ return Err(PlaybackStartError::PreparingCleanup);
+ }
+ drop(
+ self.preparing_adoption
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take(),
+ );
+ }
+ self.start_playback_internal(fps, resolution_base, start_frame_number, None)
+ .await
+ }
+
+ async fn start_playback_internal(
+ self: &Arc<Self>,
+ fps: u32,
+ resolution_base: XY<u32>,
+ start_frame_number: Option<u32>,
+ adoption: Option<crate::PreparingPlaybackAdoption>,
+ ) -> Result<PlaybackHandle, PlaybackStartError> {
let music = self.load_music_tracks().await;
let (mut handle, prev, epoch) = {
let mut state = self.state.lock().await;
- let start_frame_number = state.playhead_position;
+ if let Some(frame_number) = start_frame_number {
+ state.playhead_position = frame_number;
+ }
+ let start_frame_number = start_frame_number.unwrap_or(state.playhead_position);
- let playback_handle = match (playback::Playback {
+ let playback = playback::Playback {
segment_medias: self.segment_medias.clone(),
music: music.clone(),
renderer: self.renderer.clone(),
@@ -657,21 +856,21 @@ impl EditorInstance {
project: self.project_config.0.subscribe(),
audio_output: self.audio_output.clone(),
telemetry: None,
- })
- .start_with_diagnostics(
- fps,
- resolution_base,
- Some(cap_utils::operation_diagnostics::resource_id(
- &self.project_path,
- )),
- )
- .await
- {
- Ok(handle) => handle,
- Err(PlaybackStartError::InvalidFps) => {
- warn!(fps, "Skipping playback start due to invalid FPS");
- return;
- }
+ };
+ let playback_handle = if let Some(adoption) = adoption {
+ playback
+ .start_with_adopted_audio(fps, resolution_base, adoption)
+ .await?
+ } else {
+ playback
+ .start_with_diagnostics(
+ fps,
+ resolution_base,
+ Some(cap_utils::operation_diagnostics::resource_id(
+ &self.project_path,
+ )),
+ )
+ .await?
};
let epoch = self.playback_epoch.fetch_add(1, Ordering::SeqCst) + 1;
@@ -684,6 +883,7 @@ impl EditorInstance {
(playback_handle, prev, epoch)
};
+ let owned_handle = handle.clone();
let this = self.clone();
tokio::spawn(async move {
loop {
@@ -692,6 +892,9 @@ impl EditorInstance {
match event {
playback::PlaybackEvent::Start => {}
playback::PlaybackEvent::Frame(frame_number) => {
+ if this.playback_epoch.load(Ordering::SeqCst) != epoch {
+ continue;
+ }
this.modify_and_emit_state(|state| {
state.playhead_position = frame_number;
})
@@ -712,6 +915,7 @@ impl EditorInstance {
if let Some(prev) = prev {
prev.stop();
}
+ Ok(owned_handle)
}
/// True while a playback engine is live. Epoch-guarded against restart
@@ -1172,56 +1376,12 @@ pub struct SegmentMedia {
pub decoders: RecordingSegmentDecoders,
}
-/// Shared handle to an audio track that decodes in the background.
-///
-/// Editor startup doesn't block on decoding entire audio files into memory;
-/// consumers that actually need samples (playback, export, waveforms) await
-/// [`AudioLoader::get`], which resolves as soon as the background decode
-/// completes.
-#[derive(Clone)]
-pub struct AudioLoader {
- rx: watch::Receiver<Option<Result<Option<Arc<AudioData>>, String>>>,
-}
-
-impl AudioLoader {
- /// A loader for a segment with no audio track.
- pub fn none() -> Self {
- Self::ready(None)
- }
-
- /// A loader wrapping already-decoded audio.
- pub fn ready(audio: Option<Arc<AudioData>>) -> Self {
- // The sender is dropped immediately; `get` still resolves because the
- // value is already present when it first borrows the channel.
- let (_tx, rx) = watch::channel(Some(Ok(audio)));
- Self { rx }
- }
+pub type AudioLoader = cap_audio::ProgressiveAudio;
- /// Starts decoding `path` on the blocking pool.
- pub fn spawn(path: PathBuf, label: String) -> Self {
- let (tx, rx) = watch::channel(None);
- tokio::task::spawn_blocking(move || {
- let result = AudioData::from_file(&path)
- .map(|data| Some(Arc::new(data)))
- .map_err(|e| format!("{label} / {e}"));
- let _ = tx.send(Some(result));
- });
- Self { rx }
- }
-
- /// Waits for the background decode to finish. Returns `Ok(None)` when the
- /// segment has no audio track.
- pub async fn get(&self) -> Result<Option<Arc<AudioData>>, String> {
- let mut rx = self.rx.clone();
- loop {
- if let Some(result) = rx.borrow_and_update().clone() {
- return result;
- }
- if rx.changed().await.is_err() {
- return Err("Audio load task was dropped".to_string());
- }
- }
- }
+#[derive(Default)]
+pub struct EditorStartupInputs {
+ pub recordings: Option<Arc<ProjectRecordingsMeta>>,
+ pub completed_audio: Option<CompletedAudioHandoff>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
@@ -1245,18 +1405,11 @@ impl LegacyAudioLogTrack {
}
}
-struct LegacyAudioTimingRepair {
- log: Option<String>,
+struct LegacyAudioTimingRepair<'a> {
+ log: Option<&'a str>,
}
-impl LegacyAudioTimingRepair {
- fn load(project_path: &Path) -> Self {
- let log_path = project_path.join("recording-logs.log");
- Self {
- log: std::fs::read_to_string(log_path).ok(),
- }
- }
-
+impl LegacyAudioTimingRepair<'_> {
fn offset(
&self,
segment_index: usize,
@@ -1289,7 +1442,7 @@ impl LegacyAudioTimingRepair {
segment_index: usize,
track: LegacyAudioLogTrack,
) -> Option<cap_project::AudioGapSummary> {
- legacy_audio_gap_summary_from_log(self.log.as_deref()?, segment_index, track)
+ legacy_audio_gap_summary_from_log(self.log?, segment_index, track)
}
}
@@ -1375,12 +1528,78 @@ fn audio_timing_repair_offset(summary: Option<&cap_project::AudioGapSummary>) ->
-(summary.startup_overlap_trimmed_ms as f32 / 1_000.0)
}
+pub fn segment_audio_timing_repairs(
+ meta: &StudioRecordingMeta,
+ legacy_log: Option<&str>,
+) -> Vec<SegmentAudioTimingRepair> {
+ let count = match meta {
+ StudioRecordingMeta::SingleSegment { .. } => 1,
+ StudioRecordingMeta::MultipleSegments { inner } => inner.segments.len(),
+ };
+ (0..count)
+ .map(|index| segment_audio_timing_repair(meta, index, legacy_log))
+ .collect()
+}
+
+fn segment_audio_timing_repair(
+ meta: &StudioRecordingMeta,
+ index: usize,
+ legacy_log: Option<&str>,
+) -> SegmentAudioTimingRepair {
+ let legacy = LegacyAudioTimingRepair { log: legacy_log };
+ match meta {
+ StudioRecordingMeta::SingleSegment { segment } => SegmentAudioTimingRepair {
+ mic_offset_secs: legacy.offset(
+ 0,
+ LegacyAudioLogTrack::Mic,
+ segment
+ .audio
+ .as_ref()
+ .and_then(|audio| audio.gap_summary.as_ref()),
+ ),
+ system_audio_offset_secs: 0.0,
+ },
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ let segment = &inner.segments[index];
+ SegmentAudioTimingRepair {
+ mic_offset_secs: legacy.offset(
+ index,
+ LegacyAudioLogTrack::Mic,
+ segment
+ .mic
+ .as_ref()
+ .and_then(|audio| audio.gap_summary.as_ref()),
+ ),
+ system_audio_offset_secs: legacy.offset(
+ index,
+ LegacyAudioLogTrack::SystemAudio,
+ segment
+ .system_audio
+ .as_ref()
+ .and_then(|audio| audio.gap_summary.as_ref()),
+ ),
+ }
+ }
+ }
+}
+
+fn audio_loader_with_completed(
+ path: PathBuf,
+ label: String,
+ completed: Option<&Arc<cap_audio::DecodedAudio>>,
+) -> AudioLoader {
+ match completed {
+ Some(audio) => AudioLoader::from_result(Ok(Some(audio.clone()))),
+ None => AudioLoader::spawn(path, label),
+ }
+}
+
pub async fn create_segments(
recording_meta: &RecordingMeta,
meta: &StudioRecordingMeta,
force_ffmpeg: bool,
) -> Result<Vec<SegmentMedia>, String> {
- create_segments_with_audio(recording_meta, meta, force_ffmpeg, true).await
+ create_segments_with_audio(recording_meta, meta, force_ffmpeg, true, None).await
}
pub async fn create_segments_without_audio(
@@ -1388,7 +1607,7 @@ pub async fn create_segments_without_audio(
meta: &StudioRecordingMeta,
force_ffmpeg: bool,
) -> Result<Vec<SegmentMedia>, String> {
- create_segments_with_audio(recording_meta, meta, force_ffmpeg, false).await
+ create_segments_with_audio(recording_meta, meta, force_ffmpeg, false, None).await
}
async fn create_segments_with_audio(
@@ -1396,9 +1615,11 @@ async fn create_segments_with_audio(
meta: &StudioRecordingMeta,
force_ffmpeg: bool,
load_audio: bool,
+ completed_audio: Option<&[CompletedAudioSegment]>,
) -> Result<Vec<SegmentMedia>, String> {
- let legacy_timing_repair = LegacyAudioTimingRepair::load(&recording_meta.project_path);
- let legacy_timing_repair = &legacy_timing_repair;
+ let legacy_log =
+ std::fs::read_to_string(recording_meta.project_path.join("recording-logs.log")).ok();
+ let legacy_log = legacy_log.as_deref();
match &meta {
cap_project::StudioRecordingMeta::SingleSegment { segment: s } => {
@@ -1407,9 +1628,12 @@ async fn create_segments_with_audio(
.as_ref()
.filter(|_| load_audio)
.map(|audio_meta| {
- AudioLoader::spawn(
+ audio_loader_with_completed(
recording_meta.path(&audio_meta.path),
"SingleSegment Audio".to_string(),
+ completed_audio
+ .and_then(|segments| segments.first())
+ .and_then(|segment| segment.mic.as_ref()),
)
})
.unwrap_or_else(AudioLoader::none);
@@ -1450,14 +1674,7 @@ async fn create_segments_with_audio(
Ok(vec![SegmentMedia {
audio,
system_audio: AudioLoader::none(),
- audio_timing_repair: SegmentAudioTimingRepair {
- mic_offset_secs: legacy_timing_repair.offset(
- 0,
- LegacyAudioLogTrack::Mic,
- s.audio.as_ref().and_then(|m| m.gap_summary.as_ref()),
- ),
- system_audio_offset_secs: 0.0,
- },
+ audio_timing_repair: segment_audio_timing_repair(meta, 0, legacy_log),
cursor,
keyboard: Arc::new(Default::default()),
decoders,
@@ -1473,9 +1690,12 @@ async fn create_segments_with_audio(
.as_ref()
.filter(|_| load_audio)
.map(|audio| {
- AudioLoader::spawn(
+ audio_loader_with_completed(
recording_meta.path(&audio.path),
format!("MultipleSegments {i} Audio"),
+ completed_audio
+ .and_then(|segments| segments.get(i))
+ .and_then(|segment| segment.mic.as_ref()),
)
})
.unwrap_or_else(AudioLoader::none);
@@ -1485,9 +1705,12 @@ async fn create_segments_with_audio(
.as_ref()
.filter(|_| load_audio)
.map(|audio| {
- AudioLoader::spawn(
+ audio_loader_with_completed(
recording_meta.path(&audio.path),
format!("MultipleSegments {i} System Audio"),
+ completed_audio
+ .and_then(|segments| segments.get(i))
+ .and_then(|segment| segment.system_audio.as_ref()),
)
})
.unwrap_or_else(AudioLoader::none);
@@ -1512,18 +1735,7 @@ async fn create_segments_with_audio(
Ok::<SegmentMedia, String>(SegmentMedia {
audio,
system_audio,
- audio_timing_repair: SegmentAudioTimingRepair {
- mic_offset_secs: legacy_timing_repair.offset(
- i,
- LegacyAudioLogTrack::Mic,
- s.mic.as_ref().and_then(|m| m.gap_summary.as_ref()),
- ),
- system_audio_offset_secs: legacy_timing_repair.offset(
- i,
- LegacyAudioLogTrack::SystemAudio,
- s.system_audio.as_ref().and_then(|m| m.gap_summary.as_ref()),
- ),
- },
+ audio_timing_repair: segment_audio_timing_repair(meta, i, legacy_log),
cursor,
keyboard,
decoders,
@@ -1535,6 +1747,37 @@ async fn create_segments_with_audio(
}
}
+pub fn initial_clip_configuration(
+ project_path: &std::path::Path,
+ meta: &StudioRecordingMeta,
+) -> Vec<cap_project::ClipConfiguration> {
+ let calibration_store = load_calibration_store(project_path);
+ match meta {
+ StudioRecordingMeta::MultipleSegments { inner } => inner
+ .segments
+ .iter()
+ .enumerate()
+ .map(|(i, segment)| {
+ let calibration_offset = get_calibration_offset(
+ segment.camera_device_id(),
+ segment.mic_device_id(),
+ &calibration_store,
+ );
+ cap_project::ClipConfiguration {
+ index: i as u32,
+ offsets: segment.calculate_audio_offsets_with_calibration(calibration_offset),
+ offsets_auto_calculated: true,
+ }
+ })
+ .collect(),
+ StudioRecordingMeta::SingleSegment { .. } => vec![cap_project::ClipConfiguration {
+ index: 0,
+ offsets: cap_project::ClipOffsets::default(),
+ offsets_auto_calculated: false,
+ }],
+ }
+}
+
fn load_calibration_store(project_path: &std::path::Path) -> cap_audio::CalibrationStore {
let calibration_dir = project_path
.parent()
@@ -1561,6 +1804,55 @@ mod tests {
use super::*;
use cap_project::{AudioGapSummary, CursorClickEvent, CursorConfiguration, CursorMoveEvent};
+ #[tokio::test]
+ async fn completed_pcm_loader_reuses_arc_without_opening_a_missing_file() {
+ let audio = crate::completed_audio::tests::audio();
+ let loader = audio_loader_with_completed(
+ "not-created/audio.m4a".into(),
+ "cached".into(),
+ Some(&audio),
+ );
+ let loaded = loader.get().await.unwrap().unwrap();
+ assert!(Arc::ptr_eq(&loaded, &audio));
+ let missing =
+ audio_loader_with_completed("not-created/audio.m4a".into(), "ordinary".into(), None);
+ assert!(missing.get().await.is_err());
+ }
+
+ #[test]
+ fn shared_timing_repairs_preserve_track_index_and_legacy_precedence() {
+ let mut meta = crate::completed_audio::tests::metadata();
+ let structured = AudioGapSummary {
+ total_overlap_trimmed_ms: 867,
+ startup_overlap_trimmed_ms: 867,
+ overlap_dropped_frames: 3,
+ startup_overlap_drops: 3,
+ };
+ crate::completed_audio::tests::segments_mut(&mut meta)[0]
+ .mic
+ .as_mut()
+ .unwrap()
+ .gap_summary = Some(structured);
+ let log = (0..3).map(|_| "segment{index=0}:mic-out: Dropping overlapping audio frame frame_count=1 overlap_ms=100\nsegment{index=1}:system-audio-out: Dropping overlapping audio frame frame_count=1 overlap_ms=50\n").collect::<String>();
+ let repairs = segment_audio_timing_repairs(meta.studio_meta().unwrap(), Some(&log));
+ assert_eq!(
+ repairs,
+ vec![
+ SegmentAudioTimingRepair {
+ mic_offset_secs: -0.867,
+ system_audio_offset_secs: 0.0
+ },
+ SegmentAudioTimingRepair {
+ mic_offset_secs: 0.0,
+ system_audio_offset_secs: -0.15
+ }
+ ]
+ );
+ let without_log = segment_audio_timing_repairs(meta.studio_meta().unwrap(), None);
+ assert_eq!(without_log[0].mic_offset_secs, -0.867);
+ assert_eq!(without_log[1], SegmentAudioTimingRepair::default());
+ }
+
fn preview_cursor_events() -> Arc<CursorEvents> {
Arc::new(CursorEvents {
moves: [
@@ -1958,3 +2250,138 @@ mod tests {
assert_eq!(audio_timing_repair_offset(Some(&too_large)), 0.0);
}
}
+
+#[cfg(test)]
+mod initial_clip_configuration_tests {
+ use super::*;
+
+ fn metadata(with_ids: bool) -> StudioRecordingMeta {
+ serde_json::from_value(serde_json::json!({
+ "segments": [{
+ "display": {"path": "display.mp4", "fps": 30, "start_time": 1.23456789},
+ "camera": {"path": "camera.mp4", "fps": 24, "start_time": 0.987654321, "device_id": with_ids.then_some("camera")},
+ "mic": {"path": "mic.m4a", "start_time": 0.876543219, "device_id": with_ids.then_some("mic")},
+ "system_audio": {"path": "system.m4a", "start_time": 1.111111111}
+ }],
+ "cursors": {}
+ })).unwrap()
+ }
+
+ fn assert_bits(clips: &[cap_project::ClipConfiguration], calibration: f32) {
+ assert_eq!(clips.len(), 1);
+ assert_eq!(clips[0].index, 0);
+ assert!(clips[0].offsets_auto_calculated);
+ assert_eq!(
+ clips[0].offsets.camera.to_bits(),
+ ((1.23456789_f64 - 0.987654321) as f32).to_bits()
+ );
+ assert_eq!(
+ clips[0].offsets.mic.to_bits(),
+ (((1.23456789_f64 - 0.876543219) as f32) + calibration).to_bits()
+ );
+ assert_eq!(
+ clips[0].offsets.system_audio.to_bits(),
+ (((1.23456789_f64 - 1.111111111) as f32) + calibration).to_bits()
+ );
+ }
+
+ #[test]
+ fn calibration_projection_preserves_store_location_confidence_and_cast_order_without_writes() {
+ let directory = tempfile::tempdir().unwrap();
+ let project = directory.path().join("recordings/test.cap");
+ std::fs::create_dir_all(&project).unwrap();
+ let config = project.join("project-config.json");
+ std::fs::write(&config, b"untouched config sentinel").unwrap();
+ let mut store = cap_audio::CalibrationStore::new();
+ for confidence in [0.49, 0.5, 1.0] {
+ let offset = -0.03123456789_f64;
+ store.update_calibration(&cap_audio::DeviceSyncCalibration {
+ camera_id: "camera".into(),
+ microphone_id: "mic".into(),
+ measured_offset_secs: offset,
+ confidence,
+ measurement_count: 3,
+ });
+ store.save(directory.path()).unwrap();
+ let saved = std::fs::read(directory.path().join("sync_calibrations.json")).unwrap();
+ let clips = initial_clip_configuration(&project, &metadata(true));
+ assert_bits(
+ &clips,
+ if confidence >= 0.5 {
+ offset as f32
+ } else {
+ 0.0
+ },
+ );
+ assert_eq!(
+ std::fs::read(&config).unwrap(),
+ b"untouched config sentinel"
+ );
+ assert_eq!(
+ std::fs::read(directory.path().join("sync_calibrations.json")).unwrap(),
+ saved
+ );
+ }
+ }
+
+ #[test]
+ fn missing_store_invalid_store_and_missing_device_ids_keep_uncalibrated_offsets() {
+ let directory = tempfile::tempdir().unwrap();
+ let project = directory.path().join("recordings/test.cap");
+ assert_bits(&initial_clip_configuration(&project, &metadata(true)), 0.0);
+ assert!(!directory.path().join("sync_calibrations.json").exists());
+ std::fs::write(
+ directory.path().join("sync_calibrations.json"),
+ b"malformed",
+ )
+ .unwrap();
+ assert_bits(&initial_clip_configuration(&project, &metadata(true)), 0.0);
+ let mut store = cap_audio::CalibrationStore::new();
+ store.update_calibration(&cap_audio::DeviceSyncCalibration {
+ camera_id: "camera".into(),
+ microphone_id: "mic".into(),
+ measured_offset_secs: 0.7,
+ confidence: 1.0,
+ measurement_count: 2,
+ });
+ store.save(directory.path()).unwrap();
+ assert_bits(&initial_clip_configuration(&project, &metadata(false)), 0.0);
+ assert!(!project.exists());
+ }
+
+ #[test]
+ fn legacy_single_segment_and_missing_timing_preserve_their_default_offsets() {
+ let directory = tempfile::tempdir().unwrap();
+ let single: StudioRecordingMeta = serde_json::from_value(serde_json::json!({
+ "display": {"path": "display.mp4", "fps": 30}
+ }))
+ .unwrap();
+ let clips = initial_clip_configuration(directory.path(), &single);
+ assert_eq!(clips.len(), 1);
+ assert_eq!(clips[0].index, 0);
+ assert!(!clips[0].offsets_auto_calculated);
+ assert_eq!(
+ [
+ clips[0].offsets.camera,
+ clips[0].offsets.mic,
+ clips[0].offsets.system_audio
+ ],
+ [0.0; 3]
+ );
+ let mut multiple = metadata(true);
+ let StudioRecordingMeta::MultipleSegments { inner } = &mut multiple else {
+ panic!("Expected indexed metadata")
+ };
+ inner.segments[0].camera.as_mut().unwrap().start_time = None;
+ let clips = initial_clip_configuration(directory.path(), &multiple);
+ assert!(clips[0].offsets_auto_calculated);
+ assert_eq!(
+ [
+ clips[0].offsets.camera,
+ clips[0].offsets.mic,
+ clips[0].offsets.system_audio
+ ],
+ [0.0; 3]
+ );
+ }
+}
diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rs
index 6edd1dd8d..d932fb5a1 100644
--- a/crates/editor/src/lib.rs
+++ b/crates/editor/src/lib.rs
@@ -1,34 +1,58 @@
mod audio;
mod audio_output;
+mod completed_audio;
mod editor;
mod editor_instance;
mod export_audio;
mod playback;
+mod preparing_audio;
+mod preparing_editor;
+mod preparing_handoff;
+mod preparing_playback;
+mod preparing_preview;
mod segments;
mod telemetry;
-pub use audio::{AudioRenderer, MusicTracks};
+pub use audio::{AudioRenderer, AudioSegment, MusicTracks};
pub use audio_output::{
AudioOutput, HEADLESS_BLOCK_FRAMES, HEADLESS_CHANNELS, HEADLESS_SAMPLE_RATE, HeadlessAudioTap,
};
pub use cap_audio::{
TranscriptionAudioSource, TranscriptionAudioTake, append_transcription_audio,
- assemble_transcription_audio,
+ assemble_transcription_audio, waveform_peaks,
};
pub use cap_rendering::FrameLayout;
+pub use completed_audio::CompletedAudioHandoff;
pub use editor::{
EditorFrameCallback, EditorFrameFormat, EditorFrameOutput, Renderer, RendererHandle,
finish_renderer_layers_creation, start_renderer_layers_creation,
};
pub use editor_instance::{
- AudioLoader, EditorInstance, EditorState, SegmentMedia, create_segments,
- create_segments_without_audio,
+ AudioLoader, EditorInstance, EditorStartupInputs, EditorState, SegmentAudioTimingRepair,
+ SegmentMedia, create_segments, create_segments_without_audio, initial_clip_configuration,
+ segment_audio_timing_repairs,
};
pub use export_audio::{
ExportAudioError, ExportAudioPreparation, ExportAudioRenderer, ExportAudioValidation,
};
pub use playback::{Playback, PlaybackEvent, PlaybackHandle, PlaybackStartError};
-pub use segments::{get_audio_segments, load_music_tracks, load_music_tracks_uncached};
+pub use preparing_editor::{PreparingEditorPhase, PreparingEditorProgress, PreparingPlaybackState};
+pub use preparing_handoff::{
+ PreparingPlaybackAdoption, PreparingPlaybackHandoff, PreparingPlaybackIntent,
+};
+pub use preparing_playback::{
+ PreparingAudioSegmentInput, PreparingPlaybackController, PreparingPlaybackExit,
+ PreparingPlaybackOptions, PreparingPlaybackSession, PreparingPlaybackSnapshot,
+ PreparingPlaybackStopHandle,
+};
+pub use preparing_preview::{
+ PreparingFrameRequest, PreparingPreview, PreparingPreviewCallback, PreparingPreviewError,
+ PreparingPreviewExit, PreparingPreviewInput, PreparingPreviewOptions, PreparingPreviewReady,
+ PreparingPreviewSegment, PreparingPreviewStopHandle,
+};
+pub use segments::{
+ audio_segment_from_decoded, get_audio_segments, load_music_tracks, load_music_tracks_uncached,
+};
pub use telemetry::{
PlaybackFrameSource, PlaybackRenderOutputFormat, PlaybackSkipReason, PlaybackTelemetry,
PlaybackTelemetryEvent,
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index fb442e743..1dc66ab73 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -110,6 +110,8 @@ fn has_playback_audio(audio_segments: &[crate::audio::AudioSegment], has_music:
#[derive(Debug)]
pub enum PlaybackStartError {
InvalidFps,
+ PreparingCleanup,
+ PreparingCandidate,
}
pub struct Playback {
@@ -136,6 +138,7 @@ pub struct PlaybackHandle {
event_rx: watch::Receiver<PlaybackEvent>,
seek_tx: Arc<watch::Sender<(u64, u32)>>,
seek_generation: Arc<AtomicU64>,
+ adopted: Option<crate::PreparingPlaybackAdoption>,
}
struct PrefetchedFrame {
@@ -518,11 +521,31 @@ impl Playback {
.await
}
+ pub async fn start_with_adopted_audio(
+ self,
+ fps: u32,
+ resolution_base: XY<u32>,
+ adoption: crate::PreparingPlaybackAdoption,
+ ) -> Result<PlaybackHandle, PlaybackStartError> {
+ self.start_inner(fps, resolution_base, None, Some(adoption))
+ .await
+ }
+
pub async fn start_with_diagnostics(
+ self,
+ fps: u32,
+ resolution_base: XY<u32>,
+ resource: Option<u64>,
+ ) -> Result<PlaybackHandle, PlaybackStartError> {
+ self.start_inner(fps, resolution_base, resource, None).await
+ }
+
+ async fn start_inner(
mut self,
fps: u32,
resolution_base: XY<u32>,
resource: Option<u64>,
+ adopted: Option<crate::PreparingPlaybackAdoption>,
) -> Result<PlaybackHandle, PlaybackStartError> {
let start_call = Instant::now();
let mut diagnostic = Operation::start(
@@ -561,6 +584,7 @@ impl Playback {
event_rx,
seek_tx: Arc::new(seek_tx),
seek_generation: Arc::new(AtomicU64::new(0)),
+ adopted: adopted.clone(),
};
let (prefetch_tx, prefetch_rx) =
@@ -836,6 +860,8 @@ impl Playback {
));
diagnostic.stage("preparing_playback");
let playback_body = move || {
+ let adopted_guard = AdoptedPlaybackGuard(adopted);
+ let adopted = &adopted_guard.0;
let duration = self
.project
.borrow()
@@ -885,13 +911,29 @@ impl Playback {
let mut starvation_skips = 0u64;
while !*stop_rx.borrow() {
+ if adopted
+ .as_ref()
+ .is_some_and(|adoption| adoption.invalidated())
+ {
+ let _ = stop_tx.send(true);
+ break;
+ }
+ if let Some(snapshot) = adopted.as_ref().and_then(|adoption| adoption.snapshot()) {
+ let target = crate::preparing_handoff::presentation_frame(&snapshot, fps);
+ if target > frame_number {
+ frame_number = target;
+ prefetch_buffer.retain(|frame| frame.frame_number >= target);
+ let _ = frame_request_tx.send((seek_generation, target));
+ let _ = playback_position_tx.send(target);
+ }
+ }
refresh_prefetch_limit(
&prefetch_frame_limit,
largest_prefetched_frame_bytes,
boost_until,
);
- if seek_rx.has_changed().unwrap_or(false) {
+ if adopted.is_none() && seek_rx.has_changed().unwrap_or(false) {
(seek_generation, frame_number) = *seek_rx.borrow_and_update();
prefetch_buffer.clear();
first_frame_time = None;
@@ -1206,7 +1248,9 @@ impl Playback {
diagnostic.stage("initializing_audio_output");
let audio_spawn_start = Instant::now();
let _ = audio_playhead_tx.send(playback_start_frame as f64 / fps_f64);
- let audio_generation = if !has_playback_audio(&audio_segments, !self.music.is_empty()) {
+ let audio_generation = if adopted.is_some() {
+ None
+ } else if !has_playback_audio(&audio_segments, !self.music.is_empty()) {
info!("No audio segments found, skipping audio playback.");
None
} else {
@@ -1242,14 +1286,36 @@ impl Playback {
let mut start = Instant::now();
let mut clock_anchor_frame = playback_start_frame;
+ let mut last_adopted_frame = None;
'playback: loop {
+ if *stop_rx.borrow() {
+ break;
+ }
+ if let Some(adoption) = adopted {
+ let Some(snapshot) = adoption.snapshot() else {
+ break;
+ };
+ if snapshot.progress.phase == crate::PreparingEditorPhase::Unavailable {
+ break;
+ }
+ let target = crate::preparing_handoff::presentation_frame(&snapshot, fps);
+ if snapshot.playback.buffering || last_adopted_frame == Some(target) {
+ if !snapshot.playback.playing && adoption.is_owner() {
+ break;
+ }
+ std::thread::sleep(frame_duration);
+ continue;
+ }
+ frame_number = target;
+ let _ = playback_position_tx.send(target);
+ }
let limit_now = refresh_prefetch_limit(
&prefetch_frame_limit,
largest_prefetched_frame_bytes,
boost_until,
);
- if seek_rx.has_changed().unwrap_or(false) {
+ if adopted.is_none() && seek_rx.has_changed().unwrap_or(false) {
let (generation, target) = *seek_rx.borrow_and_update();
tracing::debug!(from = frame_number, to = target, "playback live seek");
seek_generation = generation;
@@ -1277,14 +1343,20 @@ impl Playback {
let frame_offset = frame_number.saturating_sub(clock_anchor_frame) as f64;
let next_deadline = start + frame_duration.mul_f64(frame_offset);
- precision_sleep_sync(next_deadline);
+ if adopted.is_none() {
+ precision_sleep_sync(next_deadline);
+ }
if *stop_rx.borrow() {
break;
}
- let overshoot = Instant::now().saturating_duration_since(next_deadline);
- if overshoot > frame_duration + frame_duration / 2 {
+ let overshoot = if adopted.is_some() {
+ Duration::ZERO
+ } else {
+ Instant::now().saturating_duration_since(next_deadline)
+ };
+ if adopted.is_none() && overshoot > frame_duration + frame_duration / 2 {
let frames_behind = (overshoot.as_secs_f64() * fps_f64).floor() as u32;
let skip = frames_behind.max(1);
let skipped_from = frame_number;
@@ -1354,6 +1426,31 @@ impl Playback {
was_cached = true;
cache_hits += 1;
Some(cached)
+ } else if adopted.is_some() {
+ let mut exact = prefetch_buffer
+ .iter()
+ .position(|frame| frame.frame_number == frame_number)
+ .and_then(|index| prefetch_buffer.remove(index));
+ if exact.is_none() {
+ let _ = frame_request_tx.send((seek_generation, frame_number));
+ match receive_prefetched_frame(
+ &prefetch_rx,
+ seek_generation,
+ frame_duration,
+ ) {
+ Ok(frame) if frame.frame_number == frame_number => exact = Some(frame),
+ Ok(frame) if frame.frame_number > frame_number => {
+ prefetch_buffer.push_back(frame)
+ }
+ Ok(_) | Err(std_mpsc::RecvTimeoutError::Timeout) => {}
+ Err(std_mpsc::RecvTimeoutError::Disconnected) => break 'playback,
+ }
+ }
+ let Some(frame) = exact else {
+ continue;
+ };
+ frame_source = PlaybackFrameSource::PrefetchWaitExact;
+ Some(frame.into_cached())
} else if prefetch_buffer
.front()
.is_some_and(|f| f.frame_number == frame_number)
@@ -1572,6 +1669,9 @@ impl Playback {
if let Some((segment_frames, segment_index, transition)) = segment_frames_opt {
let Some(segment_media) = self.segment_medias.get(segment_index as usize)
else {
+ if adopted.is_some() {
+ break;
+ }
frame_number = frame_number.saturating_add(1);
continue;
};
@@ -1717,6 +1817,10 @@ impl Playback {
}
event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
+ if adopted.is_some() {
+ last_adopted_frame = Some(frame_number);
+ continue;
+ }
frame_number = frame_number.saturating_add(1);
let _ = playback_position_tx.send(frame_number);
@@ -1794,8 +1898,21 @@ impl Playback {
}
}
+struct AdoptedPlaybackGuard(Option<crate::PreparingPlaybackAdoption>);
+
+impl Drop for AdoptedPlaybackGuard {
+ fn drop(&mut self) {
+ if let Some(adoption) = &self.0 {
+ adoption.cancel();
+ }
+ }
+}
+
impl PlaybackHandle {
pub fn stop(&self) {
+ if let Some(adoption) = &self.adopted {
+ adoption.cancel();
+ }
self.stop_tx.send(true).ok();
}
@@ -1803,6 +1920,9 @@ impl PlaybackHandle {
/// re-attach. Returns false once the playback thread is gone, which is the
/// caller's cue to fall back to a full restart.
pub fn seek(&self, frame: u32) -> bool {
+ if self.adopted.is_some() {
+ return false;
+ }
let generation = self.seek_generation.fetch_add(1, Ordering::Relaxed) + 1;
self.seek_tx.send((generation, frame)).is_ok()
}
@@ -1817,6 +1937,35 @@ impl PlaybackHandle {
mod tests {
use super::*;
+ #[test]
+ fn late_handoff_stop_only_cancels_its_original_playback() {
+ let make_handle = || {
+ let (stop_tx, stop_rx) = watch::channel(false);
+ let (_, event_rx) = watch::channel(PlaybackEvent::Start);
+ let (seek_tx, _) = watch::channel((0, 0));
+ (
+ PlaybackHandle {
+ adopted: None,
+ stop_tx,
+ event_rx,
+ seek_tx: Arc::new(seek_tx),
+ seek_generation: Arc::new(AtomicU64::new(0)),
+ },
+ stop_rx,
+ )
+ };
+ let (first, first_stop) = make_handle();
+ let handoff_owner = first.clone();
+ let (replacement, replacement_stop) = make_handle();
+ let mut current_playback = Some(first);
+ current_playback.replace(replacement).unwrap().stop();
+ handoff_owner.stop();
+ assert!(*first_stop.borrow());
+ assert!(!*replacement_stop.borrow());
+ current_playback.take().unwrap().stop();
+ assert!(*replacement_stop.borrow());
+ }
+
fn decoded_frames(bytes: usize) -> DecodedSegmentFrames {
DecodedSegmentFrames {
screen_size: XY::new(1, 1),
diff --git a/crates/editor/src/preparing_audio/mixer.rs b/crates/editor/src/preparing_audio/mixer.rs
new file mode 100644
index 000000000..b0948ddab
--- /dev/null
+++ b/crates/editor/src/preparing_audio/mixer.rs
@@ -0,0 +1,669 @@
+use crate::SegmentAudioTimingRepair;
+use cap_audio::{
+ AudioData, AudioRendererTrack, AudioSampleSource, AudioSampleWindow, AudioWindowRead,
+ ProgressiveAudio,
+};
+use cap_project::ProjectConfiguration;
+use std::{ops::Range, sync::Arc};
+
+const RATE: f64 = AudioData::SAMPLE_RATE as f64;
+const MAX_FRAME: usize = 1 << 40;
+const MAX_CHUNK_FRAMES: usize = 65_536;
+
+#[derive(Clone)]
+pub(crate) struct PreparingAudioSources {
+ pub(crate) project: Arc<ProjectConfiguration>,
+ pub(crate) tracks: Vec<[Option<ProgressiveAudio>; 2]>,
+ pub(crate) required: Vec<[bool; 2]>,
+ pub(crate) repairs: Vec<SegmentAudioTimingRepair>,
+}
+
+struct ClipLayout {
+ start: usize,
+ end: usize,
+ offsets: [isize; 2],
+}
+
+impl PreparingAudioSources {
+ pub(crate) fn validate(&self) -> Result<(), String> {
+ self.layout().map(drop)
+ }
+
+ pub(crate) fn total_duration(&self) -> f64 {
+ self.project.timeline.as_ref().map_or(0.0, |timeline| {
+ timeline.segments.iter().map(|segment| segment.end).sum()
+ })
+ }
+
+ fn layout(&self) -> Result<Vec<ClipLayout>, String> {
+ let timeline = self
+ .project
+ .timeline
+ .as_ref()
+ .ok_or("Preparing audio timeline is absent")?;
+ let count = self.tracks.len();
+ if count == 0
+ || count > 1024
+ || self.required.len() != count
+ || self.repairs.len() != count
+ || timeline.segments.len() != count
+ || self.project.clips.len() != count
+ || !timeline.transitions.is_empty()
+ || !timeline.audio_segments.is_empty()
+ || !timeline.hold_windows().is_empty()
+ || !self.project.audio.mic_volume_db.is_finite()
+ || !self.project.audio.system_volume_db.is_finite()
+ {
+ return Err("Preparing audio layout is unsupported".into());
+ }
+ let mut offsets = vec![None; count];
+ for clip in &self.project.clips {
+ let slot = offsets
+ .get_mut(clip.index as usize)
+ .ok_or("Preparing audio clip index is invalid")?;
+ if slot.replace(clip.offsets).is_some() {
+ return Err("Preparing audio clip index is duplicated".into());
+ }
+ }
+ let mut duration = 0.0;
+ let mut start = 0;
+ let mut clips = Vec::with_capacity(count);
+ for (index, segment) in timeline.segments.iter().enumerate() {
+ if segment.recording_clip as usize != index
+ || segment.start != 0.0
+ || segment.timescale != 1.0
+ || segment.speed_audio_mode.is_some()
+ || !segment.end.is_finite()
+ || segment.end <= 0.0
+ {
+ return Err("Preparing audio requires the stopped 1x timeline".into());
+ }
+ duration += segment.end;
+ if !duration.is_finite() || duration * RATE > MAX_FRAME as f64 {
+ return Err("Preparing audio timeline exceeds sample limits".into());
+ }
+ let end = (duration * RATE).round() as usize;
+ if end <= start {
+ return Err("Preparing audio clip has no sample frames".into());
+ }
+ let offset = offsets[index].ok_or("Preparing audio clip offsets are absent")?;
+ let repair = self.repairs[index];
+ let mut samples = [0; 2];
+ for (track, (base, repair)) in [
+ (offset.mic, repair.mic_offset_secs),
+ (offset.system_audio, repair.system_audio_offset_secs),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let sum = base + repair;
+ let rounded = (sum * AudioData::SAMPLE_RATE as f32).round();
+ if !base.is_finite()
+ || !repair.is_finite()
+ || !rounded.is_finite()
+ || rounded.abs() > MAX_FRAME as f32
+ || (!self.required[index][track] && self.tracks[index][track].is_some())
+ {
+ return Err("Preparing audio track timing or presence is invalid".into());
+ }
+ samples[track] = rounded as isize;
+ }
+ clips.push(ClipLayout {
+ start,
+ end,
+ offsets: samples,
+ });
+ start = end;
+ }
+ Ok(clips)
+ }
+
+ fn check_terminal(&self) -> Result<(), String> {
+ for loader in self.tracks.iter().flatten().flatten() {
+ let progress = loader.progress();
+ if let Some(error) = progress.error {
+ return Err(error);
+ }
+ if progress.ready_frames > MAX_FRAME
+ || progress
+ .channels
+ .is_some_and(|channels| !matches!(channels, 1 | 2))
+ {
+ return Err("Preparing audio sample layout is invalid".into());
+ }
+ }
+ Ok(())
+ }
+
+ pub(crate) fn playable_prefix(&self) -> Result<f64, String> {
+ let clips = self.layout()?;
+ self.check_terminal()?;
+ for (index, clip) in clips.iter().enumerate() {
+ let frames = clip.end - clip.start;
+ let mut available = frames;
+ for (track, required) in self.required[index].iter().enumerate() {
+ if !required {
+ continue;
+ }
+ let Some(loader) = &self.tracks[index][track] else {
+ available = 0;
+ continue;
+ };
+ let progress = loader.progress();
+ let end = progress.ready_frames;
+ let covered = match loader.try_window(end.saturating_sub(1)..end)? {
+ AudioWindowRead::Ready(Some(window)) => {
+ if window.complete_sample_count().is_some() {
+ frames
+ } else if progress.channels.is_some() && window.available_range().end >= end
+ {
+ (end as i128 - clip.offsets[track] as i128).clamp(0, frames as i128)
+ as usize
+ } else {
+ 0
+ }
+ }
+ AudioWindowRead::Pending | AudioWindowRead::Ready(None) => 0,
+ };
+ available = available.min(covered);
+ }
+ if available < frames {
+ return Ok(((clip.start + available) as f64 / RATE).min(self.total_duration()));
+ }
+ }
+ self.check_terminal()?;
+ Ok(self.total_duration())
+ }
+}
+
+pub(crate) enum PreparingAudioRead {
+ Samples {
+ start_frame: usize,
+ frames: usize,
+ samples: Vec<f32>,
+ },
+ Pending {
+ loader: Option<ProgressiveAudio>,
+ range: Range<usize>,
+ },
+ Eof,
+}
+
+pub(crate) struct PreparingAudioMixer {
+ sources: PreparingAudioSources,
+ clips: Vec<ClipLayout>,
+ position: usize,
+}
+
+struct PreparedSpan {
+ clip: usize,
+ local: usize,
+ output: usize,
+ frames: usize,
+ windows: [Option<AudioSampleWindow>; 2],
+}
+
+impl PreparingAudioMixer {
+ pub(crate) fn new(sources: PreparingAudioSources, start_seconds: f64) -> Result<Self, String> {
+ let clips = sources.layout()?;
+ if !start_seconds.is_finite()
+ || start_seconds < 0.0
+ || start_seconds > sources.total_duration()
+ {
+ return Err("Preparing audio start is outside the timeline".into());
+ }
+ let position = (start_seconds * RATE).round() as usize;
+ Ok(Self {
+ sources,
+ clips,
+ position,
+ })
+ }
+
+ pub(crate) fn next(&mut self, requested_frames: usize) -> Result<PreparingAudioRead, String> {
+ if requested_frames == 0 || requested_frames > MAX_CHUNK_FRAMES {
+ return Err("Preparing audio chunk size is invalid".into());
+ }
+ self.sources.check_terminal()?;
+ let total = self
+ .clips
+ .last()
+ .ok_or("Preparing audio timeline is empty")?
+ .end;
+ if self.position >= total {
+ return Ok(PreparingAudioRead::Eof);
+ }
+ let end = self.position + requested_frames.min(total - self.position);
+ let mut spans = Vec::new();
+ let mut pending = None;
+ for (index, clip) in self.clips.iter().enumerate() {
+ let start = self.position.max(clip.start);
+ let until = end.min(clip.end);
+ if start >= until {
+ continue;
+ }
+ let local = start - clip.start;
+ let frames = until - start;
+ let mut windows = [None, None];
+ for (track, slot) in windows.iter_mut().enumerate() {
+ if !self.sources.required[index][track] {
+ continue;
+ }
+ let first = local as i128 + clip.offsets[track] as i128;
+ let range = first.max(0) as usize..(first + frames as i128).max(0) as usize;
+ let Some(loader) = &self.sources.tracks[index][track] else {
+ pending.get_or_insert(PreparingAudioRead::Pending {
+ loader: None,
+ range,
+ });
+ continue;
+ };
+ match loader.try_window(range.clone())? {
+ AudioWindowRead::Pending => {
+ pending.get_or_insert_with(|| PreparingAudioRead::Pending {
+ loader: Some(loader.clone()),
+ range,
+ });
+ }
+ AudioWindowRead::Ready(None) => {
+ pending.get_or_insert(PreparingAudioRead::Pending {
+ loader: None,
+ range,
+ });
+ }
+ AudioWindowRead::Ready(Some(window)) => {
+ let covered = window.available_range();
+ let required = match window.complete_sample_count() {
+ Some(total) => range.start.min(total)..range.end.min(total),
+ None => range,
+ };
+ if !matches!(window.channels(), 1 | 2)
+ || (required.start < required.end
+ && (required.start < covered.start || required.end > covered.end))
+ {
+ return Err("Preparing audio window does not cover its samples".into());
+ }
+ *slot = Some(window);
+ }
+ }
+ }
+ spans.push(PreparedSpan {
+ clip: index,
+ local,
+ output: start - self.position,
+ frames,
+ windows,
+ });
+ }
+ self.sources.check_terminal()?;
+ if let Some(pending) = pending {
+ return Ok(pending);
+ }
+ let frames = end - self.position;
+ let mut samples = vec![0.0; frames * 2];
+ for span in spans {
+ let tracks = span
+ .windows
+ .iter()
+ .enumerate()
+ .filter_map(|(track, window)| {
+ let data = window.as_ref()?;
+ let audio = &self.sources.project.audio;
+ let gain = if track == 0 {
+ audio.mic_volume_db
+ } else {
+ audio.system_volume_db
+ };
+ Some(AudioRendererTrack {
+ data,
+ gain: if audio.mute || gain < -30.0 {
+ f32::NEG_INFINITY
+ } else {
+ gain
+ },
+ stereo_mode: if track == 0 {
+ match audio.mic_stereo_mode {
+ cap_project::StereoMode::Stereo => cap_audio::StereoMode::Stereo,
+ cap_project::StereoMode::MonoL => cap_audio::StereoMode::MonoL,
+ cap_project::StereoMode::MonoR => cap_audio::StereoMode::MonoR,
+ }
+ } else {
+ cap_audio::StereoMode::Stereo
+ },
+ offset: self.clips[span.clip].offsets[track],
+ })
+ })
+ .collect::<Vec<_>>();
+ cap_audio::render_audio(
+ &tracks,
+ span.local,
+ span.frames,
+ span.output * 2,
+ &mut samples,
+ );
+ }
+ self.sources.check_terminal()?;
+ let start_frame = self.position;
+ self.position = end;
+ Ok(PreparingAudioRead::Samples {
+ start_frame,
+ frames,
+ samples,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_audio::{AudioChunk, DecodedAudio, ProgressiveAudioTestProducer};
+ use cap_project::{ClipConfiguration, TimelineConfiguration, TimelineSegment};
+
+ fn audio(frames: usize, channels: u16, seed: usize) -> Arc<AudioData> {
+ Arc::new(AudioData::from_raw_f32(
+ (0..frames * usize::from(channels))
+ .map(|index| ((index * 97 + seed) % 127) as f32 / 90.0 - 0.7)
+ .collect(),
+ channels,
+ ))
+ }
+
+ fn append(producer: &ProgressiveAudioTestProducer, audio: &AudioData, range: Range<usize>) {
+ let channels = usize::from(audio.channels());
+ producer
+ .append(AudioChunk {
+ source_start_sample: range.start as u64,
+ channels: audio.channels(),
+ samples: audio.samples()[range.start * channels..range.end * channels].to_vec(),
+ })
+ .unwrap();
+ }
+
+ fn sources(
+ durations: &[f64],
+ tracks: Vec<[Option<ProgressiveAudio>; 2]>,
+ ) -> PreparingAudioSources {
+ let count = durations.len();
+ PreparingAudioSources {
+ project: Arc::new(ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: durations
+ .iter()
+ .enumerate()
+ .map(|(index, &end)| TimelineSegment {
+ recording_clip: index as u32,
+ start: 0.0,
+ end,
+ timescale: 1.0,
+ ..Default::default()
+ })
+ .collect(),
+ transitions: Vec::new(),
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ style_segments: Vec::new(),
+ image_segments: Vec::new(),
+ camera3d_segments: Vec::new(),
+ }),
+ clips: (0..count)
+ .map(|index| ClipConfiguration {
+ index: index as u32,
+ ..Default::default()
+ })
+ .collect(),
+ ..Default::default()
+ }),
+ required: tracks
+ .iter()
+ .map(|tracks| tracks.each_ref().map(Option::is_some))
+ .collect(),
+ tracks,
+ repairs: vec![SegmentAudioTimingRepair::default(); count],
+ }
+ }
+
+ fn reference(
+ sources: &PreparingAudioSources,
+ audio: Vec<[Option<Arc<AudioData>>; 2]>,
+ start: f64,
+ frames: usize,
+ ) -> (usize, Vec<f32>) {
+ let segments = audio
+ .into_iter()
+ .zip(&sources.repairs)
+ .map(|([mic, system], &repair)| {
+ let decoded = |audio: Arc<AudioData>| Arc::new(DecodedAudio::from(audio));
+ crate::audio_segment_from_decoded(mic.map(decoded), system.map(decoded), repair)
+ })
+ .collect();
+ let mut renderer = crate::AudioRenderer::new(segments);
+ renderer.set_playhead(start, &sources.project);
+ renderer.render_frame_raw(frames, &sources.project).unwrap()
+ }
+
+ fn assert_samples(
+ actual: PreparingAudioRead,
+ expected_start: usize,
+ expected: (usize, Vec<f32>),
+ ) {
+ let PreparingAudioRead::Samples {
+ start_frame,
+ frames,
+ samples,
+ } = actual
+ else {
+ panic!("Expected real mixed audio samples");
+ };
+ assert_eq!(start_frame, expected_start);
+ assert_eq!(frames, expected.0);
+ assert_eq!(samples.len(), frames * 2);
+ assert_eq!(samples.len(), expected.1.len());
+ for (index, (actual, expected)) in samples.iter().zip(&expected.1).enumerate() {
+ assert_eq!(actual.to_bits(), expected.to_bits(), "sample {index}");
+ }
+ }
+
+ #[test]
+ fn pending_blocks_match_ordinary_offset_gain_stereo_and_mute_mixing() {
+ for channels in [1, 2] {
+ for mode in [
+ cap_project::StereoMode::Stereo,
+ cap_project::StereoMode::MonoL,
+ cap_project::StereoMode::MonoR,
+ ] {
+ for mute in [false, true] {
+ let mic = audio(65_536, channels, 17);
+ let system = audio(65_536, 2, 53);
+ let (mic_loader, mic_producer) = ProgressiveAudioTestProducer::new();
+ let (system_loader, system_producer) = ProgressiveAudioTestProducer::new();
+ append(&mic_producer, &mic, 0..32_768);
+ append(&system_producer, &system, 0..32_768);
+ let mut sources =
+ sources(&[1.25], vec![[Some(mic_loader), Some(system_loader)]]);
+ let project = Arc::make_mut(&mut sources.project);
+ project.audio.mute = mute;
+ project.audio.mic_stereo_mode = mode.clone();
+ project.audio.mic_volume_db = -3.0;
+ project.audio.system_volume_db = if mute { -31.0 } else { 1.0 };
+ project.clips[0].offsets.mic = 13.25 / RATE as f32;
+ project.clips[0].offsets.system_audio = -11.75 / RATE as f32;
+ sources.repairs[0] = SegmentAudioTimingRepair {
+ mic_offset_secs: -30.5 / RATE as f32,
+ system_audio_offset_secs: 28.25 / RATE as f32,
+ };
+ let expected = reference(&sources, vec![[Some(mic), Some(system)]], 0.0, 4096);
+ let mut mixer = PreparingAudioMixer::new(sources.clone(), 0.0).unwrap();
+ assert!(sources.playable_prefix().unwrap() < sources.total_duration());
+ assert_samples(mixer.next(4096).unwrap(), 0, expected);
+ assert!(!sources.tracks[0][0].as_ref().unwrap().progress().complete);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn cross_clip_pending_preflights_the_entire_chunk_without_advancing() {
+ let first = audio(1500, 1, 7);
+ let second = audio(40_000, 2, 71);
+ let (loader, producer) = ProgressiveAudioTestProducer::new();
+ let sources = sources(
+ &[1000.0 / RATE, 40_000.0 / RATE],
+ vec![
+ [Some(ProgressiveAudio::ready(Some(first.clone()))), None],
+ [Some(loader), None],
+ ],
+ );
+ let start = 950.0 / RATE;
+ let expected = reference(
+ &sources,
+ vec![[Some(first), None], [Some(second.clone()), None]],
+ start,
+ 1024,
+ );
+ let mut mixer = PreparingAudioMixer::new(sources.clone(), start).unwrap();
+ assert_eq!(sources.playable_prefix().unwrap(), 1000.0 / RATE);
+ for _ in 0..2 {
+ let PreparingAudioRead::Pending {
+ loader: Some(_),
+ range,
+ } = mixer.next(1024).unwrap()
+ else {
+ panic!("Expected the second clip's actual pending loader");
+ };
+ assert_eq!(range, 0..974);
+ }
+ append(&producer, &second, 0..32_768);
+ assert_eq!(sources.playable_prefix().unwrap(), 33_768.0 / RATE);
+ assert_samples(mixer.next(1024).unwrap(), 950, expected);
+ append(&producer, &second, 32_768..40_000);
+ producer.finish().unwrap();
+ assert_eq!(sources.playable_prefix().unwrap(), sources.total_duration());
+ }
+
+ #[test]
+ fn clip_boundaries_use_ordinary_accumulated_rounding() {
+ let first = audio(1100, 2, 5);
+ let second = audio(1100, 1, 11);
+ let sources = sources(
+ &[1000.49 / RATE, 800.49 / RATE],
+ vec![
+ [Some(ProgressiveAudio::ready(Some(first.clone()))), None],
+ [Some(ProgressiveAudio::ready(Some(second.clone()))), None],
+ ],
+ );
+ let expected = reference(
+ &sources,
+ vec![[Some(first), None], [Some(second), None]],
+ 0.0,
+ 2048,
+ );
+ assert_eq!(expected.0, 1801);
+ let mut mixer = PreparingAudioMixer::new(sources, 0.0).unwrap();
+ assert_samples(mixer.next(2048).unwrap(), 0, expected);
+ assert!(matches!(mixer.next(1024).unwrap(), PreparingAudioRead::Eof));
+ }
+
+ #[test]
+ fn only_true_eof_admits_the_silent_tail() {
+ let data = audio(64, 1, 3);
+ let (loader, producer) = ProgressiveAudioTestProducer::new();
+ append(&producer, &data, 0..64);
+ let sources = sources(&[1000.0 / RATE], vec![[Some(loader), None]]);
+ let expected = reference(&sources, vec![[Some(data), None]], 0.0, 1024);
+ let mut mixer = PreparingAudioMixer::new(sources.clone(), 0.0).unwrap();
+ assert_eq!(sources.playable_prefix().unwrap(), 64.0 / RATE);
+ assert!(matches!(
+ mixer.next(1024).unwrap(),
+ PreparingAudioRead::Pending { .. }
+ ));
+ producer.finish().unwrap();
+ assert_eq!(sources.playable_prefix().unwrap(), sources.total_duration());
+ assert_samples(mixer.next(1024).unwrap(), 0, expected);
+ assert!(matches!(mixer.next(1).unwrap(), PreparingAudioRead::Eof));
+ }
+
+ #[test]
+ fn absent_audio_is_silence_but_declared_missing_or_empty_audio_is_pending() {
+ let mut sources = sources(&[1.0], vec![[None, None]]);
+ assert_eq!(sources.playable_prefix().unwrap(), 1.0);
+ let mut mixer = PreparingAudioMixer::new(sources.clone(), 0.0).unwrap();
+ assert_samples(mixer.next(1024).unwrap(), 0, (1024, vec![0.0; 2048]));
+ sources.required[0][0] = true;
+ for empty in [None, Some(ProgressiveAudio::none())] {
+ sources.tracks[0][0] = empty;
+ assert_eq!(sources.playable_prefix().unwrap(), 0.0);
+ let mut mixer = PreparingAudioMixer::new(sources.clone(), 0.0).unwrap();
+ assert!(matches!(
+ mixer.next(1024).unwrap(),
+ PreparingAudioRead::Pending { loader: None, .. }
+ ));
+ }
+ }
+
+ #[test]
+ fn late_failure_is_terminal_even_when_muted_or_beyond_a_blocked_clip() {
+ let data = audio(32_768, 2, 41);
+ let (loader, producer) = ProgressiveAudioTestProducer::new();
+ append(&producer, &data, 0..32_768);
+ let mut sources = sources(&[1.0], vec![[Some(loader.clone()), None]]);
+ Arc::make_mut(&mut sources.project).audio.mute = true;
+ let mut mixer = PreparingAudioMixer::new(sources.clone(), 0.0).unwrap();
+ assert_samples(mixer.next(1024).unwrap(), 0, (1024, vec![0.0; 2048]));
+ producer.fail("corrupt tail".into());
+ assert_eq!(sources.playable_prefix().unwrap_err(), "corrupt tail");
+ assert_eq!(mixer.next(1024).err().unwrap(), "corrupt tail");
+ let mut later = self::sources(&[1.0, 1.0], vec![[None, None], [Some(loader), None]]);
+ later.required[0][0] = true;
+ assert_eq!(later.playable_prefix().unwrap_err(), "corrupt tail");
+ }
+
+ #[test]
+ fn validation_rejects_unbounded_or_changed_audio_layout() {
+ let original = sources(&[1.0], vec![[None, None]]);
+ original.validate().unwrap();
+ let cases: [fn(&mut PreparingAudioSources); 7] = [
+ |sources| sources.required.clear(),
+ |sources| sources.repairs[0].mic_offset_secs = f32::NAN,
+ |sources| Arc::make_mut(&mut sources.project).clips[0].index = 1,
+ |sources| Arc::make_mut(&mut sources.project).audio.mic_volume_db = f32::INFINITY,
+ |sources| {
+ Arc::make_mut(&mut sources.project)
+ .timeline
+ .as_mut()
+ .unwrap()
+ .segments[0]
+ .end = f64::INFINITY
+ },
+ |sources| {
+ Arc::make_mut(&mut sources.project)
+ .timeline
+ .as_mut()
+ .unwrap()
+ .segments[0]
+ .timescale = 2.0
+ },
+ |sources| {
+ Arc::make_mut(&mut sources.project)
+ .timeline
+ .as_mut()
+ .unwrap()
+ .segments[0]
+ .end = MAX_FRAME as f64
+ },
+ ];
+ for change in cases {
+ let mut invalid = original.clone();
+ change(&mut invalid);
+ assert!(invalid.validate().is_err());
+ }
+ assert!(PreparingAudioMixer::new(original.clone(), f64::NAN).is_err());
+ let mut mixer = PreparingAudioMixer::new(original, 0.0).unwrap();
+ assert!(mixer.next(0).is_err());
+ assert!(mixer.next(MAX_CHUNK_FRAMES + 1).is_err());
+ }
+}
diff --git a/crates/editor/src/preparing_audio/mod.rs b/crates/editor/src/preparing_audio/mod.rs
new file mode 100644
index 000000000..08b7715ae
--- /dev/null
+++ b/crates/editor/src/preparing_audio/mod.rs
@@ -0,0 +1,7 @@
+mod mixer;
+mod output;
+
+pub(crate) use mixer::PreparingAudioSources;
+pub(crate) use output::{
+ PreparingAudioBuffer, PreparingAudioOutputHandle, PreparingAudioOutputSnapshot,
+};
diff --git a/crates/editor/src/preparing_audio/output.rs b/crates/editor/src/preparing_audio/output.rs
new file mode 100644
index 000000000..93bb257dc
--- /dev/null
+++ b/crates/editor/src/preparing_audio/output.rs
@@ -0,0 +1,590 @@
+use super::mixer::{PreparingAudioMixer, PreparingAudioRead, PreparingAudioSources};
+use crate::audio::{AudioResampler, preparing_audio_output_policy};
+use cap_audio::{AudioData, FromSampleBytes};
+use cap_media_info::AudioInfo;
+use futures::{FutureExt, future::Shared};
+use ringbuf::{
+ HeapCons, HeapProd, HeapRb,
+ traits::{Consumer, Observer, Producer, Split},
+};
+use std::{
+ sync::{
+ Arc, Mutex, OnceLock,
+ atomic::{AtomicBool, AtomicU64, Ordering},
+ },
+ thread::{self, Thread},
+ time::{Duration, Instant},
+};
+use tokio::sync::Notify;
+use tokio_util::sync::CancellationToken;
+
+const MIX_FRAMES: usize = 1_024;
+const HISTORY_SPANS: usize = 1_024;
+const MAX_RING_BYTES: usize = 64 * 1024 * 1024;
+type ProducerJoin = Shared<futures::future::BoxFuture<'static, Result<(), String>>>;
+
+#[derive(Clone, Debug)]
+pub(crate) struct PreparingAudioOutputSnapshot {
+ pub(crate) playhead_seconds: f64,
+ pub(crate) buffering: bool,
+ pub(crate) ended: bool,
+ pub(crate) error: Option<String>,
+}
+
+#[derive(Clone, Copy, Default)]
+struct ConsumptionSpan {
+ wall_start: u64,
+ wall_end: u64,
+ media_start: u64,
+ media_end: u64,
+}
+
+#[derive(Default)]
+struct AtomicSpan {
+ version: AtomicU64,
+ wall_start: AtomicU64,
+ wall_end: AtomicU64,
+ media_start: AtomicU64,
+ media_end: AtomicU64,
+}
+
+impl AtomicSpan {
+ fn store(&self, span: ConsumptionSpan) {
+ self.version.fetch_add(1, Ordering::SeqCst);
+ self.wall_start.store(span.wall_start, Ordering::SeqCst);
+ self.wall_end.store(span.wall_end, Ordering::SeqCst);
+ self.media_start.store(span.media_start, Ordering::SeqCst);
+ self.media_end.store(span.media_end, Ordering::SeqCst);
+ self.version.fetch_add(1, Ordering::SeqCst);
+ }
+
+ fn load(&self) -> Option<ConsumptionSpan> {
+ let version = self.version.load(Ordering::SeqCst);
+ if version == 0 || version % 2 != 0 {
+ return None;
+ }
+ let span = ConsumptionSpan {
+ wall_start: self.wall_start.load(Ordering::SeqCst),
+ wall_end: self.wall_end.load(Ordering::SeqCst),
+ media_start: self.media_start.load(Ordering::SeqCst),
+ media_end: self.media_end.load(Ordering::SeqCst),
+ };
+ (version == self.version.load(Ordering::SeqCst)).then_some(span)
+ }
+}
+
+struct OutputControl {
+ cancelled: AtomicBool,
+ cancellation: CancellationToken,
+ removed: AtomicBool,
+ removal: Notify,
+ worker: OnceLock<Thread>,
+ error: Mutex<Option<String>>,
+ failed: AtomicBool,
+ invalid_clock: AtomicBool,
+ eof: AtomicBool,
+ produced: AtomicU64,
+ consumed: AtomicU64,
+ permitted: AtomicU64,
+ total_output_frames: u64,
+ buffering: AtomicBool,
+ retired: AtomicU64,
+ reported: AtomicU64,
+ spans: Box<[AtomicSpan]>,
+ epoch: Instant,
+ start_seconds: f64,
+ total_seconds: f64,
+ sample_rate: u32,
+}
+
+impl OutputControl {
+ fn cancel(&self) {
+ self.cancelled.store(true, Ordering::Release);
+ self.cancellation.cancel();
+ self.wake();
+ }
+
+ fn wake(&self) {
+ if let Some(worker) = self.worker.get() {
+ worker.unpark();
+ }
+ }
+
+ fn stopped(&self) -> bool {
+ self.cancelled.load(Ordering::Acquire) || self.invalid_clock.load(Ordering::Acquire)
+ }
+
+ fn fail(&self, error: String) {
+ self.error
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get_or_insert(error);
+ self.failed.store(true, Ordering::Release);
+ }
+
+ fn nanos(&self, now: Instant) -> u64 {
+ u64::try_from(now.saturating_duration_since(self.epoch).as_nanos()).unwrap_or(u64::MAX)
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct PreparingAudioOutputHandle {
+ control: Arc<OutputControl>,
+ joined: ProducerJoin,
+}
+
+impl PreparingAudioOutputHandle {
+ pub(crate) fn cancel(&self) {
+ self.control.cancel();
+ }
+
+ pub(crate) fn set_playable_until(&self, prefix: f64) -> Result<(), String> {
+ let control = &self.control;
+ if !prefix.is_finite() || prefix < 0.0 || prefix > control.total_seconds {
+ return Err("Preparing audio playable prefix is invalid".into());
+ }
+ let frames = if prefix == control.total_seconds {
+ control.total_output_frames
+ } else {
+ ((prefix - control.start_seconds).max(0.0) * f64::from(control.sample_rate)) as u64
+ };
+ control.permitted.fetch_max(frames, Ordering::Release);
+ Ok(())
+ }
+
+ pub(crate) fn status(&self, now: Instant) -> PreparingAudioOutputSnapshot {
+ let control = &self.control;
+ let now = control.nanos(now);
+ let consumed = control.consumed.load(Ordering::Acquire);
+ let mut audible = control.retired.load(Ordering::Acquire).min(consumed);
+ for slot in &control.spans {
+ if let Some(span) = slot.load()
+ && now >= span.wall_start
+ {
+ let elapsed = now.saturating_sub(span.wall_start);
+ let length = span.wall_end.saturating_sub(span.wall_start);
+ let count = span.media_end.saturating_sub(span.media_start);
+ let frames = if length == 0 || elapsed >= length {
+ count
+ } else {
+ ((u128::from(elapsed) * u128::from(control.sample_rate)) / 1_000_000_000)
+ .min(u128::from(count)) as u64
+ };
+ audible = audible.max(span.media_start.saturating_add(frames).min(consumed));
+ }
+ }
+ audible = control
+ .reported
+ .fetch_max(audible, Ordering::AcqRel)
+ .max(audible);
+ let error = if control.invalid_clock.load(Ordering::Acquire) {
+ Some("Preparing audio callback timing is invalid".into())
+ } else {
+ control
+ .error
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ };
+ let ended = error.is_none()
+ && !control.cancelled.load(Ordering::Acquire)
+ && control.eof.load(Ordering::Acquire)
+ && audible == control.produced.load(Ordering::Acquire);
+ PreparingAudioOutputSnapshot {
+ playhead_seconds: (control.start_seconds
+ + audible as f64 / f64::from(control.sample_rate))
+ .min(control.total_seconds),
+ buffering: !ended && control.buffering.load(Ordering::Acquire),
+ ended,
+ error,
+ }
+ }
+
+ pub(crate) async fn stop_and_wait(&self) -> Result<(), String> {
+ self.cancel();
+ let joined = self.joined.clone().await;
+ loop {
+ let removed = self.control.removal.notified();
+ tokio::pin!(removed);
+ removed.as_mut().enable();
+ if self.control.removed.load(Ordering::Acquire) {
+ break;
+ }
+ removed.await;
+ }
+ joined
+ }
+}
+
+fn spawn_producer(
+ control: Arc<OutputControl>,
+ runtime: tokio::runtime::Handle,
+ run: impl FnOnce() -> Result<(), String> + Send + 'static,
+) -> Result<ProducerJoin, String> {
+ let worker = thread::Builder::new()
+ .name("cap-preparing-audio".into())
+ .spawn(move || {
+ let _ = control.worker.set(thread::current());
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)) {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => control.fail(error),
+ Err(_) => control.fail("Preparing audio producer panicked".into()),
+ }
+ })
+ .map_err(|error| error.to_string())?;
+ let joined = runtime.spawn_blocking(move || {
+ worker
+ .join()
+ .map_err(|_| "Preparing audio producer join panicked".to_string())
+ });
+ Ok(
+ async move { joined.await.map_err(|error| error.to_string())? }
+ .boxed()
+ .shared(),
+ )
+}
+
+pub(crate) struct PreparingAudioBuffer<T: FromSampleBytes> {
+ samples: Option<HeapCons<T>>,
+ control: Arc<OutputControl>,
+ channels: usize,
+ next_slot: usize,
+ previous: Option<(usize, ConsumptionSpan)>,
+}
+
+impl<T: FromSampleBytes + cpal::FromSample<f32>> PreparingAudioBuffer<T> {
+ pub(crate) fn spawn(
+ sources: PreparingAudioSources,
+ output_info: AudioInfo,
+ start_seconds: f64,
+ runtime: tokio::runtime::Handle,
+ ) -> Result<(Self, PreparingAudioOutputHandle), String> {
+ sources.validate()?;
+ let total_seconds = sources.total_duration();
+ if output_info.sample_rate == 0
+ || !(1..=8).contains(&output_info.channels)
+ || cap_media_info::ffmpeg_sample_format_for(T::FORMAT)
+ != Some(output_info.sample_format)
+ {
+ return Err("Preparing audio output format is invalid".into());
+ }
+ let capacity = (output_info.sample_rate as usize)
+ .checked_mul(output_info.channels)
+ .and_then(|samples| samples.checked_mul(2))
+ .filter(|samples| {
+ samples
+ .checked_mul(T::BYTE_SIZE)
+ .is_some_and(|bytes| bytes <= MAX_RING_BYTES)
+ })
+ .ok_or_else(|| "Preparing audio output queue exceeds its bound".to_string())?;
+ let policy = preparing_audio_output_policy(total_seconds, output_info, start_seconds)?;
+ let ring = Arc::new(HeapRb::<T>::new(capacity));
+ let (producer, samples) = ring.clone().split();
+ let control = Arc::new(OutputControl {
+ cancelled: AtomicBool::new(false),
+ cancellation: CancellationToken::new(),
+ removed: AtomicBool::new(false),
+ removal: Notify::new(),
+ worker: OnceLock::new(),
+ error: Mutex::new(None),
+ failed: AtomicBool::new(false),
+ invalid_clock: AtomicBool::new(false),
+ eof: AtomicBool::new(false),
+ produced: AtomicU64::new(0),
+ consumed: AtomicU64::new(0),
+ permitted: AtomicU64::new(0),
+ total_output_frames: ((total_seconds * f64::from(output_info.sample_rate)) as u64)
+ .saturating_sub((start_seconds * f64::from(output_info.sample_rate)) as u64),
+ buffering: AtomicBool::new(true),
+ retired: AtomicU64::new(0),
+ reported: AtomicU64::new(0),
+ spans: (0..HISTORY_SPANS).map(|_| AtomicSpan::default()).collect(),
+ epoch: Instant::now(),
+ start_seconds,
+ total_seconds,
+ sample_rate: output_info.sample_rate,
+ });
+ let worker_control = control.clone();
+ let producer_runtime = runtime.clone();
+ let joined = spawn_producer(control.clone(), runtime, move || {
+ let mixer = PreparingAudioMixer::new(sources, policy.render_start_seconds)?;
+ let resampler =
+ AudioResampler::new(policy.render_info).map_err(|error| error.to_string())?;
+ let result = OutputProducer {
+ samples: producer,
+ control: worker_control,
+ runtime: producer_runtime,
+ mixer,
+ resampler,
+ input_frame: (policy.render_start_seconds * f64::from(AudioData::SAMPLE_RATE))
+ .round() as usize,
+ skip_frames: policy.skip_output_frames,
+ convert_from_f32: policy.convert_from_f32,
+ channels: output_info.channels,
+ scratch_bytes: (capacity / 2).saturating_mul(8).min(8 * 1024 * 1024),
+ emitted: 0,
+ limit: ((total_seconds * f64::from(output_info.sample_rate)) as u64)
+ .saturating_sub((start_seconds * f64::from(output_info.sample_rate)) as u64),
+ }
+ .run();
+ drop(ring);
+ result
+ })?;
+ Ok((
+ Self {
+ samples: Some(samples),
+ control: control.clone(),
+ channels: output_info.channels,
+ next_slot: 0,
+ previous: None,
+ },
+ PreparingAudioOutputHandle { control, joined },
+ ))
+ }
+
+ pub(crate) fn is_terminal(&self) -> bool {
+ self.control.stopped()
+ || self.control.failed.load(Ordering::Acquire)
+ || (self.control.eof.load(Ordering::Acquire)
+ && self
+ .samples
+ .as_ref()
+ .is_none_or(|samples| samples.occupied_len() == 0))
+ }
+
+ pub(crate) fn fill(&mut self, output: &mut [T], latency_secs: f64) -> usize {
+ self.fill_at(output, latency_secs, Instant::now())
+ }
+
+ fn fill_at(&mut self, output: &mut [T], latency_secs: f64, now: Instant) -> usize {
+ output.fill(T::EQUILIBRIUM);
+ if self.control.stopped() || self.control.failed.load(Ordering::Acquire) {
+ return 0;
+ }
+ let Some(samples) = self.samples.as_mut() else {
+ return 0;
+ };
+ let consumed = self.control.consumed.load(Ordering::Relaxed);
+ let permitted = self
+ .control
+ .permitted
+ .load(Ordering::Acquire)
+ .saturating_sub(consumed);
+ let frames = (samples.occupied_len() / self.channels)
+ .min(output.len() / self.channels)
+ .min(usize::try_from(permitted).unwrap_or(usize::MAX));
+ if frames == 0 {
+ self.control.buffering.store(
+ !self.control.eof.load(Ordering::Acquire) || samples.occupied_len() != 0,
+ Ordering::Release,
+ );
+ return 0;
+ }
+ let now = self.control.nanos(now);
+ let latency = Duration::try_from_secs_f64(latency_secs)
+ .ok()
+ .and_then(|value| u64::try_from(value.as_nanos()).ok());
+ let Some(wall_start) = latency.and_then(|latency| now.checked_add(latency)) else {
+ self.control.invalid_clock.store(true, Ordering::Release);
+ self.control.wake();
+ return 0;
+ };
+ let wall_start = wall_start.max(self.previous.map_or(0, |(_, span)| span.wall_end));
+ let duration =
+ (frames as u128 * 1_000_000_000).div_ceil(u128::from(self.control.sample_rate)) as u64;
+ let Some(wall_end) = wall_start.checked_add(duration) else {
+ self.control.invalid_clock.store(true, Ordering::Release);
+ self.control.wake();
+ return 0;
+ };
+ let start = self.control.consumed.load(Ordering::Relaxed);
+ let span = ConsumptionSpan {
+ wall_start,
+ wall_end,
+ media_start: start,
+ media_end: start + frames as u64,
+ };
+ let merge = self
+ .previous
+ .filter(|(_, previous)| previous.wall_end == wall_start);
+ let slot = merge.map_or(self.next_slot, |(index, _)| index);
+ if merge.is_none() {
+ if let Some(previous) = self.control.spans[slot].load() {
+ if previous.wall_end > now {
+ self.control.buffering.store(true, Ordering::Release);
+ return 0;
+ }
+ self.control
+ .retired
+ .fetch_max(previous.media_end, Ordering::Release);
+ }
+ self.next_slot = (self.next_slot + 1) % HISTORY_SPANS;
+ }
+ let copied = samples.pop_slice(&mut output[..frames * self.channels]);
+ assert_eq!(copied, frames * self.channels);
+ let span = merge.map_or(span, |(_, previous)| ConsumptionSpan {
+ wall_start: previous.wall_start,
+ media_start: previous.media_start,
+ ..span
+ });
+ self.control.spans[slot].store(span);
+ self.previous = Some((slot, span));
+ self.control
+ .consumed
+ .store(start + frames as u64, Ordering::Release);
+ self.control.buffering.store(
+ frames < output.len() / self.channels
+ && (!self.control.eof.load(Ordering::Acquire) || samples.occupied_len() != 0),
+ Ordering::Release,
+ );
+ self.control.wake();
+ frames
+ }
+}
+
+impl<T: FromSampleBytes> Drop for PreparingAudioBuffer<T> {
+ fn drop(&mut self) {
+ drop(self.samples.take());
+ self.control.cancel();
+ self.control.removed.store(true, Ordering::Release);
+ self.control.removal.notify_waiters();
+ }
+}
+
+struct OutputProducer<T: FromSampleBytes> {
+ samples: HeapProd<T>,
+ control: Arc<OutputControl>,
+ runtime: tokio::runtime::Handle,
+ mixer: PreparingAudioMixer,
+ resampler: AudioResampler,
+ input_frame: usize,
+ skip_frames: usize,
+ convert_from_f32: bool,
+ channels: usize,
+ scratch_bytes: usize,
+ emitted: u64,
+ limit: u64,
+}
+
+impl<T: FromSampleBytes + cpal::FromSample<f32>> OutputProducer<T> {
+ fn run(mut self) -> Result<(), String> {
+ loop {
+ if self.control.stopped() {
+ return Ok(());
+ }
+ match self.mixer.next(MIX_FRAMES)? {
+ PreparingAudioRead::Samples {
+ start_frame,
+ frames,
+ samples,
+ } => {
+ if start_frame != self.input_frame
+ || frames == 0
+ || frames > MIX_FRAMES
+ || samples.len() != frames * 2
+ {
+ return Err("Preparing audio mixer returned invalid frames".into());
+ }
+ self.input_frame = self
+ .input_frame
+ .checked_add(frames)
+ .ok_or("Preparing audio mixer frame index overflow")?;
+ let info =
+ AudioInfo::new_raw(AudioData::SAMPLE_FORMAT, AudioData::SAMPLE_RATE, 2);
+ let frame =
+ info.wrap_frame(unsafe { cap_audio::cast_f32_slice_to_bytes(&samples) });
+ let bytes = self.resampler.queue_and_process_frame(&frame);
+ if bytes.len() > self.scratch_bytes {
+ return Err("Preparing audio resampler exceeded its scratch bound".into());
+ }
+ let bytes = bytes.to_vec();
+ self.enqueue(&bytes)?;
+ }
+ PreparingAudioRead::Pending { loader, range } => {
+ let control = &self.control;
+ self.runtime.block_on(async {
+ match loader {
+ Some(loader) => tokio::select! {
+ biased;
+ _ = control.cancellation.cancelled() => Ok(()),
+ result = loader.window(range) => result.map(|_| ()),
+ },
+ None => {
+ control.cancellation.cancelled().await;
+ Ok(())
+ }
+ }
+ })?;
+ }
+ PreparingAudioRead::Eof => {
+ while let Some(bytes) = self.resampler.flush_frame() {
+ if bytes.len() > self.scratch_bytes {
+ return Err(
+ "Preparing audio resampler exceeded its scratch bound".into()
+ );
+ }
+ let bytes = bytes.to_vec();
+ if bytes.is_empty() {
+ break;
+ }
+ self.enqueue(&bytes)?;
+ if self.control.stopped() {
+ return Ok(());
+ }
+ }
+ self.control.eof.store(true, Ordering::Release);
+ return Ok(());
+ }
+ }
+ }
+ }
+
+ fn enqueue(&mut self, bytes: &[u8]) -> Result<(), String> {
+ let width = if self.convert_from_f32 {
+ f32::BYTE_SIZE
+ } else {
+ T::BYTE_SIZE
+ };
+ if bytes.len() % (width * self.channels) != 0 {
+ return Err("Preparing audio resampler returned partial frames".into());
+ }
+ let frames = bytes.len() / (width * self.channels);
+ let skip = self.skip_frames.min(frames);
+ self.skip_frames -= skip;
+ let frames = (frames - skip).min(self.limit.saturating_sub(self.emitted) as usize);
+ let mut converted = Vec::with_capacity(frames * self.channels);
+ for chunk in bytes[skip * width * self.channels..][..frames * width * self.channels]
+ .chunks_exact(width)
+ {
+ converted.push(if self.convert_from_f32 {
+ T::from_sample(f32::from_bytes(chunk))
+ } else {
+ T::from_bytes(chunk)
+ });
+ }
+ let mut offset = 0;
+ while offset < converted.len() {
+ if self.control.stopped() {
+ return Ok(());
+ }
+ let available = self.samples.vacant_len() / self.channels * self.channels;
+ if available == 0 {
+ thread::park_timeout(Duration::from_millis(20));
+ continue;
+ }
+ let end = converted.len().min(offset + available);
+ let written = self.samples.push_slice(&converted[offset..end]);
+ if written != end - offset {
+ return Err("Preparing audio queue publication failed".into());
+ }
+ offset = end;
+ self.emitted += (written / self.channels) as u64;
+ self.control.produced.store(self.emitted, Ordering::Release);
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+#[path = "output_tests.rs"]
+mod tests;
diff --git a/crates/editor/src/preparing_audio/output_tests.rs b/crates/editor/src/preparing_audio/output_tests.rs
new file mode 100644
index 000000000..c17d4391d
--- /dev/null
+++ b/crates/editor/src/preparing_audio/output_tests.rs
@@ -0,0 +1,624 @@
+use super::*;
+use crate::{AudioRenderer, SegmentAudioTimingRepair, audio_segment_from_decoded};
+use cap_audio::{AudioChunk, DecodedAudio, ProgressiveAudio, ProgressiveAudioTestProducer};
+use cap_project::{
+ ClipConfiguration, ProjectConfiguration, TimelineConfiguration, TimelineSegment,
+};
+
+fn sources(duration: f64, loader: Option<ProgressiveAudio>) -> PreparingAudioSources {
+ PreparingAudioSources {
+ project: Arc::new(ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: vec![TimelineSegment {
+ recording_clip: 0,
+ start: 0.0,
+ end: duration,
+ timescale: 1.0,
+ ..Default::default()
+ }],
+ transitions: vec![],
+ zoom_segments: vec![],
+ scene_segments: vec![],
+ mask_segments: vec![],
+ text_segments: vec![],
+ caption_segments: vec![],
+ keyboard_segments: vec![],
+ audio_segments: vec![],
+ style_segments: vec![],
+ image_segments: vec![],
+ camera3d_segments: vec![],
+ }),
+ clips: vec![ClipConfiguration::default()],
+ ..Default::default()
+ }),
+ required: vec![[loader.is_some(), false]],
+ tracks: vec![[loader, None]],
+ repairs: vec![SegmentAudioTimingRepair::default()],
+ }
+}
+
+fn audio(frames: usize) -> Arc<AudioData> {
+ Arc::new(AudioData::from_raw_f32(
+ (0..frames * 2)
+ .map(|index| ((index * 71 + 13) % 1009) as f32 / 1300.0 - 0.4)
+ .collect(),
+ 2,
+ ))
+}
+
+fn append(
+ producer: &ProgressiveAudioTestProducer,
+ audio: &AudioData,
+ range: std::ops::Range<usize>,
+) {
+ producer
+ .append(AudioChunk {
+ source_start_sample: range.start as u64,
+ channels: 2,
+ samples: audio.samples()[range.start * 2..range.end * 2].to_vec(),
+ })
+ .unwrap();
+}
+
+fn info<T: FromSampleBytes>(rate: u32, channels: u16) -> AudioInfo {
+ AudioInfo::new_raw(
+ cap_media_info::ffmpeg_sample_format_for(T::FORMAT).unwrap(),
+ rate,
+ channels,
+ )
+}
+
+fn spawn<T: FromSampleBytes + cpal::FromSample<f32>>(
+ sources: PreparingAudioSources,
+ info: AudioInfo,
+ start: f64,
+ runtime: tokio::runtime::Handle,
+) -> Result<(PreparingAudioBuffer<T>, PreparingAudioOutputHandle), String> {
+ let total = sources.total_duration();
+ let (buffer, handle) = PreparingAudioBuffer::spawn(sources, info, start, runtime)?;
+ handle.set_playable_until(total)?;
+ Ok((buffer, handle))
+}
+
+async fn until(mut predicate: impl FnMut() -> bool) {
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while !predicate() {
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ }
+ })
+ .await
+ .expect("Preparing output did not reach the expected state");
+}
+
+async fn drain<T: FromSampleBytes + cpal::FromSample<f32>>(
+ buffer: &mut PreparingAudioBuffer<T>,
+) -> Vec<T> {
+ let mut actual = Vec::new();
+ let mut scratch = vec![T::EQUILIBRIUM; 733 * buffer.channels];
+ tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ let frames = buffer.fill(&mut scratch, 0.0);
+ actual.extend_from_slice(&scratch[..frames * buffer.channels]);
+ if buffer.is_terminal() {
+ break;
+ }
+ if frames == 0 {
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ }
+ }
+ })
+ .await
+ .expect("Preparing output did not drain");
+ actual
+}
+
+fn ordinary_reference<T: FromSampleBytes + cpal::FromSample<f32>>(
+ sources: &PreparingAudioSources,
+ audio: Arc<AudioData>,
+ output_info: AudioInfo,
+ start: f64,
+) -> Vec<T> {
+ let policy =
+ preparing_audio_output_policy(sources.total_duration(), output_info, start).unwrap();
+ let decoded = Arc::new(DecodedAudio::from(audio));
+ let mut renderer = AudioRenderer::new(vec![audio_segment_from_decoded(
+ Some(decoded),
+ None,
+ sources.repairs[0],
+ )]);
+ renderer.set_playhead(policy.render_start_seconds, &sources.project);
+ let mut resampler = AudioResampler::new(policy.render_info).unwrap();
+ let mut bytes = Vec::new();
+ while let Some(frame) = renderer.render_frame(MIX_FRAMES, &sources.project) {
+ bytes.extend_from_slice(resampler.queue_and_process_frame(&frame));
+ }
+ while let Some(tail) = resampler.flush_frame() {
+ if tail.is_empty() {
+ break;
+ }
+ bytes.extend_from_slice(tail);
+ }
+ let width = if policy.convert_from_f32 {
+ f32::BYTE_SIZE
+ } else {
+ T::BYTE_SIZE
+ };
+ let limit = (sources.total_duration() * f64::from(output_info.sample_rate)) as usize
+ - (start * f64::from(output_info.sample_rate)) as usize;
+ bytes
+ .chunks_exact(width)
+ .skip(policy.skip_output_frames * output_info.channels)
+ .take(limit * output_info.channels)
+ .map(|sample| {
+ if policy.convert_from_f32 {
+ T::from_sample(f32::from_bytes(sample))
+ } else {
+ T::from_bytes(sample)
+ }
+ })
+ .collect()
+}
+
+trait ExactSample {
+ fn bits(self) -> u64;
+}
+
+impl ExactSample for f32 {
+ fn bits(self) -> u64 {
+ u64::from(self.to_bits())
+ }
+}
+
+impl ExactSample for f64 {
+ fn bits(self) -> u64 {
+ self.to_bits()
+ }
+}
+
+impl ExactSample for i16 {
+ fn bits(self) -> u64 {
+ u64::from(self as u16)
+ }
+}
+
+async fn assert_reference<T: FromSampleBytes + cpal::FromSample<f32> + PartialEq + ExactSample>(
+ duration: f64,
+ start: f64,
+ rate: u32,
+ channels: u16,
+) {
+ let raw = audio(120_000);
+ let mut sources = sources(duration, Some(ProgressiveAudio::ready(Some(raw.clone()))));
+ let output_info = info::<T>(rate, channels);
+ if duration > 1000.0 {
+ Arc::make_mut(&mut sources.project).clips[0].offsets.mic = -1799.0;
+ }
+ let policy = preparing_audio_output_policy(duration, output_info, start).unwrap();
+ let short = duration < 1000.0;
+ assert_eq!(policy.convert_from_f32, short);
+ assert_eq!(
+ policy.render_start_seconds,
+ if short { (start - 1.0).max(0.0) } else { start }
+ );
+ assert_eq!(
+ policy.render_info.sample_format,
+ if short {
+ AudioData::SAMPLE_FORMAT
+ } else {
+ output_info.sample_format
+ }
+ );
+ assert_eq!(
+ policy.skip_output_frames,
+ if short {
+ (start * f64::from(rate)) as usize - ((start - 1.0).max(0.0) * f64::from(rate)) as usize
+ } else {
+ 0
+ }
+ );
+ let expected = ordinary_reference::<T>(&sources, raw, output_info, start);
+ let (mut buffer, handle) = spawn::<T>(
+ sources,
+ output_info,
+ start,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ assert_eq!(
+ buffer.samples.as_ref().unwrap().capacity().get(),
+ rate as usize * usize::from(channels) * 2
+ );
+ let actual = drain(&mut buffer).await;
+ assert_eq!(
+ actual.len(),
+ ((duration * f64::from(rate)) as usize - (start * f64::from(rate)) as usize)
+ * usize::from(channels)
+ );
+ assert_eq!(actual.len(), expected.len());
+ assert!(actual.iter().any(|&sample| sample != T::EQUILIBRIUM));
+ assert_eq!(
+ actual
+ .iter()
+ .zip(&expected)
+ .position(|(&a, &b)| a.bits() != b.bits()),
+ None
+ );
+ assert!(
+ handle
+ .status(Instant::now() + Duration::from_secs(10))
+ .ended
+ );
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn output_matches_ordinary_resampling_preroll_formats_channels_and_tail() {
+ for (rate, channels) in [(48_000, 2), (44_100, 2), (44_100, 1)] {
+ assert_reference::<f32>(2.013_345, 1.123_45, rate, channels).await;
+ assert_reference::<i16>(2.013_345, 1.123_45, rate, channels).await;
+ }
+ assert_reference::<i16>(1_800.013_345, 1_799.923_45, 44_100, 2).await;
+ assert_reference::<f64>(1_800.013_345, 1_799.923_45, 48_000, 2).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn pending_preserves_resampler_and_only_valid_frames_advance() {
+ let raw = audio(70_000);
+ let (loader, producer) = ProgressiveAudioTestProducer::new();
+ let sources = sources(70_000.0 / 48_000.0, Some(loader.clone()));
+ let expected = ordinary_reference::<i16>(&sources, raw.clone(), info::<i16>(44_100, 2), 0.0);
+ let (mut buffer, handle) = spawn::<i16>(
+ sources,
+ info::<i16>(44_100, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ let mut scratch = [19; 1024];
+ assert_eq!(buffer.fill(&mut scratch, 0.0), 0);
+ assert_eq!(scratch, [0; 1024]);
+ assert!(!buffer.is_terminal());
+ append(&producer, &raw, 0..32_768);
+ until(|| buffer.control.produced.load(Ordering::Acquire) > 20_000).await;
+ let mut actual = Vec::new();
+ loop {
+ let frames = buffer.fill(&mut scratch, 0.0);
+ actual.extend_from_slice(&scratch[..frames * 2]);
+ if frames == 0 {
+ break;
+ }
+ }
+ assert!(!actual.is_empty());
+ assert!(!loader.progress().complete);
+ assert!(
+ handle
+ .status(Instant::now() + Duration::from_secs(2))
+ .buffering
+ );
+ let frozen = handle
+ .status(Instant::now() + Duration::from_secs(2))
+ .playhead_seconds;
+ assert_eq!(
+ handle
+ .status(Instant::now() + Duration::from_secs(3))
+ .playhead_seconds,
+ frozen
+ );
+ append(&producer, &raw, 32_768..65_536);
+ append(&producer, &raw, 65_536..70_000);
+ producer.finish().unwrap();
+ actual.extend(drain(&mut buffer).await);
+ assert_eq!(actual.len(), expected.len());
+ assert_eq!(
+ actual
+ .iter()
+ .zip(&expected)
+ .position(|(&a, &b)| a.bits() != b.bits()),
+ None
+ );
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn hardware_silence_gaps_and_delayed_spans_do_not_advance_media_clock() {
+ let (mut buffer, handle) = spawn::<f32>(
+ sources(1.0, None),
+ info::<f32>(48_000, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ until(|| buffer.control.eof.load(Ordering::Acquire)).await;
+ let epoch = buffer.control.epoch;
+ let mut scratch = vec![7.0; 4800 * 2];
+ assert_eq!(buffer.fill_at(&mut scratch, 0.1, epoch), 4800);
+ assert!(scratch.iter().all(|&value| value == 0.0));
+ assert_eq!(
+ handle
+ .status(epoch + Duration::from_millis(50))
+ .playhead_seconds,
+ 0.0
+ );
+ assert_eq!(
+ handle
+ .status(epoch + Duration::from_millis(150))
+ .playhead_seconds,
+ 0.05
+ );
+ assert_eq!(
+ handle
+ .status(epoch + Duration::from_millis(900))
+ .playhead_seconds,
+ 0.1
+ );
+ assert_eq!(
+ buffer.fill_at(&mut scratch, 0.2, epoch + Duration::from_secs(1)),
+ 4800
+ );
+ assert_eq!(
+ handle
+ .status(epoch + Duration::from_millis(1100))
+ .playhead_seconds,
+ 0.1
+ );
+ assert_eq!(
+ handle
+ .status(epoch + Duration::from_millis(1250))
+ .playhead_seconds,
+ 0.15
+ );
+ assert_eq!(
+ handle
+ .status(epoch + Duration::from_millis(1400))
+ .playhead_seconds,
+ 0.2
+ );
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn bounded_history_applies_backpressure_without_losing_future_clock_spans() {
+ let (mut buffer, handle) = spawn::<f32>(
+ sources(1.0, None),
+ info::<f32>(48_000, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ until(|| buffer.control.eof.load(Ordering::Acquire)).await;
+ let epoch = buffer.control.epoch;
+ let mut scratch = [1.0; 2];
+ for index in 0..HISTORY_SPANS {
+ assert_eq!(
+ buffer.fill_at(&mut scratch, 10.0 + index as f64 / 1000.0, epoch),
+ 1
+ );
+ }
+ assert_eq!(handle.status(epoch).playhead_seconds, 0.0);
+ let before = buffer.control.consumed.load(Ordering::Acquire);
+ assert_eq!(buffer.fill_at(&mut scratch, 12.0, epoch), 0);
+ assert_eq!(buffer.control.consumed.load(Ordering::Acquire), before);
+ assert_eq!(
+ buffer.fill_at(&mut scratch, 0.0, epoch + Duration::from_secs(15)),
+ 1
+ );
+ assert_eq!(
+ handle
+ .status(epoch + Duration::from_secs(15))
+ .playhead_seconds,
+ HISTORY_SPANS as f64 / 48_000.0
+ );
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cancellation_joins_pending_and_full_workers_after_actual_receiver_removal() {
+ for mode in 0..3 {
+ let (loader, producer) = ProgressiveAudioTestProducer::new();
+ let mut sources = sources(10.0, (mode == 0).then_some(loader));
+ if mode == 2 {
+ sources.required[0][0] = true;
+ }
+ let project = Arc::downgrade(&sources.project);
+ let (buffer, handle) = spawn::<f32>(
+ sources,
+ info::<f32>(48_000, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ if mode == 1 {
+ until(|| buffer.control.produced.load(Ordering::Acquire) >= 96_000).await;
+ }
+ let mut stop = Box::pin(handle.stop_and_wait());
+ assert!(
+ tokio::time::timeout(Duration::from_millis(20), &mut stop)
+ .await
+ .is_err()
+ );
+ assert!(!buffer.control.removed.load(Ordering::Acquire));
+ drop(stop);
+ drop(buffer);
+ tokio::time::timeout(Duration::from_secs(2), handle.stop_and_wait())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(project.upgrade().is_none());
+ drop(producer);
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn failed_loader_is_terminal_without_valid_ack_and_cleanup_still_succeeds() {
+ let (loader, producer) = ProgressiveAudioTestProducer::new();
+ let (mut buffer, handle) = spawn::<f32>(
+ sources(1.0, Some(loader)),
+ info::<f32>(48_000, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ producer.fail("injected audio failure".into());
+ until(|| buffer.is_terminal()).await;
+ let mut scratch = [1.0; 1024];
+ assert_eq!(buffer.fill(&mut scratch, 0.0), 0);
+ assert!(scratch.iter().all(|&sample| sample == 0.0));
+ assert_eq!(
+ handle.status(Instant::now()).error.as_deref(),
+ Some("injected audio failure")
+ );
+ assert!(!handle.status(Instant::now()).ended);
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn invalid_latency_fails_closed_and_zero_length_callbacks_preserve_samples() {
+ let (mut buffer, handle) = spawn::<f32>(
+ sources(0.1, None),
+ info::<f32>(48_000, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ until(|| buffer.control.eof.load(Ordering::Acquire)).await;
+ assert_eq!(buffer.fill(&mut [], 0.0), 0);
+ assert_eq!(buffer.control.consumed.load(Ordering::Acquire), 0);
+ assert_eq!(buffer.fill(&mut [1.0; 16], f64::NAN), 0);
+ assert!(buffer.is_terminal());
+ assert!(handle.status(Instant::now()).error.is_some());
+ assert_eq!(buffer.control.consumed.load(Ordering::Acquire), 0);
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn panic_boundary_retains_actual_native_join_and_sticky_error() {
+ let (loader, producer) = ProgressiveAudioTestProducer::new();
+ let (buffer, handle) = spawn::<f32>(
+ sources(1.0, Some(loader)),
+ info::<f32>(48_000, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ let owned = Arc::new(());
+ let weak = Arc::downgrade(&owned);
+ let joined = spawn_producer(
+ buffer.control.clone(),
+ tokio::runtime::Handle::current(),
+ move || {
+ let _owned = owned;
+ panic!("injected native producer panic");
+ },
+ )
+ .unwrap();
+ joined.await.unwrap();
+ assert!(weak.upgrade().is_none());
+ assert!(buffer.is_terminal());
+ assert_eq!(
+ handle.status(Instant::now()).error.as_deref(),
+ Some("Preparing audio producer panicked")
+ );
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+ drop(producer);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn installation_without_ambient_runtime_uses_retained_runtime_and_stops_at_end() {
+ let runtime = tokio::runtime::Handle::current();
+ let (mut buffer, handle) = std::thread::spawn(move || {
+ assert!(tokio::runtime::Handle::try_current().is_err());
+ spawn::<f32>(sources(0.125, None), info::<f32>(48_000, 2), 0.125, runtime).unwrap()
+ })
+ .join()
+ .unwrap();
+ until(|| buffer.is_terminal()).await;
+ assert_eq!(buffer.fill(&mut [1.0; 32], 0.0), 0);
+ assert_eq!(buffer.control.produced.load(Ordering::Acquire), 0);
+ assert!(handle.status(Instant::now()).ended);
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn confirmed_prefix_gates_queued_audio_and_growth_preserves_every_sample() {
+ let raw = audio(48_000);
+ let sources = sources(1.0, Some(ProgressiveAudio::ready(Some(raw.clone()))));
+ let expected = ordinary_reference::<f32>(&sources, raw, info::<f32>(48_000, 2), 0.0);
+ let (mut buffer, handle) = PreparingAudioBuffer::<f32>::spawn(
+ sources,
+ info::<f32>(48_000, 2),
+ 0.0,
+ tokio::runtime::Handle::current(),
+ )
+ .unwrap();
+ until(|| buffer.control.eof.load(Ordering::Acquire)).await;
+ let epoch = buffer.control.epoch;
+ let mut scratch = vec![1.0; 9600 * 2];
+ assert_eq!(buffer.fill_at(&mut scratch, 0.0, epoch), 0);
+ assert!(!buffer.is_terminal());
+ assert_eq!(buffer.control.consumed.load(Ordering::Acquire), 0);
+ handle.set_playable_until(0.1).unwrap();
+ assert_eq!(buffer.fill_at(&mut scratch, 0.0, epoch), 4800);
+ let mut actual = scratch[..4800 * 2].to_vec();
+ assert!(scratch[4800 * 2..].iter().all(|&sample| sample == 0.0));
+ assert_eq!(
+ buffer.fill_at(&mut scratch, 0.0, epoch + Duration::from_secs(1)),
+ 0
+ );
+ let paused = handle.status(epoch + Duration::from_secs(1));
+ assert_eq!(paused.playhead_seconds, 0.1);
+ assert!(paused.buffering);
+ assert!(!paused.ended);
+ assert!(handle.set_playable_until(f64::NAN).is_err());
+ assert!(handle.set_playable_until(1.1).is_err());
+ handle.set_playable_until(0.05).unwrap();
+ assert_eq!(buffer.control.permitted.load(Ordering::Acquire), 4800);
+ handle.set_playable_until(1.0).unwrap();
+ actual.extend(drain(&mut buffer).await);
+ assert_eq!(actual.len(), expected.len());
+ assert_eq!(
+ actual
+ .iter()
+ .zip(&expected)
+ .position(|(a, b)| a.to_bits() != b.to_bits()),
+ None
+ );
+ drop(buffer);
+ handle.stop_and_wait().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn invalid_output_bounds_fail_before_a_producer_is_started() {
+ for invalid in [
+ info::<f32>(0, 2),
+ info::<f32>(48_000, 9),
+ info::<f32>(u32::MAX, 8),
+ info::<i16>(48_000, 2),
+ ] {
+ assert!(
+ PreparingAudioBuffer::<f32>::spawn(
+ sources(1.0, None),
+ invalid,
+ 0.0,
+ tokio::runtime::Handle::current()
+ )
+ .is_err()
+ );
+ }
+ assert!(
+ PreparingAudioBuffer::<f32>::spawn(
+ sources(1.0, None),
+ info::<f32>(48_000, 2),
+ f64::NAN,
+ tokio::runtime::Handle::current()
+ )
+ .is_err()
+ );
+}
diff --git a/crates/editor/src/preparing_editor.rs b/crates/editor/src/preparing_editor.rs
new file mode 100644
index 000000000..88fe8430c
--- /dev/null
+++ b/crates/editor/src/preparing_editor.rs
@@ -0,0 +1,29 @@
+use serde::Serialize;
+use specta::Type;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub enum PreparingEditorPhase {
+ #[default]
+ Preparing,
+ Handoff,
+ Unavailable,
+ Ready,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PreparingEditorProgress {
+ pub total_duration: Option<f64>,
+ pub playable_until: f64,
+ pub preview_available: bool,
+ pub phase: PreparingEditorPhase,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PreparingPlaybackState {
+ pub playhead_seconds: f64,
+ pub playing: bool,
+ pub buffering: bool,
+}
diff --git a/crates/editor/src/preparing_handoff.rs b/crates/editor/src/preparing_handoff.rs
new file mode 100644
index 000000000..f4c96ec54
--- /dev/null
+++ b/crates/editor/src/preparing_handoff.rs
@@ -0,0 +1,478 @@
+use crate::preparing_audio::PreparingAudioOutputHandle;
+use crate::{CompletedAudioHandoff, PreparingPlaybackSnapshot, PreparingPlaybackStopHandle};
+use std::sync::{Arc, Mutex, Weak};
+use std::time::Instant;
+use tokio::sync::watch;
+
+pub(crate) fn presentation_frame(snapshot: &PreparingPlaybackSnapshot, fps: u32) -> u32 {
+ let requested = (snapshot.playback.playhead_seconds * f64::from(fps)).floor() as u32;
+ snapshot
+ .progress
+ .total_duration
+ .map_or(requested, |duration| {
+ requested.min(((duration * f64::from(fps)).ceil() as u32).saturating_sub(1))
+ })
+}
+
+pub(crate) type CompletedTrackIdentity = Vec<[Option<Weak<cap_audio::DecodedAudio>>; 2]>;
+
+pub(crate) fn completed_track_identity(
+ tracks: &[crate::completed_audio::CompletedAudioSegment],
+) -> CompletedTrackIdentity {
+ tracks
+ .iter()
+ .map(|track| {
+ [
+ track.mic.as_ref().map(Arc::downgrade),
+ track.system_audio.as_ref().map(Arc::downgrade),
+ ]
+ })
+ .collect()
+}
+
+fn same_completed_tracks(left: &CompletedTrackIdentity, right: &CompletedTrackIdentity) -> bool {
+ left.len() == right.len()
+ && left.iter().zip(right).all(|(left, right)| {
+ left.iter()
+ .zip(right)
+ .all(|(left, right)| match (left, right) {
+ (None, None) => true,
+ (Some(left), Some(right)) => Weak::ptr_eq(left, right),
+ _ => false,
+ })
+ })
+}
+
+#[derive(Default)]
+struct HandoffDecision {
+ revision: u64,
+ owner: u64,
+ pending_commands: usize,
+ stopped: bool,
+}
+
+pub(crate) struct HandoffState {
+ snapshot: Mutex<Option<(PreparingPlaybackSnapshot, Instant, f64)>>,
+ audio: Mutex<Option<PreparingAudioOutputHandle>>,
+ identity: Mutex<Option<(CompletedTrackIdentity, Weak<crate::AudioOutput>)>>,
+ pub(crate) completed_audio: Arc<Mutex<Option<CompletedAudioHandoff>>>,
+ ready: watch::Sender<Result<bool, String>>,
+ changed: watch::Sender<u64>,
+ decision: Mutex<HandoffDecision>,
+}
+
+impl HandoffState {
+ pub(crate) fn new() -> Arc<Self> {
+ Arc::new(Self {
+ snapshot: Mutex::new(None),
+ audio: Mutex::new(None),
+ identity: Mutex::new(None),
+ completed_audio: Arc::default(),
+ ready: watch::channel(Ok(false)).0,
+ changed: watch::channel(0).0,
+ decision: Mutex::default(),
+ })
+ }
+
+ pub(crate) fn publish(&self, snapshot: PreparingPlaybackSnapshot, position: f64) {
+ let _decision = self
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ *self
+ .snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) =
+ Some((snapshot, Instant::now(), position));
+ }
+
+ pub(crate) fn set_audio(&self, audio: Option<PreparingAudioOutputHandle>) {
+ *self
+ .audio
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = audio;
+ }
+
+ pub(crate) fn ready(&self) -> bool {
+ matches!(*self.ready.borrow(), Ok(true))
+ }
+
+ pub(crate) fn set_completed_identity(
+ &self,
+ tracks: &[crate::completed_audio::CompletedAudioSegment],
+ output: &Arc<crate::AudioOutput>,
+ ) {
+ *self
+ .identity
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) =
+ Some((completed_track_identity(tracks), Arc::downgrade(output)));
+ }
+
+ pub(crate) fn complete(&self, audio: CompletedAudioHandoff) {
+ let decision = self
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !self.ready() && !decision.stopped {
+ *self
+ .completed_audio
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(audio);
+ let _ = self.ready.send_replace(Ok(true));
+ }
+ }
+
+ pub(crate) fn cancel_adoption(&self) {
+ self.decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .stopped = true;
+ self.changed
+ .send_modify(|revision| *revision = revision.wrapping_add(1));
+ }
+
+ pub(crate) fn finish(&self, error: Option<String>) {
+ self.decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .stopped = true;
+ if let Some(error) = error {
+ let _ = self.ready.send_replace(Err(error));
+ } else if !self.ready() {
+ let _ = self
+ .ready
+ .send_replace(Err("Preparing playback ended before audio completed".into()));
+ }
+ self.changed
+ .send_modify(|revision| *revision = revision.wrapping_add(1));
+ }
+
+ pub(crate) fn begin_command(self: &Arc<Self>) -> Result<PreparingPlaybackIntent, String> {
+ let mut decision = self
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if decision.owner != 0 {
+ return Err("Preparing playback has been adopted".into());
+ }
+ if decision.stopped {
+ return Err("Preparing playback has ended".into());
+ }
+ decision.revision = decision.revision.wrapping_add(1).max(1);
+ decision.pending_commands += 1;
+ Ok(PreparingPlaybackIntent(self.clone()))
+ }
+
+ pub(crate) fn committed(&self) -> bool {
+ self.decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .owner
+ != 0
+ }
+
+ fn snapshot(&self, now: Instant) -> Option<PreparingPlaybackSnapshot> {
+ let (mut snapshot, sampled, position) = self
+ .snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()?;
+ if let Some(audio) = self
+ .audio
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ {
+ let status = audio.status(now);
+ snapshot.playback.playhead_seconds = status.playhead_seconds;
+ snapshot.playback.buffering = status.buffering;
+ if status.ended || status.error.is_some() {
+ snapshot.playback.playing = false;
+ }
+ if status.error.is_some() {
+ snapshot.progress.phase = crate::PreparingEditorPhase::Unavailable;
+ }
+ } else if snapshot.playback.playing && !snapshot.playback.buffering {
+ snapshot.playback.playhead_seconds = (position
+ + now.saturating_duration_since(sampled).as_secs_f64())
+ .min(snapshot.progress.playable_until);
+ }
+ Some(snapshot)
+ }
+}
+
+pub struct PreparingPlaybackIntent(Arc<HandoffState>);
+
+impl Drop for PreparingPlaybackIntent {
+ fn drop(&mut self) {
+ let mut decision = self
+ .0
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ decision.pending_commands = decision.pending_commands.saturating_sub(1);
+ self.0
+ .changed
+ .send_modify(|revision| *revision = revision.wrapping_add(1));
+ }
+}
+
+struct HandoffOwner {
+ state: Arc<HandoffState>,
+ stop: PreparingPlaybackStopHandle,
+}
+
+impl Drop for HandoffOwner {
+ fn drop(&mut self) {
+ self.stop.cancel();
+ }
+}
+
+#[derive(Clone)]
+pub struct PreparingPlaybackHandoff(Arc<HandoffOwner>);
+
+impl PreparingPlaybackHandoff {
+ pub(crate) fn new(state: Arc<HandoffState>, stop: PreparingPlaybackStopHandle) -> Self {
+ let stop = stop.with_handoff(&state);
+ Self(Arc::new(HandoffOwner { state, stop }))
+ }
+
+ pub async fn take_completed_audio(&self) -> Result<CompletedAudioHandoff, String> {
+ let mut ready = self.0.state.ready.subscribe();
+ let mut changed = self.0.state.changed.subscribe();
+ loop {
+ let status = ready.borrow_and_update().clone()?;
+ if self
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .stopped
+ {
+ return Err("Preparing playback has ended".into());
+ }
+ if status {
+ return self
+ .0
+ .state
+ .completed_audio
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take()
+ .ok_or_else(|| "Preparing audio was already transferred".into());
+ }
+ tokio::select! {
+ result = ready.changed() => result.map_err(|_| "Preparing audio owner ended".to_string())?,
+ result = changed.changed() => result.map_err(|_| "Preparing audio owner ended".to_string())?,
+ }
+ }
+ }
+
+ pub fn reserve_command(&self) -> Result<PreparingPlaybackIntent, String> {
+ self.0.state.begin_command()
+ }
+
+ pub fn snapshot(&self) -> Option<PreparingPlaybackSnapshot> {
+ self.0.state.snapshot(Instant::now())
+ }
+
+ pub fn prepare_adoption(&self) -> Result<PreparingPlaybackAdoption, String> {
+ let mut decision = self
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !self.0.state.ready()
+ || decision.stopped
+ || decision.owner != 0
+ || decision.pending_commands != 0
+ {
+ return Err("Preparing playback cannot be adopted".into());
+ }
+ decision.revision = decision.revision.wrapping_add(1).max(1);
+ let revision = decision.revision;
+ Ok(PreparingPlaybackAdoption {
+ handoff: self.clone(),
+ revision,
+ })
+ }
+
+ pub(crate) fn matches_completed_audio(
+ &self,
+ identity: &CompletedTrackIdentity,
+ output: &Arc<crate::AudioOutput>,
+ ) -> bool {
+ self.0
+ .state
+ .identity
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .is_some_and(|(expected, expected_output)| {
+ same_completed_tracks(identity, expected)
+ && Weak::ptr_eq(expected_output, &Arc::downgrade(output))
+ })
+ }
+
+ pub(crate) async fn prepare_when_settled(&self) -> Result<PreparingPlaybackAdoption, String> {
+ let mut changed = self.0.state.changed.subscribe();
+ loop {
+ {
+ let decision = self
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if decision.stopped || decision.owner != 0 {
+ return Err("Preparing playback cannot retry adoption".into());
+ }
+ if decision.pending_commands == 0 {
+ break;
+ }
+ }
+ changed
+ .changed()
+ .await
+ .map_err(|_| "Preparing playback ended".to_string())?;
+ }
+ self.prepare_adoption()
+ }
+
+ pub fn committed(&self) -> bool {
+ self.0.state.committed()
+ }
+
+ pub async fn wait_committed(&self) -> bool {
+ let mut changed = self.0.state.changed.subscribe();
+ while !self.committed()
+ && !self
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .stopped
+ {
+ if changed.changed().await.is_err() {
+ break;
+ }
+ }
+ self.committed()
+ }
+
+ pub fn cancel(&self) {
+ self.0.stop.cancel();
+ }
+
+ pub async fn stop_and_wait(&self) -> crate::PreparingPlaybackExit {
+ self.0.stop.stop_and_wait().await
+ }
+}
+
+#[derive(Clone)]
+pub struct PreparingPlaybackAdoption {
+ handoff: PreparingPlaybackHandoff,
+ revision: u64,
+}
+
+impl PreparingPlaybackAdoption {
+ pub async fn retry(&self) -> Result<Self, String> {
+ self.handoff.prepare_when_settled().await
+ }
+
+ pub fn snapshot(&self) -> Option<PreparingPlaybackSnapshot> {
+ let decision = self
+ .handoff
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if decision.stopped || decision.revision != self.revision {
+ return None;
+ }
+ self.handoff.snapshot()
+ }
+
+ pub fn frame_number(&self, fps: u32) -> Option<u32> {
+ self.snapshot()
+ .map(|snapshot| presentation_frame(&snapshot, fps))
+ }
+
+ pub fn invalidated(&self) -> bool {
+ let decision = self
+ .handoff
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ decision.stopped || decision.revision != self.revision
+ }
+
+ pub fn try_commit(&self, frame: u32, fps: u32) -> bool {
+ let mut decision = self
+ .handoff
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if fps == 0
+ || decision.stopped
+ || decision.revision != self.revision
+ || decision.pending_commands != 0
+ {
+ return false;
+ }
+ let Some(snapshot) = self.handoff.snapshot() else {
+ return false;
+ };
+ if snapshot.progress.phase == crate::PreparingEditorPhase::Unavailable {
+ return false;
+ }
+ let current = presentation_frame(&snapshot, fps);
+ if frame < current.saturating_sub(2) || frame > current.saturating_add(1) {
+ return false;
+ }
+ if decision.owner != 0 {
+ return decision.owner == self.revision;
+ }
+ decision.owner = self.revision;
+ self.handoff.0.state.changed.send_replace(self.revision);
+ true
+ }
+
+ pub fn is_owner(&self) -> bool {
+ self.handoff
+ .0
+ .state
+ .decision
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .owner
+ == self.revision
+ }
+
+ pub fn cancel(&self) {
+ if self.is_owner() {
+ self.handoff.cancel();
+ }
+ }
+
+ pub async fn stop_and_wait(&self) -> Option<crate::PreparingPlaybackExit> {
+ if self.is_owner() {
+ Some(self.handoff.stop_and_wait().await)
+ } else {
+ None
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "preparing_handoff_tests.rs"]
+mod tests;
diff --git a/crates/editor/src/preparing_handoff_tests.rs b/crates/editor/src/preparing_handoff_tests.rs
new file mode 100644
index 000000000..acd545838
--- /dev/null
+++ b/crates/editor/src/preparing_handoff_tests.rs
@@ -0,0 +1,261 @@
+use super::*;
+use crate::{PreparingEditorPhase, PreparingEditorProgress, PreparingPlaybackState};
+
+fn snapshot(position: f64, playing: bool) -> PreparingPlaybackSnapshot {
+ PreparingPlaybackSnapshot {
+ sequence: 1,
+ progress: PreparingEditorProgress {
+ total_duration: Some(10.0),
+ playable_until: 10.0,
+ preview_available: true,
+ phase: PreparingEditorPhase::Preparing,
+ },
+ playback: PreparingPlaybackState {
+ playhead_seconds: position,
+ playing,
+ buffering: false,
+ },
+ }
+}
+
+fn completed() -> CompletedAudioHandoff {
+ let meta = crate::completed_audio::tests::metadata();
+ let count = match meta.studio_meta().unwrap() {
+ cap_project::StudioRecordingMeta::MultipleSegments { inner } => inner.segments.len(),
+ _ => panic!("Expected test segments"),
+ };
+ CompletedAudioHandoff::from_completed_tracks(&meta, &meta, vec![Default::default(); count])
+ .unwrap()
+}
+
+fn handoff() -> (
+ PreparingPlaybackHandoff,
+ tokio_util::sync::CancellationToken,
+) {
+ let snapshot = snapshot(3.0, false);
+ let state = HandoffState::new();
+ state.publish(snapshot.clone(), 3.0);
+ state.complete(completed());
+ let (stop, cancelled) = PreparingPlaybackStopHandle::test_pending(snapshot);
+ (PreparingPlaybackHandoff::new(state, stop), cancelled)
+}
+
+#[tokio::test]
+async fn completed_cache_is_taken_once_without_stopping_owner() {
+ let (handoff, cancelled) = handoff();
+ assert!(handoff.take_completed_audio().await.is_ok());
+ assert!(handoff.take_completed_audio().await.is_err());
+ assert!(!cancelled.is_cancelled());
+ drop(handoff);
+ assert!(cancelled.is_cancelled());
+}
+
+#[test]
+fn discarded_candidate_does_not_cancel_preparing_playback() {
+ let (handoff, cancelled) = handoff();
+ let candidate = handoff.prepare_adoption().unwrap();
+ candidate.cancel();
+ drop(candidate);
+ assert!(!cancelled.is_cancelled());
+ assert!(!handoff.committed());
+}
+
+#[test]
+fn newer_candidate_rejects_old_commit_and_old_cleanup() {
+ let (handoff, cancelled) = handoff();
+ let old = handoff.prepare_adoption().unwrap();
+ let current = handoff.prepare_adoption().unwrap();
+ assert!(!old.try_commit(90, 30));
+ assert!(current.try_commit(90, 30));
+ old.cancel();
+ assert!(!cancelled.is_cancelled());
+ current.cancel();
+ assert!(cancelled.is_cancelled());
+}
+
+#[test]
+fn command_must_settle_before_current_frame_can_commit() {
+ let (handoff, _) = handoff();
+ let candidate = handoff.prepare_adoption().unwrap();
+ let command = handoff.0.state.begin_command().unwrap();
+ assert!(!candidate.try_commit(90, 30));
+ handoff.0.state.publish(snapshot(5.0, false), 5.0);
+ drop(command);
+ assert!(!candidate.try_commit(90, 30));
+ assert!(!candidate.try_commit(150, 30));
+ let renewed = handoff.prepare_adoption().unwrap();
+ assert!(renewed.try_commit(150, 30));
+ assert!(handoff.0.state.begin_command().is_err());
+}
+
+#[test]
+fn moving_clock_rejects_old_or_future_frames() {
+ let (handoff, _) = handoff();
+ let candidate = handoff.prepare_adoption().unwrap();
+ handoff.0.state.publish(snapshot(5.0, true), 5.0);
+ assert!(!candidate.try_commit(90, 30));
+ assert!(!candidate.try_commit(180, 30));
+ assert!(!candidate.try_commit(150, 0));
+ assert!(candidate.try_commit(150, 30));
+}
+
+#[tokio::test]
+async fn terminal_failure_wakes_audio_waiter_and_rejects_adoption() {
+ let state = HandoffState::new();
+ let (stop, _) = PreparingPlaybackStopHandle::test_pending(snapshot(0.0, false));
+ let handoff = PreparingPlaybackHandoff::new(state.clone(), stop);
+ state.finish(Some("decode failed".into()));
+ assert_eq!(
+ handoff.take_completed_audio().await.err().as_deref(),
+ Some("decode failed")
+ );
+ assert!(handoff.prepare_adoption().is_err());
+}
+
+#[tokio::test]
+async fn adopted_stop_awaits_actual_retained_completion() {
+ let (handoff, cancelled) = handoff();
+ let candidate = handoff.prepare_adoption().unwrap();
+ assert!(candidate.try_commit(90, 30));
+ assert!(!cancelled.is_cancelled());
+ let exit = candidate.stop_and_wait().await.unwrap();
+ assert!(cancelled.is_cancelled());
+ assert!(!exit.cleanup_failed);
+}
+
+#[test]
+fn completed_same_frame_pause_or_seek_invalidates_pending_presentation() {
+ let (handoff, cancelled) = handoff();
+ for _ in 0..2 {
+ let candidate = handoff.prepare_adoption().unwrap();
+ let command = handoff.0.state.begin_command().unwrap();
+ handoff.0.state.publish(snapshot(3.0, false), 3.0);
+ drop(command);
+ assert!(candidate.invalidated());
+ assert!(!candidate.try_commit(90, 30));
+ assert!(!cancelled.is_cancelled());
+ }
+}
+
+#[test]
+fn cancellation_invalidates_a_previously_ready_candidate() {
+ let (handoff, _) = handoff();
+ let candidate = handoff.prepare_adoption().unwrap();
+ handoff.cancel();
+ assert!(!candidate.try_commit(90, 30));
+}
+
+#[test]
+fn end_position_targets_last_video_frame() {
+ assert_eq!(presentation_frame(&snapshot(10.0, false), 30), 299);
+}
+
+#[tokio::test]
+async fn queued_intent_blocks_recreation_until_actual_command_owner_drops() {
+ let (handoff, _) = handoff();
+ let candidate = handoff.prepare_adoption().unwrap();
+ let intent = handoff.reserve_command().unwrap();
+ let retry = tokio::spawn(async move { candidate.retry().await });
+ tokio::task::yield_now().await;
+ assert!(!retry.is_finished());
+ drop(intent);
+ let renewed = retry.await.unwrap().unwrap();
+ assert!(renewed.try_commit(90, 30));
+}
+
+#[test]
+fn only_the_matching_completed_pcm_and_output_can_be_adopted() {
+ let (handoff, _) = handoff();
+ let output = Arc::new(crate::AudioOutput::new_headless(Box::new(|_, _| {})));
+ let other_output = Arc::new(crate::AudioOutput::new_headless(Box::new(|_, _| {})));
+ let tracks = vec![crate::completed_audio::CompletedAudioSegment {
+ mic: Some(crate::completed_audio::tests::audio()),
+ system_audio: None,
+ }];
+ handoff.0.state.set_completed_identity(&tracks, &output);
+ let identity = completed_track_identity(&tracks);
+ assert!(handoff.matches_completed_audio(&identity, &output));
+ assert!(!handoff.matches_completed_audio(&identity, &other_output));
+ let different_pcm = vec![crate::completed_audio::CompletedAudioSegment {
+ mic: Some(crate::completed_audio::tests::audio()),
+ system_audio: None,
+ }];
+ assert!(!handoff.matches_completed_audio(&completed_track_identity(&different_pcm), &output));
+ assert!(!handoff.matches_completed_audio(&Vec::new(), &output));
+}
+
+#[test]
+fn direct_stop_rejects_commit_before_runner_cleanup_finishes() {
+ let (handoff, cancelled) = handoff();
+ let candidate = handoff.prepare_adoption().unwrap();
+ handoff.0.stop.cancel();
+ assert!(cancelled.is_cancelled());
+ assert!(candidate.invalidated());
+ assert!(!candidate.try_commit(90, 30));
+ assert!(handoff.prepare_adoption().is_err());
+ assert!(handoff.reserve_command().is_err());
+}
+
+#[tokio::test]
+async fn direct_stop_wakes_a_pending_audio_handoff_without_waiting_for_cleanup() {
+ let state = HandoffState::new();
+ let (stop, _) = PreparingPlaybackStopHandle::test_pending(snapshot(0.0, false));
+ let handoff = PreparingPlaybackHandoff::new(state, stop);
+ let waiter = tokio::spawn({
+ let handoff = handoff.clone();
+ async move { handoff.take_completed_audio().await }
+ });
+ tokio::task::yield_now().await;
+ assert!(!waiter.is_finished());
+ handoff.0.stop.cancel();
+ assert_eq!(
+ waiter.await.unwrap().err().as_deref(),
+ Some("Preparing playback has ended")
+ );
+}
+
+#[tokio::test]
+async fn retained_task_join_error_wakes_audio_and_adoption_waiters() {
+ let state = HandoffState::new();
+ let initial = snapshot(0.0, false);
+ let (stop, _) = PreparingPlaybackStopHandle::test_pending(initial.clone());
+ let handoff = PreparingPlaybackHandoff::new(state.clone(), stop);
+ let intent = handoff.reserve_command().unwrap();
+ let audio = tokio::spawn({
+ let handoff = handoff.clone();
+ async move { handoff.take_completed_audio().await }
+ });
+ let adoption = tokio::spawn({
+ let handoff = handoff.clone();
+ async move { handoff.prepare_when_settled().await }
+ });
+ let committed = tokio::spawn({
+ let handoff = handoff.clone();
+ async move { handoff.wait_committed().await }
+ });
+ let (release, released) = tokio::sync::oneshot::channel::<()>();
+ let task = tokio::spawn(async move {
+ released.await.unwrap();
+ panic!("injected cleanup panic")
+ });
+ let retained = tokio::spawn(crate::preparing_playback::join_preparing_task(
+ task, initial, state,
+ ));
+ tokio::task::yield_now().await;
+ assert!(!audio.is_finished());
+ assert!(!adoption.is_finished());
+ release.send(()).unwrap();
+ let exit = retained.await.unwrap();
+ assert!(exit.cleanup_failed);
+ assert!(
+ audio
+ .await
+ .unwrap()
+ .err()
+ .unwrap()
+ .contains("injected cleanup panic")
+ );
+ assert!(adoption.await.unwrap().is_err());
+ assert!(!committed.await.unwrap());
+ drop(intent);
+}
diff --git a/crates/editor/src/preparing_playback.rs b/crates/editor/src/preparing_playback.rs
new file mode 100644
index 000000000..5758bbc8e
--- /dev/null
+++ b/crates/editor/src/preparing_playback.rs
@@ -0,0 +1,1498 @@
+use std::{
+ sync::{Arc, Mutex},
+ time::{Duration, Instant},
+};
+
+use cap_audio::{ManagedAudioInput, ManagedAudioStopHandle, ManagedProgressiveAudio};
+use cap_project::{StudioRecordingMeta, XY};
+use futures::{
+ FutureExt,
+ future::{BoxFuture, Shared},
+};
+use tokio::sync::{mpsc, oneshot, watch};
+use tokio_util::sync::CancellationToken;
+
+use crate::{PreparingEditorPhase, PreparingEditorProgress, PreparingPlaybackState};
+
+pub struct PreparingAudioSegmentInput {
+ pub mic: Option<ManagedAudioInput>,
+ pub system_audio: Option<ManagedAudioInput>,
+ pub timing_repair: crate::SegmentAudioTimingRepair,
+}
+
+#[derive(Clone, Copy)]
+pub struct PreparingPlaybackOptions {
+ pub preview: crate::PreparingPreviewOptions,
+ pub fps: u32,
+ pub resolution: XY<u32>,
+}
+
+#[derive(Clone)]
+pub struct PreparingPlaybackExit {
+ pub snapshot: PreparingPlaybackSnapshot,
+ pub preview: Option<crate::PreparingPreviewExit>,
+ completed_audio: Arc<Mutex<Option<crate::CompletedAudioHandoff>>>,
+ pub error: Option<String>,
+ pub cleanup_failed: bool,
+}
+
+impl PreparingPlaybackExit {
+ pub fn take_completed_audio(&self) -> Option<crate::CompletedAudioHandoff> {
+ self.completed_audio
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take()
+ }
+}
+
+type CommandResult = oneshot::Sender<Result<(), String>>;
+
+enum PreparingPlaybackCommand {
+ Seek(f64, CommandResult),
+ Playing(bool, CommandResult),
+}
+
+#[derive(Clone)]
+pub struct PreparingPlaybackController {
+ commands: mpsc::Sender<PreparingPlaybackCommand>,
+ handoff: Arc<crate::preparing_handoff::HandoffState>,
+}
+
+impl PreparingPlaybackController {
+ pub async fn seek(&self, seconds: f64) -> Result<(), String> {
+ let _intent = self.handoff.begin_command()?;
+ let (reply, received) = oneshot::channel();
+ self.commands
+ .send(PreparingPlaybackCommand::Seek(seconds, reply))
+ .await
+ .map_err(|_| "Preparing playback has ended".to_string())?;
+ received
+ .await
+ .map_err(|_| "Preparing seek has ended".to_string())?
+ }
+
+ pub async fn set_playing(&self, playing: bool) -> Result<(), String> {
+ let _intent = self.handoff.begin_command()?;
+ let (reply, received) = oneshot::channel();
+ self.commands
+ .send(PreparingPlaybackCommand::Playing(playing, reply))
+ .await
+ .map_err(|_| "Preparing playback has ended".to_string())?;
+ received
+ .await
+ .map_err(|_| "Preparing playback has ended".to_string())?
+ }
+}
+
+#[derive(Clone)]
+pub struct PreparingPlaybackStopHandle {
+ handoff: std::sync::Weak<crate::preparing_handoff::HandoffState>,
+ cancelled: CancellationToken,
+ completion: Shared<BoxFuture<'static, PreparingPlaybackExit>>,
+}
+
+impl PreparingPlaybackStopHandle {
+ #[cfg(test)]
+ pub(crate) fn test_pending(snapshot: PreparingPlaybackSnapshot) -> (Self, CancellationToken) {
+ let cancelled = CancellationToken::new();
+ let completion_cancel = cancelled.clone();
+ let completion = async move {
+ completion_cancel.cancelled().await;
+ PreparingPlaybackExit {
+ snapshot,
+ preview: None,
+ completed_audio: Arc::default(),
+ error: None,
+ cleanup_failed: false,
+ }
+ }
+ .boxed()
+ .shared();
+ (
+ Self {
+ handoff: Default::default(),
+ cancelled: cancelled.clone(),
+ completion,
+ },
+ cancelled,
+ )
+ }
+
+ pub(crate) fn with_handoff(
+ mut self,
+ state: &Arc<crate::preparing_handoff::HandoffState>,
+ ) -> Self {
+ self.handoff = Arc::downgrade(state);
+ self
+ }
+
+ pub fn cancel(&self) {
+ if let Some(handoff) = self.handoff.upgrade() {
+ handoff.cancel_adoption();
+ }
+ self.cancelled.cancel();
+ }
+
+ pub async fn stop_and_wait(&self) -> PreparingPlaybackExit {
+ self.cancel();
+ self.completion.clone().await
+ }
+}
+
+pub struct PreparingPlaybackSession {
+ controller: PreparingPlaybackController,
+ stop: PreparingPlaybackStopHandle,
+ updates: watch::Receiver<PreparingPlaybackSnapshot>,
+ handoff: crate::PreparingPlaybackHandoff,
+}
+
+impl PreparingPlaybackSession {
+ pub fn spawn(
+ input: crate::PreparingPreviewInput,
+ audio: Vec<PreparingAudioSegmentInput>,
+ options: PreparingPlaybackOptions,
+ audio_output: Arc<crate::AudioOutput>,
+ callback: crate::PreparingPreviewCallback,
+ ) -> Result<Self, String> {
+ let expected = input.recording_meta.clone();
+ Self::spawn_with_expected_metadata(input, audio, options, audio_output, callback, expected)
+ }
+
+ pub fn spawn_with_expected_metadata(
+ input: crate::PreparingPreviewInput,
+ audio: Vec<PreparingAudioSegmentInput>,
+ options: PreparingPlaybackOptions,
+ audio_output: Arc<crate::AudioOutput>,
+ callback: crate::PreparingPreviewCallback,
+ expected_finalized_metadata: cap_project::RecordingMeta,
+ ) -> Result<Self, String> {
+ validate_expected_metadata(&input.recording_meta, &expected_finalized_metadata)?;
+ crate::preparing_preview::validate_input(&input).map_err(|error| error.to_string())?;
+ if options.fps == 0
+ || options.fps > 240
+ || options.resolution.x < 2
+ || options.resolution.x > 8192
+ || options.resolution.y < 2
+ || options.resolution.y > 8192
+ {
+ return Err("Preparing playback output is invalid".into());
+ }
+ let Some(StudioRecordingMeta::MultipleSegments { inner }) =
+ input.recording_meta.studio_meta()
+ else {
+ return Err("Preparing playback requires stopped segments".into());
+ };
+ if audio.len() != inner.segments.len() {
+ return Err("Preparing audio layout does not match".into());
+ }
+ let required_audio: Vec<_> = inner
+ .segments
+ .iter()
+ .map(|segment| [segment.mic.is_some(), segment.system_audio.is_some()])
+ .collect();
+ let durations: Vec<_> = input
+ .project
+ .timeline
+ .as_ref()
+ .ok_or("Preparing timeline is absent")?
+ .segments
+ .iter()
+ .map(|segment| segment.end)
+ .collect();
+ let clock = PreparingPlaybackClock::new(
+ &durations,
+ &required_audio
+ .iter()
+ .map(|tracks| tracks.iter().any(|required| *required))
+ .collect::<Vec<_>>(),
+ )?;
+ let runtime = tokio::runtime::Handle::try_current().map_err(|error| error.to_string())?;
+ let (commands, received) = mpsc::channel(8);
+ let (updates, receiver) = watch::channel(clock.snapshot.clone());
+ let cancelled = CancellationToken::new();
+ let handoff = crate::preparing_handoff::HandoffState::new();
+ let runner = PreparingPlaybackRunner {
+ handoff: handoff.clone(),
+ source_metadata: input.recording_meta.clone(),
+ clock,
+ options,
+ project: input.project.clone(),
+ expected_finalized_metadata,
+ audio_output,
+ audio_ticket: None,
+ audio_sources: None,
+ audio: Vec::new(),
+ audio_stops: Vec::new(),
+ required_audio,
+ completed_audio: Vec::new(),
+ repairs: Vec::new(),
+ preview: None,
+ preview_cleanup_failed: false,
+ pending: None,
+ commands: received,
+ updates,
+ cancelled: cancelled.clone(),
+ callback,
+ };
+ let fallback = runner.clock.snapshot.clone();
+ let task = runtime.spawn(runner.run(input, audio));
+ let completion = join_preparing_task(task, fallback, handoff.clone())
+ .boxed()
+ .shared();
+ let retained = completion.clone();
+ drop(runtime.spawn(async move {
+ drop(retained.await);
+ }));
+ let stop = PreparingPlaybackStopHandle {
+ handoff: Arc::downgrade(&handoff),
+ cancelled,
+ completion,
+ };
+ Ok(Self {
+ controller: PreparingPlaybackController {
+ commands,
+ handoff: handoff.clone(),
+ },
+ handoff: crate::PreparingPlaybackHandoff::new(handoff, stop.clone()),
+ stop,
+ updates: receiver,
+ })
+ }
+
+ pub fn handoff_handle(&self) -> crate::PreparingPlaybackHandoff {
+ self.handoff.clone()
+ }
+
+ pub fn controller(&self) -> PreparingPlaybackController {
+ self.controller.clone()
+ }
+
+ pub fn stop_handle(&self) -> PreparingPlaybackStopHandle {
+ self.stop.clone()
+ }
+
+ pub fn updates(&self) -> watch::Receiver<PreparingPlaybackSnapshot> {
+ self.updates.clone()
+ }
+}
+
+fn validate_expected_metadata(
+ source: &cap_project::RecordingMeta,
+ expected: &cap_project::RecordingMeta,
+) -> Result<(), String> {
+ let mut cleared = source.clone();
+ if let cap_project::RecordingMetaInner::Studio(studio) = &mut cleared.inner
+ && let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut()
+ {
+ for segment in &mut inner.segments {
+ for track in [&mut segment.mic, &mut segment.system_audio]
+ .into_iter()
+ .flatten()
+ {
+ track.gap_summary = None;
+ }
+ }
+ }
+ let serialize = |meta: &cap_project::RecordingMeta| {
+ serde_json::to_value(meta).map_err(|error| error.to_string())
+ };
+ let expected_value = serialize(expected)?;
+ if source.project_path != expected.project_path
+ || (serialize(source)? != expected_value && serialize(&cleared)? != expected_value)
+ {
+ return Err("Preparing finalized metadata changes more than audio gap summaries".into());
+ }
+ Ok(())
+}
+
+enum FramePurpose {
+ Display {
+ reply: Option<CommandResult>,
+ settle_playing: Option<bool>,
+ },
+ Probe(usize),
+}
+
+struct PendingFrame {
+ sequence: u64,
+ purpose: FramePurpose,
+}
+
+pub(crate) async fn join_preparing_task(
+ task: tokio::task::JoinHandle<PreparingPlaybackExit>,
+ fallback: PreparingPlaybackSnapshot,
+ handoff: Arc<crate::preparing_handoff::HandoffState>,
+) -> PreparingPlaybackExit {
+ match task.await {
+ Ok(exit) => exit,
+ Err(error) => {
+ let error = format!("Preparing playback cleanup failed: {error}");
+ handoff.finish(Some(error.clone()));
+ PreparingPlaybackExit {
+ snapshot: fallback,
+ preview: None,
+ completed_audio: Arc::default(),
+ error: Some(error),
+ cleanup_failed: true,
+ }
+ }
+ }
+}
+
+struct PreparingPlaybackRunner {
+ handoff: Arc<crate::preparing_handoff::HandoffState>,
+ source_metadata: cap_project::RecordingMeta,
+ clock: PreparingPlaybackClock,
+ options: PreparingPlaybackOptions,
+ project: cap_project::ProjectConfiguration,
+ expected_finalized_metadata: cap_project::RecordingMeta,
+ audio_output: Arc<crate::AudioOutput>,
+ audio_ticket: Option<crate::audio_output::PreparingAudioPlayTicket>,
+ audio_sources: Option<crate::preparing_audio::PreparingAudioSources>,
+ audio: Vec<[Option<ManagedProgressiveAudio>; 2]>,
+ audio_stops: Vec<ManagedAudioStopHandle>,
+ required_audio: Vec<[bool; 2]>,
+ completed_audio: Vec<[Option<Arc<cap_audio::DecodedAudio>>; 2]>,
+ repairs: Vec<crate::SegmentAudioTimingRepair>,
+ preview: Option<crate::PreparingPreview>,
+ preview_cleanup_failed: bool,
+ pending: Option<PendingFrame>,
+ commands: mpsc::Receiver<PreparingPlaybackCommand>,
+ updates: watch::Sender<PreparingPlaybackSnapshot>,
+ cancelled: CancellationToken,
+ callback: crate::PreparingPreviewCallback,
+}
+
+impl PreparingPlaybackRunner {
+ async fn run(
+ mut self,
+ input: crate::PreparingPreviewInput,
+ audio: Vec<PreparingAudioSegmentInput>,
+ ) -> PreparingPlaybackExit {
+ let source_metadata = input.recording_meta.clone();
+ let result = std::panic::AssertUnwindSafe(self.run_inner(input, audio))
+ .catch_unwind()
+ .await;
+ let mut error = match result {
+ Ok(Ok(())) => None,
+ Ok(Err(error)) => Some(error),
+ Err(_) => Some("Preparing playback task panicked".into()),
+ };
+ let audio_cleanup_failed = match self.stop_audio().await {
+ Ok(()) => false,
+ Err(cleanup_error) => {
+ error = Some(cleanup_error);
+ true
+ }
+ };
+ self.clock.handoff();
+ if error.is_some() {
+ self.clock.snapshot.progress.phase = PreparingEditorPhase::Unavailable;
+ self.clock.snapshot.progress.playable_until = 0.0;
+ self.clock.snapshot.playback.playing = false;
+ }
+ let _ = self.publish();
+ for stop in &self.audio_stops {
+ stop.cancel();
+ }
+ let preview = if let Some(preview) = self.preview.take() {
+ Some(preview.stop_handle().stop_and_wait().await)
+ } else {
+ None
+ };
+ let preview_cleanup_failed = preview
+ .as_ref()
+ .is_some_and(|exit| matches!(exit.reason, crate::PreparingPreviewError::TaskJoin(_)));
+ let cleanup_failed =
+ audio_cleanup_failed || preview_cleanup_failed || self.preview_cleanup_failed;
+ if preview_cleanup_failed {
+ error = Some("Preparing preview workers could not be joined".into());
+ }
+ for stop in &self.audio_stops {
+ drop(stop.wait().await);
+ }
+ for (index, tracks) in self.audio.iter().enumerate() {
+ for (track, audio) in tracks.iter().enumerate() {
+ if let Some(audio) = audio
+ && audio.loader().progress().complete
+ && let Ok(Some(decoded)) = audio.loader().get().await
+ {
+ self.completed_audio[index][track] = Some(decoded);
+ }
+ }
+ }
+ self.audio.clear();
+ self.audio_sources = None;
+ let completed_audio = crate::CompletedAudioHandoff::from_completed_tracks(
+ &source_metadata,
+ &self.expected_finalized_metadata,
+ self.completed_audio
+ .into_iter()
+ .map(
+ |[mic, system_audio]| crate::completed_audio::CompletedAudioSegment {
+ mic,
+ system_audio,
+ },
+ )
+ .collect(),
+ )
+ .ok();
+ if !self.handoff.ready() {
+ *self
+ .handoff
+ .completed_audio
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = completed_audio;
+ }
+ self.handoff.finish(error.clone());
+ PreparingPlaybackExit {
+ snapshot: self.clock.snapshot,
+ preview,
+ completed_audio: self.handoff.completed_audio.clone(),
+ error,
+ cleanup_failed,
+ }
+ }
+
+ fn publish(&mut self) -> Result<(), String> {
+ let snapshot = self.clock.publish()?;
+ self.handoff
+ .publish(snapshot.clone(), self.clock.position_at(Instant::now()));
+ self.handoff.set_audio(
+ self.audio_ticket
+ .as_ref()
+ .and_then(|ticket| ticket.output_handle()),
+ );
+ self.updates.send_replace(snapshot);
+ Ok(())
+ }
+
+ async fn stop_audio(&mut self) -> Result<(), String> {
+ if let Some(ticket) = &self.audio_ticket {
+ ticket.stop_and_wait().await?;
+ }
+ self.audio_ticket = None;
+ Ok(())
+ }
+
+ async fn run_inner(
+ &mut self,
+ input: crate::PreparingPreviewInput,
+ audio: Vec<PreparingAudioSegmentInput>,
+ ) -> Result<(), String> {
+ if self.cancelled.is_cancelled() {
+ return Ok(());
+ }
+ for (index, audio) in audio.into_iter().enumerate() {
+ let mut tracks = [None, None];
+ for (track, input) in [audio.mic, audio.system_audio].into_iter().enumerate() {
+ if let Some(input) = input {
+ if !self.required_audio[index][track] {
+ return Err("Unexpected preparing audio track".into());
+ }
+ let managed = ManagedProgressiveAudio::spawn(
+ input,
+ format!("Preparing {index} track {track}"),
+ )
+ .map_err(|error| error.to_string())?;
+ self.audio_stops.push(managed.stop_handle());
+ tracks[track] = Some(managed);
+ }
+ }
+ self.audio.push(tracks);
+ self.completed_audio.push([None, None]);
+ self.repairs.push(audio.timing_repair);
+ }
+ let sources = crate::preparing_audio::PreparingAudioSources {
+ project: Arc::new(self.project.clone()),
+ tracks: self
+ .audio
+ .iter()
+ .map(|tracks| {
+ tracks
+ .each_ref()
+ .map(|audio| audio.as_ref().map(|audio| audio.loader().clone()))
+ })
+ .collect(),
+ required: self.required_audio.clone(),
+ repairs: self.repairs.clone(),
+ };
+ sources.validate()?;
+ self.audio_sources = Some(sources);
+ if self
+ .required_audio
+ .iter()
+ .flatten()
+ .any(|required| *required)
+ {
+ self.audio_output.prewarm();
+ }
+ let (frames, received) = flume::bounded(1);
+ let discard = received.clone();
+ let preview = crate::PreparingPreview::spawn(
+ input,
+ self.options.preview,
+ Box::new(move |request, output, layout| {
+ deliver_latest(&frames, &discard, (request, output, layout));
+ }),
+ )
+ .map_err(|error| error.to_string())?;
+ self.preview = Some(preview);
+ tokio::select! {
+ biased;
+ _ = self.cancelled.cancelled() => return Ok(()),
+ ready = self.preview.as_mut().ok_or("Preparing preview is absent")?.wait_ready() => {
+ ready.map_err(|error| error.to_string())?;
+ }
+ }
+ self.request(
+ 0,
+ FramePurpose::Display {
+ reply: None,
+ settle_playing: Some(false),
+ },
+ )?;
+ let mut interval =
+ tokio::time::interval(Duration::from_secs_f64(1.0 / f64::from(self.options.fps)));
+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ let mut commands_open = true;
+ loop {
+ tokio::select! {
+ biased;
+ _ = self.cancelled.cancelled() => return Ok(()),
+ command = self.commands.recv(), if commands_open => {
+ let Some(command) = command else {
+ if !self.handoff.committed() { return Ok(()); }
+ commands_open = false;
+ continue;
+ };
+ self.command(command).await?;
+ }
+ frame = received.recv_async(), if self.preview.is_some() => {
+ let (request, output, layout) = frame.map_err(|error| error.to_string())?;
+ self.frame(request, output, layout).await?;
+ }
+ _ = interval.tick() => {
+ self.tick().await?;
+ }
+ }
+ }
+ }
+
+ fn request(&mut self, frame: u32, purpose: FramePurpose) -> Result<(), String> {
+ if let Some(PendingFrame {
+ purpose: FramePurpose::Display {
+ reply: Some(reply), ..
+ },
+ ..
+ }) = self.pending.take()
+ {
+ let _ = reply.send(Err("Preparing seek was replaced".into()));
+ }
+ let sequence = self
+ .preview
+ .as_mut()
+ .ok_or("Preparing preview is absent")?
+ .request_frame(frame, self.options.fps, self.options.resolution)
+ .map_err(|error| error.to_string())?;
+ self.pending = Some(PendingFrame { sequence, purpose });
+ Ok(())
+ }
+
+ async fn frame(
+ &mut self,
+ request: crate::PreparingFrameRequest,
+ output: crate::EditorFrameOutput,
+ layout: cap_rendering::FrameLayout,
+ ) -> Result<(), String> {
+ if self
+ .pending
+ .as_ref()
+ .is_none_or(|pending| pending.sequence != request.sequence)
+ {
+ return Ok(());
+ }
+ let pending = self
+ .pending
+ .take()
+ .ok_or("Preparing frame request is absent")?;
+ let seconds = f64::from(request.frame_number) / f64::from(request.fps);
+ let (_, segment) = self
+ .project
+ .get_segment_time(seconds)
+ .ok_or("Preparing frame is outside the timeline")?;
+ self.clock.video_ready(segment.recording_clip as usize)?;
+ match pending.purpose {
+ FramePurpose::Display {
+ reply,
+ settle_playing,
+ } => {
+ if self.handoff.committed() {
+ return self.publish();
+ }
+ (self.callback)(request, output, layout);
+ self.clock.snapshot.progress.preview_available = true;
+ self.clock.snapshot.playback.playhead_seconds = seconds;
+ if let Some(playing) = settle_playing {
+ if playing {
+ if !self.start_audio().await? {
+ return Ok(());
+ }
+ self.start_clock()?;
+ } else {
+ self.clock.anchor = None;
+ self.clock.audio_position = None;
+ self.clock.snapshot.playback.playing = false;
+ self.clock.snapshot.playback.buffering = false;
+ }
+ }
+ self.publish()?;
+ if let Some(reply) = reply {
+ let _ = reply.send(Ok(()));
+ }
+ return Ok(());
+ }
+ FramePurpose::Probe(index) => {
+ if segment.recording_clip as usize != index {
+ return Err("Preparing probe did not resolve the requested clip".into());
+ }
+ }
+ }
+ self.publish()
+ }
+
+ async fn refresh_audio(&mut self) -> Result<(), String> {
+ for (index, tracks) in self.audio.iter().enumerate() {
+ for (track, audio) in tracks.iter().enumerate() {
+ if self.completed_audio[index][track].is_some() {
+ continue;
+ }
+ if let Some(audio) = audio {
+ let progress = audio.loader().progress();
+ if let Some(error) = progress.error {
+ return Err(error);
+ }
+ if progress.complete {
+ self.completed_audio[index][track] = audio.loader().get().await?;
+ }
+ }
+ }
+ if self.required_audio[index]
+ .iter()
+ .enumerate()
+ .all(|(track, required)| !required || self.completed_audio[index][track].is_some())
+ {
+ self.clock.audio_ready(index)?;
+ }
+ }
+ let prefix = self
+ .audio_sources
+ .as_ref()
+ .ok_or("Preparing audio sources are absent")?
+ .playable_prefix()?;
+ self.clock.audio_prefix(prefix)?;
+ if !self.handoff.ready()
+ && self
+ .required_audio
+ .iter()
+ .enumerate()
+ .all(|(index, tracks)| {
+ tracks.iter().enumerate().all(|(track, required)| {
+ !required || self.completed_audio[index][track].is_some()
+ })
+ })
+ {
+ for stop in &self.audio_stops {
+ let exit = stop.wait().await;
+ if !matches!(
+ exit.terminal,
+ cap_audio::ManagedAudioTerminal::Complete { .. }
+ ) {
+ return Err(exit.terminal.to_string());
+ }
+ }
+ let tracks = self
+ .completed_audio
+ .iter()
+ .map(
+ |[mic, system_audio]| crate::completed_audio::CompletedAudioSegment {
+ mic: mic.clone(),
+ system_audio: system_audio.clone(),
+ },
+ )
+ .collect::<Vec<_>>();
+ self.handoff
+ .set_completed_identity(&tracks, &self.audio_output);
+ let completed = crate::CompletedAudioHandoff::from_completed_tracks(
+ &self.source_metadata,
+ &self.expected_finalized_metadata,
+ tracks,
+ )?;
+ self.handoff.complete(completed);
+ }
+ Ok(())
+ }
+
+ fn start_clock(&mut self) -> Result<(), String> {
+ self.clock.start(Instant::now())?;
+ if self
+ .audio_ticket
+ .as_ref()
+ .and_then(|ticket| ticket.output_status(Instant::now()))
+ .is_some()
+ {
+ self.clock.anchor = None;
+ }
+ Ok(())
+ }
+
+ async fn start_audio(&mut self) -> Result<bool, String> {
+ self.stop_audio().await?;
+ if self.cancelled.is_cancelled() {
+ return Ok(false);
+ }
+ let position = self.clock.snapshot.playback.playhead_seconds;
+ if !self
+ .required_audio
+ .iter()
+ .flatten()
+ .any(|required| *required)
+ {
+ return Ok(true);
+ }
+ let sources = self
+ .audio_sources
+ .as_ref()
+ .ok_or("Preparing audio sources are absent")?
+ .clone();
+ self.audio_ticket = Some(self.audio_output.prepare_progressive_playback(
+ sources,
+ position,
+ self.clock.snapshot.progress.playable_until,
+ ));
+ let started = tokio::select! {
+ biased;
+ _ = self.cancelled.cancelled() => false,
+ started = self.audio_ticket.as_ref().expect("Preparing audio ticket is retained").wait_started() => started,
+ };
+ if !started || self.cancelled.is_cancelled() {
+ let status = self
+ .audio_ticket
+ .as_ref()
+ .and_then(|ticket| ticket.output_status(Instant::now()));
+ self.stop_audio().await?;
+ if !self.cancelled.is_cancelled()
+ && let Some(status) = status
+ {
+ return Err(status
+ .error
+ .unwrap_or_else(|| "Preparing audio did not start".into()));
+ }
+ }
+ Ok(!self.cancelled.is_cancelled())
+ }
+
+ async fn command(&mut self, command: PreparingPlaybackCommand) -> Result<(), String> {
+ match command {
+ PreparingPlaybackCommand::Seek(seconds, reply) => {
+ let was_playing = self.clock.snapshot.playback.playing;
+ if let Err(error) = self.clock.validate_seek(seconds) {
+ let _ = reply.send(Err(error));
+ return Ok(());
+ }
+ let frame = (seconds * f64::from(self.options.fps)).floor() as u32;
+ self.stop_audio().await?;
+ self.clock.anchor = None;
+ self.clock.audio_position = None;
+ self.clock.snapshot.playback.buffering = was_playing;
+ self.request(
+ frame,
+ FramePurpose::Display {
+ reply: Some(reply),
+ settle_playing: Some(was_playing),
+ },
+ )?;
+ self.publish()?;
+ }
+ PreparingPlaybackCommand::Playing(playing, reply) => {
+ if playing {
+ if self.pending.as_ref().is_some_and(|pending| {
+ matches!(
+ pending.purpose,
+ FramePurpose::Display {
+ settle_playing: Some(_),
+ ..
+ }
+ )
+ }) {
+ let _ = reply.send(Err("Preparing seek is still being presented".into()));
+ return Ok(());
+ }
+ if self.clock.snapshot.playback.playing {
+ let _ = reply.send(Ok(()));
+ return Ok(());
+ }
+ if !self.clock.snapshot.progress.preview_available
+ || self.clock.snapshot.playback.playhead_seconds
+ >= self.clock.snapshot.progress.playable_until
+ {
+ let _ = reply.send(Err(
+ "Preparing playback is not ready at this position".into()
+ ));
+ return Ok(());
+ }
+ self.clock.snapshot.playback.playing = true;
+ self.clock.snapshot.playback.buffering = true;
+ self.clock.anchor = None;
+ self.clock.audio_position = None;
+ self.publish()?;
+ if !self.start_audio().await? {
+ return Ok(());
+ }
+ self.start_clock()?;
+ } else {
+ if let Some(status) = self
+ .audio_ticket
+ .as_ref()
+ .and_then(|ticket| ticket.output_status(Instant::now()))
+ {
+ self.clock.sync_audio(&status)?;
+ }
+ let position = self.clock.position_at(Instant::now());
+ self.stop_audio().await?;
+ self.clock.pause();
+ if self.clock.snapshot.progress.playable_until > 0.0 {
+ let fps = f64::from(self.options.fps);
+ let last_frame =
+ (self.clock.snapshot.progress.playable_until * fps).ceil() as u32;
+ let frame =
+ ((position * fps).floor() as u32).min(last_frame.saturating_sub(1));
+ self.request(
+ frame,
+ FramePurpose::Display {
+ reply: Some(reply),
+ settle_playing: Some(false),
+ },
+ )?;
+ return self.publish();
+ }
+ }
+ self.publish()?;
+ let _ = reply.send(Ok(()));
+ }
+ }
+ Ok(())
+ }
+
+ async fn tick(&mut self) -> Result<(), String> {
+ if self.handoff.committed()
+ && self.clock.clips.iter().all(|clip| clip.video)
+ && let Some(preview) = self.preview.take()
+ {
+ self.pending = None;
+ let exit = preview.stop_handle().stop_and_wait().await;
+ if matches!(exit.reason, crate::PreparingPreviewError::TaskJoin(_)) {
+ self.preview_cleanup_failed = true;
+ return Err("Preparing video handoff could not join its workers".into());
+ }
+ }
+ if let Some(error) = self
+ .preview
+ .as_ref()
+ .and_then(|preview| preview.stop_handle().terminal_error())
+ {
+ return Err(error.to_string());
+ }
+ let old_prefix = self.clock.snapshot.progress.playable_until;
+ self.refresh_audio().await?;
+ if let Some(ticket) = &self.audio_ticket {
+ ticket.set_playable_until(self.clock.snapshot.progress.playable_until)?;
+ }
+ let now = Instant::now();
+ let audio_status = self
+ .audio_ticket
+ .as_ref()
+ .and_then(|ticket| ticket.output_status(now));
+ let has_audio_clock = audio_status.is_some();
+ if let Some(status) = audio_status {
+ let ended = status.ended;
+ let buffering = self.clock.snapshot.playback.buffering;
+ self.clock.sync_audio(&status)?;
+ if ended {
+ self.stop_audio().await?;
+ }
+ if ended || buffering != self.clock.snapshot.playback.buffering {
+ self.publish()?;
+ }
+ }
+ if self.audio_ticket.is_none()
+ && self.clock.snapshot.playback.playing
+ && self.clock.snapshot.playback.buffering
+ && self.pending.is_none()
+ && self.clock.position_at(now) < self.clock.snapshot.progress.playable_until
+ {
+ if !self.start_audio().await? {
+ return Ok(());
+ }
+ self.start_clock()?;
+ self.publish()?;
+ }
+ let now = Instant::now();
+ if !has_audio_clock && self.clock.reach_boundary(now) {
+ self.publish()?;
+ }
+ if old_prefix != self.clock.snapshot.progress.playable_until {
+ self.publish()?;
+ }
+ if self.pending.is_some() {
+ return Ok(());
+ }
+ if let Some(index) = self.clock.clips.iter().position(|clip| !clip.video) {
+ let start = if index == 0 {
+ 0.0
+ } else {
+ self.clock.clips[index - 1].end
+ };
+ let frame = (start * f64::from(self.options.fps)).ceil() as u32;
+ let time = f64::from(frame) / f64::from(self.options.fps);
+ if time < self.clock.clips[index].end
+ && (self.handoff.committed()
+ || !self.clock.snapshot.playback.playing
+ || start <= self.clock.position_at(now) + 2.0)
+ {
+ self.request(frame, FramePurpose::Probe(index))?;
+ return Ok(());
+ }
+ }
+ if self.handoff.committed() {
+ return self.publish();
+ }
+ if (self.clock.snapshot.playback.playing || has_audio_clock)
+ && self.clock.snapshot.progress.playable_until > 0.0
+ {
+ let fps = f64::from(self.options.fps);
+ let last_frame = (self.clock.snapshot.progress.playable_until * fps).ceil() as u32;
+ let frame = ((self.clock.position_at(now) * fps).floor() as u32)
+ .min(last_frame.saturating_sub(1));
+ if f64::from(frame) / fps != self.clock.snapshot.playback.playhead_seconds {
+ self.request(
+ frame,
+ FramePurpose::Display {
+ reply: None,
+ settle_playing: None,
+ },
+ )?;
+ }
+ }
+ Ok(())
+ }
+}
+
+fn deliver_latest<T>(sender: &flume::Sender<T>, discard: &flume::Receiver<T>, value: T) {
+ if let Err(flume::TrySendError::Full(value)) = sender.try_send(value) {
+ drop(discard.try_recv());
+ let _ = sender.try_send(value);
+ }
+}
+
+impl Drop for PreparingPlaybackSession {
+ fn drop(&mut self) {
+ if !self.handoff.committed() {
+ self.stop.cancel();
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct PreparingPlaybackSnapshot {
+ pub sequence: u64,
+ pub progress: PreparingEditorProgress,
+ pub playback: PreparingPlaybackState,
+}
+
+struct ClipReadiness {
+ end: f64,
+ video: bool,
+ audio_until: f64,
+}
+
+struct PreparingPlaybackClock {
+ clips: Vec<ClipReadiness>,
+ snapshot: PreparingPlaybackSnapshot,
+ anchor: Option<(Instant, f64)>,
+ audio_position: Option<f64>,
+}
+
+impl PreparingPlaybackClock {
+ fn new(durations: &[f64], has_audio: &[bool]) -> Result<Self, String> {
+ if durations.is_empty() || durations.len() != has_audio.len() {
+ return Err("Preparing clip layout does not match".into());
+ }
+ let mut total = 0.0;
+ let mut clips = Vec::with_capacity(durations.len());
+ for (&duration, &has_audio) in durations.iter().zip(has_audio) {
+ let start = total;
+ total += duration;
+ if !duration.is_finite() || duration <= 0.0 || !total.is_finite() {
+ return Err("Preparing duration is invalid".into());
+ }
+ clips.push(ClipReadiness {
+ end: total,
+ video: false,
+ audio_until: if has_audio { start } else { total },
+ });
+ }
+ Ok(Self {
+ clips,
+ snapshot: PreparingPlaybackSnapshot {
+ sequence: 0,
+ progress: PreparingEditorProgress {
+ total_duration: Some(total),
+ ..Default::default()
+ },
+ playback: PreparingPlaybackState::default(),
+ },
+ anchor: None,
+ audio_position: None,
+ })
+ }
+
+ fn refresh_prefix(&mut self) {
+ let mut prefix = 0.0;
+ for clip in &self.clips {
+ if !clip.video {
+ break;
+ }
+ prefix = clip.audio_until;
+ if prefix < clip.end {
+ break;
+ }
+ }
+ self.snapshot.progress.playable_until = prefix;
+ }
+
+ fn video_ready(&mut self, index: usize) -> Result<(), String> {
+ let clip = self
+ .clips
+ .get_mut(index)
+ .ok_or("Preparing video clip is outside the timeline")?;
+ clip.video = true;
+ self.refresh_prefix();
+ Ok(())
+ }
+
+ fn audio_ready(&mut self, index: usize) -> Result<(), String> {
+ let clip = self
+ .clips
+ .get_mut(index)
+ .ok_or("Preparing audio clip is outside the timeline")?;
+ clip.audio_until = clip.end;
+ self.refresh_prefix();
+ Ok(())
+ }
+
+ fn audio_prefix(&mut self, prefix: f64) -> Result<(), String> {
+ let total = self
+ .snapshot
+ .progress
+ .total_duration
+ .ok_or("Preparing duration is unavailable")?;
+ if !prefix.is_finite() || prefix < 0.0 || prefix > total {
+ return Err("Preparing audio prefix is outside the timeline".into());
+ }
+ let mut start = 0.0;
+ for clip in &mut self.clips {
+ clip.audio_until = clip.audio_until.max(prefix.clamp(start, clip.end));
+ start = clip.end;
+ }
+ self.refresh_prefix();
+ Ok(())
+ }
+
+ fn sync_audio(
+ &mut self,
+ status: &crate::preparing_audio::PreparingAudioOutputSnapshot,
+ ) -> Result<(), String> {
+ if let Some(error) = &status.error {
+ return Err(error.clone());
+ }
+ let total = self
+ .snapshot
+ .progress
+ .total_duration
+ .ok_or("Preparing duration is unavailable")?;
+ if self.snapshot.progress.phase != PreparingEditorPhase::Preparing
+ || !status.playhead_seconds.is_finite()
+ || status.playhead_seconds < 0.0
+ || status.playhead_seconds > total
+ || (status.ended && status.buffering)
+ {
+ return Err("Preparing audio position is invalid".into());
+ }
+ self.audio_position = Some(
+ status
+ .playhead_seconds
+ .min(self.snapshot.progress.playable_until),
+ );
+ self.anchor = None;
+ self.snapshot.playback.buffering = status.buffering;
+ if status.ended {
+ self.snapshot.playback.playing = false;
+ }
+ Ok(())
+ }
+
+ fn position_at(&self, now: Instant) -> f64 {
+ let position = self.anchor.map_or_else(
+ || {
+ self.audio_position
+ .unwrap_or(self.snapshot.playback.playhead_seconds)
+ },
+ |(start, at)| at + now.saturating_duration_since(start).as_secs_f64(),
+ );
+ position.min(self.snapshot.progress.playable_until)
+ }
+
+ fn start(&mut self, now: Instant) -> Result<(), String> {
+ let position = self.position_at(now);
+ if self.snapshot.progress.phase != PreparingEditorPhase::Preparing
+ || !self.snapshot.progress.preview_available
+ || position >= self.snapshot.progress.playable_until
+ {
+ return Err("Preparing playback is not ready at this position".into());
+ }
+ self.anchor = Some((now, position));
+ self.audio_position = None;
+ self.snapshot.playback.playing = true;
+ self.snapshot.playback.buffering = false;
+ Ok(())
+ }
+
+ fn pause(&mut self) {
+ self.snapshot.playback.playing = false;
+ self.snapshot.playback.buffering = false;
+ self.anchor = None;
+ self.audio_position = None;
+ }
+
+ fn validate_seek(&self, seconds: f64) -> Result<(), String> {
+ if self.snapshot.progress.phase != PreparingEditorPhase::Preparing
+ || !seconds.is_finite()
+ || seconds < 0.0
+ || seconds >= self.snapshot.progress.playable_until
+ {
+ return Err("Requested position is outside the playable recording".into());
+ }
+ Ok(())
+ }
+
+ fn reach_boundary(&mut self, now: Instant) -> bool {
+ if !self.snapshot.playback.playing
+ || self.snapshot.playback.buffering
+ || self.position_at(now) < self.snapshot.progress.playable_until
+ {
+ return false;
+ }
+ self.anchor = None;
+ self.audio_position = Some(self.snapshot.progress.playable_until);
+ let at_end =
+ self.snapshot.progress.total_duration == Some(self.snapshot.progress.playable_until);
+ self.snapshot.playback.playing = !at_end;
+ self.snapshot.playback.buffering = !at_end;
+ true
+ }
+
+ fn handoff(&mut self) {
+ self.anchor = None;
+ self.audio_position = None;
+ self.snapshot.progress.phase = PreparingEditorPhase::Handoff;
+ self.snapshot.playback.buffering = false;
+ }
+
+ fn publish(&mut self) -> Result<PreparingPlaybackSnapshot, String> {
+ self.snapshot.sequence = self
+ .snapshot
+ .sequence
+ .checked_add(1)
+ .ok_or("Preparing update sequence exhausted")?;
+ Ok(self.snapshot.clone())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn expected_audio_metadata_only_allows_gap_summary_clearing() {
+ let source: cap_project::RecordingMeta = serde_json::from_value(serde_json::json!({
+ "pretty_name": "Stopped capture",
+ "segments": [{
+ "display": { "path": "display", "fps": 30 },
+ "mic": {
+ "path": "audio-input.m4a", "start_time": 0.125,
+ "gap_summary": {
+ "total_overlap_trimmed_ms": 5,
+ "startup_overlap_trimmed_ms": 0,
+ "overlap_dropped_frames": 0,
+ "startup_overlap_drops": 0
+ }
+ }
+ }]
+ }))
+ .unwrap();
+ validate_expected_metadata(&source, &source).unwrap();
+ let mut cleared = serde_json::to_value(&source).unwrap();
+ cleared["segments"][0]["mic"]
+ .as_object_mut()
+ .unwrap()
+ .remove("gap_summary");
+ let expected: cap_project::RecordingMeta = serde_json::from_value(cleared.clone()).unwrap();
+ validate_expected_metadata(&source, &expected).unwrap();
+ for field in ["path", "start_time", "device_id"] {
+ let mut changed = cleared.clone();
+ changed["segments"][0]["mic"][field] = if field == "start_time" {
+ serde_json::json!(0.5)
+ } else {
+ serde_json::json!("changed")
+ };
+ let changed = serde_json::from_value(changed).unwrap();
+ assert!(validate_expected_metadata(&source, &changed).is_err());
+ }
+ let mut changed = expected;
+ changed.project_path = "another.cap".into();
+ assert!(validate_expected_metadata(&source, &changed).is_err());
+ let mut changed = serde_json::to_value(&source).unwrap();
+ changed["segments"][0]["mic"]["gap_summary"]["total_overlap_trimmed_ms"] =
+ serde_json::json!(9);
+ let changed = serde_json::from_value(changed).unwrap();
+ assert!(validate_expected_metadata(&source, &changed).is_err());
+ }
+
+ #[test]
+ fn saturated_frame_delivery_retains_the_newest_seek_response() {
+ let (frames, received) = flume::bounded(1);
+ let discard = received.clone();
+ for sequence in 1..=100 {
+ deliver_latest(&frames, &discard, sequence);
+ }
+ assert_eq!(received.try_recv().unwrap(), 100);
+ assert!(received.try_recv().is_err());
+ deliver_latest(&frames, &discard, 101);
+ assert_eq!(received.try_recv().unwrap(), 101);
+ }
+
+ #[test]
+ fn readiness_never_skips_an_unready_clip_or_required_audio() {
+ let mut clock =
+ PreparingPlaybackClock::new(&[10.0, 20.0, 30.0], &[true, true, false]).unwrap();
+ clock.video_ready(2).unwrap();
+ clock.audio_ready(1).unwrap();
+ clock.video_ready(1).unwrap();
+ clock.video_ready(0).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 0.0);
+ clock.audio_ready(0).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 60.0);
+ }
+
+ #[test]
+ fn preview_and_wall_time_cannot_admit_playback() {
+ let mut clock = PreparingPlaybackClock::new(&[7_200.0], &[true]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.video_ready(0).unwrap();
+ let now = Instant::now();
+ assert!(clock.start(now).is_err());
+ assert_eq!(clock.position_at(now + Duration::from_secs(7_200)), 0.0);
+ assert!(clock.validate_seek(0.0).is_err());
+ }
+
+ #[test]
+ fn buffering_freezes_clock_and_resumes_from_boundary_without_catching_up() {
+ let mut clock = PreparingPlaybackClock::new(&[10.0, 20.0], &[false, false]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.video_ready(0).unwrap();
+ let now = Instant::now();
+ clock.start(now).unwrap();
+ clock.snapshot.playback.playhead_seconds = 9.5;
+ assert!(clock.reach_boundary(now + Duration::from_secs(20)));
+ assert_eq!(clock.position_at(now + Duration::from_secs(20)), 10.0);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 9.5);
+ assert!(clock.snapshot.playback.playing);
+ assert!(clock.snapshot.playback.buffering);
+ clock.video_ready(1).unwrap();
+ assert_eq!(clock.position_at(now + Duration::from_secs(30)), 10.0);
+ clock.start(now + Duration::from_secs(30)).unwrap();
+ assert_eq!(clock.position_at(now + Duration::from_secs(31)), 11.0);
+ }
+
+ #[test]
+ fn handoff_preserves_playing_intent_and_seeking_never_advances_beyond_prefix() {
+ let mut clock = PreparingPlaybackClock::new(&[60.0], &[false]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.video_ready(0).unwrap();
+ for position in [f64::NAN, f64::INFINITY, -1.0, 60.0] {
+ assert!(clock.validate_seek(position).is_err());
+ }
+ clock.validate_seek(12.25).unwrap();
+ clock.snapshot.playback.playhead_seconds = 12.25;
+ let now = Instant::now();
+ clock.start(now).unwrap();
+ clock.handoff();
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 12.25);
+ assert!(clock.snapshot.playback.playing);
+ assert_eq!(clock.snapshot.progress.phase, PreparingEditorPhase::Handoff);
+ assert!(clock.validate_seek(0.0).is_err());
+ assert!(clock.start(now).is_err());
+ }
+
+ #[test]
+ fn reaching_the_complete_recording_end_pauses_without_buffering() {
+ let mut clock = PreparingPlaybackClock::new(&[1.0], &[false]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.video_ready(0).unwrap();
+ let now = Instant::now();
+ clock.start(now).unwrap();
+ clock.snapshot.playback.playhead_seconds = 0.9;
+ assert!(clock.reach_boundary(now + Duration::from_secs(2)));
+ assert_eq!(clock.position_at(now + Duration::from_secs(2)), 1.0);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 0.9);
+ assert!(!clock.snapshot.playback.playing);
+ assert!(!clock.snapshot.playback.buffering);
+ }
+
+ #[test]
+ fn pause_and_update_sequence_preserve_the_confirmed_position() {
+ let mut clock = PreparingPlaybackClock::new(&[60.0], &[false]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.video_ready(0).unwrap();
+ let now = Instant::now();
+ clock.start(now).unwrap();
+ clock.snapshot.playback.playhead_seconds = 3.0;
+ clock.pause();
+ assert_eq!(clock.position_at(now + Duration::from_secs(30)), 3.0);
+ assert_eq!(clock.publish().unwrap().sequence, 1);
+ assert_eq!(clock.publish().unwrap().sequence, 2);
+ }
+
+ fn audio_status(
+ position: f64,
+ buffering: bool,
+ ended: bool,
+ ) -> crate::preparing_audio::PreparingAudioOutputSnapshot {
+ crate::preparing_audio::PreparingAudioOutputSnapshot {
+ playhead_seconds: position,
+ buffering,
+ ended,
+ error: None,
+ }
+ }
+
+ #[test]
+ fn partial_audio_admits_a_long_clip_only_after_its_video_is_ready() {
+ let mut clock = PreparingPlaybackClock::new(&[7200.0], &[true]).unwrap();
+ clock.audio_prefix(0.25).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 0.0);
+ clock.video_ready(0).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 0.25);
+ clock.audio_prefix(60.0).unwrap();
+ clock.audio_prefix(0.5).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 60.0);
+ for prefix in [f64::NAN, f64::INFINITY, -1.0, 7200.01] {
+ assert!(clock.audio_prefix(prefix).is_err());
+ assert_eq!(clock.snapshot.progress.playable_until, 60.0);
+ }
+ }
+
+ #[test]
+ fn partial_audio_prefix_preserves_contiguous_video_and_silent_clip_gates() {
+ let mut clock =
+ PreparingPlaybackClock::new(&[5.0, 5.0, 5.0], &[false, true, false]).unwrap();
+ clock.audio_prefix(8.0).unwrap();
+ clock.video_ready(2).unwrap();
+ clock.video_ready(1).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 0.0);
+ clock.video_ready(0).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 8.0);
+ clock.audio_prefix(10.0).unwrap();
+ assert_eq!(clock.snapshot.progress.playable_until, 15.0);
+ }
+
+ #[test]
+ fn audible_starvation_and_resume_never_advance_the_presented_frame_or_wall_clock() {
+ let mut clock = PreparingPlaybackClock::new(&[7200.0], &[true]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.snapshot.playback.playhead_seconds = 1.0;
+ clock.audio_prefix(20.0).unwrap();
+ clock.video_ready(0).unwrap();
+ let now = Instant::now();
+ clock.start(now).unwrap();
+ clock.sync_audio(&audio_status(1.5, true, false)).unwrap();
+ assert_eq!(clock.position_at(now + Duration::from_secs(100)), 1.5);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 1.0);
+ assert!(clock.snapshot.playback.playing);
+ assert!(clock.snapshot.playback.buffering);
+ clock.audio_prefix(40.0).unwrap();
+ clock.sync_audio(&audio_status(1.75, false, false)).unwrap();
+ assert_eq!(clock.position_at(now + Duration::from_secs(200)), 1.75);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 1.0);
+ assert!(clock.snapshot.playback.playing);
+ assert!(!clock.snapshot.playback.buffering);
+ clock.audio_prefix(7200.0).unwrap();
+ clock
+ .sync_audio(&audio_status(7200.0, false, true))
+ .unwrap();
+ assert!(!clock.snapshot.playback.playing);
+ assert!(!clock.snapshot.playback.buffering);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 1.0);
+ }
+
+ #[test]
+ fn pause_and_handoff_discard_audible_ahead_position_but_retain_the_presented_frame() {
+ let mut clock = PreparingPlaybackClock::new(&[10.0], &[true]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.snapshot.playback.playhead_seconds = 3.0;
+ clock.audio_prefix(10.0).unwrap();
+ clock.video_ready(0).unwrap();
+ let now = Instant::now();
+ clock.start(now).unwrap();
+ clock.sync_audio(&audio_status(3.2, false, false)).unwrap();
+ clock.pause();
+ assert_eq!(clock.position_at(now + Duration::from_secs(100)), 3.0);
+ clock.start(now + Duration::from_secs(100)).unwrap();
+ assert_eq!(clock.position_at(now + Duration::from_secs(100)), 3.0);
+ clock.sync_audio(&audio_status(3.3, false, false)).unwrap();
+ clock.handoff();
+ assert_eq!(clock.position_at(now + Duration::from_secs(200)), 3.0);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 3.0);
+ assert!(clock.snapshot.playback.playing);
+ assert!(clock.sync_audio(&audio_status(3.4, false, false)).is_err());
+ }
+
+ #[test]
+ fn invalid_audio_status_cannot_mutate_the_clock_and_valid_status_clamps_to_prefix() {
+ let mut clock = PreparingPlaybackClock::new(&[10.0], &[true]).unwrap();
+ clock.snapshot.progress.preview_available = true;
+ clock.audio_prefix(5.0).unwrap();
+ clock.video_ready(0).unwrap();
+ let now = Instant::now();
+ clock.start(now).unwrap();
+ clock.sync_audio(&audio_status(6.0, false, false)).unwrap();
+ assert_eq!(clock.position_at(now), 5.0);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 0.0);
+ for status in [
+ audio_status(f64::NAN, false, false),
+ audio_status(f64::INFINITY, false, false),
+ audio_status(-1.0, false, false),
+ audio_status(10.1, false, false),
+ audio_status(10.0, true, true),
+ crate::preparing_audio::PreparingAudioOutputSnapshot {
+ error: Some("late source failure".into()),
+ ..audio_status(6.5, false, false)
+ },
+ ] {
+ assert!(clock.sync_audio(&status).is_err());
+ assert_eq!(clock.position_at(now + Duration::from_secs(60)), 5.0);
+ assert_eq!(clock.snapshot.playback.playhead_seconds, 0.0);
+ }
+ }
+}
diff --git a/crates/editor/src/preparing_preview.rs b/crates/editor/src/preparing_preview.rs
new file mode 100644
index 000000000..0e15a21c6
--- /dev/null
+++ b/crates/editor/src/preparing_preview.rs
@@ -0,0 +1,800 @@
+use std::{collections::VecDeque, panic::AssertUnwindSafe, sync::Arc};
+
+use cap_project::{
+ BackgroundSource, CursorEvents, FrameStyle, ProjectConfiguration, RecordingMeta, XY,
+};
+use cap_rendering::decoder::ManagedVideoError;
+use cap_rendering::{
+ FrameLayout, FrameRenderer, FrozenRecordedCursorAssets, ManagedRecordingSegmentDecoders,
+ ManagedSegmentDecoderStatus, ManagedSegmentStopHandles, ManagedSegmentVideoError,
+ ManagedSegmentVideoExit, ManagedSegmentVideoInput, ProjectUniforms, RenderOptions,
+ RenderVideoConstants, RendererLayers, ZoomTransformTimeline,
+};
+use futures::{FutureExt, future::BoxFuture, future::Shared};
+use tokio::sync::watch;
+use tokio_util::sync::CancellationToken;
+
+use crate::{
+ EditorFrameFormat, EditorFrameOutput,
+ editor_instance::{
+ PREVIEW_RENDER_MAX_ATTEMPTS, PREVIEW_RENDER_RETRY_DELAY_MS, PreviewCursorCache,
+ },
+};
+
+const MAX_OPEN_SEGMENTS: usize = 2;
+
+#[cfg(test)]
+mod native_tests;
+#[cfg(test)]
+mod tests;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum PreparingPreviewError {
+ Cancelled,
+ InvalidInput(String),
+ Media(ManagedSegmentVideoError),
+ Render(String),
+ Panicked,
+ TaskJoin(String),
+}
+
+impl std::fmt::Display for PreparingPreviewError {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Cancelled => formatter.write_str("Preparing preview cancelled"),
+ Self::InvalidInput(error) => write!(formatter, "Invalid preparing preview: {error}"),
+ Self::Media(error) => write!(formatter, "Preparing preview media: {error}"),
+ Self::Render(error) => write!(formatter, "Preparing preview render: {error}"),
+ Self::Panicked => formatter.write_str("Preparing preview task panicked"),
+ Self::TaskJoin(error) => write!(formatter, "Preparing preview task join: {error}"),
+ }
+ }
+}
+
+impl std::error::Error for PreparingPreviewError {}
+
+pub struct PreparingPreviewSegment {
+ pub video: ManagedSegmentVideoInput,
+ pub cursor: Arc<CursorEvents>,
+}
+
+pub struct PreparingPreviewInput {
+ pub recording_meta: RecordingMeta,
+ pub project: ProjectConfiguration,
+ pub segments: Vec<PreparingPreviewSegment>,
+ pub cursor_assets: FrozenRecordedCursorAssets,
+}
+
+#[derive(Clone, Copy, Debug, Default)]
+pub struct PreparingPreviewOptions {
+ pub use_hardware_decoding: bool,
+ pub frame_format: EditorFrameFormat,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct PreparingFrameRequest {
+ pub sequence: u64,
+ pub frame_number: u32,
+ pub fps: u32,
+ pub resolution_base: XY<u32>,
+}
+
+#[derive(Clone, Debug)]
+pub struct PreparingPreviewReady {
+ pub screen_size: XY<u32>,
+ pub camera_size: Option<XY<u32>>,
+ pub duration: f64,
+}
+
+#[derive(Clone, Debug)]
+pub struct PreparingPreviewExit {
+ pub reason: PreparingPreviewError,
+ pub workers: Vec<ManagedSegmentVideoExit>,
+}
+
+pub type PreparingPreviewCallback =
+ Box<dyn FnMut(PreparingFrameRequest, EditorFrameOutput, FrameLayout) + Send>;
+
+#[derive(Clone, Default)]
+struct PreviewState {
+ ready: Option<PreparingPreviewReady>,
+ terminal: Option<PreparingPreviewError>,
+}
+
+struct PreviewControl {
+ cancel: CancellationToken,
+ state: watch::Sender<PreviewState>,
+}
+
+impl PreviewControl {
+ fn check(&self) -> Result<(), PreparingPreviewError> {
+ if let Some(error) = self.state.borrow().terminal.clone() {
+ Err(error)
+ } else if self.cancel.is_cancelled() {
+ Err(PreparingPreviewError::Cancelled)
+ } else {
+ Ok(())
+ }
+ }
+
+ fn finish(&self, error: PreparingPreviewError) {
+ self.state.send_modify(|state| {
+ state.terminal.get_or_insert(error);
+ });
+ }
+}
+
+#[derive(Clone)]
+pub struct PreparingPreviewStopHandle {
+ control: Arc<PreviewControl>,
+ completion: Shared<BoxFuture<'static, PreparingPreviewExit>>,
+}
+
+impl PreparingPreviewStopHandle {
+ pub fn cancel(&self) {
+ self.control.cancel.cancel();
+ }
+
+ pub fn terminal_error(&self) -> Option<PreparingPreviewError> {
+ self.control.state.borrow().terminal.clone()
+ }
+
+ pub async fn stop_and_wait(&self) -> PreparingPreviewExit {
+ self.cancel();
+ self.completion.clone().await
+ }
+}
+
+pub struct PreparingPreview {
+ stop: PreparingPreviewStopHandle,
+ requests: watch::Sender<Option<PreparingFrameRequest>>,
+ next_sequence: u64,
+ duration: f64,
+}
+
+impl PreparingPreview {
+ pub fn spawn(
+ input: PreparingPreviewInput,
+ options: PreparingPreviewOptions,
+ callback: PreparingPreviewCallback,
+ ) -> Result<Self, PreparingPreviewError> {
+ let duration = validate_input(&input)?;
+ let runtime = tokio::runtime::Handle::try_current()
+ .map_err(|error| PreparingPreviewError::InvalidInput(error.to_string()))?;
+ let (state, _) = watch::channel(PreviewState::default());
+ let control = Arc::new(PreviewControl {
+ cancel: CancellationToken::new(),
+ state,
+ });
+ let (requests, receiver) = watch::channel(None);
+ let task_control = control.clone();
+ let task = runtime.spawn(async move {
+ let mut workers = Vec::new();
+ let result = AssertUnwindSafe(run_preview(
+ input,
+ options,
+ callback,
+ receiver,
+ &task_control,
+ &mut workers,
+ ))
+ .catch_unwind()
+ .await;
+ let mut reason = match result {
+ Ok(Err(error)) => error,
+ Ok(Ok(())) => PreparingPreviewError::Cancelled,
+ Err(_) => PreparingPreviewError::Panicked,
+ };
+ if reason != PreparingPreviewError::Cancelled {
+ task_control.finish(reason.clone());
+ }
+ task_control.cancel.cancel();
+ for (_, handles) in &workers {
+ handles.cancel();
+ }
+ let mut exits = Vec::with_capacity(workers.len());
+ for (_, handles) in workers {
+ let exit = handles.stop_and_wait().await;
+ if reason == PreparingPreviewError::Cancelled
+ && let Some(error) = worker_exit_error(&exit)
+ {
+ reason = error;
+ }
+ exits.push(exit);
+ }
+ task_control.finish(reason.clone());
+ PreparingPreviewExit {
+ reason,
+ workers: exits,
+ }
+ });
+ let joined_control = control.clone();
+ let completion = async move {
+ match task.await {
+ Ok(exit) => exit,
+ Err(error) => {
+ let reason = PreparingPreviewError::TaskJoin(error.to_string());
+ joined_control.finish(reason.clone());
+ PreparingPreviewExit {
+ reason,
+ workers: Vec::new(),
+ }
+ }
+ }
+ }
+ .boxed()
+ .shared();
+ Ok(Self {
+ stop: PreparingPreviewStopHandle {
+ control,
+ completion,
+ },
+ requests,
+ next_sequence: 1,
+ duration,
+ })
+ }
+
+ pub fn stop_handle(&self) -> PreparingPreviewStopHandle {
+ self.stop.clone()
+ }
+
+ pub async fn wait_ready(&mut self) -> Result<PreparingPreviewReady, PreparingPreviewError> {
+ let mut guard = CancelReadiness(Some(self.stop.control.cancel.clone()));
+ let mut state = self.stop.control.state.subscribe();
+ loop {
+ self.stop.control.check()?;
+ if let Some(ready) = state.borrow_and_update().ready.clone() {
+ guard.0 = None;
+ return Ok(ready);
+ }
+ tokio::select! {
+ biased;
+ _ = self.stop.control.cancel.cancelled() => {
+ return Err(self.stop.control.check().err().unwrap_or(PreparingPreviewError::Cancelled));
+ }
+ changed = state.changed() => {
+ changed.map_err(|error| PreparingPreviewError::TaskJoin(error.to_string()))?;
+ }
+ }
+ }
+ }
+
+ pub fn request_frame(
+ &mut self,
+ frame_number: u32,
+ fps: u32,
+ resolution_base: XY<u32>,
+ ) -> Result<u64, PreparingPreviewError> {
+ self.stop.control.check()?;
+ validate_request(frame_number, fps, resolution_base, self.duration)?;
+ let next = self.next_sequence.checked_add(1).ok_or_else(|| {
+ PreparingPreviewError::InvalidInput("Frame request sequence exhausted".into())
+ })?;
+ let request = PreparingFrameRequest {
+ sequence: self.next_sequence,
+ frame_number,
+ fps,
+ resolution_base,
+ };
+ self.requests
+ .send(Some(request))
+ .map_err(|_| PreparingPreviewError::Cancelled)?;
+ self.next_sequence = next;
+ Ok(request.sequence)
+ }
+}
+
+impl Drop for PreparingPreview {
+ fn drop(&mut self) {
+ self.stop.cancel();
+ }
+}
+
+struct CancelReadiness(Option<CancellationToken>);
+
+impl Drop for CancelReadiness {
+ fn drop(&mut self) {
+ if let Some(cancel) = &self.0 {
+ cancel.cancel();
+ }
+ }
+}
+
+fn validate_request(
+ frame_number: u32,
+ fps: u32,
+ resolution: XY<u32>,
+ duration: f64,
+) -> Result<(), PreparingPreviewError> {
+ if fps == 0
+ || fps > 240
+ || resolution.x < 2
+ || resolution.y < 2
+ || resolution.x > 8192
+ || resolution.y > 8192
+ || !duration.is_finite()
+ || duration <= 0.0
+ || f64::from(frame_number) / f64::from(fps) >= duration
+ {
+ Err(PreparingPreviewError::InvalidInput(
+ "Frame, FPS, or output dimensions are outside preview limits".into(),
+ ))
+ } else {
+ Ok(())
+ }
+}
+
+pub(crate) fn validate_input(input: &PreparingPreviewInput) -> Result<f64, PreparingPreviewError> {
+ let invalid = |message: &str| PreparingPreviewError::InvalidInput(message.into());
+ let Some(meta) = input.recording_meta.studio_meta() else {
+ return Err(invalid("Studio metadata is required"));
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = meta else {
+ return Err(invalid("Indexed stopped segments are required"));
+ };
+ let count = input.segments.len();
+ if count == 0 || count > 1024 || count != inner.segments.len() {
+ return Err(invalid("Stopped segment layout does not match"));
+ }
+ let project = &input.project;
+ project
+ .validate()
+ .map_err(|error| invalid(&error.to_string()))?;
+ let Some(timeline) = &project.timeline else {
+ return Err(invalid("Resolved stopped timeline is required"));
+ };
+ if timeline.segments.len() != count
+ || input.segments.iter().enumerate().any(|(index, segment)| {
+ segment.video.segment_index() != index
+ || !segment.video.matches_metadata(meta)
+ || timeline.segments[index].recording_clip as usize != index
+ || timeline.segments[index].start != 0.0
+ || timeline.segments[index].timescale != 1.0
+ || !timeline.segments[index].end.is_finite()
+ || timeline.segments[index].end <= 0.0
+ || timeline.segments[index].name.is_some()
+ || timeline.segments[index].speed_audio_mode.is_some()
+ })
+ {
+ return Err(invalid("Preparing requires the unchanged stopped timeline"));
+ }
+ if !matches!(
+ project.background.source,
+ BackgroundSource::Color { .. }
+ | BackgroundSource::Gradient { .. }
+ | BackgroundSource::AnimatedGradient { .. }
+ ) || project
+ .background
+ .frame
+ .as_ref()
+ .is_some_and(|frame| frame.style != FrameStyle::None)
+ || project.captions.is_some()
+ || project.camera.background_blur.is_active()
+ || project.keyboard.is_some()
+ || !project.annotations.is_empty()
+ || !project.hidden_text_segments.is_empty()
+ || !project.overlay_order.is_empty()
+ || !timeline.transitions.is_empty()
+ || !timeline.scene_segments.is_empty()
+ || !timeline.mask_segments.is_empty()
+ || !timeline.text_segments.is_empty()
+ || !timeline.caption_segments.is_empty()
+ || !timeline.keyboard_segments.is_empty()
+ || !timeline.audio_segments.is_empty()
+ || !timeline.style_segments.is_empty()
+ || !timeline.image_segments.is_empty()
+ || !timeline.camera3d_segments.is_empty()
+ {
+ return Err(invalid("Presentation requires ordinary project loading"));
+ }
+ if project.clips.len() != count {
+ return Err(invalid("Every clip requires resolved calibration offsets"));
+ }
+ let mut seen = vec![false; count];
+ for clip in &project.clips {
+ let Some(seen) = seen.get_mut(clip.index as usize) else {
+ return Err(invalid("Clip index is outside the stopped timeline"));
+ };
+ if *seen
+ || !clip.offsets.camera.is_finite()
+ || !clip.offsets.mic.is_finite()
+ || !clip.offsets.system_audio.is_finite()
+ {
+ return Err(invalid("Clip offsets must be unique and finite"));
+ }
+ *seen = true;
+ }
+ let duration = timeline.duration();
+ if !duration.is_finite() || duration <= 0.0 {
+ return Err(invalid("Stopped duration must be finite and positive"));
+ }
+ Ok(duration)
+}
+
+type WorkerRegistry = Vec<(usize, ManagedSegmentStopHandles)>;
+
+struct OpenSegment {
+ index: usize,
+ decoder: ManagedRecordingSegmentDecoders,
+ status: ManagedSegmentDecoderStatus,
+}
+
+struct PreviewDecoders {
+ inputs: Vec<PreparingPreviewSegment>,
+ opened: VecDeque<OpenSegment>,
+ use_hardware: bool,
+}
+
+impl PreviewDecoders {
+ fn check(&self) -> Result<(), PreparingPreviewError> {
+ for entry in &self.opened {
+ if let Some(error) = entry.decoder.terminal_error() {
+ return Err(PreparingPreviewError::Media(error));
+ }
+ }
+ Ok(())
+ }
+
+ async fn failed(&self) -> PreparingPreviewError {
+ let (error, _, _) = futures::future::select_all(
+ self.opened
+ .iter()
+ .map(|entry| entry.decoder.wait_for_terminal().boxed()),
+ )
+ .await;
+ PreparingPreviewError::Media(error)
+ }
+
+ async fn ensure(
+ &mut self,
+ index: usize,
+ control: &PreviewControl,
+ registry: &mut WorkerRegistry,
+ ) -> Result<&OpenSegment, PreparingPreviewError> {
+ control.check()?;
+ self.check()?;
+ if let Some(position) = self.opened.iter().position(|entry| entry.index == index) {
+ let segment = self
+ .opened
+ .remove(position)
+ .expect("Located segment is present");
+ self.opened.push_back(segment);
+ } else {
+ if self.opened.len() == MAX_OPEN_SEGMENTS {
+ let evicted = self.opened.pop_front().expect("Cache is full");
+ let exit = evicted.decoder.stop_and_wait().await;
+ if let Some(error) = worker_exit_error(&exit) {
+ return Err(error);
+ }
+ registry.retain(|(entry, _)| *entry != evicted.index);
+ drop(evicted);
+ control.check()?;
+ }
+ let mut decoder = ManagedRecordingSegmentDecoders::spawn(
+ self.inputs[index].video.clone(),
+ self.use_hardware,
+ );
+ registry.push((index, decoder.stop_handles()));
+ let status = tokio::select! {
+ biased;
+ _ = control.cancel.cancelled() => return Err(PreparingPreviewError::Cancelled),
+ result = decoder.wait_ready() => result.map_err(PreparingPreviewError::Media)?,
+ };
+ self.opened.push_back(OpenSegment {
+ index,
+ decoder,
+ status,
+ });
+ }
+ control.check()?;
+ Ok(self.opened.back().expect("Requested segment is cached"))
+ }
+}
+
+fn is_current(
+ receiver: &watch::Receiver<Option<PreparingFrameRequest>>,
+ request: PreparingFrameRequest,
+) -> bool {
+ receiver
+ .borrow()
+ .as_ref()
+ .is_some_and(|latest| latest.sequence == request.sequence)
+}
+
+async fn run_preview(
+ input: PreparingPreviewInput,
+ options: PreparingPreviewOptions,
+ mut callback: PreparingPreviewCallback,
+ mut requests: watch::Receiver<Option<PreparingFrameRequest>>,
+ control: &PreviewControl,
+ registry: &mut WorkerRegistry,
+) -> Result<(), PreparingPreviewError> {
+ control.check()?;
+ let PreparingPreviewInput {
+ recording_meta,
+ project,
+ segments,
+ cursor_assets,
+ } = input;
+ let metadata = recording_meta
+ .studio_meta()
+ .expect("Validated Studio metadata")
+ .clone();
+ let duration = project
+ .timeline
+ .as_ref()
+ .expect("Validated timeline")
+ .duration();
+ let mut decoders = PreviewDecoders {
+ inputs: segments,
+ opened: VecDeque::new(),
+ use_hardware: options.use_hardware_decoding,
+ };
+ let first = decoders.ensure(0, control, registry).await?.status.clone();
+ let screen_size = XY::new(first.display.video_width, first.display.video_height);
+ let camera_size = first
+ .camera
+ .as_ref()
+ .map(|camera| XY::new(camera.video_width, camera.video_height));
+ let constants = RenderVideoConstants::new_with_options(
+ RenderOptions {
+ screen_size,
+ camera_size,
+ preserve_screen_alpha: false,
+ },
+ recording_meta,
+ metadata,
+ )
+ .await
+ .map_err(|error| PreparingPreviewError::Render(error.to_string()))?
+ .with_frozen_recorded_cursors(cursor_assets);
+ control.check()?;
+ let mut layers = RendererLayers::new_for_preparing_preview(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ &project,
+ )
+ .map_err(|error| PreparingPreviewError::Render(error.to_string()))?;
+ control.check()?;
+ layers.preload_cursor_assets(
+ &constants,
+ project.cursor.use_svg,
+ project.cursor.cursor_type(),
+ );
+ check_cursor_error(&constants)?;
+ control.check()?;
+ let mut renderer = FrameRenderer::new(&constants);
+ let mut cursor_cache = PreviewCursorCache::default();
+ let mut zoom_cache = VecDeque::new();
+ control.state.send_modify(|state| {
+ state.ready = Some(PreparingPreviewReady {
+ screen_size,
+ camera_size,
+ duration,
+ })
+ });
+ 'requests: loop {
+ control.check()?;
+ decoders.check()?;
+ let request = *requests.borrow_and_update();
+ let Some(request) = request else {
+ tokio::select! {
+ biased;
+ _ = control.cancel.cancelled() => return Err(PreparingPreviewError::Cancelled),
+ error = decoders.failed() => return Err(error),
+ changed = requests.changed() => {
+ changed.map_err(|_| PreparingPreviewError::Cancelled)?;
+ continue;
+ }
+ }
+ };
+ let frame_time = f64::from(request.frame_number) / f64::from(request.fps);
+ let (segment_time, timeline_segment) =
+ project.get_segment_time(frame_time).ok_or_else(|| {
+ PreparingPreviewError::InvalidInput(
+ "Requested frame is outside the stopped timeline".into(),
+ )
+ })?;
+ let index = timeline_segment.recording_clip as usize;
+ let offsets = project
+ .clips
+ .iter()
+ .find(|clip| clip.index == timeline_segment.recording_clip)
+ .expect("Validated complete clip offsets")
+ .offsets;
+ let cursor = decoders.inputs[index].cursor.clone();
+ for attempt in 0..PREVIEW_RENDER_MAX_ATTEMPTS {
+ let segment = decoders.ensure(index, control, registry).await?;
+ let frames = tokio::select! {
+ biased;
+ _ = control.cancel.cancelled() => return Err(PreparingPreviewError::Cancelled),
+ result = async {
+ if attempt == 0 {
+ segment.decoder.get_frames_initial(segment_time as f32, project.requires_camera(), true, offsets).await
+ } else {
+ segment.decoder.get_frames(segment_time as f32, project.requires_camera(), true, offsets).await
+ }
+ } => {
+ result.map_err(PreparingPreviewError::Media)?
+ }
+ };
+ control.check()?;
+ decoders.check()?;
+ if !is_current(&requests, request) {
+ continue 'requests;
+ }
+ let cursor_timeline =
+ cursor_cache.get(timeline_segment.recording_clip, &cursor, &project);
+ control.check()?;
+ let zoom = cached_zoom(
+ &mut zoom_cache,
+ timeline_segment.recording_clip,
+ &project,
+ &cursor,
+ duration,
+ screen_size,
+ );
+ zoom.ensure_precomputed_until((request.frame_number as f32 + 1.0) / request.fps as f32);
+ control.check()?;
+ if !is_current(&requests, request) {
+ continue 'requests;
+ }
+ let uniforms = if let Some(cursor_timeline) = &cursor_timeline {
+ ProjectUniforms::new_with_precomputed_cursor(
+ &constants,
+ &project,
+ request.frame_number,
+ request.fps,
+ request.resolution_base,
+ &cursor,
+ &frames,
+ duration,
+ zoom,
+ cursor_timeline,
+ )
+ } else {
+ ProjectUniforms::new(
+ &constants,
+ &project,
+ request.frame_number,
+ request.fps,
+ request.resolution_base,
+ &cursor,
+ &frames,
+ duration,
+ zoom,
+ )
+ };
+ let layout = uniforms.frame_layout();
+ let output = match options.frame_format {
+ EditorFrameFormat::Rgba => renderer
+ .render_immediate(frames, uniforms, &cursor, true, &mut layers)
+ .await
+ .map(EditorFrameOutput::Rgba),
+ #[cfg(target_os = "macos")]
+ EditorFrameFormat::BgraSurface => renderer
+ .render_immediate_bgra_surface(frames, uniforms, &cursor, true, &mut layers)
+ .await
+ .map(EditorFrameOutput::Surface),
+ };
+ check_cursor_error(&constants)?;
+ control.check()?;
+ decoders.check()?;
+ if !is_current(&requests, request) {
+ continue 'requests;
+ }
+ let output = match output {
+ Ok(output) => output,
+ Err(error) if attempt + 1 < PREVIEW_RENDER_MAX_ATTEMPTS => {
+ tracing::warn!(%error, attempt, "Retrying preparing preview render");
+ tokio::select! {
+ biased;
+ _ = control.cancel.cancelled() => return Err(PreparingPreviewError::Cancelled),
+ error = decoders.failed() => return Err(error),
+ changed = requests.changed() => {
+ changed.map_err(|_| PreparingPreviewError::Cancelled)?;
+ continue 'requests;
+ }
+ _ = tokio::time::sleep(std::time::Duration::from_millis(PREVIEW_RENDER_RETRY_DELAY_MS)) => {}
+ }
+ continue;
+ }
+ Err(error) => return Err(PreparingPreviewError::Render(error.to_string())),
+ };
+ validate_output(&output, request, layout)?;
+ callback(request, output, layout);
+ control.check()?;
+ if !is_current(&requests, request) {
+ continue 'requests;
+ }
+ break;
+ }
+ tokio::select! {
+ biased;
+ _ = control.cancel.cancelled() => return Err(PreparingPreviewError::Cancelled),
+ error = decoders.failed() => return Err(error),
+ changed = requests.changed() => {
+ changed.map_err(|_| PreparingPreviewError::Cancelled)?;
+ }
+ }
+ }
+}
+
+fn worker_exit_error(exit: &ManagedSegmentVideoExit) -> Option<PreparingPreviewError> {
+ if let Some(display) = &exit.display
+ && display.terminal != ManagedVideoError::Cancelled
+ {
+ return Some(PreparingPreviewError::Media(
+ ManagedSegmentVideoError::Display(display.terminal.clone()),
+ ));
+ }
+ if let Some(camera) = &exit.camera
+ && camera.terminal != ManagedVideoError::Cancelled
+ {
+ return Some(PreparingPreviewError::Media(
+ ManagedSegmentVideoError::Camera(camera.terminal.clone()),
+ ));
+ }
+ None
+}
+
+fn check_cursor_error(constants: &RenderVideoConstants) -> Result<(), PreparingPreviewError> {
+ if let Some(error) = constants.frozen_cursor_error() {
+ Err(PreparingPreviewError::Render(error.to_string()))
+ } else {
+ Ok(())
+ }
+}
+
+fn cached_zoom<'a>(
+ cache: &'a mut VecDeque<(u32, ZoomTransformTimeline)>,
+ clip: u32,
+ project: &ProjectConfiguration,
+ cursor: &CursorEvents,
+ duration: f64,
+ screen_size: XY<u32>,
+) -> &'a mut ZoomTransformTimeline {
+ if let Some(position) = cache.iter().position(|(index, _)| *index == clip) {
+ let entry = cache
+ .remove(position)
+ .expect("Located zoom entry is present");
+ cache.push_back(entry);
+ } else {
+ if cache.len() == MAX_OPEN_SEGMENTS {
+ cache.pop_front();
+ }
+ cache.push_back((
+ clip,
+ ZoomTransformTimeline::from_project_for_clip(
+ project,
+ cursor,
+ duration,
+ screen_size,
+ clip,
+ ),
+ ));
+ }
+ &mut cache.back_mut().expect("Requested zoom entry is cached").1
+}
+
+fn validate_output(
+ output: &EditorFrameOutput,
+ request: PreparingFrameRequest,
+ layout: FrameLayout,
+) -> Result<(), PreparingPreviewError> {
+ let (number, width, height) = match output {
+ EditorFrameOutput::Rgba(frame) => (frame.frame_number, frame.width, frame.height),
+ EditorFrameOutput::Nv12(frame) => (frame.frame_number, frame.width, frame.height),
+ #[cfg(target_os = "macos")]
+ EditorFrameOutput::Surface(frame) => (frame.frame_number, frame.width, frame.height),
+ };
+ if number != request.frame_number || [width, height] != layout.output_size {
+ Err(PreparingPreviewError::Render(
+ "Rendered frame does not match the requested frame and layout".into(),
+ ))
+ } else {
+ Ok(())
+ }
+}
diff --git a/crates/editor/src/preparing_preview/native_tests.rs b/crates/editor/src/preparing_preview/native_tests.rs
new file mode 100644
index 000000000..81044c058
--- /dev/null
+++ b/crates/editor/src/preparing_preview/native_tests.rs
@@ -0,0 +1,1423 @@
+use super::*;
+use cap_enc_ffmpeg::{
+ RelocatableSource,
+ h264::DEFAULT_KEYFRAME_INTERVAL_SECS,
+ segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig},
+};
+use cap_project::{ClipConfiguration, ClipOffsets, CursorMeta, TimelineConfiguration};
+use cap_rendering::{
+ ManagedVideoTrackInput, RecordingSegmentDecoders, RenderedFrame, SegmentVideoPaths,
+};
+use std::{
+ io::Cursor,
+ path::{Path, PathBuf},
+ sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::Duration,
+};
+
+struct SourceLease {
+ location: Arc<Mutex<PathBuf>>,
+ after_close: PathBuf,
+ released: Arc<AtomicBool>,
+ rename_succeeded: Arc<AtomicBool>,
+}
+
+impl Drop for SourceLease {
+ fn drop(&mut self) {
+ let location = self.location.lock().unwrap();
+ self.rename_succeeded.store(
+ std::fs::rename(location.as_path(), &self.after_close).is_ok(),
+ Ordering::Release,
+ );
+ self.released.store(true, Ordering::Release);
+ }
+}
+
+struct Fixture {
+ directory: tempfile::TempDir,
+ source: RelocatableSource,
+ location: Arc<Mutex<PathBuf>>,
+ released: Arc<AtomicBool>,
+ rename_succeeded: Arc<AtomicBool>,
+ metadata: RecordingMeta,
+ reference_metadata: RecordingMeta,
+ display: Vec<PathBuf>,
+ camera: Vec<PathBuf>,
+ project: ProjectConfiguration,
+ cursor: Arc<CursorEvents>,
+ assets: FrozenRecordedCursorAssets,
+}
+
+fn encode_track(
+ root: &Path,
+ track: &str,
+ width: u32,
+ height: u32,
+ fps: u32,
+ mut noise: u32,
+) -> Vec<PathBuf> {
+ let directory = root.join(track);
+ let mut encoder = SegmentedVideoEncoder::init(
+ directory.clone(),
+ cap_media_info::VideoInfo {
+ pixel_format: cap_media_info::Pixel::NV12,
+ width,
+ height,
+ time_base: ffmpeg::Rational(1, 1_000_000),
+ frame_rate: ffmpeg::Rational(fps as i32, 1),
+ },
+ SegmentedVideoEncoderConfig {
+ segment_duration: Duration::from_secs(1),
+ bpp: 4.0,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let frame_count = u64::from(fps) * u64::from(DEFAULT_KEYFRAME_INTERVAL_SECS) * 3;
+ for index in 0..frame_count {
+ let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, width, height);
+ for byte in frame.data_mut(0) {
+ noise ^= noise << 13;
+ noise ^= noise >> 17;
+ noise ^= noise << 5;
+ *byte = (noise % 220 + 16) as u8;
+ }
+ frame.data_mut(1).fill(128);
+ encoder
+ .queue_frame(
+ frame,
+ Duration::from_micros(index * 1_000_000 / u64::from(fps)),
+ )
+ .unwrap();
+ }
+ encoder.finish().unwrap();
+ let mut paths = std::fs::read_dir(&directory)
+ .unwrap()
+ .map(|entry| entry.unwrap().path())
+ .filter(|path| path.extension().is_some_and(|extension| extension == "m4s"))
+ .map(|path| PathBuf::from(track).join(path.file_name().unwrap()))
+ .collect::<Vec<_>>();
+ paths.sort();
+ assert!(paths.len() >= 3);
+ paths.insert(0, PathBuf::from(track).join("init.mp4"));
+ paths
+}
+
+fn finalize_track(root: &Path, paths: &[PathBuf], output: &Path) {
+ cap_enc_ffmpeg::remux::concatenate_m4s_segments_with_init(
+ &root.join(&paths[0]),
+ &paths[1..]
+ .iter()
+ .map(|path| root.join(path))
+ .collect::<Vec<_>>(),
+ output,
+ )
+ .unwrap();
+ assert!(cap_enc_ffmpeg::remux::probe_video_can_decode(output).unwrap());
+}
+
+fn fixture(svg: bool) -> Fixture {
+ ffmpeg::init().unwrap();
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let reference = directory.path().join("reference");
+ std::fs::create_dir(&original).unwrap();
+ std::fs::create_dir(&reference).unwrap();
+ let display = encode_track(&original, "display", 160, 120, 30, 123456789);
+ let camera = encode_track(&original, "camera", 80, 80, 24, 987654321);
+ finalize_track(&original, &display, &reference.join("display.mp4"));
+ finalize_track(&original, &camera, &reference.join("camera.mp4"));
+ let mut image = image::RgbaImage::new(16, 24);
+ for (x, y, pixel) in image.enumerate_pixels_mut() {
+ *pixel = image::Rgba([255, (x * 13) as u8, (y * 9) as u8, 220]);
+ }
+ let mut png = Cursor::new(Vec::new());
+ image.write_to(&mut png, image::ImageFormat::Png).unwrap();
+ let bytes: Arc<[u8]> = png.into_inner().into();
+ std::fs::write(reference.join("cursor.png"), &bytes).unwrap();
+ let cursor_meta: CursorMeta = serde_json::from_value(serde_json::json!({
+ "imagePath": "cursor.png",
+ "hotspot": {"x": 0.25, "y": 0.125},
+ "shape": svg.then_some("MacOS|Arrow")
+ }))
+ .unwrap();
+ let mut metadata: RecordingMeta = serde_json::from_value(serde_json::json!({
+ "platform": "MacOS", "pretty_name": "Preparing preview native test", "sharing": null,
+ "segments": [{
+ "display": {"path": "display", "fps": 30, "start_time": 0.0},
+ "camera": {"path": "camera", "fps": 24, "start_time": 0.125},
+ "mic": {"path": "mic.aac", "start_time": 0.25}
+ }],
+ "cursors": {"arrow": cursor_meta},
+ "status": {"status": "NeedsRemux"}
+ }))
+ .unwrap();
+ metadata.project_path = original.clone();
+ let mut reference_metadata = metadata.clone();
+ reference_metadata.project_path = reference;
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut reference_metadata.inner else {
+ panic!("Studio metadata expected");
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!("Indexed metadata expected");
+ };
+ inner.segments[0].display.path = "display.mp4".into();
+ inner.segments[0].camera.as_mut().unwrap().path = "camera.mp4".into();
+ inner.status = Some(cap_project::StudioRecordingStatus::Complete);
+ let mut project = ProjectConfiguration {
+ timeline: Some(
+ serde_json::from_value::<TimelineConfiguration>(serde_json::json!({
+ "segments": [{"recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 3.25}],
+ "zoomSegments": [{"start": 0.3, "end": 2.7, "amount": 1.6, "mode": "auto"}]
+ }))
+ .unwrap(),
+ ),
+ clips: vec![ClipConfiguration {
+ index: 0,
+ offsets: ClipOffsets {
+ camera: 0.25,
+ mic: 0.03125,
+ system_audio: 0.0,
+ },
+ offsets_auto_calculated: true,
+ }],
+ ..Default::default()
+ };
+ project.cursor.use_svg = svg;
+ project.cursor.hide_when_idle = false;
+ project.cursor.size = 150;
+ project.cursor.motion_blur = 0.0;
+ project.background.padding = 8.0;
+ project.background.shadow = 0.0;
+ project.camera.hide = false;
+ project.camera.size = 30.0;
+ project.camera.shadow = 0.0;
+ let cursor = Arc::new(CursorEvents {
+ moves: [
+ (0.0, 0.1, 0.15),
+ (300.0, 0.2, 0.3),
+ (600.0, 0.7, 0.25),
+ (1100.0, 0.8, 0.7),
+ (1800.0, 0.4, 0.6),
+ (2600.0, 0.2, 0.3),
+ (3500.0, 0.8, 0.8),
+ ]
+ .into_iter()
+ .map(|(time_ms, x, y)| cap_project::CursorMoveEvent {
+ active_modifiers: Vec::new(),
+ cursor_id: "arrow".into(),
+ time_ms,
+ x,
+ y,
+ })
+ .collect(),
+ clicks: Vec::new(),
+ });
+ let assets = FrozenRecordedCursorAssets::new([("arrow".into(), cursor_meta, bytes)]).unwrap();
+ let location = Arc::new(Mutex::new(original.clone()));
+ let released = Arc::new(AtomicBool::new(false));
+ let rename_succeeded = Arc::new(AtomicBool::new(false));
+ let source = RelocatableSource::new_with_owner(
+ original,
+ Arc::new(SourceLease {
+ location: location.clone(),
+ after_close: directory.path().join("released-after-native-join"),
+ released: released.clone(),
+ rename_succeeded: rename_succeeded.clone(),
+ }),
+ )
+ .unwrap();
+ Fixture {
+ directory,
+ source,
+ location,
+ released,
+ rename_succeeded,
+ metadata,
+ reference_metadata,
+ display,
+ camera,
+ project,
+ cursor,
+ assets,
+ }
+}
+
+impl Fixture {
+ fn input(&self) -> PreparingPreviewInput {
+ let metadata = self.metadata.studio_meta().unwrap();
+ PreparingPreviewInput {
+ recording_meta: self.metadata.clone(),
+ project: self.project.clone(),
+ segments: (0..self.project.clips.len())
+ .map(|index| PreparingPreviewSegment {
+ video: ManagedSegmentVideoInput::new(
+ index,
+ metadata,
+ ManagedVideoTrackInput::new(self.source.clone(), self.display.clone())
+ .unwrap(),
+ Some(
+ ManagedVideoTrackInput::new(self.source.clone(), self.camera.clone())
+ .unwrap(),
+ ),
+ )
+ .unwrap(),
+ cursor: self.cursor.clone(),
+ })
+ .collect(),
+ cursor_assets: self.assets.clone(),
+ }
+ }
+
+ fn relocate(&self, name: &str) {
+ let destination = self.directory.path().join(name);
+ self.source.relocate(destination.clone()).unwrap();
+ *self.location.lock().unwrap() = destination;
+ }
+}
+
+fn visible_rgba(frame: &RenderedFrame) -> Vec<u8> {
+ let row_bytes = (frame.width as usize).checked_mul(4).unwrap();
+ let stride = frame.padded_bytes_per_row as usize;
+ let rows = frame.height as usize;
+ assert!(row_bytes > 0 && rows > 0);
+ assert!(stride >= row_bytes);
+ assert_eq!(frame.data.len(), stride.checked_mul(rows).unwrap());
+ frame
+ .data
+ .chunks_exact(frame.padded_bytes_per_row as usize)
+ .take(frame.height as usize)
+ .flat_map(|row| row[..frame.width as usize * 4].iter().copied())
+ .collect()
+}
+
+async fn ordinary_composed_frames(
+ fixture: &Fixture,
+ frame_numbers: &[u32],
+ force_ffmpeg: bool,
+) -> Vec<(RenderedFrame, FrameLayout)> {
+ let metadata = &fixture.reference_metadata;
+ let studio = metadata.studio_meta().unwrap();
+ let mut decoders = Vec::new();
+ for index in 0..fixture.project.clips.len() {
+ decoders.push(
+ RecordingSegmentDecoders::new(
+ metadata,
+ studio,
+ SegmentVideoPaths {
+ display: metadata.project_path.join("display.mp4"),
+ camera: Some(metadata.project_path.join("camera.mp4")),
+ },
+ index,
+ force_ffmpeg,
+ )
+ .await
+ .unwrap(),
+ );
+ }
+ #[cfg(target_os = "macos")]
+ if !force_ffmpeg {
+ for decoder in &decoders {
+ assert_eq!(
+ decoder.screen_decoder_status().decoder_type,
+ cap_rendering::decoder::DecoderType::AVAssetReader,
+ );
+ assert_eq!(
+ decoder.camera_decoder_status().unwrap().decoder_type,
+ cap_rendering::decoder::DecoderType::AVAssetReader,
+ );
+ }
+ }
+ let duration = fixture.project.timeline.as_ref().unwrap().duration();
+ let constants = RenderVideoConstants::new_with_options(
+ RenderOptions {
+ screen_size: XY::new(160, 120),
+ camera_size: Some(XY::new(80, 80)),
+ preserve_screen_alpha: false,
+ },
+ metadata.clone(),
+ studio.clone(),
+ )
+ .await
+ .unwrap();
+ let mut layers = RendererLayers::new_with_options(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ );
+ layers.preload_cursor_assets(
+ &constants,
+ fixture.project.cursor.use_svg,
+ fixture.project.cursor.cursor_type(),
+ );
+ let mut renderer = FrameRenderer::new(&constants);
+ let mut cache = PreviewCursorCache::default();
+ let mut result = Vec::new();
+ let mut cursor_positions = Vec::new();
+ let mut zoom_amounts = Vec::new();
+ for &frame_number in frame_numbers {
+ let time = f64::from(frame_number) / 30.0;
+ let (segment_time, segment) = fixture.project.get_segment_time(time).unwrap();
+ let frames = decoders[segment.recording_clip as usize]
+ .get_frames_initial(
+ segment_time as f32,
+ true,
+ true,
+ fixture.project.clips[segment.recording_clip as usize].offsets,
+ )
+ .await
+ .unwrap();
+ let timeline = cache.get(segment.recording_clip, &fixture.cursor, &fixture.project);
+ let mut zoom = ZoomTransformTimeline::from_project_for_clip(
+ &fixture.project,
+ &fixture.cursor,
+ duration,
+ constants.options.screen_size,
+ segment.recording_clip,
+ );
+ zoom.ensure_precomputed_until((frame_number as f32 + 1.0) / 30.0);
+ let uniforms = match timeline {
+ Some(timeline) => ProjectUniforms::new_with_precomputed_cursor(
+ &constants,
+ &fixture.project,
+ frame_number,
+ 30,
+ XY::new(320, 240),
+ &fixture.cursor,
+ &frames,
+ duration,
+ &zoom,
+ &timeline,
+ ),
+ None => ProjectUniforms::new(
+ &constants,
+ &fixture.project,
+ frame_number,
+ 30,
+ XY::new(320, 240),
+ &fixture.cursor,
+ &frames,
+ duration,
+ &zoom,
+ ),
+ };
+ zoom_amounts.push(uniforms.zoom.display_amount());
+ cursor_positions.push(
+ uniforms
+ .prev_cursor
+ .as_ref()
+ .expect("The recorded cursor must have a preceding sample")
+ .position
+ .coord,
+ );
+ let layout = uniforms.frame_layout();
+ assert!(layout.camera.is_some());
+ result.push((
+ renderer
+ .render_immediate(frames, uniforms, &fixture.cursor, true, &mut layers)
+ .await
+ .unwrap(),
+ layout,
+ ));
+ }
+ assert!(cursor_positions.windows(2).any(|pair| pair[0] != pair[1]));
+ assert!(
+ zoom_amounts
+ .iter()
+ .any(|amount| (amount - 1.0).abs() > 0.01)
+ );
+ drop(decoders);
+ result
+}
+
+async fn composed_parity(fixture: Fixture, frames: &[u32]) {
+ composed_parity_with_reference(fixture, frames, true, EditorFrameFormat::Rgba).await;
+}
+
+#[tokio::test]
+async fn native_preparing_playback_seeks_match_ordinary_and_handoff_joins_sources() {
+ let mut fixture = fixture(false);
+ for metadata in [&mut fixture.metadata, &mut fixture.reference_metadata] {
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut metadata.inner else {
+ panic!("Studio metadata expected");
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!("Indexed metadata expected");
+ };
+ inner.segments[0].mic = None;
+ }
+ let expected = ordinary_composed_frames(&fixture, &[0, 45], true).await;
+ let (frames, mut received) = tokio::sync::mpsc::unbounded_channel();
+ let session = crate::PreparingPlaybackSession::spawn(
+ fixture.input(),
+ vec![crate::PreparingAudioSegmentInput {
+ mic: None,
+ system_audio: None,
+ timing_repair: Default::default(),
+ }],
+ crate::PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions::default(),
+ fps: 30,
+ resolution: XY::new(320, 240),
+ },
+ Arc::new(crate::AudioOutput::new_headless(Box::new(|_, _| {}))),
+ Box::new(move |request, output, layout| {
+ let EditorFrameOutput::Rgba(frame) = output else {
+ panic!("Expected RGBA frame");
+ };
+ let _ = frames.send((request, frame, layout));
+ }),
+ )
+ .unwrap();
+ let controller = session.controller();
+ let stop = session.stop_handle();
+ let mut updates = session.updates();
+ tokio::time::timeout(Duration::from_secs(30), async {
+ loop {
+ if updates.borrow_and_update().progress.preview_available {
+ break;
+ }
+ updates.changed().await.unwrap();
+ }
+ })
+ .await
+ .unwrap();
+ assert_eq!(updates.borrow().progress.playable_until, 3.25);
+ for (index, (expected, expected_layout)) in expected.into_iter().enumerate() {
+ if index == 1 {
+ fixture.relocate("retained-during-playback");
+ tokio::time::timeout(Duration::from_secs(15), controller.seek(1.5))
+ .await
+ .unwrap()
+ .unwrap();
+ }
+ let (request, actual, layout) =
+ tokio::time::timeout(Duration::from_secs(15), received.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(request.frame_number, if index == 0 { 0 } else { 45 });
+ assert_eq!(layout, expected_layout);
+ assert_eq!(visible_rgba(&actual), visible_rgba(&expected));
+ }
+ let seeks = [0.3, 1.0, 2.0, 1.1, 1.5].map(|time| controller.seek(time));
+ let results = tokio::time::timeout(Duration::from_secs(15), futures::future::join_all(seeks))
+ .await
+ .unwrap();
+ assert!(results.last().unwrap().is_ok());
+ let mut last_seek_frame = None;
+ while let Ok((request, _, _)) = received.try_recv() {
+ last_seek_frame = Some(request.frame_number);
+ }
+ assert_eq!(last_seek_frame, Some(45));
+ controller.set_playing(true).await.unwrap();
+ let (request, _, _) = tokio::time::timeout(Duration::from_secs(15), received.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(request.frame_number >= 45);
+ controller.set_playing(false).await.unwrap();
+ let paused = updates.borrow().clone();
+ assert!(!paused.playback.playing);
+ tokio::time::sleep(Duration::from_millis(80)).await;
+ assert_eq!(
+ updates.borrow().playback.playhead_seconds,
+ paused.playback.playhead_seconds
+ );
+ controller.set_playing(true).await.unwrap();
+ drop(fixture.source);
+ let exit = tokio::time::timeout(Duration::from_secs(15), stop.stop_and_wait())
+ .await
+ .unwrap();
+ assert!(exit.error.is_none(), "{:?}", exit.error);
+ assert_eq!(
+ exit.snapshot.progress.phase,
+ crate::PreparingEditorPhase::Handoff
+ );
+ assert!(exit.snapshot.playback.playing);
+ assert!(exit.snapshot.playback.playhead_seconds >= 1.5);
+ assert!(exit.snapshot.playback.playhead_seconds < 3.25);
+ let preview = exit.preview.unwrap();
+ assert_eq!(preview.reason, PreparingPreviewError::Cancelled);
+ assert_eq!(preview.workers.len(), 1);
+ assert!(fixture.released.load(Ordering::Acquire));
+ assert!(fixture.rename_succeeded.load(Ordering::Acquire));
+}
+
+#[tokio::test]
+async fn native_preparing_image_does_not_enable_playback_with_unavailable_declared_audio() {
+ let fixture = fixture(false);
+ let session = crate::PreparingPlaybackSession::spawn(
+ fixture.input(),
+ vec![crate::PreparingAudioSegmentInput {
+ mic: None,
+ system_audio: None,
+ timing_repair: Default::default(),
+ }],
+ crate::PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions::default(),
+ fps: 30,
+ resolution: XY::new(320, 240),
+ },
+ Arc::new(crate::AudioOutput::new_headless(Box::new(|_, _| {}))),
+ Box::new(|_, _, _| {}),
+ )
+ .unwrap();
+ let mut updates = session.updates();
+ tokio::time::timeout(Duration::from_secs(30), async {
+ loop {
+ if updates.borrow_and_update().progress.preview_available {
+ break;
+ }
+ updates.changed().await.unwrap();
+ }
+ })
+ .await
+ .unwrap();
+ assert_eq!(updates.borrow().progress.playable_until, 0.0);
+ assert!(session.controller().seek(0.0).await.is_err());
+ assert!(session.controller().set_playing(true).await.is_err());
+ let stop = session.stop_handle();
+ drop(fixture.source);
+ drop(session);
+ let exit = tokio::time::timeout(Duration::from_secs(15), stop.stop_and_wait())
+ .await
+ .unwrap();
+ assert!(exit.error.is_none(), "{:?}", exit.error);
+ assert!(!exit.snapshot.playback.playing);
+ assert!(fixture.released.load(Ordering::Acquire));
+ assert!(fixture.rename_succeeded.load(Ordering::Acquire));
+}
+
+#[tokio::test]
+async fn native_preparing_playback_audio_matches_completed_pcm_and_releases_its_source() {
+ use cap_audio::AudioSampleSource;
+ use std::io::Write;
+ use std::sync::atomic::AtomicUsize;
+
+ let mut fixture = fixture(false);
+ let expected_metadata = fixture.metadata.clone();
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut fixture.metadata.inner else {
+ panic!("Studio metadata expected");
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!("Indexed metadata expected");
+ };
+ inner.segments[0].mic.as_mut().unwrap().gap_summary = Some(cap_project::AudioGapSummary {
+ total_overlap_trimmed_ms: 0,
+ startup_overlap_trimmed_ms: 0,
+ overlap_dropped_frames: 0,
+ startup_overlap_drops: 0,
+ });
+ let path = fixture.metadata.project_path.join("mic.aac");
+ let sample_count = 4 * 48_000_u32;
+ let mut file = std::fs::File::create(&path).unwrap();
+ file.write_all(b"RIFF").unwrap();
+ file.write_all(&(sample_count * 2 + 36).to_le_bytes())
+ .unwrap();
+ file.write_all(b"WAVEfmt ").unwrap();
+ file.write_all(&16_u32.to_le_bytes()).unwrap();
+ file.write_all(&1_u16.to_le_bytes()).unwrap();
+ file.write_all(&1_u16.to_le_bytes()).unwrap();
+ file.write_all(&48_000_u32.to_le_bytes()).unwrap();
+ file.write_all(&96_000_u32.to_le_bytes()).unwrap();
+ file.write_all(&2_u16.to_le_bytes()).unwrap();
+ file.write_all(&16_u16.to_le_bytes()).unwrap();
+ file.write_all(b"data").unwrap();
+ file.write_all(&(sample_count * 2).to_le_bytes()).unwrap();
+ for sample in 0..sample_count {
+ let value = ((sample % 10_000) as i16 + 1_000).to_le_bytes();
+ file.write_all(&value).unwrap();
+ }
+ drop(file);
+ let expected = cap_audio::AudioData::from_file(&path).unwrap();
+ let nonzero = Arc::new(AtomicUsize::new(0));
+ let tapped = nonzero.clone();
+ let output = Arc::new(crate::AudioOutput::new_headless(Box::new(
+ move |samples, _| {
+ tapped.fetch_add(
+ samples.iter().filter(|sample| **sample != 0.0).count(),
+ Ordering::Relaxed,
+ );
+ },
+ )));
+ let session = crate::PreparingPlaybackSession::spawn_with_expected_metadata(
+ fixture.input(),
+ vec![crate::PreparingAudioSegmentInput {
+ mic: Some(
+ cap_audio::ManagedAudioInput::new(fixture.source.clone(), PathBuf::from("mic.aac"))
+ .unwrap(),
+ ),
+ system_audio: None,
+ timing_repair: Default::default(),
+ }],
+ crate::PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions::default(),
+ fps: 30,
+ resolution: XY::new(320, 240),
+ },
+ output,
+ Box::new(|_, _, _| {}),
+ expected_metadata.clone(),
+ )
+ .unwrap();
+ let mut updates = session.updates();
+ tokio::time::timeout(Duration::from_secs(30), async {
+ loop {
+ let ready = {
+ let state = updates.borrow_and_update();
+ state.progress.preview_available && state.progress.playable_until == 3.25
+ };
+ if ready {
+ break;
+ }
+ updates.changed().await.unwrap();
+ }
+ })
+ .await
+ .unwrap();
+ session.controller().seek(1.5).await.unwrap();
+ session.controller().set_playing(true).await.unwrap();
+ tokio::time::timeout(Duration::from_secs(15), async {
+ loop {
+ if updates.borrow_and_update().playback.playhead_seconds > 1.6 {
+ break;
+ }
+ updates.changed().await.unwrap();
+ }
+ })
+ .await
+ .unwrap();
+ assert!(nonzero.load(Ordering::Relaxed) > 0);
+ let stop = session.stop_handle();
+ let metadata = expected_metadata;
+ drop(fixture.source);
+ let exit = stop.stop_and_wait().await;
+ assert!(exit.error.is_none(), "{:?}", exit.error);
+ let retained_exit = exit.clone();
+ let cached = exit
+ .take_completed_audio()
+ .unwrap()
+ .into_matching(&metadata, metadata.studio_meta().unwrap())
+ .unwrap();
+ assert!(retained_exit.take_completed_audio().is_none());
+ let actual = cached[0].mic.as_ref().unwrap();
+ assert_eq!(actual.sample_count(), expected.sample_count());
+ assert_eq!(actual.channels(), expected.channels());
+ assert!(
+ actual
+ .sample_slices()
+ .flatten()
+ .zip(expected.samples())
+ .all(|(actual, expected)| actual.to_bits() == expected.to_bits())
+ );
+ assert!(actual.sample(expected.samples().len()).is_none());
+ assert!(fixture.released.load(Ordering::Acquire));
+ assert!(fixture.rename_succeeded.load(Ordering::Acquire));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_preparing_audio_decode_failure_never_admits_playback() {
+ let fixture = fixture(false);
+ std::fs::write(
+ fixture.metadata.project_path.join("mic.aac"),
+ b"invalid audio",
+ )
+ .unwrap();
+ let session = crate::PreparingPlaybackSession::spawn(
+ fixture.input(),
+ vec![crate::PreparingAudioSegmentInput {
+ mic: Some(
+ cap_audio::ManagedAudioInput::new(fixture.source.clone(), PathBuf::from("mic.aac"))
+ .unwrap(),
+ ),
+ system_audio: None,
+ timing_repair: Default::default(),
+ }],
+ crate::PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions::default(),
+ fps: 30,
+ resolution: XY::new(320, 240),
+ },
+ Arc::new(crate::AudioOutput::new_headless(Box::new(|_, _| {}))),
+ Box::new(|_, _, _| {}),
+ )
+ .unwrap();
+ let mut updates = session.updates();
+ tokio::time::timeout(Duration::from_secs(15), async {
+ loop {
+ let state = updates.borrow_and_update().clone();
+ assert_eq!(state.progress.playable_until, 0.0);
+ if state.progress.phase == crate::PreparingEditorPhase::Unavailable {
+ break;
+ }
+ updates.changed().await.unwrap();
+ }
+ })
+ .await
+ .unwrap();
+ assert!(session.controller().set_playing(true).await.is_err());
+ drop(fixture.source);
+ let exit = session.stop_handle().stop_and_wait().await;
+ assert!(exit.error.is_some());
+ assert!(!exit.cleanup_failed);
+ assert_eq!(exit.snapshot.progress.playable_until, 0.0);
+ assert!(fixture.released.load(Ordering::Acquire));
+ assert!(fixture.rename_succeeded.load(Ordering::Acquire));
+}
+
+async fn composed_parity_with_reference(
+ fixture: Fixture,
+ frames: &[u32],
+ force_ffmpeg: bool,
+ frame_format: EditorFrameFormat,
+) {
+ let svg = fixture.project.cursor.use_svg;
+ assert!(!fixture.metadata.project_path.join("cursor.png").exists());
+ let expected = ordinary_composed_frames(&fixture, frames, force_ffmpeg).await;
+ let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
+ let mut preview = PreparingPreview::spawn(
+ fixture.input(),
+ PreparingPreviewOptions {
+ use_hardware_decoding: true,
+ frame_format,
+ },
+ Box::new(move |request, output, layout| {
+ let frame = match output {
+ EditorFrameOutput::Rgba(frame) => {
+ assert_eq!(frame_format, EditorFrameFormat::Rgba);
+ frame
+ }
+ #[cfg(target_os = "macos")]
+ EditorFrameOutput::Surface(frame) => {
+ assert_eq!(frame_format, EditorFrameFormat::BgraSurface);
+ surface_rgba(frame)
+ }
+ EditorFrameOutput::Nv12(_) => panic!("Unexpected NV12 output"),
+ };
+ sender.send((request, frame, layout)).unwrap();
+ }),
+ )
+ .unwrap();
+ let stop = preview.stop_handle();
+ let ready = tokio::time::timeout(Duration::from_secs(30), preview.wait_ready())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(ready.screen_size, XY::new(160, 120));
+ assert_eq!(ready.camera_size, Some(XY::new(80, 80)));
+ for (index, (frame_number, (expected, expected_layout))) in
+ frames.iter().copied().zip(expected).enumerate()
+ {
+ if index == 1 {
+ fixture.relocate("retained");
+ }
+ if index == 2 {
+ fixture.relocate("original");
+ }
+ let sequence = preview
+ .request_frame(frame_number, 30, XY::new(320, 240))
+ .unwrap();
+ let (request, actual, layout) =
+ tokio::time::timeout(Duration::from_secs(15), receiver.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(request.sequence, sequence);
+ assert_eq!(actual.frame_number, frame_number);
+ assert_eq!(layout, expected_layout);
+ assert_eq!(
+ (actual.width, actual.height),
+ (expected.width, expected.height)
+ );
+ assert_eq!(
+ visible_rgba(&actual),
+ visible_rgba(&expected),
+ "Composed frame differs: svg={svg}, frame={frame_number}"
+ );
+ assert!(!fixture.released.load(Ordering::Acquire));
+ }
+ assert!(fixture.assets.first_error().is_none());
+ drop(fixture.source);
+ let second_stop = preview.stop_handle();
+ let (first, second) = tokio::join!(stop.stop_and_wait(), second_stop.stop_and_wait());
+ assert_eq!(first.reason, PreparingPreviewError::Cancelled);
+ assert_eq!(second.reason, PreparingPreviewError::Cancelled);
+ assert_eq!(first.workers.len(), fixture.project.clips.len().min(2));
+ assert!(
+ first
+ .workers
+ .iter()
+ .all(|worker| worker.display.is_some() && worker.camera.is_some())
+ );
+ assert!(fixture.released.load(Ordering::Acquire));
+ assert!(fixture.rename_succeeded.load(Ordering::Acquire));
+ assert!(
+ fixture
+ .directory
+ .path()
+ .join("released-after-native-join")
+ .is_dir()
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_preparing_png_cursor_zoom_camera_and_relocation_match_finalized_render() {
+ composed_parity(fixture(false), &[0, 45, 12, 90]).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_preparing_svg_cursor_zoom_camera_and_relocation_match_finalized_render() {
+ composed_parity(fixture(true), &[0, 45, 12, 90]).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_recorded_keyboard_without_overlay_matches_finalized_render() {
+ let mut fixture = fixture(false);
+ let keyboard = cap_project::KeyboardEvents {
+ presses: vec![cap_project::KeyPressEvent {
+ key: "A".into(),
+ key_code: "KeyA".into(),
+ time_ms: 0.0,
+ down: true,
+ }],
+ };
+ for metadata in [&mut fixture.metadata, &mut fixture.reference_metadata] {
+ let path = metadata.project_path.join("keyboard.bin");
+ keyboard.write_to_file(&path).unwrap();
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut metadata.inner else {
+ panic!("Studio metadata expected");
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!("Indexed metadata expected");
+ };
+ inner.segments[0].keyboard = Some("keyboard.bin".into());
+ let segment = inner.segments[0].clone();
+ assert_eq!(segment.keyboard_events(metadata).presses, keyboard.presses);
+ }
+ let before = serde_json::to_value(&fixture.project).unwrap();
+ cap_project::synchronize_legacy_keyboard(&fixture.reference_metadata, &mut fixture.project);
+ assert_eq!(serde_json::to_value(&fixture.project).unwrap(), before);
+ assert!(fixture.project.keyboard.is_none());
+ assert!(
+ fixture
+ .project
+ .timeline
+ .as_ref()
+ .unwrap()
+ .keyboard_segments
+ .is_empty()
+ );
+ composed_parity(fixture, &[0, 45, 12, 90]).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_three_clip_eviction_reopen_and_boundaries_match_finalized_render() {
+ let mut fixture = fixture(false);
+ for metadata in [&mut fixture.metadata, &mut fixture.reference_metadata] {
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut metadata.inner else {
+ panic!("Studio metadata expected");
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!("Indexed metadata expected");
+ };
+ inner.segments.resize(3, inner.segments[0].clone());
+ }
+ fixture.project.timeline = Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": (0..3).map(|index| serde_json::json!({
+ "recordingSegment": index, "timescale": 1.0, "start": 0.0, "end": 3.0
+ })).collect::<Vec<_>>(),
+ "zoomSegments": (0..3).map(|index| serde_json::json!({
+ "start": f64::from(index) * 3.0 + 0.3,
+ "end": f64::from(index) * 3.0 + 2.7,
+ "amount": 1.6, "mode": "auto"
+ })).collect::<Vec<_>>()
+ }))
+ .unwrap(),
+ );
+ fixture.project.clips = (0..3)
+ .map(|index| ClipConfiguration {
+ index,
+ offsets: ClipOffsets {
+ camera: 0.25 + index as f32 * 0.125,
+ mic: 0.03125,
+ system_audio: 0.0,
+ },
+ offsets_auto_calculated: true,
+ })
+ .collect();
+ composed_parity(fixture, &[0, 90, 180, 12, 89, 90, 179, 180, 269, 0]).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_callback_panic_joins_workers_and_releases_source_owner() {
+ let fixture = fixture(false);
+ let (sender, receiver) = tokio::sync::oneshot::channel();
+ let mut sender = Some(sender);
+ let mut preview = PreparingPreview::spawn(
+ fixture.input(),
+ PreparingPreviewOptions {
+ use_hardware_decoding: true,
+ frame_format: EditorFrameFormat::Rgba,
+ },
+ Box::new(move |_, _, _| {
+ sender.take().unwrap().send(()).unwrap();
+ panic!("Native preparing callback failure");
+ }),
+ )
+ .unwrap();
+ let stop = preview.stop_handle();
+ tokio::time::timeout(Duration::from_secs(30), preview.wait_ready())
+ .await
+ .unwrap()
+ .unwrap();
+ drop(fixture.source);
+ assert!(!fixture.released.load(Ordering::Acquire));
+ preview.request_frame(0, 30, XY::new(320, 240)).unwrap();
+ tokio::time::timeout(Duration::from_secs(15), receiver)
+ .await
+ .unwrap()
+ .unwrap();
+ let exit = tokio::time::timeout(Duration::from_secs(15), stop.stop_and_wait())
+ .await
+ .unwrap();
+ assert_eq!(exit.reason, PreparingPreviewError::Panicked);
+ assert_eq!(exit.workers.len(), 1);
+ assert!(exit.workers[0].display.is_some() && exit.workers[0].camera.is_some());
+ assert!(fixture.released.load(Ordering::Acquire));
+ assert!(fixture.rename_succeeded.load(Ordering::Acquire));
+}
+
+#[cfg(target_os = "macos")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_preparing_matches_default_avasset_editor_decoder() {
+ composed_parity_with_reference(
+ fixture(false),
+ &[0, 45, 12, 90],
+ false,
+ EditorFrameFormat::Rgba,
+ )
+ .await;
+ composed_parity_with_reference(
+ fixture(true),
+ &[0, 45, 12, 90],
+ false,
+ EditorFrameFormat::Rgba,
+ )
+ .await;
+}
+
+#[cfg(target_os = "macos")]
+fn surface_rgba(frame: cap_rendering::SurfaceFrame) -> RenderedFrame {
+ use std::ffi::c_void;
+
+ unsafe extern "C" {
+ fn CVPixelBufferLockBaseAddress(buffer: *const c_void, flags: u64) -> i32;
+ fn CVPixelBufferUnlockBaseAddress(buffer: *const c_void, flags: u64) -> i32;
+ fn CVPixelBufferGetBaseAddress(buffer: *const c_void) -> *const u8;
+ fn CVPixelBufferGetBytesPerRow(buffer: *const c_void) -> usize;
+ fn CVPixelBufferGetDataSize(buffer: *const c_void) -> usize;
+ fn CVPixelBufferGetWidth(buffer: *const c_void) -> usize;
+ fn CVPixelBufferGetHeight(buffer: *const c_void) -> usize;
+ fn CVPixelBufferGetPixelFormatType(buffer: *const c_void) -> u32;
+ }
+
+ struct LockedBuffer(*const c_void);
+
+ impl Drop for LockedBuffer {
+ fn drop(&mut self) {
+ unsafe {
+ CVPixelBufferUnlockBaseAddress(self.0, 1);
+ }
+ }
+ }
+
+ let buffer = std::ptr::from_ref(frame.pixel_buffer.as_ref()).cast::<c_void>();
+ assert_eq!(unsafe { CVPixelBufferLockBaseAddress(buffer, 1) }, 0);
+ let lock = LockedBuffer(buffer);
+ let width = unsafe { CVPixelBufferGetWidth(buffer) };
+ let height = unsafe { CVPixelBufferGetHeight(buffer) };
+ let stride = unsafe { CVPixelBufferGetBytesPerRow(buffer) };
+ let data_size = unsafe { CVPixelBufferGetDataSize(buffer) };
+ assert_eq!(
+ unsafe { CVPixelBufferGetPixelFormatType(buffer) },
+ u32::from_be_bytes(*b"BGRA")
+ );
+ assert_eq!(width, frame.width as usize);
+ assert_eq!(height, frame.height as usize);
+ let row_bytes = width.checked_mul(4).unwrap();
+ let buffer_bytes = stride.checked_mul(height).unwrap();
+ assert!(row_bytes > 0 && height > 0 && stride >= row_bytes);
+ assert!(data_size >= buffer_bytes);
+ let address = unsafe { CVPixelBufferGetBaseAddress(buffer) };
+ assert!(!address.is_null());
+ let pixels = unsafe { std::slice::from_raw_parts(address, buffer_bytes) };
+ let mut rgba = Vec::with_capacity(row_bytes.checked_mul(height).unwrap());
+ for row in pixels.chunks_exact(stride) {
+ for pixel in row[..row_bytes].chunks_exact(4) {
+ rgba.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);
+ }
+ }
+ drop(lock);
+ RenderedFrame {
+ data: Arc::new(rgba),
+ width: frame.width,
+ height: frame.height,
+ padded_bytes_per_row: row_bytes.try_into().unwrap(),
+ frame_number: frame.frame_number,
+ target_time_ns: frame.target_time_ns,
+ }
+}
+
+#[cfg(target_os = "macos")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_preparing_bgra_surface_matches_default_avasset_editor_frame() {
+ composed_parity_with_reference(
+ fixture(false),
+ &[0, 45, 12, 90],
+ false,
+ EditorFrameFormat::BgraSurface,
+ )
+ .await;
+}
+
+fn handoff_fixture() -> Fixture {
+ use std::io::Write;
+
+ let mut fixture = fixture(false);
+ let root = fixture.metadata.project_path.clone();
+ for track in ["display", "camera"] {
+ std::fs::copy(
+ fixture
+ .reference_metadata
+ .project_path
+ .join(format!("{track}.mp4")),
+ root.join(format!("{track}.mp4")),
+ )
+ .unwrap();
+ }
+ std::fs::copy(
+ fixture.reference_metadata.project_path.join("cursor.png"),
+ root.join("cursor.png"),
+ )
+ .unwrap();
+ let cap_project::RecordingMetaInner::Studio(studio) = &mut fixture.metadata.inner else {
+ panic!("Expected Studio metadata");
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!("Expected indexed metadata");
+ };
+ inner.segments[0].display.path = "display.mp4".into();
+ inner.segments[0].camera.as_mut().unwrap().path = "camera.mp4".into();
+ inner.segments.resize(3, inner.segments[0].clone());
+ fixture.metadata.save_for_project().unwrap();
+ let segment = fixture.project.timeline.as_ref().unwrap().segments[0].clone();
+ fixture.project.timeline.as_mut().unwrap().segments = (0..3)
+ .map(|index| cap_project::TimelineSegment {
+ recording_clip: index,
+ end: 5.5,
+ ..segment.clone()
+ })
+ .collect();
+ let clip = fixture.project.clips[0].clone();
+ fixture.project.clips = (0..3)
+ .map(|index| ClipConfiguration {
+ index,
+ ..clip.clone()
+ })
+ .collect();
+ fixture.project.write(&root).unwrap();
+ let sample_count = 8 * 48_000_u32;
+ let mut file = std::fs::File::create(root.join("mic.aac")).unwrap();
+ file.write_all(b"RIFF").unwrap();
+ file.write_all(&(sample_count * 2 + 36).to_le_bytes())
+ .unwrap();
+ file.write_all(b"WAVEfmt ").unwrap();
+ file.write_all(&16_u32.to_le_bytes()).unwrap();
+ file.write_all(&1_u16.to_le_bytes()).unwrap();
+ file.write_all(&1_u16.to_le_bytes()).unwrap();
+ file.write_all(&48_000_u32.to_le_bytes()).unwrap();
+ file.write_all(&96_000_u32.to_le_bytes()).unwrap();
+ file.write_all(&2_u16.to_le_bytes()).unwrap();
+ file.write_all(&16_u16.to_le_bytes()).unwrap();
+ file.write_all(b"data").unwrap();
+ file.write_all(&(sample_count * 2).to_le_bytes()).unwrap();
+ for sample in 0..sample_count {
+ file.write_all(&((sample % 10_000) as i16 + 1_000).to_le_bytes())
+ .unwrap();
+ }
+ drop(file);
+ fixture
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_handoff_reuses_pcm_preserves_audio_across_candidate_disposal_and_joins_before_restart()
+ {
+ use std::sync::atomic::AtomicUsize;
+
+ let fixture = handoff_fixture();
+ let root = fixture.metadata.project_path.clone();
+ let nonzero = Arc::new(AtomicUsize::new(0));
+ let tapped = nonzero.clone();
+ let output = Arc::new(crate::AudioOutput::new_headless(Box::new(
+ move |samples, _| {
+ tapped.fetch_add(
+ samples.iter().filter(|sample| **sample != 0.0).count(),
+ Ordering::Relaxed,
+ );
+ },
+ )));
+ let session = crate::PreparingPlaybackSession::spawn(
+ fixture.input(),
+ (0..3)
+ .map(|_| crate::PreparingAudioSegmentInput {
+ mic: Some(
+ cap_audio::ManagedAudioInput::new(
+ fixture.source.clone(),
+ PathBuf::from("mic.aac"),
+ )
+ .unwrap(),
+ ),
+ system_audio: None,
+ timing_repair: Default::default(),
+ })
+ .collect(),
+ crate::PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions::default(),
+ fps: 30,
+ resolution: XY::new(320, 240),
+ },
+ output.clone(),
+ Box::new(|_, _, _| {}),
+ )
+ .unwrap();
+ let handoff = session.handoff_handle();
+ let cache = tokio::time::timeout(Duration::from_secs(30), handoff.take_completed_audio())
+ .await
+ .unwrap()
+ .unwrap();
+ let expected = cache
+ .clone()
+ .into_matching(&fixture.metadata, fixture.metadata.studio_meta().unwrap())
+ .unwrap()[0]
+ .mic
+ .clone()
+ .unwrap();
+ let candidate = crate::EditorInstance::new_with_startup_inputs(
+ root.clone(),
+ |_| {},
+ Box::new(|_, _| {}),
+ None,
+ crate::EditorFrameFormat::Rgba,
+ output,
+ crate::EditorStartupInputs {
+ recordings: None,
+ completed_audio: Some(cache),
+ },
+ )
+ .await
+ .unwrap();
+ let actual = candidate.segment_medias[0]
+ .audio
+ .get()
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(Arc::ptr_eq(&expected, &actual));
+ let mut updates = session.updates();
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while !updates.borrow_and_update().progress.preview_available {
+ updates.changed().await.unwrap();
+ }
+ })
+ .await
+ .unwrap();
+ session.controller().seek(0.5).await.unwrap();
+ session.controller().set_playing(true).await.unwrap();
+ candidate.install_preparing_handoff(&handoff).await.unwrap();
+ let obsolete = candidate.preparing_adoption().unwrap();
+ session.controller().seek(0.5).await.unwrap();
+ assert!(obsolete.invalidated());
+ candidate.dispose().await;
+ candidate.dispose().await;
+ let before = nonzero.load(Ordering::Relaxed);
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while nonzero.load(Ordering::Relaxed) <= before {
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .unwrap();
+ let (frames, mut received) = tokio::sync::watch::channel(None);
+ let next = candidate
+ .recreate_preparing_candidate(
+ |_| {},
+ Box::new(move |output, _| {
+ let frame = match output {
+ crate::EditorFrameOutput::Rgba(frame) => frame.frame_number,
+ crate::EditorFrameOutput::Nv12(frame) => frame.frame_number,
+ #[cfg(target_os = "macos")]
+ crate::EditorFrameOutput::Surface(frame) => frame.frame_number,
+ };
+ frames.send_replace(Some(frame));
+ }),
+ crate::EditorFrameFormat::Rgba,
+ )
+ .await
+ .unwrap();
+ assert!(Arc::ptr_eq(&candidate.segment_medias, &next.segment_medias));
+ candidate.dispose().await;
+ assert!(!obsolete.try_commit(15, 30));
+ assert!(
+ next.start_preparing_handoff(30, XY::new(320, 240))
+ .await
+ .unwrap()
+ );
+ tokio::time::timeout(Duration::from_secs(30), async {
+ loop {
+ if received
+ .borrow_and_update()
+ .is_some_and(|frame| next.commit_preparing_frame(frame, 30))
+ {
+ break;
+ }
+ received.changed().await.unwrap();
+ }
+ })
+ .await
+ .unwrap();
+ assert!(handoff.committed());
+ assert_eq!(
+ next.install_preparing_handoff(&handoff).await.unwrap_err(),
+ "Editor already has a preparing candidate"
+ );
+ assert!(handoff.committed());
+ let before = nonzero.load(Ordering::Relaxed);
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while nonzero.load(Ordering::Relaxed) <= before {
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .unwrap();
+ let ordinary = next
+ .start_playback_with_handle(30, XY::new(320, 240), Some(30))
+ .await
+ .unwrap();
+ let exit = session.stop_handle().stop_and_wait().await;
+ assert!(!exit.cleanup_failed, "{:?}", exit.error);
+ assert!(next.preparing_adoption().is_none());
+ assert!(Arc::ptr_eq(
+ &expected,
+ &next.segment_medias[0].audio.get().await.unwrap().unwrap()
+ ));
+ ordinary.stop();
+ next.dispose().await;
+ drop(ordinary);
+ drop(next);
+ drop(candidate);
+ drop(obsolete);
+ drop(handoff);
+ drop(session);
+ drop(fixture.source);
+ assert!(fixture.released.load(Ordering::Acquire));
+}
+
+async fn failed_handoff_installation_retires_native_candidate(cancelled: bool) {
+ use futures::FutureExt;
+
+ let fixture = handoff_fixture();
+ let output = Arc::new(crate::AudioOutput::new_headless(Box::new(|_, _| {})));
+ let session = crate::PreparingPlaybackSession::spawn(
+ fixture.input(),
+ (0..3)
+ .map(|_| crate::PreparingAudioSegmentInput {
+ mic: Some(
+ cap_audio::ManagedAudioInput::new(
+ fixture.source.clone(),
+ PathBuf::from("mic.aac"),
+ )
+ .unwrap(),
+ ),
+ system_audio: None,
+ timing_repair: Default::default(),
+ })
+ .collect(),
+ crate::PreparingPlaybackOptions {
+ preview: PreparingPreviewOptions::default(),
+ fps: 30,
+ resolution: XY::new(320, 240),
+ },
+ output.clone(),
+ Box::new(|_, _, _| {}),
+ )
+ .unwrap();
+ let handoff = session.handoff_handle();
+ let cache = tokio::time::timeout(Duration::from_secs(30), handoff.take_completed_audio())
+ .await
+ .unwrap()
+ .unwrap();
+ let candidate = crate::EditorInstance::new_with_startup_inputs(
+ fixture.metadata.project_path.clone(),
+ |_| {},
+ Box::new(|_, _| {}),
+ None,
+ crate::EditorFrameFormat::Rgba,
+ output,
+ crate::EditorStartupInputs {
+ recordings: None,
+ completed_audio: if cancelled { Some(cache) } else { None },
+ },
+ )
+ .await
+ .unwrap();
+ let retained = Arc::downgrade(&candidate);
+ assert!(candidate.state.lock().await.preview_task.is_some());
+ if cancelled {
+ handoff.cancel();
+ }
+ let error = tokio::time::timeout(
+ Duration::from_secs(30),
+ candidate.install_preparing_handoff(&handoff),
+ )
+ .await
+ .unwrap()
+ .unwrap_err();
+ assert_eq!(
+ error,
+ if cancelled {
+ "Preparing playback cannot retry adoption"
+ } else {
+ "Preparing audio does not match this editor's completed sources or output"
+ }
+ );
+ assert!(candidate.state.lock().await.preview_task.is_none());
+ let stop = session.stop_handle();
+ let exit = stop
+ .stop_and_wait()
+ .now_or_never()
+ .expect("Failed installation returned before managed workers joined");
+ assert!(!exit.cleanup_failed, "{:?}", exit.error);
+ drop(exit);
+ drop(candidate);
+ assert!(retained.upgrade().is_none());
+ drop(stop);
+ drop(handoff);
+ drop(session);
+ drop(fixture.source);
+ assert!(fixture.released.load(Ordering::Acquire));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_cancelled_handoff_installation_joins_and_releases_the_candidate() {
+ failed_handoff_installation_retires_native_candidate(true).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn native_rejected_audio_handoff_installation_joins_and_releases_the_candidate() {
+ failed_handoff_installation_retires_native_candidate(false).await;
+}
diff --git a/crates/editor/src/preparing_preview/tests.rs b/crates/editor/src/preparing_preview/tests.rs
new file mode 100644
index 000000000..6e16a7f18
--- /dev/null
+++ b/crates/editor/src/preparing_preview/tests.rs
@@ -0,0 +1,269 @@
+use super::*;
+use cap_enc_ffmpeg::RelocatableSource;
+use cap_rendering::{ManagedVideoTrackInput, decoder::ManagedVideoExit};
+use std::{
+ path::Path,
+ sync::atomic::{AtomicBool, Ordering},
+};
+
+struct OwnerDropped(Arc<AtomicBool>);
+
+impl Drop for OwnerDropped {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::Release);
+ }
+}
+
+fn input(path: &Path) -> (PreparingPreviewInput, Arc<AtomicBool>) {
+ let dropped = Arc::new(AtomicBool::new(false));
+ let source = RelocatableSource::new_with_owner(
+ path.to_path_buf(),
+ Arc::new(OwnerDropped(dropped.clone())),
+ )
+ .unwrap();
+ let recording_meta: RecordingMeta = serde_json::from_value(serde_json::json!({
+ "project_path": path,
+ "pretty_name": "Preparing test",
+ "segments": [{"display": {"path": "content/segments/segment-0/display", "fps": 30, "start_time": 0.0}}],
+ "status": {"status": "NeedsRemux"}
+ })).unwrap();
+ let segment = PreparingPreviewSegment {
+ video: ManagedSegmentVideoInput::new(
+ 0,
+ recording_meta.studio_meta().unwrap(),
+ ManagedVideoTrackInput::new(source, vec!["missing-init.mp4".into()]).unwrap(),
+ None,
+ )
+ .unwrap(),
+ cursor: Arc::new(CursorEvents::default()),
+ };
+ let project = ProjectConfiguration {
+ timeline: Some(serde_json::from_value(serde_json::json!({
+ "segments": [{"recordingSegment": 0, "start": 0.0, "end": 7200.0, "timescale": 1.0}],
+ "zoomSegments": []
+ })).unwrap()),
+ clips: vec![cap_project::ClipConfiguration::default()],
+ ..Default::default()
+ };
+ (
+ PreparingPreviewInput {
+ recording_meta,
+ project,
+ segments: vec![segment],
+ cursor_assets: FrozenRecordedCursorAssets::new([]).unwrap(),
+ },
+ dropped,
+ )
+}
+
+#[test]
+fn unsupported_presentation_and_unresolved_offsets_decline_before_open() {
+ let directory = tempfile::tempdir().unwrap();
+ let mutations: [fn(&mut ProjectConfiguration); 8] = [
+ |project| {
+ project.background.source = BackgroundSource::Image {
+ path: Some("unreadable.png".into()),
+ }
+ },
+ |project| project.camera.background_blur.mode = cap_project::BackgroundBlurMode::Heavy,
+ |project| project.clips.clear(),
+ |project| project.clips.push(project.clips[0].clone()),
+ |project| project.clips[0].offsets.camera = f32::NAN,
+ |project| project.timeline.as_mut().unwrap().segments[0].timescale = 0.5,
+ |project| project.keyboard = Some(cap_project::KeyboardData::default()),
+ |project| {
+ project.timeline.as_mut().unwrap().keyboard_segments.push(
+ serde_json::from_value(serde_json::json!({
+ "id": "kb-0", "start": 0.0, "end": 1.0, "displayText": "A"
+ }))
+ .unwrap(),
+ )
+ },
+ ];
+ for mutate in mutations {
+ let (mut input, dropped) = input(directory.path());
+ assert_eq!(validate_input(&input).unwrap(), 7200.0);
+ mutate(&mut input.project);
+ assert!(matches!(
+ validate_input(&input),
+ Err(PreparingPreviewError::InvalidInput(_))
+ ));
+ drop(input);
+ assert!(dropped.load(Ordering::Acquire));
+ }
+ assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
+}
+
+#[test]
+fn input_metadata_must_match_bound_decoder_timing() {
+ let directory = tempfile::tempdir().unwrap();
+ for changed in ["fps", "start_time", "missing_start"] {
+ let (mut input, _) = input(directory.path());
+ let cap_project::RecordingMetaInner::Studio(metadata) = &mut input.recording_meta.inner
+ else {
+ unreachable!()
+ };
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = metadata.as_mut() else {
+ unreachable!()
+ };
+ match changed {
+ "fps" => inner.segments[0].display.fps = 24,
+ "start_time" => inner.segments[0].display.start_time = Some(1.0),
+ _ => inner.segments[0].display.start_time = None,
+ }
+ assert!(
+ matches!(
+ validate_input(&input),
+ Err(PreparingPreviewError::InvalidInput(_))
+ ),
+ "{changed}"
+ );
+ }
+}
+
+#[test]
+fn requests_reject_exclusive_end_and_invalid_dimensions() {
+ let resolution = XY::new(1920, 1080);
+ assert!(validate_request(7199 * 60, 60, resolution, 7200.0).is_ok());
+ assert!(validate_request(7200 * 60, 60, resolution, 7200.0).is_err());
+ assert!(validate_request(0, 0, resolution, 7200.0).is_err());
+ assert!(validate_request(0, 60, XY::new(0, 1080), 7200.0).is_err());
+ assert!(validate_request(0, 60, XY::new(16384, 1080), 7200.0).is_err());
+ assert!(validate_request(0, 60, resolution, f64::INFINITY).is_err());
+}
+
+#[test]
+fn rendered_frame_identity_and_latest_sequence_are_both_required() {
+ let first = PreparingFrameRequest {
+ sequence: 1,
+ frame_number: 30,
+ fps: 30,
+ resolution_base: XY::new(160, 120),
+ };
+ let latest = PreparingFrameRequest {
+ sequence: 2,
+ frame_number: 60,
+ ..first
+ };
+ let (sender, receiver) = watch::channel(Some(first));
+ sender.send_replace(Some(latest));
+ assert!(!is_current(&receiver, first));
+ assert!(is_current(&receiver, latest));
+ let layout = FrameLayout {
+ display: [0.0, 0.0, 160.0, 120.0],
+ camera: None,
+ output_size: [160, 120],
+ };
+ let mut frame = cap_rendering::RenderedFrame {
+ data: Arc::new(Vec::new()),
+ width: 160,
+ height: 120,
+ padded_bytes_per_row: 640,
+ frame_number: first.frame_number,
+ target_time_ns: 0,
+ };
+ assert!(validate_output(&EditorFrameOutput::Rgba(frame.clone()), latest, layout).is_err());
+ frame.frame_number = latest.frame_number;
+ assert!(validate_output(&EditorFrameOutput::Rgba(frame.clone()), latest, layout).is_ok());
+ frame.width = 80;
+ assert!(validate_output(&EditorFrameOutput::Rgba(frame), latest, layout).is_err());
+}
+
+#[tokio::test]
+async fn missing_media_preserves_failure_and_joins_before_source_release() {
+ let directory = tempfile::tempdir().unwrap();
+ let (input, dropped) = input(directory.path());
+ let mut preview = PreparingPreview::spawn(
+ input,
+ PreparingPreviewOptions::default(),
+ Box::new(|_, _, _| panic!("Missing media must not render")),
+ )
+ .unwrap();
+ let stop = preview.stop_handle();
+ let error = preview.wait_ready().await.unwrap_err();
+ assert!(
+ matches!(
+ &error,
+ PreparingPreviewError::Media(ManagedSegmentVideoError::Display(
+ ManagedVideoError::Initialization(_)
+ ))
+ ),
+ "{error:?}"
+ );
+ let exit = stop.stop_and_wait().await;
+ assert_eq!(exit.reason, error);
+ assert_eq!(exit.workers.len(), 1);
+ assert!(matches!(
+ exit.workers[0].display.as_ref().unwrap().terminal,
+ ManagedVideoError::Initialization(_)
+ ));
+ assert!(dropped.load(Ordering::Acquire));
+ assert!(preview.request_frame(0, 30, XY::new(160, 120)).is_err());
+ assert!(preview.wait_ready().await.is_err());
+}
+
+#[tokio::test]
+async fn dropped_readiness_and_shutdown_waiters_retain_join_ownership() {
+ let directory = tempfile::tempdir().unwrap();
+ let (input, dropped) = input(directory.path());
+ let mut preview = PreparingPreview::spawn(
+ input,
+ PreparingPreviewOptions::default(),
+ Box::new(|_, _, _| panic!("Cancelled preview must not render")),
+ )
+ .unwrap();
+ let stop = preview.stop_handle();
+ assert!(preview.wait_ready().now_or_never().is_none());
+ assert!(stop.control.cancel.is_cancelled());
+ assert!(stop.stop_and_wait().now_or_never().is_none());
+ assert!(!dropped.load(Ordering::Acquire));
+ let exit = stop.stop_and_wait().await;
+ assert_eq!(exit.reason, PreparingPreviewError::Cancelled);
+ assert!(exit.workers.is_empty());
+ assert!(dropped.load(Ordering::Acquire));
+ let weak = Arc::downgrade(&stop.control);
+ drop(preview);
+ drop(stop);
+ assert!(weak.upgrade().is_none());
+}
+
+#[tokio::test]
+async fn owner_drop_closes_admission_before_join() {
+ let directory = tempfile::tempdir().unwrap();
+ let (input, dropped) = input(directory.path());
+ let mut preview = PreparingPreview::spawn(
+ input,
+ PreparingPreviewOptions::default(),
+ Box::new(|_, _, _| panic!("Cancelled preview must not render")),
+ )
+ .unwrap();
+ assert_eq!(preview.request_frame(0, 30, XY::new(160, 120)).unwrap(), 1);
+ assert_eq!(preview.request_frame(30, 30, XY::new(160, 120)).unwrap(), 2);
+ let stop = preview.stop_handle();
+ drop(preview);
+ assert!(stop.control.cancel.is_cancelled());
+ assert!(!dropped.load(Ordering::Acquire));
+ assert_eq!(
+ stop.stop_and_wait().await.reason,
+ PreparingPreviewError::Cancelled
+ );
+ assert!(dropped.load(Ordering::Acquire));
+}
+
+#[test]
+fn real_camera_failure_is_not_replaced_by_cancelled_display() {
+ let exit = ManagedSegmentVideoExit {
+ display: Some(ManagedVideoExit {
+ terminal: ManagedVideoError::Cancelled,
+ }),
+ camera: Some(ManagedVideoExit {
+ terminal: ManagedVideoError::Decode("missing fragment".into()),
+ }),
+ };
+ assert_eq!(
+ worker_exit_error(&exit),
+ Some(PreparingPreviewError::Media(
+ ManagedSegmentVideoError::Camera(ManagedVideoError::Decode("missing fragment".into()))
+ ))
+ );
+}
diff --git a/crates/editor/src/segments.rs b/crates/editor/src/segments.rs
index 7d6855114..7c8f8f371 100644
--- a/crates/editor/src/segments.rs
+++ b/crates/editor/src/segments.rs
@@ -105,7 +105,7 @@ pub fn load_music_tracks_uncached(
async fn loaded_track(
loader: &crate::AudioLoader,
label: &str,
-) -> Option<Arc<cap_audio::AudioData>> {
+) -> Option<Arc<cap_audio::DecodedAudio>> {
match loader.get().await {
Ok(audio) => audio,
Err(error) => {
@@ -122,36 +122,96 @@ pub async fn get_audio_segments(segments: &[SegmentMedia]) -> Vec<AudioSegment>
let audio = loaded_track(&s.audio, "mic audio").await;
let system_audio = loaded_track(&s.system_audio, "system audio").await;
- out.push(AudioSegment {
- tracks: [
- audio.map(|a| {
- AudioSegmentTrack::new(
- a,
- |c| c.mic_volume_db,
- |c| match c.mic_stereo_mode {
- cap_project::StereoMode::Stereo => cap_audio::StereoMode::Stereo,
- cap_project::StereoMode::MonoL => cap_audio::StereoMode::MonoL,
- cap_project::StereoMode::MonoR => cap_audio::StereoMode::MonoR,
- },
- |o| o.mic,
- )
- .with_timing_offset_secs(s.audio_timing_repair.mic_offset_secs)
- }),
- system_audio.map(|a| -> AudioSegmentTrack {
- AudioSegmentTrack::new(
- a,
- |c| c.system_volume_db,
- |_| cap_audio::StereoMode::Stereo,
- |o| o.system_audio,
- )
- .with_timing_offset_secs(s.audio_timing_repair.system_audio_offset_secs)
- }),
- ]
- .into_iter()
- .flatten()
- .collect::<Vec<_>>(),
- });
+ out.push(audio_segment_from_decoded(
+ audio,
+ system_audio,
+ s.audio_timing_repair,
+ ));
}
out
}
+
+pub fn audio_segment_from_decoded(
+ audio: Option<Arc<cap_audio::DecodedAudio>>,
+ system_audio: Option<Arc<cap_audio::DecodedAudio>>,
+ repair: crate::editor_instance::SegmentAudioTimingRepair,
+) -> AudioSegment {
+ AudioSegment {
+ tracks: [
+ audio.map(|a| {
+ AudioSegmentTrack::from_decoded(
+ a,
+ |c| c.mic_volume_db,
+ |c| match c.mic_stereo_mode {
+ cap_project::StereoMode::Stereo => cap_audio::StereoMode::Stereo,
+ cap_project::StereoMode::MonoL => cap_audio::StereoMode::MonoL,
+ cap_project::StereoMode::MonoR => cap_audio::StereoMode::MonoR,
+ },
+ |o| o.mic,
+ )
+ .with_timing_offset_secs(repair.mic_offset_secs)
+ }),
+ system_audio.map(|a| -> AudioSegmentTrack {
+ AudioSegmentTrack::from_decoded(
+ a,
+ |c| c.system_volume_db,
+ |_| cap_audio::StereoMode::Stereo,
+ |o| o.system_audio,
+ )
+ .with_timing_offset_secs(repair.system_audio_offset_secs)
+ }),
+ ]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>(),
+ }
+}
+
+#[cfg(test)]
+mod completed_audio_tests {
+ use super::*;
+ use cap_project::{AudioConfiguration, ClipOffsets};
+
+ #[test]
+ fn shared_audio_segment_preserves_arc_gain_stereo_and_timing() {
+ let audio = crate::completed_audio::tests::audio();
+ let repair = crate::SegmentAudioTimingRepair {
+ mic_offset_secs: -0.25,
+ system_audio_offset_secs: 0.125,
+ };
+ let segment = audio_segment_from_decoded(Some(audio.clone()), Some(audio.clone()), repair);
+ assert_eq!(segment.tracks.len(), 2);
+ for track in &segment.tracks {
+ assert!(Arc::ptr_eq(track.data(), &audio));
+ }
+ let config = AudioConfiguration {
+ mic_volume_db: -3.5,
+ system_volume_db: -8.0,
+ mic_stereo_mode: cap_project::StereoMode::MonoR,
+ ..Default::default()
+ };
+ let offsets = ClipOffsets {
+ mic: 0.5,
+ system_audio: -0.5,
+ ..Default::default()
+ };
+ assert_eq!(segment.tracks[0].gain(&config), -3.5);
+ assert_eq!(segment.tracks[1].gain(&config), -8.0);
+ assert!(matches!(
+ segment.tracks[0].stereo_mode(&config),
+ cap_audio::StereoMode::MonoR
+ ));
+ assert!(matches!(
+ segment.tracks[1].stereo_mode(&config),
+ cap_audio::StereoMode::Stereo
+ ));
+ assert_eq!(segment.tracks[0].offset(&offsets), 0.25);
+ assert_eq!(segment.tracks[1].offset(&offsets), -0.375);
+ assert!(
+ audio_segment_from_decoded(None, None, repair)
+ .tracks
+ .is_empty()
+ );
+ }
+}
diff --git a/crates/enc-ffmpeg/Cargo.toml b/crates/enc-ffmpeg/Cargo.toml
index ac939b361..878134e90 100644
--- a/crates/enc-ffmpeg/Cargo.toml
+++ b/crates/enc-ffmpeg/Cargo.toml
@@ -16,6 +16,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[target.'cfg(target_os = "windows")'.dependencies]
cap-frame-converter = { path = "../frame-converter" }
+windows = { workspace = true, features = ["Win32_Storage_FileSystem"] }
[dev-dependencies]
tempfile = "3.20.0"
diff --git a/crates/enc-ffmpeg/src/lib.rs b/crates/enc-ffmpeg/src/lib.rs
index 99bcf2bcd..b1b13d20c 100644
--- a/crates/enc-ffmpeg/src/lib.rs
+++ b/crates/enc-ffmpeg/src/lib.rs
@@ -12,7 +12,11 @@ pub use video::*;
mod mux;
pub use mux::*;
+mod relocatable_source;
pub mod remux;
+pub use relocatable_source::{RelocatableReader, RelocatableSource};
+mod segmented_input;
+pub use segmented_input::SegmentedInput;
pub mod dash_audio {
pub use crate::mux::dash_audio::*;
}
diff --git a/crates/enc-ffmpeg/src/relocatable_source.rs b/crates/enc-ffmpeg/src/relocatable_source.rs
new file mode 100644
index 000000000..e6322ccc7
--- /dev/null
+++ b/crates/enc-ffmpeg/src/relocatable_source.rs
@@ -0,0 +1,1172 @@
+use std::{
+ collections::HashSet,
+ fs::{self, File, Metadata},
+ io::{self, Read, Seek, SeekFrom},
+ path::{Component, Path, PathBuf},
+ sync::{Arc, Mutex, RwLock, Weak},
+ time::SystemTime,
+};
+
+type CachedFile = Arc<Mutex<Option<File>>>;
+
+#[derive(Clone)]
+pub struct RelocatableSource(Arc<RwLock<DirectoryState>>);
+
+struct DirectoryState {
+ root: PathBuf,
+ identity: FileIdentity,
+ readers: Vec<Weak<Mutex<Option<File>>>>,
+ next_cleanup: usize,
+ _owner: Option<Arc<dyn Send + Sync>>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct FileIdentity {
+ #[cfg(unix)]
+ device: u64,
+ #[cfg(unix)]
+ inode: u64,
+ #[cfg(windows)]
+ volume: u64,
+ #[cfg(windows)]
+ file_id: [u8; 16],
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+struct FileSnapshot {
+ identity: FileIdentity,
+ length: u64,
+ modified: SystemTime,
+}
+
+pub struct RelocatableReader {
+ relative: PathBuf,
+ snapshot: FileSnapshot,
+ file: CachedFile,
+ position: u64,
+ failure: Option<io::Error>,
+ // Cached files must close before the final source-owned lease is released.
+ source: RelocatableSource,
+}
+
+fn identity(file: &File) -> io::Result<FileIdentity> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ let metadata = file.metadata()?;
+ Ok(FileIdentity {
+ device: metadata.dev(),
+ inode: metadata.ino(),
+ })
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::io::AsRawHandle;
+ use windows::Win32::{
+ Foundation::HANDLE,
+ Storage::FileSystem::{FILE_ID_INFO, FileIdInfo, GetFileInformationByHandleEx},
+ };
+ let mut information = FILE_ID_INFO::default();
+ unsafe {
+ GetFileInformationByHandleEx(
+ HANDLE(file.as_raw_handle()),
+ FileIdInfo,
+ std::ptr::from_mut(&mut information).cast(),
+ std::mem::size_of::<FILE_ID_INFO>() as u32,
+ )
+ }
+ .map_err(io::Error::other)?;
+ Ok(FileIdentity {
+ volume: information.VolumeSerialNumber,
+ file_id: information.FileId.Identifier,
+ })
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ let _ = file;
+ Err(io::Error::new(
+ io::ErrorKind::Unsupported,
+ "Managed source identity is unsupported on this platform",
+ ))
+ }
+}
+
+fn directory_identity(path: &Path) -> io::Result<FileIdentity> {
+ let mut options = File::options();
+ options.read(true);
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ use windows::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
+ options.custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0);
+ }
+ let file = options.open(path)?;
+ if !file.metadata()?.is_dir() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Invalid source directory",
+ ));
+ }
+ identity(&file)
+}
+
+fn is_link(metadata: &Metadata) -> bool {
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::MetadataExt;
+ use windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
+ metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0
+ }
+ #[cfg(not(windows))]
+ {
+ metadata.file_type().is_symlink()
+ }
+}
+
+fn open_relative(root: &Path, relative: &Path) -> io::Result<File> {
+ let mut path = root.to_path_buf();
+ for component in relative.components() {
+ path.push(component);
+ if is_link(&fs::symlink_metadata(&path)?) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Managed source paths cannot contain links",
+ ));
+ }
+ }
+ File::open(path)
+}
+
+impl FileSnapshot {
+ fn capture(file: &File) -> io::Result<Self> {
+ let metadata = file.metadata()?;
+ if !metadata.is_file() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Managed sources must be regular files",
+ ));
+ }
+ Ok(Self {
+ identity: identity(file)?,
+ length: metadata.len(),
+ modified: metadata.modified()?,
+ })
+ }
+
+ fn validate(&self, file: &File) -> io::Result<()> {
+ if Self::capture(file)? != *self {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Managed source identity, length, or modification time changed",
+ ));
+ }
+ Ok(())
+ }
+}
+
+impl RelocatableSource {
+ pub fn new(root: PathBuf) -> io::Result<Self> {
+ Self::new_inner(root, None)
+ }
+
+ pub fn new_with_owner(root: PathBuf, owner: Arc<dyn Send + Sync>) -> io::Result<Self> {
+ Self::new_inner(root, Some(owner))
+ }
+
+ fn new_inner(root: PathBuf, owner: Option<Arc<dyn Send + Sync>>) -> io::Result<Self> {
+ if is_link(&fs::symlink_metadata(&root)?) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Managed source roots cannot be links",
+ ));
+ }
+ let root = root.canonicalize()?;
+ let identity = directory_identity(&root)?;
+ Ok(Self(Arc::new(RwLock::new(DirectoryState {
+ root,
+ identity,
+ readers: Vec::new(),
+ next_cleanup: 64,
+ _owner: owner,
+ }))))
+ }
+
+ pub fn reader(&self, relative: &Path) -> io::Result<RelocatableReader> {
+ self.readers(&[relative.to_path_buf()])?
+ .pop()
+ .ok_or_else(|| io::Error::other("Missing managed reader"))
+ }
+
+ pub(crate) fn readers(&self, paths: &[PathBuf]) -> io::Result<Vec<RelocatableReader>> {
+ for relative in paths {
+ if relative.as_os_str().is_empty()
+ || relative
+ .components()
+ .any(|part| !matches!(part, Component::Normal(_)))
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Invalid managed source path",
+ ));
+ }
+ }
+ let mut source = self
+ .0
+ .write()
+ .map_err(|_| io::Error::other("Source poisoned"))?;
+ if directory_identity(&source.root)? != source.identity {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Managed source directory changed",
+ ));
+ }
+ let mut parents = HashSet::new();
+ let mut readers = Vec::with_capacity(paths.len());
+ for relative in paths {
+ let mut path = source.root.clone();
+ let mut components = relative.components().peekable();
+ while let Some(component) = components.next() {
+ path.push(component);
+ let parent = components.peek().is_some();
+ if parent && parents.contains(&path) {
+ continue;
+ }
+ if is_link(&fs::symlink_metadata(&path)?) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Managed source paths cannot contain links",
+ ));
+ }
+ if parent {
+ parents.insert(path.clone());
+ }
+ }
+ let snapshot = FileSnapshot::capture(&File::open(path)?)?;
+ let file = Arc::new(Mutex::new(None));
+ if source.readers.len() >= source.next_cleanup {
+ source.readers.retain(|reader| reader.strong_count() > 0);
+ source.next_cleanup = source.readers.len().saturating_mul(2).max(64);
+ }
+ source.readers.push(Arc::downgrade(&file));
+ readers.push(RelocatableReader {
+ relative: relative.to_path_buf(),
+ snapshot,
+ file,
+ position: 0,
+ failure: None,
+ source: self.clone(),
+ });
+ }
+ Ok(readers)
+ }
+
+ pub fn relocate(&self, destination: PathBuf) -> io::Result<()> {
+ self.relocate_checked(None, destination, |source, target| {
+ fs::rename(source, target)
+ })
+ }
+
+ pub fn relocate_from(&self, expected_source: &Path, destination: PathBuf) -> io::Result<()> {
+ self.relocate_checked(Some(expected_source), destination, |source, target| {
+ fs::rename(source, target)
+ })
+ }
+
+ #[cfg(test)]
+ fn relocate_with(
+ &self,
+ destination: PathBuf,
+ rename: impl FnOnce(&Path, &Path) -> io::Result<()>,
+ ) -> io::Result<()> {
+ self.relocate_checked(None, destination, rename)
+ }
+
+ fn relocate_checked(
+ &self,
+ expected_source: Option<&Path>,
+ destination: PathBuf,
+ rename: impl FnOnce(&Path, &Path) -> io::Result<()>,
+ ) -> io::Result<()> {
+ let name = destination.file_name().ok_or_else(|| {
+ io::Error::new(io::ErrorKind::InvalidInput, "Invalid source destination")
+ })?;
+ let parent = destination
+ .parent()
+ .filter(|parent| !parent.as_os_str().is_empty())
+ .unwrap_or(Path::new("."));
+ let destination = parent.canonicalize()?.join(name);
+ let mut source = self
+ .0
+ .write()
+ .map_err(|_| io::Error::other("Source poisoned"))?;
+ if directory_identity(&source.root)? != source.identity {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Managed source directory changed",
+ ));
+ }
+ if let Some(expected) = expected_source
+ && (is_link(&fs::symlink_metadata(expected)?)
+ || expected.canonicalize()? != source.root
+ || directory_identity(expected)? != source.identity)
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Relocation does not match the managed source directory",
+ ));
+ }
+ if destination == source.root {
+ return Ok(());
+ }
+ match fs::symlink_metadata(&destination) {
+ Ok(_) => {
+ return Err(io::Error::new(
+ io::ErrorKind::AlreadyExists,
+ "Source destination already exists",
+ ));
+ }
+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error),
+ }
+ source.readers.retain(|reader| reader.strong_count() > 0);
+ for reader in source.readers.iter().filter_map(Weak::upgrade) {
+ drop(
+ reader
+ .lock()
+ .map_err(|_| io::Error::other("Reader poisoned"))?
+ .take(),
+ );
+ }
+ rename(&source.root, &destination)?;
+ source.root = destination;
+ Ok(())
+ }
+}
+
+impl RelocatableReader {
+ pub fn len(&self) -> u64 {
+ self.snapshot.length
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ pub(crate) fn close(&mut self) -> io::Result<()> {
+ drop(
+ self.file
+ .lock()
+ .map_err(|_| io::Error::other("Reader poisoned"))?
+ .take(),
+ );
+ Ok(())
+ }
+
+ fn read_current(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
+ if buffer.is_empty() || self.position >= self.len() {
+ return Ok(0);
+ }
+ let source = self
+ .source
+ .0
+ .read()
+ .map_err(|_| io::Error::other("Source poisoned"))?;
+ let mut cached = self
+ .file
+ .lock()
+ .map_err(|_| io::Error::other("Reader poisoned"))?;
+ if cached.is_none() {
+ let mut file = open_relative(&source.root, &self.relative)?;
+ self.snapshot.validate(&file)?;
+ file.seek(SeekFrom::Start(self.position))?;
+ *cached = Some(file);
+ }
+ let file = cached
+ .as_mut()
+ .ok_or_else(|| io::Error::other("Missing managed source file"))?;
+ let limit = (self.len() - self.position).min(buffer.len() as u64) as usize;
+ let count = file.read(&mut buffer[..limit])?;
+ if count == 0 {
+ return Err(io::Error::new(
+ io::ErrorKind::UnexpectedEof,
+ "Managed source was truncated",
+ ));
+ }
+ let position = self.position.checked_add(count as u64).ok_or_else(|| {
+ io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Managed source position overflow",
+ )
+ })?;
+ if position == self.len() {
+ self.snapshot.validate(file)?;
+ }
+ self.position = position;
+ Ok(count)
+ }
+}
+
+impl Read for RelocatableReader {
+ fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
+ if let Some(error) = &self.failure {
+ return Err(io::Error::new(error.kind(), error.to_string()));
+ }
+ match self.read_current(buffer) {
+ Ok(count) => Ok(count),
+ Err(error) => {
+ self.failure = Some(io::Error::new(error.kind(), error.to_string()));
+ Err(error)
+ }
+ }
+ }
+}
+
+impl Seek for RelocatableReader {
+ fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
+ if let Some(error) = &self.failure {
+ return Err(io::Error::new(error.kind(), error.to_string()));
+ }
+ let position = match from {
+ SeekFrom::Start(position) => i128::from(position),
+ SeekFrom::Current(offset) => i128::from(self.position) + i128::from(offset),
+ SeekFrom::End(offset) => i128::from(self.len()) + i128::from(offset),
+ };
+ let position = u64::try_from(position).map_err(|_| {
+ io::Error::new(io::ErrorKind::InvalidInput, "Invalid managed source seek")
+ })?;
+ if position != self.position {
+ self.close()?;
+ self.position = position;
+ }
+ Ok(position)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ struct Fixture(PathBuf);
+
+ impl Fixture {
+ fn new() -> Self {
+ static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+ let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let root = std::env::temp_dir().join(format!(
+ "cap-revocable-source-probe-{}-{unique}-{sequence}",
+ std::process::id()
+ ));
+ fs::create_dir(&root).unwrap();
+ fs::create_dir(root.join("original")).unwrap();
+ fs::write(root.join("original/0.m4s"), b"first-original-fragment").unwrap();
+ fs::write(root.join("original/1.m4s"), b"second-original-fragment").unwrap();
+ Self(root)
+ }
+
+ fn source(&self) -> RelocatableSource {
+ RelocatableSource::new(self.0.join("original")).unwrap()
+ }
+ }
+
+ impl Drop for Fixture {
+ fn drop(&mut self) {
+ fs::remove_dir_all(&self.0).unwrap();
+ }
+ }
+
+ fn read(source: &RelocatableSource, relative: &str) -> Vec<u8> {
+ let mut data = Vec::new();
+ source
+ .reader(Path::new(relative))
+ .unwrap()
+ .read_to_end(&mut data)
+ .unwrap();
+ data
+ }
+
+ #[test]
+ fn held_reader_and_lazy_next_fragment_survive_publication() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let mut first = source.reader(Path::new("0.m4s")).unwrap();
+ let mut prefix = [0; 5];
+ first.read_exact(&mut prefix).unwrap();
+ assert_eq!(&prefix, b"first");
+ assert!(first.file.lock().unwrap().is_some());
+ source.relocate(fixture.0.join("retained")).unwrap();
+ assert!(first.file.lock().unwrap().is_none());
+ fs::create_dir(fixture.0.join("original")).unwrap();
+ fs::write(fixture.0.join("original/0.m4s"), b"published-output").unwrap();
+ let mut rest = Vec::new();
+ first.read_to_end(&mut rest).unwrap();
+ assert_eq!(rest, b"-original-fragment");
+ first.seek(SeekFrom::Start(0)).unwrap();
+ let mut all = Vec::new();
+ first.read_to_end(&mut all).unwrap();
+ assert_eq!(all, b"first-original-fragment");
+ assert_eq!(read(&source, "0.m4s"), b"first-original-fragment");
+ assert_eq!(read(&source, "1.m4s"), b"second-original-fragment");
+ assert_eq!(
+ fs::read(fixture.0.join("original/0.m4s")).unwrap(),
+ b"published-output"
+ );
+ }
+
+ #[test]
+ fn failed_relocation_preserves_reader_position_and_original_root() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let mut reader = source.reader(Path::new("1.m4s")).unwrap();
+ let mut prefix = [0; 6];
+ reader.read_exact(&mut prefix).unwrap();
+ assert_eq!(&prefix, b"second");
+ assert!(
+ source
+ .relocate_with(fixture.0.join("retained"), |_, _| {
+ Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected"))
+ })
+ .is_err()
+ );
+ let mut rest = Vec::new();
+ reader.read_to_end(&mut rest).unwrap();
+ assert_eq!(rest, b"-original-fragment");
+ }
+
+ #[test]
+ fn rollback_relocation_preserves_active_readers() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let mut reader = source.reader(Path::new("1.m4s")).unwrap();
+ let mut prefix = [0; 3];
+ reader.read_exact(&mut prefix).unwrap();
+ source.relocate(fixture.0.join("retained")).unwrap();
+ reader.read_exact(&mut prefix).unwrap();
+ source.relocate(fixture.0.join("original")).unwrap();
+ let mut rest = Vec::new();
+ reader.read_to_end(&mut rest).unwrap();
+ assert_eq!(rest, b"-original-fragment");
+ }
+
+ #[test]
+ fn concurrent_readers_keep_exact_bytes_during_repeated_relocation() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ std::thread::scope(|scope| {
+ for _ in 0..4 {
+ let source = source.clone();
+ scope.spawn(move || {
+ let mut reader = source.reader(Path::new("1.m4s")).unwrap();
+ for _ in 0..1_000 {
+ reader.seek(SeekFrom::Start(0)).unwrap();
+ let mut bytes = Vec::new();
+ reader.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"second-original-fragment");
+ }
+ });
+ }
+ for _ in 0..300 {
+ source.relocate(fixture.0.join("retained")).unwrap();
+ source.relocate(fixture.0.join("original")).unwrap();
+ }
+ });
+ }
+
+ #[test]
+ fn reader_cannot_resolve_outside_its_relative_source() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ for path in ["", "../0.m4s", "/0.m4s", ".", "segment/../0.m4s"] {
+ assert!(source.reader(Path::new(path)).is_err());
+ }
+ }
+
+ #[test]
+ fn invalid_seek_keeps_the_last_successful_position() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let mut reader = source.reader(Path::new("1.m4s")).unwrap();
+ reader.seek(SeekFrom::Start(6)).unwrap();
+ assert!(reader.seek(SeekFrom::Current(-7)).is_err());
+ source.relocate(fixture.0.join("retained")).unwrap();
+ let mut rest = Vec::new();
+ reader.read_to_end(&mut rest).unwrap();
+ assert_eq!(rest, b"-original-fragment");
+ }
+
+ #[test]
+ fn reopened_reader_rejects_a_changed_source_size() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let mut reader = source.reader(Path::new("1.m4s")).unwrap();
+ reader.read_exact(&mut [0; 1]).unwrap();
+ source.relocate(fixture.0.join("retained")).unwrap();
+ fs::write(fixture.0.join("retained/1.m4s"), b"changed").unwrap();
+ assert!(reader.read(&mut [0; 1]).is_err());
+ }
+
+ #[test]
+ fn replacement_with_matching_length_and_mtime_is_rejected_and_stays_failed() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let mut reader = source.reader(Path::new("1.m4s")).unwrap();
+ reader.read_exact(&mut [0; 1]).unwrap();
+ source.relocate(fixture.0.join("retained")).unwrap();
+ let path = fixture.0.join("retained/1.m4s");
+ let bytes = fs::read(&path).unwrap();
+ let modified = path.metadata().unwrap().modified().unwrap();
+ let backup = path.with_extension("backup");
+ fs::rename(&path, &backup).unwrap();
+ fs::write(&path, bytes).unwrap();
+ File::options()
+ .write(true)
+ .open(&path)
+ .unwrap()
+ .set_times(fs::FileTimes::new().set_modified(modified))
+ .unwrap();
+ assert_eq!(
+ reader.read(&mut [0; 1]).unwrap_err().kind(),
+ io::ErrorKind::InvalidData
+ );
+ fs::remove_file(&path).unwrap();
+ fs::rename(backup, path).unwrap();
+ assert_eq!(
+ reader.seek(SeekFrom::Start(0)).unwrap_err().kind(),
+ io::ErrorKind::InvalidData
+ );
+ assert!(reader.read(&mut [0; 1]).is_err());
+ }
+
+ #[test]
+ fn existing_destination_and_ordinary_path_are_never_replaced() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let destination = fixture.0.join("existing");
+ fs::create_dir(&destination).unwrap();
+ fs::write(destination.join("output"), b"ordinary output").unwrap();
+ assert_eq!(
+ source.relocate(destination.clone()).unwrap_err().kind(),
+ io::ErrorKind::AlreadyExists
+ );
+ assert_eq!(
+ fs::read(destination.join("output")).unwrap(),
+ b"ordinary output"
+ );
+ assert_eq!(read(&source, "0.m4s"), b"first-original-fragment");
+ }
+
+ #[test]
+ fn capability_rejects_a_replaced_root() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ fs::rename(fixture.0.join("original"), fixture.0.join("external")).unwrap();
+ fs::create_dir(fixture.0.join("original")).unwrap();
+ fs::write(fixture.0.join("original/0.m4s"), b"replacement").unwrap();
+ assert!(source.reader(Path::new("0.m4s")).is_err());
+ assert!(source.relocate(fixture.0.join("retained")).is_err());
+ assert_eq!(
+ fs::read(fixture.0.join("external/0.m4s")).unwrap(),
+ b"first-original-fragment"
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn source_paths_cannot_follow_a_symbolic_link() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ fs::write(fixture.0.join("outside"), b"outside").unwrap();
+ std::os::unix::fs::symlink(fixture.0.join("outside"), fixture.0.join("original/link"))
+ .unwrap();
+ assert!(source.reader(Path::new("link")).is_err());
+ }
+
+ #[test]
+ fn many_lazy_readers_do_not_retain_file_handles() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let readers: Vec<_> = (0..2_000)
+ .map(|_| source.reader(Path::new("0.m4s")).unwrap())
+ .collect();
+ assert!(
+ readers
+ .iter()
+ .all(|reader| reader.file.lock().unwrap().is_none())
+ );
+ source.relocate(fixture.0.join("retained")).unwrap();
+ for mut reader in readers {
+ let mut bytes = Vec::new();
+ reader.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"first-original-fragment");
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn source_root_cannot_be_a_symbolic_link() {
+ let fixture = Fixture::new();
+ let link = fixture.0.join("link");
+ std::os::unix::fs::symlink(fixture.0.join("original"), &link).unwrap();
+ assert!(RelocatableSource::new(link).is_err());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn source_root_cannot_be_a_directory_junction() {
+ let fixture = Fixture::new();
+ let link = fixture.0.join("link");
+ let result = std::process::Command::new("cmd")
+ .args(["/C", "mklink", "/J"])
+ .arg(&link)
+ .arg(fixture.0.join("original"))
+ .output()
+ .unwrap();
+ assert!(
+ result.status.success(),
+ "{}",
+ String::from_utf8_lossy(&result.stderr)
+ );
+ assert!(RelocatableSource::new(link).is_err());
+ }
+
+ #[test]
+ fn expected_source_rejects_other_project_and_stale_roots_without_consuming_reader() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let original = fixture.0.join("original");
+ let retained = fixture.0.join("retained");
+ let other = fixture.0.join("other");
+ fs::create_dir(&other).unwrap();
+ fs::write(other.join("untouched"), b"other-project").unwrap();
+ let mut reader = source.reader(Path::new("0.m4s")).unwrap();
+ let mut prefix = [0; 5];
+ reader.read_exact(&mut prefix).unwrap();
+ assert_eq!(&prefix, b"first");
+ for destination in [&retained, &original] {
+ assert_eq!(
+ source
+ .relocate_from(&other, destination.clone())
+ .unwrap_err()
+ .kind(),
+ io::ErrorKind::InvalidInput
+ );
+ }
+ assert!(reader.file.lock().unwrap().is_some());
+ source.relocate_from(&original, retained.clone()).unwrap();
+ fs::create_dir(&original).unwrap();
+ fs::write(original.join("published"), b"ordinary-output").unwrap();
+ assert_eq!(
+ source
+ .relocate_from(&original, fixture.0.join("wrong"))
+ .unwrap_err()
+ .kind(),
+ io::ErrorKind::InvalidInput
+ );
+ let mut remainder = Vec::new();
+ reader.read_to_end(&mut remainder).unwrap();
+ assert_eq!(remainder, b"-original-fragment");
+ assert_eq!(fs::read(other.join("untouched")).unwrap(), b"other-project");
+ assert_eq!(
+ fs::read(original.join("published")).unwrap(),
+ b"ordinary-output"
+ );
+ fs::remove_file(original.join("published")).unwrap();
+ fs::remove_dir(&original).unwrap();
+ source.relocate_from(&retained, original.clone()).unwrap();
+ reader.rewind().unwrap();
+ remainder.clear();
+ reader.read_to_end(&mut remainder).unwrap();
+ assert_eq!(remainder, b"first-original-fragment");
+ }
+
+ #[test]
+ fn expected_source_rejects_replacement_identity_before_closing_readers() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let original = fixture.0.join("original");
+ let backup = fixture.0.join("external-backup");
+ let mut reader = source.reader(Path::new("0.m4s")).unwrap();
+ let mut prefix = [0; 5];
+ reader.read_exact(&mut prefix).unwrap();
+ reader.close().unwrap();
+ fs::rename(&original, &backup).unwrap();
+ fs::create_dir(&original).unwrap();
+ assert_eq!(
+ source
+ .relocate_from(&original, fixture.0.join("retained"))
+ .unwrap_err()
+ .kind(),
+ io::ErrorKind::InvalidData
+ );
+ fs::remove_dir(&original).unwrap();
+ fs::rename(&backup, &original).unwrap();
+ let mut remainder = Vec::new();
+ reader.read_to_end(&mut remainder).unwrap();
+ assert_eq!(remainder, b"-original-fragment");
+ }
+
+ #[test]
+ fn batch_keeps_each_file_identity_and_revalidates_root_between_batches() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let original = fixture.0.join("original");
+ fs::create_dir(original.join("display")).unwrap();
+ let paths: Vec<_> = (0..64)
+ .map(|index| PathBuf::from(format!("display/{index}.m4s")))
+ .collect();
+ for (index, path) in paths.iter().enumerate() {
+ fs::write(original.join(path), [index as u8; 32]).unwrap();
+ }
+ let mut readers = source.readers(&paths).unwrap();
+ assert!(
+ readers
+ .iter()
+ .all(|reader| reader.file.lock().unwrap().is_none())
+ );
+ let changed = original.join(&paths[17]);
+ let metadata = fs::metadata(&changed).unwrap();
+ fs::rename(&changed, original.join("preserved-original")).unwrap();
+ fs::write(&changed, [17; 32]).unwrap();
+ File::options()
+ .write(true)
+ .open(&changed)
+ .unwrap()
+ .set_modified(metadata.modified().unwrap())
+ .unwrap();
+ source.relocate(fixture.0.join("retained")).unwrap();
+ for (index, reader) in readers.iter_mut().enumerate() {
+ let mut output = Vec::new();
+ if index == 17 {
+ assert_eq!(
+ reader.read_to_end(&mut output).unwrap_err().kind(),
+ io::ErrorKind::InvalidData
+ );
+ } else {
+ reader.read_to_end(&mut output).unwrap();
+ assert_eq!(output, [index as u8; 32]);
+ }
+ }
+ source.relocate(original.clone()).unwrap();
+ fs::rename(&original, fixture.0.join("external")).unwrap();
+ fs::create_dir(&original).unwrap();
+ assert_eq!(
+ source.readers(&paths).err().unwrap().kind(),
+ io::ErrorKind::InvalidData
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn batch_rejects_linked_parent_and_expected_root_alias() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let original = fixture.0.join("original");
+ std::os::unix::fs::symlink(&original, fixture.0.join("alias")).unwrap();
+ assert_eq!(
+ source
+ .relocate_from(&fixture.0.join("alias"), fixture.0.join("retained"))
+ .unwrap_err()
+ .kind(),
+ io::ErrorKind::InvalidInput
+ );
+ fs::create_dir(original.join("display")).unwrap();
+ fs::write(original.join("display/0.m4s"), b"original").unwrap();
+ std::os::unix::fs::symlink(original.join("display"), original.join("linked")).unwrap();
+ assert_eq!(
+ source
+ .readers(&[
+ PathBuf::from("display/0.m4s"),
+ PathBuf::from("linked/0.m4s")
+ ])
+ .err()
+ .unwrap()
+ .kind(),
+ io::ErrorKind::InvalidInput
+ );
+ }
+
+ #[test]
+ fn competing_expected_source_moves_have_only_one_owner() {
+ let fixture = Fixture::new();
+ let source = fixture.source();
+ let original = fixture.0.join("original");
+ let barrier = Arc::new(std::sync::Barrier::new(2));
+ let workers: Vec<_> = (0..2)
+ .map(|index| {
+ let source = source.clone();
+ let expected = original.clone();
+ let destination = fixture.0.join(format!("retained-{index}"));
+ let barrier = barrier.clone();
+ std::thread::spawn(move || {
+ barrier.wait();
+ source.relocate_from(&expected, destination)
+ })
+ })
+ .collect();
+ let outcomes: Vec<_> = workers
+ .into_iter()
+ .map(|worker| worker.join().unwrap())
+ .collect();
+ assert_eq!(outcomes.iter().filter(|outcome| outcome.is_ok()).count(), 1);
+ assert_eq!(read(&source, "0.m4s"), b"first-original-fragment");
+ assert!(!original.exists());
+ }
+
+ struct ReleaseCounter(Arc<std::sync::atomic::AtomicUsize>);
+
+ impl Drop for ReleaseCounter {
+ fn drop(&mut self) {
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ }
+ }
+
+ type CachedFileWatch = Weak<Mutex<Option<File>>>;
+
+ struct FilesClosedAtRelease {
+ root: PathBuf,
+ cached: Mutex<Vec<CachedFileWatch>>,
+ released: Arc<std::sync::atomic::AtomicUsize>,
+ }
+
+ impl Drop for FilesClosedAtRelease {
+ fn drop(&mut self) {
+ assert!(
+ self.cached
+ .lock()
+ .unwrap()
+ .iter()
+ .all(|file| file.strong_count() == 0)
+ );
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ for name in ["0.m4s", "1.m4s"] {
+ drop(
+ File::options()
+ .read(true)
+ .write(true)
+ .share_mode(0)
+ .open(self.root.join(name))
+ .unwrap(),
+ );
+ }
+ }
+ let renamed = self.root.with_extension("lease-released");
+ fs::rename(&self.root, &renamed).unwrap();
+ fs::rename(&renamed, &self.root).unwrap();
+ self.released
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ }
+ }
+
+ #[test]
+ fn source_owner_survives_cloned_sources_without_readers() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let fixture = Fixture::new();
+ let released = Arc::new(AtomicUsize::new(0));
+ let source = RelocatableSource::new_with_owner(
+ fixture.0.join("original"),
+ Arc::new(ReleaseCounter(released.clone())),
+ )
+ .unwrap();
+ let first = source.clone();
+ let last = first.clone();
+ drop(source);
+ drop(first);
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ drop(last);
+ assert_eq!(released.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn source_owner_survives_every_reader_after_source_clones_drop() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let fixture = Fixture::new();
+ let released = Arc::new(AtomicUsize::new(0));
+ let source = RelocatableSource::new_with_owner(
+ fixture.0.join("original"),
+ Arc::new(ReleaseCounter(released.clone())),
+ )
+ .unwrap();
+ let copy = source.clone();
+ let first = source.reader(Path::new("0.m4s")).unwrap();
+ let mut readers = copy
+ .readers(&[PathBuf::from("0.m4s"), PathBuf::from("1.m4s")])
+ .unwrap();
+ let mut last = readers.pop().unwrap();
+ drop(source);
+ drop(copy);
+ drop(first);
+ drop(readers);
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ let mut bytes = Vec::new();
+ last.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"second-original-fragment");
+ drop(last);
+ assert_eq!(released.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn failed_source_construction_closes_files_before_releasing_owner() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let fixture = Fixture::new();
+ for root in [fixture.0.join("missing"), fixture.0.join("original/0.m4s")] {
+ let released = Arc::new(AtomicUsize::new(0));
+ let owner = Arc::new(FilesClosedAtRelease {
+ root: fixture.0.join("original"),
+ cached: Mutex::new(Vec::new()),
+ released: released.clone(),
+ });
+ assert!(RelocatableSource::new_with_owner(root, owner).is_err());
+ assert_eq!(released.load(Ordering::SeqCst), 1);
+ }
+ }
+
+ #[test]
+ fn failed_reader_registration_does_not_leak_or_release_source_owner() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let fixture = Fixture::new();
+ let released = Arc::new(AtomicUsize::new(0));
+ let owner = Arc::new(FilesClosedAtRelease {
+ root: fixture.0.join("original"),
+ cached: Mutex::new(Vec::new()),
+ released: released.clone(),
+ });
+ let source = RelocatableSource::new_with_owner(fixture.0.join("original"), owner).unwrap();
+ assert!(source.reader(Path::new("../0.m4s")).is_err());
+ assert!(source.reader(Path::new("missing.m4s")).is_err());
+ assert!(
+ source
+ .readers(&[PathBuf::from("0.m4s"), PathBuf::from("missing.m4s")])
+ .is_err()
+ );
+ assert!(
+ source
+ .0
+ .read()
+ .unwrap()
+ .readers
+ .iter()
+ .all(|reader| reader.strong_count() == 0)
+ );
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ assert_eq!(read(&source, "1.m4s"), b"second-original-fragment");
+ drop(source);
+ assert_eq!(released.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn failed_lazy_open_retains_owner_until_reader_and_files_drop() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let fixture = Fixture::new();
+ let released = Arc::new(AtomicUsize::new(0));
+ let owner = Arc::new(FilesClosedAtRelease {
+ root: fixture.0.join("original"),
+ cached: Mutex::new(Vec::new()),
+ released: released.clone(),
+ });
+ let source =
+ RelocatableSource::new_with_owner(fixture.0.join("original"), owner.clone()).unwrap();
+ let mut reader = source.reader(Path::new("0.m4s")).unwrap();
+ owner
+ .cached
+ .lock()
+ .unwrap()
+ .push(Arc::downgrade(&reader.file));
+ fs::write(fixture.0.join("original/0.m4s"), b"changed").unwrap();
+ let mut byte = [0];
+ assert_eq!(
+ reader.read(&mut byte).unwrap_err().kind(),
+ io::ErrorKind::InvalidData
+ );
+ assert!(reader.file.lock().unwrap().is_none());
+ drop(owner);
+ drop(source);
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ drop(reader);
+ assert_eq!(released.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn every_cached_file_closes_before_last_reader_releases_owner() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let fixture = Fixture::new();
+ let released = Arc::new(AtomicUsize::new(0));
+ let owner = Arc::new(FilesClosedAtRelease {
+ root: fixture.0.join("original"),
+ cached: Mutex::new(Vec::new()),
+ released: released.clone(),
+ });
+ let source =
+ RelocatableSource::new_with_owner(fixture.0.join("original"), owner.clone()).unwrap();
+ let mut first = source.reader(Path::new("0.m4s")).unwrap();
+ let mut last = source.reader(Path::new("1.m4s")).unwrap();
+ let mut byte = [0];
+ first.read_exact(&mut byte).unwrap();
+ last.read_exact(&mut byte).unwrap();
+ assert!(first.file.lock().unwrap().is_some());
+ assert!(last.file.lock().unwrap().is_some());
+ owner
+ .cached
+ .lock()
+ .unwrap()
+ .extend([Arc::downgrade(&first.file), Arc::downgrade(&last.file)]);
+ drop(owner);
+ drop(source);
+ drop(first);
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ std::thread::spawn(move || drop(last)).join().unwrap();
+ assert_eq!(released.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn source_owner_survives_publication_failed_move_and_rollback() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let fixture = Fixture::new();
+ let released = Arc::new(AtomicUsize::new(0));
+ let owner = Arc::new(ReleaseCounter(released.clone()));
+ let identity = Arc::downgrade(&owner);
+ let source = RelocatableSource::new_with_owner(fixture.0.join("original"), owner).unwrap();
+ let mut reader = source.reader(Path::new("1.m4s")).unwrap();
+ let mut bytes = [0; 3];
+ reader.read_exact(&mut bytes).unwrap();
+ assert_eq!(&bytes, b"sec");
+ source
+ .relocate_from(&fixture.0.join("original"), fixture.0.join("retained"))
+ .unwrap();
+ assert!(identity.upgrade().is_some());
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ reader.read_exact(&mut bytes).unwrap();
+ assert_eq!(&bytes, b"ond");
+ assert!(
+ source
+ .relocate_with(fixture.0.join("failed"), |_, _| {
+ Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected"))
+ })
+ .is_err()
+ );
+ assert!(identity.upgrade().is_some());
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ source
+ .relocate_from(&fixture.0.join("retained"), fixture.0.join("original"))
+ .unwrap();
+ assert!(identity.upgrade().is_some());
+ drop(source);
+ assert_eq!(released.load(Ordering::SeqCst), 0);
+ let mut rest = Vec::new();
+ reader.read_to_end(&mut rest).unwrap();
+ assert_eq!(rest, b"-original-fragment");
+ drop(reader);
+ assert!(identity.upgrade().is_none());
+ assert_eq!(released.load(Ordering::SeqCst), 1);
+ }
+}
diff --git a/crates/enc-ffmpeg/src/remux.rs b/crates/enc-ffmpeg/src/remux.rs
index 5a4609600..313139088 100644
--- a/crates/enc-ffmpeg/src/remux.rs
+++ b/crates/enc-ffmpeg/src/remux.rs
@@ -889,6 +889,17 @@ fn concatenate_m4s_segments_with_init_validated_with_reader(
}
}
+ // Existing destinations can alias an input, which must be copied before opening the output.
+ if !output.try_exists()? {
+ return crate::segmented_input::with_input(
+ std::iter::once(init_path).chain(segments.iter().map(PathBuf::as_path)),
+ |input| {
+ let mut output = avformat::output(output)?;
+ remux_streams_validated_with_reader(input, &mut output, read_packet)
+ },
+ );
+ }
+
let sequence = VALIDATED_AGGREGATE_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let combined_path = output.with_extension(format!(
"validated-combined-{}-{sequence}.mp4",
@@ -1294,6 +1305,29 @@ mod tests {
assert_no_validated_aggregate(directory.path());
}
+ #[test]
+ fn validated_m4s_concat_preserves_existing_destination_and_input_alias_support() {
+ for aliases_input in [false, true] {
+ let directory = tempfile::tempdir().unwrap();
+ let (init, segments) = encode_test_segments(&directory.path().join("source"));
+ let reference = directory.path().join("reference.mp4");
+ concatenate_m4s_segments_with_init(&init, &segments, &reference).unwrap();
+ let output = directory.path().join("existing.mp4");
+ if aliases_input {
+ std::fs::hard_link(&segments[0], &output).unwrap();
+ } else {
+ std::fs::write(&output, b"previous output").unwrap();
+ }
+ concatenate_m4s_segments_with_init_validated(&init, &segments, &output).unwrap();
+ assert_eq!(
+ video_packet_contents(&output),
+ video_packet_contents(&reference)
+ );
+ assert_eq!(decoded_video_frame_count(&output), 320);
+ assert_no_validated_aggregate(directory.path());
+ }
+ }
+
#[test]
fn validated_m4s_concat_rejects_undecodable_payload_and_retains_sources() {
let directory = tempfile::tempdir().unwrap();
diff --git a/crates/enc-ffmpeg/src/segmented_input.rs b/crates/enc-ffmpeg/src/segmented_input.rs
new file mode 100644
index 000000000..edb789291
--- /dev/null
+++ b/crates/enc-ffmpeg/src/segmented_input.rs
@@ -0,0 +1,1028 @@
+use std::{
+ ffi::{c_int, c_void},
+ fs::File,
+ io::{self, Read, Seek, SeekFrom},
+ panic::{AssertUnwindSafe, catch_unwind},
+ path::{Path, PathBuf},
+ ptr::{self, NonNull},
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+};
+
+use crate::{RelocatableReader, RelocatableSource, remux::RemuxError};
+
+struct InterruptState {
+ callback: Arc<dyn Fn() -> bool + Send + Sync>,
+ cancelled: AtomicBool,
+}
+
+impl InterruptState {
+ fn is_cancelled(&self) -> bool {
+ if self.cancelled.load(Ordering::Relaxed) {
+ return true;
+ }
+ let cancelled = catch_unwind(AssertUnwindSafe(|| (self.callback)())).unwrap_or(true);
+ if cancelled {
+ self.cancelled.store(true, Ordering::Relaxed);
+ }
+ cancelled
+ }
+}
+
+unsafe extern "C" fn interrupt_callback(opaque: *mut c_void) -> c_int {
+ if opaque.is_null() {
+ return 1;
+ }
+ let interrupt = unsafe { &*opaque.cast::<InterruptState>() };
+ c_int::from(interrupt.is_cancelled())
+}
+
+struct Part {
+ path: PathBuf,
+ start: u64,
+ end: u64,
+}
+
+struct OpenPart {
+ index: usize,
+ file: File,
+ position: u64,
+}
+
+struct ConcatenatedFiles {
+ parts: Vec<Part>,
+ length: u64,
+ position: u64,
+ current: Option<OpenPart>,
+ failure: Option<io::Error>,
+ managed: Option<Vec<RelocatableReader>>,
+ managed_current: Option<usize>,
+ interrupt: Option<Arc<InterruptState>>,
+}
+
+impl ConcatenatedFiles {
+ fn new<'a>(paths: impl IntoIterator<Item = &'a Path>) -> io::Result<Self> {
+ let mut parts = Vec::new();
+ let mut length = 0_u64;
+ for path in paths {
+ let metadata = path.metadata()?;
+ if !metadata.is_file() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Segmented input must contain regular files",
+ ));
+ }
+ let end = length
+ .checked_add(metadata.len())
+ .filter(|length| *length <= i64::MAX as u64)
+ .ok_or_else(|| {
+ io::Error::new(io::ErrorKind::InvalidInput, "Segmented input is too large")
+ })?;
+ parts.push(Part {
+ path: path.to_path_buf(),
+ start: length,
+ end,
+ });
+ length = end;
+ }
+ Ok(Self {
+ parts,
+ length,
+ position: 0,
+ current: None,
+ failure: None,
+ managed: None,
+ managed_current: None,
+ interrupt: None,
+ })
+ }
+
+ fn new_relocatable<'a>(
+ source: &RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ interrupt: Option<Arc<InterruptState>>,
+ ) -> io::Result<Self> {
+ let mut reader = Self::new([])?;
+ reader.interrupt = interrupt;
+ let mut managed = Vec::new();
+ let mut paths = paths.into_iter();
+ loop {
+ if reader.check_interrupt() {
+ return Err(reader.failure.take().unwrap());
+ }
+ let batch: Vec<_> = paths.by_ref().take(64).map(Path::to_path_buf).collect();
+ if batch.is_empty() {
+ break;
+ }
+ if reader.check_interrupt() {
+ return Err(reader.failure.take().unwrap());
+ }
+ let registered = source.readers(&batch)?;
+ if reader.check_interrupt() {
+ return Err(reader.failure.take().unwrap());
+ }
+ for (path, part) in batch.into_iter().zip(registered) {
+ let end = reader
+ .length
+ .checked_add(part.len())
+ .filter(|length| *length <= i64::MAX as u64)
+ .ok_or_else(|| {
+ io::Error::new(io::ErrorKind::InvalidInput, "Segmented input is too large")
+ })?;
+ reader.parts.push(Part {
+ path,
+ start: reader.length,
+ end,
+ });
+ managed.push(part);
+ reader.length = end;
+ }
+ }
+ reader.managed = Some(managed);
+ Ok(reader)
+ }
+
+ fn check_interrupt(&mut self) -> bool {
+ if self
+ .interrupt
+ .as_ref()
+ .is_some_and(|interrupt| interrupt.is_cancelled())
+ {
+ if self.failure.is_none() {
+ self.failure = Some(io::Error::new(
+ io::ErrorKind::Interrupted,
+ "Segmented input cancelled",
+ ));
+ }
+ true
+ } else {
+ false
+ }
+ }
+
+ fn read_managed(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
+ let index = self.parts.partition_point(|part| part.end <= self.position);
+ let part = self.parts.get(index).ok_or_else(|| {
+ io::Error::new(io::ErrorKind::InvalidData, "Missing segmented input range")
+ })?;
+ let readers = self
+ .managed
+ .as_mut()
+ .ok_or_else(|| io::Error::other("Missing managed sources"))?;
+ if self.managed_current != Some(index) {
+ if let Some(previous) = self.managed_current {
+ readers[previous].close()?;
+ }
+ self.managed_current = Some(index);
+ }
+ let reader = &mut readers[index];
+ reader.seek(SeekFrom::Start(self.position - part.start))?;
+ let count = reader.read(buffer)?;
+ self.position += count as u64;
+ Ok(count)
+ }
+
+ fn record_failure(&mut self, error: io::Error) -> c_int {
+ if self.failure.is_none() {
+ self.failure = Some(error);
+ }
+ ffmpeg::ffi::AVERROR(ffmpeg::ffi::EIO)
+ }
+}
+
+impl Read for ConcatenatedFiles {
+ fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
+ if buffer.is_empty() || self.position >= self.length {
+ return Ok(0);
+ }
+ if self.managed.is_some() {
+ return self.read_managed(buffer);
+ }
+ let index = self.parts.partition_point(|part| part.end <= self.position);
+ let part = self.parts.get(index).ok_or_else(|| {
+ io::Error::new(io::ErrorKind::InvalidData, "Missing segmented input range")
+ })?;
+ let length = part.end - part.start;
+ if self.current.as_ref().is_none_or(|open| open.index != index) {
+ let file = File::open(&part.path)?;
+ if file.metadata()?.len() != length {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Segmented input length changed",
+ ));
+ }
+ self.current = Some(OpenPart {
+ index,
+ file,
+ position: 0,
+ });
+ }
+ let current = self.current.as_mut().ok_or_else(|| {
+ io::Error::new(io::ErrorKind::InvalidData, "Missing segmented input file")
+ })?;
+ let position = self.position - part.start;
+ if current.position != position {
+ current.file.seek(SeekFrom::Start(position))?;
+ current.position = position;
+ }
+ let limit = (part.end - self.position).min(buffer.len() as u64) as usize;
+ let count = current.file.read(&mut buffer[..limit])?;
+ if count == 0 {
+ return Err(io::Error::new(
+ io::ErrorKind::UnexpectedEof,
+ "Segmented input was truncated",
+ ));
+ }
+ self.position += count as u64;
+ current.position += count as u64;
+ if self.position == part.end && current.file.metadata()?.len() != length {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Segmented input length changed",
+ ));
+ }
+ Ok(count)
+ }
+}
+
+impl Seek for ConcatenatedFiles {
+ fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
+ let position = match from {
+ SeekFrom::Start(position) => i128::from(position),
+ SeekFrom::Current(offset) => i128::from(self.position) + i128::from(offset),
+ SeekFrom::End(offset) => i128::from(self.length) + i128::from(offset),
+ };
+ if !(0..=i128::from(i64::MAX)).contains(&position) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "Invalid segmented input seek",
+ ));
+ }
+ self.position = position as u64;
+ Ok(self.position)
+ }
+}
+
+unsafe extern "C" fn read_packet(opaque: *mut c_void, buffer: *mut u8, size: c_int) -> c_int {
+ if opaque.is_null() || buffer.is_null() || size <= 0 {
+ return ffmpeg::ffi::AVERROR(ffmpeg::ffi::EINVAL);
+ }
+ let reader = unsafe { &mut *opaque.cast::<ConcatenatedFiles>() };
+ if reader.check_interrupt() {
+ return ffmpeg::ffi::AVERROR_EXIT;
+ }
+ let buffer = unsafe { std::slice::from_raw_parts_mut(buffer, size as usize) };
+ match catch_unwind(AssertUnwindSafe(|| reader.read(buffer))) {
+ Ok(Ok(0)) => ffmpeg::ffi::AVERROR_EOF,
+ Ok(Ok(count)) => count as c_int,
+ Ok(Err(error)) => reader.record_failure(error),
+ Err(_) => reader.record_failure(io::Error::other("Segmented input read panicked")),
+ }
+}
+
+unsafe extern "C" fn seek(opaque: *mut c_void, offset: i64, whence: c_int) -> i64 {
+ if opaque.is_null() {
+ return i64::from(ffmpeg::ffi::AVERROR(ffmpeg::ffi::EINVAL));
+ }
+ let reader = unsafe { &mut *opaque.cast::<ConcatenatedFiles>() };
+ if reader.check_interrupt() {
+ return i64::from(ffmpeg::ffi::AVERROR_EXIT);
+ }
+ let from = match whence & !ffmpeg::ffi::AVSEEK_FORCE {
+ ffmpeg::ffi::AVSEEK_SIZE => return reader.length as i64,
+ ffmpeg::ffi::SEEK_SET if offset >= 0 => SeekFrom::Start(offset as u64),
+ ffmpeg::ffi::SEEK_CUR => SeekFrom::Current(offset),
+ ffmpeg::ffi::SEEK_END => SeekFrom::End(offset),
+ _ => return i64::from(ffmpeg::ffi::AVERROR(ffmpeg::ffi::EINVAL)),
+ };
+ match catch_unwind(AssertUnwindSafe(|| reader.seek(from))) {
+ Ok(Ok(position)) => position as i64,
+ Ok(Err(_)) => i64::from(ffmpeg::ffi::AVERROR(ffmpeg::ffi::EINVAL)),
+ Err(_) => {
+ i64::from(reader.record_failure(io::Error::other("Segmented input seek panicked")))
+ }
+ }
+}
+
+struct IoContext {
+ context: NonNull<ffmpeg::ffi::AVIOContext>,
+ reader: Box<ConcatenatedFiles>,
+}
+
+// AVIO and its boxed callback state are exclusively owned and never accessed concurrently.
+// Moving this owner preserves every allocation and keeps Send callback state alive until close.
+unsafe impl Send for IoContext {}
+
+impl IoContext {
+ fn new(reader: ConcatenatedFiles) -> Result<Self, RemuxError> {
+ fn require_send<T: Send>() {}
+ require_send::<ConcatenatedFiles>();
+ let mut reader = Box::new(reader);
+ let buffer_size = 64 * 1024;
+ let buffer = unsafe { ffmpeg::ffi::av_malloc(buffer_size) }.cast::<u8>();
+ if buffer.is_null() {
+ return Err(io::Error::from(io::ErrorKind::OutOfMemory).into());
+ }
+ let context = unsafe {
+ ffmpeg::ffi::avio_alloc_context(
+ buffer,
+ buffer_size as c_int,
+ 0,
+ ptr::from_mut(reader.as_mut()).cast(),
+ Some(read_packet),
+ None,
+ Some(seek),
+ )
+ };
+ let Some(context) = NonNull::new(context) else {
+ unsafe { ffmpeg::ffi::av_free(buffer.cast()) };
+ return Err(io::Error::from(io::ErrorKind::OutOfMemory).into());
+ };
+ Ok(Self { context, reader })
+ }
+}
+
+impl Drop for IoContext {
+ fn drop(&mut self) {
+ let mut context = self.context.as_ptr();
+ unsafe {
+ // FFmpeg may replace the buffer; custom I/O owns the final pointer separately.
+ ffmpeg::ffi::av_free((*context).buffer.cast());
+ (*context).buffer = ptr::null_mut();
+ ffmpeg::ffi::avio_context_free(&mut context);
+ }
+ }
+}
+
+pub struct SegmentedInput {
+ // Close the format input before freeing its custom I/O buffer and callback state.
+ input: ffmpeg::format::context::Input,
+ io: IoContext,
+}
+
+impl SegmentedInput {
+ pub fn open<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Result<Self, RemuxError> {
+ Self::open_reader(ConcatenatedFiles::new(paths)?)
+ }
+
+ pub fn open_relocatable<'a>(
+ source: &RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ ) -> Result<Self, RemuxError> {
+ Self::open_reader(ConcatenatedFiles::new_relocatable(source, paths, None)?)
+ }
+
+ pub fn open_relocatable_interruptible<'a>(
+ source: &RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
+ ) -> Result<Self, RemuxError> {
+ let interrupt = Arc::new(InterruptState {
+ callback: interrupt,
+ cancelled: AtomicBool::new(false),
+ });
+ Self::open_reader(ConcatenatedFiles::new_relocatable(
+ source,
+ paths,
+ Some(interrupt),
+ )?)
+ }
+
+ fn open_reader(reader: ConcatenatedFiles) -> Result<Self, RemuxError> {
+ let mut io = IoContext::new(reader)?;
+ if io.reader.check_interrupt() {
+ return Err(io.reader.failure.take().unwrap().into());
+ }
+ let mut context = unsafe { ffmpeg::ffi::avformat_alloc_context() };
+ if context.is_null() {
+ return Err(io::Error::from(io::ErrorKind::OutOfMemory).into());
+ }
+ let opened = unsafe {
+ if let Some(interrupt) = &io.reader.interrupt {
+ (*context).interrupt_callback = ffmpeg::ffi::AVIOInterruptCB {
+ callback: Some(interrupt_callback),
+ opaque: Arc::as_ptr(interrupt).cast_mut().cast(),
+ };
+ }
+ (*context).pb = io.context.as_ptr();
+ (*context).flags |= ffmpeg::ffi::AVFMT_FLAG_CUSTOM_IO;
+ ffmpeg::ffi::avformat_open_input(
+ &mut context,
+ ptr::null(),
+ ptr::null(),
+ ptr::null_mut(),
+ )
+ };
+ let interrupted = io.reader.check_interrupt();
+ if opened < 0 || interrupted {
+ unsafe { ffmpeg::ffi::avformat_close_input(&mut context) };
+ return Err(match io.reader.failure.take() {
+ Some(error) => error.into(),
+ None => ffmpeg::Error::from(opened).into(),
+ });
+ }
+ let input = unsafe { ffmpeg::format::context::Input::wrap(context) };
+ let mut opened = Self { input, io };
+ let found = unsafe {
+ ffmpeg::ffi::avformat_find_stream_info(opened.input.as_mut_ptr(), ptr::null_mut())
+ };
+ opened.io.reader.check_interrupt();
+ if let Some(error) = opened.io.reader.failure.take() {
+ return Err(error.into());
+ }
+ if found < 0 {
+ return Err(ffmpeg::Error::from(found).into());
+ }
+ Ok(opened)
+ }
+
+ pub fn input(&self) -> &ffmpeg::format::context::Input {
+ &self.input
+ }
+
+ pub fn io_error(&self) -> Option<&io::Error> {
+ self.io.reader.failure.as_ref()
+ }
+
+ pub fn read_packet(&mut self, packet: &mut ffmpeg::Packet) -> Result<(), ffmpeg::Error> {
+ if self.io.reader.check_interrupt() {
+ return Err(ffmpeg::Error::Exit);
+ }
+ if self.io.reader.failure.is_some() {
+ return Err(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::EIO,
+ });
+ }
+ let result = packet.read(&mut self.input);
+ if self.io.reader.check_interrupt() {
+ return Err(ffmpeg::Error::Exit);
+ }
+ if self.io.reader.failure.is_some() {
+ return Err(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::EIO,
+ });
+ }
+ result
+ }
+
+ pub fn seek(&mut self, timestamp: i64) -> Result<(), ffmpeg::Error> {
+ if self.io.reader.check_interrupt() {
+ return Err(ffmpeg::Error::Exit);
+ }
+ if self.io.reader.failure.is_some() {
+ return Err(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::EIO,
+ });
+ }
+ let result = self.input.seek(timestamp, ..timestamp);
+ if self.io.reader.check_interrupt() {
+ return Err(ffmpeg::Error::Exit);
+ }
+ if self.io.reader.failure.is_some() {
+ return Err(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::EIO,
+ });
+ }
+ result
+ }
+}
+
+pub(crate) fn with_input<'a, T>(
+ paths: impl IntoIterator<Item = &'a Path>,
+ operation: impl FnOnce(&mut ffmpeg::format::context::Input) -> Result<T, RemuxError>,
+) -> Result<T, RemuxError> {
+ let mut input = SegmentedInput::open(paths)?;
+ let result = operation(&mut input.input);
+ match input.io.reader.failure.take() {
+ Some(error) => Err(error.into()),
+ None => result,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn wave_parts(directory: &Path) -> Vec<PathBuf> {
+ let data_length = 48_000_u32 * 2 * 20;
+ let mut bytes = Vec::new();
+ bytes.extend_from_slice(b"RIFF");
+ bytes.extend_from_slice(&(data_length + 36).to_le_bytes());
+ bytes.extend_from_slice(b"WAVEfmt ");
+ bytes.extend_from_slice(&16_u32.to_le_bytes());
+ bytes.extend_from_slice(&1_u16.to_le_bytes());
+ bytes.extend_from_slice(&1_u16.to_le_bytes());
+ bytes.extend_from_slice(&48_000_u32.to_le_bytes());
+ bytes.extend_from_slice(&96_000_u32.to_le_bytes());
+ bytes.extend_from_slice(&2_u16.to_le_bytes());
+ bytes.extend_from_slice(&16_u16.to_le_bytes());
+ bytes.extend_from_slice(b"data");
+ bytes.extend_from_slice(&data_length.to_le_bytes());
+ for index in 0..data_length / 2 {
+ bytes.extend_from_slice(&(index as i16).to_le_bytes());
+ }
+ bytes
+ .chunks(16_384)
+ .enumerate()
+ .map(|(index, data)| {
+ let path = directory.join(format!("part-{index:03}.bin"));
+ std::fs::write(&path, data).unwrap();
+ path
+ })
+ .collect()
+ }
+
+ #[test]
+ fn owned_input_can_move_seek_and_read_until_eof() {
+ let directory = tempfile::tempdir().unwrap();
+ let paths = wave_parts(directory.path());
+ let input = SegmentedInput::open(paths.iter().map(PathBuf::as_path)).unwrap();
+ let mut input = Box::new(input);
+ assert_eq!(input.input().streams().count(), 1);
+ for timestamp in [0, 10_000_000, 1_000_000, 19_000_000] {
+ input.seek(timestamp).unwrap();
+ let mut packet = ffmpeg::Packet::empty();
+ input.read_packet(&mut packet).unwrap();
+ assert!(packet.size() > 0);
+ }
+ loop {
+ let mut packet = ffmpeg::Packet::empty();
+ match input.read_packet(&mut packet) {
+ Ok(()) => {}
+ Err(ffmpeg::Error::Eof) => break,
+ Err(error) => panic!("Unexpected packet read failure: {error}"),
+ }
+ }
+ assert!(input.io.reader.failure.is_none());
+ }
+
+ #[test]
+ fn missing_later_part_is_a_persistent_error_even_after_seek() {
+ let directory = tempfile::tempdir().unwrap();
+ let paths = wave_parts(directory.path());
+ let mut input = SegmentedInput::open(paths.iter().map(PathBuf::as_path)).unwrap();
+ for path in paths.iter().skip(1) {
+ std::fs::remove_file(path).unwrap();
+ }
+ let mut failed = false;
+ for _ in 0..1_000 {
+ let mut packet = ffmpeg::Packet::empty();
+ match input.read_packet(&mut packet) {
+ Ok(()) => {}
+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EIO => {
+ failed = true;
+ break;
+ }
+ Err(error) => panic!("Input failure was misreported: {error}"),
+ }
+ }
+ assert!(failed, "Missing data must fail before clean EOF");
+ let mut packet = ffmpeg::Packet::empty();
+ assert_eq!(
+ input.read_packet(&mut packet),
+ Err(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::EIO
+ })
+ );
+ assert_eq!(
+ input.seek(0),
+ Err(ffmpeg::Error::Other {
+ errno: ffmpeg::ffi::EIO
+ })
+ );
+ }
+
+ #[test]
+ fn concatenated_reads_and_seeks_match_flat_bytes() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut paths = Vec::new();
+ let mut bytes = Vec::new();
+ for (index, size) in [0, 31, 131_071, 1, 0, 63, 8192].into_iter().enumerate() {
+ let data: Vec<_> = (0..size)
+ .map(|offset| (offset * 13 + index) as u8)
+ .collect();
+ let path = directory
+ .path()
+ .join(format!("fragment '{index}' café.bin"));
+ std::fs::write(&path, &data).unwrap();
+ paths.push(path);
+ bytes.extend(data);
+ }
+ let mut reader = ConcatenatedFiles::new(paths.iter().map(PathBuf::as_path)).unwrap();
+ let mut actual = Vec::new();
+ reader.read_to_end(&mut actual).unwrap();
+ assert_eq!(actual, bytes);
+ let mut reference = io::Cursor::new(&bytes);
+ reader.rewind().unwrap();
+ let mut state = 57_u64;
+ for index in 0..1000 {
+ state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
+ let from = match index % 3 {
+ 0 => SeekFrom::Start(state % (bytes.len() as u64 + 17)),
+ 1 => SeekFrom::Current((state % 513) as i64 - 256),
+ _ => SeekFrom::End(17 - (state % (bytes.len() as u64 + 1)) as i64),
+ };
+ let actual = reader.seek(from);
+ let expected = reference.seek(from);
+ assert_eq!(actual.is_ok(), expected.is_ok());
+ if let (Ok(actual), Ok(expected)) = (actual, expected) {
+ assert_eq!(actual, expected);
+ }
+ let count = state % 4097;
+ let mut actual = Vec::new();
+ let mut expected = Vec::new();
+ reader
+ .by_ref()
+ .take(count)
+ .read_to_end(&mut actual)
+ .unwrap();
+ reference
+ .by_ref()
+ .take(count)
+ .read_to_end(&mut expected)
+ .unwrap();
+ assert_eq!(actual, expected);
+ assert_eq!(reader.position, reference.position());
+ }
+ }
+
+ #[test]
+ fn changed_fragment_lengths_and_missing_files_are_errors() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("fragment.bin");
+ for changed_length in [3, 32] {
+ std::fs::write(&path, [0x35; 16]).unwrap();
+ let mut reader = ConcatenatedFiles::new([path.as_path()]).unwrap();
+ let mut prefix = [0; 2];
+ reader.read_exact(&mut prefix).unwrap();
+ File::options()
+ .write(true)
+ .open(&path)
+ .unwrap()
+ .set_len(changed_length)
+ .unwrap();
+ assert!(reader.read_to_end(&mut Vec::new()).is_err());
+ }
+ std::fs::write(&path, [0x35; 16]).unwrap();
+ let mut reader = ConcatenatedFiles::new([path.as_path()]).unwrap();
+ std::fs::remove_file(&path).unwrap();
+ assert_eq!(
+ reader.read(&mut [0; 1]).unwrap_err().kind(),
+ io::ErrorKind::NotFound
+ );
+ }
+
+ #[test]
+ fn seek_handles_large_offsets_and_rejects_overflow_without_moving() {
+ let mut reader = ConcatenatedFiles::new([]).unwrap();
+ assert_eq!(reader.seek(SeekFrom::Start(1 << 40)).unwrap(), 1 << 40);
+ assert_eq!(reader.seek(SeekFrom::Current(17)).unwrap(), (1 << 40) + 17);
+ assert!(reader.seek(SeekFrom::Start(u64::MAX)).is_err());
+ assert_eq!(reader.position, (1 << 40) + 17);
+ assert!(reader.seek(SeekFrom::Current(i64::MIN)).is_err());
+ assert_eq!(reader.position, (1 << 40) + 17);
+ assert_eq!(reader.read(&mut [0; 4]).unwrap(), 0);
+ reader.seek(SeekFrom::Start(i64::MAX as u64)).unwrap();
+ assert!(reader.seek(SeekFrom::Current(1)).is_err());
+ assert_eq!(reader.position, i64::MAX as u64);
+ assert_eq!(reader.seek(SeekFrom::End(0)).unwrap(), 0);
+ }
+
+ #[test]
+ fn io_callbacks_distinguish_eof_and_preserve_read_failures() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("fragment.bin");
+ std::fs::write(&path, [0x35; 16]).unwrap();
+ let mut reader = ConcatenatedFiles::new([path.as_path()]).unwrap();
+ let opaque = ptr::from_mut(&mut reader).cast();
+ let mut buffer = [0; 32];
+ unsafe {
+ assert_eq!(seek(opaque, 0, ffmpeg::ffi::AVSEEK_SIZE), 16);
+ assert_eq!(
+ seek(opaque, 0, ffmpeg::ffi::SEEK_SET | ffmpeg::ffi::AVSEEK_FORCE),
+ 0
+ );
+ assert_eq!(read_packet(opaque, buffer.as_mut_ptr(), 32), 16);
+ assert_eq!(
+ read_packet(opaque, buffer.as_mut_ptr(), 32),
+ ffmpeg::ffi::AVERROR_EOF
+ );
+ }
+ assert!(reader.failure.is_none());
+ reader.current = None;
+ reader.rewind().unwrap();
+ std::fs::remove_file(&path).unwrap();
+ unsafe {
+ assert_eq!(
+ read_packet(opaque, buffer.as_mut_ptr(), 32),
+ ffmpeg::ffi::AVERROR(ffmpeg::ffi::EIO)
+ );
+ assert_eq!(seek(opaque, 0, ffmpeg::ffi::SEEK_END), 16);
+ assert_eq!(
+ read_packet(opaque, buffer.as_mut_ptr(), 32),
+ ffmpeg::ffi::AVERROR_EOF
+ );
+ }
+ assert_eq!(reader.failure.unwrap().kind(), io::ErrorKind::NotFound);
+ }
+ fn relative_parts(paths: &[PathBuf]) -> Vec<PathBuf> {
+ paths
+ .iter()
+ .map(|path| PathBuf::from(path.file_name().unwrap()))
+ .collect()
+ }
+
+ #[derive(Debug, PartialEq, Eq)]
+ struct PacketSnapshot {
+ stream: usize,
+ pts: Option<i64>,
+ dts: Option<i64>,
+ duration: i64,
+ flags: i32,
+ bytes: Vec<u8>,
+ }
+
+ fn next_snapshot(input: &mut SegmentedInput) -> Option<PacketSnapshot> {
+ let mut packet = ffmpeg::Packet::empty();
+ match input.read_packet(&mut packet) {
+ Ok(()) => Some(PacketSnapshot {
+ stream: packet.stream(),
+ pts: packet.pts(),
+ dts: packet.dts(),
+ duration: packet.duration(),
+ flags: packet.flags().bits(),
+ bytes: packet.data().unwrap_or_default().to_vec(),
+ }),
+ Err(ffmpeg::Error::Eof) => None,
+ Err(error) => panic!("Unexpected packet failure: {error}"),
+ }
+ }
+
+ #[test]
+ fn live_ffmpeg_packets_and_seeks_survive_relocation_failure_and_rollback() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ let reference = directory.path().join("reference");
+ std::fs::create_dir(&original).unwrap();
+ std::fs::create_dir(&reference).unwrap();
+ let paths = wave_parts(&original);
+ let reference_paths = wave_parts(&reference);
+ let relative = relative_parts(&paths);
+ let source = RelocatableSource::new(original.clone()).unwrap();
+ let mut input =
+ SegmentedInput::open_relocatable(&source, relative.iter().map(PathBuf::as_path))
+ .unwrap();
+ let mut baseline =
+ SegmentedInput::open(reference_paths.iter().map(PathBuf::as_path)).unwrap();
+ let context = unsafe { input.input().as_ptr() };
+ assert!(input.io.reader.position + 65_536 < input.io.reader.length);
+ for _ in 0..8 {
+ assert_eq!(next_snapshot(&mut input), next_snapshot(&mut baseline));
+ }
+ source.relocate(retained.clone()).unwrap();
+ std::fs::create_dir(&original).unwrap();
+ let replacement = original.join(&relative[0]);
+ std::fs::write(&replacement, b"ordinary published output").unwrap();
+ let mut ordinary_output = ConcatenatedFiles::new([replacement.as_path()]).unwrap();
+ let mut bytes = Vec::new();
+ ordinary_output.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"ordinary published output");
+ drop(ordinary_output);
+ let mut continued_bytes = 0;
+ loop {
+ let actual = next_snapshot(&mut input);
+ let expected = next_snapshot(&mut baseline);
+ assert_eq!(actual, expected);
+ let Some(actual) = actual else { break };
+ continued_bytes += actual.bytes.len();
+ }
+ assert!(continued_bytes > 1_000_000);
+ assert_eq!(
+ source.relocate(original.clone()).unwrap_err().kind(),
+ io::ErrorKind::AlreadyExists
+ );
+ for timestamp in [19_000_000, 0, 8_000_000, 1_000_000] {
+ input.seek(timestamp).unwrap();
+ baseline.seek(timestamp).unwrap();
+ for _ in 0..8 {
+ assert_eq!(next_snapshot(&mut input), next_snapshot(&mut baseline));
+ }
+ }
+ std::fs::remove_file(replacement).unwrap();
+ std::fs::remove_dir(&original).unwrap();
+ source.relocate(original.clone()).unwrap();
+ for timestamp in [0, 18_000_000, 2_000_000] {
+ input.seek(timestamp).unwrap();
+ baseline.seek(timestamp).unwrap();
+ for _ in 0..16 {
+ assert_eq!(next_snapshot(&mut input), next_snapshot(&mut baseline));
+ }
+ }
+ assert_eq!(unsafe { input.input().as_ptr() }, context);
+ assert!(input.io_error().is_none());
+ for (original, reference) in paths.iter().zip(reference_paths) {
+ assert_eq!(
+ std::fs::read(original).unwrap(),
+ std::fs::read(reference).unwrap()
+ );
+ }
+ }
+
+ #[test]
+ fn live_ffmpeg_input_moves_to_a_worker_and_keeps_reading_after_relocation() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let reference = directory.path().join("reference");
+ std::fs::create_dir(&original).unwrap();
+ std::fs::create_dir(&reference).unwrap();
+ let paths = wave_parts(&original);
+ let reference_paths = wave_parts(&reference);
+ let mut baseline =
+ SegmentedInput::open(reference_paths.iter().map(PathBuf::as_path)).unwrap();
+ let mut expected = Vec::new();
+ while let Some(packet) = next_snapshot(&mut baseline) {
+ expected.push(packet);
+ }
+ let source = RelocatableSource::new(original).unwrap();
+ let relative = relative_parts(&paths);
+ let mut input =
+ SegmentedInput::open_relocatable(&source, relative.iter().map(PathBuf::as_path))
+ .unwrap();
+ let (ready, ready_rx) = std::sync::mpsc::channel();
+ let (resume, resume_rx) = std::sync::mpsc::channel();
+ let worker = std::thread::spawn(move || {
+ let mut actual = vec![next_snapshot(&mut input).unwrap()];
+ ready.send(()).unwrap();
+ resume_rx
+ .recv_timeout(std::time::Duration::from_secs(10))
+ .unwrap();
+ while let Some(packet) = next_snapshot(&mut input) {
+ actual.push(packet);
+ }
+ actual
+ });
+ ready_rx
+ .recv_timeout(std::time::Duration::from_secs(10))
+ .unwrap();
+ source.relocate(directory.path().join("retained")).unwrap();
+ resume.send(()).unwrap();
+ assert_eq!(worker.join().unwrap(), expected);
+ }
+
+ #[test]
+ fn managed_missing_lazy_part_is_a_sticky_io_failure() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ std::fs::create_dir(&original).unwrap();
+ let paths = wave_parts(&original);
+ let relative = relative_parts(&paths);
+ let source = RelocatableSource::new(original).unwrap();
+ let mut input =
+ SegmentedInput::open_relocatable(&source, relative.iter().map(PathBuf::as_path))
+ .unwrap();
+ assert!(input.io.reader.position + 65_536 < input.io.reader.length);
+ std::fs::remove_file(paths.last().unwrap()).unwrap();
+ let mut failed = false;
+ for _ in 0..1_000 {
+ let mut packet = ffmpeg::Packet::empty();
+ match input.read_packet(&mut packet) {
+ Ok(()) => {}
+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EIO => {
+ failed = true;
+ break;
+ }
+ Err(error) => panic!("Missing source was misreported: {error}"),
+ }
+ }
+ assert!(failed);
+ assert_eq!(input.io_error().unwrap().kind(), io::ErrorKind::NotFound);
+ assert!(input.seek(0).is_err());
+ assert!(input.read_packet(&mut ffmpeg::Packet::empty()).is_err());
+ assert_eq!(input.io_error().unwrap().kind(), io::ErrorKind::NotFound);
+ }
+
+ #[test]
+ fn managed_interrupt_is_owned_before_open_and_remains_sticky() {
+ let directory = tempfile::tempdir().unwrap();
+ let paths = wave_parts(directory.path());
+ let relative = relative_parts(&paths);
+ let source = RelocatableSource::new(directory.path().to_path_buf()).unwrap();
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let weak = Arc::downgrade(&cancelled);
+ let owned = cancelled.clone();
+ let mut input = SegmentedInput::open_relocatable_interruptible(
+ &source,
+ relative.iter().map(PathBuf::as_path),
+ Arc::new(move || owned.load(Ordering::Relaxed)),
+ )
+ .unwrap();
+ assert!(next_snapshot(&mut input).is_some());
+ cancelled.store(true, Ordering::Relaxed);
+ assert_eq!(
+ input.read_packet(&mut ffmpeg::Packet::empty()),
+ Err(ffmpeg::Error::Exit)
+ );
+ assert_eq!(input.io_error().unwrap().kind(), io::ErrorKind::Interrupted);
+ cancelled.store(false, Ordering::Relaxed);
+ assert_eq!(input.seek(0), Err(ffmpeg::Error::Exit));
+ drop(cancelled);
+ assert!(weak.upgrade().is_some());
+ drop(input);
+ assert!(weak.upgrade().is_none());
+
+ let marker = Arc::new(());
+ let weak = Arc::downgrade(&marker);
+ let cancelled = Arc::new(move || {
+ let _ = &marker;
+ true
+ });
+ let missing = Path::new("missing");
+ let error = SegmentedInput::open_relocatable_interruptible(&source, [missing], cancelled)
+ .err()
+ .unwrap();
+ assert!(error.to_string().contains("cancelled"));
+ assert!(weak.upgrade().is_none());
+ }
+
+ #[test]
+ fn panicking_interrupt_cannot_unwind_through_ffmpeg() {
+ let directory = tempfile::tempdir().unwrap();
+ let source = RelocatableSource::new(directory.path().to_path_buf()).unwrap();
+ let result = SegmentedInput::open_relocatable_interruptible(
+ &source,
+ [Path::new("missing")],
+ Arc::new(|| panic!("interrupted")),
+ );
+ assert!(result.err().unwrap().to_string().contains("cancelled"));
+ }
+
+ #[test]
+ fn managed_registration_observes_cancellation_between_bounded_batches() {
+ let directory = tempfile::tempdir().unwrap();
+ let paths = wave_parts(directory.path());
+ let source = RelocatableSource::new(directory.path().to_path_buf()).unwrap();
+ let relative: Vec<_> = paths
+ .iter()
+ .map(|path| PathBuf::from(path.file_name().unwrap()))
+ .collect();
+ std::fs::remove_file(&paths[64]).unwrap();
+ let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let observed = calls.clone();
+ let interrupt = Arc::new(InterruptState {
+ callback: Arc::new(move || observed.fetch_add(1, Ordering::Relaxed) >= 2),
+ cancelled: AtomicBool::new(false),
+ });
+ let result = ConcatenatedFiles::new_relocatable(
+ &source,
+ relative.iter().map(PathBuf::as_path),
+ Some(interrupt),
+ );
+ assert_eq!(result.err().unwrap().kind(), io::ErrorKind::Interrupted);
+ assert_eq!(calls.load(Ordering::Relaxed), 3);
+ }
+
+ #[test]
+ fn cancellation_callback_can_relocate_between_registration_batches() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ std::fs::create_dir(&original).unwrap();
+ let paths = wave_parts(&original);
+ let expected: Vec<u8> = paths
+ .iter()
+ .flat_map(|path| std::fs::read(path).unwrap())
+ .collect();
+ let relative: Vec<_> = paths
+ .iter()
+ .map(|path| PathBuf::from(path.file_name().unwrap()))
+ .collect();
+ let source = RelocatableSource::new(original.clone()).unwrap();
+ let callback_source = source.clone();
+ let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let observed = calls.clone();
+ let interrupt = Arc::new(InterruptState {
+ callback: Arc::new(move || {
+ if observed.fetch_add(1, Ordering::Relaxed) == 2 {
+ callback_source
+ .relocate_from(&original, retained.clone())
+ .unwrap();
+ }
+ false
+ }),
+ cancelled: AtomicBool::new(false),
+ });
+ let mut reader = ConcatenatedFiles::new_relocatable(
+ &source,
+ relative.iter().map(PathBuf::as_path),
+ Some(interrupt),
+ )
+ .unwrap();
+ let mut actual = Vec::new();
+ reader.read_to_end(&mut actual).unwrap();
+ assert_eq!(actual, expected);
+ assert!(calls.load(Ordering::Relaxed) > 3);
+ }
+}
diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rs
index 8dad727e5..53179c761 100644
--- a/crates/project/src/cursor.rs
+++ b/crates/project/src/cursor.rs
@@ -74,8 +74,11 @@ pub struct CursorEvents {
impl CursorEvents {
pub fn load_from_file(path: &Path) -> Result<Self, String> {
let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {e}"))?;
- serde_json::from_reader(BufReader::new(file))
- .map_err(|e| format!("Failed to parse cursor data: {e}"))
+ Self::load_from_reader(BufReader::new(file))
+ }
+
+ pub fn load_from_reader(reader: impl std::io::Read) -> Result<Self, String> {
+ serde_json::from_reader(reader).map_err(|e| format!("Failed to parse cursor data: {e}"))
}
pub fn stabilize_short_lived_cursor_shapes(
@@ -361,6 +364,55 @@ mod tests {
assert_eq!(CursorData::load_from_file(&missing).unwrap_err(), expected);
}
+ #[test]
+ fn cursor_reader_preserves_unicode_and_events_across_short_reads() {
+ struct ShortReads<'a>(&'a [u8]);
+
+ impl std::io::Read for ShortReads<'_> {
+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
+ let count = buffer.len().min(3).min(self.0.len());
+ buffer[..count].copy_from_slice(&self.0[..count]);
+ self.0 = &self.0[count..];
+ Ok(count)
+ }
+ }
+
+ let expected = CursorData {
+ clicks: vec![click_event(12.5, "文字🖱")],
+ moves: vec![move_event(1.25, "文字🖱"), move_event(99.75, "pointer")],
+ cursor_images: CursorImages::default(),
+ };
+ let bytes = serde_json::to_vec(&expected).unwrap();
+ let events = CursorEvents::load_from_reader(ShortReads(&bytes)).unwrap();
+ assert_eq!(events.clicks, expected.clicks);
+ assert_eq!(events.moves, expected.moves);
+ }
+
+ #[test]
+ fn cursor_reader_does_not_turn_late_input_failure_into_success() {
+ struct FailingReader {
+ prefix: std::io::Cursor<Vec<u8>>,
+ }
+
+ impl std::io::Read for FailingReader {
+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
+ let count = std::io::Read::read(&mut self.prefix, buffer)?;
+ if count == 0 {
+ return Err(std::io::Error::other("retained source failed"));
+ }
+ Ok(count)
+ }
+ }
+
+ let bytes = serde_json::to_vec(&CursorEvents::default()).unwrap();
+ let error = CursorEvents::load_from_reader(FailingReader {
+ prefix: std::io::Cursor::new(bytes),
+ })
+ .unwrap_err();
+ assert!(error.starts_with("Failed to parse cursor data: "));
+ assert!(error.contains("retained source failed"));
+ }
+
fn move_event(time_ms: f64, cursor_id: &str) -> CursorMoveEvent {
CursorMoveEvent {
active_modifiers: vec![],
diff --git a/crates/project/src/keyboard.rs b/crates/project/src/keyboard.rs
index b254b4540..20b915008 100644
--- a/crates/project/src/keyboard.rs
+++ b/crates/project/src/keyboard.rs
@@ -31,6 +31,10 @@ impl KeyboardEvents {
pub fn load_from_file(path: &Path) -> Result<Self, String> {
let bytes =
std::fs::read(path).map_err(|e| format!("Failed to open keyboard events file: {e}"))?;
+ Self::from_bytes(&bytes, path)
+ }
+
+ pub fn from_bytes(bytes: &[u8], source_path: &Path) -> Result<Self, String> {
let config = bincode::config::standard();
if let Some(payload) = bytes.strip_prefix(KEYBOARD_EVENTS_MAGIC) {
@@ -39,16 +43,16 @@ impl KeyboardEvents {
.map_err(|e| format!("Failed to parse keyboard events binary payload: {e}"));
}
- if path
+ if source_path
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension == "bin")
- && let Ok((events, _)) = bincode::serde::decode_from_slice::<Self, _>(&bytes, config)
+ && let Ok((events, _)) = bincode::serde::decode_from_slice::<Self, _>(bytes, config)
{
return Ok(events);
}
- serde_json::from_slice(&bytes)
+ serde_json::from_slice(bytes)
.map_err(|e| format!("Failed to parse keyboard events legacy JSON: {e}"))
}
@@ -1078,6 +1082,57 @@ mod tests {
assert_eq!(loaded.presses, events.presses);
}
+ #[test]
+ fn keyboard_bytes_preserve_versioned_unversioned_and_json_dispatch() {
+ let expected = KeyboardEvents {
+ presses: vec![key_down("文字🖱", 12.5), key_up("文字🖱", 19.75)],
+ };
+ let binary = bincode::serde::encode_to_vec(&expected, bincode::config::standard()).unwrap();
+ let mut versioned = KEYBOARD_EVENTS_MAGIC.to_vec();
+ versioned.extend(&binary);
+ let json = serde_json::to_vec(&expected).unwrap();
+ for (bytes, path) in [
+ (&versioned, "keyboard.bin"),
+ (&versioned, "keyboard.json"),
+ (&binary, "keyboard.bin"),
+ (&json, "keyboard.bin"),
+ (&json, "keyboard.json"),
+ (&json, "keyboard.BIN"),
+ ] {
+ let events = KeyboardEvents::from_bytes(bytes, Path::new(path)).unwrap();
+ assert_eq!(events.presses, expected.presses);
+ }
+ assert!(KeyboardEvents::from_bytes(&binary, Path::new("keyboard.BIN")).is_err());
+ }
+
+ #[test]
+ fn keyboard_bytes_keep_existing_trailing_data_and_error_behavior() {
+ let expected = KeyboardEvents {
+ presses: vec![key_down("a", 1.0)],
+ };
+ let mut binary =
+ bincode::serde::encode_to_vec(&expected, bincode::config::standard()).unwrap();
+ binary.extend(b"trailing bytes");
+ assert_eq!(
+ KeyboardEvents::from_bytes(&binary, Path::new("keyboard.bin"))
+ .unwrap()
+ .presses,
+ expected.presses
+ );
+ let mut versioned = KEYBOARD_EVENTS_MAGIC.to_vec();
+ versioned.extend(b"{\"presses\":[]}");
+ assert!(
+ KeyboardEvents::from_bytes(&versioned, Path::new("keyboard.json"))
+ .unwrap_err()
+ .starts_with("Failed to parse keyboard events binary payload: ")
+ );
+ assert!(
+ KeyboardEvents::from_bytes(b"{\"presses\":[]} trailing", Path::new("keyboard.bin"))
+ .unwrap_err()
+ .starts_with("Failed to parse keyboard events legacy JSON: ")
+ );
+ }
+
#[test]
fn space_splits_continuous_typing_into_words() {
let events = KeyboardEvents {
diff --git a/crates/recording/examples/studio-finalization-benchmark.rs b/crates/recording/examples/studio-finalization-benchmark.rs
new file mode 100644
index 000000000..0ea18c7bc
--- /dev/null
+++ b/crates/recording/examples/studio-finalization-benchmark.rs
@@ -0,0 +1,46 @@
+use std::{path::PathBuf, time::Instant};
+
+use cap_project::{RecordingMeta, StudioRecordingStatus};
+use cap_recording::recovery::RecoveryManager;
+
+fn main() -> anyhow::Result<()> {
+ tracing_subscriber::fmt()
+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
+ .with_writer(std::io::stderr)
+ .init();
+ let path = std::env::args_os()
+ .nth(1)
+ .map(PathBuf::from)
+ .ok_or_else(|| anyhow::anyhow!("Pass a disposable copy of an unfinished Studio project"))?;
+ let before = RecordingMeta::load_for_project(&path)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ anyhow::ensure!(
+ before
+ .studio_meta()
+ .is_some_and(|meta| matches!(meta.status(), StudioRecordingStatus::NeedsRemux)),
+ "The benchmark requires a Studio project that needs remuxing"
+ );
+ let started = Instant::now();
+ let remuxed = RecoveryManager::remux_if_needed(&path)?;
+ let elapsed = started.elapsed();
+ anyhow::ensure!(remuxed, "The benchmark did not finalize media");
+ let after = RecordingMeta::load_for_project(&path)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ anyhow::ensure!(
+ after
+ .studio_meta()
+ .is_some_and(|meta| matches!(meta.status(), StudioRecordingStatus::Complete)),
+ "Finalized metadata is not complete"
+ );
+ let project = cap_project::ProjectConfiguration::load(&path)?;
+ project.validate().map_err(anyhow::Error::msg)?;
+ println!(
+ "{}",
+ serde_json::json!({
+ "elapsedMs": elapsed.as_secs_f64() * 1000.0,
+ "durationSeconds": project.timeline.map(|timeline| timeline.duration()),
+ "remuxed": remuxed,
+ })
+ );
+ Ok(())
+}
diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rs
index 207dcf1e3..67cfad71c 100644
--- a/crates/recording/src/recovery.rs
+++ b/crates/recording/src/recovery.rs
@@ -1,8 +1,10 @@
use std::{
path::{Path, PathBuf},
- time::Duration,
+ sync::Arc,
+ time::{Duration, Instant},
};
+use cap_enc_ffmpeg::RelocatableSource;
use cap_enc_ffmpeg::fragmented_mp4::tail_is_complete;
use cap_enc_ffmpeg::remux::{
concatenate_audio_to_ogg, concatenate_m4s_segments_with_init,
@@ -19,6 +21,19 @@ use relative_path::RelativePathBuf;
use tracing::{debug, warn};
use crate::output_pipeline::{HealthSender, PipelineHealthEvent, emit_health};
+use crate::studio_recording::CompletedRecording;
+
+mod preparing_observer;
+mod preparing_projection;
+
+pub use preparing_observer::{
+ LivePreparingStudioSources, PreparingAudioLease, PreparingAudioTrack, PreparingSidecarKind,
+ PreparingSidecarLease, PreparingStudioIdentity, PreparingStudioJob, PreparingStudioObserver,
+ PreparingStudioSources, PreparingStudioState, PreparingVideoLease, PreparingVideoTrack,
+};
+pub use preparing_projection::{
+ PreparingAudioInput, PreparingCursorImage, PreparingStudioSegment, PreparingVideoInput,
+};
macro_rules! finalization_info {
($($arg:tt)*) => {
@@ -200,7 +215,34 @@ impl RecoveryManager {
}
}
+ pub fn remux_stopped_with_preparing(
+ completed: &CompletedRecording,
+ mut job: PreparingStudioJob,
+ ) -> Result<bool, RecoveryError> {
+ let matches = job.claimed().is_some_and(|claim| {
+ claim.metadata().project_path == completed.project_path
+ && serde_json::to_value(claim.metadata().studio_meta())
+ .ok()
+ .zip(serde_json::to_value(&completed.meta).ok())
+ .is_some_and(|(stopped, supplied)| stopped == supplied)
+ });
+ if !matches {
+ job.unavailable(
+ "The completed recording no longer matches its stopped snapshot".into(),
+ );
+ return Self::remux_if_needed(&completed.project_path);
+ }
+ Self::remux_with_preparing(&completed.project_path, Some(job))
+ }
+
pub fn remux_if_needed(project_path: &Path) -> Result<bool, RecoveryError> {
+ Self::remux_with_preparing(project_path, None)
+ }
+
+ fn remux_with_preparing(
+ project_path: &Path,
+ preparing: Option<PreparingStudioJob>,
+ ) -> Result<bool, RecoveryError> {
if !project_path.is_dir() {
return Ok(false);
}
@@ -221,7 +263,15 @@ impl RecoveryManager {
return Ok(false);
}
- Self::finalize(&incomplete)?;
+ Self::finalize_with_publication(
+ &incomplete,
+ RecoveryPurpose::Finalize,
+ copy_recovery_input_with_durability,
+ |_, _| Ok(()),
+ publish_recovery,
+ RecoveryLock::acquire,
+ preparing,
+ )?;
Ok(true)
}
@@ -903,6 +953,36 @@ impl RecoveryManager {
Self::finalize_with_purpose(recording, RecoveryPurpose::Finalize)
}
+ pub fn finalize_with_preparing(
+ recording: &IncompleteRecording,
+ job: PreparingStudioJob,
+ ) -> Result<RecoveredRecording, RecoveryError> {
+ Self::finalize_with_publication(
+ recording,
+ RecoveryPurpose::Finalize,
+ copy_recovery_input_with_durability,
+ |_, _| Ok(()),
+ publish_recovery,
+ RecoveryLock::acquire,
+ Some(job),
+ )
+ }
+
+ pub fn finalize_with_relocatable_source(
+ recording: &IncompleteRecording,
+ source: &RelocatableSource,
+ ) -> Result<RecoveredRecording, RecoveryError> {
+ Self::finalize_with_publication(
+ recording,
+ RecoveryPurpose::Finalize,
+ copy_recovery_input_with_durability,
+ |_, _| Ok(()),
+ |project, workspace| publish_recovery_with_source(project, workspace, source),
+ RecoveryLock::acquire_for_preparing_preview,
+ None,
+ )
+ }
+
fn finalize_with_purpose(
recording: &IncompleteRecording,
purpose: RecoveryPurpose,
@@ -916,15 +996,41 @@ impl RecoveryManager {
}
fn finalize_with_operations(
+ recording: &IncompleteRecording,
+ purpose: RecoveryPurpose,
+ copy_input: impl FnMut(&Path, &Path, RecoveryCopyDurability) -> Result<(), RecoveryError>,
+ before_source_check: impl FnOnce(&Path, &Path) -> Result<(), RecoveryError>,
+ ) -> Result<RecoveredRecording, RecoveryError> {
+ Self::finalize_with_publication(
+ recording,
+ purpose,
+ copy_input,
+ before_source_check,
+ publish_recovery,
+ RecoveryLock::acquire,
+ None,
+ )
+ }
+
+ fn finalize_with_publication(
recording: &IncompleteRecording,
purpose: RecoveryPurpose,
mut copy_input: impl FnMut(&Path, &Path, RecoveryCopyDurability) -> Result<(), RecoveryError>,
before_source_check: impl FnOnce(&Path, &Path) -> Result<(), RecoveryError>,
+ publish: impl FnOnce(&Path, &Path) -> Result<(), RecoveryError>,
+ acquire: impl FnOnce(&Path) -> Result<RecoveryLock, RecoveryError>,
+ preparing: Option<PreparingStudioJob>,
) -> Result<RecoveredRecording, RecoveryError> {
+ let started = Instant::now();
Self::require_no_track_failure(&recording.project_path)?;
let project = &recording.project_path;
- let _lock = RecoveryLock::acquire(project)?;
+ let lock = HeldRecoveryLock::new(acquire(project)?, preparing.is_some());
+ let mut preparing = preparing;
let before = recovery_snapshot(project)?;
+ debug!(
+ elapsed_ms = started.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization source snapshot ready"
+ );
let current = RecordingMeta::load_for_project(project)
.map_err(|error| RecoveryError::Validation(error.to_string()))?;
if serde_json::to_value(&current)? != serde_json::to_value(&recording.meta)? {
@@ -939,17 +1045,24 @@ impl RecoveryManager {
VideoValidation::Bounded => RecoveryCopyDurability::Deferred,
};
Self::require_recoverable_tracks(recording)?;
+ let preparing_source = prepare_studio_source(recording, preparing.as_mut(), &lock);
let workspace = project.join(format!(".recovery-{}", uuid::Uuid::new_v4()));
create_private_recovery_dir(&workspace)?;
let staged = workspace.join("staged");
create_private_recovery_dir(&staged)?;
let prepared = (|| {
+ let copying = Instant::now();
for name in RECOVERY_INPUTS {
let source = project.join(name);
if source.try_exists()? {
copy_input(&source, &staged.join(name), staging_durability)?;
}
}
+ debug!(
+ elapsed_ms = copying.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization staging copy ready"
+ );
+ let checking = Instant::now();
// Clean finalization mutates only staged bytes and rechecks originals before publication.
if recovery_snapshot(&staged)? != before
|| (video_validation == VideoValidation::Full
@@ -959,6 +1072,10 @@ impl RecoveryManager {
"Recording changed while copying".into(),
));
}
+ debug!(
+ elapsed_ms = checking.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization staging snapshot ready"
+ );
let staged_meta = RecordingMeta::load_for_project(&staged)
.map_err(|error| RecoveryError::Validation(error.to_string()))?;
for (index, track) in legacy_omitted_tracks(&staged_meta, &staged)? {
@@ -979,12 +1096,27 @@ impl RecoveryManager {
}
}
validate_recovery_manifests(&staged.join("content"))?;
+ let analyzing = Instant::now();
let staged_recording = Self::analyze_incomplete(&staged, &staged_meta)
.ok_or(RecoveryError::NoRecoverableSegments)?;
+ debug!(
+ elapsed_ms = analyzing.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization staged analysis ready"
+ );
Self::require_recoverable_tracks(&staged_recording)?;
Self::require_local_fragments(&staged_recording)?;
+ let validating = Instant::now();
Self::validate_staged_inputs(&staged_recording, video_validation)?;
+ debug!(
+ elapsed_ms = validating.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization staged inputs validated"
+ );
+ let remuxing = Instant::now();
let recovered = Self::finalize_staged(&staged_recording, purpose, video_validation)?;
+ debug!(
+ elapsed_ms = remuxing.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization media ready"
+ );
let config = ProjectConfiguration::load(&staged)?;
config
.validate()
@@ -996,14 +1128,24 @@ impl RecoveryManager {
{
return Err(RecoveryError::Validation("Staged metadata mismatch".into()));
}
+ let syncing = Instant::now();
sync_recovery_input(&staged)?;
+ debug!(
+ elapsed_ms = syncing.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization staging synced"
+ );
before_source_check(project, &staged)?;
Self::require_no_track_failure(project)?;
+ let rechecking = Instant::now();
if recovery_snapshot(project)? != before {
return Err(RecoveryError::Validation(
"Recording changed before publication".into(),
));
}
+ debug!(
+ elapsed_ms = rechecking.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization source rechecked"
+ );
Ok(recovered.meta)
})();
let meta = match prepared {
@@ -1013,7 +1155,18 @@ impl RecoveryManager {
return Err(error);
}
};
- publish_recovery(project, &workspace)?;
+ if let Some(source) = &preparing_source {
+ publish_recovery_with_source(project, &workspace, source)?;
+ if let Some(job) = &mut preparing {
+ job.mark_publication_succeeded();
+ }
+ } else {
+ publish(project, &workspace)?;
+ }
+ debug!(
+ elapsed_ms = started.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization complete"
+ );
finalization_info!(path = %workspace.display(), "Recovered recording retains original media backup");
Ok(RecoveredRecording {
project_path: project.clone(),
@@ -1182,6 +1335,7 @@ impl RecoveryManager {
.join("content/segments")
.join(format!("segment-{}", segment.index));
+ let video_started = Instant::now();
let display_output = segment_dir.join("display.mp4");
let display_dir = segment_dir.join("display");
@@ -1271,12 +1425,25 @@ impl RecoveryManager {
}
}
+ debug!(
+ segment = segment.index,
+ elapsed_ms = video_started.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization segment video ready"
+ );
+ let audio_started = Instant::now();
+
if let Some(mic_frags) = &segment.mic_fragments {
- let mic_output = segment_dir.join("audio-input.ogg");
+ let mic_output =
+ segment_dir.join(finalized_audio_name(&segment_dir, "audio-input", mic_frags));
if mic_frags.len() == 1 {
let source = &mic_frags[0];
let is_ogg = source.extension().map(|e| e == "ogg").unwrap_or(false);
- if source != &mic_output {
+ if mic_output
+ .extension()
+ .is_some_and(|extension| extension == "m4a")
+ {
+ finalize_m4a(source, &mic_output)?;
+ } else if source != &mic_output {
if is_ogg {
finalization_info!("Moving single mic fragment to {:?}", mic_output);
std::fs::rename(source, &mic_output)?;
@@ -1322,11 +1489,20 @@ impl RecoveryManager {
}
if let Some(system_frags) = &segment.system_audio_fragments {
- let system_output = segment_dir.join("system_audio.ogg");
+ let system_output = segment_dir.join(finalized_audio_name(
+ &segment_dir,
+ "system_audio",
+ system_frags,
+ ));
if system_frags.len() == 1 {
let source = &system_frags[0];
let is_ogg = source.extension().map(|e| e == "ogg").unwrap_or(false);
- if source != &system_output {
+ if system_output
+ .extension()
+ .is_some_and(|extension| extension == "m4a")
+ {
+ finalize_m4a(source, &system_output)?;
+ } else if source != &system_output {
if is_ogg {
finalization_info!(
"Moving single system audio fragment to {:?}",
@@ -1373,8 +1549,14 @@ impl RecoveryManager {
}
}
}
+ debug!(
+ segment = segment.index,
+ elapsed_ms = audio_started.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization segment audio remuxed"
+ );
}
+ let validating = Instant::now();
for segment in &recording.recoverable_segments {
let dir = recording
.project_path
@@ -1389,17 +1571,28 @@ impl RecoveryManager {
for (fragments, name, kind) in [
(
segment.camera_fragments.as_ref(),
- "camera.mp4",
+ "camera.mp4".to_string(),
ffmpeg::media::Type::Video,
),
(
segment.mic_fragments.as_ref(),
- "audio-input.ogg",
+ finalized_audio_name(
+ &dir,
+ "audio-input",
+ segment.mic_fragments.as_deref().unwrap_or_default(),
+ ),
ffmpeg::media::Type::Audio,
),
(
segment.system_audio_fragments.as_ref(),
- "system_audio.ogg",
+ finalized_audio_name(
+ &dir,
+ "system_audio",
+ segment
+ .system_audio_fragments
+ .as_deref()
+ .unwrap_or_default(),
+ ),
ffmpeg::media::Type::Audio,
),
] {
@@ -1411,6 +1604,10 @@ impl RecoveryManager {
}
}
}
+ debug!(
+ elapsed_ms = validating.elapsed().as_secs_f64() * 1000.0,
+ "Studio finalization output tracks validated"
+ );
let meta = Self::build_recovered_meta(recording)?;
let mut recording_meta = recording.meta.clone();
@@ -2003,7 +2200,12 @@ impl RecoveryManager {
if seg.mic_fragments.is_some() {
Some(AudioMeta {
path: RelativePathBuf::from(format!(
- "{segment_base}/audio-input.ogg"
+ "{segment_base}/{}",
+ finalized_audio_name(
+ &segment_dir,
+ "audio-input",
+ seg.mic_fragments.as_deref().unwrap_or_default()
+ )
)),
start_time: get_start_time_or_fallback(
original_segment
@@ -2023,7 +2225,12 @@ impl RecoveryManager {
if seg.system_audio_fragments.is_some() {
Some(AudioMeta {
path: RelativePathBuf::from(format!(
- "{segment_base}/system_audio.ogg"
+ "{segment_base}/{}",
+ finalized_audio_name(
+ &segment_dir,
+ "system_audio",
+ seg.system_audio_fragments.as_deref().unwrap_or_default()
+ )
)),
start_time: get_start_time_or_fallback(
original_segment
@@ -2443,6 +2650,52 @@ const RECOVERY_INPUTS: [&str; 4] = [
"recording-diagnostics.json",
];
+enum HeldRecoveryLock {
+ Owned { _lock: RecoveryLock },
+ Shared(Arc<RecoveryLock>),
+}
+
+impl HeldRecoveryLock {
+ fn new(lock: RecoveryLock, preparing: bool) -> Self {
+ if preparing {
+ Self::Shared(Arc::new(lock))
+ } else {
+ Self::Owned { _lock: lock }
+ }
+ }
+}
+
+fn prepare_studio_source(
+ recording: &IncompleteRecording,
+ preparing: Option<&mut PreparingStudioJob>,
+ lock: &HeldRecoveryLock,
+) -> Option<RelocatableSource> {
+ let job = preparing?;
+ let HeldRecoveryLock::Shared(lock) = lock else {
+ job.unavailable("The finalizer does not own a preparing source lease".into());
+ return None;
+ };
+ let projected = job
+ .claimed()
+ .ok_or_else(|| "The stopped recording was already claimed".to_string())
+ .and_then(|claim| preparing_projection::project(recording, claim))
+ .and_then(|projection| {
+ let source = RelocatableSource::new_with_owner(
+ recording.project_path.join("content/segments"),
+ lock.clone(),
+ )
+ .map_err(|error| error.to_string())?;
+ Ok((source, projection))
+ });
+ match projected {
+ Ok((source, projection)) => job.publish(source.clone(), projection).then_some(source),
+ Err(error) => {
+ job.unavailable(error);
+ None
+ }
+ }
+}
+
struct RecoveryLock {
_file: std::fs::File,
#[cfg(unix)]
@@ -2451,6 +2704,26 @@ struct RecoveryLock {
impl RecoveryLock {
fn acquire(project: &Path) -> Result<Self, RecoveryError> {
+ Self::acquire_with(project, reconcile_recovery_publication)
+ }
+
+ fn acquire_for_preparing_preview(project: &Path) -> Result<Self, RecoveryError> {
+ Self::acquire_with(project, |project| {
+ match project.join(RECOVERY_PUBLICATION).symlink_metadata() {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.into()),
+ Ok(_) => Err(RecoveryError::Validation(
+ "Interrupted publication must be reconciled after preparing preview readers stop"
+ .into(),
+ )),
+ }
+ })
+ }
+
+ fn acquire_with(
+ project: &Path,
+ reconcile: impl FnOnce(&Path) -> Result<(), RecoveryError>,
+ ) -> Result<Self, RecoveryError> {
reject_recovery_link(&project.symlink_metadata()?)?;
let path = project.join(".recovery.lock");
let mut options = std::fs::OpenOptions::new();
@@ -2496,7 +2769,7 @@ impl RecoveryLock {
#[cfg(unix)]
owner_pid: unsafe { libc::getpid() },
};
- if let Err(error) = reconcile_recovery_publication(project) {
+ if let Err(error) = reconcile(project) {
warn!(path = %project.display(), %error, "Interrupted recovery publication requires attention; all files retained");
return Err(error);
}
@@ -2560,6 +2833,13 @@ fn copy_recovery_input_with_durability(
}
} else if metadata.is_file() {
let mut input = std::fs::File::open(source)?;
+ #[cfg(target_os = "macos")]
+ if clone_recovery_file(&input, destination) {
+ if durability == RecoveryCopyDurability::Durable {
+ std::fs::File::open(destination)?.sync_all()?;
+ }
+ return Ok(());
+ }
let mut output = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
@@ -2577,13 +2857,57 @@ fn copy_recovery_input_with_durability(
Ok(())
}
-fn recovery_snapshot(
- project: &Path,
-) -> Result<std::collections::BTreeMap<PathBuf, Option<Vec<u8>>>, RecoveryError> {
+#[cfg(target_os = "macos")]
+fn clone_recovery_file(input: &std::fs::File, destination: &Path) -> bool {
+ use std::{os::fd::AsRawFd, os::unix::ffi::OsStrExt};
+
+ let Ok(destination) = std::ffi::CString::new(destination.as_os_str().as_bytes()) else {
+ return false;
+ };
+ unsafe { libc::fclonefileat(input.as_raw_fd(), libc::AT_FDCWD, destination.as_ptr(), 0) == 0 }
+}
+
+type RecoverySnapshot = std::collections::BTreeMap<PathBuf, Option<Vec<u8>>>;
+
+fn hash_recovery_files(root: &Path, paths: &[PathBuf]) -> Result<RecoverySnapshot, RecoveryError> {
+ use std::io::Read;
+
+ let mut entries = RecoverySnapshot::new();
+ let mut buffer = [0_u8; 65536];
+ for path in paths {
+ let metadata = path.symlink_metadata()?;
+ reject_recovery_link(&metadata)?;
+ if !metadata.is_file() {
+ return Err(RecoveryError::Validation(format!(
+ "Unsupported recovery input: {}",
+ path.display()
+ )));
+ }
+ let mut input = std::fs::File::open(path)?;
+ let mut digest = blake3::Hasher::new();
+ loop {
+ let count = input.read(&mut buffer)?;
+ if count == 0 {
+ break;
+ }
+ digest.update(&buffer[..count]);
+ }
+ let relative = path
+ .strip_prefix(root)
+ .map_err(|error| RecoveryError::Validation(error.to_string()))?
+ .to_path_buf();
+ let _ = entries.insert(relative, Some(digest.finalize().as_bytes().to_vec()));
+ }
+ Ok(entries)
+}
+
+fn recovery_snapshot(project: &Path) -> Result<RecoverySnapshot, RecoveryError> {
fn visit(
root: &Path,
path: &Path,
- entries: &mut std::collections::BTreeMap<PathBuf, Option<Vec<u8>>>,
+ entries: &mut RecoverySnapshot,
+ files: &mut Vec<PathBuf>,
+ bytes: &mut u64,
) -> Result<(), RecoveryError> {
let metadata = path.symlink_metadata()?;
reject_recovery_link(&metadata)?;
@@ -2594,21 +2918,11 @@ fn recovery_snapshot(
if metadata.is_dir() {
let _ = entries.insert(relative, None);
for entry in std::fs::read_dir(path)? {
- visit(root, &entry?.path(), entries)?;
+ visit(root, &entry?.path(), entries, files, bytes)?;
}
} else if metadata.is_file() {
- let mut digest = blake3::Hasher::new();
- use std::io::Read;
- let mut input = std::fs::File::open(path)?;
- let mut buffer = [0_u8; 65536];
- loop {
- let count = input.read(&mut buffer)?;
- if count == 0 {
- break;
- }
- digest.update(&buffer[..count]);
- }
- let _ = entries.insert(relative, Some(digest.finalize().as_bytes().to_vec()));
+ files.push(path.to_path_buf());
+ *bytes = bytes.saturating_add(metadata.len());
} else {
return Err(RecoveryError::Validation(format!(
"Unsupported recovery input: {}",
@@ -2617,15 +2931,42 @@ fn recovery_snapshot(
}
Ok(())
}
- let mut entries = std::collections::BTreeMap::new();
+ let mut entries = RecoverySnapshot::new();
+ let mut files = Vec::new();
+ let mut bytes = 0;
for name in RECOVERY_INPUTS {
let path = project.join(name);
match path.symlink_metadata() {
- Ok(_) => visit(project, &path, &mut entries)?,
+ Ok(_) => visit(project, &path, &mut entries, &mut files, &mut bytes)?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
+ let can_parallelize = bytes >= 32 * 1024 * 1024
+ && files.len() >= 2
+ && std::thread::available_parallelism().is_ok_and(|count| count.get() > 1);
+ let hashes = if can_parallelize {
+ let middle = files.len().div_ceil(2);
+ std::thread::scope(|scope| {
+ match std::thread::Builder::new()
+ .name("studio-integrity-check".into())
+ .spawn_scoped(scope, || hash_recovery_files(project, &files[..middle]))
+ {
+ Ok(worker) => {
+ let remaining = hash_recovery_files(project, &files[middle..]);
+ let mut hashes = worker.join().map_err(|_| {
+ RecoveryError::Validation("Recovery integrity worker panicked".into())
+ })??;
+ hashes.extend(remaining?);
+ Ok(hashes)
+ }
+ Err(_) => hash_recovery_files(project, &files),
+ }
+ })?
+ } else {
+ hash_recovery_files(project, &files)?
+ };
+ entries.extend(hashes);
Ok(entries)
}
@@ -2648,6 +2989,12 @@ const RECOVERY_PUBLICATION: &str = ".recovery-publication.json";
const RECOVERY_PUBLICATION_RECEIPT: &str = "publication-receipt.json";
const RECOVERY_PUBLICATION_MAX_BYTES: u64 = 8192;
+#[derive(Clone, Copy)]
+enum RecoveryPublicationStampVersion {
+ V1,
+ V2,
+}
+
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct RecoveryPublication {
@@ -2707,7 +3054,10 @@ fn recovery_publication_file_digest(path: &Path) -> Result<Option<[u8; 32]>, Rec
Ok(Some(digest.finalize().into()))
}
-fn recovery_publication_segments_stamp(path: &Path) -> Result<Option<[u8; 32]>, RecoveryError> {
+fn recovery_publication_segments_stamp(
+ path: &Path,
+ version: RecoveryPublicationStampVersion,
+) -> Result<Option<[u8; 32]>, RecoveryError> {
// These stamps locate the interrupted rename; ordinary recovery still validates media content.
use sha2::Digest;
#[derive(serde::Serialize)]
@@ -2723,6 +3073,7 @@ fn recovery_publication_segments_stamp(path: &Path) -> Result<Option<[u8; 32]>,
root: &Path,
path: &Path,
entries: &mut std::collections::BTreeMap<PathBuf, Entry>,
+ version: RecoveryPublicationStampVersion,
) -> Result<(), RecoveryError> {
let metadata = path.symlink_metadata()?;
reject_recovery_link(&metadata)?;
@@ -2739,7 +3090,13 @@ fn recovery_publication_segments_stamp(path: &Path) -> Result<Option<[u8; 32]>,
.to_path_buf(),
Entry {
directory: metadata.is_dir(),
- size: metadata.len(),
+ // V1 persists allocation sizes; some filesystems change directory sizes on rename.
+ size: if metadata.is_dir() && matches!(version, RecoveryPublicationStampVersion::V2)
+ {
+ 0
+ } else {
+ metadata.len()
+ },
modified: metadata
.modified()?
.duration_since(std::time::UNIX_EPOCH)
@@ -2754,7 +3111,7 @@ fn recovery_publication_segments_stamp(path: &Path) -> Result<Option<[u8; 32]>,
);
if metadata.is_dir() {
for entry in std::fs::read_dir(path)? {
- visit(root, &entry?.path(), entries)?;
+ visit(root, &entry?.path(), entries, version)?;
}
}
Ok(())
@@ -2772,13 +3129,20 @@ fn recovery_publication_segments_stamp(path: &Path) -> Result<Option<[u8; 32]>,
Err(error) => return Err(error.into()),
}
let mut entries = std::collections::BTreeMap::new();
- visit(path, path, &mut entries)?;
+ visit(path, path, &mut entries, version)?;
Ok(Some(
sha2::Sha256::digest(serde_json::to_vec(&entries)?).into(),
))
}
fn recovery_publication_state(project: &Path) -> Result<RecoveryPublicationState, RecoveryError> {
+ recovery_publication_state_for_version(project, RecoveryPublicationStampVersion::V2)
+}
+
+fn recovery_publication_state_for_version(
+ project: &Path,
+ version: RecoveryPublicationStampVersion,
+) -> Result<RecoveryPublicationState, RecoveryError> {
for path in [project.to_path_buf(), project.join("content")] {
let metadata = path.symlink_metadata()?;
reject_recovery_link(&metadata)?;
@@ -2789,7 +3153,7 @@ fn recovery_publication_state(project: &Path) -> Result<RecoveryPublicationState
}
}
Ok(RecoveryPublicationState {
- segments: recovery_publication_segments_stamp(&project.join("content/segments"))?,
+ segments: recovery_publication_segments_stamp(&project.join("content/segments"), version)?,
meta: recovery_publication_file_digest(&project.join("recording-meta.json"))?,
config: recovery_publication_file_digest(&project.join("project-config.json"))?,
})
@@ -2880,7 +3244,7 @@ fn begin_recovery_publication(project: &Path, workspace: &Path) -> Result<Vec<u8
));
}
let receipt = RecoveryPublication {
- version: 1,
+ version: 2,
project: project.canonicalize()?,
workspace: name.into(),
original: recovery_publication_state(project)?,
@@ -2946,8 +3310,16 @@ fn reconcile_recovery_publication(project: &Path) -> Result<(), RecoveryError> {
Err(error) => return Err(error.into()),
};
let receipt: RecoveryPublication = serde_json::from_slice(&bytes)?;
- if receipt.version != 1
- || receipt.project != project.canonicalize()?
+ let version = match receipt.version {
+ 1 => RecoveryPublicationStampVersion::V1,
+ 2 => RecoveryPublicationStampVersion::V2,
+ _ => {
+ return Err(RecoveryError::Validation(
+ "Invalid publication identity; evidence retained".into(),
+ ));
+ }
+ };
+ if receipt.project != project.canonicalize()?
|| receipt.original.meta.is_none()
|| receipt.original.segments.is_none()
|| receipt.staged.meta.is_none()
@@ -2964,9 +3336,10 @@ fn reconcile_recovery_publication(project: &Path) -> Result<(), RecoveryError> {
"Publication generation does not match its workspace".into(),
));
}
- let current = recovery_publication_state(project)?;
- let staged = recovery_publication_state(&workspace.join("staged"))?;
- let backup = recovery_publication_segments_stamp(&workspace.join("original-segments"))?;
+ let current = recovery_publication_state_for_version(project, version)?;
+ let staged = recovery_publication_state_for_version(&workspace.join("staged"), version)?;
+ let backup =
+ recovery_publication_segments_stamp(&workspace.join("original-segments"), version)?;
let backup_config =
recovery_publication_file_digest(&workspace.join("original-project-config.json"))?;
if recovery_publication_file_digest(&workspace.join("original-recording-meta.json"))?
@@ -3029,7 +3402,7 @@ fn reconcile_recovery_publication(project: &Path) -> Result<(), RecoveryError> {
Err(error) => return Err(error.into()),
}
std::fs::rename(workspace.join("original-segments"), destination)?;
- if recovery_publication_state(project)? != receipt.original {
+ if recovery_publication_state_for_version(project, version)? != receipt.original {
return Err(RecoveryError::Validation(
"Restored publication state changed; evidence retained".into(),
));
@@ -3046,6 +3419,32 @@ fn publish_recovery(project: &Path, workspace: &Path) -> Result<(), RecoveryErro
publish_recovery_with(project, workspace, rename_recovery_path)
}
+fn publish_recovery_with_source(
+ project: &Path,
+ workspace: &Path,
+ source: &RelocatableSource,
+) -> Result<(), RecoveryError> {
+ let original = project.join("content/segments");
+ let backup = workspace.join("original-segments");
+ publish_recovery_with(project, workspace, |from, to| {
+ rename_recovery_path_with_source(from, to, &original, &backup, source)
+ })
+}
+
+fn rename_recovery_path_with_source(
+ from: &Path,
+ to: &Path,
+ original: &Path,
+ backup: &Path,
+ source: &RelocatableSource,
+) -> std::io::Result<()> {
+ if (from == original && to == backup) || (from == backup && to == original) {
+ source.relocate_from(from, to.to_path_buf())
+ } else {
+ rename_recovery_path(from, to)
+ }
+}
+
fn rename_recovery_path(source: &Path, destination: &Path) -> std::io::Result<()> {
std::fs::rename(source, destination)
}
@@ -3114,6 +3513,42 @@ fn publish_recovery_with(
Ok(())
}
+fn finalized_audio_name(segment_dir: &Path, stem: &str, fragments: &[PathBuf]) -> String {
+ let m4a = format!("{stem}.m4a");
+ if let [source] = fragments
+ && source
+ .extension()
+ .is_some_and(|extension| extension.eq_ignore_ascii_case("m4a"))
+ {
+ let output = segment_dir.join(&m4a);
+ let source = if source.is_file() {
+ source.as_path()
+ } else {
+ output.as_path()
+ };
+ if ffmpeg::format::input(source).is_ok_and(|input| {
+ input.streams().best(ffmpeg::media::Type::Video).is_none()
+ && input
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .is_some_and(|stream| stream.parameters().id() == ffmpeg::codec::Id::AAC)
+ }) {
+ return m4a;
+ }
+ }
+ format!("{stem}.ogg")
+}
+
+fn finalize_m4a(source: &Path, output: &Path) -> Result<(), RecoveryError> {
+ let temporary = output.with_extension(format!("{}.m4a", uuid::Uuid::new_v4()));
+ remux_file(source, &temporary).map_err(RecoveryError::AudioConcat)?;
+ replace_file(&temporary, output)?;
+ if source != output {
+ std::fs::remove_file(source)?;
+ }
+ Ok(())
+}
+
fn validate_recovered_track(path: &Path, kind: ffmpeg::media::Type) -> Result<(), RecoveryError> {
validate_recovery_track(path, kind, VideoValidation::Full)
}
@@ -3486,6 +3921,574 @@ mod clean_studio_snapshot_tests {
directory
}
+ fn add_fragmented_audio(project: &Path, name: &str, blocks: i64) -> PathBuf {
+ use cap_enc_ffmpeg::fragmented_audio::FragmentedAudioFile;
+ use ffmpeg::{ChannelLayout, format::Sample, format::sample::Type};
+
+ let path = project.join(format!("content/segments/segment-0/{name}.m4a"));
+ let mut encoder = FragmentedAudioFile::init(
+ path.clone(),
+ cap_media_info::AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 1),
+ )
+ .unwrap();
+ for block in 0..blocks {
+ let mut frame =
+ ffmpeg::frame::Audio::new(Sample::F32(Type::Packed), 1024, ChannelLayout::MONO);
+ frame.set_rate(48_000);
+ frame.set_pts(Some(block * 1024));
+ for (index, value) in frame.data_mut(0)[..4096].chunks_exact_mut(4).enumerate() {
+ let position = (block * 1024) as f32 + index as f32;
+ let sample = (position * std::f32::consts::TAU * 440.0 / 48_000.0).sin() * 0.25;
+ value.copy_from_slice(&sample.to_ne_bytes());
+ }
+ encoder
+ .queue_frame(
+ frame,
+ Duration::from_secs_f64(block as f64 * 1024.0 / 48_000.0),
+ )
+ .unwrap();
+ }
+ encoder.finish().unwrap().unwrap();
+ path
+ }
+
+ fn completed_preparing_fixture(project: &Path) -> CompletedRecording {
+ use crate::studio_recording::CleanStoppedStudio;
+
+ let mut metadata = RecordingMeta::load_for_project(project).unwrap();
+ let RecordingMetaInner::Studio(studio) = &mut metadata.inner else {
+ panic!()
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!()
+ };
+ inner.segments[0].display.path = DISPLAY.into();
+ inner.segments[0].display.start_time = Some(0.0);
+ let configuration = ProjectConfiguration {
+ timeline: Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": [{"recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 2.0}],
+ "zoomSegments": []
+ }))
+ .unwrap(),
+ ),
+ ..ProjectConfiguration::default()
+ };
+ metadata.save_for_project().unwrap();
+ configuration.write(project).unwrap();
+ CompletedRecording {
+ project_path: project.to_path_buf(),
+ meta: metadata.studio_meta().unwrap().clone(),
+ cursor_data: Default::default(),
+ clean_stopped: CleanStoppedStudio::for_test(metadata, configuration),
+ }
+ }
+
+ enum PreparingEntryCase {
+ Supported,
+ EditedConfiguration,
+ EditedMetadata,
+ WrongStoppedProject,
+ StaleAnalysis,
+ RequiredTrackFailure,
+ HeldRecoveryLock,
+ }
+
+ fn assert_preparing_entry_point_matches_ordinary(case: PreparingEntryCase) {
+ use super::preparing_observer::PreparingStudioTestTransition;
+
+ let candidate = playable_studio_project(StudioRecordingStatus::NeedsRemux);
+ let completed = completed_preparing_fixture(candidate.path());
+ let ordinary = tempfile::tempdir().unwrap();
+ for entry in fs::read_dir(candidate.path()).unwrap() {
+ let entry = entry.unwrap();
+ copy_recovery_input(&entry.path(), &ordinary.path().join(entry.file_name())).unwrap();
+ }
+ assert_eq!(
+ recovery_snapshot(candidate.path()).unwrap(),
+ recovery_snapshot(ordinary.path()).unwrap()
+ );
+ let mut candidate_recording = RecoveryManager::inspect_recording(candidate.path()).unwrap();
+ let mut ordinary_recording = RecoveryManager::inspect_recording(ordinary.path()).unwrap();
+ let alternate = tempfile::tempdir().unwrap();
+ let (job, observer) = if matches!(case, PreparingEntryCase::WrongStoppedProject) {
+ let mut metadata = RecordingMeta::load_for_project(candidate.path()).unwrap();
+ metadata.project_path = alternate.path().to_path_buf();
+ let configuration = ProjectConfiguration::load(candidate.path()).unwrap();
+ let alternate_completed = CompletedRecording {
+ project_path: alternate.path().to_path_buf(),
+ meta: metadata.studio_meta().unwrap().clone(),
+ cursor_data: Default::default(),
+ clean_stopped: crate::studio_recording::CleanStoppedStudio::for_test(
+ metadata,
+ configuration,
+ ),
+ };
+ PreparingStudioJob::claim(&alternate_completed, 73).unwrap()
+ } else {
+ PreparingStudioJob::claim(&completed, 72).unwrap()
+ };
+ match case {
+ PreparingEntryCase::Supported
+ | PreparingEntryCase::WrongStoppedProject
+ | PreparingEntryCase::HeldRecoveryLock => {}
+ PreparingEntryCase::EditedConfiguration => {
+ for path in [candidate.path(), ordinary.path()] {
+ let mut configuration = ProjectConfiguration::load(path).unwrap();
+ configuration.timeline.as_mut().unwrap().segments[0].name =
+ Some("Edited after Stop".into());
+ configuration.write(path).unwrap();
+ }
+ }
+ PreparingEntryCase::EditedMetadata => {
+ for path in [candidate.path(), ordinary.path()] {
+ let mut metadata = RecordingMeta::load_for_project(path).unwrap();
+ metadata.pretty_name.push_str(" edited after Stop");
+ metadata.save_for_project().unwrap();
+ }
+ candidate_recording = RecoveryManager::inspect_recording(candidate.path()).unwrap();
+ ordinary_recording = RecoveryManager::inspect_recording(ordinary.path()).unwrap();
+ }
+ PreparingEntryCase::StaleAnalysis => {
+ candidate_recording.meta.pretty_name.push_str(" stale");
+ ordinary_recording.meta.pretty_name.push_str(" stale");
+ }
+ PreparingEntryCase::RequiredTrackFailure => {
+ for path in [candidate.path(), ordinary.path()] {
+ fs::write(
+ path.join("recording-diagnostics.json"),
+ br#"{"version":2,"segments":[{"trackFailures":[{"track":"display","reason":"injected requested track failure"}]}]}"#,
+ )
+ .unwrap();
+ }
+ }
+ }
+ let candidate_before = recovery_snapshot(candidate.path()).unwrap();
+ let ordinary_before = recovery_snapshot(ordinary.path()).unwrap();
+ let transitions = job.test_transitions();
+ let held_locks = matches!(case, PreparingEntryCase::HeldRecoveryLock).then(|| {
+ (
+ RecoveryLock::acquire(candidate.path()).unwrap(),
+ RecoveryLock::acquire(ordinary.path()).unwrap(),
+ )
+ });
+ let expected = RecoveryManager::finalize(&ordinary_recording)
+ .map(|recording| serde_json::to_value(recording.meta).unwrap())
+ .map_err(|error| error.to_string());
+ let actual = RecoveryManager::finalize_with_preparing(&candidate_recording, job)
+ .map(|recording| serde_json::to_value(recording.meta).unwrap())
+ .map_err(|error| error.to_string());
+ assert_eq!(actual, expected);
+ assert_eq!(
+ observer.publication_succeeded(),
+ matches!(case, PreparingEntryCase::Supported) && actual.is_ok()
+ );
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ let expected_transitions = match case {
+ PreparingEntryCase::Supported => vec![
+ PreparingStudioTestTransition::Available,
+ PreparingStudioTestTransition::Ended,
+ ],
+ PreparingEntryCase::EditedConfiguration => vec![
+ PreparingStudioTestTransition::Unavailable(
+ "Persisted stopped configuration changed".into(),
+ ),
+ PreparingStudioTestTransition::Ended,
+ ],
+ PreparingEntryCase::EditedMetadata | PreparingEntryCase::WrongStoppedProject => vec![
+ PreparingStudioTestTransition::Unavailable(
+ "Stopped recording identity or metadata changed".into(),
+ ),
+ PreparingStudioTestTransition::Ended,
+ ],
+ PreparingEntryCase::StaleAnalysis
+ | PreparingEntryCase::RequiredTrackFailure
+ | PreparingEntryCase::HeldRecoveryLock => vec![PreparingStudioTestTransition::Ended],
+ };
+ assert_eq!(*transitions.lock().unwrap(), expected_transitions);
+ drop(held_locks);
+ assert!(RecoveryLock::acquire(candidate.path()).is_ok());
+ assert!(RecoveryLock::acquire(ordinary.path()).is_ok());
+ if matches!(
+ case,
+ PreparingEntryCase::StaleAnalysis
+ | PreparingEntryCase::RequiredTrackFailure
+ | PreparingEntryCase::HeldRecoveryLock
+ ) {
+ assert!(actual.is_err());
+ assert_eq!(
+ recovery_snapshot(candidate.path()).unwrap(),
+ candidate_before
+ );
+ assert_eq!(recovery_snapshot(ordinary.path()).unwrap(), ordinary_before);
+ assert!(!candidate.path().join(OUTPUT).exists());
+ assert!(!ordinary.path().join(OUTPUT).exists());
+ } else {
+ assert!(actual.is_ok());
+ assert_eq!(
+ recovery_snapshot(candidate.path()).unwrap(),
+ recovery_snapshot(ordinary.path()).unwrap()
+ );
+ assert_eq!(
+ fs::read(candidate.path().join(OUTPUT)).unwrap(),
+ fs::read(ordinary.path().join(OUTPUT)).unwrap()
+ );
+ assert!(probe_video_can_decode(&candidate.path().join(OUTPUT)).unwrap());
+ }
+ }
+
+ #[test]
+ fn inspected_preparing_finalization_matches_ordinary_outputs_and_metadata() {
+ assert_preparing_entry_point_matches_ordinary(PreparingEntryCase::Supported);
+ }
+
+ #[test]
+ fn inspected_preparing_finalization_matches_ordinary_configuration_behavior_after_edits() {
+ assert_preparing_entry_point_matches_ordinary(PreparingEntryCase::EditedConfiguration);
+ }
+
+ #[test]
+ fn inspected_preparing_finalization_preserves_fresh_metadata_edits_and_declines_preview() {
+ assert_preparing_entry_point_matches_ordinary(PreparingEntryCase::EditedMetadata);
+ }
+
+ #[test]
+ fn inspected_preparing_finalization_preserves_recovery_lock_contention_without_writes() {
+ assert_preparing_entry_point_matches_ordinary(PreparingEntryCase::HeldRecoveryLock);
+ }
+
+ #[test]
+ fn inspected_preparing_finalization_declines_a_different_stopped_project() {
+ assert_preparing_entry_point_matches_ordinary(PreparingEntryCase::WrongStoppedProject);
+ }
+
+ #[test]
+ fn inspected_preparing_finalization_rejects_stale_analysis_without_writes() {
+ assert_preparing_entry_point_matches_ordinary(PreparingEntryCase::StaleAnalysis);
+ }
+
+ #[test]
+ fn inspected_preparing_finalization_preserves_requested_track_failure() {
+ assert_preparing_entry_point_matches_ordinary(PreparingEntryCase::RequiredTrackFailure);
+ }
+
+ #[test]
+ fn preparing_finalizer_revokes_sources_and_retains_lock_until_last_reader_closes() {
+ use std::io::Read;
+
+ let directory = playable_studio_project(StudioRecordingStatus::NeedsRemux);
+ let project = directory.path();
+ let completed = completed_preparing_fixture(project);
+ let (job, observer) = PreparingStudioJob::claim(&completed, 42).unwrap();
+ let metadata = RecordingMeta::load_for_project(project).unwrap();
+ let recording = RecoveryManager::analyze_incomplete(project, &metadata).unwrap();
+ let mut retained = None;
+ RecoveryManager::finalize_with_publication(
+ &recording,
+ RecoveryPurpose::Finalize,
+ copy_recovery_input_with_durability,
+ |_, _| {
+ let sources = match observer.latest() {
+ PreparingStudioState::Available(sources) => sources,
+ PreparingStudioState::Unavailable(reason) => panic!("{reason}"),
+ _ => panic!("Expected preparing sources before publication"),
+ };
+ let live = sources.live().unwrap();
+ let video = live.video(0, PreparingVideoTrack::Display).unwrap();
+ let (source, paths) = video.input().unwrap();
+ let expected = fs::read(project.join("content/segments").join(&paths[0]))?;
+ let mut reader = source.reader(&paths[0])?;
+ let mut header = [0; 8];
+ reader.read_exact(&mut header)?;
+ assert_eq!(&header, &expected[..8]);
+ retained = Some((sources.clone(), reader, expected));
+ Ok(())
+ },
+ publish_recovery,
+ RecoveryLock::acquire,
+ Some(job),
+ )
+ .unwrap();
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ let (sources, mut reader, expected) = retained.unwrap();
+ assert!(sources.live().is_none());
+ assert!(RecoveryLock::acquire(project).is_err());
+ drop(sources);
+ drop(observer);
+ assert!(RecoveryLock::acquire(project).is_err());
+ let mut remaining = Vec::new();
+ reader.read_to_end(&mut remaining).unwrap();
+ assert_eq!(remaining, expected[8..]);
+ drop(reader);
+ let lock = RecoveryLock::acquire(project).unwrap();
+ drop(lock);
+ let finalized = RecordingMeta::load_for_project(project).unwrap();
+ assert!(matches!(
+ finalized.studio_meta().unwrap().status(),
+ StudioRecordingStatus::Complete
+ ));
+ }
+
+ #[test]
+ fn preparing_config_drift_declines_preview_without_failing_finalization() {
+ let directory = playable_studio_project(StudioRecordingStatus::NeedsRemux);
+ let project = directory.path();
+ let completed = completed_preparing_fixture(project);
+ let (job, observer) = PreparingStudioJob::claim(&completed, 7).unwrap();
+ let mut configuration = ProjectConfiguration::load(project).unwrap();
+ configuration.timeline.as_mut().unwrap().segments[0].name = Some("Changed".into());
+ configuration.write(project).unwrap();
+ let metadata = RecordingMeta::load_for_project(project).unwrap();
+ let recording = RecoveryManager::analyze_incomplete(project, &metadata).unwrap();
+ RecoveryManager::finalize_with_publication(
+ &recording,
+ RecoveryPurpose::Finalize,
+ copy_recovery_input_with_durability,
+ |_, _| {
+ assert!(matches!(
+ observer.latest(),
+ PreparingStudioState::Unavailable(_)
+ ));
+ Ok(())
+ },
+ publish_recovery,
+ RecoveryLock::acquire,
+ Some(job),
+ )
+ .unwrap();
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ assert!(project.join(OUTPUT).is_file());
+ assert!(RecoveryLock::acquire(project).is_ok());
+ }
+
+ #[test]
+ fn preparing_finalizer_panic_revokes_capability_without_unlocking_live_reader() {
+ use std::io::Read;
+
+ let directory = playable_studio_project(StudioRecordingStatus::NeedsRemux);
+ let project = directory.path();
+ let completed = completed_preparing_fixture(project);
+ let (job, observer) = PreparingStudioJob::claim(&completed, 8).unwrap();
+ let metadata = RecordingMeta::load_for_project(project).unwrap();
+ let recording = RecoveryManager::analyze_incomplete(project, &metadata).unwrap();
+ let before = recovery_snapshot(project).unwrap();
+ let mut retained = None;
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ RecoveryManager::finalize_with_publication(
+ &recording,
+ RecoveryPurpose::Finalize,
+ copy_recovery_input_with_durability,
+ |_, _| {
+ let sources = match observer.latest() {
+ PreparingStudioState::Available(sources) => sources,
+ PreparingStudioState::Unavailable(reason) => panic!("{reason}"),
+ _ => panic!("Expected preparing sources before injected failure"),
+ };
+ let live = sources.live().unwrap();
+ let video = live.video(0, PreparingVideoTrack::Display).unwrap();
+ let (source, paths) = video.input().unwrap();
+ let mut reader = source.reader(&paths[0])?;
+ let mut header = [0; 8];
+ reader.read_exact(&mut header)?;
+ retained = Some((sources.clone(), reader));
+ panic!("Injected finalizer interruption after source publication");
+ },
+ publish_recovery,
+ RecoveryLock::acquire,
+ Some(job),
+ )
+ }));
+ assert!(result.is_err());
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ let (sources, reader) = retained.unwrap();
+ assert!(sources.live().is_none());
+ drop(sources);
+ assert!(RecoveryLock::acquire(project).is_err());
+ drop(reader);
+ assert!(RecoveryLock::acquire(project).is_ok());
+ assert_eq!(recovery_snapshot(project).unwrap(), before);
+ assert!(project.join(DISPLAY).is_dir());
+ assert!(!project.join(OUTPUT).exists());
+ }
+
+ #[test]
+ fn preparing_drifted_completion_uses_ordinary_success_path() {
+ let directory = playable_studio_project(StudioRecordingStatus::NeedsRemux);
+ let project = directory.path();
+ let mut completed = completed_preparing_fixture(project);
+ let (job, observer) = PreparingStudioJob::claim(&completed, 9).unwrap();
+ let StudioRecordingMeta::MultipleSegments { inner } = &mut completed.meta else {
+ panic!()
+ };
+ inner.segments[0].display.fps = 60;
+ assert!(RecoveryManager::remux_stopped_with_preparing(&completed, job).unwrap());
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ assert!(project.join(OUTPUT).is_file());
+ assert!(RecoveryLock::acquire(project).is_ok());
+ }
+
+ #[test]
+ fn studio_finalization_preserves_encoded_audio_samples_and_offsets() {
+ let directory = playable_studio_project(StudioRecordingStatus::NeedsRemux);
+ let project = directory.path();
+ let microphone = add_fragmented_audio(project, "audio-input", 90);
+ let system_audio = add_fragmented_audio(project, "system_audio", 90);
+ let original_bytes = fs::read(&microphone).unwrap();
+ let original_audio = cap_audio::AudioData::from_file(&microphone).unwrap();
+ let mut meta = RecordingMeta::load_for_project(project).unwrap();
+ let RecordingMetaInner::Studio(studio) = &mut meta.inner else {
+ panic!()
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!()
+ };
+ inner.segments[0].mic = Some(AudioMeta {
+ path: "content/segments/segment-0/audio-input.m4a".into(),
+ start_time: Some(-0.125),
+ device_id: Some("benchmark microphone".into()),
+ gap_summary: None,
+ });
+ inner.segments[0].system_audio = Some(AudioMeta {
+ path: "content/segments/segment-0/system_audio.m4a".into(),
+ start_time: Some(0.25),
+ device_id: None,
+ gap_summary: None,
+ });
+ meta.save_for_project().unwrap();
+
+ assert!(RecoveryManager::remux_if_needed(project).unwrap());
+ let meta = RecordingMeta::load_for_project(project).unwrap();
+ let StudioRecordingMeta::MultipleSegments { inner } = meta.studio_meta().unwrap() else {
+ panic!()
+ };
+ let segment = &inner.segments[0];
+ let mic = segment.mic.as_ref().unwrap();
+ assert_eq!(
+ mic.path.as_str(),
+ "content/segments/segment-0/audio-input.m4a"
+ );
+ assert_eq!(mic.start_time, Some(-0.125));
+ assert_eq!(mic.device_id.as_deref(), Some("benchmark microphone"));
+ assert_eq!(
+ segment.system_audio.as_ref().unwrap().start_time,
+ Some(0.25)
+ );
+ for path in [&microphone, &system_audio] {
+ let audio = cap_audio::AudioData::from_file(path).unwrap();
+ assert_eq!(audio.channels(), original_audio.channels());
+ assert_eq!(audio.samples(), original_audio.samples());
+ }
+ let backup = fs::read_dir(project)
+ .unwrap()
+ .map(|entry| entry.unwrap().path())
+ .find(|path| {
+ path.file_name()
+ .unwrap()
+ .to_string_lossy()
+ .starts_with(".recovery-")
+ })
+ .unwrap();
+ assert_eq!(
+ fs::read(backup.join("original-segments/segment-0/audio-input.m4a")).unwrap(),
+ original_bytes
+ );
+ }
+
+ #[test]
+ fn studio_finalization_preserves_a_live_managed_audio_decoder() {
+ use cap_audio::{AudioStream, ChunkRead};
+ use std::sync::{Arc, atomic::AtomicBool};
+
+ let directory = playable_studio_project(StudioRecordingStatus::NeedsRemux);
+ let project = directory.path();
+ let microphone = add_fragmented_audio(project, "audio-input", 2880);
+ assert!(microphone.metadata().unwrap().len() > 4 * 64 * 1024);
+ let original_audio = cap_audio::AudioData::from_file(&microphone).unwrap();
+ let mut meta = RecordingMeta::load_for_project(project).unwrap();
+ let RecordingMetaInner::Studio(studio) = &mut meta.inner else {
+ panic!()
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ panic!()
+ };
+ inner.segments[0].mic = Some(AudioMeta {
+ path: "content/segments/segment-0/audio-input.m4a".into(),
+ start_time: Some(-0.125),
+ device_id: None,
+ gap_summary: None,
+ });
+ meta.save_for_project().unwrap();
+ let recording = RecoveryManager::analyze_incomplete(project, &meta).unwrap();
+ let source = RelocatableSource::new(project.join("content/segments")).unwrap();
+ let mut audio = AudioStream::open_relocatable(
+ &source,
+ [Path::new("segment-0/audio-input.m4a")],
+ Arc::new(AtomicBool::new(false)),
+ )
+ .unwrap();
+ let ChunkRead::Chunk(prefix) = audio.read_chunk(4096).unwrap() else {
+ panic!()
+ };
+ assert_eq!(prefix.source_start_sample, 0);
+ let mut decoded = prefix.samples;
+ let recovered =
+ RecoveryManager::finalize_with_relocatable_source(&recording, &source).unwrap();
+ assert_eq!(recovered.project_path, project);
+ loop {
+ match audio.read_chunk(4096).unwrap() {
+ ChunkRead::Chunk(chunk) => {
+ assert_eq!(
+ chunk.source_start_sample as usize,
+ decoded.len() / usize::from(original_audio.channels())
+ );
+ assert_eq!(chunk.channels, original_audio.channels());
+ decoded.extend(chunk.samples);
+ }
+ ChunkRead::Eof { next_sample } => {
+ assert_eq!(
+ next_sample as usize,
+ decoded.len() / usize::from(original_audio.channels())
+ );
+ break;
+ }
+ }
+ }
+ let expected = original_audio
+ .samples()
+ .iter()
+ .map(|sample| sample.to_bits());
+ assert!(decoded.iter().map(|sample| sample.to_bits()).eq(expected));
+ let finalized = cap_audio::AudioData::from_file(&microphone).unwrap();
+ assert!(
+ finalized
+ .samples()
+ .iter()
+ .map(|sample| sample.to_bits())
+ .eq(original_audio
+ .samples()
+ .iter()
+ .map(|sample| sample.to_bits()))
+ );
+ let persisted = RecordingMeta::load_for_project(project).unwrap();
+ assert_eq!(
+ serde_json::to_value(persisted.studio_meta()).unwrap(),
+ serde_json::to_value(&recovered.meta).unwrap()
+ );
+ }
+
+ #[test]
+ fn recovery_copies_have_independent_bytes_and_preserve_existing_destinations() {
+ let directory = tempfile::tempdir().unwrap();
+ let source = directory.path().join("source");
+ let destination = directory.path().join("destination");
+ fs::write(&source, b"original recording").unwrap();
+ copy_recovery_input(&source, &destination).unwrap();
+ fs::write(&destination, b"staged recording").unwrap();
+ assert_eq!(fs::read(&source).unwrap(), b"original recording");
+ assert!(copy_recovery_input(&source, &destination).is_err());
+ assert_eq!(fs::read(&destination).unwrap(), b"staged recording");
+ }
+
fn change_fragment_bytes(project: &Path) {
let path = project.join(FRAGMENT);
let modified = fs::metadata(&path).unwrap().modified().unwrap();
@@ -4137,6 +5140,7 @@ mod required_track_failure_recovery_tests {
#[cfg(test)]
mod transactional_recovery_tests {
use super::*;
+ use std::io::{Read, Seek, SeekFrom};
fn publication_fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {
let temporary = tempfile::tempdir().unwrap();
@@ -4179,6 +5183,144 @@ mod transactional_recovery_tests {
assert!(workspace.join(RECOVERY_PUBLICATION_RECEIPT).is_file());
}
+ fn publication_fixture_with_version(
+ version: u32,
+ had_config: bool,
+ ) -> (tempfile::TempDir, PathBuf, PathBuf) {
+ let fixture = publication_fixture();
+ let (_, project, workspace) = &fixture;
+ if !had_config {
+ std::fs::remove_file(project.join("project-config.json")).unwrap();
+ }
+ interrupt_publication(project, workspace, 0);
+ let stamp_version = match version {
+ 1 => RecoveryPublicationStampVersion::V1,
+ 2 => RecoveryPublicationStampVersion::V2,
+ _ => unreachable!(),
+ };
+ let receipt = RecoveryPublication {
+ version,
+ project: project.canonicalize().unwrap(),
+ workspace: workspace.file_name().unwrap().to_str().unwrap().into(),
+ original: recovery_publication_state_for_version(project, stamp_version).unwrap(),
+ staged: recovery_publication_state_for_version(
+ &workspace.join("staged"),
+ stamp_version,
+ )
+ .unwrap(),
+ };
+ let bytes = serde_json::to_vec(&receipt).unwrap();
+ std::fs::write(project.join(RECOVERY_PUBLICATION), &bytes).unwrap();
+ std::fs::write(workspace.join(RECOVERY_PUBLICATION_RECEIPT), bytes).unwrap();
+ fixture
+ }
+
+ #[test]
+ fn publication_receipt_versions_reconcile_without_changing_originals() {
+ for version in [1, 2] {
+ for had_config in [false, true] {
+ let (_temporary, project, workspace) =
+ publication_fixture_with_version(version, had_config);
+ let original = recovery_snapshot(&project).unwrap();
+ let receipt = std::fs::read(workspace.join(RECOVERY_PUBLICATION_RECEIPT)).unwrap();
+ let _lock = RecoveryLock::acquire(&project).unwrap();
+ assert_eq!(recovery_snapshot(&project).unwrap(), original);
+ assert!(!project.join(RECOVERY_PUBLICATION).exists());
+ assert_eq!(
+ std::fs::read(workspace.join(RECOVERY_PUBLICATION_RECEIPT)).unwrap(),
+ receipt
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn publication_receipt_versions_retain_conflict_guards() {
+ use std::io::Write;
+
+ for version in [1, 2] {
+ for changed in [
+ "raw", "added", "removed", "metadata", "config", "stamp", "receipt",
+ ] {
+ let (_temporary, project, workspace) =
+ publication_fixture_with_version(version, true);
+ match changed {
+ "raw" => {
+ let path = project.join("content/segments/raw.m4s");
+ let modified = path.metadata().unwrap().modified().unwrap();
+ let mut file = std::fs::OpenOptions::new().write(true).open(path).unwrap();
+ file.set_len(0).unwrap();
+ file.write_all(b"different raw length with original modification time")
+ .unwrap();
+ file.set_times(std::fs::FileTimes::new().set_modified(modified))
+ .unwrap();
+ }
+ "added" => {
+ std::fs::create_dir(project.join("content/segments/unrelated")).unwrap();
+ }
+ "removed" => {
+ std::fs::remove_file(project.join("content/segments/raw.m4s")).unwrap();
+ }
+ "metadata" | "config" => {
+ let name = if changed == "metadata" {
+ "recording-meta.json"
+ } else {
+ "project-config.json"
+ };
+ let path = project.join(name);
+ let mut bytes = std::fs::read(&path).unwrap();
+ bytes[0] ^= 1;
+ std::fs::write(path, bytes).unwrap();
+ }
+ "stamp" => {
+ let path = project.join(RECOVERY_PUBLICATION);
+ let mut receipt: RecoveryPublication =
+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ receipt.original.segments.as_mut().unwrap()[0] ^= 1;
+ let bytes = serde_json::to_vec(&receipt).unwrap();
+ std::fs::write(path, &bytes).unwrap();
+ std::fs::write(workspace.join(RECOVERY_PUBLICATION_RECEIPT), bytes)
+ .unwrap();
+ }
+ "receipt" => {
+ std::fs::write(
+ workspace.join(RECOVERY_PUBLICATION_RECEIPT),
+ b"different receipt",
+ )
+ .unwrap();
+ }
+ _ => unreachable!(),
+ }
+ let before = recovery_snapshot(&project).unwrap();
+ assert!(RecoveryLock::acquire(&project).is_err());
+ assert_eq!(recovery_snapshot(&project).unwrap(), before);
+ assert!(project.join(RECOVERY_PUBLICATION).is_file());
+ assert!(workspace.join(RECOVERY_PUBLICATION_RECEIPT).is_file());
+ }
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn legacy_publication_receipts_never_fall_back_to_version_two_stamps() {
+ let (_temporary, project, workspace) = publication_fixture_with_version(2, true);
+ let legacy =
+ recovery_publication_state_for_version(&project, RecoveryPublicationStampVersion::V1)
+ .unwrap();
+ let path = project.join(RECOVERY_PUBLICATION);
+ let mut receipt: RecoveryPublication =
+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert!(legacy.segments != receipt.original.segments);
+ receipt.version = 1;
+ let bytes = serde_json::to_vec(&receipt).unwrap();
+ std::fs::write(&path, &bytes).unwrap();
+ std::fs::write(workspace.join(RECOVERY_PUBLICATION_RECEIPT), &bytes).unwrap();
+ let before = recovery_snapshot(&project).unwrap();
+ assert!(RecoveryLock::acquire(&project).is_err());
+ assert_eq!(recovery_snapshot(&project).unwrap(), before);
+ assert_eq!(std::fs::read(path).unwrap(), bytes);
+ }
+
fn scannable_publication_fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {
let (temporary, project, workspace) = publication_fixture();
let meta = RecordingMeta {
@@ -4584,7 +5726,7 @@ mod transactional_recovery_tests {
"oversized" => vec![0; RECOVERY_PUBLICATION_MAX_BYTES as usize + 1],
_ => {
match value {
- "version" => receipt.version = 2,
+ "version" => receipt.version = u32::MAX,
"generation" => {
receipt.workspace = format!(".recovery-{}", uuid::Uuid::new_v4())
}
@@ -4670,6 +5812,195 @@ mod transactional_recovery_tests {
}
}
+ #[test]
+ fn preparing_reader_retains_recovery_lock_after_source_and_finalizer_drop() {
+ let (_temporary, project, workspace) = publication_fixture();
+ let mut reader = {
+ let lock = Arc::new(RecoveryLock::acquire(&project).unwrap());
+ let source =
+ RelocatableSource::new_with_owner(project.join("content/segments"), lock.clone())
+ .unwrap();
+ let mut reader = source.reader(Path::new("raw.m4s")).unwrap();
+ let mut prefix = [0; 4];
+ reader.read_exact(&mut prefix).unwrap();
+ assert_eq!(&prefix, b"orig");
+ publish_recovery_with_source(&project, &workspace, &source).unwrap();
+ reader
+ };
+ assert!(RecoveryLock::acquire(&project).is_err());
+ let mut suffix = Vec::new();
+ reader.read_to_end(&mut suffix).unwrap();
+ assert_eq!(suffix, b"inal raw");
+ drop(reader);
+ let lock = RecoveryLock::acquire(&project).unwrap();
+ drop(lock);
+ }
+
+ #[test]
+ fn preparing_source_failures_release_recovery_lock_without_retained_readers() {
+ let (_temporary, project, _workspace) = publication_fixture();
+ let owner = Arc::new(RecoveryLock::acquire(&project).unwrap());
+ assert!(RelocatableSource::new_with_owner(project.join("missing"), owner).is_err());
+ let owner = Arc::new(RecoveryLock::acquire(&project).unwrap());
+ let source =
+ RelocatableSource::new_with_owner(project.join("content/segments"), owner).unwrap();
+ assert!(source.reader(Path::new("missing.m4s")).is_err());
+ drop(source);
+ let lock = RecoveryLock::acquire(&project).unwrap();
+ drop(lock);
+ }
+
+ #[test]
+ fn managed_recovery_publication_keeps_readers_on_original_media() {
+ let (_temporary, project, workspace) = publication_fixture();
+ let source = RelocatableSource::new(project.join("content/segments")).unwrap();
+ let mut reader = source.reader(Path::new("raw.m4s")).unwrap();
+ let mut prefix = [0; 4];
+ reader.read_exact(&mut prefix).unwrap();
+ assert_eq!(&prefix, b"orig");
+ publish_recovery_with_source(&project, &workspace, &source).unwrap();
+ let mut suffix = Vec::new();
+ reader.read_to_end(&mut suffix).unwrap();
+ assert_eq!(suffix, b"inal raw");
+ reader.seek(SeekFrom::Start(0)).unwrap();
+ let mut bytes = Vec::new();
+ reader.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"original raw");
+ let mut reopened = source.reader(Path::new("raw.m4s")).unwrap();
+ bytes.clear();
+ reopened.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"original raw");
+ assert_eq!(
+ std::fs::read(project.join("content/segments/display.mp4")).unwrap(),
+ b"validated output"
+ );
+ assert!(!project.join(RECOVERY_PUBLICATION).exists());
+ }
+
+ #[test]
+ fn managed_recovery_readers_survive_every_publication_rollback() {
+ for failure in 1..=4 {
+ let (_temporary, project, workspace) = publication_fixture();
+ let before = recovery_snapshot(&project).unwrap();
+ let original = project.join("content/segments");
+ let backup = workspace.join("original-segments");
+ let source = RelocatableSource::new(original.clone()).unwrap();
+ let mut reader = source.reader(Path::new("raw.m4s")).unwrap();
+ let mut prefix = [0; 4];
+ reader.read_exact(&mut prefix).unwrap();
+ let mut calls = 0;
+ let result = publish_recovery_with(&project, &workspace, |from, to| {
+ calls += 1;
+ if calls == failure {
+ return Err(std::io::Error::other(
+ "injected managed publication failure",
+ ));
+ }
+ rename_recovery_path_with_source(from, to, &original, &backup, &source)
+ });
+ assert!(result.is_err());
+ assert_eq!(recovery_snapshot(&project).unwrap(), before);
+ assert!(!project.join(RECOVERY_PUBLICATION).exists());
+ let mut suffix = Vec::new();
+ reader.read_to_end(&mut suffix).unwrap();
+ assert_eq!(suffix, b"inal raw");
+ assert!(source.reader(Path::new("raw.m4s")).is_ok());
+ }
+ }
+
+ #[test]
+ fn managed_recovery_rollback_failure_retains_readable_originals() {
+ for rollback_failure in 5..=7 {
+ let (_temporary, project, workspace) = publication_fixture();
+ let original = project.join("content/segments");
+ let backup = workspace.join("original-segments");
+ let source = RelocatableSource::new(original.clone()).unwrap();
+ let mut reader = source.reader(Path::new("raw.m4s")).unwrap();
+ let mut prefix = [0; 4];
+ reader.read_exact(&mut prefix).unwrap();
+ let mut calls = 0;
+ let result = publish_recovery_with(&project, &workspace, |from, to| {
+ calls += 1;
+ if calls == 4 || calls == rollback_failure {
+ return Err(std::io::Error::other("injected managed rollback failure"));
+ }
+ rename_recovery_path_with_source(from, to, &original, &backup, &source)
+ });
+ assert!(result.unwrap_err().to_string().contains("rollback failed"));
+ assert!(project.join(RECOVERY_PUBLICATION).is_file());
+ assert_eq!(
+ std::fs::read(backup.join("raw.m4s")).unwrap(),
+ b"original raw"
+ );
+ let mut suffix = Vec::new();
+ reader.read_to_end(&mut suffix).unwrap();
+ assert_eq!(suffix, b"inal raw");
+ }
+ }
+
+ #[test]
+ fn managed_recovery_refuses_a_different_projects_source() {
+ let (_temporary, project, workspace) = publication_fixture();
+ let (_other_temporary, other, _other_workspace) = publication_fixture();
+ let before = recovery_snapshot(&project).unwrap();
+ let other_before = recovery_snapshot(&other).unwrap();
+ let source = RelocatableSource::new(other.join("content/segments")).unwrap();
+ let mut reader = source.reader(Path::new("raw.m4s")).unwrap();
+ assert!(publish_recovery_with_source(&project, &workspace, &source).is_err());
+ assert_eq!(recovery_snapshot(&project).unwrap(), before);
+ assert_eq!(recovery_snapshot(&other).unwrap(), other_before);
+ assert!(!project.join(RECOVERY_PUBLICATION).exists());
+ let mut bytes = Vec::new();
+ reader.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"original raw");
+ }
+
+ #[test]
+ fn managed_recovery_lock_leaves_pending_publication_for_reader_shutdown() {
+ let (_temporary, project, workspace) = publication_fixture();
+ let original = project.join("content/segments");
+ let backup = workspace.join("original-segments");
+ let source = RelocatableSource::new(original.clone()).unwrap();
+ let mut reader = source.reader(Path::new("raw.m4s")).unwrap();
+ let mut prefix = [0; 4];
+ reader.read_exact(&mut prefix).unwrap();
+ {
+ let _lock = RecoveryLock::acquire(&project).unwrap();
+ let mut calls = 0;
+ let interrupted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ publish_recovery_with(&project, &workspace, |from, to| {
+ rename_recovery_path_with_source(from, to, &original, &backup, &source)?;
+ calls += 1;
+ assert_ne!(calls, 1, "interrupted after managed source relocation");
+ Ok(())
+ })
+ }));
+ assert!(interrupted.is_err());
+ }
+ let receipt = std::fs::read(project.join(RECOVERY_PUBLICATION)).unwrap();
+ assert!(RecoveryLock::acquire_for_preparing_preview(&project).is_err());
+ assert_eq!(
+ std::fs::read(project.join(RECOVERY_PUBLICATION)).unwrap(),
+ receipt
+ );
+ assert!(!original.exists());
+ assert_eq!(
+ std::fs::read(backup.join("raw.m4s")).unwrap(),
+ b"original raw"
+ );
+ let mut suffix = Vec::new();
+ reader.read_to_end(&mut suffix).unwrap();
+ assert_eq!(suffix, b"inal raw");
+ drop(reader);
+ drop(source);
+ let _lock = RecoveryLock::acquire(&project).unwrap();
+ assert_eq!(
+ std::fs::read(original.join("raw.m4s")).unwrap(),
+ b"original raw"
+ );
+ assert!(!project.join(RECOVERY_PUBLICATION).exists());
+ }
+
#[test]
fn recovery_scan_cannot_mark_failed_during_publication_rollback() {
let (temporary, project, workspace) = publication_fixture();
@@ -4940,6 +6271,51 @@ mod transactional_recovery_tests {
std::fs::create_dir(project.join("content/segments/segment-1")).unwrap();
assert_ne!(recovery_snapshot(&project).unwrap(), before);
}
+
+ #[test]
+ fn large_recovery_snapshots_preserve_exact_bytes_and_directory_entries() {
+ use std::io::{Seek, SeekFrom, Write};
+
+ let directory = tempfile::tempdir().unwrap();
+ let project = directory.path();
+ std::fs::create_dir_all(project.join("content/nested/empty")).unwrap();
+ let first = vec![0x25; 16 * 1024 * 1024 + 1];
+ let second = vec![0x82; first.len()];
+ std::fs::write(project.join("content/first.bin"), &first).unwrap();
+ std::fs::write(project.join("content/nested/second.bin"), &second).unwrap();
+ std::fs::write(project.join("recording-meta.json"), b"metadata").unwrap();
+ std::fs::write(project.join("excluded"), b"not a recovery input").unwrap();
+
+ let mut expected = RecoverySnapshot::new();
+ for path in ["content", "content/nested", "content/nested/empty"] {
+ let _ = expected.insert(PathBuf::from(path), None);
+ }
+ for (path, bytes) in [
+ ("content/first.bin", first.as_slice()),
+ ("content/nested/second.bin", second.as_slice()),
+ ("recording-meta.json", b"metadata".as_slice()),
+ ] {
+ let _ = expected.insert(
+ PathBuf::from(path),
+ Some(blake3::hash(bytes).as_bytes().to_vec()),
+ );
+ }
+ assert_eq!(recovery_snapshot(project).unwrap(), expected);
+
+ let path = project.join("content/nested/second.bin");
+ let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
+ let mut file = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
+ file.seek(SeekFrom::End(-1)).unwrap();
+ file.write_all(&[0x83]).unwrap();
+ file.set_times(std::fs::FileTimes::new().set_modified(modified))
+ .unwrap();
+ assert_ne!(recovery_snapshot(project).unwrap(), expected);
+ file.seek(SeekFrom::End(-1)).unwrap();
+ file.write_all(&[0x82]).unwrap();
+ assert_eq!(recovery_snapshot(project).unwrap(), expected);
+ std::fs::remove_dir(project.join("content/nested/empty")).unwrap();
+ assert_ne!(recovery_snapshot(project).unwrap(), expected);
+ }
#[test]
fn recovery_lock_child_probe() {
let Some(path) = std::env::var_os("CAP_RECOVERY_LOCK_CHILD") else {
@@ -4994,3 +6370,6 @@ mod transactional_recovery_tests {
);
}
}
+
+#[cfg(test)]
+mod preparing_canonical_probe;
diff --git a/crates/recording/src/recovery/preparing_canonical_probe.rs b/crates/recording/src/recovery/preparing_canonical_probe.rs
new file mode 100644
index 000000000..b098a2103
--- /dev/null
+++ b/crates/recording/src/recovery/preparing_canonical_probe.rs
@@ -0,0 +1,1259 @@
+use super::preparing_observer::{PreparingAudioTrack, PreparingVideoTrack};
+use super::{
+ PreparingStudioJob, PreparingStudioObserver, PreparingStudioSources, PreparingStudioState,
+ RecoveryManager,
+};
+use crate::studio_recording::{CleanStoppedStudio, CleanStoppedStudioClaim, CompletedRecording};
+use anyhow::{Context, Result, bail, ensure};
+use cap_audio::{AudioStream, ChunkRead};
+use cap_enc_ffmpeg::RelocatableSource;
+use cap_project::{
+ Cursors, MultipleSegment, ProjectConfiguration, RecordingMeta, RecordingMetaInner,
+ StudioRecordingMeta,
+};
+use cap_rendering::decoder::{
+ DecodedFrame, ManagedVideoDecoder, PixelFormat, spawn_managed_decoder,
+};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use sha2::{Digest, Sha256};
+use std::{
+ collections::BTreeMap,
+ fs,
+ io::Read,
+ path::{Component, Path, PathBuf},
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+ thread::JoinHandle,
+ time::Instant,
+};
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+struct FileRecord {
+ bytes: u64,
+ sha256: String,
+}
+
+type FileManifest = BTreeMap<String, FileRecord>;
+
+fn hash_file(path: &Path) -> Result<FileRecord> {
+ let mut input = fs::File::open(path)?;
+ let mut hash = Sha256::new();
+ let mut bytes = 0_u64;
+ let mut buffer = vec![0_u8; 1024 * 1024];
+ loop {
+ let count = input.read(&mut buffer)?;
+ if count == 0 {
+ break;
+ }
+ bytes += count as u64;
+ hash.update(&buffer[..count]);
+ }
+ Ok(FileRecord {
+ bytes,
+ sha256: hex::encode(hash.finalize()),
+ })
+}
+
+fn manifest(root: &Path, public_only: bool) -> Result<FileManifest> {
+ fn visit(root: &Path, path: &Path, public_only: bool, result: &mut FileManifest) -> Result<()> {
+ let metadata = path.symlink_metadata()?;
+ super::reject_recovery_link(&metadata)?;
+ if metadata.is_dir() {
+ for entry in fs::read_dir(path)? {
+ let entry = entry?;
+ if public_only && path == root {
+ let name = entry.file_name();
+ let name = name.to_string_lossy();
+ if name == ".recovery.lock"
+ || (entry.file_type()?.is_dir()
+ && name
+ .strip_prefix(".recovery-")
+ .is_some_and(|suffix| uuid::Uuid::parse_str(suffix).is_ok()))
+ {
+ continue;
+ }
+ }
+ visit(root, &entry.path(), public_only, result)?;
+ }
+ } else {
+ ensure!(
+ metadata.is_file(),
+ "Unsupported fixture object: {}",
+ path.display()
+ );
+ let relative = path
+ .strip_prefix(root)?
+ .to_str()
+ .context("Non-UTF8 fixture path")?
+ .replace('\\', "/");
+ ensure!(
+ result.insert(relative, hash_file(path)?).is_none(),
+ "Duplicate fixture path"
+ );
+ }
+ Ok(())
+ }
+ let mut result = BTreeMap::new();
+ visit(root, root, public_only, &mut result)?;
+ Ok(result)
+}
+
+fn copy_fixture(source: &Path, destination: &Path, expected: &FileManifest) -> Result<()> {
+ fs::create_dir(destination)?;
+ for (relative, wanted) in expected {
+ let relative = Path::new(relative);
+ ensure!(
+ relative
+ .components()
+ .all(|part| matches!(part, Component::Normal(_))),
+ "Non-local fixture path"
+ );
+ let target = destination.join(relative);
+ fs::create_dir_all(target.parent().context("Missing copy parent")?)?;
+ fs::copy(source.join(relative), &target)?;
+ ensure!(
+ hash_file(&target)? == *wanted,
+ "Fixture copy differs: {}",
+ relative.display()
+ );
+ }
+ Ok(())
+}
+
+fn ordered_json(value: Value) -> Value {
+ match value {
+ Value::Object(values) => {
+ let sorted: BTreeMap<_, _> = values.into_iter().collect();
+ Value::Object(
+ sorted
+ .into_iter()
+ .map(|(key, value)| (key, ordered_json(value)))
+ .collect(),
+ )
+ }
+ Value::Array(values) => Value::Array(values.into_iter().map(ordered_json).collect()),
+ value => value,
+ }
+}
+
+fn changed_json_fields(before: &Value, after: &Value) -> Vec<Value> {
+ fn visit(
+ path: String,
+ before: Option<&Value>,
+ after: Option<&Value>,
+ changes: &mut Vec<Value>,
+ ) {
+ if before == after {
+ return;
+ }
+ match (before, after) {
+ (Some(Value::Object(before)), Some(Value::Object(after))) => {
+ let keys: std::collections::BTreeSet<_> = before.keys().chain(after.keys()).collect();
+ for key in keys {
+ let escaped = key.replace('~', "~0").replace('/', "~1");
+ visit(format!("{path}/{escaped}"), before.get(key), after.get(key), changes);
+ }
+ }
+ (Some(Value::Array(before)), Some(Value::Array(after))) if before.len() == after.len() => {
+ for (index, (before, after)) in before.iter().zip(after).enumerate() {
+ visit(format!("{path}/{index}"), Some(before), Some(after), changes);
+ }
+ }
+ _ => changes.push(json!({ "pointer": path, "beforePresent": before.is_some(), "before": before, "afterPresent": after.is_some(), "after": after })),
+ }
+ }
+ let mut changes = Vec::new();
+ visit(String::new(), Some(before), Some(after), &mut changes);
+ changes
+}
+
+fn normalize_empty_legacy_cursors(metadata: &mut RecordingMeta) -> Result<()> {
+ let RecordingMetaInner::Studio(studio) = &mut metadata.inner else {
+ bail!("Current-writer fixture requires Studio metadata");
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ bail!("Current-writer fixture requires indexed Studio metadata");
+ };
+ match &inner.cursors {
+ Cursors::Old(cursors) if cursors.is_empty() => inner.cursors = Cursors::default(),
+ _ => bail!("Current-writer variant only accepts the canonical empty legacy cursor map"),
+ }
+ Ok(())
+}
+
+fn validate_current_writer_document(name: &str, before: &Value, after: &Value) -> Result<()> {
+ let expected = match name {
+ "recording-meta.json" => {
+ ensure!(
+ before.get("cursors") == Some(&json!({})),
+ "Expected exactly the canonical empty legacy cursor map"
+ );
+ let mut expected = before.clone();
+ expected
+ .as_object_mut()
+ .context("Metadata is not an object")?
+ .remove("cursors")
+ .context("Legacy cursor field disappeared")?;
+ expected
+ }
+ "project-config.json" => before.clone(),
+ _ => bail!("Unsupported current-writer document"),
+ };
+ ensure!(
+ expected == *after,
+ "Current writer would change unapproved {name} fields: {}",
+ json!(changed_json_fields(before, after))
+ );
+ Ok(())
+}
+
+fn current_writer_snapshot(project: &Path, original: &FileManifest) -> Result<Value> {
+ let mut metadata = RecordingMeta::load_for_project(project)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let configuration: ProjectConfiguration =
+ serde_json::from_slice(&fs::read(project.join("project-config.json"))?)?;
+ let before_metadata_semantics = serde_json::to_value(&metadata)?;
+ let before_configuration_semantics = serde_json::to_value(&configuration)?;
+ normalize_empty_legacy_cursors(&mut metadata)?;
+ ensure!(
+ serde_json::to_value(&metadata)? == before_metadata_semantics,
+ "Empty cursor representation changed typed metadata semantics"
+ );
+ let names = ["recording-meta.json", "project-config.json"];
+ let mut before_documents = BTreeMap::new();
+ for name in names {
+ let bytes = fs::read(project.join(name))?;
+ ensure!(
+ hash_file(&project.join(name))? == original[name],
+ "Owned legacy document differs before normalization"
+ );
+ before_documents.insert(name, serde_json::from_slice::<Value>(&bytes)?);
+ }
+ for (name, bytes) in [
+ ("recording-meta.json", serde_json::to_vec_pretty(&metadata)?),
+ (
+ "project-config.json",
+ serde_json::to_vec_pretty(&configuration)?,
+ ),
+ ] {
+ let planned: Value = serde_json::from_slice(&bytes)?;
+ validate_current_writer_document(name, &before_documents[name], &planned)?;
+ }
+ metadata
+ .save_for_project()
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ configuration.write(project)?;
+ let roundtrip_metadata = RecordingMeta::load_for_project(project)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let roundtrip_configuration: ProjectConfiguration =
+ serde_json::from_slice(&fs::read(project.join("project-config.json"))?)?;
+ ensure!(
+ serde_json::to_value(&roundtrip_metadata)? == before_metadata_semantics,
+ "Metadata writer roundtrip changed typed semantics"
+ );
+ ensure!(
+ serde_json::to_value(&roundtrip_configuration)? == before_configuration_semantics,
+ "Configuration writer roundtrip changed typed semantics"
+ );
+ let mut expected = original.clone();
+ let mut documents = BTreeMap::new();
+ for name in names {
+ let after = hash_file(&project.join(name))?;
+ let after_value: Value = serde_json::from_slice(&fs::read(project.join(name))?)?;
+ validate_current_writer_document(name, &before_documents[name], &after_value)?;
+ documents.insert(name, json!({ "before": original[name], "after": after, "changedFields": changed_json_fields(&before_documents[name], &after_value), "typedSemanticsUnchangedAfterWriterRoundtrip": true }));
+ expected.insert(name.to_string(), after);
+ }
+ ensure!(
+ manifest(project, false)? == expected,
+ "Current writer changed media, sidecars or unexpected files"
+ );
+ Ok(
+ json!({ "variant": "current-writer-empty-cursor-snapshot", "metadataWriter": "RecordingMeta::save_for_project", "configurationWriter": "ProjectConfiguration::write", "documents": documents, "allMediaAndSidecarBytesUnchanged": true }),
+ )
+}
+
+fn preflight_current_writer(project: &Path) -> Result<Value> {
+ let lock = super::RecoveryLock::acquire(project)?;
+ let metadata = RecordingMeta::load_for_project(project)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let configuration: ProjectConfiguration =
+ serde_json::from_slice(&fs::read(project.join("project-config.json"))?)?;
+ let claim = CleanStoppedStudioClaim::for_test(metadata.clone(), configuration)
+ .context("Current-writer snapshot receipt declined before finalization")?;
+ let recording = RecoveryManager::analyze_incomplete(project, &metadata)
+ .context("Current-writer snapshot has no recoverable source")?;
+ let projection = super::preparing_projection::project(&recording, &claim)
+ .map_err(anyhow::Error::msg)
+ .context("Current-writer source projection declined before finalization")?;
+ let segment_count = projection.segments.len();
+ drop(projection);
+ drop(claim);
+ drop(lock);
+ Ok(
+ json!({ "receiptEligible": true, "actualProjectorEligible": true, "segments": segment_count, "preflightObjectsAndLockDroppedBeforeFinalization": true }),
+ )
+}
+
+fn source_manifest_files(manifest: &Value) -> Result<BTreeMap<String, String>> {
+ match &manifest["files"] {
+ Value::Object(files) => files
+ .iter()
+ .map(|(path, hash)| {
+ Ok((
+ path.clone(),
+ hash.as_str()
+ .context("Source hash is not a string")?
+ .to_string(),
+ ))
+ })
+ .collect(),
+ Value::Array(files) => files
+ .iter()
+ .map(|file| {
+ Ok((
+ file["path"]
+ .as_str()
+ .context("Missing source path")?
+ .to_string(),
+ file["sha256"]
+ .as_str()
+ .context("Missing source SHA256")?
+ .to_string(),
+ ))
+ })
+ .collect(),
+ _ => bail!("Unsupported source manifest file map"),
+ }
+}
+
+fn validate_legacy_source_identity(control: &Value, current: &Value) -> Result<Value> {
+ let identity = &control["identity"];
+ let path = PathBuf::from(
+ identity["sourceManifest"]
+ .as_str()
+ .context("Legacy source manifest path missing")?,
+ );
+ let expected_hash = identity["sourceManifestSha256"]
+ .as_str()
+ .context("Legacy source manifest hash missing")?;
+ ensure!(
+ path.is_absolute() && hash_file(&path)?.sha256 == expected_hash,
+ "Legacy source manifest file identity mismatch"
+ );
+ let legacy_manifest: Value = serde_json::from_slice(&fs::read(&path)?)?;
+ ensure!(
+ legacy_manifest == identity["sourceManifestValue"],
+ "Legacy embedded source manifest differs from retained manifest"
+ );
+ let legacy_files = source_manifest_files(&legacy_manifest)?;
+ let current_files = source_manifest_files(current)?;
+ ensure!(
+ legacy_files.keys().eq(current_files.keys()),
+ "Legacy/current source manifests cover different files"
+ );
+ let probe = "crates/recording/src/recovery/preparing_canonical_probe.rs";
+ ensure!(
+ legacy_files.get(probe).map(String::as_str)
+ == Some("c633490f13fceaf76007ac3daa4c2692606af449ca6d2fc987b5507c25b7af6c"),
+ "Legacy control was not produced by the frozen v1 probe"
+ );
+ for (path, hash) in &legacy_files {
+ ensure!(
+ path == probe || current_files.get(path) == Some(hash),
+ "Runtime source differs from legacy control: {path}"
+ );
+ }
+ Ok(
+ json!({ "manifestPath": path, "manifestSha256": expected_hash, "sourceFilesCompared": legacy_files.len(), "onlyPermittedSourceDifference": probe, "runtimeSourceIdentityMatched": true }),
+ )
+}
+
+fn public_output(project: &Path) -> Result<Value> {
+ let mut media = manifest(project, true)?;
+ let mut documents = BTreeMap::new();
+ for name in ["recording-meta.json", "project-config.json"] {
+ let raw = media.remove(name).context("Missing published document")?;
+ let value = ordered_json(serde_json::from_slice(&fs::read(project.join(name))?)?);
+ let normalized = hex::encode(Sha256::digest(serde_json::to_vec(&value)?));
+ documents.insert(
+ name,
+ json!({ "raw": raw, "normalizedSha256": normalized, "value": value }),
+ );
+ }
+ Ok(json!({ "media": media, "documents": documents }))
+}
+
+fn compare_outputs(before: &Value, after: &Value) -> Result<()> {
+ ensure!(
+ before["media"] == after["media"],
+ "Published media bytes or file set differ"
+ );
+ for name in ["recording-meta.json", "project-config.json"] {
+ ensure!(
+ before["documents"][name]["value"] == after["documents"][name]["value"],
+ "Published {name} semantics differ"
+ );
+ }
+ Ok(())
+}
+
+fn retained_segments(project: &Path, canonical: &FileManifest) -> Result<Value> {
+ let mut backups = Vec::new();
+ for entry in fs::read_dir(project)? {
+ let entry = entry?;
+ if entry
+ .file_name()
+ .to_string_lossy()
+ .starts_with(".recovery-")
+ {
+ let path = entry.path().join("original-segments");
+ if path.try_exists()? {
+ backups.push(path);
+ }
+ }
+ }
+ ensure!(
+ backups.len() == 1,
+ "Expected one retained original-segments backup"
+ );
+ let expected: FileManifest = canonical
+ .iter()
+ .filter_map(|(name, record)| {
+ name.strip_prefix("content/segments/")
+ .map(|name| (name.to_string(), record.clone()))
+ })
+ .collect();
+ let actual = manifest(&backups[0], false)?;
+ ensure!(actual == expected, "Retained original media changed");
+ Ok(json!({ "path": backups[0], "files": actual, "allOriginalSegmentBytesMatch": true }))
+}
+
+struct OwnedThread<T>(Option<JoinHandle<T>>);
+
+impl<T> OwnedThread<T> {
+ fn join(mut self) -> Result<T> {
+ self.0
+ .take()
+ .context("Worker already joined")?
+ .join()
+ .map_err(|_| anyhow::anyhow!("Native worker panicked"))
+ }
+}
+
+impl<T> Drop for OwnedThread<T> {
+ fn drop(&mut self) {
+ if let Some(worker) = self.0.take() {
+ let _ = worker.join();
+ }
+ }
+}
+
+struct AudioWorker {
+ cancelled: Arc<AtomicBool>,
+ worker: Option<OwnedThread<Result<Value>>>,
+}
+
+impl AudioWorker {
+ fn start(
+ source: RelocatableSource,
+ relative: PathBuf,
+ canonical: PathBuf,
+ started: Instant,
+ ) -> Result<Self> {
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let stop = cancelled.clone();
+ let worker = std::thread::Builder::new().name("canonical-preparing-audio".into()).spawn(move || {
+ let mut reference = AudioStream::open(&canonical, Arc::new(AtomicBool::new(false)))?;
+ let mut managed = match AudioStream::open_relocatable(&source, [relative.as_path()], stop.clone()) {
+ Ok(managed) => managed,
+ Err(error) if error.is_cancelled() && stop.load(Ordering::Acquire) => {
+ drop(reference);
+ drop(source);
+ return Ok(json!({ "path": relative, "comparedFrames": 0, "allComparedPcmBitsMatch": true, "firstChunkObservedMs": null, "completeEofCompared": false, "cancelledAfterEnded": true, "openCancelledAfterEnded": true, "resourcesDroppedMs": started.elapsed().as_secs_f64() * 1000.0 }));
+ }
+ Err(error) => return Err(error.into()),
+ };
+ let mut frames = 0_u64;
+ let mut first_chunk_ms = None;
+ let mut eof = false;
+ let mut cancelled = false;
+ loop {
+ if stop.load(Ordering::Acquire) {
+ cancelled = true;
+ break;
+ }
+ let actual = match managed.read_chunk(12_000) {
+ Ok(actual) => actual,
+ Err(error) if error.is_cancelled() && stop.load(Ordering::Acquire) => {
+ cancelled = true;
+ break;
+ }
+ Err(error) => return Err(error.into()),
+ };
+ match (actual, reference.read_chunk(12_000)?) {
+ (ChunkRead::Chunk(actual), ChunkRead::Chunk(expected)) => {
+ first_chunk_ms.get_or_insert_with(|| started.elapsed().as_secs_f64() * 1000.0);
+ ensure!(actual.source_start_sample == frames && expected.source_start_sample == frames, "Non-contiguous audio prefix");
+ ensure!(actual.channels == expected.channels && actual.samples.len() == expected.samples.len(), "Audio shape differs");
+ ensure!(actual.samples.iter().zip(&expected.samples).all(|(actual, expected)| actual.to_bits() == expected.to_bits()), "Audio PCM bits differ at chunk starting {frames}");
+ frames += (actual.samples.len() / usize::from(actual.channels)) as u64;
+ }
+ (ChunkRead::Eof { next_sample: actual }, ChunkRead::Eof { next_sample: expected }) => {
+ ensure!(actual == expected && actual == frames, "Audio EOF differs");
+ eof = true;
+ break;
+ }
+ _ => bail!("Audio chunk/EOF state differs"),
+ }
+ }
+ drop(managed);
+ drop(reference);
+ drop(source);
+ Ok(json!({ "path": relative, "comparedFrames": frames, "allComparedPcmBitsMatch": true, "firstChunkObservedMs": first_chunk_ms, "completeEofCompared": eof, "cancelledAfterEnded": cancelled, "openCancelledAfterEnded": false, "resourcesDroppedMs": started.elapsed().as_secs_f64() * 1000.0 }))
+ })?;
+ Ok(Self {
+ cancelled,
+ worker: Some(OwnedThread(Some(worker))),
+ })
+ }
+
+ async fn stop_and_join(mut self, started: Instant) -> Result<Value> {
+ self.cancelled.store(true, Ordering::Release);
+ let worker = self.worker.take().context("Audio worker already joined")?;
+ let mut value = tokio::task::spawn_blocking(move || worker.join()).await???;
+ value["nativeJoinObservedMs"] = json!(started.elapsed().as_secs_f64() * 1000.0);
+ Ok(value)
+ }
+}
+
+impl Drop for AudioWorker {
+ fn drop(&mut self) {
+ self.cancelled.store(true, Ordering::Release);
+ drop(self.worker.take());
+ }
+}
+
+async fn ended(mut observer: PreparingStudioObserver) {
+ loop {
+ if matches!(observer.latest(), PreparingStudioState::Ended) {
+ return;
+ }
+ observer.changed().await;
+ }
+}
+
+fn frame_record(frame: &DecodedFrame) -> Result<Value> {
+ let mut hash = Sha256::new();
+ let mut bytes = 0_usize;
+ let width = frame.width() as usize;
+ let height = frame.height() as usize;
+ let mut plane = |data: &[u8], stride: usize, row_bytes: usize, rows: usize| -> Result<()> {
+ ensure!(
+ stride >= row_bytes && data.len() >= stride * rows,
+ "Invalid decoded plane"
+ );
+ for row in data.chunks(stride).take(rows) {
+ hash.update(&row[..row_bytes]);
+ bytes += row_bytes;
+ }
+ Ok(())
+ };
+ match frame.format() {
+ PixelFormat::Rgba => plane(frame.data(), width * 4, width * 4, height)?,
+ PixelFormat::Nv12 => {
+ plane(
+ frame.y_plane().context("Missing luma")?,
+ frame.y_stride() as usize,
+ width,
+ height,
+ )?;
+ plane(
+ frame.uv_plane().context("Missing chroma")?,
+ frame.uv_stride() as usize,
+ width,
+ height / 2,
+ )?;
+ }
+ PixelFormat::Yuv420p => {
+ plane(
+ frame.y_plane().context("Missing luma")?,
+ frame.y_stride() as usize,
+ width,
+ height,
+ )?;
+ plane(
+ frame.u_plane().context("Missing U plane")?,
+ frame.uv_stride() as usize,
+ width / 2,
+ height / 2,
+ )?;
+ plane(
+ frame.v_plane().context("Missing V plane")?,
+ frame.uv_stride() as usize,
+ width / 2,
+ height / 2,
+ )?;
+ }
+ }
+ ensure!(bytes > 0, "Empty software-decoded image");
+ Ok(
+ json!({ "width": width, "height": height, "format": format!("{:?}", frame.format()), "pixelBytes": bytes, "sha256": hex::encode(hash.finalize()) }),
+ )
+}
+
+fn single_segment(metadata: &RecordingMeta) -> Result<&MultipleSegment> {
+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = metadata.studio_meta() else {
+ bail!("Canonical fixture is not a multiple-segment Studio recording");
+ };
+ ensure!(
+ inner.segments.len() == 1,
+ "Canonical fixture must have one segment"
+ );
+ Ok(&inner.segments[0])
+}
+
+fn display_offset(segment: &MultipleSegment) -> f64 {
+ segment
+ .latest_start_time()
+ .zip(segment.display.start_time)
+ .map(|(latest, display)| latest - display)
+ .unwrap_or(0.0)
+}
+
+async fn finalized_video_reference(
+ project: &Path,
+ stopped: &RecordingMeta,
+ times: &[f32],
+) -> Result<Value> {
+ let finalized = RecordingMeta::load_for_project(project)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let stopped_segment = single_segment(stopped)?;
+ let finalized_segment = single_segment(&finalized)?;
+ let stopped_offset = display_offset(stopped_segment);
+ let finalized_offset = display_offset(finalized_segment);
+ ensure!(
+ stopped_offset.to_bits() == finalized_offset.to_bits(),
+ "Published display offset differs from stopped metadata"
+ );
+ ensure!(
+ stopped_segment.display.fps == finalized_segment.display.fps,
+ "Published display FPS differs from stopped metadata"
+ );
+ let root = project.join("content/segments");
+ let display_path = finalized_segment.display.path.to_path(project);
+ ensure!(
+ display_path
+ .extension()
+ .is_some_and(|extension| extension == "mp4"),
+ "Reference is not a finalized MP4 file"
+ );
+ let relative = display_path.strip_prefix(&root)?.to_path_buf();
+ let source = RelocatableSource::new(root)?;
+ let mut decoder = spawn_managed_decoder(
+ "canonical-finalized-file-reference",
+ source.clone(),
+ [relative.as_path()],
+ finalized_segment.display.fps,
+ finalized_offset,
+ false,
+ )?;
+ let work = async {
+ let status = decoder.wait_ready().await?;
+ let mut frames = Vec::new();
+ for &time in times {
+ let frame = decoder.get_frame_initial(time).await?;
+ frames.push(json!({ "requestedTime": time, "pixels": frame_record(&frame)? }));
+ }
+ Ok::<_, anyhow::Error>(json!({ "method": "ordinary-finalized-file/software/shared-managed-worker-loop", "relativeFile": relative, "fps": finalized_segment.display.fps, "stoppedOffset": stopped_offset, "finalizedOffset": finalized_offset, "decoderType": format!("{:?}", status.decoder_type), "frames": frames }))
+ }.await;
+ let exit = decoder.stop_and_wait().await;
+ drop(decoder);
+ drop(source);
+ let mut result = work?;
+ result["workerExit"] = json!(format!("{:?}", exit.terminal));
+ result["workerJoinedAndFileHandlesDroppedBeforeBaselineDeletion"] = json!(true);
+ Ok(result)
+}
+
+async fn exercise_video(
+ decoder: &mut ManagedVideoDecoder,
+ observer: &PreparingStudioObserver,
+ sources: &PreparingStudioSources,
+ times: &[f32],
+ reference: &Value,
+ started: Instant,
+) -> Result<Value> {
+ let ready = tokio::select! {
+ result = decoder.wait_ready() => Some(result),
+ () = ended(observer.clone()) => None,
+ };
+ let Some(ready) = ready else {
+ return Ok(json!({ "endedBeforeReady": true, "frames": [] }));
+ };
+ let status = ready?;
+ let mut frames = Vec::new();
+ for (index, &time) in times.iter().enumerate() {
+ if sources.live().is_none() {
+ break;
+ }
+ let result = tokio::select! {
+ result = decoder.get_frame_initial(time) => Some(result),
+ () = ended(observer.clone()) => None,
+ };
+ let Some(result) = result else { break };
+ let observed_ms = started.elapsed().as_secs_f64() * 1000.0;
+ if sources.live().is_none() {
+ break;
+ }
+ let frame = result?;
+ let pixels = frame_record(&frame)?;
+ let expected = &reference["frames"][index];
+ ensure!(
+ expected["requestedTime"] == json!(time),
+ "Finalized reference request differs at index {index}"
+ );
+ ensure!(
+ pixels == expected["pixels"],
+ "Preparing/finalized pixels differ at {time}: preparing={pixels}, finalized={}",
+ expected["pixels"]
+ );
+ frames.push(json!({ "requestedTime": time, "decodedFrameObservedMs": observed_ms, "pixels": pixels, "matchesOrdinaryFinalizedSoftwareFrame": true }));
+ }
+ Ok(
+ json!({ "decoderType": format!("{:?}", status.decoder_type), "frames": frames, "allCommonSeeksObserved": frames.len() == times.len(), "endedDuringRequests": sources.live().is_none() }),
+ )
+}
+
+async fn observe_preparing(
+ mut observer: PreparingStudioObserver,
+ canonical: &Path,
+ times: &[f32],
+ reference: &Value,
+ started: Instant,
+) -> Result<Value> {
+ let sources = loop {
+ match observer.latest() {
+ PreparingStudioState::Available(sources) => break sources,
+ PreparingStudioState::Ended => {
+ return Ok(
+ json!({ "endedBeforeAvailabilityObserved": true, "availabilityObservedMs": null }),
+ );
+ }
+ PreparingStudioState::Unavailable(reason) => {
+ bail!("Canonical preparing source declined: {reason}")
+ }
+ PreparingStudioState::Waiting => {
+ observer.changed().await;
+ }
+ }
+ };
+ let available_ms = started.elapsed().as_secs_f64() * 1000.0;
+ ensure!(
+ sources.identity().same_job(observer.identity()),
+ "Available source belongs to a different finalizer job"
+ );
+ let job_identity = json!({ "projectPath": sources.identity().project_path(), "generation": sources.identity().generation(), "jobId": sources.identity().job_id().to_string() });
+ let Some(live) = sources.live() else {
+ return Ok(json!({ "availabilityObservedMs": available_ms, "endedBeforeLiveView": true }));
+ };
+ let Some(segments) = live.segments() else {
+ return Ok(json!({ "availabilityObservedMs": available_ms, "endedBeforeSegments": true }));
+ };
+ ensure!(
+ segments.len() == 1 && segments[0].index() == 0,
+ "Canonical probe expects its original single segment"
+ );
+ let metadata = segments[0].metadata().clone();
+ let mut audios = Vec::new();
+ for (track, declared) in [
+ (PreparingAudioTrack::Mic, metadata.mic.is_some()),
+ (
+ PreparingAudioTrack::SystemAudio,
+ metadata.system_audio.is_some(),
+ ),
+ ] {
+ if !declared {
+ continue;
+ }
+ let Some(lease) = live.audio(0, track) else {
+ break;
+ };
+ let Some((source, path)) = lease.input() else {
+ break;
+ };
+ audios.push(AudioWorker::start(
+ source.clone(),
+ path.to_path_buf(),
+ canonical.join("content/segments").join(path),
+ started,
+ )?);
+ }
+ let video_work = async {
+ let Some(lease) = live.video(0, PreparingVideoTrack::Display) else {
+ return Ok(json!({ "endedBeforeVideoLease": true }));
+ };
+ let Some((source, paths)) = lease.input() else {
+ return Ok(json!({ "endedBeforeVideoInput": true }));
+ };
+ let offset = display_offset(&metadata);
+ ensure!(reference["stoppedOffset"] == json!(offset), "Preparing display offset differs from stopped reference");
+ ensure!(reference["fps"] == json!(metadata.display.fps), "Preparing display FPS differs from reference");
+ let mut decoder = spawn_managed_decoder("canonical-preparing-display", source.clone(), paths.iter().map(PathBuf::as_path), metadata.display.fps, offset, false)?;
+ let work = exercise_video(&mut decoder, &observer, &sources, times, reference, started).await;
+ let exit = decoder.stop_and_wait().await;
+ let joined_ms = started.elapsed().as_secs_f64() * 1000.0;
+ drop(decoder);
+ work.map(|video| json!({ "video": video, "videoWorkerJoinedMs": joined_ms, "videoExit": format!("{:?}", exit.terminal), "offset": offset }))
+ }.await;
+ ended(observer.clone()).await;
+ let ended_ms = started.elapsed().as_secs_f64() * 1000.0;
+ for worker in &audios {
+ worker.cancelled.store(true, Ordering::Release);
+ }
+ let mut audio_results = Vec::new();
+ let mut audio_error = None;
+ for worker in audios {
+ match worker.stop_and_join(started).await {
+ Ok(result) => audio_results.push(result),
+ Err(error) => {
+ audio_error.get_or_insert(error);
+ }
+ }
+ }
+ ensure!(
+ sources.live().is_none(),
+ "Ended source still authorizes new access"
+ );
+ drop(sources);
+ let source_references_dropped_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let last_joined_ms = video_work
+ .as_ref()
+ .ok()
+ .and_then(|value| value["videoWorkerJoinedMs"].as_f64())
+ .into_iter()
+ .chain(
+ audio_results
+ .iter()
+ .filter_map(|value| value["nativeJoinObservedMs"].as_f64()),
+ )
+ .reduce(f64::max);
+ let video = video_work?;
+ if let Some(error) = audio_error {
+ return Err(error);
+ }
+ Ok(
+ json!({ "jobIdentity": job_identity, "availabilityObservedMs": available_ms, "endedObservedMs": ended_ms, "lastPreparingWorkerJoinObservedMs": last_joined_ms, "sourceReferencesDroppedMs": source_references_dropped_ms, "video": video, "audio": audio_results, "allPreparingSourceReferencesDropped": true }),
+ )
+}
+
+struct ProbeConfig {
+ fixture: PathBuf,
+ fixture_name: String,
+ manifest_path: PathBuf,
+ work_root: PathBuf,
+ output: PathBuf,
+ source_manifest: PathBuf,
+ source_manifest_sha256: String,
+ binary_sha256: String,
+ current_writer_snapshot: bool,
+ legacy_control: Option<(PathBuf, String)>,
+}
+
+impl ProbeConfig {
+ fn environment() -> Result<Self> {
+ let required = |name| {
+ std::env::var(name).with_context(|| format!("Explicit manual probe requires {name}"))
+ };
+ let config = Self {
+ fixture: PathBuf::from(required("CAP_PREPARING_FIXTURE")?),
+ fixture_name: required("CAP_PREPARING_FIXTURE_NAME")?,
+ manifest_path: PathBuf::from(required("CAP_PREPARING_FIXTURE_MANIFEST")?),
+ work_root: PathBuf::from(required("CAP_PREPARING_WORK_ROOT")?),
+ output: PathBuf::from(required("CAP_PREPARING_EVIDENCE_OUTPUT")?),
+ source_manifest: PathBuf::from(required("CAP_PREPARING_SOURCE_MANIFEST")?),
+ source_manifest_sha256: required("CAP_PREPARING_SOURCE_MANIFEST_SHA256")?,
+ binary_sha256: required("CAP_PREPARING_BINARY_SHA256")?,
+ current_writer_snapshot: std::env::var("CAP_PREPARING_CURRENT_WRITER_SNAPSHOT")
+ .as_deref()
+ == Ok("1"),
+ legacy_control: match (
+ std::env::var("CAP_PREPARING_LEGACY_CONTROL"),
+ std::env::var("CAP_PREPARING_LEGACY_CONTROL_SHA256"),
+ ) {
+ (Ok(path), Ok(hash)) => Some((PathBuf::from(path), hash)),
+ (Err(std::env::VarError::NotPresent), Err(std::env::VarError::NotPresent)) => None,
+ _ => bail!("Legacy control path and SHA256 must be supplied together"),
+ },
+ };
+ ensure!(
+ !config.current_writer_snapshot || config.fixture_name == "replay-2h.cap",
+ "Current-writer variant is restricted to replay-2h.cap"
+ );
+ ensure!(
+ !config.current_writer_snapshot || config.legacy_control.is_some(),
+ "Current-writer variant requires the separate hash-verified legacy control"
+ );
+ ensure!(
+ config.fixture.is_absolute()
+ && config.work_root.is_absolute()
+ && config.output.is_absolute()
+ && config.manifest_path.is_absolute()
+ && config.source_manifest.is_absolute(),
+ "Probe paths must be absolute"
+ );
+ let canonical = config.fixture.canonicalize()?;
+ ensure!(
+ !config.work_root.canonicalize()?.starts_with(&canonical),
+ "Work root must be outside the canonical fixture"
+ );
+ ensure!(
+ !config
+ .output
+ .parent()
+ .context("Missing evidence parent")?
+ .canonicalize()?
+ .starts_with(&canonical),
+ "Evidence output must be outside the canonical fixture"
+ );
+ Ok(config)
+ }
+}
+
+async fn run_probe(config: &ProbeConfig, evidence: &mut Value) -> Result<()> {
+ let times: &[f32] = match config.fixture_name.as_str() {
+ "native-screen-15.cap" => &[0.0, 7.0, 13.5, 1.0],
+ "native-mic-60.cap" => &[0.0, 30.0, 58.0, 1.0],
+ "replay-2h.cap" => {
+ ensure!(
+ std::env::var("CAP_PREPARING_ALLOW_TWO_HOURS").as_deref() == Ok("1"),
+ "Two-hour copies require explicit CAP_PREPARING_ALLOW_TWO_HOURS=1"
+ );
+ &[0.0, 3600.0, 7194.5, 1.0]
+ }
+ _ => bail!("Unknown canonical fixture name"),
+ };
+ ensure!(
+ config.fixture.is_absolute()
+ && config.work_root.is_absolute()
+ && config.output.is_absolute(),
+ "Probe paths must be absolute"
+ );
+ let executable = std::env::current_exe()?;
+ ensure!(
+ hash_file(&executable)?.sha256 == config.binary_sha256,
+ "Running binary differs from external manifest"
+ );
+ ensure!(
+ hash_file(&config.source_manifest)?.sha256 == config.source_manifest_sha256,
+ "Source manifest differs from external hash"
+ );
+ evidence["identity"] = json!({ "binary": executable, "binarySha256": config.binary_sha256, "sourceManifest": config.source_manifest, "sourceManifestSha256": config.source_manifest_sha256, "sourceManifestValue": serde_json::from_slice::<Value>(&fs::read(&config.source_manifest)?)? });
+ ffmpeg::init()?;
+ let fixture_manifest: Value = serde_json::from_slice(&fs::read(&config.manifest_path)?)?;
+ let expected: FileManifest = serde_json::from_value(
+ fixture_manifest["fixtures"][&config.fixture_name]["files"].clone(),
+ )?;
+ let original = manifest(&config.fixture, false)?;
+ ensure!(
+ original == expected,
+ "Canonical inputs differ from shared fixture manifest"
+ );
+ evidence["canonicalBefore"] = serde_json::to_value(&original)?;
+ if config.current_writer_snapshot {
+ let metadata = RecordingMeta::load_for_project(&config.fixture)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let configuration: ProjectConfiguration =
+ serde_json::from_slice(&fs::read(config.fixture.join("project-config.json"))?)?;
+ let declined = CleanStoppedStudio::for_test(metadata, configuration).is_none();
+ evidence["originalLegacyReceiptDeclined"] = json!(declined);
+ ensure!(
+ declined,
+ "Expected the immutable legacy fixture receipt to decline"
+ );
+ let (path, sha256) = config
+ .legacy_control
+ .as_ref()
+ .context("Missing legacy control")?;
+ ensure!(
+ path.is_absolute() && hash_file(path)?.sha256 == *sha256,
+ "Legacy control evidence identity mismatch"
+ );
+ let control: Value = serde_json::from_slice(&fs::read(path)?)?;
+ ensure!(
+ control["fixture"] == "replay-2h.cap"
+ && control["passed"] == false
+ && control["error"] == "Canonical stopped snapshot declined",
+ "Legacy control must record the original receipt decline after ordinary finalization"
+ );
+ ensure!(
+ control["canonicalBefore"] == serde_json::to_value(&original)?
+ && control["canonicalFinalAuditUnchanged"] == true
+ && control["canonicalFinalAudit"] == serde_json::to_value(&original)?,
+ "Legacy control used different or changed canonical input bytes"
+ );
+ ensure!(
+ control["ordinaryFinalizationMs"].is_number()
+ && control["ordinaryOutput"].is_object()
+ && control["ordinaryFinalizedSoftwareVideoReference"].is_object(),
+ "Legacy control lacks ordinary output/reference evidence"
+ );
+ let source_identity = validate_legacy_source_identity(
+ &control,
+ &evidence["identity"]["sourceManifestValue"],
+ )?;
+ evidence["fixtureManifestIdentity"] = json!({ "path": config.manifest_path, "sha256": hash_file(&config.manifest_path)?.sha256, "legacyCanonicalFilesMatchCurrentSharedManifest": true });
+ evidence["legacySourceIdentity"] = source_identity;
+ evidence["legacyOrdinaryControl"] = json!({ "path": path, "sha256": sha256, "identity": control["identity"], "ordinaryFinalizationMs": control["ordinaryFinalizationMs"], "ordinaryOutput": control["ordinaryOutput"], "ordinaryFinalizedSoftwareVideoReference": control["ordinaryFinalizedSoftwareVideoReference"], "canonicalFinalAuditUnchanged": true, "originalReceiptDeclined": true, "reusedAsCurrentWriterComparison": false });
+ evidence["snapshotVariant"] = json!("current-writer-empty-cursor-snapshot");
+ }
+ let owned = tempfile::Builder::new()
+ .prefix("cap-preparing-canonical-")
+ .tempdir_in(&config.work_root)?
+ .keep();
+ evidence["ownedRunDirectory"] = json!(owned);
+ let ordinary = owned.join("ordinary.cap");
+ copy_fixture(&config.fixture, &ordinary, &original)?;
+ if config.current_writer_snapshot {
+ evidence["ordinaryCurrentWriterSnapshot"] = current_writer_snapshot(&ordinary, &original)?;
+ evidence["ordinaryCurrentWriterPreflight"] = preflight_current_writer(&ordinary)?;
+ }
+ let stopped_metadata = RecordingMeta::load_for_project(&ordinary)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let baseline_started = Instant::now();
+ let baseline_path = ordinary.clone();
+ let baseline = tokio::task::spawn_blocking(move || {
+ RecoveryManager::remux_if_needed(&baseline_path).map_err(|error| error.to_string())
+ })
+ .await?
+ .map_err(anyhow::Error::msg)?;
+ let baseline_ms = baseline_started.elapsed().as_secs_f64() * 1000.0;
+ ensure!(baseline, "Ordinary canonical finalizer did not run");
+ let baseline_output = public_output(&ordinary)?;
+ evidence["ordinaryFinalizationMs"] = json!(baseline_ms);
+ evidence["ordinaryOutput"] = baseline_output.clone();
+ evidence["ordinaryRetainedSources"] = retained_segments(&ordinary, &original)?;
+ let reference = finalized_video_reference(&ordinary, &stopped_metadata, times).await?;
+ evidence["ordinaryFinalizedSoftwareVideoReference"] = reference.clone();
+ fs::remove_dir_all(&ordinary)?;
+ evidence["ordinaryOwnedCopyRemovedAfterVerification"] = json!(true);
+ let preparing = owned.join("preparing.cap");
+ copy_fixture(&config.fixture, &preparing, &original)?;
+ if config.current_writer_snapshot {
+ let snapshot = current_writer_snapshot(&preparing, &original)?;
+ ensure!(
+ snapshot == evidence["ordinaryCurrentWriterSnapshot"],
+ "Owned baseline/preparing writer snapshots differ"
+ );
+ evidence["preparingCurrentWriterSnapshot"] = snapshot;
+ evidence["preparingCurrentWriterPreflight"] = preflight_current_writer(&preparing)?;
+ }
+ let metadata = RecordingMeta::load_for_project(&preparing)
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ let configuration: ProjectConfiguration =
+ serde_json::from_slice(&fs::read(preparing.join("project-config.json"))?)?;
+ let studio = metadata
+ .studio_meta()
+ .context("Expected Studio fixture")?
+ .clone();
+ let receipt = CleanStoppedStudio::for_test(metadata, configuration)
+ .context("Canonical stopped snapshot declined")?;
+ let completed = CompletedRecording {
+ project_path: preparing.clone(),
+ meta: studio,
+ cursor_data: Default::default(),
+ clean_stopped: Some(receipt),
+ };
+ let (job, observer) =
+ PreparingStudioJob::claim(&completed, 1).context("Fresh receipt claim failed")?;
+ ensure!(
+ PreparingStudioJob::claim(&completed, 2).is_none(),
+ "Receipt reused across generations"
+ );
+ let started = Instant::now();
+ let finalizer = OwnedThread(Some(
+ std::thread::Builder::new()
+ .name("canonical-retained-finalizer".into())
+ .spawn(move || {
+ let result = RecoveryManager::remux_stopped_with_preparing(&completed, job)
+ .map_err(|error| error.to_string());
+ (result, started.elapsed().as_secs_f64() * 1000.0)
+ })?,
+ ));
+ let preview = observe_preparing(
+ observer.clone(),
+ &config.fixture,
+ times,
+ &reference,
+ started,
+ )
+ .await;
+ let (finalized, finalization_ms) =
+ tokio::task::spawn_blocking(move || finalizer.join()).await??;
+ evidence["preparingFinalizationMs"] = json!(finalization_ms);
+ evidence["finalizerThreadJoinedMs"] = json!(started.elapsed().as_secs_f64() * 1000.0);
+ match preview {
+ Ok(preview) => evidence["preparing"] = preview,
+ Err(error) => evidence["preparingError"] = json!(format!("{error:#}")),
+ }
+ ensure!(
+ matches!(observer.latest(), PreparingStudioState::Ended),
+ "Finalizer did not revoke observer"
+ );
+ ensure!(
+ finalized.map_err(anyhow::Error::msg)?,
+ "Preparing finalizer did not run"
+ );
+ let candidate_output = public_output(&preparing)?;
+ evidence["preparingOutput"] = candidate_output.clone();
+ evidence["preparingRetainedSources"] = retained_segments(&preparing, &original)?;
+ compare_outputs(&baseline_output, &candidate_output)?;
+ evidence["publishedMediaAndNormalizedDocumentsMatch"] = json!(true);
+ let lock = super::RecoveryLock::acquire(&preparing)?;
+ drop(lock);
+ evidence["ordinaryRecoveryLockAvailableAfterWorkerTeardown"] = json!(true);
+ let after = manifest(&config.fixture, false)?;
+ evidence["canonicalAfter"] = serde_json::to_value(&after)?;
+ ensure!(after == original, "Canonical original files changed");
+ ensure!(
+ evidence.get("preparingError").is_none(),
+ "Preparing worker error; finalization/source evidence retained"
+ );
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+#[ignore = "manual canonical .cap integration probe; requires explicit fixture/work/evidence/source identity environment"]
+async fn canonical_preparing_finalization_probe() {
+ let config = ProbeConfig::environment().expect("Missing manual probe environment");
+ assert!(
+ !config.output.exists(),
+ "Evidence output must be a new file"
+ );
+ let mut evidence = json!({ "fixture": config.fixture_name, "method": "Functional integration run, ordinary-first then preparing. Copy/hash/receipt setup excluded from finalization timers. Order/cache/CPU competition are uncontrolled; times are not speedup, Stop/editor, audible playback, cold-cache or p95 evidence. Audio comparison is contiguous from sample zero until EOF or Ended cancellation, reported explicitly. Video hashes cover visible software-decoded planes. Source/binary identity is supplied and hash-checked before running. Only per-run owned baseline copies are deleted; candidate outputs and originals are retained." });
+ let mut result = run_probe(&config, &mut evidence).await;
+ match manifest(&config.fixture, false) {
+ Ok(after) => {
+ let value = serde_json::to_value(after).expect("Serialize canonical audit");
+ if let Some(before) = evidence.get("canonicalBefore") {
+ let unchanged = *before == value;
+ evidence["canonicalFinalAuditUnchanged"] = json!(unchanged);
+ if !unchanged && result.is_ok() {
+ result = Err(anyhow::anyhow!(
+ "Canonical originals changed at final audit"
+ ));
+ }
+ }
+ evidence["canonicalFinalAudit"] = value;
+ }
+ Err(error) => {
+ evidence["canonicalFinalAuditError"] = json!(format!("{error:#}"));
+ if result.is_ok() {
+ result = Err(error);
+ }
+ }
+ }
+ evidence["passed"] = json!(result.is_ok());
+ if let Err(error) = &result {
+ evidence["error"] = json!(format!("{error:#}"));
+ }
+ let output = fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&config.output)
+ .expect("Create new evidence output");
+ serde_json::to_writer_pretty(output, &evidence).expect("Write canonical probe evidence");
+ assert!(result.is_ok(), "Canonical probe failed: {result:?}");
+}
+
+#[cfg(test)]
+mod current_writer_snapshot_tests {
+ use super::*;
+
+ fn legacy_metadata() -> Value {
+ json!({ "platform": "MacOS", "pretty_name": "Writer snapshot test", "sharing": null, "segments": [{ "display": { "path": "content/segments/segment-0/display", "fps": 30, "start_time": 0.0 } }], "cursors": {}, "status": { "status": "NeedsRemux" } })
+ }
+
+ fn fixture(metadata: Value, configuration: Value) -> tempfile::TempDir {
+ let directory = tempfile::tempdir().unwrap();
+ fs::write(
+ directory.path().join("recording-meta.json"),
+ serde_json::to_vec(&metadata).unwrap(),
+ )
+ .unwrap();
+ fs::write(
+ directory.path().join("project-config.json"),
+ serde_json::to_vec(&configuration).unwrap(),
+ )
+ .unwrap();
+ fs::create_dir(directory.path().join("content")).unwrap();
+ fs::write(
+ directory.path().join("content/media-sentinel"),
+ b"immutable sample bytes",
+ )
+ .unwrap();
+ directory
+ }
+
+ fn configuration() -> Value {
+ serde_json::from_slice(
+ &serde_json::to_vec_pretty(&ProjectConfiguration::default()).unwrap(),
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn empty_legacy_cursor_writer_roundtrip_preserves_semantics_and_media() {
+ let directory = fixture(legacy_metadata(), configuration());
+ let before = manifest(directory.path(), false).unwrap();
+ let report = current_writer_snapshot(directory.path(), &before).unwrap();
+ assert_eq!(report["allMediaAndSidecarBytesUnchanged"], true);
+ assert_eq!(
+ report["documents"]["recording-meta.json"]["changedFields"],
+ json!([{ "pointer": "/cursors", "beforePresent": true, "before": {}, "afterPresent": false, "after": null }])
+ );
+ assert_eq!(
+ report["documents"]["project-config.json"]["changedFields"],
+ json!([])
+ );
+ let metadata = RecordingMeta::load_for_project(directory.path()).unwrap();
+ let configuration: ProjectConfiguration = serde_json::from_slice(
+ &fs::read(directory.path().join("project-config.json")).unwrap(),
+ )
+ .unwrap();
+ assert!(CleanStoppedStudio::for_test(metadata, configuration).is_some());
+ }
+
+ #[test]
+ fn nonempty_legacy_cursor_map_is_rejected_without_writes() {
+ let mut metadata = legacy_metadata();
+ metadata["cursors"] = json!({ "cursor": "content/cursor.png" });
+ let directory = fixture(metadata, configuration());
+ let before = manifest(directory.path(), false).unwrap();
+ assert!(current_writer_snapshot(directory.path(), &before).is_err());
+ assert_eq!(manifest(directory.path(), false).unwrap(), before);
+ }
+
+ #[test]
+ fn unknown_metadata_fields_are_rejected_without_writes() {
+ let mut metadata = legacy_metadata();
+ metadata["unrecognizedField"] = json!(42);
+ let directory = fixture(metadata, configuration());
+ let before = manifest(directory.path(), false).unwrap();
+ assert!(current_writer_snapshot(directory.path(), &before).is_err());
+ assert_eq!(manifest(directory.path(), false).unwrap(), before);
+ }
+
+ #[test]
+ fn unknown_configuration_fields_are_rejected_without_writes() {
+ let mut configuration = configuration();
+ configuration["unrecognizedField"] = json!({ "future": true });
+ let directory = fixture(legacy_metadata(), configuration);
+ let before = manifest(directory.path(), false).unwrap();
+ assert!(current_writer_snapshot(directory.path(), &before).is_err());
+ assert_eq!(manifest(directory.path(), false).unwrap(), before);
+ }
+}
diff --git a/crates/recording/src/recovery/preparing_observer.rs b/crates/recording/src/recovery/preparing_observer.rs
new file mode 100644
index 000000000..c29fb223d
--- /dev/null
+++ b/crates/recording/src/recovery/preparing_observer.rs
@@ -0,0 +1,738 @@
+use super::preparing_projection::{
+ PreparingAudioInput, PreparingProjection, PreparingStudioSegment, PreparingVideoInput,
+};
+use crate::studio_recording::{CleanStoppedStudioClaim, CompletedRecording};
+use cap_enc_ffmpeg::RelocatableSource;
+use cap_project::{AudioMeta, ProjectConfiguration, RecordingMeta, VideoMeta};
+use std::{
+ path::{Path, PathBuf},
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+};
+use tokio::sync::watch;
+use uuid::Uuid;
+
+#[derive(Clone, Debug)]
+pub struct PreparingStudioIdentity {
+ shared: Arc<PreparingStudioIdentityState>,
+}
+
+#[derive(Debug)]
+struct PreparingStudioIdentityState {
+ project_path: PathBuf,
+ generation: u64,
+ job_id: Uuid,
+ alive: AtomicBool,
+ publication_succeeded: AtomicBool,
+}
+
+impl PreparingStudioIdentity {
+ pub fn project_path(&self) -> &Path {
+ &self.shared.project_path
+ }
+
+ pub fn generation(&self) -> u64 {
+ self.shared.generation
+ }
+
+ pub fn job_id(&self) -> Uuid {
+ self.shared.job_id
+ }
+
+ pub fn same_job(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.shared, &other.shared)
+ }
+
+ pub fn publication_succeeded(&self) -> bool {
+ self.shared.publication_succeeded.load(Ordering::Acquire)
+ }
+
+ fn is_alive(&self) -> bool {
+ self.shared.alive.load(Ordering::Acquire)
+ }
+}
+
+#[derive(Clone)]
+pub enum PreparingStudioState {
+ Waiting,
+ Available(Arc<PreparingStudioSources>),
+ Unavailable(String),
+ Ended,
+}
+
+#[derive(Clone)]
+pub struct PreparingStudioObserver {
+ identity: PreparingStudioIdentity,
+ receiver: watch::Receiver<PreparingStudioState>,
+}
+
+impl PreparingStudioObserver {
+ pub fn identity(&self) -> &PreparingStudioIdentity {
+ &self.identity
+ }
+
+ pub fn same_job(&self, other: &Self) -> bool {
+ self.identity.same_job(&other.identity)
+ }
+
+ pub fn publication_succeeded(&self) -> bool {
+ self.identity.publication_succeeded()
+ }
+
+ pub fn latest(&self) -> PreparingStudioState {
+ if self.identity.is_alive() {
+ self.receiver.borrow().clone()
+ } else {
+ PreparingStudioState::Ended
+ }
+ }
+
+ pub async fn changed(&mut self) -> PreparingStudioState {
+ if !self.identity.is_alive() || self.receiver.changed().await.is_err() {
+ return PreparingStudioState::Ended;
+ }
+ self.latest()
+ }
+}
+
+#[cfg(test)]
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(super) enum PreparingStudioTestTransition {
+ Available,
+ Unavailable(String),
+ Ended,
+}
+
+pub struct PreparingStudioJob {
+ identity: PreparingStudioIdentity,
+ claimed: Option<CleanStoppedStudioClaim>,
+ sender: watch::Sender<PreparingStudioState>,
+ #[cfg(test)]
+ test_transitions: Arc<std::sync::Mutex<Vec<PreparingStudioTestTransition>>>,
+}
+
+impl PreparingStudioJob {
+ pub fn claim(
+ completed: &CompletedRecording,
+ generation: u64,
+ ) -> Option<(Self, PreparingStudioObserver)> {
+ let claimed = completed
+ .clean_stopped
+ .as_ref()?
+ .claim(&completed.project_path)?;
+ let identity = PreparingStudioIdentity {
+ shared: Arc::new(PreparingStudioIdentityState {
+ project_path: claimed.metadata().project_path.clone(),
+ generation,
+ job_id: Uuid::new_v4(),
+ alive: AtomicBool::new(true),
+ publication_succeeded: AtomicBool::new(false),
+ }),
+ };
+ let (sender, receiver) = watch::channel(PreparingStudioState::Waiting);
+ let observer = PreparingStudioObserver {
+ identity: identity.clone(),
+ receiver,
+ };
+ Some((
+ Self {
+ identity,
+ claimed: Some(claimed),
+ sender,
+ #[cfg(test)]
+ test_transitions: Default::default(),
+ },
+ observer,
+ ))
+ }
+
+ pub fn identity(&self) -> &PreparingStudioIdentity {
+ &self.identity
+ }
+
+ pub fn observer(&self) -> PreparingStudioObserver {
+ PreparingStudioObserver {
+ identity: self.identity.clone(),
+ receiver: self.sender.subscribe(),
+ }
+ }
+
+ #[cfg(test)]
+ pub(super) fn test_transitions(
+ &self,
+ ) -> Arc<std::sync::Mutex<Vec<PreparingStudioTestTransition>>> {
+ self.test_transitions.clone()
+ }
+
+ #[cfg(test)]
+ fn record_test_transition(&self, transition: PreparingStudioTestTransition) {
+ self.test_transitions
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .push(transition);
+ }
+
+ pub(super) fn claimed(&self) -> Option<&CleanStoppedStudioClaim> {
+ self.claimed.as_ref()
+ }
+
+ pub(super) fn mark_publication_succeeded(&mut self) {
+ if self.identity.is_alive()
+ && matches!(*self.sender.borrow(), PreparingStudioState::Available(_))
+ {
+ self.identity
+ .shared
+ .publication_succeeded
+ .store(true, Ordering::Release);
+ }
+ }
+
+ pub(super) fn unavailable(&mut self, reason: String) {
+ if self.identity.is_alive()
+ && matches!(*self.sender.borrow(), PreparingStudioState::Waiting)
+ {
+ #[cfg(test)]
+ self.record_test_transition(PreparingStudioTestTransition::Unavailable(reason.clone()));
+ drop(
+ self.sender
+ .send_replace(PreparingStudioState::Unavailable(reason)),
+ );
+ }
+ }
+
+ pub(super) fn publish(
+ &mut self,
+ source: RelocatableSource,
+ projection: PreparingProjection,
+ ) -> bool {
+ if !self.identity.is_alive()
+ || !matches!(*self.sender.borrow(), PreparingStudioState::Waiting)
+ {
+ return false;
+ }
+ let Some(claimed) = self.claimed.take() else {
+ return false;
+ };
+ let sources = Arc::new(PreparingStudioSources {
+ identity: self.identity.clone(),
+ claimed,
+ projection,
+ source,
+ });
+ drop(
+ self.sender
+ .send_replace(PreparingStudioState::Available(sources)),
+ );
+ #[cfg(test)]
+ self.record_test_transition(PreparingStudioTestTransition::Available);
+ true
+ }
+}
+
+impl Drop for PreparingStudioJob {
+ fn drop(&mut self) {
+ self.identity.shared.alive.store(false, Ordering::Release);
+ drop(self.sender.send_replace(PreparingStudioState::Ended));
+ #[cfg(test)]
+ self.record_test_transition(PreparingStudioTestTransition::Ended);
+ }
+}
+
+pub struct PreparingStudioSources {
+ identity: PreparingStudioIdentity,
+ claimed: CleanStoppedStudioClaim,
+ projection: PreparingProjection,
+ source: RelocatableSource,
+}
+
+impl PreparingStudioSources {
+ pub fn identity(&self) -> &PreparingStudioIdentity {
+ &self.identity
+ }
+
+ pub fn live(&self) -> Option<LivePreparingStudioSources<'_>> {
+ self.identity
+ .is_alive()
+ .then_some(LivePreparingStudioSources { sources: self })
+ }
+}
+
+pub struct LivePreparingStudioSources<'a> {
+ sources: &'a PreparingStudioSources,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PreparingVideoTrack {
+ Display,
+ Camera,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PreparingAudioTrack {
+ Mic,
+ SystemAudio,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PreparingSidecarKind {
+ Cursor,
+ Keyboard,
+}
+
+impl<'a> LivePreparingStudioSources<'a> {
+ pub fn identity(&self) -> &PreparingStudioIdentity {
+ self.sources.identity()
+ }
+
+ pub fn metadata(&self) -> Option<&'a RecordingMeta> {
+ self.sources
+ .identity
+ .is_alive()
+ .then_some(self.sources.claimed.metadata())
+ }
+
+ pub fn configuration(&self) -> Option<&'a ProjectConfiguration> {
+ self.sources
+ .identity
+ .is_alive()
+ .then_some(self.sources.claimed.configuration())
+ }
+
+ pub fn configuration_bytes(&self) -> Option<&'a [u8]> {
+ self.sources
+ .identity
+ .is_alive()
+ .then_some(self.sources.projection.configuration_bytes.as_slice())
+ }
+
+ pub fn segments(&self) -> Option<&'a [PreparingStudioSegment]> {
+ self.sources
+ .identity
+ .is_alive()
+ .then_some(self.sources.projection.segments.as_slice())
+ }
+
+ pub fn video(&self, index: u32, track: PreparingVideoTrack) -> Option<PreparingVideoLease<'a>> {
+ let segment = self
+ .segments()?
+ .iter()
+ .find(|segment| segment.index() == index)?;
+ let descriptor = match track {
+ PreparingVideoTrack::Display => segment.display(),
+ PreparingVideoTrack::Camera => segment.camera()?,
+ };
+ self.sources
+ .identity
+ .is_alive()
+ .then(|| PreparingVideoLease {
+ identity: self.sources.identity.clone(),
+ source: self.sources.source.clone(),
+ descriptor,
+ })
+ }
+
+ pub fn audio(&self, index: u32, track: PreparingAudioTrack) -> Option<PreparingAudioLease<'a>> {
+ let segment = self
+ .segments()?
+ .iter()
+ .find(|segment| segment.index() == index)?;
+ let descriptor = match track {
+ PreparingAudioTrack::Mic => segment.mic()?,
+ PreparingAudioTrack::SystemAudio => segment.system_audio()?,
+ };
+ self.sources
+ .identity
+ .is_alive()
+ .then(|| PreparingAudioLease {
+ identity: self.sources.identity.clone(),
+ source: self.sources.source.clone(),
+ descriptor,
+ })
+ }
+
+ pub fn sidecar(
+ &self,
+ index: u32,
+ kind: PreparingSidecarKind,
+ ) -> Option<PreparingSidecarLease<'a>> {
+ let segment = self
+ .segments()?
+ .iter()
+ .find(|segment| segment.index() == index)?;
+ let path = match kind {
+ PreparingSidecarKind::Cursor => segment.cursor_path()?,
+ PreparingSidecarKind::Keyboard => segment.keyboard_path()?,
+ };
+ self.sources
+ .identity
+ .is_alive()
+ .then(|| PreparingSidecarLease {
+ identity: self.sources.identity.clone(),
+ source: self.sources.source.clone(),
+ path,
+ })
+ }
+}
+
+pub struct PreparingVideoLease<'a> {
+ identity: PreparingStudioIdentity,
+ source: RelocatableSource,
+ descriptor: &'a PreparingVideoInput,
+}
+
+impl PreparingVideoLease<'_> {
+ pub fn input(&self) -> Option<(&RelocatableSource, &[PathBuf])> {
+ self.identity
+ .is_alive()
+ .then_some((&self.source, self.descriptor.paths()))
+ }
+
+ pub fn metadata(&self) -> Option<&VideoMeta> {
+ self.identity
+ .is_alive()
+ .then_some(self.descriptor.metadata())
+ }
+}
+
+pub struct PreparingAudioLease<'a> {
+ identity: PreparingStudioIdentity,
+ source: RelocatableSource,
+ descriptor: &'a PreparingAudioInput,
+}
+
+impl PreparingAudioLease<'_> {
+ pub fn input(&self) -> Option<(&RelocatableSource, &Path)> {
+ self.identity
+ .is_alive()
+ .then_some((&self.source, self.descriptor.path()))
+ }
+
+ pub fn metadata(&self) -> Option<&AudioMeta> {
+ self.identity
+ .is_alive()
+ .then_some(self.descriptor.metadata())
+ }
+}
+
+pub struct PreparingSidecarLease<'a> {
+ identity: PreparingStudioIdentity,
+ source: RelocatableSource,
+ path: &'a Path,
+}
+
+impl PreparingSidecarLease<'_> {
+ pub fn input(&self) -> Option<(&RelocatableSource, &Path)> {
+ self.identity
+ .is_alive()
+ .then_some((&self.source, self.path))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::studio_recording::CleanStoppedStudio;
+ use cap_project::{
+ MultipleSegment, MultipleSegments, Platform, RecordingMetaInner, StudioRecordingMeta,
+ StudioRecordingStatus,
+ };
+ use std::io::Read;
+
+ struct Dropped(Arc<AtomicBool>);
+
+ impl Drop for Dropped {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::Release);
+ }
+ }
+
+ fn segment() -> MultipleSegment {
+ MultipleSegment {
+ display: VideoMeta {
+ path: "content/segments/media".into(),
+ fps: 30,
+ start_time: Some(0.25),
+ device_id: None,
+ },
+ camera: None,
+ mic: None,
+ system_audio: None,
+ cursor: None,
+ keyboard: None,
+ display_notch: None,
+ }
+ }
+
+ fn completed(path: &Path) -> CompletedRecording {
+ let metadata = RecordingMeta {
+ platform: Some(Platform::default()),
+ project_path: path.to_path_buf(),
+ pretty_name: "Preparing observer fixture".to_string(),
+ sharing: None,
+ inner: RecordingMetaInner::Studio(Box::new(StudioRecordingMeta::MultipleSegments {
+ inner: MultipleSegments {
+ segments: vec![segment()],
+ cursors: cap_project::Cursors::Correct(Default::default()),
+ status: Some(StudioRecordingStatus::NeedsRemux),
+ },
+ })),
+ upload: None,
+ };
+ let RecordingMetaInner::Studio(studio) = &metadata.inner else {
+ unreachable!();
+ };
+ CompletedRecording {
+ project_path: path.to_path_buf(),
+ meta: studio.as_ref().clone(),
+ cursor_data: Default::default(),
+ clean_stopped: CleanStoppedStudio::for_test(metadata, ProjectConfiguration::default()),
+ }
+ }
+
+ fn publication(root: &Path) -> (RelocatableSource, PreparingProjection, Arc<AtomicBool>) {
+ std::fs::create_dir_all(root.join("media")).unwrap();
+ std::fs::write(root.join("media/init.mp4"), b"init-contents").unwrap();
+ std::fs::write(root.join("media/one.m4s"), b"fragment-contents").unwrap();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let source = RelocatableSource::new_with_owner(
+ root.to_path_buf(),
+ Arc::new(Dropped(dropped.clone())),
+ )
+ .unwrap();
+ let projection = PreparingProjection::for_test(
+ segment(),
+ vec!["media/init.mp4".into(), "media/one.m4s".into()],
+ b"{\"fixture\":true}".to_vec(),
+ );
+ (source, projection, dropped)
+ }
+
+ fn available(observer: &PreparingStudioObserver) -> Arc<PreparingStudioSources> {
+ match observer.latest() {
+ PreparingStudioState::Available(sources) => sources,
+ _ => panic!("Expected preparing sources"),
+ }
+ }
+
+ #[test]
+ fn completion_receipt_claim_is_one_shot_and_wrong_path_does_not_consume_it() {
+ let completion = completed(Path::new("same.cap"));
+ let mut wrong_path = completion.clone();
+ wrong_path.project_path = PathBuf::from("different.cap");
+ assert!(PreparingStudioJob::claim(&wrong_path, 1).is_none());
+ let (job, observer) = PreparingStudioJob::claim(&completion, 1).unwrap();
+ assert!(PreparingStudioJob::claim(&completion.clone(), 2).is_none());
+ assert!(job.claimed().is_some());
+ assert_eq!(job.identity().project_path(), Path::new("same.cap"));
+ assert_eq!(observer.identity().generation(), 1);
+ assert!(observer.same_job(&observer.clone()));
+ let mut reconstructed = completion.clone();
+ reconstructed.clean_stopped = None;
+ assert!(PreparingStudioJob::claim(&reconstructed, 3).is_none());
+ }
+
+ #[test]
+ fn separate_jobs_with_same_project_and_generation_have_distinct_identity() {
+ let first = completed(Path::new("same.cap"));
+ let second = completed(Path::new("same.cap"));
+ let third = completed(Path::new("same.cap"));
+ let (first_job, first_observer) = PreparingStudioJob::claim(&first, 7).unwrap();
+ let (second_job, second_observer) = PreparingStudioJob::claim(&second, 7).unwrap();
+ let (third_job, third_observer) = PreparingStudioJob::claim(&third, 8).unwrap();
+ assert!(!first_observer.same_job(&second_observer));
+ assert!(!first_observer.same_job(&third_observer));
+ assert_ne!(
+ first_job.identity().job_id(),
+ second_job.identity().job_id()
+ );
+ assert_ne!(
+ first_job.identity().generation(),
+ third_job.identity().generation()
+ );
+ assert!(first_observer.identity().same_job(first_job.identity()));
+ }
+
+ #[tokio::test]
+ async fn late_observer_sees_retained_available_and_then_ended() {
+ let directory = tempfile::tempdir().unwrap();
+ let completion = completed(directory.path());
+ let (mut job, mut early) = PreparingStudioJob::claim(&completion, 9).unwrap();
+ assert!(matches!(early.latest(), PreparingStudioState::Waiting));
+ let (source, projection, _) = publication(&directory.path().join("segments"));
+ assert!(job.publish(source, projection));
+ assert!(job.claimed().is_none());
+ assert!(matches!(
+ early.changed().await,
+ PreparingStudioState::Available(_)
+ ));
+ let mut late = job.observer();
+ let early_sources = available(&early);
+ let late_sources = available(&late);
+ assert!(Arc::ptr_eq(&early_sources, &late_sources));
+ assert!(early.same_job(&late));
+ drop(job);
+ assert!(matches!(late.changed().await, PreparingStudioState::Ended));
+ assert!(matches!(early.latest(), PreparingStudioState::Ended));
+ assert!(!early.publication_succeeded());
+ assert!(early_sources.live().is_none());
+ }
+
+ #[test]
+ fn publication_retains_sources_without_any_observer_receivers() {
+ let directory = tempfile::tempdir().unwrap();
+ let completion = completed(directory.path());
+ let (mut job, observer) = PreparingStudioJob::claim(&completion, 10).unwrap();
+ drop(observer);
+ assert_eq!(job.sender.receiver_count(), 0);
+ let (source, projection, dropped) = publication(&directory.path().join("segments"));
+ assert!(job.publish(source, projection));
+ assert!(!dropped.load(Ordering::Acquire));
+ let late = job.observer();
+ let sources = available(&late);
+ assert!(sources.live().is_some());
+ let weak = Arc::downgrade(&sources);
+ drop(sources);
+ drop(job);
+ assert!(matches!(late.latest(), PreparingStudioState::Ended));
+ assert!(weak.upgrade().is_none());
+ assert!(dropped.load(Ordering::Acquire));
+ }
+
+ #[test]
+ fn unavailable_keeps_finalization_identity_alive_without_publishing_later() {
+ let directory = tempfile::tempdir().unwrap();
+ let completion = completed(directory.path());
+ let (mut job, observer) = PreparingStudioJob::claim(&completion, 11).unwrap();
+ job.unavailable("Unsupported input grouping".to_string());
+ assert!(job.identity.is_alive());
+ assert!(job.claimed().is_some());
+ assert!(
+ matches!(observer.latest(), PreparingStudioState::Unavailable(reason) if reason == "Unsupported input grouping")
+ );
+ let late = job.observer();
+ assert!(matches!(
+ late.latest(),
+ PreparingStudioState::Unavailable(_)
+ ));
+ let (source, projection, dropped) = publication(&directory.path().join("segments"));
+ assert!(!job.publish(source, projection));
+ assert!(dropped.load(Ordering::Acquire));
+ assert!(matches!(
+ observer.latest(),
+ PreparingStudioState::Unavailable(_)
+ ));
+ drop(job);
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ }
+
+ #[test]
+ fn revoked_views_and_leases_reject_new_access_but_existing_reader_keeps_owner() {
+ let directory = tempfile::tempdir().unwrap();
+ let completion = completed(directory.path());
+ let (mut job, observer) = PreparingStudioJob::claim(&completion, 12).unwrap();
+ let identity = Arc::downgrade(&job.identity.shared);
+ let (source, projection, dropped) = publication(&directory.path().join("segments"));
+ assert!(job.publish(source, projection));
+ let sources = available(&observer);
+ let source_weak = Arc::downgrade(&sources);
+ let mut reader = {
+ let live = sources.live().unwrap();
+ assert_eq!(live.metadata().unwrap().project_path, directory.path());
+ assert!(live.configuration().is_some());
+ assert_eq!(live.configuration_bytes().unwrap(), b"{\"fixture\":true}");
+ assert_eq!(live.segments().unwrap().len(), 1);
+ assert!(live.video(1, PreparingVideoTrack::Display).is_none());
+ assert!(live.video(0, PreparingVideoTrack::Camera).is_none());
+ assert!(live.audio(0, PreparingAudioTrack::Mic).is_none());
+ assert!(live.audio(0, PreparingAudioTrack::SystemAudio).is_none());
+ assert!(live.sidecar(0, PreparingSidecarKind::Cursor).is_none());
+ assert!(live.sidecar(0, PreparingSidecarKind::Keyboard).is_none());
+ let lease = live.video(0, PreparingVideoTrack::Display).unwrap();
+ assert_eq!(lease.metadata().unwrap().fps, 30);
+ let (source, paths) = lease.input().unwrap();
+ assert_eq!(
+ paths,
+ &[
+ PathBuf::from("media/init.mp4"),
+ PathBuf::from("media/one.m4s")
+ ]
+ );
+ let mut reader = source.reader(&paths[0]).unwrap();
+ let mut prefix = [0_u8; 4];
+ reader.read_exact(&mut prefix).unwrap();
+ assert_eq!(&prefix, b"init");
+ drop(job);
+ assert!(sources.live().is_none());
+ assert!(live.metadata().is_none());
+ assert!(live.configuration().is_none());
+ assert!(live.configuration_bytes().is_none());
+ assert!(live.segments().is_none());
+ assert!(live.video(0, PreparingVideoTrack::Display).is_none());
+ assert!(lease.input().is_none());
+ assert!(lease.metadata().is_none());
+ reader
+ };
+ drop(sources);
+ drop(observer);
+ assert!(source_weak.upgrade().is_none());
+ assert!(identity.upgrade().is_none());
+ assert!(!dropped.load(Ordering::Acquire));
+ let mut remaining = Vec::new();
+ reader.read_to_end(&mut remaining).unwrap();
+ assert_eq!(remaining, b"-contents");
+ drop(reader);
+ assert!(dropped.load(Ordering::Acquire));
+ }
+
+ #[test]
+ fn unwinding_job_revokes_and_drops_watch_owned_source_without_cycle() {
+ let directory = tempfile::tempdir().unwrap();
+ let completion = completed(directory.path());
+ let (mut job, observer) = PreparingStudioJob::claim(&completion, 13).unwrap();
+ let (source, projection, dropped) = publication(&directory.path().join("segments"));
+ assert!(job.publish(source, projection));
+ let sources = available(&observer);
+ let source_weak = Arc::downgrade(&sources);
+ drop(sources);
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
+ let _job = job;
+ panic!("Preparing finalizer unwind probe");
+ }));
+ assert!(result.is_err());
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ assert!(source_weak.upgrade().is_none());
+ assert!(dropped.load(Ordering::Acquire));
+ }
+
+ #[tokio::test]
+ async fn waiting_job_drop_wakes_changed_and_preserves_ended_for_clones() {
+ let completion = completed(Path::new("waiting.cap"));
+ let (job, mut observer) = PreparingStudioJob::claim(&completion, 14).unwrap();
+ let mut changed = Box::pin(observer.changed());
+ assert!(futures::poll!(&mut changed).is_pending());
+ drop(job);
+ assert!(matches!(changed.await, PreparingStudioState::Ended));
+ let mut late = observer.clone();
+ assert!(matches!(late.latest(), PreparingStudioState::Ended));
+ assert!(matches!(late.changed().await, PreparingStudioState::Ended));
+ }
+ #[test]
+ fn successful_publication_receipt_never_reopens_ended_admission() {
+ let directory = tempfile::tempdir().unwrap();
+ let completion = completed(directory.path());
+ let (mut job, observer) = PreparingStudioJob::claim(&completion, 55).unwrap();
+ job.mark_publication_succeeded();
+ assert!(!observer.publication_succeeded());
+ let (source, projection, _) = publication(&directory.path().join("segments"));
+ assert!(job.publish(source, projection));
+ let sources = available(&observer);
+ job.mark_publication_succeeded();
+ drop(job);
+ assert!(observer.publication_succeeded());
+ assert!(observer.identity().publication_succeeded());
+ assert!(matches!(observer.latest(), PreparingStudioState::Ended));
+ assert!(sources.live().is_none());
+ }
+}
diff --git a/crates/recording/src/recovery/preparing_projection.rs b/crates/recording/src/recovery/preparing_projection.rs
new file mode 100644
index 000000000..f1b087c32
--- /dev/null
+++ b/crates/recording/src/recovery/preparing_projection.rs
@@ -0,0 +1,1391 @@
+use std::{
+ collections::{HashMap, HashSet},
+ fs::{File, Metadata, OpenOptions},
+ io::Read,
+ path::{Component, Path, PathBuf},
+ sync::Arc,
+};
+
+use cap_project::{
+ AudioMeta, CursorMeta, Cursors, MultipleSegment, ProjectConfiguration, StudioRecordingMeta,
+ StudioRecordingStatus, VideoMeta,
+};
+
+use super::{IncompleteRecording, RecoveryManager, reject_recovery_link};
+use crate::studio_recording::CleanStoppedStudioClaim;
+
+const MAX_JSON_BYTES: u64 = 8 * 1024 * 1024;
+const MAX_MANIFEST_BYTES: u64 = 32 * 1024 * 1024;
+const MAX_INIT_BYTES: u64 = 4 * 1024 * 1024;
+const MAX_CURSOR_IMAGE_BYTES: u64 = 4 * 1024 * 1024;
+const MAX_CURSOR_IMAGES_BYTES: u64 = 64 * 1024 * 1024;
+const MAX_SOURCE_ENTRIES: usize = 262_144;
+const MAX_SOURCE_PATH_BYTES: usize = 64 * 1024 * 1024;
+
+pub(super) struct PreparingProjection {
+ pub(super) segments: Vec<PreparingStudioSegment>,
+ pub(super) configuration_bytes: Vec<u8>,
+}
+
+pub struct PreparingStudioSegment {
+ index: u32,
+ metadata: MultipleSegment,
+ display: PreparingVideoInput,
+ camera: Option<PreparingVideoInput>,
+ mic: Option<PreparingAudioInput>,
+ system_audio: Option<PreparingAudioInput>,
+ cursor_path: Option<PathBuf>,
+ keyboard_path: Option<PathBuf>,
+ cursor_images: Arc<[PreparingCursorImage]>,
+}
+
+impl PreparingStudioSegment {
+ pub fn index(&self) -> u32 {
+ self.index
+ }
+
+ pub fn metadata(&self) -> &MultipleSegment {
+ &self.metadata
+ }
+
+ pub fn display(&self) -> &PreparingVideoInput {
+ &self.display
+ }
+
+ pub fn camera(&self) -> Option<&PreparingVideoInput> {
+ self.camera.as_ref()
+ }
+
+ pub fn mic(&self) -> Option<&PreparingAudioInput> {
+ self.mic.as_ref()
+ }
+
+ pub fn system_audio(&self) -> Option<&PreparingAudioInput> {
+ self.system_audio.as_ref()
+ }
+
+ pub fn cursor_path(&self) -> Option<&Path> {
+ self.cursor_path.as_deref()
+ }
+
+ pub fn keyboard_path(&self) -> Option<&Path> {
+ self.keyboard_path.as_deref()
+ }
+
+ pub fn cursor_images(&self) -> &[PreparingCursorImage] {
+ &self.cursor_images
+ }
+}
+
+pub struct PreparingVideoInput {
+ metadata: VideoMeta,
+ paths: Vec<PathBuf>,
+}
+
+impl PreparingVideoInput {
+ pub fn metadata(&self) -> &VideoMeta {
+ &self.metadata
+ }
+
+ pub fn paths(&self) -> &[PathBuf] {
+ &self.paths
+ }
+}
+
+pub struct PreparingAudioInput {
+ metadata: AudioMeta,
+ path: PathBuf,
+}
+
+impl PreparingAudioInput {
+ pub fn metadata(&self) -> &AudioMeta {
+ &self.metadata
+ }
+
+ pub fn path(&self) -> &Path {
+ &self.path
+ }
+}
+
+pub struct PreparingCursorImage {
+ id: String,
+ metadata: CursorMeta,
+ bytes: Vec<u8>,
+}
+
+impl PreparingCursorImage {
+ pub fn id(&self) -> &str {
+ &self.id
+ }
+
+ pub fn metadata(&self) -> &CursorMeta {
+ &self.metadata
+ }
+
+ pub fn bytes(&self) -> &[u8] {
+ &self.bytes
+ }
+}
+
+pub(super) fn project(
+ recording: &IncompleteRecording,
+ claim: &CleanStoppedStudioClaim,
+) -> Result<PreparingProjection, String> {
+ if recording.project_path != claim.metadata().project_path
+ || recording.meta.project_path != recording.project_path
+ || persisted_json_value(&recording.meta)? != persisted_json_value(claim.metadata())?
+ {
+ return Err("Stopped recording identity or metadata changed".into());
+ }
+ let project = &recording.project_path;
+ checked_metadata(project, Path::new("content/segments"), true)?;
+ let metadata_bytes = read_bounded(project, Path::new("recording-meta.json"), MAX_JSON_BYTES)?;
+ let disk_metadata: serde_json::Value =
+ serde_json::from_slice(&metadata_bytes).map_err(|error| error.to_string())?;
+ if disk_metadata != persisted_json_value(claim.metadata())? {
+ return Err("Persisted stopped metadata changed".into());
+ }
+ let configuration_bytes =
+ read_bounded(project, Path::new("project-config.json"), MAX_JSON_BYTES)?;
+ let disk_configuration: serde_json::Value =
+ serde_json::from_slice(&configuration_bytes).map_err(|error| error.to_string())?;
+ if disk_configuration != persisted_json_value(claim.configuration())? {
+ return Err("Persisted stopped configuration changed".into());
+ }
+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = claim.metadata().studio_meta()
+ else {
+ return Err("Preparing requires indexed Studio metadata".into());
+ };
+ if !matches!(inner.status, Some(StudioRecordingStatus::NeedsRemux))
+ || inner.segments.is_empty()
+ || inner.segments.len() != recording.recoverable_segments.len()
+ {
+ return Err("Preparing requires every stopped segment".into());
+ }
+ validate_configuration(claim.configuration(), inner.segments.len())?;
+ validate_diagnostics(project)?;
+ let cursor_images = cursor_images(project, &inner.cursors)?;
+ let source_root = project.join("content/segments");
+ let mut inventory = Inventory::read(&source_root)?;
+ let mut segments = Vec::with_capacity(inner.segments.len());
+ for (index, (metadata, recovered)) in inner
+ .segments
+ .iter()
+ .zip(&recording.recoverable_segments)
+ .enumerate()
+ {
+ if usize::try_from(recovered.index).ok() != Some(index) {
+ return Err("Stopped and discovered segment indexes differ".into());
+ }
+ let segment_dir = PathBuf::from(format!("segment-{}", recovered.index));
+ inventory.directory(&segment_dir)?;
+ let display = video(
+ &source_root,
+ &mut inventory,
+ metadata.display.clone(),
+ &segment_dir.join("display"),
+ recovered.display_init_segment.as_deref(),
+ &recovered.display_fragments,
+ )?;
+ let camera = match (&metadata.camera, &recovered.camera_fragments) {
+ (Some(metadata), Some(fragments)) => Some(video(
+ &source_root,
+ &mut inventory,
+ metadata.clone(),
+ &segment_dir.join("camera"),
+ recovered.camera_init_segment.as_deref(),
+ fragments,
+ )?),
+ (None, None) if recovered.camera_init_segment.is_none() => None,
+ _ => return Err("Stopped camera track does not match discovered media".into()),
+ };
+ let mic = audio(
+ &source_root,
+ &mut inventory,
+ metadata.mic.as_ref(),
+ recovered.mic_fragments.as_deref(),
+ &segment_dir,
+ "audio-input",
+ )?;
+ let system_audio = audio(
+ &source_root,
+ &mut inventory,
+ metadata.system_audio.as_ref(),
+ recovered.system_audio_fragments.as_deref(),
+ &segment_dir,
+ "system_audio",
+ )?;
+ let cursor_path = sidecar(
+ &mut inventory,
+ metadata.cursor.as_ref(),
+ &segment_dir.join("cursor.json"),
+ )?;
+ if recovered.cursor_path.as_deref()
+ != cursor_path
+ .as_ref()
+ .map(|path| source_root.join(path))
+ .as_deref()
+ {
+ return Err("Stopped cursor sidecar does not match discovery".into());
+ }
+ let keyboard_path = keyboard(&mut inventory, metadata, &segment_dir)?;
+ if let Some(notch) = metadata.display_notch
+ && (!notch.x.is_finite() || !notch.width.is_finite() || !notch.height.is_finite())
+ {
+ return Err("Invalid stopped notch metadata".into());
+ }
+ segments.push(PreparingStudioSegment {
+ index: recovered.index,
+ metadata: metadata.clone(),
+ display,
+ camera,
+ mic,
+ system_audio,
+ cursor_path,
+ keyboard_path,
+ cursor_images: cursor_images.clone(),
+ });
+ }
+ inventory.finish()?;
+ Ok(PreparingProjection {
+ segments,
+ configuration_bytes,
+ })
+}
+
+fn persisted_json_value(value: &impl serde::Serialize) -> Result<serde_json::Value, String> {
+ // Value serialization widens f32; compare the same decimal representation the file writer uses.
+ let bytes = serde_json::to_vec(value).map_err(|error| error.to_string())?;
+ serde_json::from_slice(&bytes).map_err(|error| error.to_string())
+}
+
+fn validate_configuration(
+ config: &ProjectConfiguration,
+ segment_count: usize,
+) -> Result<(), String> {
+ config.validate().map_err(|error| error.to_string())?;
+ let timeline = config.timeline.as_ref().ok_or("Missing stopped timeline")?;
+ if timeline.segments.len() != segment_count {
+ return Err("Stopped timeline does not map every segment".into());
+ }
+ for (index, segment) in timeline.segments.iter().enumerate() {
+ if usize::try_from(segment.recording_clip).ok() != Some(index)
+ || segment.start != 0.0
+ || !segment.end.is_finite()
+ || segment.end <= 0.0
+ || segment.timescale != 1.0
+ || segment.name.is_some()
+ || segment.speed_audio_mode.is_some()
+ {
+ return Err("Preparing requires the unchanged stopped timeline".into());
+ }
+ }
+ let timeline_json = persisted_json_value(timeline)?;
+ if timeline_json.as_object().is_none_or(|fields| {
+ fields.iter().any(|(key, value)| {
+ key != "segments" && value.as_array().is_none_or(|values| !values.is_empty())
+ })
+ }) {
+ return Err("Timeline overlays require ordinary loading".into());
+ }
+ let expected = ProjectConfiguration {
+ timeline: config.timeline.clone(),
+ clips: config.clips.clone(),
+ ..ProjectConfiguration::default()
+ };
+ if persisted_json_value(config)? != persisted_json_value(&expected)? {
+ return Err("Edited or legacy configuration requires ordinary loading".into());
+ }
+ let mut indexes = HashSet::new();
+ for clip in &config.clips {
+ if clip.index as usize >= segment_count
+ || !indexes.insert(clip.index)
+ || !clip.offsets.camera.is_finite()
+ || !clip.offsets.mic.is_finite()
+ || !clip.offsets.system_audio.is_finite()
+ {
+ return Err("Invalid stopped clip offsets".into());
+ }
+ }
+ Ok(())
+}
+
+fn validate_diagnostics(project: &Path) -> Result<(), String> {
+ let path = Path::new("recording-diagnostics.json");
+ match project.join(path).symlink_metadata() {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(error.to_string()),
+ Ok(_) => {}
+ }
+ let diagnostics: serde_json::Value =
+ serde_json::from_slice(&read_bounded(project, path, MAX_JSON_BYTES)?)
+ .map_err(|error| error.to_string())?;
+ if diagnostics
+ .get("segments")
+ .and_then(serde_json::Value::as_array)
+ .is_none_or(|segments| {
+ segments.iter().any(|segment| {
+ segment
+ .get("trackFailures")
+ .and_then(serde_json::Value::as_array)
+ .is_none_or(|failures| !failures.is_empty())
+ })
+ })
+ {
+ return Err(
+ "Requested-track failures or incomplete diagnostics require ordinary finalization"
+ .into(),
+ );
+ }
+ Ok(())
+}
+
+fn local_relative(path: &Path) -> Result<(), String> {
+ if path.as_os_str().is_empty()
+ || !path
+ .components()
+ .all(|part| matches!(part, Component::Normal(_)))
+ || path.to_str().is_none_or(|value| {
+ value.contains(':')
+ || (cfg!(unix) && value.contains('\\'))
+ || value
+ .split(['/', '\\'])
+ .any(|part| matches!(part, "" | "." | ".."))
+ })
+ {
+ return Err("Preparing input path is not local and normalized".into());
+ }
+ Ok(())
+}
+
+fn source_relative(path: &relative_path::RelativePath) -> Result<PathBuf, String> {
+ if path.as_str().contains('\\') {
+ return Err("Preparing metadata path contains a platform-specific separator".into());
+ }
+ let path = Path::new(path.as_str());
+ local_relative(path)?;
+ let relative = path
+ .strip_prefix("content/segments")
+ .map_err(|_| "Preparing media must remain within content/segments")?;
+ local_relative(relative)?;
+ Ok(relative.to_path_buf())
+}
+
+fn checked_metadata(root: &Path, relative: &Path, directory: bool) -> Result<Metadata, String> {
+ local_relative(relative)?;
+ let mut path = root.to_path_buf();
+ let root_metadata = path.symlink_metadata().map_err(|error| error.to_string())?;
+ reject_recovery_link(&root_metadata).map_err(|error| error.to_string())?;
+ if !root_metadata.is_dir() {
+ return Err("Preparing source root is not a directory".into());
+ }
+ let mut parts = relative.components().peekable();
+ while let Some(part) = parts.next() {
+ path.push(part.as_os_str());
+ let metadata = path.symlink_metadata().map_err(|error| error.to_string())?;
+ reject_recovery_link(&metadata).map_err(|error| error.to_string())?;
+ if parts.peek().is_none() {
+ if (directory && !metadata.is_dir()) || (!directory && !metadata.is_file()) {
+ return Err("Preparing input has an unexpected file type".into());
+ }
+ return Ok(metadata);
+ }
+ if !metadata.is_dir() {
+ return Err("Preparing input ancestor is not a directory".into());
+ }
+ }
+ Err("Preparing input path is empty".into())
+}
+
+fn read_bounded(root: &Path, relative: &Path, limit: u64) -> Result<Vec<u8>, String> {
+ let metadata = checked_metadata(root, relative, false)?;
+ if metadata.len() > limit {
+ return Err("Preparing input exceeds the read limit".into());
+ }
+ let mut options = OpenOptions::new();
+ options.read(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ options.custom_flags(0x0020_0000);
+ }
+ let file: File = options
+ .open(root.join(relative))
+ .map_err(|error| error.to_string())?;
+ let opened = file.metadata().map_err(|error| error.to_string())?;
+ reject_recovery_link(&opened).map_err(|error| error.to_string())?;
+ if !opened.is_file() || opened.len() != metadata.len() {
+ return Err("Preparing input changed before reading".into());
+ }
+ let mut bytes = Vec::new();
+ file.take(limit + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|error| error.to_string())?;
+ if bytes.len() as u64 != metadata.len() {
+ return Err("Preparing input changed while reading".into());
+ }
+ Ok(bytes)
+}
+
+struct Inventory {
+ files: HashMap<PathBuf, u64>,
+ directories: HashSet<PathBuf>,
+}
+
+impl Inventory {
+ fn read(root: &Path) -> Result<Self, String> {
+ let mut inventory = Self {
+ files: HashMap::new(),
+ directories: HashSet::new(),
+ };
+ let mut pending = vec![PathBuf::new()];
+ let mut entry_count = 0_usize;
+ let mut path_bytes = 0_usize;
+ while let Some(directory) = pending.pop() {
+ for entry in
+ std::fs::read_dir(root.join(&directory)).map_err(|error| error.to_string())?
+ {
+ let entry = entry.map_err(|error| error.to_string())?;
+ let relative = directory.join(entry.file_name());
+ local_relative(&relative)?;
+ entry_count += 1;
+ path_bytes = path_bytes
+ .checked_add(relative.as_os_str().len())
+ .ok_or("Path budget overflow")?;
+ if entry_count > MAX_SOURCE_ENTRIES
+ || path_bytes > MAX_SOURCE_PATH_BYTES
+ || relative.components().count() > 3
+ {
+ return Err("Preparing input exceeds the descriptor budget".into());
+ }
+ let metadata = entry
+ .path()
+ .symlink_metadata()
+ .map_err(|error| error.to_string())?;
+ reject_recovery_link(&metadata).map_err(|error| error.to_string())?;
+ if metadata.is_dir() {
+ inventory.directories.insert(relative.clone());
+ pending.push(relative);
+ } else if metadata.is_file() {
+ let _ = inventory.files.insert(relative, metadata.len());
+ } else {
+ return Err("Unsupported preparing source file type".into());
+ }
+ }
+ }
+ Ok(inventory)
+ }
+
+ fn directory(&mut self, path: &Path) -> Result<(), String> {
+ if !self.directories.remove(path) {
+ return Err("Missing or reused preparing track directory".into());
+ }
+ Ok(())
+ }
+
+ fn file(&mut self, path: &Path) -> Result<u64, String> {
+ self.files
+ .remove(path)
+ .ok_or_else(|| "Missing or reused preparing input".into())
+ }
+
+ fn finish(self) -> Result<(), String> {
+ if !self.files.is_empty() || !self.directories.is_empty() {
+ return Err(
+ "Unrepresented source files or respawn layouts require ordinary finalization"
+ .into(),
+ );
+ }
+ Ok(())
+ }
+}
+
+fn video(
+ root: &Path,
+ inventory: &mut Inventory,
+ metadata: VideoMeta,
+ directory: &Path,
+ init: Option<&Path>,
+ fragments: &[PathBuf],
+) -> Result<PreparingVideoInput, String> {
+ if metadata.fps == 0
+ || metadata.start_time.is_none_or(|time| !time.is_finite())
+ || source_relative(&metadata.path)? != directory
+ || fragments.is_empty()
+ || fragments.len() > MAX_SOURCE_ENTRIES
+ {
+ return Err("Unsupported stopped video metadata or layout".into());
+ }
+ inventory.directory(directory)?;
+ let expected_init = directory.join("init.mp4");
+ if init != Some(root.join(&expected_init).as_path()) {
+ return Err("Preparing video requires exactly one init segment".into());
+ }
+ inventory.file(&expected_init)?;
+ validate_init(&read_bounded(root, &expected_init, MAX_INIT_BYTES)?)?;
+ let mut paths = Vec::with_capacity(fragments.len() + 1);
+ paths.push(expected_init);
+ let mut previous: Option<u64> = None;
+ for fragment in fragments {
+ let relative = fragment
+ .strip_prefix(root)
+ .map_err(|_| "Discovered video is outside source root")?;
+ local_relative(relative)?;
+ let index =
+ RecoveryManager::m4s_fragment_index(fragment).ok_or("Unsupported M4S fragment name")?;
+ if relative.parent() != Some(directory)
+ || previous.is_some_and(|previous| previous.checked_add(1) != Some(index))
+ || (previous.is_none() && index > 1)
+ || !RecoveryManager::is_m4s_complete(fragment)
+ {
+ return Err(
+ "Video fragments are not complete and contiguous in discovered order".into(),
+ );
+ }
+ inventory.file(relative)?;
+ previous = Some(index);
+ paths.push(relative.to_path_buf());
+ }
+ validate_manifest(root, inventory, directory, &paths)?;
+ for name in ["dash_manifest.mpd", "master.m3u8", "media_0.m3u8"] {
+ let path = directory.join(name);
+ if inventory.files.contains_key(&path) {
+ inventory.file(&path)?;
+ }
+ }
+ Ok(PreparingVideoInput { metadata, paths })
+}
+
+fn validate_init(bytes: &[u8]) -> Result<(), String> {
+ let mut rest = bytes;
+ let mut ftyp = false;
+ let mut moov = false;
+ let mut boxes = 0;
+ while !rest.is_empty() {
+ boxes += 1;
+ if rest.len() < 8 || boxes > 256 {
+ return Err("Incomplete video initialization segment".into());
+ }
+ let size =
+ u32::from_be_bytes(rest[..4].try_into().map_err(|_| "Invalid init box")?) as usize;
+ if size < 8 || size > rest.len() {
+ return Err("Unsupported or incomplete video initialization box".into());
+ }
+ ftyp |= &rest[4..8] == b"ftyp";
+ moov |= &rest[4..8] == b"moov";
+ rest = &rest[size..];
+ }
+ if !ftyp || !moov {
+ return Err("Video initialization lacks ftyp or moov".into());
+ }
+ Ok(())
+}
+
+fn validate_manifest(
+ root: &Path,
+ inventory: &mut Inventory,
+ directory: &Path,
+ paths: &[PathBuf],
+) -> Result<(), String> {
+ let path = directory.join("manifest.json");
+ if !inventory.files.contains_key(&path) {
+ return Ok(());
+ }
+ inventory.file(&path)?;
+ let manifest: serde_json::Value =
+ serde_json::from_slice(&read_bounded(root, &path, MAX_MANIFEST_BYTES)?)
+ .map_err(|error| error.to_string())?;
+ if manifest.get("type").and_then(serde_json::Value::as_str) != Some("m4s_segments")
+ || manifest
+ .get("version")
+ .and_then(serde_json::Value::as_u64)
+ .is_none_or(|version| !(1..=5).contains(&version))
+ || manifest
+ .get("init_segment")
+ .and_then(serde_json::Value::as_str)
+ != Some("init.mp4")
+ {
+ return Err("Unsupported video manifest".into());
+ }
+ let entries = manifest
+ .get("segments")
+ .and_then(serde_json::Value::as_array)
+ .ok_or("Missing manifest segments")?;
+ if entries.len() + 1 != paths.len() {
+ return Err("Manifest does not describe every discovered video fragment".into());
+ }
+ for (entry, path) in entries.iter().zip(&paths[1..]) {
+ let name = entry
+ .get("path")
+ .and_then(serde_json::Value::as_str)
+ .ok_or("Missing manifest path")?;
+ local_relative(Path::new(name))?;
+ if directory.join(name) != *path
+ || entry
+ .get("is_complete")
+ .and_then(serde_json::Value::as_bool)
+ != Some(true)
+ || entry.get("index").and_then(serde_json::Value::as_u64)
+ != RecoveryManager::m4s_fragment_index(path)
+ || entry.get("file_size").and_then(serde_json::Value::as_u64)
+ != Some(checked_metadata(root, path, false)?.len())
+ {
+ return Err("Video manifest differs from complete discovered inputs".into());
+ }
+ }
+ Ok(())
+}
+
+fn audio(
+ root: &Path,
+ inventory: &mut Inventory,
+ metadata: Option<&AudioMeta>,
+ fragments: Option<&[PathBuf]>,
+ directory: &Path,
+ name: &str,
+) -> Result<Option<PreparingAudioInput>, String> {
+ let (metadata, fragments) = match (metadata, fragments) {
+ (None, None) => return Ok(None),
+ (Some(metadata), Some(fragments)) => (metadata, fragments),
+ _ => return Err("Stopped audio track does not match discovered media".into()),
+ };
+ let path = source_relative(&metadata.path)?;
+ if fragments.len() != 1
+ || fragments[0] != root.join(&path)
+ || path.parent() != Some(directory)
+ || path.file_stem().is_none_or(|stem| stem != name)
+ || path.extension().is_none_or(|extension| {
+ !["m4a", "ogg", "mp3"]
+ .iter()
+ .any(|allowed| extension == *allowed)
+ })
+ || metadata.start_time.is_none_or(|time| !time.is_finite())
+ || inventory.file(&path)? == 0
+ {
+ return Err("Preparing audio requires one complete discovered file".into());
+ }
+ Ok(Some(PreparingAudioInput {
+ metadata: metadata.clone(),
+ path,
+ }))
+}
+
+fn sidecar(
+ inventory: &mut Inventory,
+ declared: Option<&relative_path::RelativePathBuf>,
+ expected: &Path,
+) -> Result<Option<PathBuf>, String> {
+ let Some(declared) = declared else {
+ return Ok(None);
+ };
+ let path = source_relative(declared)?;
+ if path != expected {
+ return Err("Unsupported stopped sidecar path".into());
+ }
+ inventory.file(&path)?;
+ Ok(Some(path))
+}
+
+fn keyboard(
+ inventory: &mut Inventory,
+ metadata: &MultipleSegment,
+ directory: &Path,
+) -> Result<Option<PathBuf>, String> {
+ let binary = directory.join(cap_project::KEYBOARD_EVENTS_FILE_NAME);
+ let legacy = directory.join(cap_project::LEGACY_KEYBOARD_EVENTS_FILE_NAME);
+ let preferred = if inventory.files.contains_key(&binary) {
+ &binary
+ } else {
+ &legacy
+ };
+ if let Some(declared) = &metadata.keyboard {
+ return sidecar(inventory, Some(declared), preferred);
+ }
+ if inventory.files.contains_key(preferred) {
+ inventory.file(preferred)?;
+ return Ok(Some(preferred.clone()));
+ }
+ Ok(None)
+}
+
+fn cursor_images(project: &Path, cursors: &Cursors) -> Result<Arc<[PreparingCursorImage]>, String> {
+ let Cursors::Correct(cursors) = cursors else {
+ return Err("Legacy cursor assets require ordinary loading".into());
+ };
+ validate_cursor_inventory(project, cursors)?;
+ let mut remaining = MAX_CURSOR_IMAGES_BYTES;
+ let mut images = Vec::with_capacity(cursors.len());
+ let mut ordered: Vec<_> = cursors.iter().collect();
+ ordered.sort_by(|(left, _), (right, _)| left.cmp(right));
+ for (id, metadata) in ordered {
+ let path = Path::new(metadata.image_path.as_str());
+ local_relative(path)?;
+ if path.parent() != Some(Path::new("content/cursors"))
+ || path.extension().is_none_or(|extension| extension != "png")
+ || !metadata.hotspot.x.is_finite()
+ || !metadata.hotspot.y.is_finite()
+ {
+ return Err("Unsupported stopped cursor image".into());
+ }
+ let bytes = read_bounded(project, path, remaining.min(MAX_CURSOR_IMAGE_BYTES))?;
+ if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
+ return Err("Stopped cursor image is not PNG".into());
+ }
+ remaining = remaining
+ .checked_sub(bytes.len() as u64)
+ .ok_or("Cursor image budget exceeded")?;
+ images.push(PreparingCursorImage {
+ id: id.clone(),
+ metadata: metadata.clone(),
+ bytes,
+ });
+ }
+ Ok(images.into())
+}
+
+fn validate_cursor_inventory(
+ project: &Path,
+ cursors: &HashMap<String, CursorMeta>,
+) -> Result<(), String> {
+ let directory = Path::new("content/cursors");
+ match project.join(directory).symlink_metadata() {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound && cursors.is_empty() => {
+ return Ok(());
+ }
+ Err(error) => return Err(error.to_string()),
+ Ok(_) => {}
+ }
+ checked_metadata(project, directory, true)?;
+ let mut remaining: HashSet<_> = cursors
+ .values()
+ .map(|cursor| PathBuf::from(cursor.image_path.as_str()))
+ .collect();
+ for entry in std::fs::read_dir(project.join(directory)).map_err(|error| error.to_string())? {
+ let entry = entry.map_err(|error| error.to_string())?;
+ let path = directory.join(entry.file_name());
+ checked_metadata(project, &path, false)?;
+ if !remaining.remove(&path) {
+ return Err("Unrepresented cursor assets require ordinary finalization".into());
+ }
+ }
+ if !remaining.is_empty() {
+ return Err("Missing stopped cursor assets".into());
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+impl PreparingProjection {
+ pub(super) fn for_test(
+ metadata: MultipleSegment,
+ display_paths: Vec<PathBuf>,
+ configuration_bytes: Vec<u8>,
+ ) -> Self {
+ Self {
+ segments: vec![PreparingStudioSegment {
+ index: 0,
+ display: PreparingVideoInput {
+ metadata: metadata.display.clone(),
+ paths: display_paths,
+ },
+ metadata,
+ camera: None,
+ mic: None,
+ system_audio: None,
+ cursor_path: None,
+ keyboard_path: None,
+ cursor_images: Arc::from([]),
+ }],
+ configuration_bytes,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_project::{MultipleSegments, RecordingMeta, RecordingMetaInner};
+ use relative_path::RelativePathBuf;
+
+ struct Fixture {
+ directory: tempfile::TempDir,
+ recording: IncompleteRecording,
+ configuration: ProjectConfiguration,
+ }
+
+ impl Fixture {
+ fn new(count: u32) -> Self {
+ let directory = tempfile::tempdir().unwrap();
+ let mut segments = Vec::new();
+ let mut recovered = Vec::new();
+ for index in 0..count {
+ let base = format!("content/segments/segment-{index}");
+ let video = directory.path().join(&base).join("display");
+ let (init, fragments) = write_video(&video);
+ segments.push(MultipleSegment {
+ display: VideoMeta {
+ path: RelativePathBuf::from(format!("{base}/display")),
+ fps: 30,
+ start_time: Some(0.25 + f64::from(index)),
+ device_id: Some("display-device".into()),
+ },
+ camera: None,
+ mic: None,
+ system_audio: None,
+ cursor: None,
+ keyboard: None,
+ display_notch: None,
+ });
+ recovered.push(super::super::RecoverableSegment {
+ index,
+ display_fragments: fragments,
+ display_init_segment: Some(init),
+ camera_fragments: None,
+ camera_init_segment: None,
+ mic_fragments: None,
+ system_audio_fragments: None,
+ cursor_path: None,
+ });
+ }
+ let metadata = RecordingMeta {
+ platform: None,
+ project_path: directory.path().to_path_buf(),
+ pretty_name: "Preparing projection".into(),
+ sharing: None,
+ inner: RecordingMetaInner::Studio(Box::new(
+ StudioRecordingMeta::MultipleSegments {
+ inner: MultipleSegments {
+ segments,
+ cursors: Cursors::default(),
+ status: Some(StudioRecordingStatus::NeedsRemux),
+ },
+ },
+ )),
+ upload: None,
+ };
+ let configuration = ProjectConfiguration {
+ timeline: Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": (0..count).map(|index| serde_json::json!({
+ "recordingSegment": index, "timescale": 1.0, "start": 0.0,
+ "end": 7200.25 + f64::from(index), "name": null
+ })).collect::<Vec<_>>(),
+ "zoomSegments": []
+ }))
+ .unwrap(),
+ ),
+ ..ProjectConfiguration::default()
+ };
+ let fixture = Self {
+ recording: IncompleteRecording {
+ project_path: directory.path().to_path_buf(),
+ meta: metadata,
+ recoverable_segments: recovered,
+ estimated_duration: std::time::Duration::from_secs(1),
+ },
+ directory,
+ configuration,
+ };
+ fixture.persist();
+ fixture
+ }
+
+ fn metadata(&mut self) -> &mut MultipleSegments {
+ let RecordingMetaInner::Studio(studio) = &mut self.recording.meta.inner else {
+ unreachable!()
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ unreachable!()
+ };
+ inner
+ }
+
+ fn persist(&self) {
+ self.recording.meta.save_for_project().unwrap();
+ self.configuration.write(self.directory.path()).unwrap();
+ }
+
+ fn claim(&self) -> CleanStoppedStudioClaim {
+ CleanStoppedStudioClaim::for_test(
+ self.recording.meta.clone(),
+ self.configuration.clone(),
+ )
+ .unwrap()
+ }
+
+ fn project(&self) -> Result<PreparingProjection, String> {
+ project(&self.recording, &self.claim())
+ }
+
+ fn snapshot(&self) -> std::collections::BTreeMap<PathBuf, Vec<u8>> {
+ let mut paths = vec![self.directory.path().to_path_buf()];
+ let mut snapshot = std::collections::BTreeMap::new();
+ while let Some(path) = paths.pop() {
+ if path.is_dir() {
+ paths.extend(
+ std::fs::read_dir(path)
+ .unwrap()
+ .map(|entry| entry.unwrap().path()),
+ );
+ } else {
+ let _ = snapshot.insert(
+ path.strip_prefix(self.directory.path())
+ .unwrap()
+ .to_path_buf(),
+ std::fs::read(path).unwrap(),
+ );
+ }
+ }
+ snapshot
+ }
+
+ fn add_optional_tracks_and_sidecars(&mut self) {
+ let base = "content/segments/segment-0";
+ let segment = self.directory.path().join(base);
+ let (init, fragments) = write_video(&segment.join("camera"));
+ self.recording.recoverable_segments[0].camera_init_segment = Some(init);
+ self.recording.recoverable_segments[0].camera_fragments = Some(fragments);
+ for name in ["audio-input.m4a", "system_audio.ogg"] {
+ std::fs::write(segment.join(name), b"discovery-validated-audio").unwrap();
+ }
+ self.recording.recoverable_segments[0].mic_fragments =
+ Some(vec![segment.join("audio-input.m4a")]);
+ self.recording.recoverable_segments[0].system_audio_fragments =
+ Some(vec![segment.join("system_audio.ogg")]);
+ std::fs::write(segment.join("cursor.json"), b"{\"moves\":[],\"clicks\":[]}").unwrap();
+ std::fs::write(
+ segment.join(cap_project::KEYBOARD_EVENTS_FILE_NAME),
+ b"raw keyboard bytes",
+ )
+ .unwrap();
+ self.recording.recoverable_segments[0].cursor_path = Some(segment.join("cursor.json"));
+ let asset = self.directory.path().join("content/cursors/cursor_0.png");
+ std::fs::create_dir_all(asset.parent().unwrap()).unwrap();
+ std::fs::write(&asset, b"\x89PNG\r\n\x1a\nimmutable asset").unwrap();
+ let metadata = self.metadata();
+ metadata.segments[0].camera = Some(VideoMeta {
+ path: RelativePathBuf::from(format!("{base}/camera")),
+ fps: 24,
+ start_time: Some(0.5),
+ device_id: Some("camera-device".into()),
+ });
+ metadata.segments[0].mic = Some(AudioMeta {
+ path: RelativePathBuf::from(format!("{base}/audio-input.m4a")),
+ start_time: Some(-0.125),
+ device_id: Some("microphone-device".into()),
+ gap_summary: Some(cap_project::AudioGapSummary {
+ total_overlap_trimmed_ms: 21,
+ startup_overlap_trimmed_ms: 7,
+ overlap_dropped_frames: 2,
+ startup_overlap_drops: 1,
+ }),
+ });
+ metadata.segments[0].system_audio = Some(AudioMeta {
+ path: RelativePathBuf::from(format!("{base}/system_audio.ogg")),
+ start_time: Some(0.375),
+ device_id: None,
+ gap_summary: None,
+ });
+ metadata.segments[0].cursor =
+ Some(RelativePathBuf::from(format!("{base}/cursor.json")));
+ metadata.segments[0].display_notch = Some(cap_project::DisplayNotch {
+ x: 0.45,
+ width: 0.1,
+ height: 0.03,
+ });
+ metadata.cursors = Cursors::Correct(HashMap::from([(
+ "0".into(),
+ CursorMeta {
+ image_path: RelativePathBuf::from("content/cursors/cursor_0.png"),
+ hotspot: cap_project::XY { x: 0.25, y: 0.125 },
+ shape: None,
+ },
+ )]));
+ self.persist();
+ }
+ }
+
+ fn mp4_box(name: &[u8; 4], payload: usize) -> Vec<u8> {
+ let mut bytes = Vec::new();
+ bytes.extend_from_slice(&((payload + 8) as u32).to_be_bytes());
+ bytes.extend_from_slice(name);
+ bytes.resize(payload + 8, 0);
+ bytes
+ }
+
+ fn write_video(directory: &Path) -> (PathBuf, Vec<PathBuf>) {
+ std::fs::create_dir_all(directory).unwrap();
+ let init = directory.join("init.mp4");
+ std::fs::write(&init, [mp4_box(b"ftyp", 16), mp4_box(b"moov", 16)].concat()).unwrap();
+ let fragments: Vec<_> = (1..=2)
+ .map(|index| {
+ let path = directory.join(format!("segment_{index:03}.m4s"));
+ std::fs::write(
+ &path,
+ [mp4_box(b"moof", 16), mp4_box(b"mdat", 128)].concat(),
+ )
+ .unwrap();
+ path
+ })
+ .collect();
+ (init, fragments)
+ }
+
+ fn manifest(fixture: &Fixture) -> serde_json::Value {
+ serde_json::json!({"version":5,"type":"m4s_segments","init_segment":"init.mp4",
+ "segments": fixture.recording.recoverable_segments[0].display_fragments.iter().enumerate().map(|(index,path)| {
+ serde_json::json!({"index": index + 1, "path":path.file_name().unwrap().to_str().unwrap(),
+ "is_complete":true,"file_size":path.metadata().unwrap().len()})
+ }).collect::<Vec<_>>()})
+ }
+
+ #[test]
+ fn preparing_projection_preserves_all_tracks_offsets_duration_and_raw_sidecars_without_writes()
+ {
+ let mut fixture = Fixture::new(2);
+ fixture.add_optional_tracks_and_sidecars();
+ let before = fixture.snapshot();
+ let projection = fixture.project().unwrap();
+ assert_eq!(before, fixture.snapshot());
+ assert_eq!(projection.segments.len(), 2);
+ let first = &projection.segments[0];
+ assert_eq!(first.index(), 0);
+ assert_eq!(first.metadata().latest_start_time(), Some(0.5));
+ assert_eq!(
+ first.display().paths()[0],
+ Path::new("segment-0/display/init.mp4")
+ );
+ assert_eq!(
+ first.display().paths()[2],
+ Path::new("segment-0/display/segment_002.m4s")
+ );
+ assert_eq!(first.camera().unwrap().metadata().fps, 24);
+ assert_eq!(
+ first
+ .mic()
+ .unwrap()
+ .metadata()
+ .gap_summary
+ .unwrap()
+ .startup_overlap_trimmed_ms,
+ 7
+ );
+ assert_eq!(
+ first.system_audio().unwrap().metadata().start_time,
+ Some(0.375)
+ );
+ assert_eq!(
+ first.cursor_path(),
+ Some(Path::new("segment-0/cursor.json"))
+ );
+ assert_eq!(
+ first.keyboard_path(),
+ Some(
+ Path::new("segment-0")
+ .join(cap_project::KEYBOARD_EVENTS_FILE_NAME)
+ .as_path()
+ )
+ );
+ assert_eq!(first.cursor_images()[0].metadata().hotspot.x, 0.25);
+ assert_eq!(first.cursor_images()[0].id(), "0");
+ assert_eq!(
+ projection.configuration_bytes,
+ before[Path::new("project-config.json")]
+ );
+ assert!(Arc::ptr_eq(
+ &first.cursor_images,
+ &projection.segments[1].cursor_images
+ ));
+ std::fs::write(
+ fixture
+ .directory
+ .path()
+ .join("content/cursors/cursor_0.png"),
+ b"changed",
+ )
+ .unwrap();
+ assert_eq!(
+ first.cursor_images()[0].bytes(),
+ b"\x89PNG\r\n\x1a\nimmutable asset"
+ );
+ }
+
+ #[test]
+ fn preparing_projection_compares_writer_float_representation_and_rejects_unknown_fields() {
+ let fixture = Fixture::new(1);
+ let path = fixture.directory.path().join("project-config.json");
+ let mut persisted: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ let in_memory = serde_json::to_value(&fixture.configuration).unwrap();
+ let field = "/background/advancedShadow/blur";
+ assert_ne!(in_memory.pointer(field), persisted.pointer(field));
+ eprintln!(
+ "{}",
+ serde_json::json!({
+ "probe": "preparing-configuration-float-representation", "field": field,
+ "inMemory": in_memory.pointer(field), "persisted": persisted.pointer(field)
+ })
+ );
+ assert_eq!(
+ persisted_json_value(&fixture.configuration).unwrap(),
+ persisted
+ );
+ assert!(fixture.project().is_ok());
+ persisted["unrecognizedFutureMedia"] = serde_json::json!({"path":"foreign.wav"});
+ let changed = serde_json::to_vec_pretty(&persisted).unwrap();
+ std::fs::write(&path, &changed).unwrap();
+ assert!(fixture.project().is_err());
+ assert_eq!(std::fs::read(path).unwrap(), changed);
+ }
+
+ #[test]
+ fn preparing_projection_rejects_current_or_persisted_metadata_and_configuration_drift() {
+ for mutation in 0..5 {
+ let mut fixture = Fixture::new(1);
+ let claim = fixture.claim();
+ match mutation {
+ 0 => fixture.recording.meta.pretty_name.push_str(" changed"),
+ 1 => {
+ fixture.recording.meta.pretty_name.push_str(" changed");
+ fixture.persist();
+ }
+ 2 => {
+ fixture.configuration.timeline.as_mut().unwrap().segments[0].end += 1.0;
+ fixture.persist();
+ }
+ 3 => {
+ let path = fixture.directory.path().join("project-config.json");
+ let mut value: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ let _ = value.as_object_mut().unwrap().remove("textSizeVersion");
+ std::fs::write(path, serde_json::to_vec(&value).unwrap()).unwrap();
+ }
+ _ => fixture.recording.project_path = fixture.directory.path().join("other"),
+ }
+ let before = fixture.snapshot();
+ assert!(project(&fixture.recording, &claim).is_err());
+ assert_eq!(before, fixture.snapshot());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_requires_one_to_one_indexes_and_exact_discovered_order() {
+ for mutation in 0..5 {
+ let mut fixture = Fixture::new(2);
+ match mutation {
+ 0 => fixture.recording.recoverable_segments.swap(0, 1),
+ 1 => fixture.recording.recoverable_segments[1].index = 0,
+ 2 => {
+ let _ = fixture.recording.recoverable_segments.pop();
+ }
+ 3 => fixture.recording.recoverable_segments[0]
+ .display_fragments
+ .reverse(),
+ _ => {
+ let _ = fixture.recording.recoverable_segments[0]
+ .display_fragments
+ .remove(0);
+ }
+ }
+ assert!(fixture.project().is_err());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_manifest_completeness_order_and_size_are_authoritative() {
+ for mutation in 0..6 {
+ let fixture = Fixture::new(1);
+ assert!(fixture.project().is_ok());
+ let mut value = manifest(&fixture);
+ match mutation {
+ 0 => {}
+ 1 => value["segments"][0]["is_complete"] = false.into(),
+ 2 => value["segments"][0]["file_size"] = 1.into(),
+ 3 => value["segments"].as_array_mut().unwrap().reverse(),
+ 4 => value["segments"][0]["path"] = "../segment_001.m4s".into(),
+ _ => value["version"] = 6.into(),
+ }
+ std::fs::write(
+ fixture
+ .directory
+ .path()
+ .join("content/segments/segment-0/display/manifest.json"),
+ serde_json::to_vec(&value).unwrap(),
+ )
+ .unwrap();
+ let before = fixture.snapshot();
+ assert_eq!(fixture.project().is_ok(), mutation == 0);
+ assert_eq!(before, fixture.snapshot());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_does_not_rescue_pending_fragments_or_ignore_extra_tracks() {
+ for name in [
+ "display/segment_003.m4s.tmp",
+ "display/init_1.mp4",
+ "camera.mp4",
+ "audio-input.m4a",
+ "cursor.json",
+ "unknown/data",
+ ] {
+ let fixture = Fixture::new(1);
+ let path = fixture
+ .directory
+ .path()
+ .join("content/segments/segment-0")
+ .join(name);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, b"retained original").unwrap();
+ let before = fixture.snapshot();
+ assert!(fixture.project().is_err(), "{name}");
+ assert_eq!(before, fixture.snapshot());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_declines_missing_optional_tracks_and_grouped_audio() {
+ for mutation in 0..4 {
+ let mut fixture = Fixture::new(1);
+ fixture.add_optional_tracks_and_sidecars();
+ match mutation {
+ 0 => fixture.recording.recoverable_segments[0].camera_fragments = None,
+ 1 => fixture.recording.recoverable_segments[0].mic_fragments = None,
+ 2 => {
+ let files = fixture.recording.recoverable_segments[0]
+ .mic_fragments
+ .as_mut()
+ .unwrap();
+ files.push(files[0].clone());
+ }
+ _ => {
+ std::fs::remove_file(
+ fixture
+ .directory
+ .path()
+ .join("content/cursors/cursor_0.png"),
+ )
+ .unwrap();
+ }
+ }
+ let before = fixture.snapshot();
+ assert!(fixture.project().is_err());
+ assert_eq!(before, fixture.snapshot());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_rejects_truncated_media_and_oversized_metadata_without_writes() {
+ for mutation in 0..3 {
+ let fixture = Fixture::new(1);
+ let path = match mutation {
+ 0 => fixture.recording.recoverable_segments[0]
+ .display_init_segment
+ .clone()
+ .unwrap(),
+ 1 => fixture.recording.recoverable_segments[0].display_fragments[1].clone(),
+ _ => fixture.directory.path().join("recording-meta.json"),
+ };
+ let length = if mutation == 2 { MAX_JSON_BYTES + 1 } else { 5 };
+ OpenOptions::new()
+ .write(true)
+ .open(path)
+ .unwrap()
+ .set_len(length)
+ .unwrap();
+ let before = fixture.snapshot();
+ assert!(fixture.project().is_err());
+ assert_eq!(before, fixture.snapshot());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_rejects_foreign_paths_and_nonfinite_timing() {
+ for mutation in 0..5 {
+ let mut fixture = Fixture::new(1);
+ let display = &mut fixture.metadata().segments[0].display;
+ match mutation {
+ 0 => display.path = RelativePathBuf::from("../display"),
+ 1 => display.path = RelativePathBuf::from("content/segments/segment-0/../display"),
+ 2 => display.path = RelativePathBuf::from("content\\segments\\segment-0\\display"),
+ 3 => display.fps = 0,
+ _ => display.start_time = None,
+ }
+ fixture.persist();
+ assert!(fixture.project().is_err());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_accepts_complete_diagnostics_and_retains_failed_diagnostics() {
+ for failures in [
+ serde_json::json!([]),
+ serde_json::json!([{"track":"camera","error":"failed"}]),
+ serde_json::Value::Null,
+ ] {
+ let fixture = Fixture::new(1);
+ std::fs::write(
+ fixture.directory.path().join("recording-diagnostics.json"),
+ serde_json::to_vec(&serde_json::json!({"version":2,"segments":[{"segmentIndex":0,"trackFailures":failures}]})).unwrap(),
+ ).unwrap();
+ let before = fixture.snapshot();
+ assert_eq!(
+ fixture.project().is_ok(),
+ failures.as_array().is_some_and(Vec::is_empty)
+ );
+ assert_eq!(before, fixture.snapshot());
+ }
+ }
+
+ #[test]
+ fn preparing_projection_does_not_omit_undeclared_cursor_assets_or_second_keyboard_format() {
+ for extra_asset in [false, true] {
+ let mut fixture = Fixture::new(1);
+ fixture.add_optional_tracks_and_sidecars();
+ let extra = if extra_asset {
+ fixture
+ .directory
+ .path()
+ .join("content/cursors/cursor_extra.png")
+ } else {
+ fixture
+ .directory
+ .path()
+ .join("content/segments/segment-0")
+ .join(cap_project::LEGACY_KEYBOARD_EVENTS_FILE_NAME)
+ };
+ std::fs::write(&extra, b"original extra input").unwrap();
+ let before = fixture.snapshot();
+ assert!(fixture.project().is_err());
+ assert_eq!(before, fixture.snapshot());
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn preparing_projection_rejects_source_and_asset_symlinks() {
+ for asset in [false, true] {
+ let mut fixture = Fixture::new(1);
+ fixture.add_optional_tracks_and_sidecars();
+ let path = if asset {
+ fixture
+ .directory
+ .path()
+ .join("content/cursors/cursor_0.png")
+ } else {
+ fixture.recording.recoverable_segments[0].display_fragments[0].clone()
+ };
+ let outside = tempfile::NamedTempFile::new().unwrap();
+ std::fs::copy(&path, outside.path()).unwrap();
+ std::fs::remove_file(&path).unwrap();
+ std::os::unix::fs::symlink(outside.path(), &path).unwrap();
+ assert!(fixture.project().is_err());
+ assert!(path.symlink_metadata().unwrap().file_type().is_symlink());
+ }
+ }
+}
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index e44d10182..a8e881e16 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -1421,6 +1421,7 @@ impl Pipeline {
}
pub async fn stop(mut self) -> anyhow::Result<PipelineStopOutcome> {
+ let stop_started = Instant::now();
#[cfg(any(target_os = "linux", windows))]
self.stopping
.store(true, std::sync::atomic::Ordering::Release);
@@ -1446,6 +1447,11 @@ impl Pipeline {
OptionFuture::from(self.system_audio.map(|s| s.stop_with_outcome()))
);
+ tracing::info!(
+ elapsed_ms = stop_started.elapsed().as_secs_f64() * 1000.0,
+ "Studio capture pipelines stopped"
+ );
+
if let Some(cursor) = self.cursor.as_mut() {
cursor.actor.stop();
}
@@ -2296,11 +2302,171 @@ async fn spawn_studio_recording_actor(
})
}
+const MAX_PREPARING_SEGMENTS: usize = 1024;
+const MAX_PREPARING_CURSOR_IMAGES: usize = 4096;
+const MAX_PREPARING_METADATA_STRING_BYTES: usize = 1024 * 1024;
+
+struct BoundedStoppedStudioMeta(RecordingMeta);
+
+impl BoundedStoppedStudioMeta {
+ fn new(meta: RecordingMeta) -> Option<Self> {
+ let RecordingMetaInner::Studio(studio) = &meta.inner else {
+ return None;
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_ref() else {
+ return None;
+ };
+ if !matches!(inner.status, Some(StudioRecordingStatus::NeedsRemux))
+ || inner.segments.is_empty()
+ || inner.segments.len() > MAX_PREPARING_SEGMENTS
+ || inner.segments.capacity() > MAX_PREPARING_SEGMENTS * 2
+ || meta.sharing.is_some()
+ || meta.upload.is_some()
+ {
+ return None;
+ }
+ let cap_project::Cursors::Correct(cursors) = &inner.cursors else {
+ return None;
+ };
+ if cursors.len() > MAX_PREPARING_CURSOR_IMAGES
+ || cursors.capacity() > MAX_PREPARING_CURSOR_IMAGES * 2
+ {
+ return None;
+ }
+ let mut remaining = MAX_PREPARING_METADATA_STRING_BYTES;
+ let mut account = |bytes: usize| -> Option<()> {
+ remaining = remaining.checked_sub(bytes)?;
+ Some(())
+ };
+ account(meta.project_path.capacity())?;
+ account(meta.pretty_name.capacity())?;
+ for segment in &inner.segments {
+ account(segment.display.path.as_str().len())?;
+ account(
+ segment
+ .display
+ .device_id
+ .as_ref()
+ .map_or(0, String::capacity),
+ )?;
+ if let Some(camera) = &segment.camera {
+ account(camera.path.as_str().len())?;
+ account(camera.device_id.as_ref().map_or(0, String::capacity))?;
+ }
+ for audio in [&segment.mic, &segment.system_audio].into_iter().flatten() {
+ account(audio.path.as_str().len())?;
+ account(audio.device_id.as_ref().map_or(0, String::capacity))?;
+ }
+ for path in [&segment.cursor, &segment.keyboard].into_iter().flatten() {
+ account(path.as_str().len())?;
+ }
+ }
+ for (id, cursor) in cursors {
+ account(id.capacity())?;
+ account(cursor.image_path.as_str().len())?;
+ }
+ Some(Self(meta))
+ }
+}
+
+#[derive(Clone)]
+pub struct CleanStoppedStudio {
+ snapshot: Arc<CleanStoppedStudioSnapshot>,
+}
+
+struct CleanStoppedStudioSnapshot {
+ metadata: RecordingMeta,
+ configuration: cap_project::ProjectConfiguration,
+ claimed: std::sync::atomic::AtomicBool,
+}
+
+pub(crate) struct CleanStoppedStudioClaim {
+ snapshot: Arc<CleanStoppedStudioSnapshot>,
+}
+
+impl CleanStoppedStudio {
+ #[cfg(test)]
+ pub(crate) fn for_test(
+ metadata: RecordingMeta,
+ configuration: cap_project::ProjectConfiguration,
+ ) -> Option<Self> {
+ Self::new(BoundedStoppedStudioMeta::new(metadata)?, configuration)
+ }
+
+ fn new(
+ metadata: BoundedStoppedStudioMeta,
+ configuration: cap_project::ProjectConfiguration,
+ ) -> Option<Self> {
+ if configuration.clips.len() > MAX_PREPARING_SEGMENTS
+ || configuration.clips.capacity() > MAX_PREPARING_SEGMENTS * 2
+ {
+ return None;
+ }
+ if let Some(timeline) = &configuration.timeline {
+ if timeline.segments.len() > MAX_PREPARING_SEGMENTS
+ || timeline.segments.capacity() > MAX_PREPARING_SEGMENTS * 2
+ {
+ return None;
+ }
+ let mut remaining = MAX_PREPARING_METADATA_STRING_BYTES;
+ for segment in &timeline.segments {
+ remaining =
+ remaining.checked_sub(segment.name.as_ref().map_or(0, String::capacity))?;
+ }
+ }
+ Some(Self {
+ snapshot: Arc::new(CleanStoppedStudioSnapshot {
+ metadata: metadata.0,
+ configuration,
+ claimed: std::sync::atomic::AtomicBool::new(false),
+ }),
+ })
+ }
+
+ pub(crate) fn claim(&self, project_path: &Path) -> Option<CleanStoppedStudioClaim> {
+ if project_path != self.snapshot.metadata.project_path.as_path() {
+ return None;
+ }
+ self.snapshot
+ .claimed
+ .compare_exchange(
+ false,
+ true,
+ std::sync::atomic::Ordering::AcqRel,
+ std::sync::atomic::Ordering::Acquire,
+ )
+ .ok()?;
+ Some(CleanStoppedStudioClaim {
+ snapshot: self.snapshot.clone(),
+ })
+ }
+}
+
+impl CleanStoppedStudioClaim {
+ #[cfg(test)]
+ pub(crate) fn for_test(
+ metadata: RecordingMeta,
+ configuration: cap_project::ProjectConfiguration,
+ ) -> Option<Self> {
+ let receipt = CleanStoppedStudio::for_test(metadata, configuration)?;
+ receipt.claim(&receipt.snapshot.metadata.project_path)
+ }
+
+ pub(crate) fn metadata(&self) -> &RecordingMeta {
+ &self.snapshot.metadata
+ }
+
+ pub(crate) fn configuration(&self) -> &cap_project::ProjectConfiguration {
+ &self.snapshot.configuration
+ }
+}
+
#[derive(Clone)]
pub struct CompletedRecording {
pub project_path: PathBuf,
pub meta: StudioRecordingMeta,
pub cursor_data: cap_project::CursorImages,
+ pub clean_stopped: Option<CleanStoppedStudio>,
}
fn snap_nearby_start_time(
@@ -2604,7 +2770,13 @@ async fn stop_recording(
);
}
- persist_final_recording_meta(&recording_dir, &meta)?;
+ let persisted_meta = persist_final_recording_meta(&recording_dir, &meta)?;
+ let bounded_meta = if required_track_failure.is_none() {
+ BoundedStoppedStudioMeta::new(persisted_meta)
+ } else {
+ drop(persisted_meta);
+ None
+ };
let mut project_config = cap_project::ProjectConfiguration::default();
if !timeline_segments.is_empty() {
@@ -2634,10 +2806,13 @@ async fn stop_recording(
bail!(error);
}
+ let clean_stopped = bounded_meta.and_then(|meta| CleanStoppedStudio::new(meta, project_config));
+
Ok(CompletedRecording {
project_path: recording_dir,
meta,
cursor_data: Default::default(),
+ clean_stopped,
// display_source: actor.options.capture_target,
// segments: actor.segments,
})
@@ -3290,7 +3465,7 @@ fn persist_failed_recording(recording_dir: &Path, error: &str) -> anyhow::Result
fn persist_final_recording_meta(
recording_dir: &Path,
studio_meta: &StudioRecordingMeta,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<RecordingMeta> {
use chrono::Local;
let pretty_name = Local::now().format("Cap %Y-%m-%d at %H.%M.%S").to_string();
@@ -3305,7 +3480,8 @@ fn persist_final_recording_meta(
recording_meta
.save_for_project()
- .context("persist final recording metadata")
+ .context("persist final recording metadata")?;
+ Ok(recording_meta)
}
fn write_in_progress_meta(recording_dir: &Path) -> anyhow::Result<()> {
@@ -5530,3 +5706,245 @@ mod windows_cancel_tests {
actor.wait_for_stop().await;
}
}
+
+#[cfg(test)]
+mod clean_stop_receipt_tests {
+ use super::*;
+
+ fn metadata(segments: usize, cursors: usize) -> RecordingMeta {
+ let segment = MultipleSegment {
+ display: cap_project::VideoMeta {
+ path: "content/segments/segment-0/display".into(),
+ fps: 30,
+ start_time: Some(0.0),
+ device_id: None,
+ },
+ camera: None,
+ mic: None,
+ system_audio: None,
+ cursor: None,
+ keyboard: None,
+ display_notch: None,
+ };
+ RecordingMeta {
+ platform: Some(Platform::default()),
+ project_path: PathBuf::from("synthetic.cap"),
+ pretty_name: "Synthetic".to_string(),
+ sharing: None,
+ inner: RecordingMetaInner::Studio(Box::new(StudioRecordingMeta::MultipleSegments {
+ inner: MultipleSegments {
+ segments: vec![segment; segments],
+ cursors: cap_project::Cursors::Correct(
+ (0..cursors)
+ .map(|index| {
+ (
+ index.to_string(),
+ cap_project::CursorMeta {
+ image_path: format!("content/cursors/cursor_{index}.png")
+ .into(),
+ hotspot: cap_project::XY::new(0.0, 0.0),
+ shape: None,
+ },
+ )
+ })
+ .collect(),
+ ),
+ status: Some(StudioRecordingStatus::NeedsRemux),
+ },
+ })),
+ upload: None,
+ }
+ }
+
+ fn receipt(metadata: RecordingMeta) -> Option<CleanStoppedStudio> {
+ CleanStoppedStudio::new(
+ BoundedStoppedStudioMeta::new(metadata)?,
+ cap_project::ProjectConfiguration::default(),
+ )
+ }
+
+ #[test]
+ fn clean_stop_receipt_is_single_use_across_completion_clones() {
+ let metadata = metadata(1, 1);
+ let RecordingMetaInner::Studio(studio) = &metadata.inner else {
+ unreachable!();
+ };
+ let completed = CompletedRecording {
+ project_path: metadata.project_path.clone(),
+ meta: studio.as_ref().clone(),
+ cursor_data: Default::default(),
+ clean_stopped: receipt(metadata),
+ };
+ let second = completed.clone();
+ let first_receipt = completed.clean_stopped.as_ref().unwrap();
+ let second_receipt = second.clean_stopped.as_ref().unwrap();
+ assert!(Arc::ptr_eq(
+ &first_receipt.snapshot,
+ &second_receipt.snapshot
+ ));
+ assert!(first_receipt.claim(Path::new("different.cap")).is_none());
+ let claim = first_receipt.claim(&completed.project_path).unwrap();
+ assert_eq!(claim.metadata().project_path, completed.project_path);
+ assert!(second_receipt.claim(&second.project_path).is_none());
+ assert!(first_receipt.claim(&completed.project_path).is_none());
+ }
+
+ #[test]
+ fn clean_stop_receipt_has_one_winner_under_concurrent_claims() {
+ let receipt = receipt(metadata(1, 0)).unwrap();
+ let winners = std::thread::scope(|scope| {
+ let workers = (0..8)
+ .map(|_| {
+ let receipt = &receipt;
+ scope.spawn(move || receipt.claim(Path::new("synthetic.cap")).is_some())
+ })
+ .collect::<Vec<_>>();
+ workers
+ .into_iter()
+ .map(|worker| worker.join().unwrap())
+ .filter(|winner| *winner)
+ .count()
+ });
+ assert_eq!(winners, 1);
+ }
+
+ #[test]
+ fn clean_stop_receipt_bounds_are_preview_eligibility_only() {
+ assert!(receipt(metadata(MAX_PREPARING_SEGMENTS, 0)).is_some());
+ let oversized = metadata(MAX_PREPARING_SEGMENTS + 1, 0);
+ let RecordingMetaInner::Studio(studio) = &oversized.inner else {
+ unreachable!();
+ };
+ let completed = CompletedRecording {
+ project_path: oversized.project_path.clone(),
+ meta: studio.as_ref().clone(),
+ cursor_data: Default::default(),
+ clean_stopped: receipt(oversized),
+ };
+ assert!(completed.clean_stopped.is_none());
+ let StudioRecordingMeta::MultipleSegments { inner } = completed.meta else {
+ unreachable!();
+ };
+ assert_eq!(inner.segments.len(), MAX_PREPARING_SEGMENTS + 1);
+ assert!(receipt(metadata(1, MAX_PREPARING_CURSOR_IMAGES)).is_some());
+ assert!(receipt(metadata(1, MAX_PREPARING_CURSOR_IMAGES + 1)).is_none());
+ }
+
+ #[test]
+ fn clean_stop_receipt_string_budget_accepts_boundary_and_rejects_one_more_byte() {
+ for extra in [0, 1] {
+ let mut metadata = metadata(1, 0);
+ let fixed = metadata.project_path.capacity() + metadata.pretty_name.capacity();
+ let RecordingMetaInner::Studio(studio) = &mut metadata.inner else {
+ unreachable!();
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ unreachable!();
+ };
+ let fixed = fixed + inner.segments[0].display.path.as_str().len();
+ inner.segments[0].display.device_id =
+ Some("x".repeat(MAX_PREPARING_METADATA_STRING_BYTES - fixed + extra));
+ assert_eq!(receipt(metadata).is_some(), extra == 0);
+ }
+ }
+
+ #[test]
+ fn clean_stop_receipt_rejects_complete_failed_and_empty_recordings() {
+ for status in [
+ Some(StudioRecordingStatus::Complete),
+ Some(StudioRecordingStatus::InProgress),
+ Some(StudioRecordingStatus::Failed {
+ error: "retained failure".into(),
+ }),
+ None,
+ ] {
+ let mut metadata = metadata(1, 0);
+ let RecordingMetaInner::Studio(studio) = &mut metadata.inner else {
+ unreachable!();
+ };
+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {
+ unreachable!();
+ };
+ inner.status = status;
+ assert!(receipt(metadata).is_none());
+ }
+ assert!(receipt(metadata(0, 0)).is_none());
+ }
+
+ #[test]
+ fn clean_stop_receipt_moves_existing_persistence_and_configuration_allocations() {
+ let metadata = metadata(1, 1);
+ let RecordingMetaInner::Studio(studio) = &metadata.inner else {
+ unreachable!();
+ };
+ let metadata_pointer = studio.as_ref() as *const StudioRecordingMeta;
+ let mut configuration = cap_project::ProjectConfiguration::default();
+ configuration
+ .clips
+ .push(cap_project::ClipConfiguration::default());
+ let clips_pointer = configuration.clips.as_ptr();
+ let receipt = CleanStoppedStudio::new(
+ BoundedStoppedStudioMeta::new(metadata).unwrap(),
+ configuration,
+ )
+ .unwrap();
+ let claim = receipt.claim(Path::new("synthetic.cap")).unwrap();
+ let RecordingMetaInner::Studio(studio) = &claim.metadata().inner else {
+ unreachable!();
+ };
+ assert_eq!(
+ studio.as_ref() as *const StudioRecordingMeta,
+ metadata_pointer
+ );
+ assert_eq!(claim.configuration().clips.as_ptr(), clips_pointer);
+ }
+
+ #[test]
+ fn clean_stop_receipt_declines_oversized_config_capacity_without_changing_config() {
+ let mut configuration = cap_project::ProjectConfiguration {
+ clips: Vec::with_capacity(MAX_PREPARING_SEGMENTS * 2 + 1),
+ ..cap_project::ProjectConfiguration::default()
+ };
+ configuration
+ .clips
+ .push(cap_project::ClipConfiguration::default());
+ assert!(
+ CleanStoppedStudio::new(
+ BoundedStoppedStudioMeta::new(metadata(1, 0)).unwrap(),
+ configuration,
+ )
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn clean_stop_receipt_snapshot_matches_existing_persisted_bytes() {
+ let directory = tempfile::tempdir().unwrap();
+ let metadata = metadata(1, 1);
+ let RecordingMetaInner::Studio(studio) = &metadata.inner else {
+ unreachable!();
+ };
+ let persisted = persist_final_recording_meta(directory.path(), studio).unwrap();
+ let expected = serde_json::to_vec_pretty(&persisted).unwrap();
+ assert_eq!(
+ std::fs::read(directory.path().join("recording-meta.json")).unwrap(),
+ expected
+ );
+ let configuration = cap_project::ProjectConfiguration::default();
+ configuration.write(directory.path()).unwrap();
+ let receipt = CleanStoppedStudio::new(
+ BoundedStoppedStudioMeta::new(persisted).unwrap(),
+ configuration,
+ )
+ .unwrap();
+ let claim = receipt.claim(directory.path()).unwrap();
+ assert_eq!(
+ serde_json::to_vec_pretty(claim.metadata()).unwrap(),
+ expected
+ );
+ assert_eq!(
+ std::fs::read(directory.path().join("project-config.json")).unwrap(),
+ serde_json::to_vec_pretty(claim.configuration()).unwrap()
+ );
+ }
+}
diff --git a/crates/recording/tests/oop_muxer.rs b/crates/recording/tests/oop_muxer.rs
index ee57f5c3c..c705d4077 100644
--- a/crates/recording/tests/oop_muxer.rs
+++ b/crates/recording/tests/oop_muxer.rs
@@ -1,6 +1,6 @@
use cap_recording::oop_muxer::{
- MuxerSubprocess, MuxerSubprocessConfig, RespawningMuxerSubprocess, VideoStreamInit,
- resolve_muxer_binary,
+ AudioStreamInit, MuxerSubprocess, MuxerSubprocessConfig, RespawningMuxerSubprocess,
+ VideoStreamInit, resolve_muxer_binary,
};
use std::path::PathBuf;
use std::sync::Once;
@@ -14,8 +14,13 @@ static MUXER_BINARY: Once = Once::new();
fn setup_muxer_binary() -> PathBuf {
let workspace = env!("CARGO_MANIFEST_DIR");
- let target_debug = PathBuf::from(workspace).join("../../target/debug/cap-muxer");
- let target_release = PathBuf::from(workspace).join("../../target/release/cap-muxer");
+ let binary_name = format!("cap-muxer{}", std::env::consts::EXE_SUFFIX);
+ let target_debug = PathBuf::from(workspace)
+ .join("../../target/debug")
+ .join(&binary_name);
+ let target_release = PathBuf::from(workspace)
+ .join("../../target/release")
+ .join(binary_name);
for candidate in [target_debug, target_release] {
if candidate.exists() {
@@ -64,24 +69,134 @@ fn subprocess_spawns_and_finishes_cleanly_without_packets() {
assert_eq!(report.packets_written, 0);
}
+fn empty_audio_init() -> AudioStreamInit {
+ AudioStreamInit {
+ codec: "aac".into(),
+ sample_rate: 48_000,
+ channels: 2,
+ sample_format: "fltp".into(),
+ time_base: (1, 48_000),
+ extradata: vec![0x11, 0x90],
+ }
+}
+
+#[test]
+fn empty_audio_and_combined_streams_preserve_initialization_files() {
+ let binary = setup_muxer_binary();
+ for with_video in [false, true] {
+ let directory = TempDir::new().unwrap();
+ let output = directory.path().join("output");
+ let mut config = minimal_video_config(&output, Vec::new());
+ if !with_video {
+ config.video_init = None;
+ }
+ config.audio_init = Some(empty_audio_init());
+ config.init_segment_name = "init_$RepresentationID$.mp4".into();
+ let subprocess = MuxerSubprocess::spawn(binary.clone(), config, None).unwrap();
+ let report = subprocess.finish().unwrap();
+ assert_eq!(report.exit_code, Some(0));
+ assert_eq!(report.packets_written, 0);
+ assert!(output.join("init_0.mp4").is_file());
+ assert_eq!(output.join("init_1.mp4").is_file(), with_video);
+ assert!(
+ std::fs::read(output.join("dash_manifest.mpd"))
+ .unwrap()
+ .is_empty()
+ );
+ assert!(!output.join("dash_manifest.mpd.tmp").exists());
+ }
+}
+
+#[test]
+fn discarded_packets_before_first_video_keyframe_leave_a_clean_empty_output() {
+ let directory = TempDir::new().unwrap();
+ let output = directory.path().join("output");
+ let mut config = minimal_video_config(&output, Vec::new());
+ config.audio_init = Some(empty_audio_init());
+ config.init_segment_name = "init_$RepresentationID$.mp4".into();
+ let mut subprocess = MuxerSubprocess::spawn(setup_muxer_binary(), config, None).unwrap();
+ subprocess
+ .write_video_packet(0, 0, 3_000, false, &[1, 2, 3])
+ .unwrap();
+ subprocess
+ .write_audio_packet(0, 0, 1_024, &[4, 5, 6])
+ .unwrap();
+ let report = subprocess.finish().unwrap();
+ assert_eq!(report.exit_code, Some(0));
+ assert_eq!(report.packets_written, 2);
+ assert!(output.join("init_0.mp4").is_file());
+ assert!(output.join("init_1.mp4").is_file());
+ assert!(
+ std::fs::read(output.join("dash_manifest.mpd"))
+ .unwrap()
+ .is_empty()
+ );
+ assert!(std::fs::read_dir(&output).unwrap().all(|entry| {
+ !entry
+ .unwrap()
+ .file_name()
+ .to_string_lossy()
+ .ends_with(".m4s")
+ }));
+}
+
#[test]
fn subprocess_exits_after_finish_or_abort_without_waiting_for_stdin_eof() {
- use cap_muxer_protocol::{Frame, write_frame};
+ use cap_muxer_protocol::{Frame, InitVideo, StartParams, write_frame};
use std::io::Write;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
let binary = setup_muxer_binary();
- for (frame, expected_exit) in [(Frame::Finish, 0), (Frame::Abort("test".into()), 40)] {
+ for (initialized, frame, expected_exit) in [
+ (false, Some(Frame::Finish), 0),
+ (false, Some(Frame::Abort("test".into())), 40),
+ (true, Some(Frame::Finish), 0),
+ (true, Some(Frame::Abort("test".into())), 40),
+ (true, None, 0),
+ ] {
+ let directory = TempDir::new().unwrap();
let mut child = Command::new(&binary)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap();
- let mut stdin = child.stdin.take().unwrap();
- write_frame(&mut stdin, &frame).unwrap();
- stdin.flush().unwrap();
+ let mut stdin = child.stdin.take();
+ let writer = stdin.as_mut().unwrap();
+ if initialized {
+ write_frame(
+ writer,
+ &Frame::InitVideo(InitVideo {
+ codec: "libx264".into(),
+ width: TEST_WIDTH,
+ height: TEST_HEIGHT,
+ frame_rate_num: TEST_FPS as i32,
+ frame_rate_den: 1,
+ time_base_num: 1,
+ time_base_den: 90_000,
+ extradata: Vec::new(),
+ segment_duration_ms: 2_000,
+ }),
+ )
+ .unwrap();
+ write_frame(
+ writer,
+ &Frame::Start(StartParams {
+ output_directory: directory.path().to_string_lossy().into_owned(),
+ init_segment_name: "init.mp4".into(),
+ media_segment_pattern: "segment_$Number%03d$.m4s".into(),
+ }),
+ )
+ .unwrap();
+ }
+ if let Some(frame) = &frame {
+ write_frame(writer, frame).unwrap();
+ writer.flush().unwrap();
+ } else {
+ writer.flush().unwrap();
+ drop(stdin.take());
+ }
let started = Instant::now();
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
@@ -96,6 +211,9 @@ fn subprocess_exits_after_finish_or_abort_without_waiting_for_stdin_eof() {
};
drop(stdin);
assert_eq!(status.code(), Some(expected_exit));
+ if initialized {
+ assert!(directory.path().join("init.mp4").is_file());
+ }
}
}
@@ -256,6 +374,15 @@ fn subprocess_survives_finish_after_init_only() {
#[test]
fn encoder_to_subprocess_end_to_end_produces_playable_init_and_segments() {
+ assert_encoded_recording_survives_finish(60);
+}
+
+#[test]
+fn the_only_encoded_packet_is_flushed_before_empty_output_is_decided() {
+ assert_encoded_recording_survives_finish(1);
+}
+
+fn assert_encoded_recording_survives_finish(frame_count: u64) {
use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset};
use cap_enc_ffmpeg::h264_packet::EncodePacketError;
use cap_media_info::{Pixel, VideoInfo};
@@ -330,7 +457,7 @@ fn encoder_to_subprocess_end_to_end_produces_playable_init_and_segments() {
})
}
- for i in 0..60u64 {
+ for i in 0..frame_count {
let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, 320, 240);
for plane_idx in 0..frame.planes() {
let data = frame.data_mut(plane_idx);
@@ -352,11 +479,7 @@ fn encoder_to_subprocess_end_to_end_produces_playable_init_and_segments() {
let report = subprocess.finish().expect("subprocess finish cleanly");
assert_eq!(report.exit_code, Some(0));
- assert!(
- report.packets_written > 0,
- "expected subprocess to have written at least one packet, got {}",
- report.packets_written
- );
+ assert_eq!(report.packets_written, frame_count);
let init_path = output_dir.join("init.mp4");
assert!(
@@ -370,7 +493,7 @@ fn encoder_to_subprocess_end_to_end_produces_playable_init_and_segments() {
init_meta.len()
);
- let mut segment_count = 0u32;
+ let mut segments = Vec::new();
for entry in std::fs::read_dir(&output_dir).unwrap().flatten() {
let name = entry.file_name();
let name_str = name.to_string_lossy();
@@ -380,11 +503,45 @@ fn encoder_to_subprocess_end_to_end_produces_playable_init_and_segments() {
meta.len() > 0,
"segment file {name_str} should be non-empty"
);
- segment_count += 1;
+ segments.push(entry.path());
}
}
assert!(
- segment_count > 0,
- "expected at least one segment_*.m4s file, got {segment_count}"
+ !segments.is_empty(),
+ "expected at least one segment_*.m4s file"
);
+ segments.sort();
+ let combined_path = temp_dir.path().join("combined.mp4");
+ let mut combined = std::fs::read(init_path).unwrap();
+ for segment in segments {
+ combined.extend(std::fs::read(segment).unwrap());
+ }
+ std::fs::write(&combined_path, combined).unwrap();
+ let mut input = ffmpeg::format::input(&combined_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 decoded_frames = 0;
+ let mut receive_frames = |decoder: &mut ffmpeg::decoder::Video| loop {
+ let mut frame = ffmpeg::frame::Video::empty();
+ match decoder.receive_frame(&mut frame) {
+ Ok(()) => decoded_frames += 1,
+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,
+ Err(ffmpeg::Error::Eof) => break,
+ Err(error) => panic!("Failed to decode finalized recording: {error}"),
+ }
+ };
+ for (stream, packet) in input.packets() {
+ if stream.index() == stream_index {
+ decoder.send_packet(&packet).unwrap();
+ receive_frames(&mut decoder);
+ }
+ }
+ decoder.send_eof().unwrap();
+ receive_frames(&mut decoder);
+ assert_eq!(decoded_frames, frame_count);
}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index dbe09bb55..cb030f00f 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -7,6 +7,7 @@ edition = "2024"
workspace = true
[dependencies]
+cap-enc-ffmpeg = { path = "../enc-ffmpeg" }
anyhow.workspace = true
bytemuck = { version = "1.7", features = ["derive"] }
cap-camera-effects = { path = "../camera-effects" }
@@ -63,6 +64,8 @@ windows_0_58 = { package = "windows", version = "0.58", features = [
] }
[dev-dependencies]
+cap-media-info = { path = "../media-info" }
+tempfile = "3"
pollster = "0.4.0"
pretty_assertions = "1.4.1"
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index 92d271337..39afc4518 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -18,8 +18,9 @@ use crate::{DecodedFrame, PixelFormat};
use cap_video_decode::FrameTextures;
use super::{
- DecoderInitResult, DecoderType, FRAME_CACHE_SIZE, VideoDecoderMessage,
- frame_converter::FrameConverter, pts_to_frame, record_pts_hole,
+ DecoderInitResult, DecoderType, FRAME_CACHE_SIZE, ManagedVideoControl, ManagedVideoError,
+ ManagedVideoInput, VideoDecoderMessage, frame_converter::FrameConverter, pts_to_frame,
+ record_pts_hole,
};
#[derive(Clone)]
@@ -272,6 +273,70 @@ fn insert_cached_frame(
cache.insert(number, frame);
}
+enum DecoderInput {
+ Ordinary(PathBuf),
+ Managed(ManagedVideoInput),
+}
+
+impl DecoderInput {
+ fn open(
+ &self,
+ hardware: Option<ffmpeg::sys::AVHWDeviceType>,
+ managed: Option<&Arc<ManagedVideoControl>>,
+ ) -> Result<cap_video_decode::FFmpegDecoder, String> {
+ match self {
+ Self::Ordinary(path) => cap_video_decode::FFmpegDecoder::new(path.clone(), hardware),
+ Self::Managed(input) => {
+ let control = managed
+ .cloned()
+ .ok_or("Managed video input requires a cancellation owner")?;
+ cap_video_decode::FFmpegDecoder::new_relocatable_interruptible(
+ &input.source,
+ input.paths.iter().map(PathBuf::as_path),
+ hardware,
+ Arc::new(move || control.is_cancelled()),
+ )
+ }
+ }
+ }
+}
+
+fn managed_error(control: &ManagedVideoControl, error: ManagedVideoError) -> ManagedVideoError {
+ if control.is_cancelled() {
+ ManagedVideoError::Cancelled
+ } else {
+ error
+ }
+}
+
+fn managed_stopped(control: Option<&Arc<ManagedVideoControl>>) -> bool {
+ control.is_some_and(|control| control.is_cancelled() || control.terminal().is_some())
+}
+
+fn first_frame(
+ frames: &mut impl Iterator<Item = Result<frame::Video, ffmpeg::Error>>,
+ managed: Option<&Arc<ManagedVideoControl>>,
+) -> Result<Option<frame::Video>, ManagedVideoError> {
+ let Some(control) = managed else {
+ return Ok(frames.flatten().next());
+ };
+ if let Some(error) = control.terminal() {
+ return Err(error);
+ }
+ if control.is_cancelled() {
+ return Err(control.fail(ManagedVideoError::Cancelled));
+ }
+ let frame = frames.next();
+ if control.is_cancelled() {
+ return Err(control.fail(ManagedVideoError::Cancelled));
+ }
+ match frame {
+ Some(Ok(frame)) => Ok(Some(frame)),
+ Some(Err(error)) => Err(control.fail(ManagedVideoError::Decode(error.to_string()))),
+ None => Ok(None),
+ }
+}
+
pub struct FfmpegDecoder;
impl FfmpegDecoder {
@@ -293,571 +358,252 @@ impl FfmpegDecoder {
ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,
use_hw_acceleration: bool,
) -> Result<(), String> {
- std::thread::spawn(move || {
- let hw_device_type = if use_hw_acceleration {
- #[cfg(target_os = "windows")]
- {
- Some(AVHWDeviceType::AV_HWDEVICE_TYPE_D3D11VA)
- }
- #[cfg(target_os = "macos")]
- {
- Some(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX)
- }
- #[cfg(not(any(target_os = "windows", target_os = "macos")))]
- {
- None
- }
- } else {
- None
- };
- let mut this = match cap_video_decode::FFmpegDecoder::new(path.clone(), hw_device_type)
- {
- Err(e) => {
- let _ = ready_tx.send(Err(e));
- return;
- }
- Ok(v) => {
- let is_hw = v.is_hardware_accelerated();
- let width = v.decoder().width();
- let height = v.decoder().height();
- info!(
- "FFmpeg decoder created for '{}': {}x{}, hw_accel={}",
- name, width, height, is_hw
- );
- v
- }
- };
-
- let time_base = this.decoder().time_base();
- let start_time = this.start_time();
- let video_width = this.decoder().width();
- let video_height = this.decoder().height();
- let is_hw = this.is_hardware_accelerated();
-
- let mut cache = BTreeMap::<u32, CachedFrame>::new();
- let mut last_active_frame = None::<u32>;
- // pts holes (start frame -> first frame after the hole) discovered
- // from decode-order jumps; facts about the file, so they survive
- // resets and cache eviction.
- let mut pts_holes = BTreeMap::<u32, u32>::new();
- // Content of the most recently served VFR hold, kept across
- // requests so a hole keeps rendering its true frame even after
- // the pre-hole frame leaves the cache.
- let mut gap_hold: Option<OutputFrame> = None;
- // Previous vended frame number since the last reset, for pts-hole
- // discovery (the reader vends in pts order between resets).
- let mut prev_vended: Option<u32> = None;
-
- let last_sent_frame = Rc::new(RefCell::new(None::<OutputFrame>));
- let first_ever_frame = Rc::new(RefCell::new(None::<OutputFrame>));
-
- let mut frames = this.frames();
- let mut converter = FrameConverter::new();
-
- let first_frame_result = (&mut frames).flatten().next();
-
- if first_frame_result.is_none() && is_hw {
- let mut sw_this = match cap_video_decode::FFmpegDecoder::new(path.clone(), None) {
- Err(e) => {
- let _ = ready_tx.send(Err(format!("Software fallback failed: {e}")));
- return;
- }
- Ok(v) => v,
- };
-
- let sw_time_base = sw_this.decoder().time_base();
- let sw_start_time = sw_this.start_time();
-
- let mut sw_cache = BTreeMap::<u32, CachedFrame>::new();
- let mut sw_last_active_frame = None::<u32>;
- // pts holes (start frame -> first frame after the hole) from
- // decode-order jumps; facts about the file that survive resets
- // and cache eviction.
- let mut sw_pts_holes = BTreeMap::<u32, u32>::new();
- // Content of the most recently served VFR hold.
- let mut sw_gap_hold: Option<OutputFrame> = None;
- // Previous vended frame number since the last reset.
- let mut sw_prev_vended: Option<u32> = None;
- let sw_last_sent_frame = Rc::new(RefCell::new(None::<OutputFrame>));
- let sw_first_ever_frame = Rc::new(RefCell::new(None::<OutputFrame>));
- let mut sw_frames = sw_this.frames();
- let mut sw_converter = FrameConverter::new();
-
- if let Some(frame) = (&mut sw_frames).flatten().next() {
- let current_frame =
- pts_to_frame(frame.pts().unwrap_or(0) - sw_start_time, sw_time_base, fps);
- let mut cache_frame = CachedFrame::Raw {
- frame,
- number: current_frame,
- };
- let output = cache_frame.produce(&mut sw_converter);
- sw_cache.insert(current_frame, cache_frame);
- *sw_first_ever_frame.borrow_mut() = Some(output.clone());
- *sw_last_sent_frame.borrow_mut() = Some(output);
- // The pre-decoded frame is a real vend: without seeding
- // this, an opening static hold would never be recorded.
- sw_prev_vended = Some(current_frame);
- }
-
- let sw_decoder_type = DecoderType::FFmpegSoftware;
- let sw_init_result = DecoderInitResult {
- width: video_width,
- height: video_height,
- decoder_type: sw_decoder_type,
- };
- let _ = ready_tx.send(Ok(sw_init_result));
-
- while let Ok(r) = rx.recv() {
- let mut pending_requests: Vec<PendingRequest> = Vec::with_capacity(8);
- let mut push_request =
- |requested_time: f32, reply: oneshot::Sender<DecodedFrame>| {
- if reply.is_closed() {
- return;
- }
-
- let requested_time = requested_time.max(0.0);
- let requested_frame = (requested_time * fps as f32).floor() as u32;
-
- pending_requests.push(PendingRequest {
- time: requested_time,
- frame: requested_frame,
- reply,
- });
- };
-
- match r {
- VideoDecoderMessage::GetFrame(requested_time, _, reply) => {
- push_request(requested_time, reply);
- }
- }
-
- while let Ok(msg) = rx.try_recv() {
- match msg {
- VideoDecoderMessage::GetFrame(requested_time, _, reply) => {
- push_request(requested_time, reply);
- }
- }
- }
-
- pending_requests.sort_by_key(|r| r.frame);
-
- for PendingRequest {
- time: requested_time,
- frame: requested_frame,
- reply,
- } in pending_requests
- {
- if reply.is_closed() {
- continue;
- }
-
- let last_sent_number =
- sw_last_sent_frame.borrow().as_ref().map(|f| f.number);
- let is_backward_seek = last_sent_number
- .map(|last| requested_frame < last)
- .unwrap_or(false);
-
- if let Some(cached) = sw_cache.get_mut(&requested_frame) {
- let data = cached.produce(&mut sw_converter);
- if reply.send(data.frame.clone()).is_err() {
- log::warn!(
- "FFmpeg '{name}': Failed to send cached frame {requested_frame}: receiver dropped"
- );
- }
- *sw_last_sent_frame.borrow_mut() = Some(data);
- continue;
- }
-
- if is_backward_seek {
- let best_cached_frame = sw_cache
- .range(..=requested_frame)
- .next_back()
- .filter(|(k, _)| {
- requested_frame.saturating_sub(**k)
- <= MAX_FRAME_LOOKBACK_TOLERANCE
- })
- .map(|(k, _)| *k);
-
- if let Some(frame_num) = best_cached_frame
- && let Some(cached) = sw_cache.get_mut(&frame_num)
- {
- let data = cached.produce(&mut sw_converter);
- *sw_last_sent_frame.borrow_mut() = Some(data.clone());
- let _ = reply.send(data.frame);
- continue;
- }
-
- if requested_frame <= MAX_FRAME_LOOKBACK_TOLERANCE
- && let Some(first_frame) = sw_first_ever_frame.borrow().clone()
- {
- *sw_last_sent_frame.borrow_mut() = Some(first_frame.clone());
- let _ = reply.send(first_frame.frame);
- continue;
- }
-
- let _ = sw_this.reset(requested_time);
- sw_frames = sw_this.frames();
- *sw_last_sent_frame.borrow_mut() = None;
- sw_cache.clear();
- sw_prev_vended = None;
- }
-
- // Requests inside a KNOWN pts hole are answered with the
- // hole's start frame — the true VFR hold — without
- // touching the decoder; see the hardware path above.
- if !is_backward_seek
- && let Some(hole_start) = sw_pts_holes
- .range(..=requested_frame)
- .next_back()
- .filter(|&(_, &end)| requested_frame < end)
- .map(|(&start, _)| start)
- {
- let data = sw_cache
- .get_mut(&hole_start)
- .map(|c| c.produce(&mut sw_converter))
- .or_else(|| sw_gap_hold.clone().filter(|h| h.number == hole_start));
- if let Some(data) = data {
- sw_gap_hold = Some(data.clone());
- *sw_last_sent_frame.borrow_mut() = Some(data.clone());
- let _ = reply.send(data.frame);
- continue;
- }
- }
-
- if reply.is_closed() {
- continue;
- }
-
- let reply_cell = Rc::new(RefCell::new(Some(reply)));
- let reply_for_respond = reply_cell.clone();
-
- let mut respond = {
- let last_sent_frame = sw_last_sent_frame.clone();
- Some(move |data: OutputFrame| {
- let frame_number = data.number;
- *last_sent_frame.borrow_mut() = Some(data.clone());
- if let Some(reply) = reply_for_respond.borrow_mut().take()
- && reply.send(data.frame).is_err()
- {
- log::warn!(
- "Failed to send decoded frame {frame_number}: receiver dropped"
- );
- }
- })
- };
-
- let cache_min = requested_frame.saturating_sub(FRAME_CACHE_SIZE as u32 / 2);
- let cache_max = requested_frame + FRAME_CACHE_SIZE as u32 / 2;
-
- let is_far_forward = sw_last_sent_frame.borrow().as_ref().map_or_else(
- || {
- if sw_first_ever_frame.borrow().is_some() {
- let first_frame_num = sw_first_ever_frame
- .borrow()
- .as_ref()
- .map(|f| f.number)
- .unwrap_or(0);
- requested_frame.saturating_sub(first_frame_num)
- > FRAME_CACHE_SIZE as u32
- } else {
- requested_frame != 0
- }
- },
- |last| {
- requested_frame.saturating_sub(last.number)
- > FRAME_CACHE_SIZE as u32
- },
- );
-
- if is_far_forward {
- let _ = sw_this.reset(requested_time);
- sw_frames = sw_this.frames();
- *sw_last_sent_frame.borrow_mut() = None;
- sw_cache.clear();
- sw_prev_vended = None;
- }
-
- let mut exit = false;
- // Newest vended frame below the cache window: after a reset
- // the reader re-vends from the keyframe before the request,
- // and that frame is the true VFR hold for a request inside
- // a pts hole.
- let mut hold_candidate: Option<(u32, CachedFrame)> = None;
-
- for frame in &mut sw_frames {
- if reply_cell.borrow().as_ref().is_none_or(|r| r.is_closed()) {
- respond.take();
- // The frame just pulled is discarded: it breaks
- // the vend continuity that hole discovery
- // relies on.
- sw_prev_vended = None;
- break;
- }
-
- let Ok(frame) = frame.map_err(|e| format!("read frame / {e}")) else {
- // A skipped frame breaks the vend continuity
- // that hole discovery relies on.
- sw_prev_vended = None;
- continue;
- };
-
- let Some(pts) = frame.pts() else {
- sw_prev_vended = None;
- continue;
- };
- let current_frame =
- pts_to_frame(pts - sw_start_time, sw_time_base, fps);
-
- if let Some(prev) = sw_prev_vended
- && current_frame > prev + 1
- {
- record_pts_hole(&mut sw_pts_holes, prev, current_frame);
- }
- sw_prev_vended = Some(current_frame);
-
- let mut cache_frame = CachedFrame::Raw {
- frame,
- number: current_frame,
- };
-
- if sw_first_ever_frame.borrow().is_none() {
- let output = cache_frame.produce(&mut sw_converter);
- *sw_first_ever_frame.borrow_mut() = Some(output);
- }
-
- let exceeds_cache_bounds = current_frame > cache_max;
- let too_small_for_cache_bounds = current_frame < cache_min;
-
- if too_small_for_cache_bounds {
- // Keep the newest pre-request frame as the VFR hold
- // candidate instead of discarding it; a frame below
- // the cache window can never exceed the request, so
- // nothing else in this iteration applies to it.
- if current_frame <= requested_frame {
- hold_candidate = Some((current_frame, cache_frame));
- }
- continue;
- }
-
- {
- cache_frame.produce(&mut sw_converter);
-
- 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
- // at-or-before holds for later gap requests.
- if current_frame == requested_frame
- && let Some(respond) = respond.take()
- {
- let output = sw_cache
- .get_mut(&current_frame)
- .unwrap()
- .produce(&mut sw_converter);
- (respond)(output);
- break;
- }
- }
+ Self::spawn_worker(
+ name,
+ DecoderInput::Ordinary(path),
+ fps,
+ rx,
+ ready_tx,
+ use_hw_acceleration,
+ None,
+ )
+ .map(drop)
+ }
- if current_frame > requested_frame && respond.is_some() {
- // A frame at-or-before the request is the true content for
- // that time in a VFR recording: a pts gap means the frame
- // stayed on screen, however long the gap is. Prefer the
- // newest such frame among the cache, the hold candidate a
- // reset re-vended, and the persistent gap hold.
- let cached_before = sw_cache
- .range(..=requested_frame)
- .next_back()
- .map(|(&n, _)| n);
- let candidate_number = hold_candidate
- .as_ref()
- .map(|(n, _)| *n)
- .filter(|&n| n <= requested_frame);
- let hold_before = sw_gap_hold.clone().filter(|h| {
- sw_pts_holes.get(&h.number).is_some_and(|&end| {
- h.number <= requested_frame && requested_frame < end
- })
- });
- let last_before = sw_last_sent_frame
- .borrow()
- .as_ref()
- .filter(|l| l.number <= requested_frame)
- .cloned();
- let best_number = [
- cached_before,
- candidate_number,
- hold_before.as_ref().map(|h| h.number),
- last_before.as_ref().map(|l| l.number),
- ]
- .into_iter()
- .flatten()
- .max();
-
- if let Some(best_number) = best_number
- && let Some(respond) = respond.take()
- {
- let output = if cached_before == Some(best_number) {
- sw_cache
- .get_mut(&best_number)
- .unwrap()
- .produce(&mut sw_converter)
- } else if candidate_number == Some(best_number) {
- let (_, mut candidate) = hold_candidate.take().unwrap();
- candidate.produce(&mut sw_converter)
- } else if hold_before.as_ref().map(|h| h.number)
- == Some(best_number)
- {
- hold_before.unwrap()
- } else {
- last_before.unwrap()
- };
- sw_gap_hold = Some(output.clone());
- (respond)(output);
- } else if let Some(respond) = respond.take() {
- let output = sw_cache
- .get_mut(&current_frame)
- .unwrap()
- .produce(&mut sw_converter);
- (respond)(output);
- }
-
- // The request is answered; stop here so the
- // next sample stays in the decoder for the
- // next request. Pulling it now would discard
- // it at the reply guard and poison the vend
- // continuity that hole discovery relies on.
- break;
- }
+ #[cfg(test)]
+ pub(super) fn spawn_ordinary_test_worker(
+ path: PathBuf,
+ fps: u32,
+ rx: mpsc::Receiver<VideoDecoderMessage>,
+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,
+ use_hw_acceleration: bool,
+ ) -> std::thread::JoinHandle<()> {
+ Self::spawn_worker(
+ "ordinary-test",
+ DecoderInput::Ordinary(path),
+ fps,
+ rx,
+ ready_tx,
+ use_hw_acceleration,
+ None,
+ )
+ .unwrap()
+ }
- exit = exit || exceeds_cache_bounds;
+ pub(super) fn spawn_managed(
+ name: &'static str,
+ input: ManagedVideoInput,
+ fps: u32,
+ rx: mpsc::Receiver<VideoDecoderMessage>,
+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,
+ use_hw_acceleration: bool,
+ managed: Arc<ManagedVideoControl>,
+ ) -> Result<std::thread::JoinHandle<()>, String> {
+ Self::spawn_worker(
+ name,
+ DecoderInput::Managed(input),
+ fps,
+ rx,
+ ready_tx,
+ use_hw_acceleration,
+ Some(managed),
+ )
+ }
- if exit {
- break;
- }
- }
+ fn spawn_worker(
+ name: &'static str,
+ input: DecoderInput,
+ fps: u32,
+ rx: mpsc::Receiver<VideoDecoderMessage>,
+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,
+ use_hw_acceleration: bool,
+ managed: Option<Arc<ManagedVideoControl>>,
+ ) -> Result<std::thread::JoinHandle<()>, String> {
+ let is_managed = managed.is_some();
+ let worker = move || {
+ if let Some(control) = &managed {
+ control.run_worker(|| {
+ Self::run(
+ name,
+ input,
+ fps,
+ rx,
+ ready_tx,
+ use_hw_acceleration,
+ managed.clone(),
+ );
+ });
+ } else {
+ Self::run(name, input, fps, rx, ready_tx, use_hw_acceleration, None);
+ }
+ };
+ if is_managed {
+ std::thread::Builder::new()
+ .name(format!("managed-video-{name}"))
+ .spawn(worker)
+ .map_err(|error| error.to_string())
+ } else {
+ Ok(std::thread::spawn(worker))
+ }
+ }
- sw_last_active_frame = Some(requested_frame);
+ fn run(
+ name: &'static str,
+ input: DecoderInput,
+ fps: u32,
+ rx: mpsc::Receiver<VideoDecoderMessage>,
+ ready_tx: oneshot::Sender<Result<DecoderInitResult, String>>,
+ use_hw_acceleration: bool,
+ managed: Option<Arc<ManagedVideoControl>>,
+ ) {
+ let hw_device_type = if use_hw_acceleration {
+ #[cfg(target_os = "windows")]
+ {
+ Some(AVHWDeviceType::AV_HWDEVICE_TYPE_D3D11VA)
+ }
+ #[cfg(target_os = "macos")]
+ {
+ Some(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX)
+ }
+ #[cfg(not(any(target_os = "windows", target_os = "macos")))]
+ {
+ None
+ }
+ } else {
+ None
+ };
+ let mut this = match input.open(hw_device_type, managed.as_ref()) {
+ Err(e) => {
+ if let Some(control) = &managed {
+ control.fail(managed_error(
+ control,
+ ManagedVideoError::Initialization(e.clone()),
+ ));
+ }
+ let _ = ready_tx.send(Err(e));
+ return;
+ }
+ Ok(v) => {
+ let is_hw = v.is_hardware_accelerated();
+ let width = v.decoder().width();
+ let height = v.decoder().height();
+ info!(
+ "FFmpeg decoder created for '{}': {}x{}, hw_accel={}",
+ name, width, height, is_hw
+ );
+ v
+ }
+ };
- if let Some(respond) = respond.take() {
- // The newest frame at-or-before the request is always a
- // valid VFR hold, regardless of how far back it is —
- // whether it is cached, was re-vended below the cache
- // window by a reset, or is the persistent gap hold.
- let cached_before = sw_cache
- .range(..=requested_frame)
- .next_back()
- .map(|(&n, _)| n);
- let candidate_number = hold_candidate
- .as_ref()
- .map(|(n, _)| *n)
- .filter(|&n| n <= requested_frame);
- let hold_before = sw_gap_hold.clone().filter(|h| {
- sw_pts_holes.get(&h.number).is_some_and(|&end| {
- h.number <= requested_frame && requested_frame < end
- })
- });
- let last_before = sw_last_sent_frame
- .borrow()
- .as_ref()
- .filter(|l| l.number <= requested_frame)
- .cloned();
- let best_number = [
- cached_before,
- candidate_number,
- hold_before.as_ref().map(|h| h.number),
- last_before.as_ref().map(|l| l.number),
- ]
- .into_iter()
- .flatten()
- .max();
+ let time_base = this.decoder().time_base();
+ let start_time = this.start_time();
+ let video_width = this.decoder().width();
+ let video_height = this.decoder().height();
+ let is_hw = this.is_hardware_accelerated();
+
+ let mut cache = BTreeMap::<u32, CachedFrame>::new();
+ let mut last_active_frame = None::<u32>;
+ // pts holes (start frame -> first frame after the hole) discovered
+ // from decode-order jumps; facts about the file, so they survive
+ // resets and cache eviction.
+ let mut pts_holes = BTreeMap::<u32, u32>::new();
+ // Content of the most recently served VFR hold, kept across
+ // requests so a hole keeps rendering its true frame even after
+ // the pre-hole frame leaves the cache.
+ let mut gap_hold: Option<OutputFrame> = None;
+ // Previous vended frame number since the last reset, for pts-hole
+ // discovery (the reader vends in pts order between resets).
+ let mut prev_vended: Option<u32> = None;
+
+ let last_sent_frame = Rc::new(RefCell::new(None::<OutputFrame>));
+ let first_ever_frame = Rc::new(RefCell::new(None::<OutputFrame>));
+
+ let mut frames = this.frames();
+ let mut converter = FrameConverter::new();
+
+ let first_frame_result = match first_frame(&mut frames, managed.as_ref()) {
+ Ok(frame) => frame,
+ Err(error) => {
+ let _ = ready_tx.send(Err(error.to_string()));
+ return;
+ }
+ };
- if let Some(best_number) = best_number {
- let output = if cached_before == Some(best_number) {
- sw_cache
- .get_mut(&best_number)
- .unwrap()
- .produce(&mut sw_converter)
- } else if candidate_number == Some(best_number) {
- let (_, mut candidate) = hold_candidate.take().unwrap();
- candidate.produce(&mut sw_converter)
- } else if hold_before.as_ref().map(|h| h.number)
- == Some(best_number)
- {
- hold_before.unwrap()
- } else {
- last_before.unwrap()
- };
- sw_gap_hold = Some(output.clone());
- (respond)(output);
- } else {
- let last_frame_clone = sw_last_sent_frame.borrow().clone();
- let first_frame_clone = sw_first_ever_frame.borrow().clone();
- if let Some(last_frame) = last_frame_clone {
- (respond)(last_frame);
- } else if let Some(first_frame) = first_frame_clone {
- (respond)(first_frame);
- } else {
- let black_frame_data =
- vec![0u8; (video_width * video_height * 4) as usize];
- let black_frame = OutputFrame {
- number: requested_frame,
- frame: DecodedFrame::new_with_arc(
- Arc::new(black_frame_data),
- video_width,
- video_height,
- ),
- };
- (respond)(black_frame);
- }
- }
- }
+ if first_frame_result.is_none() && is_hw {
+ let mut sw_this = match input.open(None, managed.as_ref()) {
+ Err(e) => {
+ if let Some(control) = &managed {
+ control.fail(managed_error(
+ control,
+ ManagedVideoError::Initialization(e.clone()),
+ ));
}
+ let _ = ready_tx.send(Err(format!("Software fallback failed: {e}")));
+ return;
}
+ Ok(v) => v,
+ };
+ let sw_time_base = sw_this.decoder().time_base();
+ let sw_start_time = sw_this.start_time();
+
+ let mut sw_cache = BTreeMap::<u32, CachedFrame>::new();
+ let mut sw_last_active_frame = None::<u32>;
+ // pts holes (start frame -> first frame after the hole) from
+ // decode-order jumps; facts about the file that survive resets
+ // and cache eviction.
+ let mut sw_pts_holes = BTreeMap::<u32, u32>::new();
+ // Content of the most recently served VFR hold.
+ let mut sw_gap_hold: Option<OutputFrame> = None;
+ // Previous vended frame number since the last reset.
+ let mut sw_prev_vended: Option<u32> = None;
+ let sw_last_sent_frame = Rc::new(RefCell::new(None::<OutputFrame>));
+ let sw_first_ever_frame = Rc::new(RefCell::new(None::<OutputFrame>));
+ let mut sw_frames = sw_this.frames();
+ let mut sw_converter = FrameConverter::new();
+
+ let first_software_frame = match first_frame(&mut sw_frames, managed.as_ref()) {
+ Ok(frame) => frame,
+ Err(error) => {
+ let _ = ready_tx.send(Err(error.to_string()));
+ return;
+ }
+ };
+ if first_software_frame.is_none()
+ && let Some(control) = &managed
+ {
+ let error = control.fail(ManagedVideoError::NoFrames);
+ let _ = ready_tx.send(Err(error.to_string()));
return;
}
-
- if let Some(frame) = first_frame_result {
+ if let Some(frame) = first_software_frame {
let current_frame =
- pts_to_frame(frame.pts().unwrap_or(0) - start_time, time_base, fps);
+ pts_to_frame(frame.pts().unwrap_or(0) - sw_start_time, sw_time_base, fps);
let mut cache_frame = CachedFrame::Raw {
frame,
number: current_frame,
};
- let output = cache_frame.produce(&mut converter);
-
- cache.insert(current_frame, cache_frame);
- *first_ever_frame.borrow_mut() = Some(output.clone());
- *last_sent_frame.borrow_mut() = Some(output);
- // The pre-decoded frame is a real vend: without seeding this,
- // an opening static hold would never be recorded.
- prev_vended = Some(current_frame);
- info!(
- "FFmpeg decoder '{}': pre-decoded first frame {} ({}x{})",
- name, current_frame, video_width, video_height
- );
+ let output = cache_frame.produce(&mut sw_converter);
+ sw_cache.insert(current_frame, cache_frame);
+ *sw_first_ever_frame.borrow_mut() = Some(output.clone());
+ *sw_last_sent_frame.borrow_mut() = Some(output);
+ // The pre-decoded frame is a real vend: without seeding
+ // this, an opening static hold would never be recorded.
+ sw_prev_vended = Some(current_frame);
}
- let decoder_type = if is_hw {
- DecoderType::FFmpegHardware
- } else {
- DecoderType::FFmpegSoftware
- };
- let init_result = DecoderInitResult {
+ let sw_decoder_type = DecoderType::FFmpegSoftware;
+ let sw_init_result = DecoderInitResult {
width: video_width,
height: video_height,
- decoder_type,
+ decoder_type: sw_decoder_type,
};
- let _ = ready_tx.send(Ok(init_result));
+ let _ = ready_tx.send(Ok(sw_init_result));
while let Ok(r) = rx.recv() {
+ if managed_stopped(managed.as_ref()) {
+ return;
+ }
let mut pending_requests: Vec<PendingRequest> = Vec::with_capacity(8);
let mut push_request =
|requested_time: f32, reply: oneshot::Sender<DecodedFrame>| {
@@ -882,6 +628,9 @@ impl FfmpegDecoder {
}
while let Ok(msg) = rx.try_recv() {
+ if managed_stopped(managed.as_ref()) {
+ return;
+ }
match msg {
VideoDecoderMessage::GetFrame(requested_time, _, reply) => {
push_request(requested_time, reply);
@@ -897,29 +646,31 @@ impl FfmpegDecoder {
reply,
} in pending_requests
{
+ if managed_stopped(managed.as_ref()) {
+ return;
+ }
if reply.is_closed() {
continue;
}
- let last_sent_number = last_sent_frame.borrow().as_ref().map(|f| f.number);
+ let last_sent_number = sw_last_sent_frame.borrow().as_ref().map(|f| f.number);
let is_backward_seek = last_sent_number
.map(|last| requested_frame < last)
.unwrap_or(false);
- if let Some(cached) = cache.get_mut(&requested_frame) {
- let data = cached.produce(&mut converter);
-
+ if let Some(cached) = sw_cache.get_mut(&requested_frame) {
+ let data = cached.produce(&mut sw_converter);
if reply.send(data.frame.clone()).is_err() {
log::warn!(
"FFmpeg '{name}': Failed to send cached frame {requested_frame}: receiver dropped"
);
}
- *last_sent_frame.borrow_mut() = Some(data);
+ *sw_last_sent_frame.borrow_mut() = Some(data);
continue;
}
if is_backward_seek {
- let best_cached_frame = cache
+ let best_cached_frame = sw_cache
.range(..=requested_frame)
.next_back()
.filter(|(k, _)| {
@@ -928,51 +679,54 @@ impl FfmpegDecoder {
.map(|(k, _)| *k);
if let Some(frame_num) = best_cached_frame
- && let Some(cached) = cache.get_mut(&frame_num)
+ && let Some(cached) = sw_cache.get_mut(&frame_num)
{
- let data = cached.produce(&mut converter);
- *last_sent_frame.borrow_mut() = Some(data.clone());
+ let data = cached.produce(&mut sw_converter);
+ *sw_last_sent_frame.borrow_mut() = Some(data.clone());
let _ = reply.send(data.frame);
continue;
}
if requested_frame <= MAX_FRAME_LOOKBACK_TOLERANCE
- && let Some(first_frame) = first_ever_frame.borrow().clone()
+ && let Some(first_frame) = sw_first_ever_frame.borrow().clone()
{
- *last_sent_frame.borrow_mut() = Some(first_frame.clone());
+ *sw_last_sent_frame.borrow_mut() = Some(first_frame.clone());
let _ = reply.send(first_frame.frame);
continue;
}
- let _ = this.reset(requested_time);
- frames = this.frames();
- *last_sent_frame.borrow_mut() = None;
- cache.clear();
- prev_vended = None;
+ if let Err(error) = sw_this.reset(requested_time)
+ && let Some(control) = &managed
+ {
+ control.fail(managed_error(
+ control,
+ ManagedVideoError::Seek(error.to_string()),
+ ));
+ return;
+ }
+ sw_frames = sw_this.frames();
+ *sw_last_sent_frame.borrow_mut() = None;
+ sw_cache.clear();
+ sw_prev_vended = None;
}
// Requests inside a KNOWN pts hole are answered with the
- // hole's start frame — the true VFR hold (the frame simply
- // stayed on screen) — without touching the decoder. This
- // keeps the post-hole frames cached and the reader parked,
- // however long the hole runs. Only recorded holes qualify: a
- // bare "some cached frame lies beyond the request" test would
- // also match disjoint cache islands left by seeks, and
- // serving stale content there would freeze playback.
+ // hole's start frame — the true VFR hold — without
+ // touching the decoder; see the hardware path above.
if !is_backward_seek
- && let Some(hole_start) = pts_holes
+ && let Some(hole_start) = sw_pts_holes
.range(..=requested_frame)
.next_back()
.filter(|&(_, &end)| requested_frame < end)
.map(|(&start, _)| start)
{
- let data = cache
+ let data = sw_cache
.get_mut(&hole_start)
- .map(|c| c.produce(&mut converter))
- .or_else(|| gap_hold.clone().filter(|h| h.number == hole_start));
+ .map(|c| c.produce(&mut sw_converter))
+ .or_else(|| sw_gap_hold.clone().filter(|h| h.number == hole_start));
if let Some(data) = data {
- gap_hold = Some(data.clone());
- *last_sent_frame.borrow_mut() = Some(data.clone());
+ sw_gap_hold = Some(data.clone());
+ *sw_last_sent_frame.borrow_mut() = Some(data.clone());
let _ = reply.send(data.frame);
continue;
}
@@ -986,7 +740,7 @@ impl FfmpegDecoder {
let reply_for_respond = reply_cell.clone();
let mut respond = {
- let last_sent_frame = last_sent_frame.clone();
+ let last_sent_frame = sw_last_sent_frame.clone();
Some(move |data: OutputFrame| {
let frame_number = data.number;
*last_sent_frame.borrow_mut() = Some(data.clone());
@@ -1003,10 +757,10 @@ impl FfmpegDecoder {
let cache_min = requested_frame.saturating_sub(FRAME_CACHE_SIZE as u32 / 2);
let cache_max = requested_frame + FRAME_CACHE_SIZE as u32 / 2;
- let is_far_forward = last_sent_frame.borrow().as_ref().map_or_else(
+ let is_far_forward = sw_last_sent_frame.borrow().as_ref().map_or_else(
|| {
- if first_ever_frame.borrow().is_some() {
- let first_frame_num = first_ever_frame
+ if sw_first_ever_frame.borrow().is_some() {
+ let first_frame_num = sw_first_ever_frame
.borrow()
.as_ref()
.map(|f| f.number)
@@ -1023,11 +777,19 @@ impl FfmpegDecoder {
);
if is_far_forward {
- let _ = this.reset(requested_time);
- frames = this.frames();
- *last_sent_frame.borrow_mut() = None;
- cache.clear();
- prev_vended = None;
+ if let Err(error) = sw_this.reset(requested_time)
+ && let Some(control) = &managed
+ {
+ control.fail(managed_error(
+ control,
+ ManagedVideoError::Seek(error.to_string()),
+ ));
+ return;
+ }
+ sw_frames = sw_this.frames();
+ *sw_last_sent_frame.borrow_mut() = None;
+ sw_cache.clear();
+ sw_prev_vended = None;
}
let mut exit = false;
@@ -1037,43 +799,54 @@ impl FfmpegDecoder {
// a pts hole.
let mut hold_candidate: Option<(u32, CachedFrame)> = None;
- for frame in &mut frames {
+ for frame in &mut sw_frames {
+ if let Some(control) = &managed {
+ if control.is_cancelled() {
+ control.fail(ManagedVideoError::Cancelled);
+ return;
+ }
+ if let Err(error) = &frame {
+ control.fail(ManagedVideoError::Decode(error.to_string()));
+ return;
+ }
+ }
if reply_cell.borrow().as_ref().is_none_or(|r| r.is_closed()) {
respond.take();
- // The frame just pulled is discarded: it breaks the
- // vend continuity that hole discovery relies on.
- prev_vended = None;
+ // The frame just pulled is discarded: it breaks
+ // the vend continuity that hole discovery
+ // relies on.
+ sw_prev_vended = None;
break;
}
let Ok(frame) = frame.map_err(|e| format!("read frame / {e}")) else {
- // A skipped frame breaks the vend continuity that
- // hole discovery relies on.
- prev_vended = None;
+ // A skipped frame breaks the vend continuity
+ // that hole discovery relies on.
+ sw_prev_vended = None;
continue;
};
let Some(pts) = frame.pts() else {
- prev_vended = None;
+ sw_prev_vended = None;
continue;
};
- let current_frame = pts_to_frame(pts - start_time, time_base, fps);
+ let current_frame = pts_to_frame(pts - sw_start_time, sw_time_base, fps);
- if let Some(prev) = prev_vended
+ if let Some(prev) = sw_prev_vended
&& current_frame > prev + 1
{
- record_pts_hole(&mut pts_holes, prev, current_frame);
+ record_pts_hole(&mut sw_pts_holes, prev, current_frame);
}
- prev_vended = Some(current_frame);
+ sw_prev_vended = Some(current_frame);
let mut cache_frame = CachedFrame::Raw {
frame,
number: current_frame,
};
- if first_ever_frame.borrow().is_none() {
- let output = cache_frame.produce(&mut converter);
- *first_ever_frame.borrow_mut() = Some(output);
+ if sw_first_ever_frame.borrow().is_none() {
+ let output = cache_frame.produce(&mut sw_converter);
+ *sw_first_ever_frame.borrow_mut() = Some(output);
}
let exceeds_cache_bounds = current_frame > cache_max;
@@ -1091,14 +864,14 @@ impl FfmpegDecoder {
}
{
- cache_frame.produce(&mut converter);
+ cache_frame.produce(&mut sw_converter);
insert_cached_frame(
- &mut cache,
+ &mut sw_cache,
current_frame,
cache_frame,
requested_frame,
- last_active_frame,
+ sw_last_active_frame,
MAX_FRAME_CACHE_BYTES,
);
@@ -1108,10 +881,10 @@ impl FfmpegDecoder {
if current_frame == requested_frame
&& let Some(respond) = respond.take()
{
- let output = cache
+ let output = sw_cache
.get_mut(&current_frame)
.unwrap()
- .produce(&mut converter);
+ .produce(&mut sw_converter);
(respond)(output);
break;
}
@@ -1123,18 +896,20 @@ impl FfmpegDecoder {
// stayed on screen, however long the gap is. Prefer the
// newest such frame among the cache, the hold candidate a
// reset re-vended, and the persistent gap hold.
- let cached_before =
- cache.range(..=requested_frame).next_back().map(|(&n, _)| n);
+ let cached_before = sw_cache
+ .range(..=requested_frame)
+ .next_back()
+ .map(|(&n, _)| n);
let candidate_number = hold_candidate
.as_ref()
.map(|(n, _)| *n)
.filter(|&n| n <= requested_frame);
- let hold_before = gap_hold.clone().filter(|h| {
- pts_holes.get(&h.number).is_some_and(|&end| {
+ let hold_before = sw_gap_hold.clone().filter(|h| {
+ sw_pts_holes.get(&h.number).is_some_and(|&end| {
h.number <= requested_frame && requested_frame < end
})
});
- let last_before = last_sent_frame
+ let last_before = sw_last_sent_frame
.borrow()
.as_ref()
.filter(|l| l.number <= requested_frame)
@@ -1153,10 +928,13 @@ impl FfmpegDecoder {
&& let Some(respond) = respond.take()
{
let output = if cached_before == Some(best_number) {
- cache.get_mut(&best_number).unwrap().produce(&mut converter)
+ sw_cache
+ .get_mut(&best_number)
+ .unwrap()
+ .produce(&mut sw_converter)
} else if candidate_number == Some(best_number) {
let (_, mut candidate) = hold_candidate.take().unwrap();
- candidate.produce(&mut converter)
+ candidate.produce(&mut sw_converter)
} else if hold_before.as_ref().map(|h| h.number)
== Some(best_number)
{
@@ -1164,21 +942,21 @@ impl FfmpegDecoder {
} else {
last_before.unwrap()
};
- gap_hold = Some(output.clone());
+ sw_gap_hold = Some(output.clone());
(respond)(output);
} else if let Some(respond) = respond.take() {
- let output = cache
+ let output = sw_cache
.get_mut(&current_frame)
.unwrap()
- .produce(&mut converter);
+ .produce(&mut sw_converter);
(respond)(output);
}
- // The request is answered; stop here so the next
- // sample stays in the decoder for the next
- // request. Pulling it now would discard it at the
- // reply guard and poison the vend continuity that
- // hole discovery relies on.
+ // The request is answered; stop here so the
+ // next sample stays in the decoder for the
+ // next request. Pulling it now would discard
+ // it at the reply guard and poison the vend
+ // continuity that hole discovery relies on.
break;
}
@@ -1189,25 +967,27 @@ impl FfmpegDecoder {
}
}
- last_active_frame = Some(requested_frame);
+ sw_last_active_frame = Some(requested_frame);
if let Some(respond) = respond.take() {
- // The newest frame at-or-before the request is always a valid
- // VFR hold, regardless of how far back it is — whether it is
- // cached, was re-vended below the cache window by a reset, or
- // is the persistent gap hold.
- let cached_before =
- cache.range(..=requested_frame).next_back().map(|(&n, _)| n);
+ // The newest frame at-or-before the request is always a
+ // valid VFR hold, regardless of how far back it is —
+ // whether it is cached, was re-vended below the cache
+ // window by a reset, or is the persistent gap hold.
+ let cached_before = sw_cache
+ .range(..=requested_frame)
+ .next_back()
+ .map(|(&n, _)| n);
let candidate_number = hold_candidate
.as_ref()
.map(|(n, _)| *n)
.filter(|&n| n <= requested_frame);
- let hold_before = gap_hold.clone().filter(|h| {
- pts_holes.get(&h.number).is_some_and(|&end| {
+ let hold_before = sw_gap_hold.clone().filter(|h| {
+ sw_pts_holes.get(&h.number).is_some_and(|&end| {
h.number <= requested_frame && requested_frame < end
})
});
- let last_before = last_sent_frame
+ let last_before = sw_last_sent_frame
.borrow()
.as_ref()
.filter(|l| l.number <= requested_frame)
@@ -1224,20 +1004,23 @@ impl FfmpegDecoder {
if let Some(best_number) = best_number {
let output = if cached_before == Some(best_number) {
- cache.get_mut(&best_number).unwrap().produce(&mut converter)
+ sw_cache
+ .get_mut(&best_number)
+ .unwrap()
+ .produce(&mut sw_converter)
} else if candidate_number == Some(best_number) {
let (_, mut candidate) = hold_candidate.take().unwrap();
- candidate.produce(&mut converter)
+ candidate.produce(&mut sw_converter)
} else if hold_before.as_ref().map(|h| h.number) == Some(best_number) {
hold_before.unwrap()
} else {
last_before.unwrap()
};
- gap_hold = Some(output.clone());
+ sw_gap_hold = Some(output.clone());
(respond)(output);
} else {
- let last_frame_clone = last_sent_frame.borrow().clone();
- let first_frame_clone = first_ever_frame.borrow().clone();
+ let last_frame_clone = sw_last_sent_frame.borrow().clone();
+ let first_frame_clone = sw_first_ever_frame.borrow().clone();
if let Some(last_frame) = last_frame_clone {
(respond)(last_frame);
} else if let Some(first_frame) = first_frame_clone {
@@ -1259,9 +1042,481 @@ impl FfmpegDecoder {
}
}
}
- });
- Ok(())
+ return;
+ }
+
+ if first_frame_result.is_none()
+ && let Some(control) = &managed
+ {
+ let error = control.fail(ManagedVideoError::NoFrames);
+ let _ = ready_tx.send(Err(error.to_string()));
+ return;
+ }
+ if let Some(frame) = first_frame_result {
+ let current_frame = pts_to_frame(frame.pts().unwrap_or(0) - start_time, time_base, fps);
+ let mut cache_frame = CachedFrame::Raw {
+ frame,
+ number: current_frame,
+ };
+ let output = cache_frame.produce(&mut converter);
+
+ cache.insert(current_frame, cache_frame);
+ *first_ever_frame.borrow_mut() = Some(output.clone());
+ *last_sent_frame.borrow_mut() = Some(output);
+ // The pre-decoded frame is a real vend: without seeding this,
+ // an opening static hold would never be recorded.
+ prev_vended = Some(current_frame);
+ info!(
+ "FFmpeg decoder '{}': pre-decoded first frame {} ({}x{})",
+ name, current_frame, video_width, video_height
+ );
+ }
+
+ let decoder_type = if is_hw {
+ DecoderType::FFmpegHardware
+ } else {
+ DecoderType::FFmpegSoftware
+ };
+ let init_result = DecoderInitResult {
+ width: video_width,
+ height: video_height,
+ decoder_type,
+ };
+ let _ = ready_tx.send(Ok(init_result));
+
+ while let Ok(r) = rx.recv() {
+ if managed_stopped(managed.as_ref()) {
+ return;
+ }
+ let mut pending_requests: Vec<PendingRequest> = Vec::with_capacity(8);
+ let mut push_request = |requested_time: f32, reply: oneshot::Sender<DecodedFrame>| {
+ if reply.is_closed() {
+ return;
+ }
+
+ let requested_time = requested_time.max(0.0);
+ let requested_frame = (requested_time * fps as f32).floor() as u32;
+
+ pending_requests.push(PendingRequest {
+ time: requested_time,
+ frame: requested_frame,
+ reply,
+ });
+ };
+
+ match r {
+ VideoDecoderMessage::GetFrame(requested_time, _, reply) => {
+ push_request(requested_time, reply);
+ }
+ }
+
+ while let Ok(msg) = rx.try_recv() {
+ if managed_stopped(managed.as_ref()) {
+ return;
+ }
+ match msg {
+ VideoDecoderMessage::GetFrame(requested_time, _, reply) => {
+ push_request(requested_time, reply);
+ }
+ }
+ }
+
+ pending_requests.sort_by_key(|r| r.frame);
+
+ for PendingRequest {
+ time: requested_time,
+ frame: requested_frame,
+ reply,
+ } in pending_requests
+ {
+ if managed_stopped(managed.as_ref()) {
+ return;
+ }
+ if reply.is_closed() {
+ continue;
+ }
+
+ let last_sent_number = last_sent_frame.borrow().as_ref().map(|f| f.number);
+ let is_backward_seek = last_sent_number
+ .map(|last| requested_frame < last)
+ .unwrap_or(false);
+
+ if let Some(cached) = cache.get_mut(&requested_frame) {
+ let data = cached.produce(&mut converter);
+
+ if reply.send(data.frame.clone()).is_err() {
+ log::warn!(
+ "FFmpeg '{name}': Failed to send cached frame {requested_frame}: receiver dropped"
+ );
+ }
+ *last_sent_frame.borrow_mut() = Some(data);
+ continue;
+ }
+
+ if is_backward_seek {
+ let best_cached_frame = cache
+ .range(..=requested_frame)
+ .next_back()
+ .filter(|(k, _)| {
+ requested_frame.saturating_sub(**k) <= MAX_FRAME_LOOKBACK_TOLERANCE
+ })
+ .map(|(k, _)| *k);
+
+ if let Some(frame_num) = best_cached_frame
+ && let Some(cached) = cache.get_mut(&frame_num)
+ {
+ let data = cached.produce(&mut converter);
+ *last_sent_frame.borrow_mut() = Some(data.clone());
+ let _ = reply.send(data.frame);
+ continue;
+ }
+
+ if requested_frame <= MAX_FRAME_LOOKBACK_TOLERANCE
+ && let Some(first_frame) = first_ever_frame.borrow().clone()
+ {
+ *last_sent_frame.borrow_mut() = Some(first_frame.clone());
+ let _ = reply.send(first_frame.frame);
+ continue;
+ }
+
+ if let Err(error) = this.reset(requested_time)
+ && let Some(control) = &managed
+ {
+ control.fail(managed_error(
+ control,
+ ManagedVideoError::Seek(error.to_string()),
+ ));
+ return;
+ }
+ frames = this.frames();
+ *last_sent_frame.borrow_mut() = None;
+ cache.clear();
+ prev_vended = None;
+ }
+
+ // Requests inside a KNOWN pts hole are answered with the
+ // hole's start frame — the true VFR hold (the frame simply
+ // stayed on screen) — without touching the decoder. This
+ // keeps the post-hole frames cached and the reader parked,
+ // however long the hole runs. Only recorded holes qualify: a
+ // bare "some cached frame lies beyond the request" test would
+ // also match disjoint cache islands left by seeks, and
+ // serving stale content there would freeze playback.
+ if !is_backward_seek
+ && let Some(hole_start) = pts_holes
+ .range(..=requested_frame)
+ .next_back()
+ .filter(|&(_, &end)| requested_frame < end)
+ .map(|(&start, _)| start)
+ {
+ let data = cache
+ .get_mut(&hole_start)
+ .map(|c| c.produce(&mut converter))
+ .or_else(|| gap_hold.clone().filter(|h| h.number == hole_start));
+ if let Some(data) = data {
+ gap_hold = Some(data.clone());
+ *last_sent_frame.borrow_mut() = Some(data.clone());
+ let _ = reply.send(data.frame);
+ continue;
+ }
+ }
+
+ if reply.is_closed() {
+ continue;
+ }
+
+ let reply_cell = Rc::new(RefCell::new(Some(reply)));
+ let reply_for_respond = reply_cell.clone();
+
+ let mut respond = {
+ let last_sent_frame = last_sent_frame.clone();
+ Some(move |data: OutputFrame| {
+ let frame_number = data.number;
+ *last_sent_frame.borrow_mut() = Some(data.clone());
+ if let Some(reply) = reply_for_respond.borrow_mut().take()
+ && reply.send(data.frame).is_err()
+ {
+ log::warn!(
+ "Failed to send decoded frame {frame_number}: receiver dropped"
+ );
+ }
+ })
+ };
+
+ let cache_min = requested_frame.saturating_sub(FRAME_CACHE_SIZE as u32 / 2);
+ let cache_max = requested_frame + FRAME_CACHE_SIZE as u32 / 2;
+
+ let is_far_forward = last_sent_frame.borrow().as_ref().map_or_else(
+ || {
+ if first_ever_frame.borrow().is_some() {
+ let first_frame_num = first_ever_frame
+ .borrow()
+ .as_ref()
+ .map(|f| f.number)
+ .unwrap_or(0);
+ requested_frame.saturating_sub(first_frame_num)
+ > FRAME_CACHE_SIZE as u32
+ } else {
+ requested_frame != 0
+ }
+ },
+ |last| requested_frame.saturating_sub(last.number) > FRAME_CACHE_SIZE as u32,
+ );
+
+ if is_far_forward {
+ if let Err(error) = this.reset(requested_time)
+ && let Some(control) = &managed
+ {
+ control.fail(managed_error(
+ control,
+ ManagedVideoError::Seek(error.to_string()),
+ ));
+ return;
+ }
+ frames = this.frames();
+ *last_sent_frame.borrow_mut() = None;
+ cache.clear();
+ prev_vended = None;
+ }
+
+ let mut exit = false;
+ // Newest vended frame below the cache window: after a reset
+ // the reader re-vends from the keyframe before the request,
+ // and that frame is the true VFR hold for a request inside
+ // a pts hole.
+ let mut hold_candidate: Option<(u32, CachedFrame)> = None;
+
+ for frame in &mut frames {
+ if let Some(control) = &managed {
+ if control.is_cancelled() {
+ control.fail(ManagedVideoError::Cancelled);
+ return;
+ }
+ if let Err(error) = &frame {
+ control.fail(ManagedVideoError::Decode(error.to_string()));
+ return;
+ }
+ }
+ if reply_cell.borrow().as_ref().is_none_or(|r| r.is_closed()) {
+ respond.take();
+ // The frame just pulled is discarded: it breaks the
+ // vend continuity that hole discovery relies on.
+ prev_vended = None;
+ break;
+ }
+
+ let Ok(frame) = frame.map_err(|e| format!("read frame / {e}")) else {
+ // A skipped frame breaks the vend continuity that
+ // hole discovery relies on.
+ prev_vended = None;
+ continue;
+ };
+
+ let Some(pts) = frame.pts() else {
+ prev_vended = None;
+ continue;
+ };
+ let current_frame = pts_to_frame(pts - start_time, time_base, fps);
+
+ if let Some(prev) = prev_vended
+ && current_frame > prev + 1
+ {
+ record_pts_hole(&mut pts_holes, prev, current_frame);
+ }
+ prev_vended = Some(current_frame);
+
+ let mut cache_frame = CachedFrame::Raw {
+ frame,
+ number: current_frame,
+ };
+
+ if first_ever_frame.borrow().is_none() {
+ let output = cache_frame.produce(&mut converter);
+ *first_ever_frame.borrow_mut() = Some(output);
+ }
+
+ let exceeds_cache_bounds = current_frame > cache_max;
+ let too_small_for_cache_bounds = current_frame < cache_min;
+
+ if too_small_for_cache_bounds {
+ // Keep the newest pre-request frame as the VFR hold
+ // candidate instead of discarding it; a frame below
+ // the cache window can never exceed the request, so
+ // nothing else in this iteration applies to it.
+ if current_frame <= requested_frame {
+ hold_candidate = Some((current_frame, cache_frame));
+ }
+ continue;
+ }
+
+ {
+ cache_frame.produce(&mut converter);
+
+ 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
+ // at-or-before holds for later gap requests.
+ if current_frame == requested_frame
+ && let Some(respond) = respond.take()
+ {
+ let output = cache
+ .get_mut(&current_frame)
+ .unwrap()
+ .produce(&mut converter);
+ (respond)(output);
+ break;
+ }
+ }
+
+ if current_frame > requested_frame && respond.is_some() {
+ // A frame at-or-before the request is the true content for
+ // that time in a VFR recording: a pts gap means the frame
+ // stayed on screen, however long the gap is. Prefer the
+ // newest such frame among the cache, the hold candidate a
+ // reset re-vended, and the persistent gap hold.
+ let cached_before =
+ cache.range(..=requested_frame).next_back().map(|(&n, _)| n);
+ let candidate_number = hold_candidate
+ .as_ref()
+ .map(|(n, _)| *n)
+ .filter(|&n| n <= requested_frame);
+ let hold_before = gap_hold.clone().filter(|h| {
+ pts_holes.get(&h.number).is_some_and(|&end| {
+ h.number <= requested_frame && requested_frame < end
+ })
+ });
+ let last_before = last_sent_frame
+ .borrow()
+ .as_ref()
+ .filter(|l| l.number <= requested_frame)
+ .cloned();
+ let best_number = [
+ cached_before,
+ candidate_number,
+ hold_before.as_ref().map(|h| h.number),
+ last_before.as_ref().map(|l| l.number),
+ ]
+ .into_iter()
+ .flatten()
+ .max();
+
+ if let Some(best_number) = best_number
+ && let Some(respond) = respond.take()
+ {
+ let output = if cached_before == Some(best_number) {
+ cache.get_mut(&best_number).unwrap().produce(&mut converter)
+ } else if candidate_number == Some(best_number) {
+ let (_, mut candidate) = hold_candidate.take().unwrap();
+ candidate.produce(&mut converter)
+ } else if hold_before.as_ref().map(|h| h.number) == Some(best_number) {
+ hold_before.unwrap()
+ } else {
+ last_before.unwrap()
+ };
+ gap_hold = Some(output.clone());
+ (respond)(output);
+ } else if let Some(respond) = respond.take() {
+ let output = cache
+ .get_mut(&current_frame)
+ .unwrap()
+ .produce(&mut converter);
+ (respond)(output);
+ }
+
+ // The request is answered; stop here so the next
+ // sample stays in the decoder for the next
+ // request. Pulling it now would discard it at the
+ // reply guard and poison the vend continuity that
+ // hole discovery relies on.
+ break;
+ }
+
+ exit = exit || exceeds_cache_bounds;
+
+ if exit {
+ break;
+ }
+ }
+
+ last_active_frame = Some(requested_frame);
+
+ if let Some(respond) = respond.take() {
+ // The newest frame at-or-before the request is always a valid
+ // VFR hold, regardless of how far back it is — whether it is
+ // cached, was re-vended below the cache window by a reset, or
+ // is the persistent gap hold.
+ let cached_before =
+ cache.range(..=requested_frame).next_back().map(|(&n, _)| n);
+ let candidate_number = hold_candidate
+ .as_ref()
+ .map(|(n, _)| *n)
+ .filter(|&n| n <= requested_frame);
+ let hold_before = gap_hold.clone().filter(|h| {
+ pts_holes.get(&h.number).is_some_and(|&end| {
+ h.number <= requested_frame && requested_frame < end
+ })
+ });
+ let last_before = last_sent_frame
+ .borrow()
+ .as_ref()
+ .filter(|l| l.number <= requested_frame)
+ .cloned();
+ let best_number = [
+ cached_before,
+ candidate_number,
+ hold_before.as_ref().map(|h| h.number),
+ last_before.as_ref().map(|l| l.number),
+ ]
+ .into_iter()
+ .flatten()
+ .max();
+
+ if let Some(best_number) = best_number {
+ let output = if cached_before == Some(best_number) {
+ cache.get_mut(&best_number).unwrap().produce(&mut converter)
+ } else if candidate_number == Some(best_number) {
+ let (_, mut candidate) = hold_candidate.take().unwrap();
+ candidate.produce(&mut converter)
+ } else if hold_before.as_ref().map(|h| h.number) == Some(best_number) {
+ hold_before.unwrap()
+ } else {
+ last_before.unwrap()
+ };
+ gap_hold = Some(output.clone());
+ (respond)(output);
+ } else {
+ let last_frame_clone = last_sent_frame.borrow().clone();
+ let first_frame_clone = first_ever_frame.borrow().clone();
+ if let Some(last_frame) = last_frame_clone {
+ (respond)(last_frame);
+ } else if let Some(first_frame) = first_frame_clone {
+ (respond)(first_frame);
+ } else {
+ let black_frame_data =
+ vec![0u8; (video_width * video_height * 4) as usize];
+ let black_frame = OutputFrame {
+ number: requested_frame,
+ frame: DecodedFrame::new_with_arc(
+ Arc::new(black_frame_data),
+ video_width,
+ video_height,
+ ),
+ };
+ (respond)(black_frame);
+ }
+ }
+ }
+ }
+ }
}
}
@@ -1385,3 +1640,46 @@ mod cache_tests {
// }
// }
// }
+
+#[cfg(test)]
+mod managed_frame_tests {
+ use super::*;
+ use std::cell::Cell;
+
+ #[test]
+ fn managed_first_frame_stops_after_one_sticky_error() {
+ let control = ManagedVideoControl::new();
+ let pulls = Cell::new(0);
+ let mut frames = std::iter::from_fn(|| {
+ pulls.set(pulls.get() + 1);
+ Some(Err(ffmpeg::Error::InvalidData))
+ });
+ assert!(matches!(
+ first_frame(&mut frames, Some(&control)),
+ Err(ManagedVideoError::Decode(_))
+ ));
+ assert_eq!(pulls.get(), 1);
+ assert!(first_frame(&mut frames, Some(&control)).is_err());
+ assert_eq!(pulls.get(), 1);
+ }
+
+ #[test]
+ fn ordinary_first_frame_still_skips_recoverable_errors() {
+ let mut frames = [Err(ffmpeg::Error::InvalidData), Ok(frame::Video::empty())].into_iter();
+ assert!(first_frame(&mut frames, None).unwrap().is_some());
+ assert!(frames.next().is_none());
+ }
+
+ #[test]
+ fn cancelled_first_frame_never_reads_or_reports_eof() {
+ let control = ManagedVideoControl::new();
+ control.cancel();
+ let mut frames = std::iter::from_fn(|| {
+ panic!("Cancellation must be observed before requesting another frame")
+ });
+ assert!(matches!(
+ first_frame(&mut frames, Some(&control)),
+ Err(ManagedVideoError::Cancelled)
+ ));
+ }
+}
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index 13a206476..296747b6c 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -757,6 +757,403 @@ impl AsyncVideoDecoderHandle {
}
}
+#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
+pub enum ManagedVideoError {
+ #[error("Managed video initialization failed: {0}")]
+ Initialization(String),
+ #[error("Managed video decode failed: {0}")]
+ Decode(String),
+ #[error("Managed video seek failed: {0}")]
+ Seek(String),
+ #[error("Managed video contains no decodable frames")]
+ NoFrames,
+ #[error("Managed video was cancelled")]
+ Cancelled,
+ #[error("Managed video worker panicked")]
+ WorkerPanicked,
+ #[error("Managed video worker exited")]
+ WorkerExited,
+ #[error("Managed video is not initialized")]
+ NotReady,
+ #[error("Managed video initialization timed out")]
+ InitializationTimeout,
+ #[error("Managed video frame request timed out")]
+ FrameTimeout,
+}
+
+#[derive(Clone, Debug)]
+pub struct ManagedVideoExit {
+ pub terminal: ManagedVideoError,
+}
+
+#[derive(Clone, Default)]
+struct ManagedVideoState {
+ terminal: Option<ManagedVideoError>,
+ exit: Option<ManagedVideoExit>,
+}
+
+struct ManagedVideoControl {
+ cancelled: std::sync::atomic::AtomicBool,
+ state: tokio::sync::watch::Sender<ManagedVideoState>,
+ join: std::sync::Mutex<Option<std::thread::JoinHandle<()>>>,
+}
+
+impl ManagedVideoControl {
+ fn new() -> Arc<Self> {
+ let (state, _) = tokio::sync::watch::channel(ManagedVideoState::default());
+ Arc::new(Self {
+ cancelled: std::sync::atomic::AtomicBool::new(false),
+ state,
+ join: std::sync::Mutex::new(None),
+ })
+ }
+
+ fn is_cancelled(&self) -> bool {
+ self.cancelled.load(std::sync::atomic::Ordering::Acquire)
+ }
+
+ fn terminal(&self) -> Option<ManagedVideoError> {
+ self.state.borrow().terminal.clone()
+ }
+
+ fn fail(&self, error: ManagedVideoError) -> ManagedVideoError {
+ self.state.send_if_modified(|state| {
+ if state.terminal.is_some() {
+ false
+ } else {
+ state.terminal = Some(error.clone());
+ true
+ }
+ });
+ self.terminal().unwrap_or(error)
+ }
+
+ fn cancel(&self) {
+ self.cancelled
+ .store(true, std::sync::atomic::Ordering::Release);
+ self.fail(ManagedVideoError::Cancelled);
+ }
+
+ fn run_worker(&self, work: impl FnOnce()) {
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work));
+ self.finished_after_drop(result.is_err());
+ }
+
+ fn finished_after_drop(&self, panicked: bool) {
+ self.fail(if panicked {
+ ManagedVideoError::WorkerPanicked
+ } else if self.is_cancelled() {
+ ManagedVideoError::Cancelled
+ } else {
+ ManagedVideoError::WorkerExited
+ });
+ }
+
+ fn joined(&self, panicked: bool) {
+ self.finished_after_drop(panicked);
+ self.state.send_modify(|state| {
+ state.exit = Some(ManagedVideoExit {
+ terminal: state
+ .terminal
+ .clone()
+ .unwrap_or(ManagedVideoError::WorkerExited),
+ });
+ });
+ }
+}
+
+#[derive(Clone)]
+pub struct ManagedVideoStopHandle {
+ control: Arc<ManagedVideoControl>,
+ wake: mpsc::Sender<VideoDecoderMessage>,
+}
+
+impl ManagedVideoStopHandle {
+ pub fn cancel(&self) {
+ self.control.cancel();
+ let (reply, receiver) = oneshot::channel();
+ drop(receiver);
+ let _ = self.wake.send(VideoDecoderMessage::GetFrame(0.0, 0, reply));
+ }
+
+ pub fn terminal_error(&self) -> Option<ManagedVideoError> {
+ self.control.terminal()
+ }
+
+ pub async fn wait_for_terminal(&self) -> ManagedVideoError {
+ let mut state = self.control.state.subscribe();
+ loop {
+ if let Some(error) = state.borrow_and_update().terminal.clone() {
+ return error;
+ }
+ state
+ .changed()
+ .await
+ .expect("Managed worker owner retains its status sender");
+ }
+ }
+
+ pub async fn stop_and_wait(&self) -> ManagedVideoExit {
+ self.cancel();
+ let join = self
+ .control
+ .join
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take();
+ if let Some(join) = join {
+ let control = self.control.clone();
+ drop(tokio::task::spawn_blocking(move || {
+ let panicked = join.join().is_err();
+ control.joined(panicked);
+ }));
+ }
+ let mut state = self.control.state.subscribe();
+ loop {
+ if let Some(exit) = state.borrow_and_update().exit.clone() {
+ return exit;
+ }
+ state
+ .changed()
+ .await
+ .expect("Managed worker owner retains its status sender");
+ }
+ }
+}
+
+struct CancelManagedReadiness(Option<ManagedVideoStopHandle>);
+
+impl Drop for CancelManagedReadiness {
+ fn drop(&mut self) {
+ if let Some(worker) = self.0.take() {
+ worker.cancel();
+ }
+ }
+}
+
+struct ManagedVideoInput {
+ source: cap_enc_ffmpeg::RelocatableSource,
+ paths: Vec<PathBuf>,
+}
+
+pub struct ManagedVideoDecoder {
+ worker: ManagedVideoStopHandle,
+ ready: Option<oneshot::Receiver<Result<DecoderInitResult, String>>>,
+ decoder: Option<AsyncVideoDecoderHandle>,
+ offset: f64,
+ max_fallback_distance: u32,
+}
+
+impl ManagedVideoDecoder {
+ pub fn with_max_fallback_distance(mut self, max_fallback_distance: u32) -> Self {
+ self.max_fallback_distance = max_fallback_distance.min(DEFAULT_MAX_FALLBACK_DISTANCE);
+ if let Some(decoder) = self.decoder.as_mut() {
+ decoder.max_fallback_distance = self.max_fallback_distance;
+ }
+ self
+ }
+
+ pub fn stop_handle(&self) -> ManagedVideoStopHandle {
+ self.worker.clone()
+ }
+
+ pub fn terminal_error(&self) -> Option<ManagedVideoError> {
+ self.worker.terminal_error()
+ }
+
+ pub async fn wait_ready(&mut self) -> Result<DecoderStatus, ManagedVideoError> {
+ if let Some(error) = self.terminal_error() {
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ if let Some(decoder) = &self.decoder {
+ return Ok(decoder.status.clone());
+ }
+ let ready = self.ready.as_mut().ok_or(ManagedVideoError::NotReady)?;
+ let mut cancellation = CancelManagedReadiness(Some(self.worker.clone()));
+ let result = tokio::time::timeout(Duration::from_secs(30), ready).await;
+ cancellation.0 = None;
+ let _ = self.ready.take();
+ let initialized = match result {
+ Ok(Ok(Ok(initialized))) => initialized,
+ result => {
+ let error = match result {
+ Ok(Ok(Err(error))) => ManagedVideoError::Initialization(error),
+ Ok(Err(_)) => ManagedVideoError::WorkerExited,
+ Err(_) => ManagedVideoError::InitializationTimeout,
+ Ok(Ok(Ok(_))) => unreachable!(),
+ };
+ let error = self.worker.control.fail(error);
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ };
+ if let Some(error) = self.terminal_error() {
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ let status = DecoderStatus {
+ decoder_type: initialized.decoder_type,
+ video_width: initialized.width,
+ video_height: initialized.height,
+ fallback_reason: None,
+ };
+ self.decoder = Some(AsyncVideoDecoderHandle {
+ sender: self.worker.wake.clone(),
+ offset: self.offset,
+ status: status.clone(),
+ max_fallback_distance: self.max_fallback_distance,
+ });
+ Ok(status)
+ }
+
+ pub fn decoder_status(&self) -> Option<&DecoderStatus> {
+ self.decoder
+ .as_ref()
+ .map(AsyncVideoDecoderHandle::decoder_status)
+ }
+
+ pub async fn get_frame(&self, time: f32) -> Result<DecodedFrame, ManagedVideoError> {
+ if let Some(error) = self.terminal_error() {
+ return Err(error);
+ }
+ let decoder = self.decoder.as_ref().ok_or(ManagedVideoError::NotReady)?;
+ self.get_frame_with_timeout(
+ time,
+ decoder.normal_timeout_ms(),
+ decoder.max_fallback_distance,
+ )
+ .await
+ }
+
+ pub async fn get_frame_initial(&self, time: f32) -> Result<DecodedFrame, ManagedVideoError> {
+ if let Some(error) = self.terminal_error() {
+ return Err(error);
+ }
+ let decoder = self.decoder.as_ref().ok_or(ManagedVideoError::NotReady)?;
+ self.get_frame_with_timeout(
+ time,
+ AsyncVideoDecoderHandle::INITIAL_SEEK_TIMEOUT_MS,
+ decoder
+ .max_fallback_distance
+ .min(AsyncVideoDecoderHandle::INITIAL_MAX_FALLBACK_DISTANCE),
+ )
+ .await
+ }
+
+ async fn get_frame_with_timeout(
+ &self,
+ time: f32,
+ timeout_ms: u64,
+ max_fallback_distance: u32,
+ ) -> Result<DecodedFrame, ManagedVideoError> {
+ if let Some(error) = self.terminal_error() {
+ return Err(error);
+ }
+ let decoder = self.decoder.as_ref().ok_or(ManagedVideoError::NotReady)?;
+ let (reply, mut receiver) = oneshot::channel();
+ let mut state = self.worker.control.state.subscribe();
+ if decoder
+ .sender
+ .send(VideoDecoderMessage::GetFrame(
+ decoder.get_time(time),
+ max_fallback_distance,
+ reply,
+ ))
+ .is_err()
+ {
+ let error = self.worker.control.fail(ManagedVideoError::WorkerExited);
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ let timeout = tokio::time::sleep(Duration::from_millis(timeout_ms));
+ tokio::pin!(timeout);
+ loop {
+ if let Some(error) = self.terminal_error() {
+ return Err(error);
+ }
+ tokio::select! {
+ result = &mut receiver => {
+ if let Some(error) = self.terminal_error() {
+ return Err(error);
+ }
+ match result {
+ Ok(frame) => return Ok(frame),
+ Err(_) => {
+ let error = self.worker.control.fail(ManagedVideoError::WorkerExited);
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ }
+ }
+ _ = &mut timeout => {
+ let error = self.worker.control.fail(ManagedVideoError::FrameTimeout);
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ changed = state.changed() => {
+ changed.expect("Managed worker owner retains its status sender");
+ }
+ }
+ }
+ }
+
+ pub async fn stop_and_wait(&self) -> ManagedVideoExit {
+ self.worker.stop_and_wait().await
+ }
+}
+
+impl Drop for ManagedVideoDecoder {
+ fn drop(&mut self) {
+ self.worker.cancel();
+ }
+}
+
+pub fn spawn_managed_decoder<'a>(
+ name: &'static str,
+ source: cap_enc_ffmpeg::RelocatableSource,
+ paths: impl IntoIterator<Item = &'a std::path::Path>,
+ fps: u32,
+ offset: f64,
+ use_hw_acceleration: bool,
+) -> Result<ManagedVideoDecoder, ManagedVideoError> {
+ let input = ManagedVideoInput {
+ source,
+ paths: paths
+ .into_iter()
+ .map(std::path::Path::to_path_buf)
+ .collect(),
+ };
+ let control = ManagedVideoControl::new();
+ let (sender, receiver) = mpsc::channel();
+ let (ready_tx, ready_rx) = oneshot::channel();
+ let worker = ManagedVideoStopHandle {
+ control: control.clone(),
+ wake: sender,
+ };
+ let join = ffmpeg::FfmpegDecoder::spawn_managed(
+ name,
+ input,
+ fps,
+ receiver,
+ ready_tx,
+ use_hw_acceleration,
+ control.clone(),
+ )
+ .map_err(ManagedVideoError::Initialization)?;
+ *control
+ .join
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(join);
+ Ok(ManagedVideoDecoder {
+ worker,
+ ready: Some(ready_rx),
+ decoder: None,
+ offset,
+ max_fallback_distance: DEFAULT_MAX_FALLBACK_DISTANCE,
+ })
+}
+
#[cfg(target_os = "macos")]
async fn spawn_ffmpeg_decoder(
name: &'static str,
@@ -813,9 +1210,11 @@ pub async fn spawn_decoder(
#[cfg(target_os = "macos")]
{
- if force_ffmpeg {
+ if force_ffmpeg || path.is_dir() {
info!(
- "Video '{}' using FFmpeg decoder (forced via experimental setting)",
+ force_ffmpeg,
+ segmented = path.is_dir(),
+ "Video '{}' using FFmpeg decoder",
name
);
return spawn_ffmpeg_decoder(name, path, fps, offset, timeout_duration, &path_display)
@@ -1188,3 +1587,996 @@ mod tests {
}
}
}
+
+#[cfg(test)]
+mod managed_worker_tests {
+ mod segment_terminal_tests {
+ use super::*;
+ use crate::{
+ ManagedRecordingSegmentDecoders, ManagedSegmentVideoError, ManagedSegmentVideoExit,
+ };
+
+ enum TerminalWorkerCommand {
+ ReplyFrame,
+ Fail(ManagedVideoError),
+ Finish,
+ }
+
+ struct TerminalWorkerDriver {
+ worker: ManagedVideoStopHandle,
+ commands: mpsc::Sender<TerminalWorkerCommand>,
+ release: mpsc::Sender<()>,
+ dropped: Arc<AtomicBool>,
+ }
+
+ impl TerminalWorkerDriver {
+ fn reply_frame(&self) {
+ self.commands
+ .send(TerminalWorkerCommand::ReplyFrame)
+ .unwrap();
+ }
+
+ fn fail(&self, error: ManagedVideoError) {
+ self.commands
+ .send(TerminalWorkerCommand::Fail(error))
+ .unwrap();
+ }
+
+ fn release(&self) {
+ self.commands.send(TerminalWorkerCommand::Finish).unwrap();
+ self.release.send(()).unwrap();
+ }
+
+ fn assert_healthy(&self) {
+ assert!(!self.worker.control.is_cancelled());
+ assert_eq!(self.worker.terminal_error(), None);
+ assert!(!self.dropped.load(Ordering::Acquire));
+ assert!(self.worker.control.state.borrow().exit.is_none());
+ }
+ }
+
+ impl Drop for TerminalWorkerDriver {
+ fn drop(&mut self) {
+ self.worker.cancel();
+ let _ = self.commands.send(TerminalWorkerCommand::Finish);
+ let _ = self.release.send(());
+ }
+ }
+
+ fn terminal_worker() -> (ManagedVideoDecoder, TerminalWorkerDriver) {
+ let control = ManagedVideoControl::new();
+ let (wake, requests) = mpsc::channel();
+ let (commands, requested_commands) = mpsc::channel();
+ let (release, released) = mpsc::channel();
+ let (ready_sender, ready_receiver) = oneshot::channel();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let worker_control = control.clone();
+ let worker_dropped = dropped.clone();
+ let join = std::thread::spawn(move || {
+ worker_control.run_worker(|| {
+ let _resource = DropSignal(worker_dropped);
+ let _ = ready_sender.send(Ok(DecoderInitResult {
+ width: 2,
+ height: 2,
+ decoder_type: DecoderType::FFmpegSoftware,
+ }));
+ while let Ok(command) = requested_commands.recv() {
+ match command {
+ TerminalWorkerCommand::ReplyFrame => {
+ if let Ok(VideoDecoderMessage::GetFrame(_, _, reply)) =
+ requests.recv()
+ {
+ let _ = reply.send(DecodedFrame::new(vec![73; 16], 2, 2));
+ }
+ }
+ TerminalWorkerCommand::Fail(error) => {
+ worker_control.fail(error);
+ }
+ TerminalWorkerCommand::Finish => break,
+ }
+ }
+ let _ = released.recv();
+ });
+ });
+ *control.join.lock().unwrap() = Some(join);
+ let worker = ManagedVideoStopHandle { control, wake };
+ let mut decoder = pending_decoder(worker.clone());
+ decoder.ready = Some(ready_receiver);
+ (
+ decoder,
+ TerminalWorkerDriver {
+ worker,
+ commands,
+ release,
+ dropped,
+ },
+ )
+ }
+
+ async fn ready_segment() -> (
+ ManagedRecordingSegmentDecoders,
+ TerminalWorkerDriver,
+ TerminalWorkerDriver,
+ ) {
+ let (display, display_driver) = terminal_worker();
+ let (camera, camera_driver) = terminal_worker();
+ let mut segment = ManagedRecordingSegmentDecoders::from_test_workers(display, camera);
+ let status = tokio::time::timeout(Duration::from_secs(5), segment.wait_ready())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ (status.display.video_width, status.display.video_height),
+ (2, 2)
+ );
+ assert_eq!(
+ status.camera.unwrap().decoder_type,
+ DecoderType::FFmpegSoftware
+ );
+ display_driver.assert_healthy();
+ camera_driver.assert_healthy();
+ (segment, display_driver, camera_driver)
+ }
+
+ async fn reply_frames(
+ segment: &ManagedRecordingSegmentDecoders,
+ display: &TerminalWorkerDriver,
+ camera: &TerminalWorkerDriver,
+ ) -> crate::DecodedSegmentFrames {
+ display.reply_frame();
+ camera.reply_frame();
+ let frames = tokio::time::timeout(
+ Duration::from_secs(5),
+ segment.get_frames(0.0, true, true, Default::default()),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ for frame in [&frames.screen_frame, &frames.camera_frame] {
+ let frame = frame.as_ref().unwrap();
+ assert_eq!(
+ (frame.width(), frame.height(), frame.byte_len()),
+ (2, 2, 16)
+ );
+ assert_eq!(frame.data(), &[73; 16]);
+ }
+ frames
+ }
+
+ async fn join_both(
+ segment: &ManagedRecordingSegmentDecoders,
+ display: &TerminalWorkerDriver,
+ camera: &TerminalWorkerDriver,
+ ) -> ManagedSegmentVideoExit {
+ let stops = segment.stop_handles();
+ let mut first = Box::pin(segment.stop_and_wait());
+ let mut second = Box::pin(stops.stop_and_wait());
+ assert!(futures::poll!(&mut first).is_pending());
+ assert!(futures::poll!(&mut second).is_pending());
+ for driver in [display, camera] {
+ assert!(!driver.dropped.load(Ordering::Acquire));
+ assert!(driver.worker.control.state.borrow().exit.is_none());
+ }
+ display.release();
+ camera.release();
+ let (first, second) = tokio::time::timeout(Duration::from_secs(5), async {
+ tokio::join!(first, second)
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ first.display.as_ref().unwrap().terminal,
+ second.display.unwrap().terminal
+ );
+ assert_eq!(
+ first.camera.as_ref().unwrap().terminal,
+ second.camera.unwrap().terminal
+ );
+ for driver in [display, camera] {
+ assert!(driver.dropped.load(Ordering::Acquire));
+ assert!(driver.worker.control.state.borrow().exit.is_some());
+ assert!(driver.worker.control.join.lock().unwrap().is_none());
+ }
+ first
+ }
+
+ async fn idle_terminal_failure(camera_fails: bool, decoded_frame_retained: bool) {
+ let (segment, display, camera) = ready_segment().await;
+ let retained = if decoded_frame_retained {
+ Some(reply_frames(&segment, &display, &camera).await)
+ } else {
+ None
+ };
+ let mut observer = Box::pin(segment.wait_for_terminal());
+ assert!(futures::poll!(&mut observer).is_pending());
+ let native_error = ManagedVideoError::Decode("Controlled idle source failure".into());
+ let expected = if camera_fails {
+ camera.fail(native_error.clone());
+ ManagedSegmentVideoError::Camera(native_error.clone())
+ } else {
+ display.fail(native_error.clone());
+ ManagedSegmentVideoError::Display(native_error.clone())
+ };
+ let observed = tokio::time::timeout(Duration::from_secs(5), observer)
+ .await
+ .unwrap();
+ assert_eq!(observed, expected);
+ assert_eq!(segment.terminal_error(), Some(expected.clone()));
+ let healthy = if camera_fails { &display } else { &camera };
+ healthy.assert_healthy();
+ assert!(matches!(
+ segment.get_frames(0.0, false, false, Default::default()).await,
+ Err(actual) if actual == expected
+ ));
+ assert_eq!(segment.wait_for_terminal().await, expected);
+ let exit = join_both(&segment, &display, &camera).await;
+ let (failed, cancelled) = if camera_fails {
+ (exit.camera.unwrap(), exit.display.unwrap())
+ } else {
+ (exit.display.unwrap(), exit.camera.unwrap())
+ };
+ assert_eq!(failed.terminal, native_error);
+ assert_eq!(cancelled.terminal, ManagedVideoError::Cancelled);
+ assert_eq!(segment.terminal_error(), Some(expected.clone()));
+ assert_eq!(segment.wait_for_terminal().await, expected);
+ drop(retained);
+ }
+
+ #[tokio::test]
+ async fn managed_segment_terminal_wait_observes_display_idle_failure_after_ready() {
+ idle_terminal_failure(false, false).await;
+ }
+
+ #[tokio::test]
+ async fn managed_segment_terminal_wait_observes_camera_idle_failure_after_ready() {
+ idle_terminal_failure(true, false).await;
+ }
+
+ #[tokio::test]
+ async fn managed_segment_terminal_wait_observes_decode_ahead_failure_with_retained_frame() {
+ idle_terminal_failure(true, true).await;
+ }
+
+ #[tokio::test]
+ async fn managed_segment_dropped_and_cancelled_terminal_waiters_leave_both_workers_healthy()
+ {
+ let (segment, display, camera) = ready_segment().await;
+ let mut dropped = Box::pin(segment.wait_for_terminal());
+ assert!(futures::poll!(&mut dropped).is_pending());
+ drop(dropped);
+ let mut cancelled = Box::pin(segment.wait_for_terminal());
+ assert!(futures::poll!(&mut cancelled).is_pending());
+ tokio::select! {
+ error = &mut cancelled => panic!("Healthy terminal waiter completed: {error:?}"),
+ _ = std::future::ready(()) => {},
+ }
+ drop(cancelled);
+ display.assert_healthy();
+ camera.assert_healthy();
+ drop(reply_frames(&segment, &display, &camera).await);
+ display.assert_healthy();
+ camera.assert_healthy();
+ let exit = join_both(&segment, &display, &camera).await;
+ assert_eq!(exit.display.unwrap().terminal, ManagedVideoError::Cancelled);
+ assert_eq!(exit.camera.unwrap().terminal, ManagedVideoError::Cancelled);
+ }
+ }
+ use super::*;
+ use cap_enc_ffmpeg::segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig};
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ struct DropSignal(Arc<AtomicBool>);
+
+ impl Drop for DropSignal {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::Release);
+ }
+ }
+
+ fn blocked_worker() -> (ManagedVideoStopHandle, mpsc::Sender<()>, Arc<AtomicBool>) {
+ let control = ManagedVideoControl::new();
+ let (wake, requests) = mpsc::channel();
+ let (release, released) = mpsc::channel();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let worker_control = control.clone();
+ let worker_dropped = dropped.clone();
+ let join = std::thread::spawn(move || {
+ worker_control.run_worker(|| {
+ let _resource = DropSignal(worker_dropped);
+ let _ = requests.recv();
+ let _ = released.recv();
+ });
+ });
+ *control.join.lock().unwrap() = Some(join);
+ (ManagedVideoStopHandle { control, wake }, release, dropped)
+ }
+
+ fn pending_decoder(worker: ManagedVideoStopHandle) -> ManagedVideoDecoder {
+ ManagedVideoDecoder {
+ worker,
+ ready: None,
+ decoder: None,
+ offset: 0.0,
+ max_fallback_distance: DEFAULT_MAX_FALLBACK_DISTANCE,
+ }
+ }
+
+ #[tokio::test]
+ async fn managed_concurrent_stop_waiters_observe_native_drop_and_join() {
+ let (worker, release, dropped) = blocked_worker();
+ let mut first = Box::pin(worker.stop_and_wait());
+ let mut second = Box::pin(worker.stop_and_wait());
+ assert!(futures::poll!(&mut first).is_pending());
+ assert!(futures::poll!(&mut second).is_pending());
+ assert!(!dropped.load(Ordering::Acquire));
+ assert!(worker.control.state.borrow().exit.is_none());
+ assert_eq!(
+ worker.wait_for_terminal().await,
+ ManagedVideoError::Cancelled
+ );
+ release.send(()).unwrap();
+ let (first, second) = tokio::time::timeout(Duration::from_secs(5), async {
+ tokio::join!(first, second)
+ })
+ .await
+ .unwrap();
+ assert_eq!(first.terminal, ManagedVideoError::Cancelled);
+ assert_eq!(second.terminal, first.terminal);
+ assert!(dropped.load(Ordering::Acquire));
+ assert!(worker.control.join.lock().unwrap().is_none());
+ }
+
+ #[tokio::test]
+ async fn managed_dropped_stop_waiter_does_not_abandon_the_join() {
+ let (worker, release, dropped) = blocked_worker();
+ let mut first = Box::pin(worker.stop_and_wait());
+ assert!(futures::poll!(&mut first).is_pending());
+ drop(first);
+ assert!(!dropped.load(Ordering::Acquire));
+ release.send(()).unwrap();
+ tokio::time::timeout(Duration::from_secs(5), worker.stop_and_wait())
+ .await
+ .unwrap();
+ assert!(dropped.load(Ordering::Acquire));
+ assert!(worker.control.state.borrow().exit.is_some());
+ }
+
+ #[tokio::test]
+ async fn managed_dropped_readiness_future_cancels_but_retains_cleanup_owner() {
+ let (worker, release, dropped) = blocked_worker();
+ let (ready_sender, ready_receiver) = oneshot::channel();
+ let mut decoder = pending_decoder(worker.clone());
+ decoder.ready = Some(ready_receiver);
+ let mut readiness = Box::pin(decoder.wait_ready());
+ assert!(futures::poll!(&mut readiness).is_pending());
+ drop(readiness);
+ assert_eq!(
+ worker.wait_for_terminal().await,
+ ManagedVideoError::Cancelled
+ );
+ assert!(!dropped.load(Ordering::Acquire));
+ assert!(worker.control.state.borrow().exit.is_none());
+ drop(decoder);
+ drop(ready_sender);
+ release.send(()).unwrap();
+ tokio::time::timeout(Duration::from_secs(5), worker.stop_and_wait())
+ .await
+ .unwrap();
+ assert!(dropped.load(Ordering::Acquire));
+ }
+
+ #[tokio::test]
+ async fn managed_worker_panic_is_terminal_after_resource_drop_before_join_ack() {
+ let control = ManagedVideoControl::new();
+ let (wake, requests) = mpsc::channel();
+ let worker_control = control.clone();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let worker_dropped = dropped.clone();
+ let join = std::thread::spawn(move || {
+ worker_control.run_worker(|| {
+ let _resource = DropSignal(worker_dropped);
+ drop(requests);
+ panic!("Managed worker panic probe");
+ });
+ });
+ *control.join.lock().unwrap() = Some(join);
+ let worker = ManagedVideoStopHandle { control, wake };
+ assert_eq!(
+ tokio::time::timeout(Duration::from_secs(5), worker.wait_for_terminal())
+ .await
+ .unwrap(),
+ ManagedVideoError::WorkerPanicked
+ );
+ assert!(dropped.load(Ordering::Acquire));
+ assert!(worker.control.state.borrow().exit.is_none());
+ assert_eq!(
+ worker.stop_and_wait().await.terminal,
+ ManagedVideoError::WorkerPanicked
+ );
+ }
+
+ #[tokio::test]
+ async fn managed_terminal_error_is_preserved_through_cancel_and_unready_requests() {
+ let (worker, release, _) = blocked_worker();
+ let error = ManagedVideoError::Decode("Source identity changed".to_string());
+ worker.control.fail(error.clone());
+ let decoder = pending_decoder(worker.clone());
+ assert!(matches!(decoder.get_frame(0.0).await, Err(actual) if actual == error));
+ assert!(matches!(decoder.get_frame_initial(0.0).await, Err(actual) if actual == error));
+ worker.cancel();
+ assert_eq!(worker.wait_for_terminal().await, error);
+ release.send(()).unwrap();
+ assert_eq!(worker.stop_and_wait().await.terminal, error);
+ }
+
+ fn encode_gapped_segments(directory: &std::path::Path) -> Vec<PathBuf> {
+ ::ffmpeg::init().unwrap();
+ let mut encoder = SegmentedVideoEncoder::init(
+ directory.to_path_buf(),
+ cap_media_info::VideoInfo {
+ pixel_format: cap_media_info::Pixel::NV12,
+ width: 160,
+ height: 120,
+ time_base: Rational(1, 1_000_000),
+ frame_rate: Rational(30, 1),
+ },
+ SegmentedVideoEncoderConfig {
+ segment_duration: Duration::from_secs(1),
+ bpp: 4.0,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let mut noise = 123456789_u32;
+ for index in (0..90_u64).chain(180..300) {
+ let mut frame = ::ffmpeg::frame::Video::new(::ffmpeg::format::Pixel::NV12, 160, 120);
+ for byte in frame.data_mut(0) {
+ noise ^= noise << 13;
+ noise ^= noise >> 17;
+ noise ^= noise << 5;
+ *byte = (noise % 220 + 16) as u8;
+ }
+ frame.data_mut(1).fill(128);
+ encoder
+ .queue_frame(frame, Duration::from_micros(index * 1_000_000 / 30))
+ .unwrap();
+ }
+ encoder.finish().unwrap();
+ let mut paths = std::fs::read_dir(directory)
+ .unwrap()
+ .map(|entry| entry.unwrap().path())
+ .filter(|path| path.extension().is_some_and(|extension| extension == "m4s"))
+ .map(|path| PathBuf::from(path.file_name().unwrap()))
+ .collect::<Vec<_>>();
+ paths.sort();
+ assert!(paths.len() >= 3);
+ assert!(
+ std::fs::metadata(directory.join(paths.last().unwrap()))
+ .unwrap()
+ .len()
+ > 65_536
+ );
+ paths.insert(0, PathBuf::from("init.mp4"));
+ paths
+ }
+
+ async fn ordinary_worker(
+ path: PathBuf,
+ offset: f64,
+ hardware: bool,
+ ) -> (AsyncVideoDecoderHandle, std::thread::JoinHandle<()>) {
+ ordinary_worker_with_fps(path, offset, hardware, 30).await
+ }
+
+ async fn ordinary_worker_with_fps(
+ path: PathBuf,
+ offset: f64,
+ hardware: bool,
+ fps: u32,
+ ) -> (AsyncVideoDecoderHandle, std::thread::JoinHandle<()>) {
+ let (sender, receiver) = mpsc::channel();
+ let (ready_sender, ready_receiver) = oneshot::channel();
+ let join = ffmpeg::FfmpegDecoder::spawn_ordinary_test_worker(
+ path,
+ fps,
+ receiver,
+ ready_sender,
+ hardware,
+ );
+ let initialized = tokio::time::timeout(Duration::from_secs(30), ready_receiver)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ (
+ AsyncVideoDecoderHandle {
+ sender,
+ offset,
+ status: DecoderStatus {
+ decoder_type: initialized.decoder_type,
+ video_width: initialized.width,
+ video_height: initialized.height,
+ fallback_reason: None,
+ },
+ max_fallback_distance: DEFAULT_MAX_FALLBACK_DISTANCE,
+ },
+ join,
+ )
+ }
+
+ fn frame_pixels(frame: &DecodedFrame) -> Vec<u8> {
+ let mut pixels = Vec::new();
+ let width = frame.width as usize;
+ let height = frame.height as usize;
+ let mut append_rows = |plane: &[u8], stride: usize, row_bytes: usize, rows: usize| {
+ for row in plane.chunks(stride).take(rows) {
+ pixels.extend_from_slice(&row[..row_bytes]);
+ }
+ };
+ match frame.format {
+ PixelFormat::Rgba => append_rows(frame.data(), width * 4, width * 4, height),
+ PixelFormat::Nv12 => {
+ append_rows(
+ frame.y_plane().unwrap(),
+ frame.y_stride as usize,
+ width,
+ height,
+ );
+ append_rows(
+ frame.uv_plane().unwrap(),
+ frame.uv_stride as usize,
+ width,
+ height / 2,
+ );
+ }
+ PixelFormat::Yuv420p => {
+ append_rows(
+ frame.y_plane().unwrap(),
+ frame.y_stride as usize,
+ width,
+ height,
+ );
+ append_rows(
+ frame.u_plane().unwrap(),
+ frame.uv_stride as usize,
+ width / 2,
+ height / 2,
+ );
+ append_rows(
+ frame.v_plane().unwrap(),
+ frame.uv_stride as usize,
+ width / 2,
+ height / 2,
+ );
+ }
+ }
+ let expected_bytes = match frame.format {
+ PixelFormat::Rgba => width * height * 4,
+ PixelFormat::Nv12 | PixelFormat::Yuv420p => width * height * 3 / 2,
+ };
+ assert_eq!(pixels.len(), expected_bytes);
+ pixels
+ }
+
+ async fn compare_gapped_workers(hardware: bool) {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let reference = directory.path().join("reference");
+ let retained = directory.path().join("retained");
+ let paths = encode_gapped_segments(&original);
+ std::fs::create_dir(&reference).unwrap();
+ for path in &paths {
+ std::fs::copy(original.join(path), reference.join(path)).unwrap();
+ }
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let (ordinary, join) = ordinary_worker(reference, 0.25, hardware).await;
+ let mut managed = spawn_managed_decoder(
+ "gapped-test",
+ source.clone(),
+ paths.iter().map(PathBuf::as_path),
+ 30,
+ 0.25,
+ hardware,
+ )
+ .unwrap();
+ let status = managed.wait_ready().await.unwrap();
+ println!(
+ "{}",
+ serde_json::json!({
+ "probe": "managed-async-worker",
+ "hardwareRequested": hardware,
+ "ordinaryDecoder": ordinary.status.decoder_type.to_string(),
+ "managedDecoder": status.decoder_type.to_string(),
+ "width": status.video_width,
+ "height": status.video_height,
+ "offsetSeconds": 0.25,
+ "gapStartSeconds": 3.0,
+ "gapEndSeconds": 6.0,
+ })
+ );
+ assert_eq!(status.decoder_type, ordinary.status.decoder_type);
+ assert_eq!(status.video_width, ordinary.status.video_width);
+ assert_eq!(status.video_height, ordinary.status.video_height);
+ for cycle in 0..3 {
+ let destination = if cycle % 2 == 0 { &retained } else { &original };
+ source.relocate(destination.clone()).unwrap();
+ for time in [0.0, 2.6, 3.0, 4.0, 5.5, 6.0, 9.5, 0.5, 4.0, 8.0, 2.6] {
+ let expected = ordinary.get_frame_initial(time).await.unwrap();
+ let actual = managed.get_frame_initial(time).await.unwrap();
+ assert_eq!(
+ (actual.width, actual.height, actual.format),
+ (expected.width, expected.height, expected.format),
+ "cycle {cycle}, time {time}"
+ );
+ assert_eq!(
+ frame_pixels(&actual),
+ frame_pixels(&expected),
+ "cycle {cycle}, time {time}"
+ );
+ }
+ }
+ let exit = managed.stop_and_wait().await;
+ assert_eq!(exit.terminal, ManagedVideoError::Cancelled);
+ drop(managed);
+ drop(ordinary);
+ tokio::task::spawn_blocking(move || join.join().unwrap())
+ .await
+ .unwrap();
+ for path in &paths {
+ assert_eq!(
+ std::fs::read(retained.join(path)).unwrap(),
+ std::fs::read(directory.path().join("reference").join(path)).unwrap()
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn managed_async_worker_preserves_software_frames_offsets_seeks_and_vfr_holds() {
+ compare_gapped_workers(false).await;
+ }
+
+ #[cfg(target_os = "macos")]
+ #[tokio::test]
+ async fn managed_async_worker_preserves_hardware_frames_offsets_seeks_and_vfr_holds() {
+ compare_gapped_workers(true).await;
+ }
+
+ fn last_fragment_request_time(directory: &std::path::Path, paths: &[PathBuf], fps: u32) -> f32 {
+ let last_start = paths[..paths.len() - 1]
+ .iter()
+ .map(|path| std::fs::metadata(directory.join(path)).unwrap().len())
+ .sum::<u64>();
+ let absolute_paths = paths
+ .iter()
+ .map(|path| directory.join(path))
+ .collect::<Vec<_>>();
+ let mut input =
+ cap_enc_ffmpeg::SegmentedInput::open(absolute_paths.iter().map(PathBuf::as_path))
+ .unwrap();
+ let (stream_index, start_time, time_base) = {
+ let stream = input
+ .input()
+ .streams()
+ .best(::ffmpeg::media::Type::Video)
+ .unwrap();
+ (stream.index(), stream.start_time(), stream.time_base())
+ };
+ let mut packet = ::ffmpeg::Packet::empty();
+ loop {
+ input.read_packet(&mut packet).unwrap();
+ if packet.stream() == stream_index
+ && u64::try_from(packet.position()).is_ok_and(|position| position >= last_start)
+ {
+ let pts = packet.pts().unwrap();
+ let frame = pts_to_frame(pts.checked_sub(start_time).unwrap(), time_base, fps);
+ let requested_time = ((f64::from(frame) + 0.25) / f64::from(fps)) as f32;
+ assert_eq!((requested_time * fps as f32).floor() as u32, frame);
+ println!(
+ "{}",
+ serde_json::json!({
+ "probe": "missing-fragment-target",
+ "fragment": paths.last().unwrap(),
+ "fragmentStartBytes": last_start,
+ "packetPosition": packet.position(),
+ "packetPts": pts,
+ "streamStart": start_time,
+ "timeBase": [time_base.numerator(), time_base.denominator()],
+ "renderFrame": frame,
+ "requestedTime": requested_time,
+ })
+ );
+ return requested_time;
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn managed_async_worker_missing_lazy_fragment_is_terminal_without_fallback_frame() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ let paths = encode_gapped_segments(&original);
+ let requested_time = last_fragment_request_time(&original, &paths, 30);
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original).unwrap();
+ let mut input_probe = cap_enc_ffmpeg::SegmentedInput::open_relocatable(
+ &source,
+ paths.iter().map(PathBuf::as_path),
+ )
+ .unwrap();
+ let mut managed = spawn_managed_decoder(
+ "missing-fragment-test",
+ source.clone(),
+ paths.iter().map(PathBuf::as_path),
+ 30,
+ 0.0,
+ false,
+ )
+ .unwrap();
+ managed.wait_ready().await.unwrap();
+ let initial = managed.get_frame_initial(0.0).await.unwrap();
+ assert!(!frame_pixels(&initial).is_empty());
+ source.relocate(retained.clone()).unwrap();
+ std::fs::remove_file(retained.join(paths.last().unwrap())).unwrap();
+ let input_error = loop {
+ match input_probe.read_packet(&mut ::ffmpeg::Packet::empty()) {
+ Ok(()) => {}
+ Err(error) => break error,
+ }
+ };
+ assert_eq!(
+ input_probe.io_error().unwrap().kind(),
+ std::io::ErrorKind::NotFound
+ );
+ assert!(
+ matches!(input_error, ::ffmpeg::Error::Other { errno } if errno == ::ffmpeg::ffi::EIO)
+ );
+ println!(
+ "{}",
+ serde_json::json!({
+ "probe": "missing-fragment-io-error",
+ "error": input_error.to_string(),
+ "sourceError": input_probe.io_error().unwrap().to_string(),
+ })
+ );
+ let error = managed
+ .get_frame_initial(requested_time)
+ .await
+ .err()
+ .unwrap();
+ assert!(
+ matches!(
+ error,
+ ManagedVideoError::Decode(_) | ManagedVideoError::Seek(_)
+ ),
+ "{error:?}"
+ );
+ assert!(matches!(managed.get_frame(0.0).await, Err(actual) if actual == error));
+ assert_eq!(managed.stop_handle().wait_for_terminal().await, error);
+ assert_eq!(managed.stop_and_wait().await.terminal, error);
+ }
+ fn segment_wrapper_metadata(camera: bool) -> cap_project::StudioRecordingMeta {
+ serde_json::from_value(serde_json::json!({
+ "segments": [{
+ "display": {"path":"display.mp4", "fps":30, "start_time":10.0},
+ "camera": camera.then(|| serde_json::json!({"path":"camera.mp4", "fps":24, "start_time":10.125})),
+ "mic": {"path":"mic.aac", "start_time":10.25}
+ }]
+ })).unwrap()
+ }
+
+ #[tokio::test]
+ async fn managed_segment_matches_ordinary_camera_offsets_masks_gaps_and_relocation() {
+ use crate::{
+ ManagedRecordingSegmentDecoders, ManagedSegmentVideoInput, ManagedVideoTrackInput,
+ RecordingSegmentDecoders,
+ };
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ let reference = directory.path().join("reference");
+ let paths = encode_gapped_segments(&original);
+ std::fs::create_dir(&reference).unwrap();
+ for path in &paths {
+ std::fs::copy(original.join(path), reference.join(path)).unwrap();
+ }
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let (display, display_join) =
+ ordinary_worker_with_fps(reference.clone(), 0.25, false, 30).await;
+ let (camera, camera_join) = ordinary_worker_with_fps(reference, 0.125, false, 24).await;
+ let ordinary = RecordingSegmentDecoders {
+ screen: display.with_max_fallback_distance(crate::SCREEN_MAX_FALLBACK_DISTANCE),
+ camera: Some(camera.with_max_fallback_distance(crate::CAMERA_MAX_FALLBACK_DISTANCE)),
+ segment_offset: 10.25,
+ };
+ let input = ManagedSegmentVideoInput::new(
+ 0,
+ &segment_wrapper_metadata(true),
+ ManagedVideoTrackInput::new(source.clone(), paths.clone()).unwrap(),
+ Some(ManagedVideoTrackInput::new(source.clone(), paths.clone()).unwrap()),
+ )
+ .unwrap();
+ let mut managed = ManagedRecordingSegmentDecoders::spawn(input, false);
+ let stops = managed.stop_handles();
+ let status = managed.wait_ready().await.unwrap();
+ assert_eq!(status.segment_index, 0);
+ assert_eq!(
+ (status.display.video_width, status.display.video_height),
+ ordinary.screen_video_dimensions()
+ );
+ assert_eq!(
+ status
+ .camera
+ .as_ref()
+ .map(|camera| (camera.video_width, camera.video_height)),
+ ordinary.camera_video_dimensions()
+ );
+ let offsets = cap_project::ClipOffsets {
+ camera: 0.125,
+ ..Default::default()
+ };
+ for cycle in 0..2 {
+ source
+ .relocate(if cycle == 0 {
+ retained.clone()
+ } else {
+ original.clone()
+ })
+ .unwrap();
+ for (time, needs_camera, needs_display) in [
+ (0.0, true, true),
+ (2.6, true, true),
+ (4.0, true, true),
+ (5.5, false, true),
+ (6.0, true, false),
+ (9.5, true, true),
+ (0.5, true, true),
+ (4.0, false, false),
+ ] {
+ let expected = if cycle == 0 {
+ ordinary
+ .get_frames_initial(time, needs_camera, needs_display, offsets)
+ .await
+ } else {
+ ordinary
+ .get_frames(time, needs_camera, needs_display, offsets)
+ .await
+ }
+ .unwrap();
+ let actual = if cycle == 0 {
+ managed
+ .get_frames_initial(time, needs_camera, needs_display, offsets)
+ .await
+ } else {
+ managed
+ .get_frames(time, needs_camera, needs_display, offsets)
+ .await
+ }
+ .unwrap();
+ assert_eq!(actual.screen_size, expected.screen_size);
+ assert_eq!(
+ actual.segment_time.to_bits(),
+ expected.segment_time.to_bits()
+ );
+ assert_eq!(
+ actual.recording_time.to_bits(),
+ expected.recording_time.to_bits()
+ );
+ assert_eq!(actual.segment_has_camera, expected.segment_has_camera);
+ for (actual, expected) in [
+ (actual.screen_frame, expected.screen_frame),
+ (actual.camera_frame, expected.camera_frame),
+ ] {
+ assert_eq!(actual.is_some(), expected.is_some());
+ if let (Some(actual), Some(expected)) = (actual, expected) {
+ assert_eq!(
+ (actual.width, actual.height, actual.format),
+ (expected.width, expected.height, expected.format)
+ );
+ assert_eq!(frame_pixels(&actual), frame_pixels(&expected));
+ }
+ }
+ }
+ }
+ let (first, second) = tokio::join!(managed.stop_and_wait(), stops.stop_and_wait());
+ assert_eq!(
+ first.display.unwrap().terminal,
+ ManagedVideoError::Cancelled
+ );
+ assert_eq!(first.camera.unwrap().terminal, ManagedVideoError::Cancelled);
+ assert_eq!(
+ second.display.unwrap().terminal,
+ ManagedVideoError::Cancelled
+ );
+ assert_eq!(
+ second.camera.unwrap().terminal,
+ ManagedVideoError::Cancelled
+ );
+ drop(managed);
+ drop(ordinary);
+ tokio::task::spawn_blocking(move || {
+ display_join.join().unwrap();
+ camera_join.join().unwrap();
+ })
+ .await
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn managed_segment_missing_camera_joins_both_workers_and_never_returns_display_only() {
+ use crate::{
+ ManagedRecordingSegmentDecoders, ManagedSegmentVideoError, ManagedSegmentVideoInput,
+ ManagedVideoTrackInput,
+ };
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let paths = encode_gapped_segments(&original);
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original).unwrap();
+ let input = ManagedSegmentVideoInput::new(
+ 0,
+ &segment_wrapper_metadata(true),
+ ManagedVideoTrackInput::new(source.clone(), paths).unwrap(),
+ Some(
+ ManagedVideoTrackInput::new(source, vec![PathBuf::from("missing-init.mp4")])
+ .unwrap(),
+ ),
+ )
+ .unwrap();
+ let mut managed = ManagedRecordingSegmentDecoders::spawn(input, false);
+ let stops = managed.stop_handles();
+ let error = managed.wait_ready().await.unwrap_err();
+ assert!(
+ matches!(error, ManagedSegmentVideoError::Camera(_)),
+ "{error:?}"
+ );
+ assert_eq!(managed.terminal_error(), Some(error.clone()));
+ assert!(
+ matches!(managed.get_frames_initial(0.0, false, true, Default::default()).await, Err(actual) if actual == error)
+ );
+ let (first, second) = tokio::join!(managed.stop_and_wait(), stops.stop_and_wait());
+ assert!(first.display.is_some() && first.camera.is_some());
+ assert!(second.display.is_some() && second.camera.is_some());
+ }
+
+ #[tokio::test]
+ async fn managed_segment_readiness_drop_cancels_both_and_retained_handles_join_after_owner_drop()
+ {
+ use crate::ManagedRecordingSegmentDecoders;
+ let (display_worker, display_release, display_dropped) = blocked_worker();
+ let (camera_worker, camera_release, camera_dropped) = blocked_worker();
+ let (display_sender, display_receiver) = oneshot::channel();
+ let (camera_sender, camera_receiver) = oneshot::channel();
+ let mut display = pending_decoder(display_worker.clone());
+ let mut camera = pending_decoder(camera_worker.clone());
+ display.ready = Some(display_receiver);
+ camera.ready = Some(camera_receiver);
+ let mut managed = ManagedRecordingSegmentDecoders::from_test_workers(display, camera);
+ let stops = managed.stop_handles();
+ let mut readiness = Box::pin(managed.wait_ready());
+ assert!(futures::poll!(&mut readiness).is_pending());
+ drop(readiness);
+ assert_eq!(
+ display_worker.terminal_error(),
+ Some(ManagedVideoError::Cancelled)
+ );
+ assert_eq!(
+ camera_worker.terminal_error(),
+ Some(ManagedVideoError::Cancelled)
+ );
+ assert!(!display_dropped.load(Ordering::Acquire));
+ assert!(!camera_dropped.load(Ordering::Acquire));
+ drop(managed);
+ drop(display_sender);
+ drop(camera_sender);
+ let mut stopped = Box::pin(stops.stop_and_wait());
+ assert!(futures::poll!(&mut stopped).is_pending());
+ display_release.send(()).unwrap();
+ camera_release.send(()).unwrap();
+ let exit = tokio::time::timeout(Duration::from_secs(5), stopped)
+ .await
+ .unwrap();
+ assert_eq!(exit.display.unwrap().terminal, ManagedVideoError::Cancelled);
+ assert_eq!(exit.camera.unwrap().terminal, ManagedVideoError::Cancelled);
+ assert!(display_dropped.load(Ordering::Acquire));
+ assert!(camera_dropped.load(Ordering::Acquire));
+ }
+}
diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rs
index 33008b1d3..1f78273ad 100644
--- a/crates/rendering/src/frame_pipeline.rs
+++ b/crates/rendering/src/frame_pipeline.rs
@@ -1052,6 +1052,7 @@ pub struct RgbaToBgraSurfaceConverter {
/// resolution change swaps both entries out within two frames, so no
/// retired texture is kept alive past that.
source_bind_groups: Vec<(wgpu::Texture, wgpu::BindGroup)>,
+ readiness_first_output: bool,
}
#[cfg(target_os = "macos")]
@@ -1075,6 +1076,7 @@ struct BgraSurfaceSlot {
#[cfg(target_os = "macos")]
impl RgbaToBgraSurfaceConverter {
pub fn new(device: &wgpu::Device) -> Result<Self, RenderingError> {
+ let phase = crate::readiness::Phase::start("bgra.converter");
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("RGBA to BGRA Surface Blit"),
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!(
@@ -1127,7 +1129,7 @@ impl RgbaToBgraSurfaceConverter {
let texture_cache = IOSurfaceTextureCache::new()
.ok_or_else(|| RenderingError::Surface("Metal device is unavailable".to_string()))?;
- Ok(Self {
+ let converter = Self {
pipeline,
bind_group_layout,
texture_cache,
@@ -1137,7 +1139,10 @@ impl RgbaToBgraSurfaceConverter {
allocation_attributes: surface_allocation_attributes(BGRA_SURFACE_RING_MAX)?,
pool_size: (0, 0),
source_bind_groups: Vec::new(),
- })
+ readiness_first_output: true,
+ };
+ phase.finish("returned");
+ Ok(converter)
}
fn source_bind_group(
@@ -1395,6 +1400,7 @@ impl PendingSurface {
}
pub struct PendingReadback {
+ readiness_phase: Option<crate::readiness::Phase>,
rx: oneshot::Receiver<Result<(), wgpu::BufferAsyncError>>,
buffer: Arc<wgpu::Buffer>,
padded_bytes_per_row: u32,
@@ -1470,6 +1476,9 @@ impl PendingReadback {
}
}
+ if let Some(phase) = &self.readiness_phase {
+ phase.mark("gpu_map_observed");
+ }
let Some(active_bytes) =
usize::try_from(self.buffer.size())
.ok()
@@ -1495,6 +1504,9 @@ impl PendingReadback {
let target_time_ns =
(self.frame_number as u64 * 1_000_000_000) / self.frame_rate.max(1) as u64;
+ if let Some(phase) = self.readiness_phase.take() {
+ phase.finish("frame_ready");
+ }
Ok(RenderedFrame {
data: Arc::new(data_vec),
padded_bytes_per_row: self.padded_bytes_per_row,
@@ -1513,6 +1525,7 @@ pub struct PipelinedGpuReadback {
pending: Option<PendingReadback>,
needs_resize: bool,
pending_resize_size: u64,
+ readiness_first_output: bool,
}
impl PipelinedGpuReadback {
@@ -1533,6 +1546,7 @@ impl PipelinedGpuReadback {
pending: None,
needs_resize: false,
pending_resize_size: 0,
+ readiness_first_output: true,
}
}
@@ -1603,6 +1617,8 @@ impl PipelinedGpuReadback {
uniforms: &ProjectUniforms,
mut render_encoder: wgpu::CommandEncoder,
) -> Result<(), RenderingError> {
+ let phase = std::mem::take(&mut self.readiness_first_output)
+ .then(|| crate::readiness::Phase::start("rgba.first_output"));
let padded_bytes_per_row = padded_bytes_per_row(uniforms.output_size);
let output_buffer_size =
u64::from(padded_bytes_per_row) * u64::from(uniforms.output_size.1);
@@ -1634,7 +1650,13 @@ impl PipelinedGpuReadback {
output_texture_size,
);
+ if let Some(phase) = &phase {
+ phase.mark("submit_start");
+ }
queue.submit(std::iter::once(render_encoder.finish()));
+ if let Some(phase) = &phase {
+ phase.mark("submit_returned");
+ }
let (tx, rx) = oneshot::channel();
buffer
@@ -1646,6 +1668,7 @@ impl PipelinedGpuReadback {
});
self.pending = Some(PendingReadback {
+ readiness_phase: phase,
rx,
buffer,
padded_bytes_per_row,
@@ -1674,6 +1697,7 @@ pub struct RenderSession {
impl RenderSession {
pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
+ let phase = crate::readiness::Phase::start("frame.session");
let make_texture = || {
device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
@@ -1695,7 +1719,7 @@ impl RenderSession {
let textures = (make_texture(), make_texture());
- Self {
+ let session = Self {
current_is_left: true,
texture_views: (
textures.0.create_view(&Default::default()),
@@ -1705,7 +1729,9 @@ impl RenderSession {
pipelined_readback: None,
texture_width: width,
texture_height: height,
- }
+ };
+ phase.finish("returned");
+ session
}
pub fn update_texture_size(&mut self, device: &wgpu::Device, width: u32, height: u32) {
@@ -1960,6 +1986,8 @@ pub async fn finish_encoder_bgra_surface(
uniforms: &ProjectUniforms,
mut encoder: wgpu::CommandEncoder,
) -> Result<SurfaceFrame, RenderingError> {
+ let phase = std::mem::take(&mut converter.readiness_first_output)
+ .then(|| crate::readiness::Phase::start("bgra.first_output"));
let texture = if session.current_is_left {
&session.textures.0
} else {
@@ -1976,8 +2004,22 @@ pub async fn finish_encoder_bgra_surface(
uniforms.frame_rate,
)
.await?;
+ if let Some(phase) = &phase {
+ phase.mark("submit_start");
+ }
queue.submit(std::iter::once(encoder.finish()));
- pending.wait(device, queue).await
+ if let Some(phase) = &phase {
+ phase.mark("submit_returned");
+ }
+ let result = pending.wait(device, queue).await;
+ if let Some(phase) = phase {
+ phase.finish(if result.is_ok() {
+ "frame_ready"
+ } else {
+ "error"
+ });
+ }
+ result
}
pub async fn flush_pending_readback(
diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs
index 6f6906194..0c47bddd9 100644
--- a/crates/rendering/src/layers/captions.rs
+++ b/crates/rendering/src/layers/captions.rs
@@ -295,6 +295,7 @@ impl CaptionsLayer {
});
let font_system = super::new_font_system();
+ let glyph_phase = crate::readiness::Phase::start("glyph.captions.gpu_resources");
let swash_cache = SwashCache::new();
let cache = Cache::new(device);
let viewport = Viewport::new(device, &cache);
@@ -305,6 +306,7 @@ impl CaptionsLayer {
wgpu::MultisampleState::default(),
None,
);
+ glyph_phase.finish("returned");
let metrics = Metrics::new(24.0, 24.0 * 1.2);
let text_buffer = Buffer::new_empty(metrics);
diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rs
index 9e8e4b63f..fc4513358 100644
--- a/crates/rendering/src/layers/cursor.rs
+++ b/crates/rendering/src/layers/cursor.rs
@@ -276,18 +276,28 @@ impl CursorLayer {
) -> Option<CursorTexture> {
let mut loaded_cursor = None;
- let recorded_shape = match &constants.recording_meta.inner {
- RecordingMetaInner::Studio(studio) => match studio.as_ref() {
- StudioRecordingMeta::MultipleSegments {
- inner:
- MultipleSegments {
- cursors: Cursors::Correct(cursors),
- ..
- },
- } => cursors.get(cursor_id).and_then(|v| v.shape),
+ let recorded_shape = if let Some(assets) = &constants.frozen_recorded_cursors {
+ match assets.metadata(cursor_id) {
+ Ok(metadata) => metadata.shape,
+ Err(error) => {
+ error!("{error}");
+ return None;
+ }
+ }
+ } else {
+ match &constants.recording_meta.inner {
+ RecordingMetaInner::Studio(studio) => match studio.as_ref() {
+ StudioRecordingMeta::MultipleSegments {
+ inner:
+ MultipleSegments {
+ cursors: Cursors::Correct(cursors),
+ ..
+ },
+ } => cursors.get(cursor_id).and_then(|v| v.shape),
+ _ => None,
+ },
_ => None,
- },
- _ => None,
+ }
};
// An explicit family cross-maps the recorded shape into it (and
@@ -313,18 +323,39 @@ impl CursorLayer {
.ok();
}
- if let StudioRecordingMeta::MultipleSegments { inner, .. } = &constants.meta
- && loaded_cursor.is_none()
- && let Some(c) = inner.get_cursor_image(&constants.recording_meta, cursor_id)
- && let Ok(img) = image::open(&c.path)
- .map_err(|err| error!("Failed to load cursor image from {:?}: {err}", c.path))
- {
- loaded_cursor = Some(CursorTexture::prepare(
- constants,
- &img.to_rgba8(),
- img.dimensions(),
- c.hotspot,
- ));
+ if loaded_cursor.is_none() {
+ let cursor = crate::recorded_cursor_assets::select_recorded_cursor_image(
+ constants.frozen_recorded_cursors.as_ref(),
+ cursor_id,
+ || {
+ let StudioRecordingMeta::MultipleSegments { inner, .. } = &constants.meta
+ else {
+ return None;
+ };
+ let cursor = inner.get_cursor_image(&constants.recording_meta, cursor_id)?;
+ let image = image::open(&cursor.path)
+ .map_err(|err| {
+ error!("Failed to load cursor image from {:?}: {err}", cursor.path)
+ })
+ .ok()?;
+ Some(crate::recorded_cursor_assets::DecodedRecordedCursor {
+ image,
+ hotspot: cursor.hotspot,
+ })
+ },
+ );
+ match cursor {
+ Ok(Some(cursor)) => {
+ loaded_cursor = Some(CursorTexture::prepare(
+ constants,
+ &cursor.image.to_rgba8(),
+ cursor.image.dimensions(),
+ cursor.hotspot,
+ ));
+ }
+ Err(error) => error!("{error}"),
+ Ok(None) => {}
+ }
}
loaded_cursor
@@ -336,6 +367,18 @@ impl CursorLayer {
use_svg: bool,
cursor_type: &CursorType,
) {
+ if let Some(assets) = &constants.frozen_recorded_cursors {
+ for cursor_id in assets.ids() {
+ if !self.cursors.contains_key(cursor_id)
+ && let Some(texture) =
+ Self::load_cursor_texture(constants, cursor_id, use_svg, cursor_type)
+ {
+ self.cursors.insert(cursor_id.clone(), texture);
+ }
+ }
+ return;
+ }
+
let StudioRecordingMeta::MultipleSegments { inner, .. } = &constants.meta else {
return;
};
diff --git a/crates/rendering/src/layers/keyboard.rs b/crates/rendering/src/layers/keyboard.rs
index 513452604..a690adf3f 100644
--- a/crates/rendering/src/layers/keyboard.rs
+++ b/crates/rendering/src/layers/keyboard.rs
@@ -167,6 +167,7 @@ pub struct KeyboardLayer {
impl KeyboardLayer {
pub fn new(device: &Device, queue: &Queue) -> Self {
let font_system = super::new_font_system();
+ let glyph_phase = crate::readiness::Phase::start("glyph.keyboard.gpu_resources");
let swash_cache = SwashCache::new();
let cache = Cache::new(device);
let viewport = Viewport::new(device, &cache);
@@ -177,6 +178,7 @@ impl KeyboardLayer {
wgpu::MultisampleState::default(),
None,
);
+ glyph_phase.finish("returned");
let metrics = Metrics::new(28.0, 28.0 * 1.2);
let text_buffer = Buffer::new_empty(metrics);
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index ad0fe1e47..897b82a2d 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -30,8 +30,11 @@ use std::sync::OnceLock;
pub(crate) fn new_font_system() -> glyphon::FontSystem {
static FONT_TEMPLATE: OnceLock<(String, glyphon::fontdb::Database)> = OnceLock::new();
+ let font_phase = crate::readiness::Phase::start("font.instance");
+ let template_phase = crate::readiness::Phase::start("font.template_lookup");
let (locale, db) = FONT_TEMPLATE.get_or_init(|| {
- let font_system = glyphon::FontSystem::new();
+ let init_phase = crate::readiness::Phase::start("font.template_init");
+ let font_system = crate::readiness::measure("font.system_scan", glyphon::FontSystem::new);
let mut db = font_system.db().clone();
// Pin the generic families to the fonts the editor webview resolves
// them to. fontdb's stock defaults (e.g. "Arial") often don't match
@@ -60,10 +63,17 @@ pub(crate) fn new_font_system() -> glyphon::FontSystem {
db.set_serif_family("DejaVu Serif");
db.set_monospace_family("DejaVu Sans Mono");
}
- (font_system.locale().to_string(), db)
+ let template = (font_system.locale().to_string(), db);
+ init_phase.finish("returned");
+ template
});
+ template_phase.finish("returned");
- glyphon::FontSystem::new_with_locale_and_db(locale.clone(), db.clone())
+ let result = crate::readiness::measure("font.clone_and_index", || {
+ glyphon::FontSystem::new_with_locale_and_db(locale.clone(), db.clone())
+ });
+ font_phase.finish("returned");
+ result
}
pub use animated_gradient::*;
diff --git a/crates/rendering/src/layers/text.rs b/crates/rendering/src/layers/text.rs
index 24bf9e8b4..7cfff37ec 100644
--- a/crates/rendering/src/layers/text.rs
+++ b/crates/rendering/src/layers/text.rs
@@ -190,6 +190,7 @@ fn shift_bounds(bounds: TextBounds, dx: f32, dy: f32) -> TextBounds {
impl TextLayer {
pub fn new(device: &Device, queue: &Queue) -> Self {
let font_system = super::new_font_system();
+ let glyph_phase = crate::readiness::Phase::start("glyph.text.gpu_resources");
let swash_cache = SwashCache::new();
let cache = Cache::new(device);
let viewport = Viewport::new(device, &cache);
@@ -200,6 +201,7 @@ impl TextLayer {
wgpu::MultisampleState::default(),
None,
);
+ glyph_phase.finish("returned");
Self {
font_system,
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 74e00736b..7120c516b 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -20,8 +20,8 @@ use frame_pipeline::{
use futures::future::OptionFuture;
use layers::{
Background, BackgroundLayer, BlurLayer, Camera3DBlurKind, Camera3DLayer, CameraLayer,
- CaptionsLayer, ClickRippleLayer, ColorGradeLayer, CursorLayer, DisplayLayer, FrameLayer,
- ImageLayer, KeyboardLayer, MaskLayer, NotchLayer, NotchUniforms, TextLayer,
+ ClickRippleLayer, ColorGradeLayer, CursorLayer, DisplayLayer, FrameLayer, MaskLayer,
+ NotchLayer, NotchUniforms,
};
use specta::Type;
use spring_mass_damper::SpringMassDamperSimulationConfig;
@@ -45,10 +45,15 @@ mod frame_pipeline;
#[cfg(target_os = "macos")]
pub mod iosurface_texture;
mod layers;
+mod managed_segment;
mod mask;
pub mod notch_shape;
+mod overlay_layers;
mod project_recordings;
+mod readiness;
+mod recorded_cursor_assets;
mod scene;
+mod segment_timing;
pub mod spring_mass_damper;
mod takeover;
mod text;
@@ -67,7 +72,14 @@ pub use frame_pipeline::{GpuOutputFormat, Nv12RenderedFrame, RenderedFrame, Shar
#[cfg(target_os = "macos")]
pub use frame_pipeline::{PendingSurface, RgbaToBgraSurfaceConverter};
pub use layers::{BackgroundTextureCache, clean_background_path};
+pub use managed_segment::{
+ ManagedRecordingSegmentDecoders, ManagedSegmentDecoderStatus, ManagedSegmentStopHandles,
+ ManagedSegmentVideoError, ManagedSegmentVideoExit, ManagedSegmentVideoInput,
+ ManagedVideoTrackInput,
+};
+use overlay_layers::OverlayLayers;
pub use project_recordings::{ProjectRecordingsMeta, SegmentRecordings, Video};
+pub use recorded_cursor_assets::{FrozenCursorAssetError, FrozenRecordedCursorAssets};
use transition::{TransitionCompositor, TransitionParameters};
/// Warms the process-wide system-font scan used by the text/captions/keyboard
@@ -354,53 +366,13 @@ impl RecordingSegmentDecoders {
camera: camera_path,
} = segment;
- let latest_start_time = match &meta {
- StudioRecordingMeta::SingleSegment { .. } => None,
- StudioRecordingMeta::MultipleSegments { inner, .. } => {
- inner.segments[segment_i].latest_start_time()
- }
- };
-
- let screen_fps = match &meta {
- StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
- StudioRecordingMeta::MultipleSegments { inner, .. } => {
- inner.segments[segment_i].display.fps
- }
- };
-
- let camera_fps = match &meta {
- StudioRecordingMeta::SingleSegment { segment } => {
- segment.camera.as_ref().map(|camera| camera.fps)
- }
- StudioRecordingMeta::MultipleSegments { inner, .. } => inner.segments[segment_i]
- .camera
- .as_ref()
- .map(|camera| camera.fps),
- };
-
- let screen_offset = match &meta {
- StudioRecordingMeta::SingleSegment { .. } => 0.0,
- StudioRecordingMeta::MultipleSegments { inner, .. } => {
- let segment = &inner.segments[segment_i];
-
- latest_start_time
- .zip(segment.display.start_time)
- .map(|(latest_start_time, display_time)| latest_start_time - display_time)
- .unwrap_or(0.0)
- }
- };
-
- let camera_offset = match &meta {
- StudioRecordingMeta::SingleSegment { .. } => 0.0,
- StudioRecordingMeta::MultipleSegments { inner, .. } => {
- let segment = &inner.segments[segment_i];
-
- latest_start_time
- .zip(segment.camera.as_ref().and_then(|camera| camera.start_time))
- .map(|(latest_start_time, start_time)| latest_start_time - start_time)
- .unwrap_or(0.0)
- }
- };
+ let segment_timing::SegmentVideoTiming {
+ latest_start_time,
+ screen_fps,
+ camera_fps,
+ screen_offset,
+ camera_offset,
+ } = segment_timing::segment_video_timing(meta, segment_i);
let screen_future = async {
spawn_decoder(
@@ -451,7 +423,8 @@ impl RecordingSegmentDecoders {
needs_display: bool,
offsets: ClipOffsets,
) -> Option<DecodedSegmentFrames> {
- let camera_request_time = segment_time + offsets.camera;
+ let (camera_request_time, recording_time) =
+ segment_timing::segment_frame_times(segment_time, self.segment_offset, offsets);
let (screen_width, screen_height) = self.screen_video_dimensions();
let screen_size = XY::new(screen_width, screen_height);
@@ -479,7 +452,7 @@ impl RecordingSegmentDecoders {
screen_frame: Some(screen?),
camera_frame,
segment_time,
- recording_time: segment_time + self.segment_offset as f32,
+ recording_time,
segment_has_camera: self.camera.is_some(),
})
} else {
@@ -505,7 +478,7 @@ impl RecordingSegmentDecoders {
screen_frame: None,
camera_frame,
segment_time,
- recording_time: segment_time + self.segment_offset as f32,
+ recording_time,
segment_has_camera: self.camera.is_some(),
})
}
@@ -518,7 +491,8 @@ impl RecordingSegmentDecoders {
needs_display: bool,
offsets: ClipOffsets,
) -> Option<DecodedSegmentFrames> {
- let camera_request_time = segment_time + offsets.camera;
+ let (camera_request_time, recording_time) =
+ segment_timing::segment_frame_times(segment_time, self.segment_offset, offsets);
let (screen_width, screen_height) = self.screen_video_dimensions();
let screen_size = XY::new(screen_width, screen_height);
@@ -542,7 +516,7 @@ impl RecordingSegmentDecoders {
screen_frame: Some(screen?),
camera_frame,
segment_time,
- recording_time: segment_time + self.segment_offset as f32,
+ recording_time,
segment_has_camera: self.camera.is_some(),
})
} else {
@@ -568,12 +542,22 @@ impl RecordingSegmentDecoders {
screen_frame: None,
camera_frame,
segment_time,
- recording_time: segment_time + self.segment_offset as f32,
+ recording_time,
segment_has_camera: self.camera.is_some(),
})
}
}
+ pub fn screen_decoder_status(&self) -> &decoder::DecoderStatus {
+ self.screen.decoder_status()
+ }
+
+ pub fn camera_decoder_status(&self) -> Option<&decoder::DecoderStatus> {
+ self.camera
+ .as_ref()
+ .map(AsyncVideoDecoderHandle::decoder_status)
+ }
+
pub fn screen_video_dimensions(&self) -> (u32, u32) {
self.screen.video_dimensions()
}
@@ -587,6 +571,8 @@ impl RecordingSegmentDecoders {
pub enum RenderingError {
#[error("No GPU adapter found")]
NoAdapter,
+ #[error("Project overlays require ordinary editor loading")]
+ PreparingOverlayContent,
#[error("No segments available in recording")]
NoSegments,
#[error(transparent)]
@@ -2000,6 +1986,7 @@ pub struct RenderVideoConstants {
pub background_textures: std::sync::Arc<BackgroundTextureCache>,
pub is_software_adapter: bool,
adapter_name: String,
+ frozen_recorded_cursors: Option<FrozenRecordedCursorAssets>,
}
pub struct SharedWgpuDevice {
@@ -2011,6 +1998,17 @@ pub struct SharedWgpuDevice {
}
impl RenderVideoConstants {
+ pub fn with_frozen_recorded_cursors(mut self, assets: FrozenRecordedCursorAssets) -> Self {
+ self.frozen_recorded_cursors = Some(assets);
+ self
+ }
+
+ pub fn frozen_cursor_error(&self) -> Option<FrozenCursorAssetError> {
+ self.frozen_recorded_cursors
+ .as_ref()
+ .and_then(FrozenRecordedCursorAssets::first_error)
+ }
+
pub fn new_with_device(
shared: SharedWgpuDevice,
segments: &[SegmentRecordings],
@@ -2045,6 +2043,7 @@ impl RenderVideoConstants {
background_textures,
meta,
recording_meta,
+ frozen_recorded_cursors: None,
is_software_adapter: shared.is_software_adapter,
adapter_name,
})
@@ -2074,6 +2073,7 @@ impl RenderVideoConstants {
background_textures,
meta,
recording_meta,
+ frozen_recorded_cursors: None,
is_software_adapter: shared.is_software_adapter,
adapter_name,
}
@@ -2107,13 +2107,17 @@ impl RenderVideoConstants {
recording_meta: RecordingMeta,
meta: StudioRecordingMeta,
) -> Result<Self, RenderingError> {
+ let constants_phase = readiness::Phase::start("constants.new");
+ let instance_phase = readiness::Phase::start("wgpu.instance");
let instance = create_wgpu_instance().await;
+ instance_phase.finish("returned");
let force_software_adapter = force_software_wgpu_adapter();
if force_software_adapter {
tracing::warn!("Forcing software WGPU adapter");
}
+ let adapter_phase = readiness::Phase::start("wgpu.adapter");
let hardware_adapter = if force_software_adapter {
None
} else {
@@ -2169,6 +2173,12 @@ impl RenderVideoConstants {
(software_adapter, true, adapter_info.name)
};
+ adapter_phase.finish(if is_software_adapter {
+ "software"
+ } else {
+ "hardware"
+ });
+
let mut required_features = wgpu::Features::empty();
if adapter.features().contains(wgpu::Features::PIPELINE_CACHE) {
required_features |= wgpu::Features::PIPELINE_CACHE;
@@ -2186,7 +2196,9 @@ impl RenderVideoConstants {
..Default::default()
};
+ let device_phase = readiness::Phase::start("wgpu.device");
let (device, queue) = adapter.request_device(&device_descriptor).await?;
+ device_phase.finish("returned");
let background_textures = Arc::new(BackgroundTextureCache::default());
@@ -2194,6 +2206,7 @@ impl RenderVideoConstants {
frame_pipeline::note_software_adapter_in_use();
}
+ constants_phase.finish("returned");
Ok(Self {
_instance: instance,
_adapter: adapter,
@@ -2203,6 +2216,7 @@ impl RenderVideoConstants {
background_textures,
meta,
recording_meta,
+ frozen_recorded_cursors: None,
is_software_adapter,
adapter_name,
})
@@ -5338,6 +5352,7 @@ mod style_image_tests {
.expect("studio metadata")
.clone(),
recording_meta,
+ frozen_recorded_cursors: None,
background_textures: Arc::new(BackgroundTextureCache::default()),
is_software_adapter: false,
};
@@ -5539,6 +5554,7 @@ mod nv12_flush_tests {
.expect("studio metadata")
.clone(),
recording_meta,
+ frozen_recorded_cursors: None,
background_textures: Arc::new(BackgroundTextureCache::default()),
is_software_adapter: software,
};
@@ -5624,6 +5640,7 @@ mod nv12_flush_tests {
pub struct FrameRenderer<'a> {
constants: &'a RenderVideoConstants,
+ readiness_first_render: bool,
session: Option<RenderSession>,
nv12_converter: Option<frame_pipeline::RgbaToNv12Converter>,
#[cfg(target_os = "macos")]
@@ -5640,6 +5657,7 @@ impl<'a> FrameRenderer<'a> {
pub fn new(constants: &'a RenderVideoConstants) -> Self {
Self {
constants,
+ readiness_first_render: true,
session: None,
nv12_converter: None,
#[cfg(target_os = "macos")]
@@ -5707,6 +5725,8 @@ impl<'a> FrameRenderer<'a> {
render_display: bool,
layers: &mut RendererLayers,
) -> Result<(Option<RenderedFrame>, FrameRenderStageTimings), RenderingError> {
+ let phase = std::mem::take(&mut self.readiness_first_render)
+ .then(|| readiness::Phase::start("frame.rgba_first_render"));
let mut last_error = None;
for attempt in 0..Self::MAX_RENDER_RETRIES {
@@ -5746,7 +5766,12 @@ impl<'a> FrameRenderer<'a> {
)
.await
{
- Ok(result) => return Ok(result),
+ Ok(result) => {
+ if let Some(phase) = phase {
+ phase.finish("submitted");
+ }
+ return Ok(result);
+ }
Err(RenderingError::BufferMapWaitingFailed) => {
tracing::warn!(
frame_number = uniforms.frame_number,
@@ -5946,6 +5971,8 @@ impl<'a> FrameRenderer<'a> {
render_display: bool,
layers: &mut RendererLayers,
) -> Result<SurfaceFrame, RenderingError> {
+ let phase = std::mem::take(&mut self.readiness_first_render)
+ .then(|| readiness::Phase::start("frame.bgra_first_render"));
let mut last_error = None;
for attempt in 0..Self::MAX_RENDER_RETRIES {
if attempt > 0 {
@@ -6001,7 +6028,7 @@ impl<'a> FrameRenderer<'a> {
session,
&uniforms,
render_display,
- );
+ )?;
let converter = self
.bgra_surface_converter
.as_mut()
@@ -6016,7 +6043,12 @@ impl<'a> FrameRenderer<'a> {
)
.await
{
- Ok(frame) => return Ok(frame),
+ Ok(frame) => {
+ if let Some(phase) = phase {
+ phase.finish("frame_ready");
+ }
+ return Ok(frame);
+ }
Err(RenderingError::BufferMapWaitingFailed) => {
last_error = Some(RenderingError::BufferMapWaitingFailed);
}
@@ -6419,7 +6451,7 @@ impl<'a> FrameRenderer<'a> {
session,
&uniforms,
render_display,
- );
+ )?;
match finish_encoder_nv12_pooled(
session,
@@ -6459,10 +6491,7 @@ pub struct RendererLayers {
camera: CameraLayer,
camera_only: CameraLayer,
mask: MaskLayer,
- text: TextLayer,
- images: ImageLayer,
- captions: CaptionsLayer,
- keyboard: KeyboardLayer,
+ overlays: Option<OverlayLayers>,
camera3d: Camera3DLayer,
camera_blur_processor: Option<cap_camera_effects::BlurProcessor>,
camera_blur_init_failed: bool,
@@ -6479,44 +6508,94 @@ impl RendererLayers {
queue: &wgpu::Queue,
prefer_cpu_conversion: bool,
) -> Self {
- let shared_yuv_pipelines = Arc::new(yuv_converter::YuvConverterPipelines::new(device));
- let shared_composite_pipeline =
- Arc::new(composite_frame::CompositeVideoFramePipeline::new(device));
+ Self::new_with_overlay_layers(device, queue, prefer_cpu_conversion, true)
+ }
+
+ pub fn new_for_preparing_preview(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ prefer_cpu_conversion: bool,
+ project: &ProjectConfiguration,
+ ) -> Result<Self, RenderingError> {
+ OverlayLayers::validate_omission(project, false)?;
+ Ok(Self::new_with_overlay_layers(
+ device,
+ queue,
+ prefer_cpu_conversion,
+ false,
+ ))
+ }
+
+ fn new_with_overlay_layers(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ prefer_cpu_conversion: bool,
+ include_overlays: bool,
+ ) -> Self {
+ let layers_phase = readiness::Phase::start("layers.new");
+ let shared_yuv_pipelines = readiness::measure("layers.shared_yuv", || {
+ Arc::new(yuv_converter::YuvConverterPipelines::new(device))
+ });
+ let shared_composite_pipeline = readiness::measure("layers.shared_composite", || {
+ Arc::new(composite_frame::CompositeVideoFramePipeline::new(device))
+ });
- Self {
- background: BackgroundLayer::new(device),
- background_blur: BlurLayer::new(device),
- background_color_grade: ColorGradeLayer::new(device),
- frame: FrameLayer::new(device, shared_composite_pipeline.clone()),
- notch: NotchLayer::new(device, shared_composite_pipeline.clone()),
- display: DisplayLayer::new_with_all_shared_pipelines(
- device,
- shared_yuv_pipelines.clone(),
- shared_composite_pipeline.clone(),
- prefer_cpu_conversion,
- ),
- click_ripple: ClickRippleLayer::new(device),
- cursor: CursorLayer::new(device),
- camera: CameraLayer::new_with_all_shared_pipelines(
- device,
- shared_yuv_pipelines.clone(),
- shared_composite_pipeline.clone(),
- ),
- camera_only: CameraLayer::new_with_all_shared_pipelines(
- device,
- shared_yuv_pipelines,
- shared_composite_pipeline,
- ),
- mask: MaskLayer::new(device),
- text: TextLayer::new(device, queue),
- images: ImageLayer::new(device),
- captions: CaptionsLayer::new(device, queue),
- keyboard: KeyboardLayer::new(device, queue),
- camera3d: Camera3DLayer::new(device),
+ let layers = Self {
+ background: readiness::measure("layers.background", || BackgroundLayer::new(device)),
+ background_blur: readiness::measure("layers.background_blur", || {
+ BlurLayer::new(device)
+ }),
+ background_color_grade: readiness::measure("layers.background_color_grade", || {
+ ColorGradeLayer::new(device)
+ }),
+ frame: readiness::measure("layers.frame", || {
+ FrameLayer::new(device, shared_composite_pipeline.clone())
+ }),
+ notch: readiness::measure("layers.notch", || {
+ NotchLayer::new(device, shared_composite_pipeline.clone())
+ }),
+ display: readiness::measure("layers.display", || {
+ DisplayLayer::new_with_all_shared_pipelines(
+ device,
+ shared_yuv_pipelines.clone(),
+ shared_composite_pipeline.clone(),
+ prefer_cpu_conversion,
+ )
+ }),
+ click_ripple: readiness::measure("layers.click_ripple", || {
+ ClickRippleLayer::new(device)
+ }),
+ cursor: readiness::measure("layers.cursor", || CursorLayer::new(device)),
+ camera: readiness::measure("layers.camera", || {
+ CameraLayer::new_with_all_shared_pipelines(
+ device,
+ shared_yuv_pipelines.clone(),
+ shared_composite_pipeline.clone(),
+ )
+ }),
+ camera_only: readiness::measure("layers.camera_only", || {
+ CameraLayer::new_with_all_shared_pipelines(
+ device,
+ shared_yuv_pipelines,
+ shared_composite_pipeline,
+ )
+ }),
+ mask: readiness::measure("layers.mask", || MaskLayer::new(device)),
+ overlays: include_overlays.then(|| OverlayLayers::new(device, queue)),
+ camera3d: readiness::measure("layers.camera3d", || Camera3DLayer::new(device)),
camera_blur_processor: None,
camera_blur_init_failed: false,
camera_blur_unavailable: false,
+ };
+ layers_phase.finish("returned");
+ layers
+ }
+
+ fn validate_overlay_uniforms(&self, uniforms: &ProjectUniforms) -> Result<(), RenderingError> {
+ if self.overlays.is_none() {
+ OverlayLayers::validate_omission(&uniforms.project, !uniforms.texts.is_empty())?;
}
+ Ok(())
}
fn ensure_camera_blur_processor(&mut self, device: &wgpu::Device) {
@@ -6638,7 +6717,9 @@ impl RendererLayers {
use_svg: bool,
cursor_type: &CursorType,
) {
- self.cursor.preload_assets(constants, use_svg, cursor_type);
+ readiness::measure("cursor.preload", || {
+ self.cursor.preload_assets(constants, use_svg, cursor_type)
+ });
}
pub async fn prepare(
@@ -6649,6 +6730,7 @@ impl RendererLayers {
cursor: &CursorEvents,
render_display: bool,
) -> Result<(), RenderingError> {
+ self.validate_overlay_uniforms(uniforms)?;
self.camera_blur_unavailable = false;
self.background
.prepare(
@@ -6731,39 +6813,41 @@ impl RendererLayers {
self.run_shared_camera_blur(&constants.device, &constants.queue, mode);
}
- self.images.prepare(constants, uniforms).await;
+ if let Some(overlays) = &mut self.overlays {
+ overlays.images.prepare(constants, uniforms).await;
- if uniforms.project.overlay_order.is_empty() {
- self.text.prepare(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
+ if uniforms.project.overlay_order.is_empty() {
+ overlays.text.prepare(
+ &constants.device,
+ &constants.queue,
+ uniforms.output_size,
+ &uniforms.texts,
+ );
+ } else {
+ overlays.text.prepare_mixed(
+ &constants.device,
+ &constants.queue,
+ uniforms.output_size,
+ &uniforms.texts,
+ );
+ }
+
+ overlays.captions.prepare(
+ uniforms,
+ segment_frames,
+ XY::new(uniforms.output_size.0, uniforms.output_size.1),
+ constants,
);
- } else {
- self.text.prepare_mixed(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
+
+ overlays.keyboard.prepare(
+ uniforms,
+ segment_frames,
+ XY::new(uniforms.output_size.0, uniforms.output_size.1),
+ constants,
+ overlays.captions.active_layout(),
);
}
- self.captions.prepare(
- uniforms,
- segment_frames,
- XY::new(uniforms.output_size.0, uniforms.output_size.1),
- constants,
- );
-
- self.keyboard.prepare(
- uniforms,
- segment_frames,
- XY::new(uniforms.output_size.0, uniforms.output_size.1),
- constants,
- self.captions.active_layout(),
- );
-
Ok(())
}
@@ -6797,6 +6881,7 @@ impl RendererLayers {
encoder: &mut wgpu::CommandEncoder,
render_display: bool,
) -> Result<FrameRenderStageTimings, RenderingError> {
+ self.validate_overlay_uniforms(uniforms)?;
self.camera_blur_unavailable = false;
let mut timings = FrameRenderStageTimings::default();
@@ -6906,44 +6991,46 @@ impl RendererLayers {
}
timings.camera_blur_prepare_duration = start.elapsed();
- let start = Instant::now();
- self.images.prepare(constants, uniforms).await;
+ if let Some(overlays) = &mut self.overlays {
+ let start = Instant::now();
+ overlays.images.prepare(constants, uniforms).await;
- if uniforms.project.overlay_order.is_empty() {
- self.text.prepare(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
+ if uniforms.project.overlay_order.is_empty() {
+ overlays.text.prepare(
+ &constants.device,
+ &constants.queue,
+ uniforms.output_size,
+ &uniforms.texts,
+ );
+ } else {
+ overlays.text.prepare_mixed(
+ &constants.device,
+ &constants.queue,
+ uniforms.output_size,
+ &uniforms.texts,
+ );
+ }
+ timings.text_prepare_duration = start.elapsed();
+
+ let start = Instant::now();
+ overlays.captions.prepare(
+ uniforms,
+ segment_frames,
+ XY::new(uniforms.output_size.0, uniforms.output_size.1),
+ constants,
);
- } else {
- self.text.prepare_mixed(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
+ timings.captions_prepare_duration = start.elapsed();
+
+ let start = Instant::now();
+ overlays.keyboard.prepare(
+ uniforms,
+ segment_frames,
+ XY::new(uniforms.output_size.0, uniforms.output_size.1),
+ constants,
+ overlays.captions.active_layout(),
);
+ timings.keyboard_prepare_duration = start.elapsed();
}
- timings.text_prepare_duration = start.elapsed();
-
- let start = Instant::now();
- self.captions.prepare(
- uniforms,
- segment_frames,
- XY::new(uniforms.output_size.0, uniforms.output_size.1),
- constants,
- );
- timings.captions_prepare_duration = start.elapsed();
-
- let start = Instant::now();
- self.keyboard.prepare(
- uniforms,
- segment_frames,
- XY::new(uniforms.output_size.0, uniforms.output_size.1),
- constants,
- self.captions.active_layout(),
- );
- timings.keyboard_prepare_duration = start.elapsed();
self.camera3d.prepare(&constants.queue, uniforms);
@@ -6958,7 +7045,8 @@ impl RendererLayers {
session: &mut RenderSession,
uniforms: &ProjectUniforms,
render_display: bool,
- ) {
+ ) -> Result<(), RenderingError> {
+ self.validate_overlay_uniforms(uniforms)?;
macro_rules! render_pass {
($view:expr, $load:expr) => {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -7129,16 +7217,18 @@ impl RendererLayers {
}
}
- if render_display && self.images.has_content() {
- let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.images.render(&mut pass);
- }
+ if let Some(overlays) = &self.overlays {
+ if render_display && overlays.images.has_content() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ overlays.images.render(&mut pass);
+ }
- if !uniforms.texts.is_empty() {
- let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.text.render(&mut pass);
+ if !uniforms.texts.is_empty() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ overlays.text.render(&mut pass);
+ }
}
- } else {
+ } else if let Some(overlays) = &self.overlays {
for overlay in uniforms.project.overlay_tracks().into_iter().rev() {
match overlay.kind {
OverlayTrackKind::Mask => {
@@ -7151,31 +7241,34 @@ impl RendererLayers {
}
}
OverlayTrackKind::Image
- if render_display && self.images.has_track(overlay.track) =>
+ if render_display && overlays.images.has_track(overlay.track) =>
{
let mut pass =
render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.images.render_track(&mut pass, overlay.track);
+ overlays.images.render_track(&mut pass, overlay.track);
}
- OverlayTrackKind::Text if self.text.has_track(overlay.track) => {
+ OverlayTrackKind::Text if overlays.text.has_track(overlay.track) => {
let mut pass =
render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.text.render_track(&mut pass, overlay.track);
+ overlays.text.render_track(&mut pass, overlay.track);
}
OverlayTrackKind::Text | OverlayTrackKind::Image => {}
}
}
}
- if self.keyboard.has_content() {
- let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.keyboard.render(&mut pass);
- }
+ if let Some(overlays) = &self.overlays {
+ if overlays.keyboard.has_content() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ overlays.keyboard.render(&mut pass);
+ }
- if self.captions.has_content() {
- let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.captions.render(&mut pass);
+ if overlays.captions.has_content() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ overlays.captions.render(&mut pass);
+ }
}
+ Ok(())
}
}
@@ -7215,7 +7308,7 @@ async fn produce_frame_with_timings(
session,
&uniforms,
render_display,
- );
+ )?;
timings.layer_render_duration = layer_render_start.elapsed();
let finish_start = Instant::now();
@@ -7267,7 +7360,7 @@ async fn produce_transition_texture(
session,
&outgoing.uniforms,
outgoing.render_display,
- );
+ )?;
compositor.capture_outgoing(&mut outgoing_encoder, session.current_texture());
constants
.queue
@@ -7299,7 +7392,7 @@ async fn produce_transition_texture(
session,
&incoming.uniforms,
incoming.render_display,
- );
+ )?;
compositor.capture_incoming_and_render(
&constants.queue,
&mut incoming_encoder,
diff --git a/crates/rendering/src/managed_segment.rs b/crates/rendering/src/managed_segment.rs
new file mode 100644
index 000000000..3b79de7f0
--- /dev/null
+++ b/crates/rendering/src/managed_segment.rs
@@ -0,0 +1,587 @@
+use crate::{
+ CAMERA_MAX_FALLBACK_DISTANCE, DecodedSegmentFrames, DecoderStatus,
+ SCREEN_MAX_FALLBACK_DISTANCE,
+ decoder::{
+ ManagedVideoDecoder, ManagedVideoError, ManagedVideoExit, ManagedVideoStopHandle,
+ spawn_managed_decoder,
+ },
+ segment_timing::{SegmentVideoTiming, segment_frame_times, segment_video_timing},
+};
+use cap_enc_ffmpeg::RelocatableSource;
+use cap_project::{ClipOffsets, StudioRecordingMeta, XY};
+use std::path::{Component, PathBuf};
+
+#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
+pub enum ManagedSegmentVideoError {
+ #[error("Invalid managed segment input: {0}")]
+ InvalidInput(String),
+ #[error("Display: {0}")]
+ Display(ManagedVideoError),
+ #[error("Camera: {0}")]
+ Camera(ManagedVideoError),
+}
+
+#[derive(Clone)]
+pub struct ManagedVideoTrackInput {
+ source: RelocatableSource,
+ paths: Vec<PathBuf>,
+}
+
+impl ManagedVideoTrackInput {
+ pub fn new(
+ source: RelocatableSource,
+ paths: Vec<PathBuf>,
+ ) -> Result<Self, ManagedSegmentVideoError> {
+ if paths.is_empty()
+ || paths.iter().any(|path| {
+ path.as_os_str().is_empty()
+ || !path.components().all(|part| match part {
+ Component::Normal(name) => !name.to_string_lossy().contains(['\\', ':']),
+ _ => false,
+ })
+ })
+ {
+ return Err(ManagedSegmentVideoError::InvalidInput(
+ "Track requires ordered source-relative paths".into(),
+ ));
+ }
+ Ok(Self { source, paths })
+ }
+}
+
+#[derive(Clone)]
+pub struct ManagedSegmentVideoInput {
+ segment_index: usize,
+ timing: SegmentVideoTiming,
+ display: ManagedVideoTrackInput,
+ camera: Option<ManagedVideoTrackInput>,
+}
+
+impl ManagedSegmentVideoInput {
+ pub fn new(
+ segment_index: usize,
+ metadata: &StudioRecordingMeta,
+ display: ManagedVideoTrackInput,
+ camera: Option<ManagedVideoTrackInput>,
+ ) -> Result<Self, ManagedSegmentVideoError> {
+ let timing = validated_timing(segment_index, metadata, camera.is_some())?;
+ Ok(Self {
+ segment_index,
+ timing,
+ display,
+ camera,
+ })
+ }
+
+ pub fn matches_metadata(&self, metadata: &StudioRecordingMeta) -> bool {
+ validated_timing(self.segment_index, metadata, self.camera.is_some())
+ .is_ok_and(|timing| timing == self.timing)
+ }
+
+ pub fn segment_index(&self) -> usize {
+ self.segment_index
+ }
+}
+
+fn validated_timing(
+ segment_index: usize,
+ metadata: &StudioRecordingMeta,
+ has_camera: bool,
+) -> Result<SegmentVideoTiming, ManagedSegmentVideoError> {
+ let valid_index = match metadata {
+ StudioRecordingMeta::SingleSegment { .. } => segment_index == 0,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => segment_index < inner.segments.len(),
+ };
+ if !valid_index {
+ return Err(ManagedSegmentVideoError::InvalidInput(
+ "Segment index is outside the stopped metadata".into(),
+ ));
+ }
+ let timing = segment_video_timing(metadata, segment_index);
+ let finite_starts = match metadata {
+ StudioRecordingMeta::SingleSegment { .. } => true,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ let segment = &inner.segments[segment_index];
+ std::iter::once(segment.display.start_time)
+ .chain(segment.camera.iter().map(|track| track.start_time))
+ .chain(segment.mic.iter().map(|track| track.start_time))
+ .chain(segment.system_audio.iter().map(|track| track.start_time))
+ .all(|start| start.is_some_and(f64::is_finite))
+ }
+ };
+ if !finite_starts
+ || !timing.screen_offset.is_finite()
+ || !timing.camera_offset.is_finite()
+ || !timing.latest_start_time.unwrap_or(0.0).is_finite()
+ || timing.screen_fps == 0
+ || timing.camera_fps == Some(0)
+ || has_camera != timing.camera_fps.is_some()
+ {
+ return Err(ManagedSegmentVideoError::InvalidInput(
+ "Track layout, FPS, or start times are invalid".into(),
+ ));
+ }
+ Ok(timing)
+}
+
+#[derive(Clone, Debug)]
+pub struct ManagedSegmentDecoderStatus {
+ pub segment_index: usize,
+ pub display: DecoderStatus,
+ pub camera: Option<DecoderStatus>,
+}
+
+#[derive(Clone, Default)]
+pub struct ManagedSegmentStopHandles {
+ display: Option<ManagedVideoStopHandle>,
+ camera: Option<ManagedVideoStopHandle>,
+}
+
+#[derive(Clone, Debug)]
+pub struct ManagedSegmentVideoExit {
+ pub display: Option<ManagedVideoExit>,
+ pub camera: Option<ManagedVideoExit>,
+}
+
+impl ManagedSegmentStopHandles {
+ pub fn cancel(&self) {
+ if let Some(display) = &self.display {
+ display.cancel();
+ }
+ if let Some(camera) = &self.camera {
+ camera.cancel();
+ }
+ }
+
+ pub async fn stop_and_wait(&self) -> ManagedSegmentVideoExit {
+ self.cancel();
+ let (display, camera) = tokio::join!(
+ async {
+ match &self.display {
+ Some(display) => Some(display.stop_and_wait().await),
+ None => None,
+ }
+ },
+ async {
+ match &self.camera {
+ Some(camera) => Some(camera.stop_and_wait().await),
+ None => None,
+ }
+ }
+ );
+ ManagedSegmentVideoExit { display, camera }
+ }
+}
+
+struct CancelSegmentReadiness(Option<ManagedSegmentStopHandles>);
+
+impl Drop for CancelSegmentReadiness {
+ fn drop(&mut self) {
+ if let Some(handles) = &self.0 {
+ handles.cancel();
+ }
+ }
+}
+
+pub struct ManagedRecordingSegmentDecoders {
+ segment_index: usize,
+ segment_offset: f64,
+ display: Option<ManagedVideoDecoder>,
+ camera: Option<ManagedVideoDecoder>,
+ handles: ManagedSegmentStopHandles,
+ terminal: std::sync::Mutex<Option<ManagedSegmentVideoError>>,
+ readiness_phase: Option<crate::readiness::Phase>,
+}
+
+impl ManagedRecordingSegmentDecoders {
+ #[cfg(test)]
+ pub(crate) fn from_test_workers(
+ display: ManagedVideoDecoder,
+ camera: ManagedVideoDecoder,
+ ) -> Self {
+ Self {
+ segment_index: 0,
+ segment_offset: 0.0,
+ handles: ManagedSegmentStopHandles {
+ display: Some(display.stop_handle()),
+ camera: Some(camera.stop_handle()),
+ },
+ display: Some(display),
+ camera: Some(camera),
+ terminal: std::sync::Mutex::new(None),
+ readiness_phase: None,
+ }
+ }
+
+ pub fn spawn(input: ManagedSegmentVideoInput, use_hw_acceleration: bool) -> Self {
+ let readiness_phase = crate::readiness::Phase::start("managed.spawn_to_ready");
+ let ManagedSegmentVideoInput {
+ segment_index,
+ timing,
+ display,
+ camera,
+ } = input;
+ let mut result = Self {
+ segment_index,
+ segment_offset: timing.latest_start_time.unwrap_or(0.0),
+ display: None,
+ camera: None,
+ handles: ManagedSegmentStopHandles::default(),
+ terminal: std::sync::Mutex::new(None),
+ readiness_phase: Some(readiness_phase),
+ };
+ match spawn_managed_decoder(
+ "screen",
+ display.source,
+ display.paths.iter().map(PathBuf::as_path),
+ timing.screen_fps,
+ timing.screen_offset,
+ use_hw_acceleration,
+ ) {
+ Ok(decoder) => {
+ result.handles.display = Some(decoder.stop_handle());
+ result.display =
+ Some(decoder.with_max_fallback_distance(SCREEN_MAX_FALLBACK_DISTANCE));
+ }
+ Err(error) => {
+ result.fail(ManagedSegmentVideoError::Display(error));
+ return result;
+ }
+ }
+ if let Some(camera) = camera {
+ match spawn_managed_decoder(
+ "camera",
+ camera.source,
+ camera.paths.iter().map(PathBuf::as_path),
+ timing
+ .camera_fps
+ .expect("Managed input validates camera metadata"),
+ timing.camera_offset,
+ use_hw_acceleration,
+ ) {
+ Ok(decoder) => {
+ result.handles.camera = Some(decoder.stop_handle());
+ result.camera =
+ Some(decoder.with_max_fallback_distance(CAMERA_MAX_FALLBACK_DISTANCE));
+ }
+ Err(error) => {
+ result.fail(ManagedSegmentVideoError::Camera(error));
+ result.handles.cancel();
+ }
+ }
+ }
+ result
+ }
+
+ pub fn stop_handles(&self) -> ManagedSegmentStopHandles {
+ self.handles.clone()
+ }
+
+ fn fail(&self, error: ManagedSegmentVideoError) -> ManagedSegmentVideoError {
+ self.terminal
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get_or_insert(error)
+ .clone()
+ }
+
+ pub fn terminal_error(&self) -> Option<ManagedSegmentVideoError> {
+ if let Some(error) = self
+ .terminal
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ {
+ return Some(error);
+ }
+ self.display
+ .as_ref()
+ .and_then(ManagedVideoDecoder::terminal_error)
+ .map(ManagedSegmentVideoError::Display)
+ .or_else(|| {
+ self.camera
+ .as_ref()
+ .and_then(ManagedVideoDecoder::terminal_error)
+ .map(ManagedSegmentVideoError::Camera)
+ })
+ .map(|error| self.fail(error))
+ }
+
+ pub async fn wait_ready(
+ &mut self,
+ ) -> Result<ManagedSegmentDecoderStatus, ManagedSegmentVideoError> {
+ let readiness_phase = self.readiness_phase.take();
+ if let Some(error) = self.terminal_error() {
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ let mut cancellation = CancelSegmentReadiness(Some(self.stop_handles()));
+ let result = tokio::try_join!(
+ async {
+ self.display
+ .as_mut()
+ .ok_or(ManagedSegmentVideoError::Display(
+ ManagedVideoError::NotReady,
+ ))?
+ .wait_ready()
+ .await
+ .map_err(ManagedSegmentVideoError::Display)
+ },
+ async {
+ match &mut self.camera {
+ Some(camera) => camera
+ .wait_ready()
+ .await
+ .map(Some)
+ .map_err(ManagedSegmentVideoError::Camera),
+ None => Ok(None),
+ }
+ }
+ );
+ cancellation.0 = None;
+ match result {
+ Ok((display, camera)) => {
+ if let Some(error) = self.terminal_error() {
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ if let Some(phase) = readiness_phase {
+ phase.finish("ready");
+ }
+ Ok(ManagedSegmentDecoderStatus {
+ segment_index: self.segment_index,
+ display,
+ camera,
+ })
+ }
+ Err(error) => {
+ let error = self.fail(error);
+ self.stop_and_wait().await;
+ Err(error)
+ }
+ }
+ }
+
+ pub async fn get_frames_initial(
+ &self,
+ segment_time: f32,
+ needs_camera: bool,
+ needs_display: bool,
+ offsets: ClipOffsets,
+ ) -> Result<DecodedSegmentFrames, ManagedSegmentVideoError> {
+ self.request_frames::<true>(segment_time, needs_camera, needs_display, offsets)
+ .await
+ }
+
+ pub async fn get_frames(
+ &self,
+ segment_time: f32,
+ needs_camera: bool,
+ needs_display: bool,
+ offsets: ClipOffsets,
+ ) -> Result<DecodedSegmentFrames, ManagedSegmentVideoError> {
+ self.request_frames::<false>(segment_time, needs_camera, needs_display, offsets)
+ .await
+ }
+
+ async fn request_frames<const INITIAL: bool>(
+ &self,
+ segment_time: f32,
+ needs_camera: bool,
+ needs_display: bool,
+ offsets: ClipOffsets,
+ ) -> Result<DecodedSegmentFrames, ManagedSegmentVideoError> {
+ if let Some(error) = self.terminal_error() {
+ return Err(error);
+ }
+ let display = self
+ .display
+ .as_ref()
+ .ok_or(ManagedSegmentVideoError::Display(
+ ManagedVideoError::NotReady,
+ ))?;
+ let status = display
+ .decoder_status()
+ .ok_or(ManagedSegmentVideoError::Display(
+ ManagedVideoError::NotReady,
+ ))?;
+ let (camera_time, recording_time) =
+ segment_frame_times(segment_time, self.segment_offset, offsets);
+ let result = tokio::try_join!(
+ async {
+ if !needs_display {
+ return Ok(None);
+ }
+ if INITIAL {
+ display.get_frame_initial(segment_time).await
+ } else {
+ display.get_frame(segment_time).await
+ }
+ .map(Some)
+ .map_err(ManagedSegmentVideoError::Display)
+ },
+ async {
+ let Some(camera) = self.camera.as_ref().filter(|_| needs_camera) else {
+ return Ok(None);
+ };
+ if INITIAL {
+ camera.get_frame_initial(camera_time).await
+ } else {
+ camera.get_frame(camera_time).await
+ }
+ .map(Some)
+ .map_err(ManagedSegmentVideoError::Camera)
+ }
+ );
+ let (screen_frame, camera_frame) = match result {
+ Ok(frames) => frames,
+ Err(error) => {
+ let error = self.fail(error);
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ };
+ if let Some(error) = self.terminal_error() {
+ self.stop_and_wait().await;
+ return Err(error);
+ }
+ Ok(DecodedSegmentFrames {
+ screen_size: XY::new(status.video_width, status.video_height),
+ screen_frame,
+ camera_frame,
+ segment_time,
+ recording_time,
+ segment_has_camera: self.camera.is_some(),
+ })
+ }
+
+ pub async fn stop_and_wait(&self) -> ManagedSegmentVideoExit {
+ self.handles.stop_and_wait().await
+ }
+
+ pub async fn wait_for_terminal(&self) -> ManagedSegmentVideoError {
+ if let Some(error) = self.terminal_error() {
+ return error;
+ }
+ match (&self.handles.display, &self.handles.camera) {
+ (Some(display), Some(camera)) => {
+ tokio::select! {
+ error = display.wait_for_terminal() => self.fail(ManagedSegmentVideoError::Display(error)),
+ error = camera.wait_for_terminal() => self.fail(ManagedSegmentVideoError::Camera(error)),
+ }
+ }
+ (Some(display), None) => self.fail(ManagedSegmentVideoError::Display(
+ display.wait_for_terminal().await,
+ )),
+ _ => self.fail(ManagedSegmentVideoError::InvalidInput(
+ "Managed display worker is unavailable".into(),
+ )),
+ }
+ }
+}
+
+impl Drop for ManagedRecordingSegmentDecoders {
+ fn drop(&mut self) {
+ self.handles.cancel();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn metadata() -> StudioRecordingMeta {
+ serde_json::from_value(serde_json::json!({
+ "segments": [{
+ "display": {"path":"display.mp4", "fps":60, "start_time":10.0},
+ "camera": {"path":"camera.mp4", "fps":24, "start_time":10.125},
+ "mic": {"path":"mic.aac", "start_time":10.25}
+ }]
+ }))
+ .unwrap()
+ }
+
+ fn track(source: &RelocatableSource) -> ManagedVideoTrackInput {
+ ManagedVideoTrackInput::new(
+ source.clone(),
+ vec![PathBuf::from("segment-0").join("display").join("init.mp4")],
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn owned_input_accepts_native_relative_components_without_opening_media() {
+ let directory = tempfile::tempdir().unwrap();
+ let source = RelocatableSource::new(directory.path().to_path_buf()).unwrap();
+ let input =
+ ManagedSegmentVideoInput::new(0, &metadata(), track(&source), Some(track(&source)))
+ .unwrap();
+ assert_eq!(input.segment_index(), 0);
+ assert_eq!(input.timing.screen_offset, 0.25);
+ assert_eq!(input.timing.camera_offset, 0.125);
+ assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
+ for paths in [
+ Vec::new(),
+ vec![PathBuf::new()],
+ vec![PathBuf::from("../init.mp4")],
+ vec![directory.path().join("init.mp4")],
+ vec![PathBuf::from("D:init.mp4")],
+ ] {
+ assert!(ManagedVideoTrackInput::new(source.clone(), paths).is_err());
+ }
+ }
+
+ #[test]
+ fn managed_input_declines_bad_index_camera_layout_and_nonfinite_starts() {
+ let directory = tempfile::tempdir().unwrap();
+ let source = RelocatableSource::new(directory.path().to_path_buf()).unwrap();
+ assert!(
+ ManagedSegmentVideoInput::new(1, &metadata(), track(&source), Some(track(&source)))
+ .is_err()
+ );
+ assert!(ManagedSegmentVideoInput::new(0, &metadata(), track(&source), None).is_err());
+ let mut metadata = metadata();
+ let StudioRecordingMeta::MultipleSegments { inner } = &mut metadata else {
+ panic!("Expected multi-segment metadata");
+ };
+ inner.segments[0].mic.as_mut().unwrap().start_time = Some(f64::NAN);
+ assert!(
+ ManagedSegmentVideoInput::new(0, &metadata, track(&source), Some(track(&source)))
+ .is_err()
+ );
+ let StudioRecordingMeta::MultipleSegments { inner } = &mut metadata else {
+ panic!("Expected multi-segment metadata");
+ };
+ inner.segments[0].mic.as_mut().unwrap().start_time = Some(10.25);
+ inner.segments[0].camera.as_mut().unwrap().fps = 0;
+ assert!(
+ ManagedSegmentVideoInput::new(0, &metadata, track(&source), Some(track(&source)))
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn managed_input_requires_start_times_for_every_declared_track() {
+ let directory = tempfile::tempdir().unwrap();
+ let source = RelocatableSource::new(directory.path().to_path_buf()).unwrap();
+ for missing in 0..4 {
+ let mut metadata = metadata();
+ let StudioRecordingMeta::MultipleSegments { inner } = &mut metadata else {
+ panic!("Expected multi-segment metadata");
+ };
+ let segment = &mut inner.segments[0];
+ segment.system_audio = segment.mic.clone();
+ let starts = [
+ &mut segment.display.start_time,
+ &mut segment.camera.as_mut().unwrap().start_time,
+ &mut segment.mic.as_mut().unwrap().start_time,
+ &mut segment.system_audio.as_mut().unwrap().start_time,
+ ];
+ *starts.into_iter().nth(missing).unwrap() = None;
+ assert!(
+ ManagedSegmentVideoInput::new(0, &metadata, track(&source), Some(track(&source)))
+ .is_err()
+ );
+ }
+ }
+}
diff --git a/crates/rendering/src/overlay_layers.rs b/crates/rendering/src/overlay_layers.rs
new file mode 100644
index 000000000..513de7ab6
--- /dev/null
+++ b/crates/rendering/src/overlay_layers.rs
@@ -0,0 +1,152 @@
+use crate::{
+ ProjectConfiguration, RenderingError,
+ layers::{CaptionsLayer, ImageLayer, KeyboardLayer, TextLayer},
+ readiness,
+};
+
+pub(super) struct OverlayLayers {
+ pub(super) text: TextLayer,
+ pub(super) images: ImageLayer,
+ pub(super) captions: CaptionsLayer,
+ pub(super) keyboard: KeyboardLayer,
+}
+
+impl OverlayLayers {
+ pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
+ Self {
+ text: readiness::measure("layers.text", || TextLayer::new(device, queue)),
+ images: readiness::measure("layers.images", || ImageLayer::new(device)),
+ captions: readiness::measure("layers.captions", || CaptionsLayer::new(device, queue)),
+ keyboard: readiness::measure("layers.keyboard", || KeyboardLayer::new(device, queue)),
+ }
+ }
+
+ pub(super) fn validate_omission(
+ project: &ProjectConfiguration,
+ has_prepared_text: bool,
+ ) -> Result<(), RenderingError> {
+ if has_prepared_text
+ || project.captions.is_some()
+ || project.keyboard.is_some()
+ || !project.annotations.is_empty()
+ || !project.hidden_text_segments.is_empty()
+ || !project.overlay_order.is_empty()
+ || project.timeline.as_ref().is_some_and(|timeline| {
+ !timeline.text_segments.is_empty()
+ || !timeline.image_segments.is_empty()
+ || !timeline.caption_segments.is_empty()
+ || !timeline.keyboard_segments.is_empty()
+ })
+ {
+ Err(RenderingError::PreparingOverlayContent)
+ } else {
+ Ok(())
+ }
+ }
+}
+
+#[cfg(test)]
+mod native_tests;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn project() -> ProjectConfiguration {
+ ProjectConfiguration {
+ timeline: Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": [],
+ "zoomSegments": []
+ }))
+ .unwrap(),
+ ),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn omitted_layers_accept_an_overlay_free_project() {
+ assert!(OverlayLayers::validate_omission(&project(), false).is_ok());
+ assert!(OverlayLayers::validate_omission(&ProjectConfiguration::default(), false).is_ok());
+ }
+
+ #[test]
+ fn prepared_text_cannot_bypass_project_admission() {
+ assert!(matches!(
+ OverlayLayers::validate_omission(&project(), true),
+ Err(RenderingError::PreparingOverlayContent)
+ ));
+ }
+
+ #[test]
+ fn every_declared_overlay_source_requires_the_bundle() {
+ let mutations: [fn(&mut ProjectConfiguration); 9] =
+ [
+ |project| project.captions = Some(Default::default()),
+ |project| project.keyboard = Some(Default::default()),
+ |project| project.hidden_text_segments.push(0),
+ |project| {
+ project.overlay_order.push(cap_project::OverlayTrack {
+ kind: cap_project::OverlayTrackKind::Mask,
+ track: 0,
+ });
+ },
+ |project| {
+ project.annotations.push(
+ serde_json::from_value(serde_json::json!({
+ "id": "text", "type": "text", "x": 0.0, "y": 0.0,
+ "width": 1.0, "height": 1.0, "strokeColor": "#000000",
+ "strokeWidth": 1.0, "fillColor": "#ffffff", "opacity": 0.0,
+ "rotation": 0.0, "text": "hidden annotation"
+ }))
+ .unwrap(),
+ );
+ },
+ |project| {
+ project.timeline.as_mut().unwrap().text_segments.push(
+ serde_json::from_value(serde_json::json!({
+ "start": 0.0, "end": 1.0, "enabled": false
+ }))
+ .unwrap(),
+ );
+ },
+ |project| {
+ project.timeline.as_mut().unwrap().image_segments.push(
+ cap_project::ImageSegment {
+ enabled: false,
+ path: "unopened-overlay.png".into(),
+ ..Default::default()
+ },
+ );
+ },
+ |project| {
+ project.timeline.as_mut().unwrap().caption_segments.push(
+ serde_json::from_value(serde_json::json!({
+ "id": "caption", "start": 0.0, "end": 1.0, "text": "caption"
+ }))
+ .unwrap(),
+ );
+ },
+ |project| {
+ project.timeline.as_mut().unwrap().keyboard_segments.push(
+ serde_json::from_value(serde_json::json!({
+ "id": "keys", "start": 0.0, "end": 1.0, "displayText": "A"
+ }))
+ .unwrap(),
+ );
+ },
+ ];
+ for (index, mutate) in mutations.iter().enumerate() {
+ let mut project = project();
+ mutate(&mut project);
+ assert!(
+ matches!(
+ OverlayLayers::validate_omission(&project, false),
+ Err(RenderingError::PreparingOverlayContent)
+ ),
+ "overlay source {index} bypassed the missing bundle guard"
+ );
+ }
+ }
+}
diff --git a/crates/rendering/src/overlay_layers/native_tests.rs b/crates/rendering/src/overlay_layers/native_tests.rs
new file mode 100644
index 000000000..db1695c6b
--- /dev/null
+++ b/crates/rendering/src/overlay_layers/native_tests.rs
@@ -0,0 +1,368 @@
+use crate::{
+ CursorEvents, DecodedFrame, DecodedSegmentFrames, FrameLayout, FrameRenderer,
+ ProjectConfiguration, ProjectUniforms, RecordingMeta, RenderOptions, RenderVideoConstants,
+ RenderedFrame, RendererLayers, RenderingError, XY, ZoomTransformTimeline,
+ frame_pipeline::{RenderSession, finish_encoder_timed, flush_pending_readback},
+};
+use std::path::Path;
+
+const WIDTH: u32 = 160;
+const HEIGHT: u32 = 120;
+
+async fn constants(path: &Path) -> RenderVideoConstants {
+ let mut metadata: RecordingMeta = serde_json::from_value(serde_json::json!({
+ "pretty_name": "overlay boundary",
+ "display": {"path": "unused.mp4", "fps": 30},
+ "camera": null, "audio": null, "cursor": null
+ }))
+ .unwrap();
+ metadata.project_path = path.to_path_buf();
+ let studio = metadata.studio_meta().unwrap().clone();
+ let constants = RenderVideoConstants::new_with_options(
+ RenderOptions {
+ screen_size: XY::new(WIDTH, HEIGHT),
+ camera_size: None,
+ preserve_screen_alpha: false,
+ },
+ metadata,
+ studio,
+ )
+ .await
+ .expect("Native overlay tests require a real WGPU adapter and device");
+ let info = constants._adapter.get_info();
+ assert_ne!(info.backend, wgpu::Backend::Noop);
+ eprintln!(
+ "{}",
+ serde_json::json!({
+ "test": "overlay_native_boundary",
+ "adapter": info.name,
+ "backend": format!("{:?}", info.backend),
+ "deviceType": format!("{:?}", info.device_type),
+ "software": constants.is_software_adapter
+ })
+ );
+ constants
+}
+
+fn project() -> ProjectConfiguration {
+ ProjectConfiguration {
+ background: cap_project::BackgroundConfiguration {
+ shadow: 0.0,
+ advanced_shadow: None,
+ ..Default::default()
+ },
+ timeline: Some(
+ serde_json::from_value(serde_json::json!({
+ "segments": [{"recordingSegment": 0, "start": 0.0, "end": 3.0, "timescale": 1.0}],
+ "zoomSegments": []
+ }))
+ .unwrap(),
+ ),
+ screen_motion_blur: 0.0,
+ ..Default::default()
+ }
+}
+
+fn frames() -> DecodedSegmentFrames {
+ DecodedSegmentFrames {
+ screen_size: XY::new(WIDTH, HEIGHT),
+ screen_frame: Some(DecodedFrame::new(
+ [17, 43, 89, 255].repeat(WIDTH as usize * HEIGHT as usize),
+ WIDTH,
+ HEIGHT,
+ )),
+ camera_frame: None,
+ segment_time: 0.0,
+ recording_time: 0.0,
+ segment_has_camera: false,
+ }
+}
+
+fn uniforms(
+ constants: &RenderVideoConstants,
+ project: &ProjectConfiguration,
+ frame: u32,
+) -> ProjectUniforms {
+ let cursor = CursorEvents::default();
+ let zoom =
+ ZoomTransformTimeline::from_project(project, &cursor, 3.0, constants.options.screen_size);
+ ProjectUniforms::new(
+ constants,
+ project,
+ frame,
+ 30,
+ XY::new(320, 240),
+ &cursor,
+ &frames(),
+ 3.0,
+ &zoom,
+ )
+}
+
+fn pixels(frame: &RenderedFrame) -> Vec<u8> {
+ frame
+ .data
+ .chunks_exact(frame.padded_bytes_per_row as usize)
+ .take(frame.height as usize)
+ .flat_map(|row| row[..frame.width as usize * 4].iter().copied())
+ .collect()
+}
+
+async fn render(
+ constants: &RenderVideoConstants,
+ project: &ProjectConfiguration,
+ layers: &mut RendererLayers,
+ frame: u32,
+) -> (RenderedFrame, FrameLayout) {
+ let uniforms = uniforms(constants, project, frame);
+ let layout = uniforms.frame_layout();
+ let output = FrameRenderer::new(constants)
+ .render_immediate(frames(), uniforms, &CursorEvents::default(), true, layers)
+ .await
+ .expect("Native overlay frame must render");
+ (output, layout)
+}
+
+fn with_overlay(kind: &str, path: &str) -> ProjectConfiguration {
+ let mut project = project();
+ let timeline = project.timeline.as_mut().unwrap();
+ match kind {
+ "image" => timeline.image_segments.push(cap_project::ImageSegment {
+ start: 0.0,
+ end: 3.0,
+ path: path.into(),
+ size: cap_project::XY::new(0.6, 0.6),
+ ..Default::default()
+ }),
+ "text" => timeline.text_segments.push(
+ serde_json::from_value(serde_json::json!({
+ "start": 0.0, "end": 3.0, "content": "Visible text",
+ "fontSize": 96.0, "fadeDuration": 0.0
+ }))
+ .unwrap(),
+ ),
+ "captions" => {
+ project.captions = Some(cap_project::CaptionsData {
+ settings: cap_project::CaptionSettings {
+ enabled: true,
+ ..Default::default()
+ },
+ ..Default::default()
+ });
+ timeline.caption_segments.push(
+ serde_json::from_value(serde_json::json!({
+ "id": "caption", "start": 0.0, "end": 3.0, "text": "Visible caption"
+ }))
+ .unwrap(),
+ );
+ }
+ "keyboard" => {
+ project.keyboard = Some(cap_project::KeyboardData {
+ settings: cap_project::KeyboardSettings {
+ enabled: true,
+ ..Default::default()
+ },
+ });
+ timeline.keyboard_segments.push(
+ serde_json::from_value(serde_json::json!({
+ "id": "keys", "start": 0.0, "end": 3.0, "displayText": "Command A"
+ }))
+ .unwrap(),
+ );
+ }
+ _ => panic!("Unknown test overlay"),
+ }
+ project
+}
+
+#[tokio::test]
+async fn ordinary_bundle_renders_each_overlay_and_preserves_empty_frame_zero() {
+ let directory = tempfile::tempdir().unwrap();
+ let constants = constants(directory.path()).await;
+ image::RgbaImage::from_pixel(16, 16, image::Rgba([255, 16, 32, 255]))
+ .save(directory.path().join("overlay.png"))
+ .unwrap();
+ std::fs::write(directory.path().join("corrupt.png"), b"invalid image").unwrap();
+ let mut full = RendererLayers::new(&constants.device, &constants.queue);
+ assert!(full.overlays.is_some());
+ let mut configured = RendererLayers::new_with_options(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ );
+ assert!(configured.overlays.is_some());
+ let mut restricted = RendererLayers::new_for_preparing_preview(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ &project(),
+ )
+ .unwrap();
+ assert!(restricted.overlays.is_none());
+ let expected = render(&constants, &project(), &mut full, 0).await;
+ let actual = render(&constants, &project(), &mut restricted, 0).await;
+ assert_eq!(actual.1, expected.1);
+ assert_eq!(actual.0.frame_number, 0);
+ assert_eq!(expected.0.frame_number, 0);
+ assert!(actual.0.width > 0 && actual.0.height > 0);
+ assert_eq!(
+ pixels(&actual.0).len(),
+ actual.0.width as usize * actual.0.height as usize * 4
+ );
+ assert_eq!(pixels(&actual.0), pixels(&expected.0));
+ let baseline = render(&constants, &project(), &mut configured, 30).await;
+ for kind in ["image", "text", "captions", "keyboard"] {
+ let project = with_overlay(kind, "overlay.png");
+ let actual = render(&constants, &project, &mut configured, 30).await;
+ let overlays = configured.overlays.as_ref().unwrap();
+ let present = match kind {
+ "image" => overlays.images.has_content(),
+ "text" => !uniforms(&constants, &project, 30).texts.is_empty(),
+ "captions" => overlays.captions.has_content(),
+ "keyboard" => overlays.keyboard.has_content(),
+ _ => unreachable!(),
+ };
+ assert!(present, "Ordinary {kind} did not prepare content");
+ assert_ne!(
+ pixels(&actual.0),
+ pixels(&baseline.0),
+ "Ordinary {kind} was omitted"
+ );
+ assert!(matches!(
+ RendererLayers::new_for_preparing_preview(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ &project,
+ ),
+ Err(RenderingError::PreparingOverlayContent)
+ ));
+ }
+ let corrupt = render(
+ &constants,
+ &with_overlay("image", "corrupt.png"),
+ &mut configured,
+ 30,
+ )
+ .await;
+ assert!(!configured.overlays.as_ref().unwrap().images.has_content());
+ assert_eq!(pixels(&corrupt.0), pixels(&baseline.0));
+}
+
+async fn read_session(
+ constants: &RenderVideoConstants,
+ session: &mut RenderSession,
+ uniforms: &ProjectUniforms,
+ encoder: wgpu::CommandEncoder,
+) -> Vec<u8> {
+ let (previous, _) = finish_encoder_timed(
+ session,
+ &constants.device,
+ &constants.queue,
+ uniforms,
+ encoder,
+ )
+ .await
+ .unwrap();
+ assert!(previous.is_none());
+ pixels(
+ &flush_pending_readback(session, &constants.device)
+ .await
+ .unwrap()
+ .unwrap(),
+ )
+}
+
+#[tokio::test]
+async fn restricted_late_uniforms_fail_before_prepare_or_direct_render_work() {
+ let directory = tempfile::tempdir().unwrap();
+ let constants = constants(directory.path()).await;
+ let project = project();
+ let mut layers = RendererLayers::new_for_preparing_preview(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ &project,
+ )
+ .unwrap();
+ let clean = uniforms(&constants, &project, 30);
+ let late_project = uniforms(&constants, &with_overlay("image", "must-not-open.png"), 30);
+ let mut late_text = uniforms(&constants, &with_overlay("text", ""), 30);
+ assert!(!late_text.texts.is_empty());
+ late_text.project = project;
+ let mut session =
+ RenderSession::new(&constants.device, clean.output_size.0, clean.output_size.1);
+ let mut encoder = constants.device.create_command_encoder(&Default::default());
+ {
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("Overlay guard sentinel"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: session.current_texture_view(),
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color {
+ r: 0.25,
+ g: 0.5,
+ b: 0.75,
+ a: 1.0,
+ }),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ }
+ let expected = read_session(&constants, &mut session, &clean, encoder).await;
+ for late in [late_project, late_text] {
+ for render_display in [false, true] {
+ layers.camera_blur_unavailable = true;
+ assert!(matches!(
+ layers
+ .prepare(
+ &constants,
+ &late,
+ &frames(),
+ &CursorEvents::default(),
+ render_display
+ )
+ .await,
+ Err(RenderingError::PreparingOverlayContent)
+ ));
+ assert!(layers.camera_blur_unavailable);
+ let mut encoder = constants.device.create_command_encoder(&Default::default());
+ assert!(matches!(
+ layers
+ .prepare_with_encoder_timed(
+ &constants,
+ &late,
+ &frames(),
+ &CursorEvents::default(),
+ &mut encoder,
+ render_display
+ )
+ .await,
+ Err(RenderingError::PreparingOverlayContent)
+ ));
+ assert!(layers.camera_blur_unavailable);
+ assert!(matches!(
+ layers.render(
+ &constants.device,
+ &constants.queue,
+ &mut encoder,
+ &mut session,
+ &late,
+ render_display
+ ),
+ Err(RenderingError::PreparingOverlayContent)
+ ));
+ let actual = read_session(&constants, &mut session, &clean, encoder).await;
+ assert_eq!(
+ actual, expected,
+ "Rejected uniforms changed the target texture"
+ );
+ }
+ }
+ assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
+}
diff --git a/crates/rendering/src/project_recordings.rs b/crates/rendering/src/project_recordings.rs
index 9e4e3f471..ce6d2a32d 100644
--- a/crates/rendering/src/project_recordings.rs
+++ b/crates/rendering/src/project_recordings.rs
@@ -18,61 +18,70 @@ pub struct Video {
impl Video {
pub fn new(path: impl AsRef<Path>, start_time: f64) -> Result<Self, String> {
- fn inner(path: &Path, start_time: f64) -> Result<Video, String> {
- let input =
- ffmpeg::format::input(path).map_err(|e| format!("Failed to open video: {e}"))?;
- let stream = input
- .streams()
- .best(ffmpeg::media::Type::Video)
- .ok_or_else(|| "No video stream found".to_string())?;
-
- let decoder_ctx = ffmpeg::codec::Context::from_parameters(stream.parameters())
- .map_err(|e| format!("Failed to create decoder context: {e}"))?;
- let decoder = decoder_ctx
- .decoder()
- .video()
- .map_err(|e| format!("Failed to get video decoder: {e}"))?;
-
- let width = decoder.width();
- let height = decoder.height();
-
- if width == 0 || height == 0 {
- return Err("Invalid video dimensions".to_string());
- }
+ let path = path.as_ref();
+ if path.is_dir() {
+ let input = cap_video_decode::ffmpeg::open_fragmented_input(path)?;
+ Self::from_input(input.input(), start_time)
+ } else {
+ let input = ffmpeg::format::input(path)
+ .map_err(|error| format!("Failed to open video: {error}"))?;
+ Self::from_input(&input, start_time)
+ }
+ }
- let rate = stream.avg_frame_rate();
- let fps = if rate.denominator() != 0 {
- rate.numerator() as f64 / rate.denominator() as f64
- } else {
- 30.0
- };
+ pub fn from_input(
+ input: &ffmpeg::format::context::Input,
+ start_time: f64,
+ ) -> Result<Self, String> {
+ let stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Video)
+ .ok_or_else(|| "No video stream found".to_string())?;
+
+ let decoder_ctx = ffmpeg::codec::Context::from_parameters(stream.parameters())
+ .map_err(|e| format!("Failed to create decoder context: {e}"))?;
+ let decoder = decoder_ctx
+ .decoder()
+ .video()
+ .map_err(|e| format!("Failed to get video decoder: {e}"))?;
+
+ let width = decoder.width();
+ let height = decoder.height();
+
+ if width == 0 || height == 0 {
+ return Err("Invalid video dimensions".to_string());
+ }
+
+ let rate = stream.avg_frame_rate();
+ let fps = if rate.denominator() != 0 {
+ rate.numerator() as f64 / rate.denominator() as f64
+ } else {
+ 30.0
+ };
- let duration = {
- let container_duration = input.duration();
- if container_duration > 0 {
- container_duration as f64 / 1_000_000.0
+ let duration = {
+ let container_duration = input.duration();
+ if container_duration > 0 {
+ container_duration as f64 / 1_000_000.0
+ } else {
+ let stream_duration = stream.duration();
+ let time_base = stream.time_base();
+ if stream_duration > 0 && time_base.denominator() > 0 {
+ stream_duration as f64 * time_base.numerator() as f64
+ / time_base.denominator() as f64
} else {
- let stream_duration = stream.duration();
- let time_base = stream.time_base();
- if stream_duration > 0 && time_base.denominator() > 0 {
- stream_duration as f64 * time_base.numerator() as f64
- / time_base.denominator() as f64
- } else {
- return Err("Could not determine video duration".to_string());
- }
+ return Err("Could not determine video duration".to_string());
}
- };
-
- Ok(Video {
- width,
- height,
- duration,
- fps: fps.round() as u32,
- start_time,
- })
- }
+ }
+ };
- inner(path.as_ref(), start_time)
+ Ok(Video {
+ width,
+ height,
+ duration,
+ fps: fps.round() as u32,
+ start_time,
+ })
}
pub fn fps(&self) -> u32 {
@@ -90,29 +99,32 @@ pub struct Audio {
impl Audio {
pub fn new(path: impl AsRef<Path>, start_time: f64) -> Result<Self, String> {
- fn inner(path: &Path, start_time: f64) -> Result<Audio, String> {
- let input =
- ffmpeg::format::input(path).map_err(|e| format!("Failed to open audio: {e}"))?;
- let stream = input
- .streams()
- .best(ffmpeg::media::Type::Audio)
- .ok_or_else(|| "No audio stream found".to_string())?;
-
- let audio_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())
- .map_err(|e| format!("Failed to create decoder: {e}"))?
- .decoder()
- .audio()
- .map_err(|e| format!("Failed to get audio decoder: {e}"))?;
-
- Ok(Audio {
- duration: input.duration() as f64 / 1_000_000.0,
- sample_rate: audio_decoder.rate(),
- channels: audio_decoder.channels(),
- start_time,
- })
- }
+ let input = ffmpeg::format::input(path.as_ref())
+ .map_err(|e| format!("Failed to open audio: {e}"))?;
+ Self::from_input(&input, start_time)
+ }
- inner(path.as_ref(), start_time)
+ pub fn from_input(
+ input: &ffmpeg::format::context::Input,
+ start_time: f64,
+ ) -> Result<Self, String> {
+ let stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Audio)
+ .ok_or_else(|| "No audio stream found".to_string())?;
+
+ let audio_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())
+ .map_err(|e| format!("Failed to create decoder: {e}"))?
+ .decoder()
+ .audio()
+ .map_err(|e| format!("Failed to get audio decoder: {e}"))?;
+
+ Ok(Audio {
+ duration: input.duration() as f64 / 1_000_000.0,
+ sample_rate: audio_decoder.rate(),
+ channels: audio_decoder.channels(),
+ start_time,
+ })
}
}
diff --git a/crates/rendering/src/readiness.rs b/crates/rendering/src/readiness.rs
new file mode 100644
index 000000000..6dacf7c36
--- /dev/null
+++ b/crates/rendering/src/readiness.rs
@@ -0,0 +1,70 @@
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::Instant;
+
+static NEXT_PHASE_ID: AtomicU64 = AtomicU64::new(1);
+
+pub(crate) struct Phase {
+ active: Option<ActivePhase>,
+}
+
+struct ActivePhase {
+ name: &'static str,
+ id: u64,
+ started: Instant,
+}
+
+impl Phase {
+ pub(crate) fn start(name: &'static str) -> Self {
+ let active = tracing::enabled!(target: "cap_rendering::readiness", tracing::Level::DEBUG)
+ .then(|| {
+ let active = ActivePhase {
+ name,
+ id: NEXT_PHASE_ID.fetch_add(1, Ordering::Relaxed),
+ started: Instant::now(),
+ };
+ active.emit("start");
+ active
+ });
+ Self { active }
+ }
+
+ pub(crate) fn mark(&self, event: &'static str) {
+ if let Some(active) = &self.active {
+ active.emit(event);
+ }
+ }
+
+ pub(crate) fn finish(mut self, outcome: &'static str) {
+ if let Some(active) = self.active.take() {
+ active.emit(outcome);
+ }
+ }
+}
+
+impl ActivePhase {
+ fn emit(&self, event: &'static str) {
+ tracing::debug!(
+ target: "cap_rendering::readiness",
+ phase = self.name,
+ phase_id = self.id,
+ event,
+ elapsed_ms = self.started.elapsed().as_secs_f64() * 1_000.0,
+ "Renderer readiness phase"
+ );
+ }
+}
+
+impl Drop for Phase {
+ fn drop(&mut self) {
+ if let Some(active) = self.active.take() {
+ active.emit("dropped_before_finish");
+ }
+ }
+}
+
+pub(crate) fn measure<T>(name: &'static str, operation: impl FnOnce() -> T) -> T {
+ let phase = Phase::start(name);
+ let output = operation();
+ phase.finish("returned");
+ output
+}
diff --git a/crates/rendering/src/recorded_cursor_assets.rs b/crates/rendering/src/recorded_cursor_assets.rs
new file mode 100644
index 000000000..ae4c59e50
--- /dev/null
+++ b/crates/rendering/src/recorded_cursor_assets.rs
@@ -0,0 +1,307 @@
+use cap_project::{CursorMeta, XY};
+use std::{
+ collections::HashMap,
+ sync::{Arc, OnceLock},
+};
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum FrozenCursorAssetError {
+ #[error("Frozen recorded cursor ID is empty")]
+ EmptyId,
+ #[error("Duplicate frozen recorded cursor ID: {0}")]
+ DuplicateId(String),
+ #[error("Frozen recorded cursor is missing: {0}")]
+ Missing(String),
+ #[error("Failed to decode frozen recorded cursor {cursor_id}: {message}")]
+ Decode { cursor_id: String, message: String },
+}
+
+struct FrozenRecordedCursor {
+ metadata: CursorMeta,
+ bytes: Arc<[u8]>,
+}
+
+struct FrozenRecordedCursorState {
+ assets: HashMap<String, FrozenRecordedCursor>,
+ first_error: OnceLock<FrozenCursorAssetError>,
+}
+
+#[derive(Clone)]
+pub struct FrozenRecordedCursorAssets {
+ state: Arc<FrozenRecordedCursorState>,
+}
+
+pub(crate) struct DecodedRecordedCursor {
+ pub(crate) image: image::DynamicImage,
+ pub(crate) hotspot: XY<f64>,
+}
+
+pub(crate) fn select_recorded_cursor_image(
+ frozen: Option<&FrozenRecordedCursorAssets>,
+ cursor_id: &str,
+ ordinary: impl FnOnce() -> Option<DecodedRecordedCursor>,
+) -> Result<Option<DecodedRecordedCursor>, FrozenCursorAssetError> {
+ match frozen {
+ Some(assets) => assets.decode(cursor_id).map(Some),
+ None => Ok(ordinary()),
+ }
+}
+
+impl FrozenRecordedCursorAssets {
+ pub fn new(
+ assets: impl IntoIterator<Item = (String, CursorMeta, Arc<[u8]>)>,
+ ) -> Result<Self, FrozenCursorAssetError> {
+ let mut indexed = HashMap::new();
+ for (id, metadata, bytes) in assets {
+ if id.is_empty() {
+ return Err(FrozenCursorAssetError::EmptyId);
+ }
+ if indexed
+ .insert(id.clone(), FrozenRecordedCursor { metadata, bytes })
+ .is_some()
+ {
+ return Err(FrozenCursorAssetError::DuplicateId(id));
+ }
+ }
+ Ok(Self {
+ state: Arc::new(FrozenRecordedCursorState {
+ assets: indexed,
+ first_error: OnceLock::new(),
+ }),
+ })
+ }
+
+ pub fn first_error(&self) -> Option<FrozenCursorAssetError> {
+ self.state.first_error.get().cloned()
+ }
+
+ fn failed(&self, error: FrozenCursorAssetError) -> FrozenCursorAssetError {
+ let _ = self.state.first_error.set(error.clone());
+ error
+ }
+
+ pub(crate) fn ids(&self) -> impl Iterator<Item = &String> {
+ self.state.assets.keys()
+ }
+
+ pub(crate) fn metadata(&self, cursor_id: &str) -> Result<&CursorMeta, FrozenCursorAssetError> {
+ self.state
+ .assets
+ .get(cursor_id)
+ .map(|asset| &asset.metadata)
+ .ok_or_else(|| self.failed(FrozenCursorAssetError::Missing(cursor_id.to_owned())))
+ }
+
+ pub(crate) fn decode(
+ &self,
+ cursor_id: &str,
+ ) -> Result<DecodedRecordedCursor, FrozenCursorAssetError> {
+ let asset =
+ self.state.assets.get(cursor_id).ok_or_else(|| {
+ self.failed(FrozenCursorAssetError::Missing(cursor_id.to_owned()))
+ })?;
+ let decoded = image::ImageFormat::from_path(asset.metadata.image_path.as_str())
+ .and_then(|format| image::load_from_memory_with_format(&asset.bytes, format));
+ let image = decoded.map_err(|error| {
+ self.failed(FrozenCursorAssetError::Decode {
+ cursor_id: cursor_id.to_owned(),
+ message: error.to_string(),
+ })
+ })?;
+ Ok(DecodedRecordedCursor {
+ image,
+ hotspot: asset.metadata.hotspot,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use image::GenericImageView;
+ use std::io::Cursor;
+
+ fn metadata(path: &str) -> CursorMeta {
+ CursorMeta {
+ image_path: path.into(),
+ hotspot: XY::new(0.25, 0.75),
+ shape: None,
+ }
+ }
+
+ fn png() -> Arc<[u8]> {
+ let image =
+ image::RgbaImage::from_raw(2, 1, vec![11, 22, 33, 255, 44, 55, 66, 127]).unwrap();
+ let mut bytes = Cursor::new(Vec::new());
+ image.write_to(&mut bytes, image::ImageFormat::Png).unwrap();
+ bytes.into_inner().into()
+ }
+
+ #[test]
+ fn frozen_pixels_and_hotspot_match_ordinary_image_decoding() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("recorded.png");
+ let bytes = png();
+ std::fs::write(&path, &bytes).unwrap();
+ let ordinary = image::open(&path).unwrap();
+ let assets = FrozenRecordedCursorAssets::new([(
+ "arrow".into(),
+ metadata(path.to_str().unwrap()),
+ bytes,
+ )])
+ .unwrap();
+ let frozen = assets.decode("arrow").unwrap();
+ assert_eq!(frozen.image.dimensions(), ordinary.dimensions());
+ assert_eq!(
+ frozen.image.to_rgba8().as_raw(),
+ ordinary.to_rgba8().as_raw()
+ );
+ assert_eq!(frozen.hotspot, XY::new(0.25, 0.75));
+ assert!(assets.first_error().is_none());
+ }
+
+ #[test]
+ fn frozen_bytes_survive_original_file_removal() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("recorded.png");
+ let bytes = png();
+ std::fs::write(&path, &bytes).unwrap();
+ let assets = FrozenRecordedCursorAssets::new([(
+ "arrow".into(),
+ metadata(path.to_str().unwrap()),
+ bytes,
+ )])
+ .unwrap();
+ std::fs::remove_file(&path).unwrap();
+ assert_eq!(assets.decode("arrow").unwrap().image.dimensions(), (2, 1));
+ assert!(assets.first_error().is_none());
+ }
+
+ #[test]
+ fn corrupt_frozen_bytes_never_fall_back_to_valid_file() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("recorded.png");
+ std::fs::write(&path, png()).unwrap();
+ let assets = FrozenRecordedCursorAssets::new([(
+ "arrow".into(),
+ metadata(path.to_str().unwrap()),
+ Arc::from(&b"corrupt"[..]),
+ )])
+ .unwrap();
+ assert!(image::open(&path).is_ok());
+ assert!(matches!(
+ assets.decode("arrow"),
+ Err(FrozenCursorAssetError::Decode { .. })
+ ));
+ assert!(matches!(
+ assets.first_error(),
+ Some(FrozenCursorAssetError::Decode { .. })
+ ));
+ }
+
+ #[test]
+ fn missing_asset_error_is_shared_and_sticky_across_clones() {
+ let assets =
+ FrozenRecordedCursorAssets::new([("arrow".into(), metadata("recorded.png"), png())])
+ .unwrap();
+ let clone = assets.clone();
+ assert!(matches!(
+ clone.metadata("missing"),
+ Err(FrozenCursorAssetError::Missing(_))
+ ));
+ assert!(assets.decode("arrow").is_ok());
+ assert!(matches!(
+ assets.decode("other"),
+ Err(FrozenCursorAssetError::Missing(_))
+ ));
+ assert_eq!(
+ assets.first_error(),
+ Some(FrozenCursorAssetError::Missing("missing".into()))
+ );
+ assert_eq!(clone.first_error(), assets.first_error());
+ }
+
+ #[test]
+ fn frozen_format_selection_preserves_recorded_path_extension() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("recorded.unknown");
+ let bytes = png();
+ std::fs::write(&path, &bytes).unwrap();
+ let assets = FrozenRecordedCursorAssets::new([(
+ "arrow".into(),
+ metadata(path.to_str().unwrap()),
+ bytes,
+ )])
+ .unwrap();
+ assert!(image::open(&path).is_err());
+ assert!(matches!(
+ assets.decode("arrow"),
+ Err(FrozenCursorAssetError::Decode { .. })
+ ));
+ }
+
+ #[test]
+ fn frozen_ids_are_complete_and_duplicate_or_empty_ids_decline() {
+ let meta = metadata("recorded.png");
+ let bytes = png();
+ let assets = FrozenRecordedCursorAssets::new([
+ ("one".into(), meta.clone(), bytes.clone()),
+ ("two".into(), meta.clone(), bytes.clone()),
+ ])
+ .unwrap();
+ let mut ids = assets.ids().cloned().collect::<Vec<_>>();
+ ids.sort();
+ assert_eq!(ids, ["one", "two"]);
+ assert!(matches!(
+ FrozenRecordedCursorAssets::new([
+ ("one".into(), meta.clone(), bytes.clone()),
+ ("one".into(), meta.clone(), bytes.clone())
+ ]),
+ Err(FrozenCursorAssetError::DuplicateId(_))
+ ));
+ assert!(matches!(
+ FrozenRecordedCursorAssets::new([(String::new(), meta, bytes)]),
+ Err(FrozenCursorAssetError::EmptyId)
+ ));
+ }
+
+ #[test]
+ fn frozen_selection_never_calls_ordinary_provider_on_missing_or_corrupt_assets() {
+ let missing = FrozenRecordedCursorAssets::new([]).unwrap();
+ let corrupt = FrozenRecordedCursorAssets::new([(
+ "arrow".into(),
+ metadata("recorded.png"),
+ Arc::from(&b"corrupt"[..]),
+ )])
+ .unwrap();
+ for assets in [&missing, &corrupt] {
+ assert!(
+ select_recorded_cursor_image(Some(assets), "arrow", || panic!(
+ "Ordinary path fallback must never run"
+ ))
+ .is_err()
+ );
+ assert!(assets.first_error().is_some());
+ }
+ }
+
+ #[test]
+ fn ordinary_selection_preserves_the_supplied_provider_result() {
+ let image = image::load_from_memory(&png()).unwrap();
+ let decoded = select_recorded_cursor_image(None, "arrow", || {
+ Some(DecodedRecordedCursor {
+ image,
+ hotspot: XY::new(0.25, 0.75),
+ })
+ })
+ .unwrap()
+ .unwrap();
+ assert_eq!(decoded.image.dimensions(), (2, 1));
+ assert_eq!(decoded.hotspot, XY::new(0.25, 0.75));
+ assert!(
+ select_recorded_cursor_image(None, "missing", || None)
+ .unwrap()
+ .is_none()
+ );
+ }
+}
diff --git a/crates/rendering/src/segment_timing.rs b/crates/rendering/src/segment_timing.rs
new file mode 100644
index 000000000..5afb79df6
--- /dev/null
+++ b/crates/rendering/src/segment_timing.rs
@@ -0,0 +1,132 @@
+use cap_project::{ClipOffsets, StudioRecordingMeta};
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(super) struct SegmentVideoTiming {
+ pub(super) latest_start_time: Option<f64>,
+ pub(super) screen_fps: u32,
+ pub(super) camera_fps: Option<u32>,
+ pub(super) screen_offset: f64,
+ pub(super) camera_offset: f64,
+}
+
+pub(super) fn segment_video_timing(
+ meta: &StudioRecordingMeta,
+ segment_i: usize,
+) -> SegmentVideoTiming {
+ let latest_start_time = match &meta {
+ StudioRecordingMeta::SingleSegment { .. } => None,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ inner.segments[segment_i].latest_start_time()
+ }
+ };
+
+ let screen_fps = match &meta {
+ StudioRecordingMeta::SingleSegment { segment } => segment.display.fps,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ inner.segments[segment_i].display.fps
+ }
+ };
+
+ let camera_fps = match &meta {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ segment.camera.as_ref().map(|camera| camera.fps)
+ }
+ StudioRecordingMeta::MultipleSegments { inner, .. } => inner.segments[segment_i]
+ .camera
+ .as_ref()
+ .map(|camera| camera.fps),
+ };
+
+ let screen_offset = match &meta {
+ StudioRecordingMeta::SingleSegment { .. } => 0.0,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ let segment = &inner.segments[segment_i];
+
+ latest_start_time
+ .zip(segment.display.start_time)
+ .map(|(latest_start_time, display_time)| latest_start_time - display_time)
+ .unwrap_or(0.0)
+ }
+ };
+
+ let camera_offset = match &meta {
+ StudioRecordingMeta::SingleSegment { .. } => 0.0,
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ let segment = &inner.segments[segment_i];
+
+ latest_start_time
+ .zip(segment.camera.as_ref().and_then(|camera| camera.start_time))
+ .map(|(latest_start_time, start_time)| latest_start_time - start_time)
+ .unwrap_or(0.0)
+ }
+ };
+
+ SegmentVideoTiming {
+ latest_start_time,
+ screen_fps,
+ camera_fps,
+ screen_offset,
+ camera_offset,
+ }
+}
+
+pub(super) fn segment_frame_times(
+ segment_time: f32,
+ segment_offset: f64,
+ offsets: ClipOffsets,
+) -> (f32, f32) {
+ (
+ segment_time + offsets.camera,
+ segment_time + segment_offset as f32,
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn latest_start_includes_both_audio_tracks_and_preserves_missing_start_behavior() {
+ let mut metadata: StudioRecordingMeta = serde_json::from_value(serde_json::json!({
+ "segments": [{
+ "display": { "path": "display", "fps": 60, "start_time": 10.25 },
+ "camera": { "path": "camera", "fps": 24, "start_time": 10.5 },
+ "mic": { "path": "mic.aac", "start_time": 10.75 },
+ "system_audio": { "path": "system.ogg", "start_time": 11.0 }
+ }]
+ }))
+ .unwrap();
+ let timing = segment_video_timing(&metadata, 0);
+ assert_eq!(timing.latest_start_time, Some(11.0));
+ assert_eq!(timing.screen_offset, 0.75);
+ assert_eq!(timing.camera_offset, 0.5);
+ assert_eq!((timing.screen_fps, timing.camera_fps), (60, Some(24)));
+ let StudioRecordingMeta::MultipleSegments { inner } = &mut metadata else {
+ panic!("Expected multi-segment metadata");
+ };
+ inner.segments[0].mic.as_mut().unwrap().start_time = None;
+ let timing = segment_video_timing(&metadata, 0);
+ assert_eq!(timing.latest_start_time, None);
+ assert_eq!((timing.screen_offset, timing.camera_offset), (0.0, 0.0));
+ }
+
+ #[test]
+ fn frame_times_retain_cast_before_add_and_camera_offset_order() {
+ let segment_time = 1.0_f32;
+ let offset = 16_777_216.75_f64;
+ let clip = ClipOffsets {
+ camera: -0.25,
+ ..Default::default()
+ };
+ let (camera, recording) = segment_frame_times(segment_time, offset, clip);
+ assert_eq!(camera.to_bits(), 0.75_f32.to_bits());
+ assert_eq!(
+ recording.to_bits(),
+ (segment_time + offset as f32).to_bits()
+ );
+ assert_ne!(
+ recording.to_bits(),
+ ((segment_time as f64 + offset) as f32).to_bits()
+ );
+ }
+}
diff --git a/crates/video-decode/Cargo.toml b/crates/video-decode/Cargo.toml
index c9ccfa63d..f9a0a2be4 100644
--- a/crates/video-decode/Cargo.toml
+++ b/crates/video-decode/Cargo.toml
@@ -7,6 +7,7 @@ edition = "2024"
workspace = true
[dependencies]
+cap-enc-ffmpeg = { path = "../enc-ffmpeg" }
ffmpeg.workspace = true
ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
num_cpus = "1.17.0"
@@ -15,6 +16,11 @@ tokio = { workspace = true, features = ["rt", "rt-multi-thread"] }
tracing = "0.1.41"
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+[dev-dependencies]
+cap-media-info = { path = "../media-info" }
+serde_json.workspace = true
+sha2 = "0.10"
+
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { workspace = true }
diff --git a/crates/video-decode/examples/fragmented-readiness.rs b/crates/video-decode/examples/fragmented-readiness.rs
new file mode 100644
index 000000000..2cad303fa
--- /dev/null
+++ b/crates/video-decode/examples/fragmented-readiness.rs
@@ -0,0 +1,95 @@
+use cap_video_decode::FFmpegDecoder;
+use sha2::{Digest, Sha256};
+use std::{path::PathBuf, time::Instant};
+
+fn main() -> Result<(), String> {
+ let mut arguments = std::env::args().skip(1);
+ let path = arguments
+ .next()
+ .map(PathBuf::from)
+ .ok_or("Pass a video path")?;
+ let times = arguments
+ .map(|time| time.parse::<f32>().map_err(|error| error.to_string()))
+ .collect::<Result<Vec<_>, _>>()?;
+ let times = if times.is_empty() { vec![0.0] } else { times };
+ let frames_per_seek = std::env::var("CAP_BENCH_FRAMES")
+ .map_or(Ok(30), |value| value.parse::<usize>())
+ .map_err(|error| error.to_string())?;
+ let hardware = std::env::var_os("CAP_BENCH_HW").is_some();
+ let device = hardware.then_some(if cfg!(target_os = "macos") {
+ ffmpeg::sys::AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX
+ } else if cfg!(target_os = "windows") {
+ ffmpeg::sys::AVHWDeviceType::AV_HWDEVICE_TYPE_D3D11VA
+ } else {
+ ffmpeg::sys::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI
+ });
+ let started = Instant::now();
+ let mut decoder = FFmpegDecoder::new(&path, device)?;
+ let opened_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let mut probes = Vec::new();
+ for (index, time) in times.into_iter().enumerate() {
+ let sought = Instant::now();
+ if index > 0 || time != 0.0 {
+ decoder.reset(time).map_err(|error| error.to_string())?;
+ }
+ let mut frames = decoder.frames();
+ let mut digest = Sha256::new();
+ let mut frame_count = 0;
+ let mut first_ms = None;
+ let mut first_timestamp = None;
+ let mut last_timestamp = None;
+ for frame in frames.by_ref().take(frames_per_seek) {
+ let frame = frame.map_err(|error| error.to_string())?;
+ first_ms.get_or_insert_with(|| sought.elapsed().as_secs_f64() * 1000.0);
+ let timestamp = frame.timestamp().or_else(|| frame.pts());
+ if frame_count == 0 {
+ first_timestamp = timestamp;
+ }
+ last_timestamp = timestamp;
+ digest.update(timestamp.unwrap_or(i64::MIN).to_le_bytes());
+ digest.update(frame.width().to_le_bytes());
+ digest.update(frame.height().to_le_bytes());
+ if frame.planes() == 0 {
+ return Err("Decoded frame has no readable planes".into());
+ }
+ for plane in 0..frame.planes() {
+ let row_bytes = unsafe {
+ ffmpeg::sys::av_image_get_linesize(
+ frame.format().into(),
+ frame.width() as i32,
+ plane as i32,
+ )
+ };
+ if row_bytes <= 0 || row_bytes as usize > frame.stride(plane) {
+ return Err("Decoded frame has an invalid row size".into());
+ }
+ let height = frame.plane_height(plane) as usize;
+ for row in frame.data(plane).chunks(frame.stride(plane)).take(height) {
+ digest.update(&row[..row_bytes as usize]);
+ }
+ }
+ frame_count += 1;
+ }
+ if frame_count == 0 {
+ return Err(format!("No decoded frames at {time}"));
+ }
+ probes.push(serde_json::json!({
+ "time": time,
+ "firstFrameMs": first_ms,
+ "firstTimestamp": first_timestamp,
+ "lastTimestamp": last_timestamp,
+ "frames": frame_count,
+ "sha256": format!("{:x}", digest.finalize()),
+ }));
+ }
+ println!(
+ "{}",
+ serde_json::json!({
+ "path": path,
+ "openMs": opened_ms,
+ "hardware": decoder.is_hardware_accelerated(),
+ "probes": probes,
+ })
+ );
+ Ok(())
+}
diff --git a/crates/video-decode/examples/relocatable-video-probe.rs b/crates/video-decode/examples/relocatable-video-probe.rs
new file mode 100644
index 000000000..ea5edb7ea
--- /dev/null
+++ b/crates/video-decode/examples/relocatable-video-probe.rs
@@ -0,0 +1,310 @@
+use cap_enc_ffmpeg::RelocatableSource;
+use cap_video_decode::FFmpegDecoder;
+use serde_json::{Value, json};
+use sha2::{Digest, Sha256};
+use std::{
+ fs,
+ io::Read,
+ path::{Path, PathBuf},
+ time::Instant,
+};
+
+fn file_digest(path: &Path) -> Result<String, String> {
+ let mut file = fs::File::open(path).map_err(|error| error.to_string())?;
+ let mut digest = Sha256::new();
+ let mut buffer = [0_u8; 65_536];
+ loop {
+ let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
+ if read == 0 {
+ break;
+ }
+ digest.update(&buffer[..read]);
+ }
+ Ok(format!("{:x}", digest.finalize()))
+}
+
+fn fingerprint(
+ frames: impl IntoIterator<Item = Result<ffmpeg::frame::Video, ffmpeg::Error>>,
+) -> Result<Value, String> {
+ let mut hash = Sha256::new();
+ let mut timestamps = Vec::new();
+ for frame in frames {
+ let frame = frame.map_err(|error| error.to_string())?;
+ let timestamp = frame.timestamp().or_else(|| frame.pts());
+ timestamps.push(timestamp);
+ hash.update(timestamp.unwrap_or(i64::MIN).to_le_bytes());
+ hash.update(frame.width().to_le_bytes());
+ hash.update(frame.height().to_le_bytes());
+ if frame.planes() == 0 {
+ return Err("Decoded frame has no readable planes".into());
+ }
+ for plane in 0..frame.planes() {
+ let row_bytes = unsafe {
+ ffmpeg::sys::av_image_get_linesize(
+ frame.format().into(),
+ frame.width() as i32,
+ plane as i32,
+ )
+ };
+ if row_bytes <= 0 || row_bytes as usize > frame.stride(plane) {
+ return Err("Decoded frame has an invalid row size".into());
+ }
+ for row in frame
+ .data(plane)
+ .chunks(frame.stride(plane))
+ .take(frame.plane_height(plane) as usize)
+ {
+ hash.update(&row[..row_bytes as usize]);
+ }
+ }
+ }
+ if timestamps.is_empty() {
+ return Err("No decoded frames in the requested probe".into());
+ }
+ Ok(json!({
+ "frames": timestamps.len(),
+ "timestamps": timestamps,
+ "sha256": format!("{:x}", hash.finalize()),
+ }))
+}
+
+fn sample(decoder: &mut FFmpegDecoder, count: usize) -> Result<Value, String> {
+ fingerprint(decoder.frames().take(count))
+}
+
+struct OpenedDecoder {
+ decoder: FFmpegDecoder,
+ first: ffmpeg::frame::Video,
+ timings: Value,
+}
+
+fn open_probe(
+ open: impl FnOnce() -> Result<FFmpegDecoder, String>,
+) -> Result<OpenedDecoder, String> {
+ let started = Instant::now();
+ let mut decoder = open()?;
+ let opened = Instant::now();
+ let first = decoder
+ .frames()
+ .next()
+ .ok_or("No initial decoded frame")?
+ .map_err(|error| error.to_string())?;
+ let received = Instant::now();
+ Ok(OpenedDecoder {
+ decoder,
+ first,
+ timings: json!({
+ "openMs": opened.saturating_duration_since(started).as_secs_f64() * 1000.0,
+ "firstFrameAfterOpenMs": received.saturating_duration_since(opened).as_secs_f64() * 1000.0,
+ "openToFirstFrameMs": received.saturating_duration_since(started).as_secs_f64() * 1000.0,
+ }),
+ })
+}
+
+fn open_managed(
+ root: &Path,
+ paths: &[PathBuf],
+ device: Option<ffmpeg::sys::AVHWDeviceType>,
+) -> Result<(RelocatableSource, OpenedDecoder, f64), String> {
+ let started = Instant::now();
+ let source = RelocatableSource::new(root.to_path_buf()).map_err(|error| error.to_string())?;
+ let setup_ms = started.elapsed().as_secs_f64() * 1000.0;
+ let decoder = open_probe(|| {
+ FFmpegDecoder::new_relocatable(&source, paths.iter().map(PathBuf::as_path), device)
+ })?;
+ Ok((source, decoder, setup_ms))
+}
+
+fn compare(
+ label: String,
+ reference: &mut FFmpegDecoder,
+ candidate: &mut FFmpegDecoder,
+ count: usize,
+ probes: &mut Vec<Value>,
+) -> Result<(), String> {
+ let expected = sample(reference, count)?;
+ let actual = sample(candidate, count)?;
+ if actual != expected {
+ return Err(format!(
+ "Decoded frame mismatch at {label}: {expected} != {actual}"
+ ));
+ }
+ probes.push(json!({"label": label, "matches": true, "decoded": actual}));
+ Ok(())
+}
+
+fn move_source(
+ source: &RelocatableSource,
+ active: &mut PathBuf,
+ original: &Path,
+ retained: &Path,
+) -> Result<(), String> {
+ let destination = if active.as_path() == original {
+ retained
+ } else {
+ original
+ };
+ source
+ .relocate(destination.to_path_buf())
+ .map_err(|error| format!("relocate active video source / {error}"))?;
+ *active = destination.to_path_buf();
+ Ok(())
+}
+
+fn main() -> Result<(), String> {
+ ffmpeg::init().map_err(|error| error.to_string())?;
+ let mut arguments = std::env::args().skip(1);
+ let input = arguments
+ .next()
+ .map(PathBuf::from)
+ .ok_or("Pass a fragmented video directory and seek times")?;
+ let times = arguments
+ .map(|time| time.parse::<f32>().map_err(|error| error.to_string()))
+ .collect::<Result<Vec<_>, _>>()?;
+ if times.is_empty() {
+ return Err("Pass representative forward/backward seek times".into());
+ }
+ let mut files = fs::read_dir(&input)
+ .map_err(|error| error.to_string())?
+ .map(|entry| entry.map(|entry| entry.path()))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| error.to_string())?;
+ files.retain(|path| path.extension().is_some_and(|extension| extension == "m4s"));
+ files.sort();
+ if files.len() < 2 {
+ return Err("Probe requires multiple fragments".into());
+ }
+ files.insert(0, input.join("init.mp4"));
+ let temporary = tempfile::tempdir().map_err(|error| error.to_string())?;
+ let original = temporary.path().join("original");
+ let retained = temporary.path().join("retained");
+ fs::create_dir_all(original.join("display")).map_err(|error| error.to_string())?;
+ let mut input_hashes = Vec::new();
+ let mut relative_paths = Vec::new();
+ for path in &files {
+ let relative = Path::new("display").join(path.file_name().ok_or("Missing filename")?);
+ fs::copy(path, original.join(&relative)).map_err(|error| error.to_string())?;
+ input_hashes.push(file_digest(path)?);
+ relative_paths.push(relative);
+ }
+ let hardware = std::env::var_os("CAP_BENCH_HW").is_some();
+ let device = hardware.then_some(if cfg!(target_os = "macos") {
+ ffmpeg::sys::AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX
+ } else if cfg!(target_os = "windows") {
+ ffmpeg::sys::AVHWDeviceType::AV_HWDEVICE_TYPE_D3D11VA
+ } else {
+ ffmpeg::sys::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI
+ });
+ let managed_first = std::env::var_os("CAP_PROBE_MANAGED_FIRST").is_some();
+ let (source, managed, ordinary, source_setup_ms) = if managed_first {
+ let (source, managed, setup_ms) = open_managed(&original, &relative_paths, device)?;
+ let ordinary = open_probe(|| FFmpegDecoder::new(&input, device))?;
+ (source, managed, ordinary, setup_ms)
+ } else {
+ let ordinary = open_probe(|| FFmpegDecoder::new(&input, device))?;
+ let (source, managed, setup_ms) = open_managed(&original, &relative_paths, device)?;
+ (source, managed, ordinary, setup_ms)
+ };
+ let timings = json!({
+ "ordinary": ordinary.timings,
+ "managed": managed.timings,
+ "sourceCapabilitySetupMs": source_setup_ms,
+ "order": if managed_first { "managed-ordinary" } else { "ordinary-managed" },
+ "method": "Each open is immediately followed by its first frame; copy, source hashing and pixel hashing are outside timers. File caches are warmed by copy/hash preparation. Separate byte-identical source directories preserve the ordinary reference during moves. These are component measurements, not Stop/editor latency or p95.",
+ });
+ let expected_first = fingerprint(std::iter::once(Ok(ordinary.first)))?;
+ let actual_first = fingerprint(std::iter::once(Ok(managed.first)))?;
+ if expected_first != actual_first {
+ return Err("Initial frame mismatch".into());
+ }
+ let mut reference = ordinary.decoder;
+ let mut candidate = managed.decoder;
+ if reference.start_time() != candidate.start_time()
+ || reference.is_hardware_accelerated() != candidate.is_hardware_accelerated()
+ {
+ return Err("Decoder origin or selected acceleration changed".into());
+ }
+ let mut probes =
+ vec![json!({"label": "first-frame", "matches": true, "decoded": actual_first})];
+ let mut failed_moves = Vec::new();
+ let mut active = original.clone();
+ compare(
+ "prefix".into(),
+ &mut reference,
+ &mut candidate,
+ 1,
+ &mut probes,
+ )?;
+ for round in 0..6 {
+ move_source(&source, &mut active, &original, &retained)?;
+ compare(
+ format!("relocation-{round}"),
+ &mut reference,
+ &mut candidate,
+ 24,
+ &mut probes,
+ )?;
+ let error = source
+ .relocate(temporary.path().join("missing/target"))
+ .err()
+ .ok_or("Expected a failed relocation")?;
+ failed_moves.push(
+ json!({"kind": format!("{:?}", error.kind()), "rawOsError": error.raw_os_error()}),
+ );
+ compare(
+ format!("failed-move-{round}"),
+ &mut reference,
+ &mut candidate,
+ 1,
+ &mut probes,
+ )?;
+ move_source(&source, &mut active, &original, &retained)?;
+ move_source(&source, &mut active, &original, &retained)?;
+ compare(
+ format!("rollback-{round}"),
+ &mut reference,
+ &mut candidate,
+ 1,
+ &mut probes,
+ )?;
+ }
+ for time in times {
+ move_source(&source, &mut active, &original, &retained)?;
+ reference.reset(time).map_err(|error| error.to_string())?;
+ candidate.reset(time).map_err(|error| error.to_string())?;
+ move_source(&source, &mut active, &original, &retained)?;
+ compare(
+ format!("seek-{time}"),
+ &mut reference,
+ &mut candidate,
+ 30,
+ &mut probes,
+ )?;
+ }
+ for ((input, relative), expected) in files.iter().zip(&relative_paths).zip(&input_hashes) {
+ if file_digest(input)? != *expected || file_digest(&active.join(relative))? != *expected {
+ return Err("An original or relocated source file changed".into());
+ }
+ }
+ println!(
+ "{}",
+ json!({
+ "input": input,
+ "sourceFiles": files.len(),
+ "timings": timings,
+ "sourceHashes": input_hashes,
+ "originalsAndRelocatedCopyUnchanged": true,
+ "hardwareRequested": hardware,
+ "hardwareUsed": candidate.is_hardware_accelerated(),
+ "startTime": candidate.start_time(),
+ "decoderInstancesPerVariant": 1,
+ "failedMoves": failed_moves,
+ "probes": probes,
+ })
+ );
+ drop(candidate);
+ drop(source);
+ drop(reference);
+ temporary.close().map_err(|error| error.to_string())?;
+ Ok(())
+}
diff --git a/crates/video-decode/src/ffmpeg.rs b/crates/video-decode/src/ffmpeg.rs
index 65ec0208c..b343f8544 100644
--- a/crates/video-decode/src/ffmpeg.rs
+++ b/crates/video-decode/src/ffmpeg.rs
@@ -6,9 +6,8 @@ use ffmpeg::{
util as avutil,
};
use ffmpeg_hw_device::{CodecContextExt, HwDevice};
-use std::path::PathBuf;
-use std::sync::OnceLock;
-use tempfile::NamedTempFile;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, OnceLock};
use tracing::*;
#[derive(Debug, Clone)]
@@ -183,15 +182,69 @@ fn configure_software_threading(decoder: &mut avcodec::decoder::Video, width: u3
}
pub struct FFmpegDecoder {
- input: avformat::context::Input,
+ input: DecoderInput,
decoder: avcodec::decoder::Video,
stream_index: usize,
hw_device: Option<HwDevice>,
start_time: i64,
- _temp_file: Option<NamedTempFile>,
}
-fn combine_fragmented_segments(dir_path: &std::path::Path) -> Result<NamedTempFile, String> {
+enum DecoderInput {
+ File(avformat::context::Input),
+ Segmented(cap_enc_ffmpeg::SegmentedInput),
+}
+
+impl DecoderInput {
+ fn input(&self) -> &avformat::context::Input {
+ match self {
+ Self::File(input) => input,
+ Self::Segmented(input) => input.input(),
+ }
+ }
+
+ fn seek(&mut self, position: i64) -> Result<(), ffmpeg::Error> {
+ match self {
+ Self::File(input) => input.seek(position, ..position),
+ Self::Segmented(input) => input.seek(position),
+ }
+ }
+
+ fn packets(&mut self) -> DecoderPackets<'_> {
+ match self {
+ Self::File(input) => DecoderPackets::File(input.packets()),
+ Self::Segmented(input) => DecoderPackets::Segmented(input),
+ }
+ }
+}
+
+enum DecoderPackets<'a> {
+ File(PacketIter<'a>),
+ Segmented(&'a mut cap_enc_ffmpeg::SegmentedInput),
+}
+
+impl Iterator for DecoderPackets<'_> {
+ type Item = Result<(usize, ffmpeg::Packet), ffmpeg::Error>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ match self {
+ Self::File(packets) => packets
+ .next()
+ .map(|(stream, packet)| Ok((stream.index(), packet))),
+ Self::Segmented(input) => {
+ let mut packet = ffmpeg::Packet::empty();
+ match input.read_packet(&mut packet) {
+ Ok(()) => Some(Ok((packet.stream(), packet))),
+ Err(ffmpeg::Error::Eof) => None,
+ Err(error) => Some(Err(error)),
+ }
+ }
+ }
+ }
+}
+
+pub fn open_fragmented_input(
+ dir_path: &std::path::Path,
+) -> Result<cap_enc_ffmpeg::SegmentedInput, String> {
let init_segment = dir_path.join("init.mp4");
if !init_segment.exists() {
return Err(format!(
@@ -199,45 +252,23 @@ fn combine_fragmented_segments(dir_path: &std::path::Path) -> Result<NamedTempFi
dir_path.display()
));
}
-
- let mut fragments: Vec<PathBuf> = std::fs::read_dir(dir_path)
- .map_err(|e| format!("read fragmented directory / {e}"))?
- .filter_map(|e| e.ok())
- .map(|e| e.path())
- .filter(|p| p.extension().is_some_and(|ext| ext == "m4s"))
- .collect();
-
+ let mut fragments = std::fs::read_dir(dir_path)
+ .map_err(|error| format!("read fragmented directory / {error}"))?
+ .map(|entry| entry.map(|entry| entry.path()))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| format!("read fragmented directory / {error}"))?;
+ fragments.retain(|path| path.extension().is_some_and(|extension| extension == "m4s"));
fragments.sort();
-
if fragments.is_empty() {
return Err(format!(
"no .m4s segments found in fragmented directory: {}",
dir_path.display()
));
}
-
- let mut combined_data =
- std::fs::read(&init_segment).map_err(|e| format!("read init.mp4 / {e}"))?;
-
- for fragment in &fragments {
- let data = std::fs::read(fragment)
- .map_err(|e| format!("read fragment {} / {e}", fragment.display()))?;
- combined_data.extend(data);
- }
-
- let temp_file = NamedTempFile::new().map_err(|e| format!("create temp file / {e}"))?;
-
- std::fs::write(temp_file.path(), &combined_data)
- .map_err(|e| format!("write combined file / {e}"))?;
-
- info!(
- "Combined {} fragmented segments ({} bytes) into temp file: {}",
- fragments.len(),
- combined_data.len(),
- temp_file.path().display()
- );
-
- Ok(temp_file)
+ cap_enc_ffmpeg::SegmentedInput::open(
+ std::iter::once(init_segment.as_path()).chain(fragments.iter().map(PathBuf::as_path)),
+ )
+ .map_err(|error| format!("open fragmented video / {error}"))
}
impl FFmpegDecoder {
@@ -247,17 +278,46 @@ impl FFmpegDecoder {
) -> Result<Self, String> {
let path = path.into();
- let (effective_path, temp_file): (PathBuf, Option<NamedTempFile>) = if path.is_dir() {
- let temp = combine_fragmented_segments(&path)?;
- (temp.path().to_path_buf(), Some(temp))
+ let input = if path.is_dir() {
+ DecoderInput::Segmented(open_fragmented_input(&path)?)
} else {
- (path, None)
+ DecoderInput::File(
+ ffmpeg::format::input(&path).map_err(|e| format!("open file / {e}"))?,
+ )
};
- let input =
- ffmpeg::format::input(&effective_path).map_err(|e| format!("open file / {e}"))?;
+ Self::from_input(input, hw_device_type)
+ }
+
+ pub fn new_relocatable<'a>(
+ source: &cap_enc_ffmpeg::RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ hw_device_type: Option<AVHWDeviceType>,
+ ) -> Result<Self, String> {
+ let input = cap_enc_ffmpeg::SegmentedInput::open_relocatable(source, paths)
+ .map_err(|error| format!("open relocatable video / {error}"))?;
+ Self::from_input(DecoderInput::Segmented(input), hw_device_type)
+ }
+
+ pub fn new_relocatable_interruptible<'a>(
+ source: &cap_enc_ffmpeg::RelocatableSource,
+ paths: impl IntoIterator<Item = &'a Path>,
+ hw_device_type: Option<AVHWDeviceType>,
+ interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
+ ) -> Result<Self, String> {
+ let input = cap_enc_ffmpeg::SegmentedInput::open_relocatable_interruptible(
+ source, paths, interrupt,
+ )
+ .map_err(|error| format!("open relocatable video / {error}"))?;
+ Self::from_input(DecoderInput::Segmented(input), hw_device_type)
+ }
+ fn from_input(
+ input: DecoderInput,
+ hw_device_type: Option<AVHWDeviceType>,
+ ) -> Result<Self, String> {
let input_stream = input
+ .input()
.streams()
.best(avutil::media::Type::Video)
.ok_or_else(|| "no video stream".to_string())?;
@@ -317,7 +377,6 @@ impl FFmpegDecoder {
stream_index,
hw_device,
start_time,
- _temp_file: temp_file,
})
}
@@ -327,7 +386,7 @@ impl FFmpegDecoder {
let position = rescale::Rescale::rescale(&timestamp_us, (1, 1_000_000), rescale::TIME_BASE);
self.decoder.flush();
- self.input.seek(position, ..position)
+ self.input.seek(position)
}
pub fn frames(&mut self) -> FramesIter<'_> {
@@ -356,7 +415,7 @@ unsafe impl Send for FFmpegDecoder {}
pub struct FramesIter<'a> {
decoder: &'a mut avcodec::decoder::Video,
- packets: PacketIter<'a>,
+ packets: DecoderPackets<'a>,
stream_index: usize,
hw_device: Option<&'a mut HwDevice>,
}
@@ -391,9 +450,12 @@ impl<'a> Iterator for FramesIter<'a> {
Err(e) => return Some(Err(e)),
}
- let (stream, packet) = self.packets.next()?;
+ let (stream_index, packet) = match self.packets.next()? {
+ Ok(packet) => packet,
+ Err(error) => return Some(Err(error)),
+ };
- if stream.index() != self.stream_index {
+ if stream_index != self.stream_index {
continue;
};
@@ -406,3 +468,321 @@ impl<'a> Iterator for FramesIter<'a> {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_enc_ffmpeg::segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig};
+ use std::{fs::File, time::Duration};
+
+ fn encode_segments(directory: &std::path::Path) {
+ ffmpeg::init().unwrap();
+ let mut encoder = SegmentedVideoEncoder::init(
+ directory.to_path_buf(),
+ cap_media_info::VideoInfo {
+ pixel_format: cap_media_info::Pixel::NV12,
+ width: 160,
+ height: 120,
+ time_base: ffmpeg::Rational(1, 1_000_000),
+ frame_rate: ffmpeg::Rational(30, 1),
+ },
+ SegmentedVideoEncoderConfig::default(),
+ )
+ .unwrap();
+ for index in 0..120 {
+ let mut frame = avframe::Video::new(avformat::Pixel::NV12, 160, 120);
+ frame.data_mut(0).fill(32 + (index % 192) as u8);
+ frame.data_mut(1).fill(128);
+ encoder
+ .queue_frame(frame, Duration::from_micros(index * 1_000_000 / 30))
+ .unwrap();
+ }
+ encoder.finish().unwrap();
+ assert!(encoder.completed_segments().len() >= 2);
+ }
+
+ fn frame_data(frame: avframe::Video) -> (Option<i64>, Vec<u8>) {
+ assert_eq!(frame.format(), avformat::Pixel::YUV420P);
+ let mut bytes = Vec::new();
+ for plane in 0..frame.planes() {
+ for row in frame
+ .data(plane)
+ .chunks(frame.stride(plane))
+ .take(frame.plane_height(plane) as usize)
+ {
+ bytes.extend_from_slice(&row[..frame.plane_width(plane) as usize]);
+ }
+ }
+ (frame.timestamp().or_else(|| frame.pts()), bytes)
+ }
+
+ fn frames(decoder: &mut FFmpegDecoder) -> Vec<(Option<i64>, Vec<u8>)> {
+ decoder
+ .frames()
+ .map(|frame| frame_data(frame.unwrap()))
+ .collect()
+ }
+
+ #[test]
+ fn fragmented_decoder_matches_combined_file_for_full_playback_and_seeks() {
+ let directory = tempfile::tempdir().unwrap();
+ let source = directory.path().join("segments");
+ encode_segments(&source);
+ let combined = directory.path().join("combined.mp4");
+ let mut output = File::create(&combined).unwrap();
+ std::io::copy(
+ &mut File::open(source.join("init.mp4")).unwrap(),
+ &mut output,
+ )
+ .unwrap();
+ let mut paths = std::fs::read_dir(&source)
+ .unwrap()
+ .map(|entry| entry.unwrap().path())
+ .filter(|path| path.extension().is_some_and(|extension| extension == "m4s"))
+ .collect::<Vec<_>>();
+ paths.sort();
+ for path in paths {
+ std::io::copy(&mut File::open(path).unwrap(), &mut output).unwrap();
+ }
+ drop(output);
+ let mut reference = FFmpegDecoder::new(combined, None).unwrap();
+ let mut candidate = FFmpegDecoder::new(source, None).unwrap();
+ assert_eq!(reference.start_time(), candidate.start_time());
+ let expected = frames(&mut reference);
+ assert!(!expected.is_empty());
+ assert_eq!(frames(&mut candidate), expected);
+ for time in [1.5, 0.0, 3.0, 0.5] {
+ reference.reset(time).unwrap();
+ candidate.reset(time).unwrap();
+ let expected = frames(&mut reference);
+ assert!(!expected.is_empty());
+ assert_eq!(frames(&mut candidate), expected);
+ }
+ }
+
+ #[test]
+ fn relocatable_decoder_preserves_live_frames_and_seeks_after_publication() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ let retained = directory.path().join("retained");
+ encode_segments(&original);
+ let mut paths = std::fs::read_dir(&original)
+ .unwrap()
+ .map(|entry| entry.unwrap().file_name().into())
+ .filter(|path: &PathBuf| path.extension().is_some_and(|extension| extension == "m4s"))
+ .collect::<Vec<PathBuf>>();
+ paths.sort();
+ paths.insert(0, PathBuf::from("init.mp4"));
+ let mut reference = FFmpegDecoder::new(&original, None).unwrap();
+ let expected = frames(&mut reference);
+ let mut seek_reference = Vec::new();
+ for time in [1.5, 0.0, 3.0, 0.5] {
+ reference.reset(time).unwrap();
+ seek_reference.push(frames(&mut reference));
+ }
+ let expected_start = reference.start_time();
+ drop(reference);
+
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let mut candidate =
+ FFmpegDecoder::new_relocatable(&source, paths.iter().map(PathBuf::as_path), None)
+ .unwrap();
+ assert_eq!(candidate.start_time(), expected_start);
+ let mut actual = Vec::new();
+ for (index, count) in [1, 17, 23, 19].into_iter().enumerate() {
+ actual.extend(
+ candidate
+ .frames()
+ .take(count)
+ .map(|frame| frame_data(frame.unwrap())),
+ );
+ assert!(
+ source
+ .relocate(directory.path().join("missing/target"))
+ .is_err()
+ );
+ source
+ .relocate(if index % 2 == 0 {
+ retained.clone()
+ } else {
+ original.clone()
+ })
+ .unwrap();
+ }
+ actual.extend(frames(&mut candidate));
+ assert_eq!(actual, expected);
+ for (time, expected) in [1.5, 0.0, 3.0, 0.5].into_iter().zip(seek_reference) {
+ source.relocate(retained.clone()).unwrap();
+ candidate.reset(time).unwrap();
+ source.relocate(original.clone()).unwrap();
+ assert_eq!(frames(&mut candidate), expected);
+ }
+ }
+
+ #[test]
+ fn interruptible_video_rejects_cancel_before_registering_missing_sources() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ std::fs::create_dir(&original).unwrap();
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let interrupt: Arc<dyn Fn() -> bool + Send + Sync> = Arc::new(|| true);
+ let owner = Arc::downgrade(&interrupt);
+ let error = FFmpegDecoder::new_relocatable_interruptible(
+ &source,
+ [Path::new("missing.mp4")],
+ None,
+ interrupt,
+ )
+ .err()
+ .unwrap();
+ assert!(error.contains("cancelled"));
+ assert!(owner.upgrade().is_none());
+ std::fs::rename(&original, directory.path().join("retained")).unwrap();
+ }
+
+ #[test]
+ fn interruptible_video_stops_partial_registration_and_releases_ownership() {
+ use std::{
+ cell::Cell,
+ sync::atomic::{AtomicBool, Ordering},
+ };
+
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ std::fs::create_dir(&original).unwrap();
+ std::fs::write(original.join("part.m4s"), b"not parsed before cancellation").unwrap();
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let callback_cancelled = cancelled.clone();
+ let interrupt: Arc<dyn Fn() -> bool + Send + Sync> =
+ Arc::new(move || callback_cancelled.load(Ordering::Acquire));
+ let owner = Arc::downgrade(&interrupt);
+ let visited = Cell::new(0);
+ let paths = vec![PathBuf::from("part.m4s"); 512];
+ let inputs = paths.iter().enumerate().map(|(index, path)| {
+ visited.set(index + 1);
+ if index == 64 {
+ cancelled.store(true, Ordering::Release);
+ }
+ path.as_path()
+ });
+ let error = FFmpegDecoder::new_relocatable_interruptible(&source, inputs, None, interrupt)
+ .err()
+ .unwrap();
+ assert!(error.contains("cancelled"));
+ assert!(visited.get() > 64 && visited.get() < paths.len());
+ assert!(owner.upgrade().is_none());
+ std::fs::rename(&original, directory.path().join("retained")).unwrap();
+ }
+
+ #[test]
+ fn interruptible_video_retains_sticky_callback_until_decoder_drop() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ encode_segments(&original);
+ let mut paths = std::fs::read_dir(&original)
+ .unwrap()
+ .map(|entry| PathBuf::from(entry.unwrap().file_name()))
+ .filter(|path| path.extension().is_some_and(|extension| extension == "m4s"))
+ .collect::<Vec<_>>();
+ paths.sort();
+ paths.insert(0, PathBuf::from("init.mp4"));
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let callback_cancelled = cancelled.clone();
+ let interrupt: Arc<dyn Fn() -> bool + Send + Sync> =
+ Arc::new(move || callback_cancelled.load(Ordering::Acquire));
+ let owner = Arc::downgrade(&interrupt);
+ let mut decoder = FFmpegDecoder::new_relocatable_interruptible(
+ &source,
+ paths.iter().map(PathBuf::as_path),
+ None,
+ interrupt,
+ )
+ .unwrap();
+ assert!(owner.upgrade().is_some());
+ assert!(decoder.frames().next().unwrap().is_ok());
+ cancelled.store(true, Ordering::Release);
+ assert_eq!(decoder.reset(0.0), Err(ffmpeg::Error::Exit));
+ cancelled.store(false, Ordering::Release);
+ assert_eq!(decoder.reset(0.0), Err(ffmpeg::Error::Exit));
+ assert!(matches!(
+ decoder.frames().next(),
+ Some(Err(ffmpeg::Error::Exit))
+ ));
+ drop(decoder);
+ assert!(owner.upgrade().is_none());
+ std::fs::rename(&original, directory.path().join("retained")).unwrap();
+ }
+
+ #[test]
+ fn interruptible_video_releases_callback_when_input_open_fails() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ std::fs::create_dir(&original).unwrap();
+ std::fs::write(original.join("broken.mp4"), b"invalid video input").unwrap();
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let interrupt: Arc<dyn Fn() -> bool + Send + Sync> = Arc::new(|| false);
+ let owner = Arc::downgrade(&interrupt);
+ assert!(
+ FFmpegDecoder::new_relocatable_interruptible(
+ &source,
+ [Path::new("broken.mp4")],
+ None,
+ interrupt,
+ )
+ .is_err()
+ );
+ assert!(owner.upgrade().is_none());
+ std::fs::rename(&original, directory.path().join("retained")).unwrap();
+ }
+
+ #[test]
+ fn interruptible_video_releases_callback_when_video_setup_fails() {
+ let directory = tempfile::tempdir().unwrap();
+ let original = directory.path().join("original");
+ std::fs::create_dir(&original).unwrap();
+ let data_length = 24_000_u32;
+ let mut wave = Vec::new();
+ wave.extend_from_slice(b"RIFF");
+ wave.extend_from_slice(&(36 + data_length).to_le_bytes());
+ wave.extend_from_slice(b"WAVEfmt ");
+ wave.extend_from_slice(&16_u32.to_le_bytes());
+ wave.extend_from_slice(&1_u16.to_le_bytes());
+ wave.extend_from_slice(&1_u16.to_le_bytes());
+ wave.extend_from_slice(&48_000_u32.to_le_bytes());
+ wave.extend_from_slice(&96_000_u32.to_le_bytes());
+ wave.extend_from_slice(&2_u16.to_le_bytes());
+ wave.extend_from_slice(&16_u16.to_le_bytes());
+ wave.extend_from_slice(b"data");
+ wave.extend_from_slice(&data_length.to_le_bytes());
+ wave.resize(wave.len() + data_length as usize, 0);
+ std::fs::write(original.join("audio.wav"), &wave).unwrap();
+ let source = cap_enc_ffmpeg::RelocatableSource::new(original.clone()).unwrap();
+ let interrupt: Arc<dyn Fn() -> bool + Send + Sync> = Arc::new(|| false);
+ let owner = Arc::downgrade(&interrupt);
+ let error = FFmpegDecoder::new_relocatable_interruptible(
+ &source,
+ [Path::new("audio.wav")],
+ None,
+ interrupt,
+ )
+ .err()
+ .unwrap();
+ assert_eq!(error, "no video stream");
+ assert!(owner.upgrade().is_none());
+ std::fs::rename(&original, directory.path().join("retained")).unwrap();
+ }
+
+ #[test]
+ fn fragmented_input_rejects_missing_init_and_empty_segments() {
+ let directory = tempfile::tempdir().unwrap();
+ assert!(open_fragmented_input(directory.path()).is_err());
+ std::fs::write(directory.path().join("init.mp4"), b"invalid").unwrap();
+ assert!(open_fragmented_input(directory.path()).is_err());
+ std::fs::create_dir(directory.path().join("segment_001.m4s")).unwrap();
+ assert!(open_fragmented_input(directory.path()).is_err());
+ }
+}