Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

36.4 KB
Raw Blame
pub mod estimates;
pub mod gif;
pub mod mov;
pub mod mp4;
pub mod preview;
pub mod settings;

use cap_editor::{ExportAudioPreparation, ExportAudioRenderer, SegmentMedia};
use cap_project::{
    BackgroundSource, ProjectConfiguration, RecordingMeta, StudioRecordingMeta,
    TimelineConfiguration, TimelineSegment,
};
use cap_rendering::{ProjectRecordingsMeta, RenderVideoConstants};
use std::{
    path::PathBuf,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

#[derive(thiserror::Error, Debug)]
pub enum ExportError {
    #[error("FFmpeg: {0}")]
    FFmpeg(String),

    #[error("IO: {0}")]
    IO(#[from] std::io::Error),

    #[error("Rendering: {0}")]
    Rendering(#[from] cap_rendering::RenderingError),

    #[error("Media/{0}")]
    Media(#[from] cap_media::MediaError),

    #[error("Join: {0}")]
    Join(#[from] tokio::task::JoinError),

    #[error("Other:{0}")]
    Other(String),

    #[error("Exporting timed out")]
    Timeout(#[from] tokio::time::error::Elapsed),
}

#[derive(thiserror::Error, Debug)]
pub enum ExporterBuildError {
    #[error("Failed to load config: {0}")]
    ConfigLoad(#[source] Box<dyn std::error::Error>),
    #[error("Failed to load meta: {0}")]
    MetaLoad(#[source] Box<dyn std::error::Error>),
    #[error("Recording is not a studio recording")]
    NotStudioRecording,
    #[error("Failed to load recordings meta: {0}")]
    RecordingsMeta(String),
    #[error("Failed to setup renderer: {0}")]
    RendererSetup(#[source] cap_rendering::RenderingError),
    #[error("Failed to load media: {0}")]
    MediaLoad(String),
    #[error("IO error at path '{0}': {1}")]
    IO(PathBuf, std::io::Error),
    #[error("There is nothing to export: the timeline is empty")]
    NothingToExport,
}

pub struct ExporterBuilder {
    project_path: PathBuf,
    config: Option<ProjectConfiguration>,
    output_path: Option<PathBuf>,
    force_ffmpeg_decoder: bool,
}

impl ExporterBuilder {
    pub fn with_config(mut self, config: ProjectConfiguration) -> Self {
        self.config = Some(config);
        self
    }

    pub fn with_output_path(mut self, output_path: PathBuf) -> Self {
        self.output_path = Some(output_path);
        self
    }

    pub fn with_force_ffmpeg_decoder(mut self, force: bool) -> Self {
        self.force_ffmpeg_decoder = force;
        self
    }

    pub async fn build(self) -> Result<ExporterBase, ExporterBuildError> {
        self.build_inner(None, true).await
    }

    pub async fn build_video_only(self) -> Result<ExporterBase, ExporterBuildError> {
        self.build_inner(None, false).await
    }

    pub async fn build_for_mp4(
        self,
        cancellation: Arc<AtomicBool>,
    ) -> Result<Mp4ExporterBase, ExporterBuildError> {
        self.build_inner(Some(cancellation), true)
            .await
            .map(Mp4ExporterBase)
    }

    fn load_project_config(&mut self) -> Result<ProjectConfiguration, ExporterBuildError> {
        let project_config = if let Some(config) = self.config.take() {
            config
        } else {
            ProjectConfiguration::load(&self.project_path)
                .map_err(|error| ExporterBuildError::ConfigLoad(error.into()))?
        };
        Ok(project_config)
    }

    async fn build_inner(
        mut self,
        cancellation: Option<Arc<AtomicBool>>,
        include_audio: bool,
    ) -> Result<ExporterBase, ExporterBuildError> {
        type Error = ExporterBuildError;

        cap_editor::release_playback_audio_caches();
        let mut project_config = self.load_project_config()?;

        let recording_meta =
            RecordingMeta::load_for_project(&self.project_path).map_err(Error::MetaLoad)?;
        let studio_meta = recording_meta
            .studio_meta()
            .ok_or(Error::NotStudioRecording)?;

        let recordings = Arc::new(
            ProjectRecordingsMeta::new(&recording_meta.project_path, studio_meta)
                .map_err(Error::RecordingsMeta)?,
        );

        synthesize_default_timeline(&mut project_config, &recordings);
        fill_clip_offsets(
            &mut project_config,
            &recording_meta.project_path,
            studio_meta,
        );

        cap_project::clamp_timeline_to_sources(
            &mut project_config,
            &recordings
                .segments
                .iter()
                .map(|segment| segment.display.duration)
                .collect::<Vec<_>>(),
        );
        cap_project::synchronize_legacy_keyboard(&recording_meta, &mut project_config);
        cap_project::synchronize_captions(
            &mut project_config,
            &recordings
                .segments
                .iter()
                .map(|segment| segment.display.duration)
                .collect::<Vec<_>>(),
        );

        let duration =
            cap_rendering::get_duration(&recordings, &recording_meta, studio_meta, &project_config);
        if duration.is_nan() || duration <= 0.0 {
            return Err(Error::NothingToExport);
        }

        let output_path = self
            .output_path
            .unwrap_or_else(|| recording_meta.output_path());

        if let Some(parent) = output_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| ExporterBuildError::IO(parent.to_path_buf(), e))?;
        }

        let streaming_output = prepare_streaming_output(
            &output_path,
            cancellation.is_some() && ExportAudioRenderer::eligible(&project_config, studio_meta),
        );
        let stream_audio = streaming_output.is_some();

        let render_constants = Arc::new(
            RenderVideoConstants::new(
                &recordings.segments,
                recording_meta.clone(),
                studio_meta.clone(),
            )
            .await
            .map_err(Error::RendererSetup)?,
        );

        let user_cancellation = cancellation.clone();
        let audio_cancellation = if stream_audio {
            cancellation.map(ExportAudioCancellation::new)
        } else {
            None
        };
        let (segments, streaming_audio) = if let Some(control) = &audio_cancellation {
            let recording = recording_meta.clone();
            let studio = studio_meta.clone();
            let cancellation = control.user.clone();
            let abort = control.stop.clone();
            let preparation = tokio::task::spawn_blocking(move || {
                ExportAudioPreparation::open(&recording, &studio, cancellation, abort)
            });
            let segments = cap_editor::create_segments_without_audio(
                &recording_meta,
                studio_meta,
                self.force_ffmpeg_decoder,
            )
            .await;
            let (segments, audio) =
                finish_audio_preparation(segments, preparation, &control.stop).await?;
            (segments, Some(audio))
        } else if !include_audio {
            let segments = cap_editor::create_segments_without_audio(
                &recording_meta,
                studio_meta,
                self.force_ffmpeg_decoder,
            )
            .await
            .map_err(Error::MediaLoad)?;
            (segments, None)
        } else {
            let segments = cap_editor::create_segments(
                &recording_meta,
                studio_meta,
                self.force_ffmpeg_decoder,
            )
            .await
            .map_err(Error::MediaLoad)?;
            for segment in &segments {
                segment.audio.get().await.map_err(Error::MediaLoad)?;
                segment.system_audio.get().await.map_err(Error::MediaLoad)?;
            }
            (segments, None)
        };

        if reads_recordings_forward(&project_config) {
            for segment in &segments {
                segment.decoders.prefer_sequential_access();
            }
        }

        Ok(ExporterBase {
            output_path,
            studio_meta: studio_meta.clone(),
            recordings,
            render_constants,
            segments,
            recording_meta,
            project_config,
            project_path: self.project_path,
            streaming_audio,
            streaming_output,
            audio_cancellation,
            user_cancellation,
            sample_windows: None,
            sample_timing: None,
            #[cfg(feature = "test-hooks")]
            video_encoder_failure_at: None,
            #[cfg(feature = "test-hooks")]
            turbo_chunk_failure: None,
        })
    }
}

async fn finish_audio_preparation(
    segments: Result<Vec<SegmentMedia>, String>,
    preparation: tokio::task::JoinHandle<
        Result<ExportAudioPreparation, cap_editor::ExportAudioError>,
    >,
    abort: &AtomicBool,
) -> Result<(Vec<SegmentMedia>, ExportAudioRenderer), ExporterBuildError> {
    if segments.is_err() {
        abort.store(true, Ordering::Relaxed);
    }
    let preparation = preparation.await;
    let segments = segments.map_err(ExporterBuildError::MediaLoad)?;
    let audio = preparation
        .map_err(|error| ExporterBuildError::MediaLoad(error.to_string()))?
        .map_err(|error| ExporterBuildError::MediaLoad(error.to_string()))?
        .finish(&segments)
        .map_err(|error| ExporterBuildError::MediaLoad(error.to_string()))?;
    Ok((segments, audio))
}

/// A freshly recorded .cap has no timeline — only the editor creates one. Without it the
/// render loop's get_segment_time() returns None on frame 0 and produces zero frames (an empty
/// export). Synthesize the same default timeline the editor would (one segment per recording,
/// spanning its full duration) so raw recordings — e.g. from `cap export` — render correctly.
/// Desktop exports already carry a timeline by export time, so this only fires for un-edited
/// projects and changes nothing for them.
pub fn synthesize_default_timeline(
    project_config: &mut ProjectConfiguration,
    recordings: &ProjectRecordingsMeta,
) {
    if project_config.timeline.is_some() {
        return;
    }
    let segments: Vec<TimelineSegment> = recordings
        .segments
        .iter()
        .enumerate()
        .filter_map(|(i, segment)| {
            let duration = segment.duration();
            (duration > 0.0).then_some(TimelineSegment {
                recording_clip: i as u32,
                start: 0.0,
                end: duration,
                timescale: 1.0,
                name: None,
                speed_audio_mode: None,
                hide_cursor: None,
                volume: None,
            })
        })
        .collect();
    if !segments.is_empty() {
        project_config.timeline = Some(TimelineConfiguration {
            segments,
            transitions: Vec::new(),
            zoom_segments: Vec::new(),
            scene_segments: Vec::new(),
            style_segments: Vec::new(),
            image_segments: Vec::new(),
            mask_segments: Vec::new(),
            text_segments: Vec::new(),
            caption_segments: Vec::new(),
            keyboard_segments: Vec::new(),
            audio_segments: Vec::new(),
            camera3d_segments: Vec::new(),
        });
    }
}

/// Whether export requests every recording's frames front to back: each
/// recording's timeline segments advance through its source without
/// overlapping, and no transition renders two timeline segments at once.
fn reads_recordings_forward(project_config: &ProjectConfiguration) -> bool {
    let Some(timeline) = &project_config.timeline else {
        return true;
    };
    if !timeline.transitions.is_empty() {
        return false;
    }
    let mut source_ends = std::collections::HashMap::<u32, f64>::new();
    timeline.segments.iter().all(|segment| {
        let source_end = source_ends
            .entry(segment.recording_clip)
            .or_insert(f64::NEG_INFINITY);
        let forward = segment.start >= *source_end && segment.end >= segment.start;
        *source_end = segment.end;
        forward
    })
}

pub fn make_cursor_only_project(mut project_config: ProjectConfiguration) -> ProjectConfiguration {
    fn clear_background_pixels(background: &mut cap_project::BackgroundConfiguration) {
        background.source = BackgroundSource::Color {
            value: [0, 0, 0],
            alpha: 0,
        };
        background.blur = 0.0;
        background.shadow = 0.0;
        background.advanced_shadow = None;
        background.border = None;
    }

    clear_background_pixels(&mut project_config.background);
    project_config.captions = None;
    project_config.keyboard = None;

    if let Some(timeline) = project_config.timeline.as_mut() {
        timeline.mask_segments.clear();
        timeline.image_segments.clear();
        for style in &mut timeline.style_segments {
            if let Some(background) = style.overrides.background.as_mut() {
                clear_background_pixels(background);
            }
        }
        // Fullscreen text segments pause the recording clock (holds), which
        // shapes the frame count and cursor motion. Split titles also move
        // the cursor with the display, so both need invisible placeholders.
        timeline
            .text_segments
            .retain(|text| text.layout != cap_project::TextLayout::Overlay);
        for text in &mut timeline.text_segments {
            text.content.clear();
        }
        timeline.caption_segments.clear();
        timeline.keyboard_segments.clear();
    }

    project_config
}

fn prepare_streaming_output(
    output: &std::path::Path,
    eligible: bool,
) -> Option<mp4::TemporaryExportOutput> {
    if !eligible || output.extension().and_then(|extension| extension.to_str()) != Some("mp4") {
        return None;
    }
    prepare_new_output(output).ok().flatten()
}

/// Stages a new export beside its destination so a failed or cancelled export
/// never leaves a partial file there. Existing destinations are written in place.
fn prepare_new_output(
    output: &std::path::Path,
) -> Result<Option<mp4::TemporaryExportOutput>, String> {
    if !matches!(std::fs::symlink_metadata(output), Err(error) if error.kind() == std::io::ErrorKind::NotFound)
    {
        return Ok(None);
    }
    mp4::temporary_export_output(output).map(Some)
}

struct ExportAudioCancellation {
    user: Arc<AtomicBool>,
    stop: Arc<AtomicBool>,
}

impl ExportAudioCancellation {
    fn new(user: Arc<AtomicBool>) -> Self {
        Self {
            user,
            stop: Arc::new(AtomicBool::new(false)),
        }
    }
}

impl Drop for ExportAudioCancellation {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
    }
}

pub struct Mp4ExporterBase(ExporterBase);

impl Mp4ExporterBase {
    pub fn total_frames(&self, fps: u32) -> u32 {
        self.0.total_frames(fps)
    }

    pub fn uses_streaming_audio(&self) -> bool {
        self.0.streaming_audio.is_some()
    }

    #[cfg(feature = "test-hooks")]
    pub fn fail_video_encoder_at(&mut self, frames: u32) {
        self.0.fail_video_encoder_at(frames);
    }

    /// Makes this turbo chunk's encoder fail after a few frames.
    #[cfg(feature = "test-hooks")]
    pub fn fail_turbo_chunk(&mut self, chunk: usize) {
        self.0.turbo_chunk_failure = Some(chunk);
    }
}

pub struct ExporterBase {
    project_path: PathBuf,
    recording_meta: RecordingMeta,
    project_config: ProjectConfiguration,
    studio_meta: StudioRecordingMeta,
    recordings: Arc<ProjectRecordingsMeta>,
    render_constants: Arc<RenderVideoConstants>,
    segments: Vec<SegmentMedia>,
    output_path: PathBuf,
    streaming_audio: Option<ExportAudioRenderer>,
    streaming_output: Option<mp4::TemporaryExportOutput>,
    audio_cancellation: Option<ExportAudioCancellation>,
    user_cancellation: Option<Arc<AtomicBool>>,
    sample_windows: Option<cap_rendering::FrameWindows>,
    sample_timing: Option<Arc<estimates::SampleTiming>>,
    #[cfg(feature = "test-hooks")]
    video_encoder_failure_at: Option<u32>,
    #[cfg(feature = "test-hooks")]
    turbo_chunk_failure: Option<usize>,
}

impl ExporterBase {
    /// Makes the MP4 export's video encoder fail after `frames` frames the
    /// way a hardware encoder does at runtime, once, so the software
    /// encoder fallback runs on every machine.
    #[cfg(feature = "test-hooks")]
    pub fn fail_video_encoder_at(&mut self, frames: u32) {
        self.video_encoder_failure_at = Some(frames);
    }

    /// Reopens what an MP4 export consumes (the staged output and the
    /// streaming audio with its cancellation) so the export can start over.
    async fn reopen_streaming(
        &mut self,
        user_cancellation: Option<Arc<AtomicBool>>,
    ) -> Result<(), String> {
        let Some(user) = user_cancellation else {
            return Ok(());
        };
        let control = ExportAudioCancellation::new(user);
        let recording = self.recording_meta.clone();
        let studio = self.studio_meta.clone();
        let cancellation = control.user.clone();
        let abort = control.stop.clone();
        let preparation = tokio::task::spawn_blocking(move || {
            ExportAudioPreparation::open(&recording, &studio, cancellation, abort)
        })
        .await
        .map_err(|error| error.to_string())?
        .map_err(|error| error.to_string())?;
        self.streaming_audio = Some(
            preparation
                .finish(&self.segments)
                .map_err(|error| error.to_string())?,
        );
        // The first attempt staged its output, so the restart must too: if
        // something created the destination meanwhile, writing in place
        // would truncate it.
        self.streaming_output = Some(
            prepare_streaming_output(&self.output_path, true)
                .ok_or("Could not stage the export output to restart on the software encoder")?,
        );
        self.audio_cancellation = Some(control);
        Ok(())
    }

    pub fn total_frames(&self, fps: u32) -> u32 {
        let duration = cap_rendering::get_duration(
            &self.recordings,
            &self.recording_meta,
            &self.studio_meta,
            &self.project_config,
        );

        (fps as f64 * duration).ceil() as u32
    }

    pub fn builder(project_path: PathBuf) -> ExporterBuilder {
        ExporterBuilder {
            project_path,
            config: None,
            output_path: None,
            force_ffmpeg_decoder: false,
        }
    }
}

#[cfg(test)]
mod cursor_only_tests {
    use super::*;
    use cap_project::TextLayout;

    #[test]
    fn cursor_only_preserves_style_geometry_without_image_or_background_pixels() {
        let project = ProjectConfiguration {
            timeline: Some(serde_json::from_value(serde_json::json!({
            "segments": [], "zoomSegments": [],
            "imageSegments": [{ "start": 1.0, "end": 2.0, "path": "content/images/example.png" }],
            "styleSegments": [{ "start": 1.0, "end": 2.0, "overrides": {
                "background": { "source": { "type": "color", "value": [255, 0, 0], "alpha": 255 },
                    "crop": { "position": { "x": 40, "y": 20 }, "size": { "x": 800, "y": 600 } },
                    "padding": 15.0
                }
            } }]
            })).expect("timed configuration")),
            ..Default::default()
        };
        let cursor_only = make_cursor_only_project(project);
        let timeline = cursor_only.timeline.as_ref().expect("timeline");
        assert!(timeline.image_segments.is_empty());
        let styled = cursor_only.style_at(1.5);
        assert_eq!(styled.background.padding, 15.0);
        assert_eq!(
            styled.background.crop.as_ref().expect("crop").size,
            cap_project::XY::new(800, 600)
        );
        assert!(matches!(
            styled.background.source,
            BackgroundSource::Color { alpha: 0, .. }
        ));
    }

    #[test]
    fn cursor_only_preserves_layout_and_recording_time_without_title_pixels() {
        for hide_camera in [false, true] {
            let mut project = ProjectConfiguration::default();
            project.camera.hide = hide_camera;
            project.timeline = Some(
                serde_json::from_value(serde_json::json!({
                    "segments": [{ "start": 0.0, "end": 8.0, "timescale": 1.0 }],
                    "zoomSegments": [],
                    "sceneSegments": [{ "start": 1.0, "end": 3.0, "mode": "splitScreen" }],
                    "textSegments": [
                        { "start": 0.0, "end": 1.0, "layout": "overlay" },
                        { "start": 1.0, "end": 2.0, "layout": "fullscreen" },
                        { "start": 2.0, "end": 3.0, "layout": "splitLeft" },
                        { "start": 3.0, "end": 4.0, "layout": "splitRight" }
                    ]
                }))
                .unwrap(),
            );
            let duration = project.timeline.as_ref().unwrap().duration();
            let cursor_only = make_cursor_only_project(project);
            let timeline = cursor_only.timeline.unwrap();
            assert_eq!(cursor_only.camera.hide, hide_camera);
            assert_eq!(timeline.duration(), duration);
            assert_eq!(
                timeline
                    .text_segments
                    .iter()
                    .map(|text| text.layout)
                    .collect::<Vec<_>>(),
                [
                    TextLayout::Fullscreen,
                    TextLayout::SplitLeft,
                    TextLayout::SplitRight
                ],
            );
            assert!(
                timeline
                    .text_segments
                    .iter()
                    .all(|text| text.content.is_empty())
            );
            assert!(matches!(
                timeline.scene_segments[0].mode,
                cap_project::SceneMode::SplitScreen
            ));
        }
    }
}

#[cfg(test)]
mod cancellation_tests {
    use super::*;

    #[tokio::test(flavor = "current_thread")]
    async fn segment_failure_aborts_and_joins_preparation_before_returning() {
        use std::time::{Duration, Instant};

        let user = Arc::new(AtomicBool::new(false));
        let control = ExportAudioCancellation::new(user.clone());
        let abort = control.stop.clone();
        let completed = Arc::new(AtomicBool::new(false));
        let worker_completed = completed.clone();
        let (started, entered) = tokio::sync::oneshot::channel();
        let preparation = tokio::task::spawn_blocking(move || {
            started.send(()).unwrap();
            let start = Instant::now();
            while !abort.load(Ordering::Relaxed) && start.elapsed() < Duration::from_secs(2) {
                std::thread::yield_now();
            }
            assert!(abort.load(Ordering::Relaxed));
            worker_completed.store(true, Ordering::Release);
            Err(cap_editor::ExportAudioError::Sink(
                "audio preparation error".into(),
            ))
        });
        entered.await.unwrap();
        let result = finish_audio_preparation(
            Err("segment setup error".into()),
            preparation,
            &control.stop,
        )
        .await;
        assert!(
            matches!(result, Err(ExporterBuildError::MediaLoad(error)) if error == "segment setup error")
        );
        assert!(completed.load(Ordering::Acquire));
        assert!(!user.load(Ordering::Relaxed));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn preparation_error_or_panic_is_returned_after_successful_segment_setup() {
        let abort = AtomicBool::new(false);
        for panic in [false, true] {
            let preparation = tokio::task::spawn_blocking(move || {
                assert!(!panic, "preparation panic");
                Err(cap_editor::ExportAudioError::Sink(
                    "preparation error".into(),
                ))
            });
            let result = finish_audio_preparation(Ok(Vec::new()), preparation, &abort).await;
            let Err(ExporterBuildError::MediaLoad(error)) = result else {
                panic!("preparation failure was lost");
            };
            assert!(error.contains(if panic {
                "preparation panic"
            } else {
                "preparation error"
            }));
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn dropped_builder_aborts_preparation_without_user_cancellation() {
        use std::time::{Duration, Instant};

        let user = Arc::new(AtomicBool::new(false));
        let worker_user = user.clone();
        let (started, entered) = tokio::sync::oneshot::channel();
        let (finished, observed) = std::sync::mpsc::channel();
        let builder = tokio::spawn(async move {
            let control = ExportAudioCancellation::new(worker_user);
            let abort = control.stop.clone();
            let preparation = tokio::task::spawn_blocking(move || {
                started.send(()).unwrap();
                let start = Instant::now();
                while !abort.load(Ordering::Relaxed) && start.elapsed() < Duration::from_secs(2) {
                    std::thread::yield_now();
                }
                finished.send(abort.load(Ordering::Relaxed)).unwrap();
                Err(cap_editor::ExportAudioError::Cancelled)
            });
            finish_audio_preparation(Ok(Vec::new()), preparation, &control.stop)
                .await
                .map(|_| ())
                .map_err(|error| error.to_string())
        });
        entered.await.unwrap();
        builder.abort();
        assert!(builder.await.is_err_and(|error| error.is_cancelled()));
        let stopped =
            tokio::task::spawn_blocking(move || observed.recv_timeout(Duration::from_secs(2)))
                .await
                .unwrap()
                .unwrap();
        assert!(stopped);
        assert!(!user.load(Ordering::Relaxed));
        assert_eq!(Arc::strong_count(&user), 1);
    }

    #[test]
    fn unavailable_streaming_destination_falls_back_without_creating_directories() {
        let directory = tempfile::tempdir().unwrap();
        let missing_parent = directory.path().join("missing");
        assert!(prepare_streaming_output(&missing_parent.join("export.mp4"), true).is_none());
        assert!(!missing_parent.exists());
        let existing = directory.path().join("existing.mp4");
        std::fs::write(&existing, b"existing").unwrap();
        assert!(prepare_streaming_output(&existing, true).is_none());
        assert_eq!(std::fs::read(existing).unwrap(), b"existing");
    }

    #[test]
    fn new_gif_destinations_are_staged_beside_the_output() {
        let directory = tempfile::tempdir().unwrap();
        let output = directory.path().join("export.gif");
        let staged = prepare_new_output(&output).unwrap().unwrap();
        let staged_path = staged.to_path_buf();
        assert_eq!(staged_path.parent(), Some(directory.path()));
        assert_eq!(staged_path.extension(), output.extension());
        assert!(!output.exists());
        staged.persist_noclobber(&output).unwrap();
        assert!(output.exists());
        assert!(!staged_path.exists());

        assert!(prepare_new_output(&output).unwrap().is_none());
        assert!(prepare_new_output(&directory.path().join("missing/export.gif")).is_err());
    }

    #[test]
    fn prepared_destination_is_removed_when_preparation_is_dropped() {
        let directory = tempfile::tempdir().unwrap();
        let output = directory.path().join("export.mp4");
        assert!(prepare_streaming_output(&output, false).is_none());
        assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0);
        let prepared = prepare_streaming_output(&output, true).unwrap();
        let temporary_path = prepared.to_path_buf();
        assert!(temporary_path.exists());
        assert!(!output.exists());
        drop(prepared);
        assert!(!temporary_path.exists());
        assert!(!output.exists());
    }

    #[test]
    fn pipeline_stop_does_not_change_user_cancellation() {
        let user = Arc::new(AtomicBool::new(false));
        let cancellation = ExportAudioCancellation::new(user.clone());
        let stop = cancellation.stop.clone();
        drop(cancellation);
        assert!(stop.load(Ordering::Relaxed));
        assert!(!user.load(Ordering::Relaxed));
    }

    #[test]
    fn user_cancellation_does_not_change_pipeline_abort() {
        let user = Arc::new(AtomicBool::new(false));
        let cancellation = ExportAudioCancellation::new(user.clone());
        user.store(true, Ordering::Relaxed);
        assert!(cancellation.user.load(Ordering::Relaxed));
        assert!(!cancellation.stop.load(Ordering::Relaxed));
    }
}

#[cfg(test)]
mod forward_read_tests {
    use super::*;

    fn project(timeline: serde_json::Value) -> ProjectConfiguration {
        serde_json::from_value(serde_json::json!({ "timeline": timeline })).unwrap()
    }

    fn segment(clip: u32, start: f64, end: f64) -> serde_json::Value {
        serde_json::json!({ "recordingSegment": clip, "start": start, "end": end, "timescale": 1.0 })
    }

    #[test]
    fn forward_reads_require_advancing_segments_without_transitions() {
        assert!(reads_recordings_forward(&ProjectConfiguration::default()));
        assert!(reads_recordings_forward(&project(serde_json::json!({
            "segments": [segment(0, 0.0, 4.0), segment(0, 4.0, 6.0), segment(1, 0.0, 2.0), segment(0, 9.0, 12.0)],
            "zoomSegments": []
        }))));
        assert!(!reads_recordings_forward(&project(serde_json::json!({
            "segments": [segment(0, 5.0, 8.0), segment(0, 2.0, 4.0)],
            "zoomSegments": []
        }))));
        assert!(!reads_recordings_forward(&project(serde_json::json!({
            "segments": [segment(0, 0.0, 4.0), segment(0, 3.5, 6.0)],
            "zoomSegments": []
        }))));
        assert!(!reads_recordings_forward(&project(serde_json::json!({
            "segments": [segment(0, 0.0, 4.0), segment(1, 0.0, 4.0)],
            "transitions": [{ "segmentIndex": 1, "type": "cross-fade", "duration": 0.5 }],
            "zoomSegments": []
        }))));
    }
}

/// A Studio recording with a camera is saved without clip offsets: the
/// editor fills them in from the tracks' start times (and the devices'
/// calibration) when it first opens the project. An export of a project the
/// editor never opened would otherwise play every audio track from its own
/// start, late against the screen by how much earlier it started.
fn fill_clip_offsets(
    config: &mut ProjectConfiguration,
    project_path: &std::path::Path,
    studio_meta: &StudioRecordingMeta,
) {
    if config.clips.is_empty() {
        config.clips = cap_editor::initial_clip_configuration(project_path, studio_meta);
    }
}

#[cfg(test)]
mod clip_offset_tests {
    use super::*;
    use cap_project::{
        AudioMeta, ClipConfiguration, ClipOffsets, Cursors, MultipleSegment, MultipleSegments,
        VideoMeta,
    };

    fn camera_recording() -> StudioRecordingMeta {
        let video = |path: &str, start: f64| VideoMeta {
            path: path.into(),
            fps: 30,
            start_time: Some(start),
            device_id: None,
        };
        let audio = |path: &str, start: f64| AudioMeta {
            path: path.into(),
            start_time: Some(start),
            device_id: None,
            gap_summary: None,
            digital_silence_ms: None,
        };
        StudioRecordingMeta::MultipleSegments {
            inner: MultipleSegments {
                segments: vec![MultipleSegment {
                    display: video("display.mp4", 0.2026),
                    camera: Some(video("camera.mp4", 0.0331)),
                    mic: Some(audio("audio-input.ogg", 0.0331)),
                    system_audio: Some(audio("system_audio.ogg", 0.0)),
                    cursor: None,
                    keyboard: None,
                    display_notch: None,
                }],
                cursors: Cursors::default(),
                status: None,
            },
        }
    }

    #[test]
    fn a_project_without_clip_offsets_gets_the_editors() {
        let dir = tempfile::tempdir().unwrap();
        let meta = camera_recording();
        let mut config = ProjectConfiguration::default();
        assert!(config.clips.is_empty());
        fill_clip_offsets(&mut config, dir.path(), &meta);
        let offsets = config.clips[0].offsets;
        assert!((offsets.mic - 0.1695).abs() < 1e-4, "mic {}", offsets.mic);
        assert!(
            (offsets.system_audio - 0.2026).abs() < 1e-4,
            "system {}",
            offsets.system_audio
        );
        assert_eq!(offsets.camera, 0.0);
    }

    #[test]
    fn saved_clip_offsets_are_kept() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = ProjectConfiguration {
            clips: vec![ClipConfiguration {
                index: 0,
                offsets: ClipOffsets {
                    camera: 0.0,
                    mic: 0.5,
                    system_audio: 0.0,
                },
                offsets_auto_calculated: false,
            }],
            ..Default::default()
        };
        fill_clip_offsets(&mut config, dir.path(), &camera_recording());
        assert_eq!(config.clips[0].offsets.mic, 0.5);
    }
}

#[cfg(test)]
mod subtitle_export_tests {
    use super::*;

    fn project(enabled: bool, export: bool) -> ProjectConfiguration {
        serde_json::from_value(serde_json::json!({
            "textSizeVersion": 1,
            "textAnimVersion": 1,
            "captions": {
                "segments": [{"id": "source", "start": 0.0, "end": 2.0, "text": "Keep this caption"}],
                "sourceTimed": true,
                "settings": {"enabled": enabled, "exportWithSubtitles": export, "font": "System Sans-Serif"}
            },
            "timeline": {
                "segments": [{"start": 0.0, "end": 4.0, "timescale": 1.0}],
                "zoomSegments": [],
                "captionSegments": [{"id": "projected", "start": 0.0, "end": 2.0, "text": "Keep this caption"}]
            }
        }))
        .unwrap()
    }

    #[test]
    fn subtitle_export_builder_preserves_caption_visibility_for_disk_and_explicit_configs() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("project-config.json");
        for enabled in [false, true] {
            for export in [false, true] {
                let editor = project(enabled, export);
                let original = serde_json::to_value(&editor).unwrap();
                std::fs::write(&path, serde_json::to_vec(&editor).unwrap()).unwrap();
                let mut disk = ExporterBase::builder(temp.path().to_path_buf());
                let mut explicit =
                    ExporterBase::builder(temp.path().to_path_buf()).with_config(editor);
                for output in [
                    disk.load_project_config().unwrap(),
                    explicit.load_project_config().unwrap(),
                ] {
                    assert_eq!(output.captions.as_ref().unwrap().settings.enabled, enabled);
                    assert_eq!(serde_json::to_value(output).unwrap(), original);
                }
                let persisted: ProjectConfiguration =
                    serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
                assert_eq!(serde_json::to_value(persisted).unwrap(), original);
            }
        }
    }

    #[test]
    fn subtitle_export_includes_legacy_captions_without_an_export_setting() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("project-config.json");
        let mut value = serde_json::to_value(project(true, true)).unwrap();
        assert!(
            value["captions"]["settings"]
                .as_object_mut()
                .unwrap()
                .remove("exportWithSubtitles")
                .is_some()
        );
        std::fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
        let mut builder = ExporterBase::builder(temp.path().to_path_buf());
        let output = builder.load_project_config().unwrap();
        let settings = output.captions.unwrap().settings;
        assert!(settings.enabled);
        assert!(!settings.export_with_subtitles);
    }

    #[test]
    fn subtitle_export_keeps_missing_captions_missing() {
        let mut builder = ExporterBase::builder(PathBuf::from("unused-project"))
            .with_config(ProjectConfiguration::default());
        assert!(builder.load_project_config().unwrap().captions.is_none());
    }

    #[test]
    fn subtitle_export_never_reintroduces_cursor_only_captions() {
        for export in [false, true] {
            let mut builder = ExporterBase::builder(PathBuf::from("unused-project"))
                .with_config(make_cursor_only_project(project(true, export)));
            let output = builder.load_project_config().unwrap();
            assert!(output.captions.is_none());
            assert!(output.timeline.unwrap().caption_segments.is_empty());
        }
    }
}