Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

fix(export): an export never leaves a broken file, and nothing a document says can panic the GPU

Jareera2dd5e36a867
diff --git a/src/Cargo.lock b/src/Cargo.lock
index 4c423000..75c77ae1 100644
--- a/src/Cargo.lock
+++ b/src/Cargo.lock
@@ -1179,6 +1179,7 @@ name = "concat-api"
version = "0.2.6"
dependencies = [
"base64 0.22.1",
+ "concat-core",
"concat-effects",
"concat-export",
"concat-host",
diff --git a/src/crates/concat-api/Cargo.toml b/src/crates/concat-api/Cargo.toml
index f2bd9499..bd3b6dad 100644
--- a/src/crates/concat-api/Cargo.toml
+++ b/src/crates/concat-api/Cargo.toml
@@ -7,6 +7,7 @@ license.workspace = true
description = "The Concat API: one dispatcher for projects, edits, media, effects, templates, exports and frames, which every transport - the command line, a daemon, a plugin - calls."
[dependencies]
+concat-core.workspace = true
concat-project.workspace = true
concat-effects.workspace = true
concat-export.workspace = true
diff --git a/src/crates/concat-api/src/lib.rs b/src/crates/concat-api/src/lib.rs
index 4f2c89ea..0f03cd84 100644
--- a/src/crates/concat-api/src/lib.rs
+++ b/src/crates/concat-api/src/lib.rs
@@ -69,10 +69,11 @@ const CAPABILITIES: &[&str] = &["events"];
/// that writes them to a caller locks its writer inside.
pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
-/// The largest frame a preview or an export may ask for, a side: 8K. A
-/// caller with the token is trusted to edit, not to ask the machine for
-/// seventeen gigabytes of pixels (audit 2026-09-23, #4).
-pub const MAX_SIDE: u32 = 8192;
+/// The largest frame a preview or an export may ask for, a side: 8K, the
+/// engine's own ceiling. A caller with the token is trusted to edit, not
+/// to ask the machine for seventeen gigabytes of pixels (audit 2026-09-23,
+/// #4).
+pub const MAX_SIDE: u32 = concat_core::frame::MAX_SIDE;
/// The highest constant rate factor any codec here takes.
const MAX_CRF: u8 = 63;
/// The fastest frame rate an export may ask for.
diff --git a/src/crates/concat-core/src/frame.rs b/src/crates/concat-core/src/frame.rs
index 37fcb136..a825c994 100644
--- a/src/crates/concat-core/src/frame.rs
+++ b/src/crates/concat-core/src/frame.rs
@@ -25,6 +25,12 @@ use std::sync::atomic::{AtomicU64, Ordering};
/// Bytes per pixel of an eight-bit frame, the format nearly everything uses.
pub const BYTES_PER_PIXEL: usize = 4;
+/// The widest or tallest a frame may be, a side: 8K. The downlevel
+/// texture limit every GPU meets is this, so a frame past it cannot be
+/// drawn, only asked for; a document, a request and a preview are all held
+/// to it before a texture is made (audit 2026-10-09, finding 8).
+pub const MAX_SIDE: u32 = 8192;
+
/// How many bits a channel a frame's pixels hold.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Depth {
diff --git a/src/crates/concat-export/src/lib.rs b/src/crates/concat-export/src/lib.rs
index d337bb2f..5c9c8675 100644
--- a/src/crates/concat-export/src/lib.rs
+++ b/src/crates/concat-export/src/lib.rs
@@ -893,6 +893,19 @@ pub fn render_on(
request.rate_num, request.rate_den
)
})?;
+ // A frame past what one texture can hold would panic the GPU device at
+ // its first allocation, on this thread; the document and the API hold
+ // their callers to the same ceiling, and the command line reaches here
+ // with nothing in between.
+ let side = 1..=concat_core::frame::MAX_SIDE;
+ if !side.contains(&request.width) || !side.contains(&request.height) {
+ return Err(format!(
+ "{}×{} is not a frame size a video can have; the most is {} a side",
+ request.width,
+ request.height,
+ concat_core::frame::MAX_SIDE
+ ));
+ }
let output = PathBuf::from(&request.output);
// Transitions become overlaps, ramps and fade filters before anything
@@ -963,7 +976,12 @@ pub fn render_on(
}
let silent = directory.join(format!(".{stem}.concat-video.mp4"));
let mixed = directory.join(format!(".{stem}.concat-audio.m4a"));
+ let muxed = directory.join(format!(".{stem}.concat-muxed.mp4"));
+ // The output path is touched once, by the rename at the end, whichever
+ // way the file was made. The mux used to write it directly, and a mux
+ // that failed - the disk full, a read error - left a truncated file
+ // where the previous export had been (audit 2026-10-09, finding 4).
let result = (|| -> Result<(), String> {
render_picture(
request,
@@ -976,24 +994,26 @@ pub fn render_on(
&mut reporter,
)?;
- if sound.is_empty() {
- std::fs::rename(&silent, &output)
- .map_err(|error| format!("could not write {}: {error}", output.display()))?;
- return Ok(());
- }
-
- reporter.cancelled()?;
- reporter.emit(0, total_frames, "mixing audio");
- let mix: Vec<AudioClip> = sound.iter().flat_map(|clip| audio_pieces(clip)).collect();
- audio::mix_to_file(&mix, timeline_end, &mixed).map_err(|error| error.to_string())?;
-
- reporter.cancelled()?;
- reporter.emit(total_frames, total_frames, "muxing");
- audio::mux(&silent, &mixed, &output).map_err(|error| error.to_string())
+ let finished = if sound.is_empty() {
+ &silent
+ } else {
+ reporter.cancelled()?;
+ reporter.emit(0, total_frames, "mixing audio");
+ let mix: Vec<AudioClip> = sound.iter().flat_map(|clip| audio_pieces(clip)).collect();
+ audio::mix_to_file(&mix, timeline_end, &mixed).map_err(|error| error.to_string())?;
+
+ reporter.cancelled()?;
+ reporter.emit(total_frames, total_frames, "muxing");
+ audio::mux(&silent, &mixed, &muxed).map_err(|error| error.to_string())?;
+ &muxed
+ };
+ std::fs::rename(finished, &output)
+ .map_err(|error| format!("could not write {}: {error}", output.display()))
})();
let _ = std::fs::remove_file(&silent);
let _ = std::fs::remove_file(&mixed);
+ let _ = std::fs::remove_file(&muxed);
result.map(|()| output.to_string_lossy().into_owned())
}
@@ -1330,32 +1350,39 @@ fn render_picture(
.get(&layer.clip)
.copied()
.unwrap_or((request.width, request.height));
- if let Ok(frame) = sought.frame_at(
- &layer.media,
- layer.source_time,
- decode_width,
- decode_height,
- stills.contains(&layer.clip),
- None,
- None,
- ranges.get(&layer.clip).copied(),
- // Deep where the frame goes to the GPU as it is: a
- // cutout cuts eight bits.
- !cutouts.contains_key(&layer.clip),
- ) {
- let frame = cutouts
- .get(&layer.clip)
- .and_then(|job| job.cut(&frame, layer.source_time))
- .map_or(frame, std::sync::Arc::new);
- layers.push(filled(
- layer,
- frame,
- tracks.get(&layer.clip).copied().unwrap_or(0),
- passes_at(&chains, &reveal_maps, &timeline, layer.clip, time),
- geometry.get(&layer.clip),
- shapes_at(&shapes, layer, time, rate),
- ));
- }
+ // A frame that cannot be read ends the export with the
+ // reason, as it does on the paced path below. A time past
+ // the media's end is not that: the pool answers it with the
+ // last frame. This path used to drop a failed frame on the
+ // floor, so a reversed or retimed clip whose file had gone
+ // bad exported as a missing layer and nobody was told.
+ let frame = sought
+ .frame_at(
+ &layer.media,
+ layer.source_time,
+ decode_width,
+ decode_height,
+ stills.contains(&layer.clip),
+ None,
+ None,
+ ranges.get(&layer.clip).copied(),
+ // Deep where the frame goes to the GPU as it is: a
+ // cutout cuts eight bits.
+ !cutouts.contains_key(&layer.clip),
+ )
+ .map_err(|error| error.to_string())?;
+ let frame = cutouts
+ .get(&layer.clip)
+ .and_then(|job| job.cut(&frame, layer.source_time))
+ .map_or(frame, std::sync::Arc::new);
+ layers.push(filled(
+ layer,
+ frame,
+ tracks.get(&layer.clip).copied().unwrap_or(0),
+ passes_at(&chains, &reveal_maps, &timeline, layer.clip, time),
+ geometry.get(&layer.clip),
+ shapes_at(&shapes, layer, time, rate),
+ ));
continue;
}
let decoder = match decoders.entry(layer.clip) {
diff --git a/src/crates/concat-media/src/probe.rs b/src/crates/concat-media/src/probe.rs
index c680872f..ba22e256 100644
--- a/src/crates/concat-media/src/probe.rs
+++ b/src/crates/concat-media/src/probe.rs
@@ -221,9 +221,16 @@ fn rational(value: ffmpeg::Rational) -> Option<Rational> {
/// base rate is whatever the timestamps' common denominator happens to
/// be and can be absurd. `avg_frame_rate` is 0/0 for such a stream with
/// no average either, in which case the base rate is the best guess left.
+///
+/// A rate is usable when it is one a video can have: positive, and with
+/// terms the frame arithmetic can count in ([`FrameRate::checked`]). A
+/// container can say anything - `1/2147483647` is a rate libavformat will
+/// hand out - and a term past the limit overflowed the first frame time
+/// computed on it, where the document's own rates are checked at the door.
fn pick_rate(average: Option<Rational>, guess: Option<Rational>) -> Option<Rational> {
- let usable =
- |rate: &Option<Rational>| rate.filter(|rate| !rate.is_zero() && !rate.is_negative());
+ let usable = |rate: &Option<Rational>| {
+ rate.filter(|rate| FrameRate::checked(rate.numerator(), rate.denominator()).is_some())
+ };
match (usable(&average), usable(&guess)) {
(Some(average), Some(base)) => {
let (a, b) = (average.as_f64(), base.as_f64());
@@ -275,6 +282,21 @@ mod tests {
assert_eq!(pick_rate(None, None), None);
}
+ /// A rate whose terms the frame arithmetic cannot count in is not a
+ /// rate: the other one is taken, and with neither usable the stream
+ /// has no rate rather than a panic waiting in its first frame time.
+ #[test]
+ fn a_rate_past_the_frame_arithmetic_is_not_usable() {
+ let absurd = Some(Rational::new(1, i64::from(i32::MAX)));
+ let thirty = Some(Rational::from_int(30));
+ assert!(FrameRate::checked(1, i64::from(i32::MAX)).is_none());
+ assert_eq!(pick_rate(absurd, thirty), thirty);
+ assert_eq!(pick_rate(thirty, absurd), thirty);
+ assert_eq!(pick_rate(absurd, absurd), None);
+ let negative = Some(Rational::new(-25, 1));
+ assert_eq!(pick_rate(negative, thirty), thirty);
+ }
+
#[test]
fn a_missing_file_is_an_error_not_a_panic() {
assert!(probe("does-not-exist.mp4").is_err());
diff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rs
index a9f879e8..14459305 100644
--- a/src/crates/concat-project/src/lib.rs
+++ b/src/crates/concat-project/src/lib.rs
@@ -202,6 +202,26 @@ mod tests {
let opened = edited.or(VideoSettings::default());
assert_eq!((opened.rate_num, opened.rate_den), (30, 1));
assert!(opened.is_sane());
+ // A side past what one texture holds is refused the same way, and
+ // opens at the fallback's size rather than panicking the GPU.
+ let vast = VideoSettings {
+ width: 10_000,
+ height: 1080,
+ ..VideoSettings::default()
+ };
+ assert!(!vast.is_sane());
+ let opened = vast.or(VideoSettings::default());
+ assert_eq!(
+ (opened.width, opened.height),
+ (VideoSettings::default().width, 1080)
+ );
+ assert!(opened.is_sane());
+ let edge = VideoSettings {
+ width: concat_core::frame::MAX_SIDE,
+ height: concat_core::frame::MAX_SIDE,
+ ..VideoSettings::default()
+ };
+ assert!(edge.is_sane());
let ntsc = VideoSettings {
rate_num: 30000,
rate_den: 1001,
@@ -910,6 +930,43 @@ mod tests {
assert_eq!(nan.max_height, 0.0);
}
+ /// A hand-edited clip time has a ceiling as well as a floor: `1e300`
+ /// loaded as written, its frame number saturated, and the export
+ /// panicked computing its time (audit 2026-10-09, finding 9).
+ #[test]
+ fn a_clip_time_past_a_hundred_hours_is_pulled_back() {
+ use crate::model::ranges::MAX_TIME;
+ let (editor, _, clip_id) = fixture();
+ let clip = editor
+ .project()
+ .active()
+ .clips
+ .iter()
+ .find(|clip| clip.id == clip_id)
+ .expect("the clip")
+ .as_ref()
+ .clone();
+ let far = crate::model::Clip {
+ start: 1e300,
+ duration: f64::INFINITY,
+ source_start: 1e300,
+ fade_in: 1e300,
+ fade_out: 1e300,
+ ..clip
+ }
+ .tidy();
+ assert_eq!(far.start, MAX_TIME);
+ assert_eq!(far.duration, 1.0, "not a number falls back to a second");
+ assert_eq!(far.source_start, MAX_TIME);
+ assert_eq!((far.fade_in, far.fade_out), (MAX_TIME, MAX_TIME));
+ let long = crate::model::Clip {
+ duration: 1e300,
+ ..far.clone()
+ }
+ .tidy();
+ assert_eq!(long.duration, MAX_TIME);
+ }
+
#[test]
fn a_new_project_has_one_timeline_and_four_lanes() {
let editor = Editor::new();
diff --git a/src/crates/concat-project/src/model.rs b/src/crates/concat-project/src/model.rs
index 884b649d..daa3852e 100644
--- a/src/crates/concat-project/src/model.rs
+++ b/src/crates/concat-project/src/model.rs
@@ -1206,6 +1206,11 @@ pub(crate) mod wire {
pub mod ranges {
/// The shortest a clip can be: one frame at sixty.
pub const MIN_CLIP_DURATION: f64 = 1.0 / 60.0;
+ /// The furthest a clip may start, the longest it may run, and the
+ /// deepest an in-point or a fade may reach, in seconds: a hundred
+ /// hours. No cut is that long; a hand-edited `1e300` was, and its
+ /// frame number overflowed the export's arithmetic.
+ pub const MAX_TIME: f64 = 360_000.0;
/// The engine's speed range (concat-media `SPEED_RANGE`), verbatim.
pub const MIN_SPEED: f64 = 0.0625;
/// The top of the engine's speed range.
@@ -1471,12 +1476,12 @@ impl Clip {
fn finite(value: f64, fallback: f64) -> f64 {
if value.is_finite() { value } else { fallback }
}
- self.start = finite(self.start, 0.0).max(0.0);
- self.duration = finite(self.duration, 1.0).max(MIN_CLIP_DURATION);
- self.source_start = finite(self.source_start, 0.0).max(0.0);
+ self.start = finite(self.start, 0.0).clamp(0.0, MAX_TIME);
+ self.duration = finite(self.duration, 1.0).clamp(MIN_CLIP_DURATION, MAX_TIME);
+ self.source_start = finite(self.source_start, 0.0).clamp(0.0, MAX_TIME);
self.volume = finite(self.volume, 1.0).max(0.0);
- self.fade_in = finite(self.fade_in, 0.0).max(0.0);
- self.fade_out = finite(self.fade_out, 0.0).max(0.0);
+ self.fade_in = finite(self.fade_in, 0.0).clamp(0.0, MAX_TIME);
+ self.fade_out = finite(self.fade_out, 0.0).clamp(0.0, MAX_TIME);
self.scale = finite(self.scale, 1.0).clamp(MIN_SCALE, MAX_SCALE);
self.offset_x = finite(self.offset_x, 0.0).clamp(-MAX_OFFSET, MAX_OFFSET);
self.offset_y = finite(self.offset_y, 0.0).clamp(-MAX_OFFSET, MAX_OFFSET);
@@ -1902,10 +1907,10 @@ impl VideoSettings {
self.rate_num as f64 / self.rate_den.max(1) as f64
}
- /// This frame with every zero or negative field taken from `fallback`
- /// instead, and the rate as a pair when it is not one a video has (see
- /// [`FrameRate::checked`](concat_core::time::FrameRate::checked)): a
- /// document hand-edited into nonsense still opens at a size that is a
+ /// This frame with every zero, negative or oversize field taken from
+ /// `fallback` instead, and the rate as a pair when it is not one a video
+ /// has (see [`FrameRate::checked`](concat_core::time::FrameRate::checked)):
+ /// a document hand-edited into nonsense still opens at a size that is a
/// size, and at a rate the frame arithmetic can count in.
pub fn or(self, fallback: VideoSettings) -> VideoSettings {
let settings = self.or_terms(fallback);
@@ -1922,12 +1927,12 @@ impl VideoSettings {
fn or_terms(self, fallback: VideoSettings) -> VideoSettings {
VideoSettings {
- width: if self.width > 0 {
+ width: if Self::side_is_sane(self.width) {
self.width
} else {
fallback.width
},
- height: if self.height > 0 {
+ height: if Self::side_is_sane(self.height) {
self.height
} else {
fallback.height
@@ -1949,12 +1954,19 @@ impl VideoSettings {
/// Whether every term is one a frame could actually have. A zero
/// dimension or rate is never a real setting, only a caller bug, and
/// writing one would poison the document until the next open. Neither
- /// is a rate whose terms overflow the frame arithmetic.
+ /// is a rate whose terms overflow the frame arithmetic, nor a side past
+ /// what a GPU can hold in one texture
+ /// ([`MAX_SIDE`](concat_core::frame::MAX_SIDE)): a 10 000-pixel
+ /// timeline panicked the export and the preview at the first texture.
pub fn is_sane(self) -> bool {
- self.width > 0
- && self.height > 0
+ Self::side_is_sane(self.width)
+ && Self::side_is_sane(self.height)
&& concat_core::time::FrameRate::checked(self.rate_num, self.rate_den).is_some()
}
+
+ fn side_is_sane(side: u32) -> bool {
+ (1..=concat_core::frame::MAX_SIDE).contains(&side)
+ }
}
/// A font the user added from disk.
diff --git a/src/crates/concat-render/src/gpu.rs b/src/crates/concat-render/src/gpu.rs
index 0c6db126..0ea7de8e 100644
--- a/src/crates/concat-render/src/gpu.rs
+++ b/src/crates/concat-render/src/gpu.rs
@@ -704,11 +704,21 @@ impl WgpuCompositor {
.ok()?;
// The reason, when it dies, in the log: see the window's device.
let name = adapter.get_info().name;
+ let lost = name.clone();
device.set_device_lost_callback(move |reason, message| {
log::error!(
- "the compositor's GPU device on {name} was lost ({reason:?}): {message}"
+ "the compositor's GPU device on {lost} was lost ({reason:?}): {message}"
);
});
+ // An error no scope caught - a texture past the device's limit,
+ // a buffer the driver refused - is wgpu's to handle, and its
+ // default handler panics the thread it is on: the export's, or
+ // the preview's. Logged instead, the frame it was in comes out
+ // wrong and the thread goes on; the pipelines' own error scopes
+ // (`run_stages`) still catch what they catch.
+ device.on_uncaptured_error(std::sync::Arc::new(move |error: wgpu::Error| {
+ log::error!("the compositor's GPU device on {name} reported an error: {error}");
+ }));
Some(Self::with_device(device, queue))
})
}
diff --git a/src/crates/concat/src/gpu.rs b/src/crates/concat/src/gpu.rs
index 8ec2ac0c..323391fd 100644
--- a/src/crates/concat/src/gpu.rs
+++ b/src/crates/concat/src/gpu.rs
@@ -103,6 +103,13 @@ impl Gpu {
device.set_device_lost_callback(|reason, message| {
log::error!("the window's GPU device was lost ({reason:?}): {message}");
});
+ // An error no scope caught goes to the log too. wgpu's default
+ // handler panics, and on this device that is the window's thread:
+ // a texture past the limit, asked for by anything that draws on it,
+ // took the app down where a bad frame would do.
+ device.on_uncaptured_error(std::sync::Arc::new(|error: wgpu::Error| {
+ log::error!("the window's GPU device reported an error: {error}");
+ }));
Some(Gpu {
instance,
adapter,