forge
Explore
Log in

Don't you dare go Hollow

Merge the export lane into main

Browse files at this commit

c76e6c539963068833d17de72fcc86a1155ef7edAhmet Kaan GümüşParent: 9e8397dce7b65f
  • fix
    • merge the export lane into main
Show full message
🐛 fix(export): merge the export lane into main

Every sample-altering edit forces an encode in one place, and the
truncation notice counts what a file could not give. Lane:
lane-bughunt-export.
crates/engine/src/export.rsmodified+136 -21
@@ -106,7 +106,15 @@ pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;
106 /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is106 /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is
107 /// left rather than starting again from zero.107 /// left rather than starting again from zero.
108 fn picture_progress(done: u32, total: u32) -> u32 {108 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
110 }118 }
111 119
112 /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands120 /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
@@ -453,8 +461,17 @@ struct Shared {
453 outcome: Mutex<Option<crate::Result<()>>>,461 outcome: Mutex<Option<crate::Result<()>>>,
454 /// The encoders this job really opened, published the moment they are462 /// The encoders this job really opened, published the moment they are
455 /// chosen and never changed after -- one seat for the whole file, which is463 /// 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.
457 encoders: Mutex<Option<String>>,468 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,
458 }475 }
459 476
460 /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per477 /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
@@ -486,8 +503,17 @@ impl ExportHandle {
486 /// What this export is encoding with -- the video seat and what the sound503 /// What this export is encoding with -- the video seat and what the sound
487 /// is doing -- as the worker chose them, hardware fallback included.504 /// is doing -- as the worker chose them, hardware fallback included.
488 /// `None` for the first instants of a job, before the encoder is open.505 /// `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.
489 pub fn encoders(&self) -> Option<String> {511 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+ })
491 }517 }
492 518
493 /// The outcome, once — taken out of the handle, so a caller that already519 /// The outcome, once — taken out of the handle, so a caller that already
@@ -515,6 +541,7 @@ pub fn start(
515 finished: AtomicBool::new(false),541 finished: AtomicBool::new(false),
516 outcome: Mutex::new(None),542 outcome: Mutex::new(None),
517 encoders: Mutex::new(None),543 encoders: Mutex::new(None),
544+ truncated: AtomicU32::new(0),
518 });545 });
519 let worker = Arc::clone(&shared);546 let worker = Arc::clone(&shared);
520 // A second handle to the same slot, held outside the caught body below --547 // A second handle to the same slot, held outside the caught body below --
@@ -621,6 +648,12 @@ pub fn start(
621 .or_else(|| payload.downcast_ref::<String>().cloned())648 .or_else(|| payload.downcast_ref::<String>().cloned())
622 .unwrap_or_else(|| "unknown panic".to_string());649 .unwrap_or_else(|| "unknown panic".to_string());
623 if !panic_worker.finished.load(Ordering::Acquire) {650 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);
624 settle(&panic_worker, Err(format!("export worker panicked: {message}").into()));657 settle(&panic_worker, Err(format!("export worker panicked: {message}").into()));
625 }658 }
626 }659 }
@@ -807,22 +840,23 @@ fn video_label(format: Format, hw: bool) -> &'static str {
807 }840 }
808 }841 }
809 842
810-/// The cheap half of "does this timeline's sound have to be re-encoded": what843+/// Whether the *edit* has touched the samples a copy would carry out: the one
811-/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a844+/// predicate both copy-or-encode decisions ask, with `lanes` the sound's own
812-/// copy; a speeded lane is resampled; an equalizer is sample math. The other845+/// list as the caller has it -- every audio lane for the question a card asks
813-/// half -- whether the sources can be copied out of at all -- costs a file open846+/// before the button ([`forces_encode`]), and the single lane the segments have
814-/// each and belongs to [`copy_audio`], which may re-encode where this says copy.847+/// already narrowed a copy to ([`copy_audio`]).
815-fn forces_encode(project: &Project, ranged: bool) -> bool {848+///
816- let lanes: Vec<_> = project849+/// One function and not two lists of the same conditions, which is what they
817- .audio_lanes()850+/// were: `faded` reached [`forces_encode`] and not [`copy_audio`]'s gate, so an
818- .into_iter()851+/// mp4 whose lane carried a fade wrote the source's own packets with the fade
819- .filter(|&lane| !project.lane(lane).is_empty())852+/// nowhere, while the card had promised a re-encode -- and the WAV, FLAC and
820- .collect();853+/// MP3 exports of the same project applied it. Two gates that cannot be given
821- // A ranged export needs an exact offset and an exact length, which a copy854+/// two answers is the fix; the drift was the defect.
822- // of the source's own packets cannot give it ([`copy_audio`]) -- so a855+fn sample_altered(project: &Project, lanes: &[Lane]) -> bool {
823- // range marked at all always encodes, whatever the lanes look like.856+ // Two lanes are a mix and a mix is not a copy; a speeded lane is resampled;
824- ranged857+ // an equalizer, a fade and the mix itself are gain math on decoded samples
825- || lanes.len() > 1858+ // ([`equalized`], [`faded`], [`mastered`]). None of them is inside a packet.
859+ lanes.len() > 1
826 || lanes860 || lanes
827 .iter()861 .iter()
828 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))862 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
@@ -831,6 +865,18 @@ fn forces_encode(project: &Project, ranged: bool) -> bool {
831 || faded(project)865 || faded(project)
832 }866 }
833 867
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+
834 /// What the sound is written by. Every audio encoder here is software -- there880 /// What the sound is written by. Every audio encoder here is software -- there
835 /// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and881 /// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
836 /// whether a container escapes encoding altogether by copying the packets it was882 /// whether a container escapes encoding altogether by copying the packets it was
@@ -1614,8 +1660,12 @@ fn copy_audio(
1614 // ...and whether the mix itself does anything a packet never went through:1660 // ...and whether the mix itself does anything a packet never went through:
1615 // a lane volume is applied at the sum and a limiter over it, so copying1661 // a lane volume is applied at the sum and a limiter over it, so copying
1616 // such a lane would write it at unity and unlimited, silently.1662 // such a lane would write it at unity and unlimited, silently.
1617- let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());1663+ // ...asked as the very predicate [`forces_encode`] is, over the one lane
1618- if speeded || equalized(project) || mastered(project) {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]) {
1619 return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None);1669 return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None);
1620 }1670 }
1621 // What is left is a copy the *sources* may still not be able to give: AAC1671 // What is left is a copy the *sources* may still not be able to give: AAC
@@ -2734,6 +2784,9 @@ fn run(
2734 let mut audio_fed = false;2784 let mut audio_fed = false;
2735 let mut muxer = None;2785 let mut muxer = None;
2736 let mut done = 0u32;2786 let mut done = 0u32;
2787+ // ...and how many of the edit's frames a file could not give, summed over
2788+ // the spans that ran out under their clip ([`Shared::truncated`]).
2789+ let mut skipped = 0u32;
2737 let black = Black::new(meta);2790 let black = Black::new(meta);
2738 // Spans, not clips: a gap in the video is part of the timeline and gets2791 // Spans, not clips: a gap in the video is part of the timeline and gets
2739 // encoded too, as black frames. The picture count is therefore2792 // encoded too, as black frames. The picture count is therefore
@@ -2963,6 +3016,20 @@ fn run(
2963 }3016 }
2964 };3017 };
2965 let Some(frame) = picture else {3018 let Some(frame) = picture else {
3019+ // The file ran out before its clip did: this span's tail never
3020+ // gets a picture -- and *only* this span's tail, because the
3021+ // span loop this break sits in carries on with the spans after
3022+ // it and writes every picture they have. Counted, not
3023+ // swallowed: the bar reaches its end whatever happens, so
3024+ // without this a truncated file reads as a whole one. The same
3025+ // sentence `planned_subtitles` gives cues that hang past the
3026+ // last picture, said after the fact here because how many
3027+ // pictures a *file* holds is only known by opening it.
3028+ //
3029+ // `span.len > done_here` holds by the loop's own condition, and
3030+ // the sum over every break is exactly `total - done` at the end
3031+ // of the walk: the spans are disjoint and cover the whole edit.
3032+ skipped += span.len - done_here;
2966 break; // source ran out early; the clip list outlives the file3033 break; // source ran out early; the clip list outlives the file
2967 };3034 };
2968 // A picture still on the GPU has nothing waiting for it here: the3035 // A picture still on the GPU has nothing waiting for it here: the
@@ -3049,6 +3116,7 @@ fn run(
3049 // mix that lands before it (a short film, or a slow first3116 // mix that lands before it (a short film, or a slow first
3050 // frame) has nothing to hand it to until now.3117 // frame) has nothing to hand it to until now.
3051 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;3118 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
3119+ inject_export_test_panic(out);
3052 }3120 }
3053 done += 1;3121 done += 1;
3054 // Forwards only: an audio pass still running beside this one3122 // Forwards only: an audio pass still running beside this one
@@ -3062,6 +3130,12 @@ fn run(
3062 done_here += repeats;3130 done_here += repeats;
3063 }3131 }
3064 }3132 }
3133+ // The whole walk is over, so what it could not write is known to the frame
3134+ // and is published once. `fetch_max` and not `fetch_add`, because a
3135+ // hardware seat that died has the *whole* walk run again from its first
3136+ // frame ([`start`]): the same project and the same picture counts, so a
3137+ // second run must not double a number that is already on the line.
3138+ shared.truncated.fetch_max(skipped, Ordering::Relaxed);
3065 while let Some((au, key)) = encoder.drain()? {3139 while let Some((au, key)) = encoder.drain()? {
3066 write_video(3140 write_video(
3067 &mut muxer,3141 &mut muxer,
@@ -3689,6 +3763,16 @@ impl Muxer {
3689 }3763 }
3690 }3764 }
3691 3765
3766+/// Test-only panic point, so the worker's own `catch_unwind` branch in
3767+/// [`start`] is reachable without a codec parser that actually panics: the
3768+/// variable names the one `.part` whose export dies, and no export but that
3769+/// one ever matches it, so a concurrent export in the same process is safe.
3770+fn inject_export_test_panic(out: &Path) {
3771+ if std::env::var_os("VE_EXPORT_TEST_PANIC").is_some_and(|target| target == out.as_os_str()) {
3772+ panic!("export test panic: the .part is on disk");
3773+ }
3774+}
3775+
3692 /// Writes one access unit, creating the file on the first one -- the parameter3776 /// Writes one access unit, creating the file on the first one -- the parameter
3693 /// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once3777 /// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
3694 /// the encoder has coded something. Units with no coded slice are skipped: a3778 /// the encoder has coded something. Units with no coded slice are skipped: a
@@ -4906,6 +4990,37 @@ mod tests {
4906 4990
4907 use super::*;4991 use super::*;
4908 4992
4993+ /// The bar of a *feature film*: a picture count times a permille is a
4994+ /// product that has to be computed in `u64`, or a timeline past ~4.5 M
4995+ /// pictures (42 hours at 30 fps) overflowed the `u32` this used to be --
4996+ /// a panic in debug inside the export thread, and a bar that thrashed in
4997+ /// release. Every value here is a fraction of the whole, so none of them
4998+ /// may leave the scale, and the counts straddle the old overflow point.
4999+ #[test]
5000+ fn a_films_frame_count_does_not_overflow_the_bar() {
5001+ // The straddle, in the very product the old shape computed: `boundary`
5002+ // is the largest picture count whose `done * band` still fitted a
5003+ // `u32`, and one more is where it began to wrap -- a panic in debug,
5004+ // inside the export thread.
5005+ let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
5006+ let boundary = u64::from(u32::MAX) / band;
5007+ assert!(boundary * band <= u64::from(u32::MAX));
5008+ assert!((boundary + 1) * band > u64::from(u32::MAX));
5009+ for total in [boundary as u32 + 1, 21_600_000, u32::MAX] {
5010+ assert_eq!(picture_progress(total, total), PROGRESS_SCALE, "{total}");
5011+ assert_eq!(picture_progress(0, total), AUDIO_BAND, "{total}");
5012+ let half = picture_progress(total / 2, total);
5013+ assert!(
5014+ (AUDIO_BAND..PROGRESS_SCALE).contains(&half),
5015+ "half of {total} is {half}"
5016+ );
5017+ assert!(
5018+ picture_progress(total - 1, total) <= PROGRESS_SCALE,
5019+ "{total}"
5020+ );
5021+ }
5022+ }
5023+
4909 /// How a decode thread ended is never guessed from the channel being shut.5024 /// How a decode thread ended is never guessed from the channel being shut.
4910 /// A source that genuinely ran out says so, and the span ends on it; a5025 /// A source that genuinely ran out says so, and the span ends on it; a
4911 /// thread that died without a word is a failure, because reading it as end5026 /// thread that died without a word is a failure, because reading it as end
crates/engine/tests/export.rsmodified+303 -13
@@ -29,16 +29,16 @@ use std::time::{Duration, Instant};
29 /// a cancel in one deletes what the other is asserting about. One at a time.29 /// a cancel in one deletes what the other is asserting about. One at a time.
30 static PROXY_FILM: Mutex<()> = Mutex::new(());30 static PROXY_FILM: Mutex<()> = Mutex::new(());
31 31
32+use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
33+use ec_core::{Packet, TimeBase};
34+use ec_h264::H264Decoder;
32 use engine::export::ExportSettings;35 use engine::export::ExportSettings;
33 use engine::hw::HwEncoder;36 use engine::hw::HwEncoder;
34-use engine::mux::{AudioParams, Mp4Muxer, VideoParams, parameter_sets};37+use engine::mux::{parameter_sets, AudioParams, Mp4Muxer, VideoParams};
35 use engine::project::{Lane, Source, Speed};38 use engine::project::{Lane, Source, Speed};
36 use engine::scale::FitPolicy;39 use engine::scale::FitPolicy;
37 use engine::scratch::Scratch;40 use engine::scratch::Scratch;
38 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation};41 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;
42 42
43 const FPS: f64 = 30.0;43 const FPS: f64 = 30.0;
44 44
@@ -443,7 +443,13 @@ fn multi_source_round_trip(name: &str, limit: Duration) {
443 let out = out_path(name);443 let out = out_path(name);
444 444
445 let started = Instant::now();445 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+ );
447 wait(&handle, limit).expect("export");453 wait(&handle, limit).expect("export");
448 println!(454 println!(
449 "{name}: {total} frames of two sources in {:.2} s",455 "{name}: {total} frames of two sources in {:.2} s",
@@ -904,7 +910,11 @@ fn assert_no_single_stream_span_over(path: &Path, seconds: f64) {
904 (pos, stream, pts)910 (pos, stream, pts)
905 })911 })
906 .collect();912 .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+ );
908 packets.sort_by_key(|&(pos, ..)| pos);918 packets.sort_by_key(|&(pos, ..)| pos);
909 919
910 let streams: std::collections::HashSet<u32> = packets.iter().map(|&(_, s, _)| s).collect();920 let streams: std::collections::HashSet<u32> = packets.iter().map(|&(_, s, _)| s).collect();
@@ -988,14 +998,21 @@ fn mp4_audio_interleaves_with_the_picture() {
988 // A/V sync: the first audio sample starts at movie time zero either way --998 // A/V sync: the first audio sample starts at movie time zero either way --
989 // interleaving moves *where in the file* a packet sits, never what `stts`999 // interleaving moves *where in the file* a packet sits, never what `stts`
990 // says it plays at.1000 // 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+ );
992 1006
993 assert_no_single_stream_span_over(&out, 2.0);1007 assert_no_single_stream_span_over(&out, 2.0);
994 1008
995 // Nothing else about the file moved: same duration, same sample counts,1009 // Nothing else about the file moved: same duration, same sample counts,
996 // to within the packet the two sibling tests above already allow.1010 // to within the packet the two sibling tests above already allow.
997 let (video_meta, _) = engine::demux::Demuxer::open(&out).unwrap();1011 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+ );
999 let (audio_meta, chunks) = engine::AudioSession::open(&out)1016 let (audio_meta, chunks) = engine::AudioSession::open(&out)
1000 .unwrap()1017 .unwrap()
1001 .expect("export has an audio track");1018 .expect("export has an audio track");
@@ -1264,7 +1281,10 @@ fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() {
1264 let again = engine::proxy::generate(&source).expect("ask again");1281 let again = engine::proxy::generate(&source).expect("ask again");
1265 assert!(again.is_finished(), "a cached proxy is done on the spot");1282 assert!(again.is_finished(), "a cached proxy is done on the spot");
1266 assert_eq!(1283 assert_eq!(
1267- again.outcome().expect("cached outcome").expect("cached path"),1284+ again
1285+ .outcome()
1286+ .expect("cached outcome")
1287+ .expect("cached path"),
1268 out1288 out
1269 );1289 );
1270 assert_eq!(engine::proxy::cached(&source), Some(out.clone()));1290 assert_eq!(engine::proxy::cached(&source), Some(out.clone()));
@@ -1426,7 +1446,11 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
1426 );1446 );
1427 let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");1447 let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");
1428 let syncs = engine::demux::sync_points(&made);1448 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+ );
1430 assert_eq!(1454 assert_eq!(
1431 syncs.len() as u32,1455 syncs.len() as u32,
1432 meta.frame_count,1456 meta.frame_count,
@@ -1440,7 +1464,11 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
1440 // refused the stream, while this test stayed green. So decode it, all of1464 // refused the stream, while this test stayed green. So decode it, all of
1441 // it, and let an outside decoder say the same.1465 // it, and let an outside decoder say the same.
1442 let frames = decode_all(&made);1466 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+ );
1444 assert_eq!(1472 assert_eq!(
1445 frames.len() as u32,1473 frames.len() as u32,
1446 meta.frame_count,1474 meta.frame_count,
@@ -1533,7 +1561,10 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() {
1533 "a cancelled proxy left {} behind",1561 "a cancelled proxy left {} behind",
1534 out.display()1562 out.display()
1535 );1563 );
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+ );
1537 assert_eq!(engine::proxy::cached(&film), None);1568 assert_eq!(engine::proxy::cached(&film), None);
1538 }1569 }
1539 1570
@@ -1578,7 +1609,9 @@ fn injected_with<T>(
1578 timeout_ms: Option<&str>,1609 timeout_ms: Option<&str>,
1579 body: impl FnOnce() -> T,1610 body: impl FnOnce() -> T,
1580 ) -> T {1611 ) -> 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());
1582 let restore = std::env::var_os("VE_SW_ENC");1615 let restore = std::env::var_os("VE_SW_ENC");
1583 unsafe {1616 unsafe {
1584 std::env::set_var("VE_SW", "1");1617 std::env::set_var("VE_SW", "1");
@@ -1961,3 +1994,260 @@ fn a_dead_encoder_answers_every_later_call_the_same_way() {
1961 );1994 );
1962 });1995 });
1963 }1996 }
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+/// Two whole-clip spans of one source, both lanes: an edit whose first take is
2131+/// short and whose second one is whole. Both clips read the file from its own
2132+/// first frame, so the walk keeps two spans rather than fusing them into one
2133+/// window -- a span is continued only where the source window continues.
2134+fn two_clip_edit(source: &Path, first: u32, second: u32) -> (Project, engine::VideoMeta) {
2135+ let (meta, _) = engine::demux::Demuxer::open(source).expect("open the fixture");
2136+ let clip = |start: u32, out_frame: u32| engine::Clip {
2137+ fade_in: 0,
2138+ fade_out: 0,
2139+ transition_out: 0,
2140+ visualizer: 0,
2141+ viz_paint: 0,
2142+ start,
2143+ in_frame: 0,
2144+ out_frame,
2145+ source: 0,
2146+ link: None,
2147+ eq: None,
2148+ color: None,
2149+ transform: None,
2150+ fit: FitPolicy::default(),
2151+ speed: Speed::NORMAL,
2152+ };
2153+ let clips = vec![clip(0, first), clip(first, second)];
2154+ let project = Project::from_parts(
2155+ vec![Source {
2156+ path: source.to_path_buf(),
2157+ audio_stream: 0,
2158+ }],
2159+ vec![
2160+ (engine::project::LaneKind::Video, clips.clone()),
2161+ (engine::project::LaneKind::Audio, clips),
2162+ ],
2163+ Vec::new(),
2164+ Vec::new(),
2165+ Vec::new(),
2166+ )
2167+ .expect("a two-clip project");
2168+ (project, meta)
2169+}
2170+
2171+/// D4, the half the single-clip test cannot see: the walk carries on with the
2172+/// spans *after* a file runs out, so what went missing is that span's own tail
2173+/// and not everything the edit still had. Counting the rest would put 100 on
2174+/// the line for a file that holds 120 of the edit's 160 pictures.
2175+#[test]
2176+fn a_two_clip_timeline_reports_only_the_pictures_that_were_skipped() {
2177+ let _seat = pin_software();
2178+ let source = asset("test_multiaudio.mp4"); // 60 frames
2179+ let count = meta_frame_count(&source);
2180+ // The first take asks for 40 pictures the file has not got; the second one
2181+ // is whole and is written after the break.
2182+ let (project, meta) = two_clip_edit(&source, count + 40, count);
2183+ let out = out_path("truncated_two_clip");
2184+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2185+ wait(&handle, Duration::from_secs(900)).expect("export");
2186+ let line = handle.encoders().expect("the seats were published");
2187+ assert!(
2188+ line.contains("40 frames of the edit past the last picture"),
2189+ "the notice counts more than the file lost: {line}"
2190+ );
2191+ // ...and the file really holds both spans' pictures, which is what makes
2192+ // this the count of a tail and not of the whole rest of the edit: 60 of the
2193+ // short take plus all 60 of the second one.
2194+ assert_eq!(
2195+ decode_all(&out).len(),
2196+ (count * 2) as usize,
2197+ "the span after the break was not written"
2198+ );
2199+ std::fs::remove_file(&out).unwrap();
2200+}
2201+
2202+/// D4's control: an edit whose every span ends on a picture its file really has
2203+/// carries no notice at all -- the count must never be invented.
2204+#[test]
2205+fn a_healthy_two_clip_timeline_carries_no_truncation_notice() {
2206+ let _seat = pin_software();
2207+ let source = asset("test_multiaudio.mp4"); // 60 frames
2208+ let count = meta_frame_count(&source);
2209+ let (project, meta) = two_clip_edit(&source, count, count);
2210+ let out = out_path("truncated_control");
2211+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2212+ wait(&handle, Duration::from_secs(900)).expect("export");
2213+ let line = handle.encoders().expect("the seats were published");
2214+ let notice = line.contains("past the last picture");
2215+ assert_eq!(
2216+ notice, false,
2217+ "a whole export says it was truncated: {line}"
2218+ );
2219+ assert_eq!(
2220+ decode_all(&out).len(),
2221+ (count * 2) as usize,
2222+ "both spans were written"
2223+ );
2224+ std::fs::remove_file(&out).unwrap();
2225+}
2226+
2227+/// D3: the catch_unwind branch settled the worker's slot but left the `.part`
2228+/// on disk, against the module promise that every error path deletes it. The
2229+/// panic is injected at the first coded picture, so the `.part` is provably
2230+/// on disk when the worker dies.
2231+#[test]
2232+fn a_panicking_worker_deletes_the_part_file() {
2233+ let _exclusive = SEAT.write().unwrap_or_else(|p| p.into_inner());
2234+ let source = asset("test_baseline.mp4");
2235+ let (project, meta) = short_edit(&source, 20);
2236+ let out = out_path("panic");
2237+ let part = part_path(&out);
2238+ unsafe {
2239+ std::env::set_var("VE_EXPORT_TEST_PANIC", part.as_os_str().to_owned());
2240+ }
2241+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2242+ let result = wait(&handle, Duration::from_secs(120));
2243+ unsafe {
2244+ std::env::remove_var("VE_EXPORT_TEST_PANIC");
2245+ }
2246+ let error = result.expect_err("the injected panic is the outcome");
2247+ assert!(
2248+ error.to_string().contains("export worker panicked"),
2249+ "the panic is the outcome: {error}"
2250+ );
2251+ assert!(!out.exists(), "a panicked export wrote {}", out.display());
2252+ assert!(!part.exists(), "the .part outlived the panic");
2253+}