forge
Explore
Log in

Don't you dare go Hollow

Every sample-altering edit forces an encode, in one place

Browse files at this commit

24df84cd2ec34496be40fc196a1141fd2b935895Ahmet Kaan GümüşParent: 19dcc3e
  • fix
    • every sample-altering edit forces an encode, in one place
Show full message
🐛 fix(export): every sample-altering edit forces an encode, in one place

The copy-or-encode gate existed twice: `forces_encode`, which a card reads
before the button (`planned_seats`, `audio_label`), and the runtime gate inside
`copy_audio`, which decides what the file does. A fade was on the first and not
the second, so an mp4 whose lane carried a fade-in or fade-out 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.
Measured on a clip with a 1.5 s fade-in: the seat line read
`SW encode (ec-h264) · AAC copy` and the first quarter second of the file sat at
0.14 of its own tail level, against `ec-aac` and a rising ramp once both gates
ask the same question.

Both gates are now `sample_altered`, asked with the lane list each caller has --
every audio lane for the card's question, the one lane the segments came off for
the copy's -- so no condition can reach one of them and miss the other again.
The class was swept with it: `CopyPlan::of` is the picture's copy gate and names
its own sample-altering states (grade, transform, speed, rotation, rate, size,
colour, dissolve, gap, packing), and every one of them still falls back.

Three more on the same path.

`picture_progress` computed a picture count times a permille in `u32`, which
overflows past 4,520,913 pictures (42 hours at 30 fps): 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. Computed in `u64`,
which the straddle test pins at the boundary the old shape could not hold.

The `catch_unwind` branch in `start` never deleted `<out>.part`, though the
module promises every failure path does: the only cleanup was in the body's own
`result.is_err()` arm, which a panic never reaches, so a panicking export left a
half-written file beside the name it never took.

A source that ran out under its clip ended the span with no notice and the bar
reached its end anyway, so a truncated file read as a whole one. The frames that
never got a picture are now published on `Shared` and composed into
`ExportHandle::encoders`, where the card already renders the seat line --
composed at read time, because that line is published again on a rerun in
software behind a dead hardware seat.

Tests, all four of which fail on the pre-fix tree:
`a_faded_clip_encodes_and_the_fade_reaches_the_file` (the seat line says
`ec-aac`, and quarter-second RMS windows of the exported file rise through the
fade and reach unity past it), `a_films_frame_count_does_not_overflow_the_bar`,
`a_panicking_worker_deletes_the_part_file` (an env-gated panic point, so the
branch is reachable without a codec parser that really panics, and no export but
the one it names can match it), and
`a_clip_that_outlives_its_source_says_so_on_the_card`.

    cargo test -p engine --test export -- --test-threads=1
crates/engine/src/export.rsmodified+123 -21
@@ -106,7 +106,15 @@ pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;
106106 /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is
107107 /// left rather than starting again from zero.
108108 fn picture_progress(done: u32, total: u32) -> u32 {
109- AUDIO_BAND + done.min(total) * (PROGRESS_SCALE - AUDIO_BAND) / total.max(1)
109+ // In `u64`: this is a picture count times a permille, and a film past
110+ // ~4.5 M pictures (42 hours at 30 fps) overflowed the `u32` this used to be
111+ // computed in -- a panic in debug inside the export thread, which a caller
112+ // reads as `export worker panicked` on a file that was never written, and a
113+ // bar that thrashed in release. The result is under the scale by
114+ // construction, so the narrowing back is exact.
115+ let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
116+ let done = u64::from(done.min(total));
117+ AUDIO_BAND + (done * band / u64::from(total.max(1))) as u32
110118 }
111119
112120 /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
@@ -453,8 +461,17 @@ struct Shared {
453461 outcome: Mutex<Option<crate::Result<()>>>,
454462 /// The encoders this job really opened, published the moment they are
455463 /// chosen and never changed after -- one seat for the whole file, which is
456- /// what [`Enc`] states. `None` until then.
464+ /// what [`Enc`] states. `None` until then. The one thing that joins it
465+ /// afterwards is how much of the edit never got a picture
466+ /// ([`Shared::truncated`]), and [`ExportHandle::encoders`] does that
467+ /// joining, so a notice cannot land on the line twice.
457468 encoders: Mutex<Option<String>>,
469+ /// Timeline frames of the edit the walk could not write because a file ran
470+ /// out before its clip did ([`run`]'s break). The bar reaches its end
471+ /// whatever happens, so without this a truncated file reads as a whole one.
472+ /// Published the moment the walk gives up and read by
473+ /// [`ExportHandle::encoders`] beside the seat line.
474+ truncated: AtomicU32,
458475 }
459476
460477 /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
@@ -486,8 +503,17 @@ impl ExportHandle {
486503 /// What this export is encoding with -- the video seat and what the sound
487504 /// is doing -- as the worker chose them, hardware fallback included.
488505 /// `None` for the first instants of a job, before the encoder is open.
506+ ///
507+ /// ...and, where a file ran out under its clip, how much of the edit never
508+ /// got a picture. Composed here rather than written into the stored line,
509+ /// because that line is published more than once on a rerun (a hardware
510+ /// seat that died) and a notice appended at the write site lands twice.
489511 pub fn encoders(&self) -> Option<String> {
490- self.shared.encoders.lock().unwrap().clone()
512+ let line = self.shared.encoders.lock().unwrap().clone()?;
513+ Some(match self.shared.truncated.load(Ordering::Relaxed) {
514+ 0 => line,
515+ past => format!("{line} · {past} frames of the edit past the last picture"),
516+ })
491517 }
492518
493519 /// The outcome, once — taken out of the handle, so a caller that already
@@ -515,6 +541,7 @@ pub fn start(
515541 finished: AtomicBool::new(false),
516542 outcome: Mutex::new(None),
517543 encoders: Mutex::new(None),
544+ truncated: AtomicU32::new(0),
518545 });
519546 let worker = Arc::clone(&shared);
520547 // A second handle to the same slot, held outside the caught body below --
@@ -621,6 +648,12 @@ pub fn start(
621648 .or_else(|| payload.downcast_ref::<String>().cloned())
622649 .unwrap_or_else(|| "unknown panic".to_string());
623650 if !panic_worker.finished.load(Ordering::Acquire) {
651+ // ...and the `.part` the body left behind is deleted here: the
652+ // module promises every failure path removes it, and the only
653+ // path that did was the body's own `result.is_err()` arm, which
654+ // a panic never reaches. Done inside this branch only -- a body
655+ // that *did* settle has already renamed or deleted the file.
656+ let _ = std::fs::remove_file(&part);
624657 settle(&panic_worker, Err(format!("export worker panicked: {message}").into()));
625658 }
626659 }
@@ -807,22 +840,23 @@ fn video_label(format: Format, hw: bool) -> &'static str {
807840 }
808841 }
809842
810-/// The cheap half of "does this timeline's sound have to be re-encoded": what
811-/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a
812-/// copy; a speeded lane is resampled; an equalizer is sample math. The other
813-/// half -- whether the sources can be copied out of at all -- costs a file open
814-/// each and belongs to [`copy_audio`], which may re-encode where this says copy.
815-fn forces_encode(project: &Project, ranged: bool) -> bool {
816- let lanes: Vec<_> = project
817- .audio_lanes()
818- .into_iter()
819- .filter(|&lane| !project.lane(lane).is_empty())
820- .collect();
821- // A ranged export needs an exact offset and an exact length, which a copy
822- // of the source's own packets cannot give it ([`copy_audio`]) -- so a
823- // range marked at all always encodes, whatever the lanes look like.
824- ranged
825- || lanes.len() > 1
843+/// Whether the *edit* has touched the samples a copy would carry out: the one
844+/// predicate both copy-or-encode decisions ask, with `lanes` the sound's own
845+/// list as the caller has it -- every audio lane for the question a card asks
846+/// before the button ([`forces_encode`]), and the single lane the segments have
847+/// already narrowed a copy to ([`copy_audio`]).
848+///
849+/// One function and not two lists of the same conditions, which is what they
850+/// were: `faded` reached [`forces_encode`] and not [`copy_audio`]'s gate, so an
851+/// mp4 whose lane carried a fade wrote the source's own packets with the fade
852+/// nowhere, while the card had promised a re-encode -- and the WAV, FLAC and
853+/// MP3 exports of the same project applied it. Two gates that cannot be given
854+/// two answers is the fix; the drift was the defect.
855+fn sample_altered(project: &Project, lanes: &[Lane]) -> bool {
856+ // Two lanes are a mix and a mix is not a copy; a speeded lane is resampled;
857+ // an equalizer, a fade and the mix itself are gain math on decoded samples
858+ // ([`equalized`], [`faded`], [`mastered`]). None of them is inside a packet.
859+ lanes.len() > 1
826860 || lanes
827861 .iter()
828862 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
@@ -831,6 +865,18 @@ fn forces_encode(project: &Project, ranged: bool) -> bool {
831865 || faded(project)
832866 }
833867
868+/// The cheap half of "does this timeline's sound have to be re-encoded": what
869+/// the *edit* says, with no file opened ([`sample_altered`], asked of every
870+/// audio lane). The other half -- whether the sources can be copied out of at
871+/// all -- costs a file open each and belongs to [`copy_audio`], which may
872+/// re-encode where this says copy.
873+fn forces_encode(project: &Project, ranged: bool) -> bool {
874+ // A ranged export needs an exact offset and an exact length, which a copy
875+ // of the source's own packets cannot give it ([`copy_audio`]) -- so a
876+ // range marked at all always encodes, whatever the lanes look like.
877+ ranged || sample_altered(project, &project.audio_lanes())
878+}
879+
834880 /// What the sound is written by. Every audio encoder here is software -- there
835881 /// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
836882 /// whether a container escapes encoding altogether by copying the packets it was
@@ -1614,8 +1660,12 @@ fn copy_audio(
16141660 // ...and whether the mix itself does anything a packet never went through:
16151661 // a lane volume is applied at the sum and a limiter over it, so copying
16161662 // such a lane would write it at unity and unlimited, silently.
1617- let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
1618- if speeded || equalized(project) || mastered(project) {
1663+ // ...asked as the very predicate [`forces_encode`] is, over the one lane
1664+ // the segments came off, so what a card predicted and what this decides are
1665+ // one answer. `lane` here is that lane, and not `A1` by assumption:
1666+ // [`Project::audio_lanes`] is the list built for, and filtered by, these
1667+ // very segments.
1668+ if sample_altered(project, &[lane]) {
16191669 return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None);
16201670 }
16211671 // What is left is a copy the *sources* may still not be able to give: AAC
@@ -2963,6 +3013,16 @@ fn run(
29633013 }
29643014 };
29653015 let Some(frame) = picture else {
3016+ // The file ran out before its clip did, so the walk ends here
3017+ // and the rest of the edit never gets a picture. Counted, not
3018+ // swallowed: the bar reaches its end whatever happens, so
3019+ // without this a truncated file reads as a whole one. The same
3020+ // sentence `planned_subtitles` gives cues that hang past the
3021+ // last picture -- and this one is said after the fact, because
3022+ // how many pictures a *file* holds is only known by opening it.
3023+ shared
3024+ .truncated
3025+ .fetch_max(total.saturating_sub(done), Ordering::Relaxed);
29663026 break; // source ran out early; the clip list outlives the file
29673027 };
29683028 // A picture still on the GPU has nothing waiting for it here: the
@@ -3049,6 +3109,7 @@ fn run(
30493109 // mix that lands before it (a short film, or a slow first
30503110 // frame) has nothing to hand it to until now.
30513111 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
3112+ inject_export_test_panic(out);
30523113 }
30533114 done += 1;
30543115 // Forwards only: an audio pass still running beside this one
@@ -3689,6 +3750,16 @@ impl Muxer {
36893750 }
36903751 }
36913752
3753+/// Test-only panic point, so the worker's own `catch_unwind` branch in
3754+/// [`start`] is reachable without a codec parser that actually panics: the
3755+/// variable names the one `.part` whose export dies, and no export but that
3756+/// one ever matches it, so a concurrent export in the same process is safe.
3757+fn inject_export_test_panic(out: &Path) {
3758+ if std::env::var_os("VE_EXPORT_TEST_PANIC").is_some_and(|target| target == out.as_os_str()) {
3759+ panic!("export test panic: the .part is on disk");
3760+ }
3761+}
3762+
36923763 /// Writes one access unit, creating the file on the first one -- the parameter
36933764 /// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
36943765 /// the encoder has coded something. Units with no coded slice are skipped: a
@@ -4906,6 +4977,37 @@ mod tests {
49064977
49074978 use super::*;
49084979
4980+ /// The bar of a *feature film*: a picture count times a permille is a
4981+ /// product that has to be computed in `u64`, or a timeline past ~4.5 M
4982+ /// pictures (42 hours at 30 fps) overflowed the `u32` this used to be --
4983+ /// a panic in debug inside the export thread, and a bar that thrashed in
4984+ /// release. Every value here is a fraction of the whole, so none of them
4985+ /// may leave the scale, and the counts straddle the old overflow point.
4986+ #[test]
4987+ fn a_films_frame_count_does_not_overflow_the_bar() {
4988+ // The straddle, in the very product the old shape computed: `boundary`
4989+ // is the largest picture count whose `done * band` still fitted a
4990+ // `u32`, and one more is where it began to wrap -- a panic in debug,
4991+ // inside the export thread.
4992+ let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
4993+ let boundary = u64::from(u32::MAX) / band;
4994+ assert!(boundary * band <= u64::from(u32::MAX));
4995+ assert!((boundary + 1) * band > u64::from(u32::MAX));
4996+ for total in [boundary as u32 + 1, 21_600_000, u32::MAX] {
4997+ assert_eq!(picture_progress(total, total), PROGRESS_SCALE, "{total}");
4998+ assert_eq!(picture_progress(0, total), AUDIO_BAND, "{total}");
4999+ let half = picture_progress(total / 2, total);
5000+ assert!(
5001+ (AUDIO_BAND..PROGRESS_SCALE).contains(&half),
5002+ "half of {total} is {half}"
5003+ );
5004+ assert!(
5005+ picture_progress(total - 1, total) <= PROGRESS_SCALE,
5006+ "{total}"
5007+ );
5008+ }
5009+ }
5010+
49095011 /// How a decode thread ended is never guessed from the channel being shut.
49105012 /// A source that genuinely ran out says so, and the span ends on it; a
49115013 /// thread that died without a word is a failure, because reading it as end
crates/engine/tests/export.rsmodified+206 -13
@@ -29,16 +29,16 @@ use std::time::{Duration, Instant};
2929 /// a cancel in one deletes what the other is asserting about. One at a time.
3030 static PROXY_FILM: Mutex<()> = Mutex::new(());
3131
32+use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
33+use ec_core::{Packet, TimeBase};
34+use ec_h264::H264Decoder;
3235 use engine::export::ExportSettings;
3336 use engine::hw::HwEncoder;
34-use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets};
37+use engine::mux::{parameter_sets, AudioParams, Mp4Muxer, VideoParams};
3538 use engine::project::{Lane, Source, Speed};
3639 use engine::scale::FitPolicy;
3740 use engine::scratch::Scratch;
3841 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation};
39-use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
40-use ec_core::{Packet, TimeBase};
41-use ec_h264::H264Decoder;
4242
4343 const FPS: f64 = 30.0;
4444
@@ -443,7 +443,13 @@ fn multi_source_round_trip(name: &str, limit: Duration) {
443443 let out = out_path(name);
444444
445445 let started = Instant::now();
446- let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default(), None);
446+ let handle = engine::export::start(
447+ project.clone(),
448+ meta,
449+ &out,
450+ &ExportSettings::default(),
451+ None,
452+ );
447453 wait(&handle, limit).expect("export");
448454 println!(
449455 "{name}: {total} frames of two sources in {:.2} s",
@@ -904,7 +910,11 @@ fn assert_no_single_stream_span_over(path: &Path, seconds: f64) {
904910 (pos, stream, pts)
905911 })
906912 .collect();
907- assert!(packets.len() > 10, "ffprobe saw only {} packets", packets.len());
913+ assert!(
914+ packets.len() > 10,
915+ "ffprobe saw only {} packets",
916+ packets.len()
917+ );
908918 packets.sort_by_key(|&(pos, ..)| pos);
909919
910920 let streams: std::collections::HashSet<u32> = packets.iter().map(|&(_, s, _)| s).collect();
@@ -988,14 +998,21 @@ fn mp4_audio_interleaves_with_the_picture() {
988998 // A/V sync: the first audio sample starts at movie time zero either way --
989999 // interleaving moves *where in the file* a packet sits, never what `stts`
9901000 // says it plays at.
991- assert_eq!(first_pts(&out, "a"), 0.0, "first audio pts is media time zero");
1001+ assert_eq!(
1002+ first_pts(&out, "a"),
1003+ 0.0,
1004+ "first audio pts is media time zero"
1005+ );
9921006
9931007 assert_no_single_stream_span_over(&out, 2.0);
9941008
9951009 // Nothing else about the file moved: same duration, same sample counts,
9961010 // to within the packet the two sibling tests above already allow.
9971011 let (video_meta, _) = engine::demux::Demuxer::open(&out).unwrap();
998- assert_eq!(video_meta.frame_count, 150, "video track unaffected by interleaving");
1012+ assert_eq!(
1013+ video_meta.frame_count, 150,
1014+ "video track unaffected by interleaving"
1015+ );
9991016 let (audio_meta, chunks) = engine::AudioSession::open(&out)
10001017 .unwrap()
10011018 .expect("export has an audio track");
@@ -1264,7 +1281,10 @@ fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() {
12641281 let again = engine::proxy::generate(&source).expect("ask again");
12651282 assert!(again.is_finished(), "a cached proxy is done on the spot");
12661283 assert_eq!(
1267- again.outcome().expect("cached outcome").expect("cached path"),
1284+ again
1285+ .outcome()
1286+ .expect("cached outcome")
1287+ .expect("cached path"),
12681288 out
12691289 );
12701290 assert_eq!(engine::proxy::cached(&source), Some(out.clone()));
@@ -1426,7 +1446,11 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
14261446 );
14271447 let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");
14281448 let syncs = engine::demux::sync_points(&made);
1429- println!("{} of {} frames are starting points", syncs.len(), meta.frame_count);
1449+ println!(
1450+ "{} of {} frames are starting points",
1451+ syncs.len(),
1452+ meta.frame_count
1453+ );
14301454 assert_eq!(
14311455 syncs.len() as u32,
14321456 meta.frame_count,
@@ -1440,7 +1464,11 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
14401464 // refused the stream, while this test stayed green. So decode it, all of
14411465 // it, and let an outside decoder say the same.
14421466 let frames = decode_all(&made);
1443- println!("decoded back {} of {} pictures", frames.len(), meta.frame_count);
1467+ println!(
1468+ "decoded back {} of {} pictures",
1469+ frames.len(),
1470+ meta.frame_count
1471+ );
14441472 assert_eq!(
14451473 frames.len() as u32,
14461474 meta.frame_count,
@@ -1533,7 +1561,10 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() {
15331561 "a cancelled proxy left {} behind",
15341562 out.display()
15351563 );
1536- assert!(!part_path(&out).exists(), "a cancelled proxy left its .part");
1564+ assert!(
1565+ !part_path(&out).exists(),
1566+ "a cancelled proxy left its .part"
1567+ );
15371568 assert_eq!(engine::proxy::cached(&film), None);
15381569 }
15391570
@@ -1578,7 +1609,9 @@ fn injected_with<T>(
15781609 timeout_ms: Option<&str>,
15791610 body: impl FnOnce() -> T,
15801611 ) -> T {
1581- let _exclusive = SEAT.write().unwrap_or_else(|poisoned| poisoned.into_inner());
1612+ let _exclusive = SEAT
1613+ .write()
1614+ .unwrap_or_else(|poisoned| poisoned.into_inner());
15821615 let restore = std::env::var_os("VE_SW_ENC");
15831616 unsafe {
15841617 std::env::set_var("VE_SW", "1");
@@ -1961,3 +1994,163 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() {
19611994 );
19621995 });
19631996 }
1997+
1998+/// A whole-clip template on one source: the shape `exports_the_audio_stream_
1999+/// the_timeline_plays` builds, parameterised by the fade and the length the
2000+/// clip claims.
2001+fn one_source_clip(source: &Path, fade_in: u32, out_frame: u32) -> (Project, engine::VideoMeta) {
2002+ let (meta, _) = engine::demux::Demuxer::open(source).expect("open the fixture");
2003+ let whole = engine::Clip {
2004+ fade_in,
2005+ fade_out: 0,
2006+ transition_out: 0,
2007+ visualizer: 0,
2008+ viz_paint: 0,
2009+ start: 0,
2010+ in_frame: 0,
2011+ out_frame,
2012+ source: 0,
2013+ link: Some(0),
2014+ eq: None,
2015+ color: None,
2016+ transform: None,
2017+ fit: FitPolicy::default(),
2018+ speed: Speed::NORMAL,
2019+ };
2020+ let project = Project::from_parts(
2021+ vec![Source {
2022+ path: source.to_path_buf(),
2023+ audio_stream: 0,
2024+ }],
2025+ vec![
2026+ (engine::project::LaneKind::Video, vec![whole.clone()]),
2027+ (engine::project::LaneKind::Audio, vec![whole]),
2028+ ],
2029+ Vec::new(),
2030+ Vec::new(),
2031+ Vec::new(),
2032+ )
2033+ .expect("a one-source project");
2034+ (project, meta)
2035+}
2036+
2037+/// Interleaved-stereo RMS of `samples`.
2038+fn rms(samples: &[f32]) -> f64 {
2039+ let sum: f64 = samples
2040+ .chunks_exact(2)
2041+ .map(|c| f64::from(c[0]) * f64::from(c[0]) + f64::from(c[1]) * f64::from(c[1]))
2042+ .sum();
2043+ (sum / samples.len().max(1) as f64).sqrt()
2044+}
2045+
2046+/// D1: a fade is gain on decoded samples, which a packet copy cannot carry --
2047+/// so a clip with a fade must leave through the encode even where the rest of
2048+/// the timeline could copy, and the fade must reach the file: the head of the
2049+/// output ramps in by the fade's own dB, where a copy writes the source flat.
2050+#[test]
2051+fn a_faded_clip_encodes_and_the_fade_reaches_the_file() {
2052+ let _seat = pin_software();
2053+ let source = asset("test_multiaudio.mp4"); // flat -21 dB tone, 60 frames
2054+ let (project, meta) =
2055+ one_source_clip(&source, (FPS * 3.0 / 2.0) as u32, meta_frame_count(&source));
2056+ let out = out_path("faded");
2057+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2058+ wait(&handle, Duration::from_secs(600)).expect("export");
2059+
2060+ let line = handle.encoders().expect("the seats were published");
2061+ assert!(
2062+ line.contains("ec-aac"),
2063+ "the sound left through the copy, not the encode: {line}"
2064+ );
2065+
2066+ let (audio, rx) = engine::AudioSession::open(&out)
2067+ .expect("reopen export audio")
2068+ .expect("the export has audio");
2069+ // Quarter of a second of interleaved stereo, and the fade-in is 1.5 s of
2070+ // an equal-power ramp ([`engine::project::Fade::gain_at`]'s `sin`), so the
2071+ // windows below sit deep in the ramp, either side of where it ends, and
2072+ // past it.
2073+ let quarter = audio.sample_rate as usize * 2 / 4;
2074+ let mut samples = Vec::new();
2075+ for chunk in rx {
2076+ samples.extend_from_slice(&chunk.samples);
2077+ }
2078+ let envelope: Vec<f64> = samples.chunks_exact(quarter).take(6).map(rms).collect();
2079+ let flat = rms(&samples[samples.len() - quarter..]);
2080+ assert!(
2081+ flat > 0.05,
2082+ "the fixture's own tone is not in the file at all: tail rms {flat}"
2083+ );
2084+ assert!(
2085+ envelope[0] < 0.4 * flat,
2086+ "the fade-in is absent -- a copy writes the source flat: {envelope:?} against {flat}"
2087+ );
2088+ assert!(
2089+ envelope[0] > 0.02 * flat,
2090+ "the head is silence, so what is missing is the sound, not the fade: {envelope:?}"
2091+ );
2092+ assert!(
2093+ envelope[..4].windows(2).all(|w| w[1] > w[0]),
2094+ "the level does not ramp through the fade's own 1.5 s: {envelope:?}"
2095+ );
2096+ assert!(
2097+ (envelope[4] - flat).abs() < 0.15 * flat && (envelope[5] - flat).abs() < 0.15 * flat,
2098+ "the ramp never reaches unity past the fade, so this is not it: {envelope:?} against {flat}"
2099+ );
2100+ std::fs::remove_file(&out).unwrap();
2101+}
2102+
2103+fn meta_frame_count(source: &Path) -> u32 {
2104+ engine::demux::Demuxer::open(source)
2105+ .expect("open the fixture")
2106+ .0
2107+ .frame_count
2108+}
2109+
2110+/// D4: a clip asking for more pictures than its file has used to end the span
2111+/// with no notice -- the export completed as if the whole edit were in the
2112+/// file. The seat line now carries the count.
2113+#[test]
2114+fn a_clip_that_outlives_its_source_says_so_on_the_card() {
2115+ let _seat = pin_software();
2116+ let source = asset("test_multiaudio.mp4"); // 60 frames
2117+ let count = meta_frame_count(&source);
2118+ let (project, meta) = one_source_clip(&source, 0, count + 40);
2119+ let out = out_path("truncated");
2120+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2121+ wait(&handle, Duration::from_secs(600)).expect("export");
2122+ let line = handle.encoders().expect("the seats were published");
2123+ assert!(
2124+ line.contains("40 frames of the edit past the last picture"),
2125+ "the truncation is silent: {line}"
2126+ );
2127+ std::fs::remove_file(&out).unwrap();
2128+}
2129+
2130+/// D3: the catch_unwind branch settled the worker's slot but left the `.part`
2131+/// on disk, against the module promise that every error path deletes it. The
2132+/// panic is injected at the first coded picture, so the `.part` is provably
2133+/// on disk when the worker dies.
2134+#[test]
2135+fn a_panicking_worker_deletes_the_part_file() {
2136+ let _exclusive = SEAT.write().unwrap_or_else(|p| p.into_inner());
2137+ let source = asset("test_baseline.mp4");
2138+ let (project, meta) = short_edit(&source, 20);
2139+ let out = out_path("panic");
2140+ let part = part_path(&out);
2141+ unsafe {
2142+ std::env::set_var("VE_EXPORT_TEST_PANIC", part.as_os_str().to_owned());
2143+ }
2144+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2145+ let result = wait(&handle, Duration::from_secs(120));
2146+ unsafe {
2147+ std::env::remove_var("VE_EXPORT_TEST_PANIC");
2148+ }
2149+ let error = result.expect_err("the injected panic is the outcome");
2150+ assert!(
2151+ error.to_string().contains("export worker panicked"),
2152+ "the panic is the outcome: {error}"
2153+ );
2154+ assert!(!out.exists(), "a panicked export wrote {}", out.display());
2155+ assert!(!part.exists(), "the .part outlived the panic");
2156+}