Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(export): keep cancelled GIF exports from leaving a partial file

Aditya Garud5a0eba96557d
diff --git a/crates/export/src/gif.rs b/crates/export/src/gif.rs
index bb8880c4a..fcc473c12 100644
--- a/crates/export/src/gif.rs
+++ b/crates/export/src/gif.rs
@@ -6,7 +6,7 @@ use specta::Type;
use std::path::PathBuf;
use tracing::trace;
-use crate::{ExportError, ExporterBase};
+use crate::{ExportError, ExporterBase, prepare_new_output};
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Type)]
pub struct GifQuality {
@@ -109,8 +109,11 @@ impl GifExportSettings {
})
.unwrap_or_default();
+ let temporary_output = prepare_new_output(&gif_output_path);
let mut gif_encoder = cap_enc_gif::GifEncoderWrapper::new_with_quality(
- &gif_output_path,
+ temporary_output
+ .as_ref()
+ .map_or(gif_output_path.as_path(), AsRef::as_ref),
output_size.0,
output_size.1,
fps,
@@ -151,7 +154,7 @@ impl GifExportSettings {
return Err(ExportError::Other(format!("Failed to finish GIF: {e}")));
}
- Ok(gif_output_path)
+ Ok(())
})
.then(|f| async {
f.map_err(|e| e.to_string())
@@ -180,9 +183,13 @@ impl GifExportSettings {
)
.then(|f| async { f.map_err(|v| v.to_string()) });
- let (output_path, _) =
- tokio::try_join!(encoder_thread, render_video_task).map_err(|e| e.to_string())?;
+ tokio::try_join!(encoder_thread, render_video_task)?;
+ if let Some(temporary_output) = temporary_output {
+ temporary_output
+ .persist_noclobber(&gif_output_path)
+ .map_err(|e| e.to_string())?;
+ }
- Ok(output_path)
+ Ok(gif_output_path)
}
}
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 1a5667796..a2b5be57f 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -356,14 +356,21 @@ pub fn make_cursor_only_project(mut project_config: ProjectConfiguration) -> Pro
fn prepare_streaming_output(
output: &std::path::Path,
eligible: bool,
-) -> Option<mp4::TemporaryMp4Output> {
- if !eligible
- || output.extension().and_then(|extension| extension.to_str()) != Some("mp4")
- || !matches!(std::fs::symlink_metadata(output), Err(error) if error.kind() == std::io::ErrorKind::NotFound)
+) -> Option<mp4::TemporaryExportOutput> {
+ if !eligible || output.extension().and_then(|extension| extension.to_str()) != Some("mp4") {
+ return None;
+ }
+ prepare_new_output(output)
+}
+
+/// 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) -> Option<mp4::TemporaryExportOutput> {
+ if !matches!(std::fs::symlink_metadata(output), Err(error) if error.kind() == std::io::ErrorKind::NotFound)
{
return None;
}
- mp4::temporary_mp4_output(output).ok()
+ mp4::temporary_export_output(output).ok()
}
struct ExportAudioCancellation {
@@ -408,7 +415,7 @@ pub struct ExporterBase {
segments: Vec<SegmentMedia>,
output_path: PathBuf,
streaming_audio: Option<ExportAudioRenderer>,
- streaming_output: Option<mp4::TemporaryMp4Output>,
+ streaming_output: Option<mp4::TemporaryExportOutput>,
audio_cancellation: Option<ExportAudioCancellation>,
sample_windows: Option<cap_rendering::FrameWindows>,
sample_timing: Option<Arc<estimates::SampleTiming>>,
diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rs
index f120f6cff..16fb62ce9 100644
--- a/crates/export/src/mp4.rs
+++ b/crates/export/src/mp4.rs
@@ -1133,7 +1133,7 @@ fn join_audio_thread(
}
#[derive(Debug)]
-pub(crate) struct TemporaryMp4Output {
+pub(crate) struct TemporaryExportOutput {
path: tempfile::TempPath,
#[cfg(unix)]
file: std::fs::File,
@@ -1141,18 +1141,21 @@ pub(crate) struct TemporaryMp4Output {
final_permissions: std::fs::Permissions,
}
-impl AsRef<std::path::Path> for TemporaryMp4Output {
+impl AsRef<std::path::Path> for TemporaryExportOutput {
fn as_ref(&self) -> &std::path::Path {
self.path.as_ref()
}
}
-impl TemporaryMp4Output {
+impl TemporaryExportOutput {
pub(crate) fn to_path_buf(&self) -> PathBuf {
self.path.to_path_buf()
}
- fn persist_noclobber(self, output: &std::path::Path) -> Result<(), tempfile::PathPersistError> {
+ pub(crate) fn persist_noclobber(
+ self,
+ output: &std::path::Path,
+ ) -> Result<(), tempfile::PathPersistError> {
#[cfg(unix)]
let prepare_permissions = || {
use std::os::unix::fs::MetadataExt;
@@ -1177,11 +1180,17 @@ impl TemporaryMp4Output {
}
}
-pub(crate) fn temporary_mp4_output(output: &std::path::Path) -> Result<TemporaryMp4Output, String> {
+pub(crate) fn temporary_export_output(
+ output: &std::path::Path,
+) -> Result<TemporaryExportOutput, String> {
let parent = output.parent().unwrap_or_else(|| std::path::Path::new("."));
+ let suffix = output
+ .extension()
+ .map(|extension| format!(".{}", extension.to_string_lossy()))
+ .unwrap_or_default();
let temporary = tempfile::Builder::new()
.prefix(".cap-export-")
- .suffix(".mp4")
+ .suffix(&suffix)
.tempfile_in(parent)
.map_err(|error| error.to_string())?;
#[cfg(unix)]
@@ -1203,7 +1212,7 @@ pub(crate) fn temporary_mp4_output(output: &std::path::Path) -> Result<Temporary
let (file, path) = temporary.into_parts();
#[cfg(not(unix))]
drop(file);
- Ok(TemporaryMp4Output {
+ Ok(TemporaryExportOutput {
path,
#[cfg(unix)]
file,
@@ -1679,7 +1688,7 @@ mod tests {
async fn validation_failure_releases_pending_producer_receiver_and_temp_owners() {
let directory = tempfile::tempdir().unwrap();
let output = directory.path().join("export.mp4");
- let temporary = Arc::new(temporary_mp4_output(&output).unwrap());
+ let temporary = Arc::new(temporary_export_output(&output).unwrap());
let temporary_path = temporary.to_path_buf();
let abort = Arc::new(AtomicBool::new(false));
let user = AtomicBool::new(false);
@@ -1753,13 +1762,13 @@ mod tests {
fn temporary_output_is_removed_on_failure_and_never_overwrites() {
let directory = tempfile::tempdir().unwrap();
let output = directory.path().join("export.mp4");
- let temporary = temporary_mp4_output(&output).unwrap();
+ let temporary = temporary_export_output(&output).unwrap();
let path = temporary.to_path_buf();
std::fs::write(&path, b"partial").unwrap();
drop(temporary);
assert!(!path.exists());
assert!(!output.exists());
- let temporary = temporary_mp4_output(&output).unwrap();
+ let temporary = temporary_export_output(&output).unwrap();
std::fs::write(&temporary, b"completed").unwrap();
std::fs::write(&output, b"existing").unwrap();
drop(temporary.persist_noclobber(&output).unwrap_err());
@@ -1775,7 +1784,7 @@ mod tests {
let output = directory.path().join("export.mp4");
let reference = directory.path().join("reference.mp4");
std::fs::write(&reference, b"reference").unwrap();
- let temporary = temporary_mp4_output(&output).unwrap();
+ let temporary = temporary_export_output(&output).unwrap();
assert_eq!(
std::fs::metadata(&temporary).unwrap().permissions().mode() & 0o077,
0
@@ -1798,7 +1807,7 @@ mod tests {
let private = directory.path().join("private.mp4");
std::fs::write(&private, b"private recording").unwrap();
std::fs::set_permissions(&private, std::fs::Permissions::from_mode(0o600)).unwrap();
- let temporary = temporary_mp4_output(&output).unwrap();
+ let temporary = temporary_export_output(&output).unwrap();
let temporary_path = temporary.to_path_buf();
std::fs::remove_file(&temporary_path).unwrap();
symlink(&private, &temporary_path).unwrap();
diff --git a/crates/export/tests/gif_cancellation.rs b/crates/export/tests/gif_cancellation.rs
new file mode 100644
index 000000000..d9866a0b0
--- /dev/null
+++ b/crates/export/tests/gif_cancellation.rs
@@ -0,0 +1,106 @@
+use cap_export::{ExporterBase, gif::GifExportSettings};
+use cap_project::{ProjectConfiguration, XY};
+use image::AnimationDecoder;
+use std::{fs, path::Path, process::Command};
+
+fn create_project(path: &Path) {
+ fs::create_dir_all(path).unwrap();
+ let video = Command::new("ffmpeg")
+ .args([
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=size=64x64:rate=10:duration=1",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "ultrafast",
+ "-threads",
+ "1",
+ ])
+ .arg(path.join("display.mp4"))
+ .output()
+ .unwrap();
+ assert!(
+ video.status.success(),
+ "{}",
+ String::from_utf8_lossy(&video.stderr)
+ );
+ fs::write(
+ path.join("recording-meta.json"),
+ serde_json::to_vec(&serde_json::json!({
+ "pretty_name": "GIF cancellation",
+ "display": { "path": "display.mp4", "fps": 10 }
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+}
+
+async fn export(
+ project: &Path,
+ output: &Path,
+ on_progress: impl FnMut(u32) -> bool + Send + 'static,
+) -> Result<std::path::PathBuf, String> {
+ let base = Box::pin(
+ ExporterBase::builder(project.to_path_buf())
+ .with_config(ProjectConfiguration::default())
+ .with_output_path(output.to_path_buf())
+ .build(),
+ )
+ .await
+ .unwrap();
+ Box::pin(
+ GifExportSettings {
+ fps: 10,
+ resolution_base: XY::new(64, 64),
+ quality: None,
+ }
+ .export(base, on_progress),
+ )
+ .await
+}
+
+#[tokio::test]
+#[ignore = "requires ffmpeg and a wgpu adapter"]
+async fn cancelled_gif_leaves_no_partial_destination() {
+ let directory = tempfile::tempdir().unwrap();
+ let project = directory.path().join("project.cap");
+ create_project(&project);
+ let output = directory.path().join("export.gif");
+
+ assert!(export(&project, &output, |frame| frame < 2).await.is_err());
+
+ assert!(!output.exists());
+ assert_eq!(fs::read_dir(directory.path()).unwrap().count(), 1);
+}
+
+#[tokio::test]
+#[ignore = "requires ffmpeg and a wgpu adapter"]
+async fn finished_gif_lands_at_the_destination() {
+ let directory = tempfile::tempdir().unwrap();
+ let project = directory.path().join("project.cap");
+ create_project(&project);
+ let output = directory.path().join("export.gif");
+ let destination = output.clone();
+
+ let result = export(&project, &output, move |_| {
+ assert!(!destination.exists());
+ true
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(result, output);
+ let frames = image::codecs::gif::GifDecoder::new(std::io::BufReader::new(
+ fs::File::open(output).unwrap(),
+ ))
+ .unwrap()
+ .into_frames()
+ .collect_frames()
+ .unwrap();
+ assert!(!frames.is_empty());
+ assert_eq!(fs::read_dir(directory.path()).unwrap().count(), 2);
+}