Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
//! Cooperative export cancellation (MP4 and GIF) and publication of a completed output only.
use anyhow::{bail, Context, Result};
use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::sync::Arc;
const RUNNING: u8 = 0;
const CANCELLED: u8 = 1;
const COMMITTING: u8 = 2;
#[derive(Clone, Default)]
pub struct ExportControl(Arc<AtomicU8>);
#[derive(Debug)]
pub struct ExportCancelled;
impl std::fmt::Display for ExportCancelled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("export cancelled")
}
}
impl std::error::Error for ExportCancelled {}
impl ExportControl {
/// False means publication has already won the race. Repeated cancellation
/// of the same pending job is harmless.
pub fn cancel(&self) -> bool {
match self.0.compare_exchange(RUNNING, CANCELLED, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) | Err(CANCELLED) => true,
Err(_) => false,
}
}
pub fn check(&self) -> Result<()> {
if self.0.load(Ordering::Acquire) == CANCELLED {
return Err(ExportCancelled.into());
}
Ok(())
}
fn begin_commit(&self) -> Result<()> {
match self.0.compare_exchange(RUNNING, COMMITTING, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => Ok(()),
Err(CANCELLED) => Err(ExportCancelled.into()),
Err(_) => bail!("export control has already been used"),
}
}
}
static NEXT_OUTPUT: AtomicU64 = AtomicU64::new(0);
struct StagedOutput {
path: PathBuf,
published: bool,
}
impl Drop for StagedOutput {
fn drop(&mut self) {
if !self.published {
let _ = fs::remove_file(&self.path);
}
}
}
/// Keep the destination intact until rendering and flushing have succeeded.
/// `render` owns the file so it is closed before rename/cleanup on Windows; a
/// renderer that reopens the path (ffmpeg) must close it before returning too.
/// The staged name ends with the target's extension, which is what ffmpeg picks
/// the container from.
pub(crate) fn with_staged_output<T>(
target: &Path,
control: &ExportControl,
render: impl FnOnce(File, &Path) -> Result<T>,
) -> Result<T> {
control.check()?;
let parent = target.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
let ext = target.extension().map(|e| e.to_string_lossy()).unwrap_or_default();
let (mut staged, file) = loop {
let nonce = NEXT_OUTPUT.fetch_add(1, Ordering::Relaxed);
let path = parent.join(format!(".openscreen-{ext}-{}-{nonce}.partial.{ext}", std::process::id()));
match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => break (StagedOutput { path, published: false }, file),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e).context("creating temporary export output"),
}
};
let result = render(file, &staged.path).and_then(|stats| {
control.begin_commit()?;
fs::rename(&staged.path, target).context("publishing completed export output")?;
staged.published = true;
Ok(stats)
});
if result.is_err() && !staged.published {
if let Err(cleanup) = fs::remove_file(&staged.path) {
if cleanup.kind() != std::io::ErrorKind::NotFound {
// A failed cleanup is an error, even if cancellation caused it.
// Do not report a clean cancellation while leaving an output.
bail!("could not remove partial export {}: {cleanup}", staged.path.display());
}
}
}
result
}
/// Render and close an MP4, then verify a displayable decoded frame before
/// publishing it. A positive encoder submission count alone is insufficient:
/// a zero-duration MP4 sample can be flagged discard by the demuxer.
pub(crate) fn with_validated_mp4_output<T>(
target: &Path,
control: &ExportControl,
render: impl FnOnce(File, &Path) -> Result<T>,
) -> Result<T> {
with_staged_output(target, control, |file, staged| {
let stats = render(file, staged)?;
validate_video_frame(staged, control).context("validating exported video")?;
Ok(stats)
})
}
/// Own every FFmpeg allocation so validation closes the file before publication
/// or cleanup, including on cancellation and partially initialized error paths.
#[derive(Default)]
struct VideoValidation {
input: *mut crate::ffi::AVFormatContext,
decoder: *mut crate::ffi::AVCodecContext,
packet: *mut crate::ffi::AVPacket,
frame: *mut crate::ffi::AVFrame,
}
impl Drop for VideoValidation {
/// Release decoder buffers and close the input before rename or cleanup.
fn drop(&mut self) {
unsafe {
crate::ffi::av_frame_free(&mut self.frame);
crate::ffi::av_packet_free(&mut self.packet);
crate::ffi::avcodec_free_context(&mut self.decoder);
if !self.input.is_null() {
crate::ffi::avformat_close_input(&mut self.input);
}
}
}
}
/// Decode only until the first displayable frame. Decode discard-marked preroll
/// packets to preserve reference state, but never accept discard-marked frames.
/// This excludes zero-duration MP4 edit-list samples. Drain delayed frames
/// at EOF, and remain cancellable while scanning interleaved audio packets.
fn validate_video_frame(path: &Path, control: &ExportControl) -> Result<()> {
decode_video_frames(path, control, true).map(|_| ())
}
/// Count actual displayable video frames, including delayed decoder output.
/// Unlike container metadata or duration-based estimates, this also works for
/// streams with no declared frame count. Export publication uses first-only
/// mode separately, so it does not pay for this complete scan.
#[cfg(target_os = "macos")]
pub(crate) fn count_decoded_video_frames(path: &Path) -> Result<u64> {
decode_video_frames(path, &ExportControl::default(), false)
}
/// Share decoder ownership and discard/preroll handling between a first-frame
/// publication check and the macOS probe's complete frame count.
fn decode_video_frames(path: &Path, control: &ExportControl, first_only: bool) -> Result<u64> {
use crate::ffi::*;
use std::{ffi::CString, ptr};
control.check()?;
let path = CString::new(path.to_string_lossy().as_bytes())?;
let mut video = VideoValidation::default();
unsafe {
averr(
avformat_open_input(
&mut video.input,
path.as_ptr(),
ptr::null(),
ptr::null_mut(),
),
"open exported video",
)?;
averr(
avformat_find_stream_info(video.input, ptr::null_mut()),
"read exported video streams",
)?;
let index = av_find_best_stream(
video.input,
AVMediaType::AVMEDIA_TYPE_VIDEO,
-1,
-1,
ptr::null_mut(),
0,
);
averr(index, "find exported video stream")?;
let stream = sn_fmt_stream(video.input, index);
let params = (*stream).codecpar;
let codec = avcodec_find_decoder((*params).codec_id);
if codec.is_null() {
bail!("No decoder is available for the exported video.");
}
video.decoder = avcodec_alloc_context3(codec);
video.packet = av_packet_alloc();
video.frame = av_frame_alloc();
if video.decoder.is_null() || video.packet.is_null() || video.frame.is_null() {
bail!("Could not allocate exported video validation buffers.");
}
averr(
avcodec_parameters_to_context(video.decoder, params),
"configure exported video decoder",
)?;
averr(
avcodec_open2(video.decoder, codec, ptr::null_mut()),
"open exported video decoder",
)?;
let mut draining = false;
let mut frames = 0;
loop {
control.check()?;
let received = avcodec_receive_frame(video.decoder, video.frame);
if received >= 0 {
let displayable = (*video.frame).flags & AV_FRAME_FLAG_DISCARD as i32 == 0
&& (*video.frame).width > 0
&& (*video.frame).height > 0;
av_frame_unref(video.frame);
if displayable {
frames += 1;
if first_only {
return Ok(frames);
}
}
continue;
}
if received == AVERROR_EOF || (draining && received == AVERROR_EAGAIN) {
if frames > 0 {
return Ok(frames);
}
bail!("The exported video has no decodable displayable frames. The destination has not been replaced.");
}
averr(
if received == AVERROR_EAGAIN {
0
} else {
received
},
"decode exported video frame",
)?;
let read = av_read_frame(video.input, video.packet);
if read == AVERROR_EOF {
averr(
avcodec_send_packet(video.decoder, ptr::null()),
"flush exported video decoder",
)?;
draining = true;
} else {
averr(read, "read exported video packet")?;
let sent = if (*video.packet).stream_index == index {
avcodec_send_packet(video.decoder, video.packet)
} else {
0
};
av_packet_unref(video.packet);
averr(sent, "send exported video packet")?;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::sync::Barrier;
struct TestDir(PathBuf);
impl TestDir {
fn new() -> Self {
let nonce = NEXT_OUTPUT.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("openscreen-gif-test-{}-{nonce}", std::process::id()));
fs::create_dir(&path).unwrap();
Self(path)
}
fn assert_only(&self, name: &str) {
let names: Vec<_> = fs::read_dir(&self.0).unwrap().map(|p| p.unwrap().file_name()).collect();
assert_eq!(names, vec![std::ffi::OsString::from(name)]);
}
}
impl Drop for TestDir {
fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); }
}
/// An invalid completed file must not replace the destination or leave a partial.
#[test]
fn invalid_mp4_is_rejected_before_publication() {
let dir = TestDir::new();
let target = dir.0.join("out.mp4");
fs::write(&target, b"previous export").unwrap();
let result = with_validated_mp4_output(&target, &ExportControl::default(), |mut file, _| {
file.write_all(b"not an MP4")?;
Ok(1)
});
assert!(format!("{:#}", result.unwrap_err()).contains("validating exported video"));
assert_eq!(fs::read(&target).unwrap(), b"previous export");
dir.assert_only("out.mp4");
}
/// Cancellation after rendering wins before validation and publication.
#[test]
fn cancellation_before_mp4_validation_preserves_destination() {
let dir = TestDir::new();
let target = dir.0.join("out.mp4");
fs::write(&target, b"previous export").unwrap();
let control = ExportControl::default();
let result = with_validated_mp4_output(&target, &control, |mut file, _| {
file.write_all(b"not an MP4")?;
assert!(control.cancel());
Ok(1)
});
assert!(result.unwrap_err().is::<ExportCancelled>());
assert_eq!(fs::read(&target).unwrap(), b"previous export");
dir.assert_only("out.mp4");
}
#[test]
fn cancellation_before_rendering_never_opens_output() {
let dir = TestDir::new();
let control = ExportControl::default();
assert!(control.cancel());
let result = with_staged_output(&dir.0.join("out.gif"), &control, |_, _| -> Result<()> {
panic!("cancelled job must not render");
});
assert!(result.unwrap_err().is::<ExportCancelled>());
assert_eq!(fs::read_dir(&dir.0).unwrap().count(), 0);
}
#[test]
fn staged_output_keeps_the_target_extension() {
// ffmpeg picks the MP4 muxer from the file name; a bare `.partial` cannot be opened.
let dir = TestDir::new();
let control = ExportControl::default();
with_staged_output(&dir.0.join("out.mp4"), &control, |_, staged| {
assert_eq!(staged.extension().unwrap(), "mp4");
Ok(())
})
.unwrap();
dir.assert_only("out.mp4");
}
#[test]
fn cancellation_discards_partial_output_and_preserves_destination() {
let dir = TestDir::new();
let target = dir.0.join("out.gif");
fs::write(&target, b"original GIF").unwrap();
let control = ExportControl::default();
let result = with_staged_output(&target, &control, |mut file, _| {
file.write_all(b"partial replacement")?;
assert!(control.cancel());
// Even a renderer that has just completed cannot publish now.
Ok(42)
});
assert!(result.unwrap_err().is::<ExportCancelled>());
assert_eq!(fs::read(&target).unwrap(), b"original GIF");
dir.assert_only("out.gif");
}
#[test]
fn successful_publication_replaces_destination_and_rejects_late_cancel() {
let dir = TestDir::new();
let target = dir.0.join("out.gif");
fs::write(&target, b"original").unwrap();
let control = ExportControl::default();
assert_eq!(with_staged_output(&target, &control, |mut file, _| {
file.write_all(b"finished GIF")?;
Ok(7)
}).unwrap(), 7);
assert!(!control.cancel());
assert_eq!(fs::read(&target).unwrap(), b"finished GIF");
dir.assert_only("out.gif");
}
#[test]
fn render_failure_is_not_misreported_as_cancellation() {
let dir = TestDir::new();
let target = dir.0.join("out.gif");
let control = ExportControl::default();
let result = with_staged_output(&target, &control, |mut file, _| -> Result<()> {
file.write_all(b"partial")?;
control.cancel();
bail!("encoder failed")
});
assert_eq!(result.unwrap_err().to_string(), "encoder failed");
assert_eq!(fs::read_dir(&dir.0).unwrap().count(), 0);
}
#[test]
fn publication_failure_cleans_up_staging() {
let dir = TestDir::new();
let target = dir.0.join("destination-directory");
fs::create_dir(&target).unwrap();
let control = ExportControl::default();
assert!(with_staged_output(&target, &control, |mut file, _| {
file.write_all(b"finished GIF")?;
Ok(())
}).is_err());
assert!(target.is_dir());
dir.assert_only("destination-directory");
}
#[test]
fn cancellation_and_commit_have_exactly_one_winner() {
for _ in 0..64 {
let control = ExportControl::default();
let cancel_control = control.clone();
let barrier = Arc::new(Barrier::new(2));
let cancel_barrier = barrier.clone();
let cancel = std::thread::spawn(move || {
cancel_barrier.wait();
cancel_control.cancel()
});
barrier.wait();
let committed = control.begin_commit().is_ok();
assert_ne!(committed, cancel.join().unwrap());
}
}
}