diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs
index 5c0c0aa..5746ac8 100644
--- a/crates/engine/src/export.rs
+++ b/crates/engine/src/export.rs
@@ -106,7 +106,15 @@ pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;
/// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is
/// left rather than starting again from zero.
fn picture_progress(done: u32, total: u32) -> u32 {
- AUDIO_BAND + done.min(total) * (PROGRESS_SCALE - AUDIO_BAND) / total.max(1)
+ // In `u64`: this is a picture count times a permille, and a film past
+ // ~4.5 M pictures (42 hours at 30 fps) overflowed the `u32` this used to be
+ // computed in -- a panic in debug inside the export thread, which a caller
+ // reads as `export worker panicked` on a file that was never written, and a
+ // bar that thrashed in release. The result is under the scale by
+ // construction, so the narrowing back is exact.
+ let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
+ let done = u64::from(done.min(total));
+ AUDIO_BAND + (done * band / u64::from(total.max(1))) as u32
}
/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
@@ -453,8 +461,17 @@ struct Shared {
outcome: Mutex>>,
/// The encoders this job really opened, published the moment they are
/// chosen and never changed after -- one seat for the whole file, which is
- /// what [`Enc`] states. `None` until then.
+ /// what [`Enc`] states. `None` until then. The one thing that joins it
+ /// afterwards is how much of the edit never got a picture
+ /// ([`Shared::truncated`]), and [`ExportHandle::encoders`] does that
+ /// joining, so a notice cannot land on the line twice.
encoders: Mutex >,
+ /// Timeline frames of the edit the walk could not write because a file ran
+ /// out before its clip did ([`run`]'s break). The bar reaches its end
+ /// whatever happens, so without this a truncated file reads as a whole one.
+ /// Published the moment the walk gives up and read by
+ /// [`ExportHandle::encoders`] beside the seat line.
+ truncated: AtomicU32,
}
/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
@@ -486,8 +503,17 @@ impl ExportHandle {
/// What this export is encoding with -- the video seat and what the sound
/// is doing -- as the worker chose them, hardware fallback included.
/// `None` for the first instants of a job, before the encoder is open.
+ ///
+ /// ...and, where a file ran out under its clip, how much of the edit never
+ /// got a picture. Composed here rather than written into the stored line,
+ /// because that line is published more than once on a rerun (a hardware
+ /// seat that died) and a notice appended at the write site lands twice.
pub fn encoders(&self) -> Option {
- self.shared.encoders.lock().unwrap().clone()
+ let line = self.shared.encoders.lock().unwrap().clone()?;
+ Some(match self.shared.truncated.load(Ordering::Relaxed) {
+ 0 => line,
+ past => format!("{line} · {past} frames of the edit past the last picture"),
+ })
}
/// The outcome, once — taken out of the handle, so a caller that already
@@ -515,6 +541,7 @@ pub fn start(
finished: AtomicBool::new(false),
outcome: Mutex::new(None),
encoders: Mutex::new(None),
+ truncated: AtomicU32::new(0),
});
let worker = Arc::clone(&shared);
// A second handle to the same slot, held outside the caught body below --
@@ -621,6 +648,12 @@ pub fn start(
.or_else(|| payload.downcast_ref::().cloned())
.unwrap_or_else(|| "unknown panic".to_string());
if !panic_worker.finished.load(Ordering::Acquire) {
+ // ...and the `.part` the body left behind is deleted here: the
+ // module promises every failure path removes it, and the only
+ // path that did was the body's own `result.is_err()` arm, which
+ // a panic never reaches. Done inside this branch only -- a body
+ // that *did* settle has already renamed or deleted the file.
+ let _ = std::fs::remove_file(&part);
settle(&panic_worker, Err(format!("export worker panicked: {message}").into()));
}
}
@@ -807,22 +840,23 @@ fn video_label(format: Format, hw: bool) -> &'static str {
}
}
-/// The cheap half of "does this timeline's sound have to be re-encoded": what
-/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a
-/// copy; a speeded lane is resampled; an equalizer is sample math. The other
-/// half -- whether the sources can be copied out of at all -- costs a file open
-/// each and belongs to [`copy_audio`], which may re-encode where this says copy.
-fn forces_encode(project: &Project, ranged: bool) -> bool {
- let lanes: Vec<_> = project
- .audio_lanes()
- .into_iter()
- .filter(|&lane| !project.lane(lane).is_empty())
- .collect();
- // A ranged export needs an exact offset and an exact length, which a copy
- // of the source's own packets cannot give it ([`copy_audio`]) -- so a
- // range marked at all always encodes, whatever the lanes look like.
- ranged
- || lanes.len() > 1
+/// Whether the *edit* has touched the samples a copy would carry out: the one
+/// predicate both copy-or-encode decisions ask, with `lanes` the sound's own
+/// list as the caller has it -- every audio lane for the question a card asks
+/// before the button ([`forces_encode`]), and the single lane the segments have
+/// already narrowed a copy to ([`copy_audio`]).
+///
+/// One function and not two lists of the same conditions, which is what they
+/// were: `faded` reached [`forces_encode`] and not [`copy_audio`]'s gate, so an
+/// mp4 whose lane carried a fade wrote the source's own packets with the fade
+/// nowhere, while the card had promised a re-encode -- and the WAV, FLAC and
+/// MP3 exports of the same project applied it. Two gates that cannot be given
+/// two answers is the fix; the drift was the defect.
+fn sample_altered(project: &Project, lanes: &[Lane]) -> bool {
+ // Two lanes are a mix and a mix is not a copy; a speeded lane is resampled;
+ // an equalizer, a fade and the mix itself are gain math on decoded samples
+ // ([`equalized`], [`faded`], [`mastered`]). None of them is inside a packet.
+ lanes.len() > 1
|| lanes
.iter()
.any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
@@ -831,6 +865,18 @@ fn forces_encode(project: &Project, ranged: bool) -> bool {
|| faded(project)
}
+/// The cheap half of "does this timeline's sound have to be re-encoded": what
+/// the *edit* says, with no file opened ([`sample_altered`], asked of every
+/// audio lane). The other half -- whether the sources can be copied out of at
+/// all -- costs a file open each and belongs to [`copy_audio`], which may
+/// re-encode where this says copy.
+fn forces_encode(project: &Project, ranged: bool) -> bool {
+ // A ranged export needs an exact offset and an exact length, which a copy
+ // of the source's own packets cannot give it ([`copy_audio`]) -- so a
+ // range marked at all always encodes, whatever the lanes look like.
+ ranged || sample_altered(project, &project.audio_lanes())
+}
+
/// What the sound is written by. Every audio encoder here is software -- there
/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
/// whether a container escapes encoding altogether by copying the packets it was
@@ -1614,8 +1660,12 @@ fn copy_audio(
// ...and whether the mix itself does anything a packet never went through:
// a lane volume is applied at the sum and a limiter over it, so copying
// such a lane would write it at unity and unlimited, silently.
- let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
- if speeded || equalized(project) || mastered(project) {
+ // ...asked as the very predicate [`forces_encode`] is, over the one lane
+ // the segments came off, so what a card predicted and what this decides are
+ // one answer. `lane` here is that lane, and not `A1` by assumption:
+ // [`Project::audio_lanes`] is the list built for, and filtered by, these
+ // very segments.
+ if sample_altered(project, &[lane]) {
return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None);
}
// What is left is a copy the *sources* may still not be able to give: AAC
@@ -2963,6 +3013,16 @@ fn run(
}
};
let Some(frame) = picture else {
+ // The file ran out before its clip did, so the walk ends here
+ // and the rest of the edit never gets a picture. Counted, not
+ // swallowed: the bar reaches its end whatever happens, so
+ // without this a truncated file reads as a whole one. The same
+ // sentence `planned_subtitles` gives cues that hang past the
+ // last picture -- and this one is said after the fact, because
+ // how many pictures a *file* holds is only known by opening it.
+ shared
+ .truncated
+ .fetch_max(total.saturating_sub(done), Ordering::Relaxed);
break; // source ran out early; the clip list outlives the file
};
// A picture still on the GPU has nothing waiting for it here: the
@@ -3049,6 +3109,7 @@ fn run(
// mix that lands before it (a short film, or a slow first
// frame) has nothing to hand it to until now.
feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
+ inject_export_test_panic(out);
}
done += 1;
// Forwards only: an audio pass still running beside this one
@@ -3689,6 +3750,16 @@ impl Muxer {
}
}
+/// Test-only panic point, so the worker's own `catch_unwind` branch in
+/// [`start`] is reachable without a codec parser that actually panics: the
+/// variable names the one `.part` whose export dies, and no export but that
+/// one ever matches it, so a concurrent export in the same process is safe.
+fn inject_export_test_panic(out: &Path) {
+ if std::env::var_os("VE_EXPORT_TEST_PANIC").is_some_and(|target| target == out.as_os_str()) {
+ panic!("export test panic: the .part is on disk");
+ }
+}
+
/// Writes one access unit, creating the file on the first one -- the parameter
/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
/// the encoder has coded something. Units with no coded slice are skipped: a
@@ -4906,6 +4977,37 @@ mod tests {
use super::*;
+ /// The bar of a *feature film*: a picture count times a permille is a
+ /// product that has to be computed in `u64`, or a timeline past ~4.5 M
+ /// pictures (42 hours at 30 fps) overflowed the `u32` this used to be --
+ /// a panic in debug inside the export thread, and a bar that thrashed in
+ /// release. Every value here is a fraction of the whole, so none of them
+ /// may leave the scale, and the counts straddle the old overflow point.
+ #[test]
+ fn a_films_frame_count_does_not_overflow_the_bar() {
+ // The straddle, in the very product the old shape computed: `boundary`
+ // is the largest picture count whose `done * band` still fitted a
+ // `u32`, and one more is where it began to wrap -- a panic in debug,
+ // inside the export thread.
+ let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
+ let boundary = u64::from(u32::MAX) / band;
+ assert!(boundary * band <= u64::from(u32::MAX));
+ assert!((boundary + 1) * band > u64::from(u32::MAX));
+ for total in [boundary as u32 + 1, 21_600_000, u32::MAX] {
+ assert_eq!(picture_progress(total, total), PROGRESS_SCALE, "{total}");
+ assert_eq!(picture_progress(0, total), AUDIO_BAND, "{total}");
+ let half = picture_progress(total / 2, total);
+ assert!(
+ (AUDIO_BAND..PROGRESS_SCALE).contains(&half),
+ "half of {total} is {half}"
+ );
+ assert!(
+ picture_progress(total - 1, total) <= PROGRESS_SCALE,
+ "{total}"
+ );
+ }
+ }
+
/// How a decode thread ended is never guessed from the channel being shut.
/// A source that genuinely ran out says so, and the span ends on it; a
/// thread that died without a word is a failure, because reading it as end
diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs
index 8f915bc..f127d3c 100644
--- a/crates/engine/tests/export.rs
+++ b/crates/engine/tests/export.rs
@@ -29,16 +29,16 @@ use std::time::{Duration, Instant};
/// a cancel in one deletes what the other is asserting about. One at a time.
static PROXY_FILM: Mutex<()> = Mutex::new(());
+use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
+use ec_core::{Packet, TimeBase};
+use ec_h264::H264Decoder;
use engine::export::ExportSettings;
use engine::hw::HwEncoder;
-use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets};
+use engine::mux::{parameter_sets, AudioParams, Mp4Muxer, VideoParams};
use engine::project::{Lane, Source, Speed};
use engine::scale::FitPolicy;
use engine::scratch::Scratch;
use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation};
-use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
-use ec_core::{Packet, TimeBase};
-use ec_h264::H264Decoder;
const FPS: f64 = 30.0;
@@ -443,7 +443,13 @@ fn multi_source_round_trip(name: &str, limit: Duration) {
let out = out_path(name);
let started = Instant::now();
- let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default(), None);
+ let handle = engine::export::start(
+ project.clone(),
+ meta,
+ &out,
+ &ExportSettings::default(),
+ None,
+ );
wait(&handle, limit).expect("export");
println!(
"{name}: {total} frames of two sources in {:.2} s",
@@ -904,7 +910,11 @@ fn assert_no_single_stream_span_over(path: &Path, seconds: f64) {
(pos, stream, pts)
})
.collect();
- assert!(packets.len() > 10, "ffprobe saw only {} packets", packets.len());
+ assert!(
+ packets.len() > 10,
+ "ffprobe saw only {} packets",
+ packets.len()
+ );
packets.sort_by_key(|&(pos, ..)| pos);
let streams: std::collections::HashSet = packets.iter().map(|&(_, s, _)| s).collect();
@@ -988,14 +998,21 @@ fn mp4_audio_interleaves_with_the_picture() {
// A/V sync: the first audio sample starts at movie time zero either way --
// interleaving moves *where in the file* a packet sits, never what `stts`
// says it plays at.
- assert_eq!(first_pts(&out, "a"), 0.0, "first audio pts is media time zero");
+ assert_eq!(
+ first_pts(&out, "a"),
+ 0.0,
+ "first audio pts is media time zero"
+ );
assert_no_single_stream_span_over(&out, 2.0);
// Nothing else about the file moved: same duration, same sample counts,
// to within the packet the two sibling tests above already allow.
let (video_meta, _) = engine::demux::Demuxer::open(&out).unwrap();
- assert_eq!(video_meta.frame_count, 150, "video track unaffected by interleaving");
+ assert_eq!(
+ video_meta.frame_count, 150,
+ "video track unaffected by interleaving"
+ );
let (audio_meta, chunks) = engine::AudioSession::open(&out)
.unwrap()
.expect("export has an audio track");
@@ -1264,7 +1281,10 @@ fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() {
let again = engine::proxy::generate(&source).expect("ask again");
assert!(again.is_finished(), "a cached proxy is done on the spot");
assert_eq!(
- again.outcome().expect("cached outcome").expect("cached path"),
+ again
+ .outcome()
+ .expect("cached outcome")
+ .expect("cached path"),
out
);
assert_eq!(engine::proxy::cached(&source), Some(out.clone()));
@@ -1426,7 +1446,11 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
);
let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");
let syncs = engine::demux::sync_points(&made);
- println!("{} of {} frames are starting points", syncs.len(), meta.frame_count);
+ println!(
+ "{} of {} frames are starting points",
+ syncs.len(),
+ meta.frame_count
+ );
assert_eq!(
syncs.len() as u32,
meta.frame_count,
@@ -1440,7 +1464,11 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
// refused the stream, while this test stayed green. So decode it, all of
// it, and let an outside decoder say the same.
let frames = decode_all(&made);
- println!("decoded back {} of {} pictures", frames.len(), meta.frame_count);
+ println!(
+ "decoded back {} of {} pictures",
+ frames.len(),
+ meta.frame_count
+ );
assert_eq!(
frames.len() as u32,
meta.frame_count,
@@ -1533,7 +1561,10 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() {
"a cancelled proxy left {} behind",
out.display()
);
- assert!(!part_path(&out).exists(), "a cancelled proxy left its .part");
+ assert!(
+ !part_path(&out).exists(),
+ "a cancelled proxy left its .part"
+ );
assert_eq!(engine::proxy::cached(&film), None);
}
@@ -1578,7 +1609,9 @@ fn injected_with(
timeout_ms: Option<&str>,
body: impl FnOnce() -> T,
) -> T {
- let _exclusive = SEAT.write().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let _exclusive = SEAT
+ .write()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
let restore = std::env::var_os("VE_SW_ENC");
unsafe {
std::env::set_var("VE_SW", "1");
@@ -1961,3 +1994,163 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() {
);
});
}
+
+/// A whole-clip template on one source: the shape `exports_the_audio_stream_
+/// the_timeline_plays` builds, parameterised by the fade and the length the
+/// clip claims.
+fn one_source_clip(source: &Path, fade_in: u32, out_frame: u32) -> (Project, engine::VideoMeta) {
+ let (meta, _) = engine::demux::Demuxer::open(source).expect("open the fixture");
+ let whole = engine::Clip {
+ fade_in,
+ fade_out: 0,
+ transition_out: 0,
+ visualizer: 0,
+ viz_paint: 0,
+ start: 0,
+ in_frame: 0,
+ out_frame,
+ source: 0,
+ link: Some(0),
+ eq: None,
+ color: None,
+ transform: None,
+ fit: FitPolicy::default(),
+ speed: Speed::NORMAL,
+ };
+ let project = Project::from_parts(
+ vec![Source {
+ path: source.to_path_buf(),
+ audio_stream: 0,
+ }],
+ vec![
+ (engine::project::LaneKind::Video, vec![whole.clone()]),
+ (engine::project::LaneKind::Audio, vec![whole]),
+ ],
+ Vec::new(),
+ Vec::new(),
+ Vec::new(),
+ )
+ .expect("a one-source project");
+ (project, meta)
+}
+
+/// Interleaved-stereo RMS of `samples`.
+fn rms(samples: &[f32]) -> f64 {
+ let sum: f64 = samples
+ .chunks_exact(2)
+ .map(|c| f64::from(c[0]) * f64::from(c[0]) + f64::from(c[1]) * f64::from(c[1]))
+ .sum();
+ (sum / samples.len().max(1) as f64).sqrt()
+}
+
+/// D1: a fade is gain on decoded samples, which a packet copy cannot carry --
+/// so a clip with a fade must leave through the encode even where the rest of
+/// the timeline could copy, and the fade must reach the file: the head of the
+/// output ramps in by the fade's own dB, where a copy writes the source flat.
+#[test]
+fn a_faded_clip_encodes_and_the_fade_reaches_the_file() {
+ let _seat = pin_software();
+ let source = asset("test_multiaudio.mp4"); // flat -21 dB tone, 60 frames
+ let (project, meta) =
+ one_source_clip(&source, (FPS * 3.0 / 2.0) as u32, meta_frame_count(&source));
+ let out = out_path("faded");
+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
+ wait(&handle, Duration::from_secs(600)).expect("export");
+
+ let line = handle.encoders().expect("the seats were published");
+ assert!(
+ line.contains("ec-aac"),
+ "the sound left through the copy, not the encode: {line}"
+ );
+
+ let (audio, rx) = engine::AudioSession::open(&out)
+ .expect("reopen export audio")
+ .expect("the export has audio");
+ // Quarter of a second of interleaved stereo, and the fade-in is 1.5 s of
+ // an equal-power ramp ([`engine::project::Fade::gain_at`]'s `sin`), so the
+ // windows below sit deep in the ramp, either side of where it ends, and
+ // past it.
+ let quarter = audio.sample_rate as usize * 2 / 4;
+ let mut samples = Vec::new();
+ for chunk in rx {
+ samples.extend_from_slice(&chunk.samples);
+ }
+ let envelope: Vec = samples.chunks_exact(quarter).take(6).map(rms).collect();
+ let flat = rms(&samples[samples.len() - quarter..]);
+ assert!(
+ flat > 0.05,
+ "the fixture's own tone is not in the file at all: tail rms {flat}"
+ );
+ assert!(
+ envelope[0] < 0.4 * flat,
+ "the fade-in is absent -- a copy writes the source flat: {envelope:?} against {flat}"
+ );
+ assert!(
+ envelope[0] > 0.02 * flat,
+ "the head is silence, so what is missing is the sound, not the fade: {envelope:?}"
+ );
+ assert!(
+ envelope[..4].windows(2).all(|w| w[1] > w[0]),
+ "the level does not ramp through the fade's own 1.5 s: {envelope:?}"
+ );
+ assert!(
+ (envelope[4] - flat).abs() < 0.15 * flat && (envelope[5] - flat).abs() < 0.15 * flat,
+ "the ramp never reaches unity past the fade, so this is not it: {envelope:?} against {flat}"
+ );
+ std::fs::remove_file(&out).unwrap();
+}
+
+fn meta_frame_count(source: &Path) -> u32 {
+ engine::demux::Demuxer::open(source)
+ .expect("open the fixture")
+ .0
+ .frame_count
+}
+
+/// D4: a clip asking for more pictures than its file has used to end the span
+/// with no notice -- the export completed as if the whole edit were in the
+/// file. The seat line now carries the count.
+#[test]
+fn a_clip_that_outlives_its_source_says_so_on_the_card() {
+ let _seat = pin_software();
+ let source = asset("test_multiaudio.mp4"); // 60 frames
+ let count = meta_frame_count(&source);
+ let (project, meta) = one_source_clip(&source, 0, count + 40);
+ let out = out_path("truncated");
+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
+ wait(&handle, Duration::from_secs(600)).expect("export");
+ let line = handle.encoders().expect("the seats were published");
+ assert!(
+ line.contains("40 frames of the edit past the last picture"),
+ "the truncation is silent: {line}"
+ );
+ std::fs::remove_file(&out).unwrap();
+}
+
+/// D3: the catch_unwind branch settled the worker's slot but left the `.part`
+/// on disk, against the module promise that every error path deletes it. The
+/// panic is injected at the first coded picture, so the `.part` is provably
+/// on disk when the worker dies.
+#[test]
+fn a_panicking_worker_deletes_the_part_file() {
+ let _exclusive = SEAT.write().unwrap_or_else(|p| p.into_inner());
+ let source = asset("test_baseline.mp4");
+ let (project, meta) = short_edit(&source, 20);
+ let out = out_path("panic");
+ let part = part_path(&out);
+ unsafe {
+ std::env::set_var("VE_EXPORT_TEST_PANIC", part.as_os_str().to_owned());
+ }
+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
+ let result = wait(&handle, Duration::from_secs(120));
+ unsafe {
+ std::env::remove_var("VE_EXPORT_TEST_PANIC");
+ }
+ let error = result.expect_err("the injected panic is the outcome");
+ assert!(
+ error.to_string().contains("export worker panicked"),
+ "the panic is the outcome: {error}"
+ );
+ assert!(!out.exists(), "a panicked export wrote {}", out.display());
+ assert!(!part.exists(), "the .part outlived the panic");
+}