forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

export.rs2262 lines, 90.4 KiBHistoryRawDownload
1//! Export round trips: an edited timeline out to mp4 and straight back in
2//! through our own demuxer and decoder.
3//!
4//! The software test is the default one and needs nothing installed. The
5//! hardware twins need a built `libengine_hw.so` plus a VA-API driver with an
6//! H.264 encode entrypoint, so they are `#[ignore]`d:
7//!
8//! ```text
9//! cargo build -p engine-hw --release
10//! LD_LIBRARY_PATH=target/release \
11//! cargo test -p engine --release --test export -- --ignored --nocapture --test-threads=1
12//! ```
13//!
14//! That build is its own step and stays its own step: `--tests` (or building
15//! `-p engine` alongside) does **not** rebuild the cdylib, so the plugin beside
16//! the test binary is whatever was there last time -- a stale one, silently, and
17//! every hardware claim measured against it is about code nobody edited.
18//!
19//! Both env pins are process-wide, hence `--test-threads=1` for the ignored run.
20
21use std::fs::File;
22use std::io::BufReader;
23use std::path::{Path, PathBuf};
24use std::sync::{Mutex, Once};
25use std::time::{Duration, Instant};
26
27/// The two proxy tests below share one film, and a proxy job is one per film:
28/// run together, whichever asks second is refused ("already being made"), and
29/// a cancel in one deletes what the other is asserting about. One at a time.
30static PROXY_FILM: Mutex<()> = Mutex::new(());
31
32use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
33use ec_core::{Packet, TimeBase};
34use ec_h264::H264Decoder;
35use engine::export::ExportSettings;
36use engine::hw::HwEncoder;
37use engine::mux::{parameter_sets, AudioParams, Mp4Muxer, VideoParams};
38use engine::project::{Lane, Source, Speed};
39use engine::scale::FitPolicy;
40use engine::scratch::Scratch;
41use engine::{DecodeSession, ExportHandle, PlaybackSession, Project, Rotation};
42
43const FPS: f64 = 30.0;
44
45fn asset(name: &str) -> PathBuf {
46 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
47 .join("../../assets")
48 .join(name)
49}
50
51/// Its own directory, gone with the value: two suite runs at once (a release
52/// sweep beside a debug one, or two agents) would otherwise write and delete
53/// each other's export, and nothing may outlive the test that wrote it.
54fn out_path(name: &str) -> Scratch {
55 Scratch::file(&format!("ve_export_{name}"), "mp4")
56}
57
58/// What the worker actually writes to until it succeeds; the engine appends the
59/// suffix rather than replacing the extension.
60fn part_path(out: &Path) -> PathBuf {
61 PathBuf::from(format!("{}.part", out.display()))
62}
63
64/// Which seat an export takes is decided by *process-wide* environment
65/// variables, so it is a shared resource and every test in this binary borrows
66/// it rather than assuming it.
67///
68/// Readers share: the whole software suite wants the same pin and may run at
69/// once, exactly as it always did. A test that has to *change* the pin --
70/// there is one family, the encoder-death ones at the end of this file -- takes
71/// it exclusively, so no export is ever in flight while the seat is being
72/// cycled underneath it. A borrow held only for the seat's opening would not do:
73/// [`engine::export::start`] falls back and re-opens mid-run, so the pin has to
74/// hold for the whole export.
75static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(());
76
77type Shared = std::sync::RwLockReadGuard<'static, ()>;
78
79/// Pins both paths to software for the whole test binary, so the default suite
80/// proves the fallback that every machine has. Bind the guard: it is the borrow
81/// above, and dropping it early puts the export back in the race this exists to
82/// end.
83#[must_use = "the seat pin holds only while its guard is alive"]
84fn pin_software() -> Shared {
85 let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner());
86 static PIN: Once = Once::new();
87 PIN.call_once(|| unsafe {
88 std::env::set_var("VE_SW", "1");
89 std::env::set_var("VE_SW_ENC", "1");
90 });
91 borrowed
92}
93
94/// Removes both pins, for the hardware twins -- which run in their own
95/// `--ignored --test-threads=1` pass, so they never share this binary with the
96/// software ones.
97#[must_use = "the seat pin holds only while its guard is alive"]
98fn pin_hardware() -> Shared {
99 let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner());
100 static PIN: Once = Once::new();
101 PIN.call_once(|| unsafe {
102 std::env::remove_var("VE_SW");
103 std::env::remove_var("VE_SW_ENC");
104 });
105 borrowed
106}
107
108/// `[0,30) + [60,150)` of the source: two cuts and a delete, so the export has
109/// to seek, and the join is a real discontinuity rather than a formality.
110fn edited(source: &Path) -> PlaybackSession {
111 let mut session = PlaybackSession::open(source).expect("open source");
112 assert!(session.cut_at(30.0 / FPS), "cut at frame 30");
113 assert!(session.cut_at(60.0 / FPS), "cut at frame 60");
114 assert!(session.delete_clip(Lane::V1, 1), "drop the middle clip");
115 assert_eq!(session.clip_spans().len(), 2);
116 session
117}
118
119fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
120 let started = Instant::now();
121 while !handle.is_finished() {
122 assert!(
123 started.elapsed() < limit,
124 "export did not finish in {limit:?}"
125 );
126 std::thread::sleep(Duration::from_millis(20));
127 }
128 handle.result().expect("a finished export has an outcome")
129}
130
131/// Every frame of `path`, BGRA, in timeline order.
132fn decode_all(path: &Path) -> Vec<Vec<u8>> {
133 let (_, frames) = DecodeSession::open(path).expect("open export");
134 frames.into_iter().map(|frame| frame.bgra).collect()
135}
136
137/// What an outside decoder complains about while reading every packet of
138/// `path`: empty when it read the file clean. `None` where ffmpeg is not
139/// installed, which is a skip rather than a failure -- the same posture the
140/// colour tests take.
141fn ffmpeg_complaints(path: &Path) -> Option<String> {
142 let said = std::process::Command::new("ffmpeg")
143 .args(["-v", "error", "-i"])
144 .arg(path)
145 .args(["-f", "null", "-"])
146 .output()
147 .ok()?;
148 Some(String::from_utf8_lossy(&said.stderr).trim().to_string())
149}
150
151/// One frame of `path` by absolute index.
152fn frame_at(path: &Path, index: u32) -> Vec<u8> {
153 let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source");
154 frames.recv().expect("frame present").bgra
155}
156
157fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
158 assert_eq!(a.len(), b.len(), "frame sizes differ");
159 a.iter()
160 .zip(b)
161 .map(|(x, y)| f64::from(x.abs_diff(*y)))
162 .sum::<f64>()
163 / a.len() as f64
164}
165
166/// The whole point of the slice: an edited timeline survives the trip out to
167/// disk and back, frame for frame and picture for picture.
168fn round_trip(name: &str, limit: Duration) {
169 let source = asset("test_baseline.mp4");
170 let mut session = edited(&source);
171 session.pause();
172 let out = out_path(name);
173
174 let started = Instant::now();
175 let handle = session.export_to(&out);
176 wait(&handle, limit).expect("export");
177 let spent = started.elapsed();
178 println!(
179 "{name}: 120 frames in {:.2} s = {:.2} ms/frame",
180 spent.as_secs_f64(),
181 spent.as_secs_f64() * 1000.0 / 120.0
182 );
183 assert_eq!(handle.progress(), 1.0, "finished at full progress");
184
185 let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen export");
186 assert_eq!(meta.frame_count, 120, "timeline frames written");
187 assert_eq!((meta.width, meta.height), (1280, 720));
188 assert_eq!(meta.frame_rate.round(), FPS);
189
190 let file = File::open(&out).unwrap();
191 let size = file.metadata().unwrap().len();
192 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
193 let duration = reader.duration().as_secs_f64();
194 assert!(
195 (duration - 120.0 / FPS).abs() <= 1.0 / FPS,
196 "duration {duration} s is more than a frame off 4.0 s"
197 );
198
199 let frames = decode_all(&out);
200 assert_eq!(frames.len(), 120, "every written frame decodes back");
201
202 // Timeline -> source: [0,30) maps to itself, [30,120) to [60,150).
203 for (timeline, source_frame) in [(0u32, 0u32), (59, 89), (119, 149)] {
204 let diff = mean_abs_diff(&frames[timeline as usize], &frame_at(&source, source_frame));
205 println!("timeline {timeline} vs source {source_frame}: mean abs diff {diff:.2}");
206 assert!(
207 diff < 6.0,
208 "timeline frame {timeline} drifted by {diff:.2} from source frame {source_frame}"
209 );
210 }
211 std::fs::remove_file(&out).unwrap();
212}
213
214#[test]
215fn exports_an_edited_timeline_in_software() {
216 let _seat = pin_software();
217 round_trip("sw", Duration::from_secs(600));
218}
219
220/// Same trip through the plugin, and the only place the end-to-end hardware
221/// cost (decode + encode + mux) is measured.
222#[test]
223#[ignore]
224fn exports_an_edited_timeline_in_hardware() {
225 let _seat = pin_hardware();
226 round_trip("hw", Duration::from_secs(60));
227}
228
229/// An export is written at the **project's** resolution, whatever sizes the
230/// media on the timeline are -- and with the same geometry that was watched.
231///
232/// 1280x720 and 640x360 clips on a 960x720 (4:3) project: every frame comes out
233/// 960x720, and both clips are letterboxed with 90 rows of bar at each edge,
234/// which is exactly what `scale::fit_rect` places and what playback shows
235/// (`playback.rs: a_fitted_clip_is_letterboxed_and_a_filled_one_is_not`).
236#[test]
237fn exports_at_the_project_resolution_with_the_watched_geometry() {
238 let _seat = pin_software();
239 let clip = |source: usize, start: u32| engine::Clip {
240 fade_in: 0,
241 fade_out: 0,
242 transition_out: 0,
243 visualizer: 0,
244 viz_paint: 0,
245 start,
246 in_frame: 0,
247 out_frame: 10,
248 source,
249 link: Some(source as u32),
250 eq: None,
251 color: None,
252 transform: None,
253 fit: FitPolicy::default(),
254 speed: Speed::NORMAL,
255 };
256 let clips = vec![clip(0, 0), clip(1, 10)];
257 let project = Project::from_parts(
258 vec![
259 Source::new(asset("test_baseline.mp4"), 0),
260 Source::new(asset("test_mismatch.mp4"), 0),
261 ],
262 vec![
263 (engine::project::LaneKind::Video, clips.clone()),
264 (engine::project::LaneKind::Audio, clips),
265 ],
266 Vec::new(),
267 Vec::new(),
268 Vec::new(),
269 )
270 .expect("a two-source project");
271 // The project's own resolution, which is neither source's: this is the
272 // value `PlaybackSession` keeps in its meta and hands the exporter.
273 let meta = engine::VideoMeta {
274 width: 960,
275 height: 720,
276 frame_rate: FPS,
277 frame_count: 20,
278 codec: engine::Codec::H264,
279 color: Default::default(),
280 rotation: Rotation::None,
281 // Square pixels, coded where they are declared: a meta no container
282 // wrote, so nothing was read to disagree with it.
283 coded_width: 960,
284 coded_height: 720,
285 pixel_aspect: engine::demux::PixelAspect::SQUARE,
286 };
287 let out = out_path("mixed");
288 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
289 wait(&handle, Duration::from_secs(600)).expect("export");
290
291 let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export");
292 assert_eq!(
293 (written.width, written.height),
294 (960, 720),
295 "an export is the project's size, not any source's"
296 );
297 assert_eq!(written.frame_count, 20);
298
299 let frames = decode_all(&out);
300 assert_eq!(frames.len(), 20);
301 // Lossy: a bar is black plus whatever the encoder left, so the bars are
302 // asserted as *flat and dark* rather than as byte 0, and the picture rows
303 // as neither.
304 let mean = |frame: &[u8], y: usize| {
305 frame[y * 960 * 4..][..960 * 4]
306 .chunks_exact(4)
307 .flat_map(|px| [px[0], px[1], px[2]])
308 .map(f64::from)
309 .sum::<f64>()
310 / (960.0 * 3.0)
311 };
312 for (at, what) in [(5usize, "the 1280x720 clip"), (15, "the 640x360 clip")] {
313 let frame = &frames[at];
314 assert!(mean(frame, 2) < 8.0, "{what}: top bar is not black");
315 assert!(mean(frame, 717) < 8.0, "{what}: bottom bar is not black");
316 assert!(
317 mean(frame, 360) > 20.0,
318 "{what}: the picture area is black, so nothing was composed"
319 );
320 }
321 std::fs::remove_file(&out).unwrap();
322}
323
324/// The trap this slice exists to close: a timeline playing a file's *second*
325/// audio stream must export that stream's packets. Playing one stream and
326/// exporting another is a file that sounds nothing like what was edited, and
327/// nothing in it would say so -- so the check is the copied bytes, not just the
328/// header. Software only: the picture is beside the point here.
329#[test]
330fn exports_the_audio_stream_the_timeline_plays() {
331 let _seat = pin_software();
332 let multi = asset("test_multiaudio.mp4");
333 let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture");
334 let whole = engine::Clip {
335 fade_in: 0,
336 fade_out: 0,
337 transition_out: 0,
338 visualizer: 0,
339 viz_paint: 0,
340 start: 0,
341 in_frame: 0,
342 out_frame: meta.frame_count,
343 source: 0,
344 link: Some(0),
345 eq: None,
346 color: None,
347 transform: None,
348 fit: FitPolicy::default(),
349 speed: Speed::NORMAL,
350 };
351 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
352 // stereo. A project may only hold streams that agree, so this timeline is
353 // stream 1 alone -- which is exactly what an export must carry.
354 let project = Project::from_parts(
355 vec![Source {
356 path: multi.clone(),
357 audio_stream: 1,
358 }],
359 vec![
360 (engine::project::LaneKind::Video, vec![whole]),
361 (engine::project::LaneKind::Audio, vec![whole]),
362 ],
363 Vec::new(),
364 Vec::new(),
365 Vec::new(),
366 )
367 .expect("a one-source project on stream 1");
368 let out = out_path("stream1");
369 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
370 wait(&handle, Duration::from_secs(600)).expect("export");
371
372 let (audio, _) = engine::AudioSession::open(&out)
373 .expect("reopen export audio")
374 .expect("the export has audio");
375 assert_eq!(
376 (audio.sample_rate, audio.channels),
377 (22_050, 1),
378 "the export carries stream 0's parameters, not the stream that played"
379 );
380
381 // Byte for byte: the exported track is the copy of stream 1, and it is not
382 // the copy of stream 0 -- the second assert is what makes the first one
383 // mean something.
384 let segs = [(Some(0), 0.0, f64::from(meta.frame_count) / FPS)];
385 let copy = |stream| {
386 engine::AudioSession::copy_multi_streams(&[(multi.clone(), stream)], &segs)
387 .expect("copy")
388 .expect("has audio")
389 .1
390 .into_iter()
391 .map(|p| p.bytes)
392 .collect::<Vec<_>>()
393 };
394 let (one, zero) = (copy(1), copy(0));
395 assert_ne!(one, zero, "the two streams are not the same bytes");
396
397 let file = File::open(&out).unwrap();
398 let size = file.metadata().unwrap().len();
399 let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
400 let track = *reader
401 .tracks()
402 .keys()
403 .find(|id| reader.sample_count(**id).unwrap_or(0) as usize == one.len())
404 .unwrap_or(&2);
405 let written: Vec<Vec<u8>> = (1..=reader.sample_count(track).expect("audio track"))
406 .map(|id| {
407 reader
408 .read_sample(track, id)
409 .expect("sample")
410 .expect("present")
411 .bytes
412 .to_vec()
413 })
414 .collect();
415 assert_eq!(written, one, "the exported packets are stream 1's");
416 std::fs::remove_file(&out).unwrap();
417}
418
419/// `test_av[0,120)` then the whole of `test_av2`: the last second of the first
420/// source is deleted, so timeline frame 120 is both a cut and a file change --
421/// the join the multi-source export exists for.
422fn two_sources() -> Project {
423 let (av, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open test_av");
424 let (av2, _) = engine::demux::Demuxer::open(&asset("test_av2.mp4")).expect("open test_av2");
425 assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a");
426
427 let mut project = Project::single(asset("test_av.mp4"), av.frame_count);
428 let second = project.import(asset("test_av2.mp4"), 0);
429 assert_eq!(second, 1, "a second file is a second source");
430 assert!(project.append_clip(second, av2.frame_count));
431 assert!(project.split(120), "cut a second before the end of test_av");
432 assert!(project.delete(1), "drop test_av's tail");
433 assert_eq!(project.timeline_frames(), 120 + av2.frame_count);
434 assert_eq!(
435 project.clips().iter().map(|c| c.source).collect::<Vec<_>>(),
436 vec![0, 1]
437 );
438 project
439}
440
441/// A timeline spanning two files exports as one: every clip is decoded from its
442/// own source, the audio is copied across the join, and the result reopens as a
443/// single stream whose frame at the join is the second file's first frame.
444fn multi_source_round_trip(name: &str, limit: Duration) {
445 let project = two_sources();
446 let total = project.timeline_frames();
447 let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap();
448 let out = out_path(name);
449
450 let started = Instant::now();
451 let handle = engine::export::start(
452 project.clone(),
453 meta,
454 &out,
455 &ExportSettings::default(),
456 None,
457 );
458 wait(&handle, limit).expect("export");
459 println!(
460 "{name}: {total} frames of two sources in {:.2} s",
461 started.elapsed().as_secs_f64()
462 );
463
464 let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export");
465 assert_eq!(written.frame_count, total, "timeline frames written");
466 assert_eq!((written.width, written.height), (1280, 720));
467
468 let frames = decode_all(&out);
469 assert_eq!(
470 frames.len() as u32,
471 total,
472 "every written frame decodes back"
473 );
474 // The join: timeline 120 is test_av2's frame 0, timeline 119 still test_av's.
475 for (timeline, source, source_frame) in [
476 (0u32, "test_av.mp4", 0u32),
477 (119, "test_av.mp4", 119),
478 (120, "test_av2.mp4", 0),
479 (total - 1, "test_av2.mp4", total - 121),
480 ] {
481 let diff = mean_abs_diff(
482 &frames[timeline as usize],
483 &frame_at(&asset(source), source_frame),
484 );
485 println!("timeline {timeline} vs {source} {source_frame}: mean abs diff {diff:.2}");
486 assert!(
487 diff < 6.0,
488 "timeline frame {timeline} drifted by {diff:.2} from {source} frame {source_frame}"
489 );
490 }
491
492 // Audio across the join: 1 + 172 + 173. Both segments ask for 4.0 s =
493 // 172.27 packets, and the head is test_av's own priming packet (the first
494 // segment's alone -- the join must not add a second one). The first segment
495 // copies 172 and owes 272 samples, and it is that *carried* debt that makes
496 // the second copy 173: rounding each source on its own would give 345, so
497 // this number is the proof the accumulator survives a source change.
498 let file = File::open(&out).unwrap();
499 let size = file.metadata().unwrap().len();
500 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
501 let packets = reader.sample_count(2).expect("audio track");
502 assert_eq!(packets, 346, "packet total across the source join");
503 let wanted = f64::from(total) / FPS * 44_100.0;
504 assert!(
505 (f64::from(packets * 1024) - wanted).abs() < 3.0 * 1024.0,
506 "audio length {} samples drifted from {wanted}",
507 packets * 1024
508 );
509 let (audio, _) = engine::AudioSession::open(&out)
510 .expect("reopen export audio")
511 .expect("export has an audio track");
512 assert_eq!((audio.sample_rate, audio.channels), (44_100, 2));
513 std::fs::remove_file(&out).unwrap();
514}
515
516#[test]
517fn exports_two_sources_as_one_timeline_in_software() {
518 let _seat = pin_software();
519 multi_source_round_trip("multi_sw", Duration::from_secs(900));
520}
521
522#[test]
523#[ignore]
524fn exports_two_sources_as_one_timeline_in_hardware() {
525 let _seat = pin_hardware();
526 multi_source_round_trip("multi_hw", Duration::from_secs(60));
527}
528
529/// The bitrate setting is the one knob a user turns for quality, so it has to
530/// reach the encoder: the same 120-frame timeline at 1, 4 and 8 Mbps has to come
531/// back as three strictly growing files. `force_sw` pins the software encoder,
532/// whose rate control is the one every machine has.
533#[test]
534fn a_higher_bitrate_writes_a_bigger_file() {
535 let _seat = pin_software();
536 let mut sizes = Vec::new();
537 for bitrate in [1_000_000u64, 4_000_000, 8_000_000] {
538 let mut session = edited(&asset("test_baseline.mp4"));
539 session.pause();
540 let out = out_path(&format!("bitrate_{bitrate}"));
541 let settings = ExportSettings {
542 bitrate: Some(bitrate),
543 seat: engine::export::EncoderSeat::Software,
544 ..Default::default()
545 };
546 let handle = session.export_to_with(&out, &settings);
547 wait(&handle, Duration::from_secs(900)).expect("export");
548 let size = std::fs::metadata(&out).expect("export exists").len();
549 println!("{} Mbps: {size} bytes", bitrate / 1_000_000);
550 sizes.push(size);
551 std::fs::remove_file(&out).unwrap();
552 }
553 assert!(
554 sizes[0] < sizes[1] && sizes[1] < sizes[2],
555 "file sizes {sizes:?} are not strictly growing with the bitrate"
556 );
557}
558
559/// A source that disappears between the edit and the export fails the export
560/// rather than silently writing a shorter file -- and leaves neither an output
561/// nor a `.part`. Both sources are silent, so the failure is the per-clip open
562/// (the audio pass never touches the second file).
563#[test]
564fn a_vanished_source_fails_the_export() {
565 let _seat = pin_software();
566 let baseline = asset("test_baseline.mp4");
567 let doomed = Scratch::file("ve_export_vanished_source", "mp4");
568 std::fs::copy(&baseline, &doomed).expect("copy a second source");
569 let (meta, _) = engine::demux::Demuxer::open(&baseline).unwrap();
570
571 // Five frames of each: the export has to get going and then fail.
572 let mut project = Project::single(&baseline, meta.frame_count);
573 assert!(project.split(5));
574 assert!(project.delete(1));
575 let second = project.import(&doomed, 0);
576 assert!(project.append_clip(second, meta.frame_count));
577 assert!(project.split(10));
578 assert!(project.delete(2));
579 assert_eq!(project.timeline_frames(), 10);
580
581 std::fs::remove_file(&doomed).expect("unlink the second source");
582 let out = out_path("vanished");
583 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
584 let result = wait(&handle, Duration::from_secs(60));
585 let error = result.expect_err("an export of a missing file cannot succeed");
586 println!("vanished source: {error}");
587 assert!(
588 !out.exists(),
589 "a failed export still wrote {}",
590 out.display()
591 );
592 assert!(!part_path(&out).exists(), "the .part outlived the failure");
593}
594
595/// A cancelled export leaves nothing behind -- the half-written file is the
596/// thing a user would otherwise try to play.
597#[test]
598fn cancelling_leaves_no_file() {
599 let _seat = pin_software();
600 let mut session = edited(&asset("test_baseline.mp4"));
601 session.pause();
602 let out = out_path("cancel");
603
604 let handle = session.export_to(&out);
605 let started = Instant::now();
606 while handle.progress() < 0.1 {
607 assert!(
608 started.elapsed() < Duration::from_secs(60),
609 "export never got going"
610 );
611 assert!(
612 !handle.is_finished(),
613 "export finished before it was cancelled"
614 );
615 std::thread::sleep(Duration::from_millis(10));
616 }
617 handle.cancel();
618 // A liveness ceiling, not a deadline under test: a cancel lands in ~5 s on an
619 // idle box, and inside a full parallel run of this binary (34 tests, most of
620 // them encoding) the worker can be starved well past that. 60 s still fails
621 // the run if a cancel never lands.
622 let result = wait(&handle, Duration::from_secs(60));
623 assert!(result.is_err(), "a cancelled export is an error");
624 assert!(!out.exists(), "no partial file survives a cancel");
625 assert!(!part_path(&out).exists(), "the .part is cleaned up too");
626}
627
628/// The late window: cancel after the last frame, while the export is draining,
629/// writing audio and closing the file. Progress already reads 100% there, and
630/// before the cancel checkpoints outside the frame loop the export completed
631/// anyway and left a file the user never asked for.
632///
633/// Landing in that window is a race, so the attempt is repeated; whichever side
634/// of it an attempt lands on, the invariant is the same -- a finished file or no
635/// file, never a `.part`.
636#[test]
637fn cancelling_after_the_last_frame_leaves_no_file() {
638 let _seat = pin_software();
639 let out = out_path("late");
640 let part = part_path(&out);
641 for attempt in 1..=5 {
642 let mut session = edited(&asset("test_baseline.mp4"));
643 session.pause();
644 let handle = session.export_to(&out);
645 // Sleep while there is time to sleep, then spin: the window is the few
646 // milliseconds between the last frame and `finish`.
647 let started = Instant::now();
648 while handle.progress() < 0.9 && !handle.is_finished() {
649 assert!(
650 started.elapsed() < Duration::from_secs(600),
651 "export stalled"
652 );
653 std::thread::sleep(Duration::from_millis(20));
654 }
655 while handle.progress() < 1.0 && !handle.is_finished() {
656 std::hint::spin_loop();
657 }
658 handle.cancel();
659
660 let result = wait(&handle, Duration::from_secs(120));
661 assert!(!part.exists(), "attempt {attempt} left a .part behind");
662 if result.is_err() {
663 assert!(!out.exists(), "a late cancel still wrote {}", out.display());
664 return;
665 }
666 // The export beat the cancel; then it must be a whole file, not a stump.
667 assert_eq!(
668 engine::demux::Demuxer::open(&out).unwrap().0.frame_count,
669 120
670 );
671 std::fs::remove_file(&out).unwrap();
672 }
673 panic!("cancel never landed in the drain/audio/finish window");
674}
675
676/// Audio: the copied AAC packets have to land in the export as a track a reader
677/// can open again, at a length the video agrees with.
678#[test]
679#[ignore]
680fn exports_audio_alongside_the_video() {
681 let _seat = pin_hardware();
682 let source = asset("test_av.mp4");
683 let mut session = PlaybackSession::open(&source).expect("open source");
684 // One cut: the timeline is unchanged but the audio copy now runs as two
685 // segments, so the packet-boundary rounding at the join is exercised.
686 assert!(session.cut_at(2.0));
687 session.pause();
688 let timeline = session.timeline_duration();
689 let out = out_path("av");
690
691 let handle = session.export_to(&out);
692 wait(&handle, Duration::from_secs(600)).expect("export");
693
694 let file = File::open(&out).unwrap();
695 let size = file.metadata().unwrap().len();
696 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
697 let packets = reader.sample_count(2).expect("audio track");
698 let expected = engine::AudioSession::copy_segments(&source, &[(0.0, 2.0), (2.0, 5.0)])
699 .unwrap()
700 .expect("source has audio")
701 .1
702 .len() as u32;
703 assert_eq!(packets, expected, "every copied packet reached the file");
704 // Independently of the copier: the rounding stays inside one packet per join
705 // plus the priming packet it starts with.
706 let samples = f64::from(packets * 1024);
707 let wanted = timeline * 44_100.0;
708 println!("audio: {packets} packets = {samples} samples for {wanted} of timeline");
709 assert!(
710 (samples - wanted).abs() < 3.0 * 1024.0,
711 "audio length {samples} drifted from {wanted}"
712 );
713
714 let (meta, chunks) = engine::AudioSession::open(&out)
715 .expect("reopen export audio")
716 .expect("export has an audio track");
717 assert_eq!(meta.sample_rate, 44_100);
718 assert_eq!(meta.channels, 2);
719 let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum();
720 assert!(
721 decoded as f64 / 2.0 > wanted - 3.0 * 1024.0,
722 "only {decoded} samples decoded back out"
723 );
724
725 let (video, _) = engine::demux::Demuxer::open(&out).unwrap();
726 assert_eq!(video.frame_count, 150, "video track unaffected by the cut");
727 std::fs::remove_file(&out).unwrap();
728}
729
730/// Hardware-encoded access units had never been through the muxer before this
731/// slice: the Mesa slice-header fixup and the parameter-set placement were only
732/// ever proven against a raw decoder.
733#[test]
734#[ignore]
735fn hardware_access_units_repack_into_mp4() {
736 let (w, h) = (640u32, 480u32);
737 let mut encoder =
738 HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver");
739 let out = out_path("hwmux");
740 let mut muxer: Option<Mp4Muxer> = None;
741 let mut written = 0;
742 for index in 0..10u32 {
743 let (y, u, v) = synthetic(index, w as usize, h as usize);
744 let Some(au) = encoder.encode(&y, &u, &v, w, h, false).expect("encode") else {
745 continue;
746 };
747 if muxer.is_none() {
748 let (sps, pps) = parameter_sets(au).expect("first access unit carries SPS+PPS");
749 muxer = Some(
750 Mp4Muxer::create(
751 &out,
752 &VideoParams {
753 width: w,
754 height: h,
755 frame_rate: 30.0,
756 sps,
757 pps,
758 },
759 None,
760 )
761 .expect("create"),
762 );
763 }
764 muxer.as_mut().unwrap().write_video_au(au).expect("write");
765 written += 1;
766 }
767 while let Some(au) = encoder.drain().expect("drain") {
768 muxer.as_mut().unwrap().write_video_au(au).expect("write");
769 written += 1;
770 }
771 muxer.unwrap().finish().expect("finish");
772 assert_eq!(written, 10);
773
774 let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap();
775 assert_eq!(meta.frame_count, 10);
776 let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264))
777 .expect("ec-h264 takes its own codec id");
778 let mut decoded = 0;
779 while let Some(au) = demuxer.next_access_unit().unwrap() {
780 decoder
781 .send_packet(&Packet::new(0, TimeBase::new(1, 1), au))
782 .expect("software decode of the remuxed stream");
783 while let Ok(frame) = decoder.receive_frame() {
784 let ec_core::frame::Frame::Video(_) = frame else {
785 continue;
786 };
787 decoded += 1;
788 }
789 }
790 decoder.flush().expect("flush of the remuxed stream");
791 while let Ok(frame) = decoder.receive_frame() {
792 let ec_core::frame::Frame::Video(_) = frame else {
793 continue;
794 };
795 decoded += 1;
796 }
797 assert_eq!(decoded, 10, "every remuxed picture decodes again");
798 std::fs::remove_file(&out).unwrap();
799}
800
801/// A moving diagonal gradient: something that costs bits, so the encoder cannot
802/// pass the check by emitting skip frames.
803fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
804 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
805 let mut y = vec![0u8; width * height];
806 for row in 0..height {
807 for col in 0..width {
808 y[row * width + col] = (row + col + index as usize * 5) as u8;
809 }
810 }
811 (
812 y,
813 vec![64u8.wrapping_add(index as u8); cw * ch],
814 vec![192u8.wrapping_sub(index as u8); cw * ch],
815 )
816}
817
818/// One throwaway IDR slice NAL -- not a real picture (nothing here decodes
819/// it), just something `Mp4Muxer::write_video_au` accepts and ffprobe can
820/// see as one packet on the video track.
821fn fake_au(n: u8) -> Vec<u8> {
822 vec![0, 0, 1, 0x65, n, n.wrapping_add(1), 0xA5]
823}
824
825/// `Mp4Muxer` holds coded pictures back until the sound can be interleaved
826/// under them ([`Mp4Muxer::hold`], mux.rs), so that a streaming reader sees
827/// both tracks advancing together rather than the whole picture and only
828/// then the whole track. This pins the boundary the muxer's own doc comment
829/// on `hold` states in words: how tightly the two interleave depends on
830/// *when* the mix lands relative to the picture, which on a real export is a
831/// race against a mixer thread this test does not want to run. So it forces
832/// the landing itself -- writing straight to `Mp4Muxer`, exactly the shape
833/// `export::run`'s `feed_late_audio` uses it in (a burst of video, then the
834/// whole mix handed over in one tight loop, then the rest of the picture) --
835/// rather than the real threaded export.
836#[test]
837fn mp4_interleaves_a_mix_that_lands_early_under_the_rest_of_the_picture() {
838 let out = out_path("interleave");
839 let (width, height, fps) = (64u32, 64u32, 30.0);
840 let (sps, pps) = ([0x67, 0x42, 0x00, 0x1E], [0x68, 0xCE, 0x3C, 0x80]);
841 let mut muxer = Mp4Muxer::create(
842 &out,
843 &VideoParams {
844 width,
845 height,
846 frame_rate: fps,
847 sps: &sps,
848 pps: &pps,
849 },
850 None,
851 )
852 .expect("create");
853
854 // 15 frames (0.5 s) of a head start for the picture -- the file always
855 // wrote this stretch video-only, mix or no mix, and this test is about
856 // the file *after* it.
857 for i in 0..15u8 {
858 muxer.write_video_au(&fake_au(i)).expect("write video");
859 }
860 muxer
861 .add_audio_track(&AudioParams {
862 freq_index: 3, // mp4::SampleFreqIndex::Freq48000
863 chan_conf: 2, // ChannelConfig::Stereo
864 sample_rate: 48_000,
865 opus_pre_skip: None,
866 })
867 .expect("declare audio");
868 // The whole mix, handed over in one tight loop exactly as
869 // `export::feed_late_audio` does: 200 packets of 1024/48000 s each is
870 // ~4.27 s, well past the picture's 0.5 s head start, so releasing it
871 // correctly needs the *rest* of the picture below to pace it out.
872 let silence = [0x21, 0x10, 0x04, 0x60, 0x8c, 0x1c];
873 for _ in 0..200u32 {
874 muxer.write_audio_packet(&silence).expect("write audio");
875 }
876 // The rest of the picture: 135 more frames, 4.5 s, what the mix above is
877 // paced against.
878 for i in 15..150u8 {
879 muxer.write_video_au(&fake_au(i)).expect("write video");
880 }
881 muxer.write_subtitles(&[]).expect("no subtitles");
882 muxer.finish().expect("finish");
883
884 assert_no_single_stream_span_over(&out, 2.0);
885 std::fs::remove_file(&out).unwrap();
886}
887
888/// Reads `path`'s packets back with ffprobe (pts + byte position) and fails
889/// if any run of file-order-consecutive same-stream packets spans more media
890/// time than `seconds` -- the numeric shape of "no byte-span longer than 2 s
891/// of media contains packets from only one stream".
892fn assert_no_single_stream_span_over(path: &Path, seconds: f64) {
893 let output = std::process::Command::new("ffprobe")
894 .args([
895 "-v",
896 "error",
897 "-show_entries",
898 "packet=stream_index,pts_time,pos",
899 "-of",
900 "csv=p=0",
901 ])
902 .arg(path)
903 .output()
904 .expect("run ffprobe");
905 assert!(
906 output.status.success(),
907 "ffprobe failed: {}",
908 String::from_utf8_lossy(&output.stderr)
909 );
910 let text = String::from_utf8_lossy(&output.stdout);
911 let mut packets: Vec<(i64, u32, f64)> = text
912 .lines()
913 .filter(|line| !line.is_empty())
914 .map(|line| {
915 let mut fields = line.split(',');
916 let stream: u32 = fields.next().unwrap().parse().unwrap();
917 let pts: f64 = fields.next().unwrap().parse().unwrap();
918 let pos: i64 = fields.next().unwrap().parse().unwrap();
919 (pos, stream, pts)
920 })
921 .collect();
922 assert!(
923 packets.len() > 10,
924 "ffprobe saw only {} packets",
925 packets.len()
926 );
927 packets.sort_by_key(|&(pos, ..)| pos);
928
929 let streams: std::collections::HashSet<u32> = packets.iter().map(|&(_, s, _)| s).collect();
930 assert_eq!(
931 streams.len(),
932 2,
933 "expected one video and one audio stream, ffprobe saw {streams:?}"
934 );
935
936 let (mut run_stream, mut run_start) = (packets[0].1, packets[0].2);
937 for &(_, stream, pts) in &packets[1..] {
938 if stream != run_stream {
939 run_stream = stream;
940 run_start = pts;
941 continue;
942 }
943 let span = pts - run_start;
944 assert!(
945 span <= seconds,
946 "a run of stream {run_stream} packets alone spans {span:.2} s (from {run_start:.2} s) -- over the {seconds} s bound"
947 );
948 }
949}
950
951/// The first `pts_time` ffprobe reports for stream kind `select` ("v" or
952/// "a") in `path` -- just enough of [`assert_no_single_stream_span_over`]'s
953/// ffprobe call, restricted to one stream, to check A/V sync independently of
954/// the interleave order.
955fn first_pts(path: &Path, select: &str) -> f64 {
956 let output = std::process::Command::new("ffprobe")
957 .args([
958 "-v",
959 "error",
960 "-select_streams",
961 select,
962 "-show_entries",
963 "packet=pts_time",
964 "-of",
965 "csv=p=0",
966 ])
967 .arg(path)
968 .output()
969 .expect("run ffprobe");
970 assert!(
971 output.status.success(),
972 "ffprobe failed: {}",
973 String::from_utf8_lossy(&output.stderr)
974 );
975 String::from_utf8_lossy(&output.stdout)
976 .lines()
977 .find(|line| !line.is_empty())
978 .expect("stream has at least one packet")
979 .parse()
980 .expect("pts_time")
981}
982
983/// An mp4 export used to write every video sample and only then the whole
984/// audio track: byte-correct, and silent for as long as the picture took on
985/// any player that reads the file as it streams in rather than seeking to the
986/// end first. This proves the interleave holds on the real, threaded export
987/// path end to end -- `mp4_interleaves_a_mix_that_lands_early_under_the_rest_of_the_picture`
988/// above pins the same boundary by writing straight to `Mp4Muxer`, forcing the
989/// mix to land early rather than racing the mixer thread for it.
990#[test]
991fn mp4_audio_interleaves_with_the_picture() {
992 let _seat = pin_software();
993 let source = asset("test_av.mp4");
994 let mut session = PlaybackSession::open(&source).expect("open source");
995 // A cut, so the audio copy runs as two segments and the join is real --
996 // the same edit `exports_audio_alongside_the_video` makes, reused here so
997 // the interleave is proven on a timeline that was actually cut, not a
998 // straight passthrough.
999 assert!(session.cut_at(2.0));
1000 session.pause();
1001 let timeline = session.timeline_duration();
1002 let out = out_path("interleave-e2e");
1003
1004 let handle = session.export_to(&out);
1005 wait(&handle, Duration::from_secs(600)).expect("export");
1006
1007 // A/V sync: the first audio sample starts at movie time zero either way --
1008 // interleaving moves *where in the file* a packet sits, never what `stts`
1009 // says it plays at.
1010 assert_eq!(
1011 first_pts(&out, "a"),
1012 0.0,
1013 "first audio pts is media time zero"
1014 );
1015
1016 assert_no_single_stream_span_over(&out, 2.0);
1017
1018 // Nothing else about the file moved: same duration, same sample counts,
1019 // to within the packet the two sibling tests above already allow.
1020 let (video_meta, _) = engine::demux::Demuxer::open(&out).unwrap();
1021 assert_eq!(
1022 video_meta.frame_count, 150,
1023 "video track unaffected by interleaving"
1024 );
1025 let (audio_meta, chunks) = engine::AudioSession::open(&out)
1026 .unwrap()
1027 .expect("export has an audio track");
1028 assert_eq!((audio_meta.sample_rate, audio_meta.channels), (44_100, 2));
1029 let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum();
1030 let wanted = timeline * f64::from(audio_meta.sample_rate);
1031 assert!(
1032 (decoded as f64 / f64::from(audio_meta.channels) - wanted).abs() < 3.0 * 1024.0,
1033 "audio length {decoded} drifted from {wanted} samples of timeline"
1034 );
1035
1036 std::fs::remove_file(&out).unwrap();
1037}
1038
1039/// A timeline whose *first* second of sound was lifted. A reader drops the
1040/// first packet of an AAC track as encoder priming, so a track that opens on a
1041/// hole has to carry one extra packet of silence for it to drop -- without it
1042/// the drop comes out of the hole and every sound after the hole plays 23 ms
1043/// early, which is a lip sync error for the whole export.
1044#[test]
1045fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() {
1046 let _seat = pin_software();
1047 let source = asset("test_av.mp4");
1048 let mut session = PlaybackSession::open(&source).expect("open source");
1049 assert!(session.cut_at(1.0), "cut at 1 s");
1050 assert!(session.lift_clip(Lane::A1, 0), "lift the first second");
1051 session.pause();
1052 let out = out_path("leading_gap");
1053 let handle = session.export_to(&out);
1054 wait(&handle, Duration::from_secs(900)).expect("export");
1055
1056 let (_, chunks) = engine::AudioSession::open(&out)
1057 .expect("reopen export audio")
1058 .expect("export has an audio track");
1059 let mut pcm: Vec<f32> = Vec::new();
1060 while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) {
1061 pcm.resize(chunk.start_sample as usize * 2, 0.0);
1062 pcm.extend_from_slice(&chunk.samples);
1063 }
1064 // Where the sound starts, measured in whole packets so the MDCT leak either
1065 // side of the splice cannot be mistaken for the onset: the first block
1066 // carrying a quarter of the export's own peak.
1067 let block = 1024 * 2;
1068 let peak = |b: &[f32]| b.iter().fold(0.0f32, |m, s| m.max(s.abs()));
1069 let loud = peak(&pcm) / 4.0;
1070 let onset = pcm
1071 .chunks(block)
1072 .position(|b| peak(b) > loud)
1073 .expect("the export has no sound at all") as f64
1074 * 1024.0;
1075 println!("leading gap: sound starts at sample {onset} of an expected 44100");
1076 assert!(
1077 (onset - 44_100.0).abs() <= 1024.0,
1078 "the sound after the gap is at {onset}, not at the 1 s hole's end"
1079 );
1080 // ...and the hole really is a hole, not the first second played quietly.
1081 let quiet = peak(&pcm[..(0.9 * 44_100.0) as usize * 2]);
1082 assert!(quiet < 1e-3, "the lifted second is not silent: {quiet}");
1083
1084 std::fs::remove_file(&out).unwrap();
1085}
1086
1087/// A timeline with a hole in each lane, exported. The video gap is encoded as
1088/// black rather than skipped -- the file is as long as the timeline, frame for
1089/// frame -- and the audio gap is copied as real silent packets, so the audio
1090/// track covers the whole timeline inside the bresenham bound instead of ending
1091/// a second early.
1092#[test]
1093fn exports_a_gapped_timeline_as_black_and_silence() {
1094 let _seat = pin_software();
1095 let source = asset("test_av.mp4");
1096 let mut session = PlaybackSession::open(&source).expect("open source");
1097 assert!(session.cut_at(1.0), "split at 1 s");
1098 assert!(session.cut_at(2.0), "split at 2 s");
1099 // Lift the middle out of *both* lanes: one second of black and silence in
1100 // the middle of a five-second timeline, with the length unchanged.
1101 assert!(session.lift_clip(Lane::V1, 1));
1102 assert!(session.lift_clip(Lane::A1, 1));
1103 session.pause();
1104 let timeline = session.timeline_duration();
1105 let frames = (timeline * FPS).round() as u32;
1106 let out = out_path("gapped");
1107
1108 let handle = session.export_to(&out);
1109 wait(&handle, Duration::from_secs(900)).expect("export");
1110
1111 // Every frame is there, and the ones over the hole are black.
1112 let (video, _) = engine::demux::Demuxer::open(&out).unwrap();
1113 assert_eq!(
1114 video.frame_count, frames,
1115 "a gap is encoded, not skipped: {} frames for a {timeline:.3}s timeline",
1116 video.frame_count
1117 );
1118 let pictures = decode_all(&out);
1119 assert_eq!(pictures.len() as u32, frames);
1120 let (hole, hole_end) = ((1.0 * FPS) as usize, (2.0 * FPS) as usize);
1121 // Encoded black, so not bit-exact: a mean absolute distance from true black
1122 // well under one code value per channel is what "black" can mean here.
1123 let black = [0u8, 0, 0, 255].repeat(pictures[0].len() / 4);
1124 for (i, picture) in pictures.iter().enumerate() {
1125 let diff = mean_abs_diff(picture, &black);
1126 if (hole..hole_end).contains(&i) {
1127 assert!(
1128 diff < 4.0,
1129 "frame {i} of the gap is not black (MAE {diff:.2})"
1130 );
1131 }
1132 }
1133 let lit = mean_abs_diff(&pictures[0], &black);
1134 assert!(lit > 4.0, "the clips around the gap came out black too");
1135
1136 // The audio track spans the whole timeline in packets: the hole is real
1137 // silent access units, so the bresenham bound the copier promises -- half a
1138 // packet per join, carried through the gap -- covers the gap too.
1139 let file = File::open(&out).unwrap();
1140 let size = file.metadata().unwrap().len();
1141 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
1142 let count = reader.sample_count(2).expect("audio track");
1143 let samples = f64::from(count * 1024);
1144 let wanted = timeline * 44_100.0;
1145 println!("gapped export: {count} packets = {samples} samples for {wanted}");
1146 assert!(
1147 (samples - wanted).abs() < 3.0 * 1024.0,
1148 "audio length {samples} drifted from {wanted} across the gap"
1149 );
1150
1151 // ...and the silence is really silent, where the lift was.
1152 let (_, chunks) = engine::AudioSession::open(&out)
1153 .expect("reopen export audio")
1154 .expect("export has an audio track");
1155 let mut pcm: Vec<f32> = Vec::new();
1156 while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) {
1157 pcm.resize(chunk.start_sample as usize * 2, 0.0);
1158 pcm.extend_from_slice(&chunk.samples);
1159 }
1160 let window = |from: f64, to: f64| {
1161 let (a, b) = ((from * 44_100.0) as usize * 2, (to * 44_100.0) as usize * 2);
1162 pcm[a.min(pcm.len())..b.min(pcm.len())]
1163 .iter()
1164 .fold(0.0f32, |m, s| m.max(s.abs()))
1165 };
1166 // Inside the hole, off its own edges: AAC is lapped, so the packets either
1167 // side of a splice carry a little of their neighbour.
1168 let quiet = window(1.2, 1.8);
1169 assert!(quiet < 1e-3, "the gap is not silent: {quiet}");
1170 assert!(window(0.1, 0.9) > 1e-2, "the sound before it went missing");
1171 assert!(window(2.2, 4.9) > 1e-2, "the sound after it went missing");
1172
1173 std::fs::remove_file(&out).unwrap();
1174}
1175
1176/// The stand-in a proxy really is, in one pass over the fixture: a picture-only
1177/// file whose *every* frame is a decoder's starting point, playable through the
1178/// ordinary session, and found in the cache the second time it is asked for.
1179///
1180/// Software seat, like every default test here ([`pin_software`]) -- what the
1181/// hardware one buys is speed, and that is the ignored test below.
1182#[test]
1183fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() {
1184 let _film = PROXY_FILM.lock().unwrap_or_else(|e| e.into_inner());
1185 let _seat = pin_software();
1186 let source = asset("test_av.mp4");
1187 let out = engine::proxy::path_for(&source).expect("a cache directory");
1188 // A proxy left by an earlier run would make this test assert about a file
1189 // it did not write -- and the cache-hit half below would be the only half
1190 // that ran.
1191 let _ = std::fs::remove_file(&out);
1192
1193 let job = engine::proxy::generate(&source).expect("start the proxy");
1194 assert_eq!(job.path(), out, "the job writes where the key says");
1195 let started = Instant::now();
1196 while !job.is_finished() {
1197 assert!(
1198 started.elapsed() < Duration::from_secs(900),
1199 "the proxy did not finish: {:.0}% in",
1200 job.progress() * 100.0
1201 );
1202 std::thread::sleep(Duration::from_millis(20));
1203 }
1204 let made = job
1205 .outcome()
1206 .expect("a finished job has an outcome")
1207 .expect("the proxy");
1208 assert_eq!(made, out);
1209 assert_eq!(job.progress(), 1.0, "finished at full progress");
1210
1211 let (source_meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture");
1212 let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");
1213 assert_eq!(
1214 (meta.width, meta.height),
1215 engine::proxy::size_for(&source_meta),
1216 "the proxy is coded at the size the rule picked"
1217 );
1218 assert_eq!(meta.codec, engine::Codec::H264, "proxies are H.264");
1219 assert_eq!(
1220 meta.frame_count, source_meta.frame_count,
1221 "a stand-in as long as the film, or every cut lands elsewhere"
1222 );
1223
1224 // The whole point: every frame its own random-access point, so a seek never
1225 // has to start earlier than it was asked to.
1226 let syncs = engine::demux::sync_points(&made);
1227 assert_eq!(
1228 syncs.len() as u32,
1229 meta.frame_count,
1230 "{} of {} frames are starting points -- the proxy is not intra-only",
1231 syncs.len(),
1232 meta.frame_count
1233 );
1234
1235 // ...and no sound in it at all: the mix is the original's, always.
1236 assert!(
1237 engine::AudioSession::open(&made)
1238 .expect("probe the proxy for sound")
1239 .is_none(),
1240 "a proxy carries no audio track"
1241 );
1242
1243 // It plays through the ordinary door, which is what substitution needs.
1244 let session = PlaybackSession::open(&made).expect("play the proxy");
1245 assert_eq!(session.meta().frame_count, source_meta.frame_count);
1246
1247 // ...and a session on the *film* plays it instead once the switch is on,
1248 // while the film is still the only thing the project names -- which is what
1249 // an export reads and why an export can never come off a stand-in.
1250 let mut session = PlaybackSession::open(&source).expect("open the film");
1251 // The film as the project names it: canonical ([`Source::new`]), which the
1252 // proxy key resolves to as well -- the same file under two names is one
1253 // stand-in.
1254 let film = session.sources()[0].path.clone();
1255 assert_eq!(session.picture_path(0), film, "off: the film itself");
1256 session.set_proxies(true);
1257 assert!(session.proxies());
1258 assert_eq!(session.picture_path(0), made, "on: the stand-in");
1259 assert_eq!(
1260 session.sources()[0].path,
1261 film,
1262 "the project still names the film, and that is what an export reads"
1263 );
1264 // A frame really arrives from it: the switch reseeks, so the picture after
1265 // it is the proxy's.
1266 let started = Instant::now();
1267 while session.try_frame().is_none() {
1268 assert!(
1269 started.elapsed() < Duration::from_secs(60),
1270 "no picture after switching to the stand-in"
1271 );
1272 std::thread::sleep(Duration::from_millis(10));
1273 }
1274 session.set_proxies(false);
1275 assert_eq!(session.picture_path(0), film, "and back again");
1276
1277 // The switch survives a save and a load, and a project written before there
1278 // were stand-ins opens on its films.
1279 let project = Scratch::file("ve_proxy_switch", "edith");
1280 session.set_proxies(true);
1281 session.save_project(&project).expect("save");
1282 let text = std::fs::read_to_string(&project).expect("read the project back");
1283 assert!(text.starts_with("edith 23\n"), "{text}");
1284 assert!(text.contains("\nproxy on\n"), "{text}");
1285 let reopened = PlaybackSession::open_project(&project).expect("load");
1286 assert!(reopened.proxies(), "the switch came back on");
1287 assert_eq!(reopened.picture_path(0), made, "and it is substituting");
1288
1289 // Asked again, it is the file already there: no second encode.
1290 let again = engine::proxy::generate(&source).expect("ask again");
1291 assert!(again.is_finished(), "a cached proxy is done on the spot");
1292 assert_eq!(
1293 again
1294 .outcome()
1295 .expect("cached outcome")
1296 .expect("cached path"),
1297 out
1298 );
1299 assert_eq!(engine::proxy::cached(&source), Some(out.clone()));
1300
1301 std::fs::remove_file(&out).expect("clean the cache entry up");
1302 assert_eq!(engine::proxy::cached(&source), None);
1303}
1304
1305/// The way out of a stand-in nobody wants to wait for -- a whole film through a
1306/// decoder and an encoder, started without being asked for, and until now with
1307/// nothing that could stop it.
1308///
1309/// What a stop has to be worth trusting, all of it here: the worker really
1310/// gives up (it settles, so its encoder is closed and its thread is gone), the
1311/// half-written `.part` goes with it, and **nothing is left under the name a
1312/// finished stand-in would have** -- which is the invariant that keeps a cut
1313/// from being made on a truncated picture, since the cache is looked up by
1314/// existence alone ([`engine::proxy::cached`]).
1315///
1316/// ...and the two edges: asking twice is asking once, and a stop that arrives
1317/// on a stand-in *already written* must not take that file away -- it is what
1318/// the switch is at that moment playing.
1319///
1320/// Software seat, like every default test here ([`pin_software`]).
1321#[test]
1322fn a_stopped_proxy_leaves_neither_a_stand_in_nor_half_of_one() {
1323 let _film = PROXY_FILM.lock().unwrap_or_else(|e| e.into_inner());
1324 let _seat = pin_software();
1325 let source = asset("test_av.mp4");
1326 let out = engine::proxy::path_for(&source).expect("a cache directory");
1327 let part = part_path(&out);
1328 // A stand-in left by an earlier run would make this a cache hit, and a
1329 // cache hit is the one job with nothing to stop.
1330 let _ = std::fs::remove_file(&out);
1331 let _ = std::fs::remove_file(&part);
1332
1333 let job = engine::proxy::generate(&source).expect("start the proxy");
1334 // Stopped with the encoder really running: a flag set before the worker has
1335 // opened anything tests the flag and not the stop. Opening costs under a
1336 // second alone, but the sibling exports of this binary can starve it for
1337 // minutes -- the budget is a hang guard, not a speed claim.
1338 let opening = Instant::now();
1339 while job.encoder().is_none() && !job.is_finished() {
1340 assert!(
1341 opening.elapsed() < Duration::from_secs(600),
1342 "the encoder never opened"
1343 );
1344 std::thread::sleep(Duration::from_millis(10));
1345 }
1346 assert!(
1347 !job.is_finished(),
1348 "the fixture finished before it could be stopped: this test needs a film \
1349 the software seat takes a moment over"
1350 );
1351 // Twice, because a second click on the × is a thing that happens.
1352 job.cancel();
1353 job.cancel();
1354 let stopping = Instant::now();
1355 while !job.is_finished() {
1356 assert!(
1357 stopping.elapsed() < Duration::from_secs(120),
1358 "the worker kept encoding after the stop: {:.0}% in",
1359 job.progress() * 100.
1360 );
1361 std::thread::sleep(Duration::from_millis(20));
1362 }
1363 let refusal = job
1364 .outcome()
1365 .expect("a settled job has an outcome")
1366 .err()
1367 .expect("a stopped proxy is not a proxy");
1368 assert!(
1369 refusal.to_string().contains("cancelled"),
1370 "not the cancellation: {refusal}"
1371 );
1372 assert!(
1373 !out.exists(),
1374 "a stopped proxy left {} behind, and the cache is looked up by existence",
1375 out.display()
1376 );
1377 assert!(
1378 !part.exists(),
1379 "a stopped proxy left the half-written {} behind",
1380 part.display()
1381 );
1382 assert_eq!(
1383 engine::proxy::cached(&source),
1384 None,
1385 "the cache offers a stand-in that was never finished"
1386 );
1387 // Past the end it is still idempotent, and the outcome is handed out once.
1388 job.cancel();
1389 assert!(job.outcome().is_none(), "the outcome came out twice");
1390 assert!(!out.exists());
1391
1392 // The other edge, at no cost: a job for a film whose stand-in is already
1393 // written is the cache-hit job, which is exactly what a stop racing the
1394 // last instant of an encode settles into -- and cancelling it must leave
1395 // the file alone, because that file is what the picture is coming off.
1396 std::fs::write(&out, b"a stand-in that is already written").expect("seed the cache");
1397 let hit = engine::proxy::generate(&source).expect("ask again");
1398 assert!(hit.is_finished(), "a cached stand-in is done on the spot");
1399 hit.cancel();
1400 assert!(
1401 out.is_file(),
1402 "a stop deleted a finished stand-in the switch was playing"
1403 );
1404 assert_eq!(engine::proxy::cached(&source), Some(out.clone()));
1405 assert_eq!(
1406 hit.outcome().expect("cached outcome").expect("cached path"),
1407 out,
1408 "the stop turned a finished stand-in into a failure"
1409 );
1410
1411 std::fs::remove_file(&out).expect("clean the cache entry up");
1412}
1413
1414/// The same file on the **hardware** seat, asking the one question the software
1415/// twin above cannot: is what the GPU wrote really every-frame-a-starting-point?
1416///
1417/// It was not, and that is why this test exists. The plugin's ordinary H.264
1418/// seat, asked for a key frame on every picture, codes I slices that are not
1419/// IDRs and carry no parameter sets: a 60-picture proxy came back with **one**
1420/// sync point in it, and a proxy whose seeks are no better than the film's is
1421/// no proxy at all. The seat that answers this is `vh_enc_open_intra`.
1422///
1423/// ```text
1424/// cargo build -p engine-hw --release # its own step: `--tests` leaves it stale
1425/// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \
1426/// -- --ignored --nocapture --test-threads=1 hardware_proxy
1427/// ```
1428#[test]
1429#[ignore = "needs the VA-API plugin"]
1430fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
1431 let _seat = pin_hardware();
1432 let source = asset("test_av.mp4");
1433 let out = engine::proxy::path_for(&source).expect("a cache directory");
1434 let _ = std::fs::remove_file(&out);
1435 let job = engine::proxy::generate(&source).expect("start the proxy");
1436 let started = Instant::now();
1437 while !job.is_finished() {
1438 assert!(
1439 started.elapsed() < Duration::from_secs(900),
1440 "the proxy did not finish"
1441 );
1442 std::thread::sleep(Duration::from_millis(20));
1443 }
1444 let made = job
1445 .outcome()
1446 .expect("a finished job has an outcome")
1447 .expect("the proxy");
1448 let seat = job.encoder().unwrap_or_default();
1449 println!("hardware proxy seat: {seat}");
1450 // The silent-software trap: without the plugin on the path this measures
1451 // the fallback and calls it hardware.
1452 assert!(
1453 seat.contains("HW encode"),
1454 "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin"
1455 );
1456 let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");
1457 let syncs = engine::demux::sync_points(&made);
1458 println!(
1459 "{} of {} frames are starting points",
1460 syncs.len(),
1461 meta.frame_count
1462 );
1463 assert_eq!(
1464 syncs.len() as u32,
1465 meta.frame_count,
1466 "the hardware seat wrote {} starting points in {} frames",
1467 syncs.len(),
1468 meta.frame_count
1469 );
1470 // Counting starting points is not reading the file: a proxy whose every
1471 // access unit is garbage counts perfectly. It shipped that way -- the SPS
1472 // carried a wrapped `log2_max_frame_num_minus4` of 252 and every decoder
1473 // refused the stream, while this test stayed green. So decode it, all of
1474 // it, and let an outside decoder say the same.
1475 let frames = decode_all(&made);
1476 println!(
1477 "decoded back {} of {} pictures",
1478 frames.len(),
1479 meta.frame_count
1480 );
1481 assert_eq!(
1482 frames.len() as u32,
1483 meta.frame_count,
1484 "the proxy demuxes but does not decode"
1485 );
1486 assert!(
1487 frames.iter().all(|f| f.iter().any(|&b| b != 0)),
1488 "a decoded picture came back empty"
1489 );
1490 match ffmpeg_complaints(&made) {
1491 Some(said) => assert!(said.is_empty(), "ffmpeg read the proxy and said:\n{said}"),
1492 None => eprintln!("no ffmpeg: skipping the outside decoder's word on the proxy"),
1493 }
1494 std::fs::remove_file(&out).expect("clean the cache entry up");
1495}
1496
1497/// A real 4K HEVC film, on the hardware seat: a proxy of it is made **faster
1498/// than the film plays**, which is the whole promise -- and a cancel stops it
1499/// dead and leaves nothing behind.
1500///
1501/// Measured over a window rather than to the end: the film is two hours and the
1502/// number wanted is a rate, not a wall time.
1503///
1504/// ```text
1505/// cargo build -p engine-hw --release # its own step: `--tests` leaves it stale
1506/// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \
1507/// -- --ignored --nocapture --test-threads=1 proxy_of_real_4k
1508/// ```
1509#[test]
1510#[ignore = "needs the VA-API plugin and a real library"]
1511fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() {
1512 let _seat = pin_hardware();
1513 let Some(film) = engine::real_library::film("hevc_4k_hdr") else {
1514 return;
1515 };
1516 let out = engine::proxy::path_for(&film).expect("a cache directory");
1517 let _ = std::fs::remove_file(&out);
1518 let (meta, _) = engine::demux::Demuxer::open(&film).expect("open the film");
1519 let duration = f64::from(meta.frame_count) / meta.frame_rate;
1520 println!(
1521 "film: {}x{} {:.3} fps, {duration:.0}s",
1522 meta.width, meta.height, meta.frame_rate
1523 );
1524
1525 let job = engine::proxy::generate(&film).expect("start the proxy");
1526 let window = Duration::from_secs(60);
1527 let started = Instant::now();
1528 while started.elapsed() < window && !job.is_finished() {
1529 std::thread::sleep(Duration::from_millis(200));
1530 }
1531 let elapsed = started.elapsed().as_secs_f64();
1532 let made = f64::from(job.progress()) * duration;
1533 let seat = job.encoder().unwrap_or_default();
1534 println!(
1535 "proxy: {made:.0}s of film in {elapsed:.0}s = {:.2}x realtime, seat {seat}",
1536 made / elapsed
1537 );
1538 // The silent-software trap: a run without the plugin on the path measures
1539 // the fallback and calls it hardware.
1540 assert!(
1541 seat.contains("HW encode"),
1542 "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin"
1543 );
1544 // Twice realtime, not once: the rubric's floor, and the number this seat
1545 // actually measured (2.35x warm, 3.54x with the page cache hot). A `>= 1.0`
1546 // here would let a run at 1.2x -- half the speed this shipped at -- pass as
1547 // green. Cold, the disk is the ceiling instead (~1x on a first pass over an
1548 // uncached remux), so this wants a film the cache has already seen, which
1549 // is what a second run of it is.
1550 assert!(
1551 made / elapsed >= 2.0,
1552 "{:.2}x realtime is under the 2x floor this shipped at",
1553 made / elapsed
1554 );
1555
1556 // Cancel stops the reading, and a proxy that was not finished is not left
1557 // lying around under the name a finished one would have.
1558 job.cancel();
1559 let stopped = Instant::now();
1560 while !job.is_finished() {
1561 assert!(
1562 stopped.elapsed() < Duration::from_secs(120),
1563 "the proxy did not stop when cancelled"
1564 );
1565 std::thread::sleep(Duration::from_millis(50));
1566 }
1567 assert!(job.outcome().expect("an outcome").is_err(), "cancelled");
1568 assert!(
1569 !out.exists(),
1570 "a cancelled proxy left {} behind",
1571 out.display()
1572 );
1573 assert!(
1574 !part_path(&out).exists(),
1575 "a cancelled proxy left its .part"
1576 );
1577 assert_eq!(engine::proxy::cached(&film), None);
1578}
1579
1580// ---------------------------------------------------------------------------
1581// The hardware encoder's process dying under the driver.
1582//
1583// Mesa's radeonsi calls libc `abort()` from its own C worker thread when the
1584// video ring resets under it, which no `catch_unwind` in the process can see:
1585// on 2026-08-13 that killed the editor mid-export and took the session with it.
1586// The encoder now lives in a child (`engine::hwproc`), and these are the proof
1587// that its death is an inconvenience rather than a crash.
1588//
1589// None of them needs a GPU, and that is deliberate: the machine where this
1590// matters is the one whose ring is already wedged, and a test that had to hang a
1591// real ring to run could never be the oracle for the fix. `VE_HW_TEST_FAKE`
1592// opens a stand-in seat in the child that touches no driver;
1593// `VE_HW_TEST_ABORT` / `VE_HW_TEST_HANG` say where it dies or stops.
1594
1595/// The one place in this binary that *changes* the seat rather than reading it,
1596/// so it takes [`SEAT`] exclusively: while it holds, no other export in this
1597/// process is in flight, and every variable it set is gone again before it lets
1598/// go. Which is the whole of the bug this shape exists to make impossible --
1599/// a stand-in encoder seat cycled underneath a software test that had already
1600/// opened its own is a hang, not a failure, and it does not reproduce.
1601///
1602/// It also lifts the software *encode* pin for its own exports, because the
1603/// question here is what an export does when its hardware seat dies. Decode
1604/// stays pinned to software: it is not what is under test and the fixture must
1605/// decode the same way it does everywhere else in this file.
1606fn injected<T>(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T) -> T {
1607 // Short, because one of these is waiting out a child that has stopped
1608 // answering and the wait is the thing under test.
1609 injected_with(abort, hang, Some("1500"), body)
1610}
1611
1612/// The same, with the wait left to the caller: `None` is what a person's own
1613/// editor runs with, which is the one setting none of the tests above ever
1614/// exercised.
1615fn injected_with<T>(
1616 abort: Option<&str>,
1617 hang: Option<&str>,
1618 timeout_ms: Option<&str>,
1619 body: impl FnOnce() -> T,
1620) -> T {
1621 let _exclusive = SEAT
1622 .write()
1623 .unwrap_or_else(|poisoned| poisoned.into_inner());
1624 let restore = std::env::var_os("VE_SW_ENC");
1625 unsafe {
1626 std::env::set_var("VE_SW", "1");
1627 std::env::remove_var("VE_SW_ENC");
1628 std::env::set_var("VE_HW_TEST_FAKE", "1");
1629 std::env::set_var("VE_HW_CHILD_BIN", env!("CARGO_BIN_EXE_hw-encode-child"));
1630 match timeout_ms {
1631 Some(ms) => std::env::set_var("VE_HW_TIMEOUT_MS", ms),
1632 None => std::env::remove_var("VE_HW_TIMEOUT_MS"),
1633 }
1634 match abort {
1635 Some(at) => std::env::set_var("VE_HW_TEST_ABORT", at),
1636 None => std::env::remove_var("VE_HW_TEST_ABORT"),
1637 }
1638 match hang {
1639 Some(at) => std::env::set_var("VE_HW_TEST_HANG", at),
1640 None => std::env::remove_var("VE_HW_TEST_HANG"),
1641 }
1642 }
1643 let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body));
1644 unsafe {
1645 for var in [
1646 "VE_HW_TEST_FAKE",
1647 "VE_HW_CHILD_BIN",
1648 "VE_HW_TIMEOUT_MS",
1649 "VE_HW_TEST_ABORT",
1650 "VE_HW_TEST_HANG",
1651 ] {
1652 std::env::remove_var(var);
1653 }
1654 // Put the software suite's pin back exactly as it was found -- it is
1655 // set once for the whole binary and this is the only thing that ever
1656 // takes it away.
1657 if let Some(pinned) = restore {
1658 std::env::set_var("VE_SW_ENC", pinned);
1659 }
1660 }
1661 match out {
1662 Ok(value) => value,
1663 Err(panic) => std::panic::resume_unwind(panic),
1664 }
1665}
1666
1667/// The timeline these all export: short, and cut, so the export really runs a
1668/// span loop rather than copying one clip.
1669fn short_edit(source: &Path, frames: u32) -> (Project, engine::VideoMeta) {
1670 let (meta, _) = engine::demux::Demuxer::open(source).expect("open source");
1671 let mut project = Project::single(source, meta.frame_count);
1672 assert!(project.split(frames));
1673 assert!(project.delete(1));
1674 assert_eq!(project.timeline_frames(), frames);
1675 (project, meta)
1676}
1677
1678/// A whole export whose hardware encoder is killed three frames in: the editor
1679/// is still here, and so is the file -- written again, from the first frame, by
1680/// the software encoder for the same codec, and clean enough that an outside
1681/// decoder reads every packet of it without a word.
1682///
1683/// Invariant 1 at its entry surface: `export::start` is what the export card
1684/// presses, and this is that same call with a driver dying under it.
1685#[test]
1686fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() {
1687 let source = asset("test_baseline.mp4");
1688 let (project, meta) = short_edit(&source, 20);
1689 let out = out_path("hw_child_abort");
1690
1691 injected(Some("3"), None, || {
1692 // `Auto` is what an untouched export card sends: the seat that *may*
1693 // fall back, which is the whole question here.
1694 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
1695 wait(&handle, Duration::from_secs(180)).expect("the export survived its encoder");
1696 });
1697
1698 let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1699 assert_eq!(written.frame_count, 20, "every timeline frame was written");
1700 assert_eq!(decode_all(&out).len(), 20, "and every one of them decodes");
1701 if let Some(said) = ffmpeg_complaints(&out) {
1702 assert!(
1703 said.is_empty(),
1704 "ffmpeg read the fallback's file badly: {said}"
1705 );
1706 }
1707 assert!(!part_path(&out).exists(), "the .part outlived the export");
1708 std::fs::remove_file(&out).unwrap();
1709}
1710
1711/// ...and the bar over that same death only ever goes forwards. The rerun is a
1712/// whole second pass over the timeline, so the one thing a person must not see
1713/// is the progress they watched fill drop back to zero: it holds at the mark the
1714/// dead seat reached and moves on from there, ending exactly full.
1715#[test]
1716fn a_hardware_encoder_killed_mid_export_never_pulls_the_bar_backwards() {
1717 let source = asset("test_baseline.mp4");
1718 let (project, meta) = short_edit(&source, 20);
1719 let out = out_path("hw_child_abort_progress");
1720
1721 let seen = injected(Some("3"), None, || {
1722 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
1723 // Sampled far faster than the export writes, so the retry cannot slip
1724 // through between two reads.
1725 let started = Instant::now();
1726 let mut seen = vec![handle.progress()];
1727 while !handle.is_finished() {
1728 assert!(
1729 started.elapsed() < Duration::from_secs(180),
1730 "export did not finish"
1731 );
1732 let now = handle.progress();
1733 if now != *seen.last().unwrap() {
1734 seen.push(now);
1735 }
1736 std::thread::sleep(Duration::from_millis(1));
1737 }
1738 handle
1739 .result()
1740 .expect("a finished export has an outcome")
1741 .expect("the export survived its encoder");
1742 seen.push(handle.progress());
1743 seen
1744 });
1745
1746 assert!(
1747 seen.windows(2).all(|pair| pair[1] >= pair[0]),
1748 "the bar went backwards across the fallback: {seen:?}"
1749 );
1750 assert_eq!(
1751 seen.last().copied(),
1752 Some(1.0),
1753 "a finished export leaves a full bar: {seen:?}"
1754 );
1755 std::fs::remove_file(&out).unwrap();
1756}
1757
1758/// Threads of this very process that belong to an audio pass. Every worker the
1759/// pass starts inherits its name from the thread that spawned it (Linux `comm`
1760/// is inherited), so this is the pass *and its own workers* -- which is what
1761/// makes it a measure of how many passes are running: two at once is twice the
1762/// crowd of one.
1763fn audio_pass_threads() -> usize {
1764 std::fs::read_dir("/proc/self/task")
1765 .into_iter()
1766 .flatten()
1767 .flatten()
1768 .filter(|thread| {
1769 std::fs::read_to_string(thread.path().join("comm"))
1770 .is_ok_and(|name| name.trim() == "export-audio")
1771 })
1772 .count()
1773}
1774
1775/// The busiest that crowd ever gets while `export` writes this project.
1776fn busiest_audio_pass(project: Project, meta: engine::VideoMeta, out: &Path) -> usize {
1777 let handle = engine::export::start(project, meta, out, &ExportSettings::default(), None);
1778 let started = Instant::now();
1779 let mut most = 0;
1780 while !handle.is_finished() {
1781 assert!(
1782 started.elapsed() < Duration::from_secs(180),
1783 "export did not finish"
1784 );
1785 most = most.max(audio_pass_threads());
1786 std::thread::sleep(Duration::from_millis(1));
1787 }
1788 handle
1789 .result()
1790 .expect("a finished export has an outcome")
1791 .expect("the export was written");
1792 most
1793}
1794
1795/// One audio pass at a time, across that same death. An mp4 runs the sound
1796/// beside the picture, and the picture's failure used to leave that thread
1797/// *detached*: the re-run started a second pass, and a machine that had just
1798/// lost its GPU mixed and encoded the same film's sound twice at once. Measured
1799/// against the same export with nothing dying under it -- the fallback may not
1800/// be a busier place than an ordinary export is.
1801#[test]
1802fn a_hardware_encoder_killed_mid_export_leaves_no_audio_pass_behind() {
1803 // AC-3: an mp4 cannot carry it, so the pass is a real decode and encode
1804 // rather than the packet copy an AAC source is over in a millisecond.
1805 let source = asset("test_ac3.mp4");
1806 let out = out_path("hw_child_abort_audio");
1807
1808 let (project, meta) = short_edit(&source, 40);
1809 let alone = {
1810 let _seat = pin_software();
1811 busiest_audio_pass(project, meta, &out)
1812 };
1813 std::fs::remove_file(&out).unwrap();
1814
1815 let (project, meta) = short_edit(&source, 40);
1816 let across = injected(Some("3"), None, || busiest_audio_pass(project, meta, &out));
1817
1818 println!("audio pass threads: {alone} alone, {across} across the fallback");
1819 assert!(
1820 across <= alone,
1821 "the fallback ran {across} audio-pass threads where one pass runs {alone}"
1822 );
1823 let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1824 assert_eq!(written.frame_count, 40, "every timeline frame was written");
1825 std::fs::remove_file(&out).unwrap();
1826}
1827
1828/// What a *shipping* editor waits when its child stops answering. Every test
1829/// here pins `VE_HW_TIMEOUT_MS` at 1.5 s, so none of them ever ran the 15 s
1830/// default -- fifteen seconds an export spends on a child that will never
1831/// answer again, before the software encoder it is owed can even begin.
1832///
1833/// The ceiling stays where it is, because an encoder opening on a 4K frame is
1834/// not a dead one. What changes is that a child which has answered its first
1835/// frames has *said* what its frames cost, and from then on the wait is that
1836/// measure and not the ceiling.
1837#[test]
1838fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() {
1839 let (width, height) = (320u32, 240u32);
1840 // No `VE_HW_TIMEOUT_MS` at all: the wait is the one a person's export gets.
1841 injected_with(None, Some("10"), None, || {
1842 let mut encoder =
1843 HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened");
1844 let (y, u, v) = synthetic(0, width as usize, height as usize);
1845 for frame in 0..10 {
1846 assert!(
1847 encoder.encode(&y, &u, &v, width, height, false).is_ok(),
1848 "picture {frame} is before the wedge"
1849 );
1850 }
1851 let started = Instant::now();
1852 let wedged = encoder
1853 .encode(&y, &u, &v, width, height, false)
1854 .expect_err("a child that stops answering is not an encode");
1855 let waited = started.elapsed();
1856 println!("wedge at the shipping default: contained in {waited:.2?}");
1857 assert!(engine::hwproc::is_lost(&wedged), "{wedged}");
1858 assert!(
1859 waited < Duration::from_secs(6),
1860 "waited {waited:.2?} on a wedged child at the shipping default"
1861 );
1862 // ...and never so little that a slow picture could be mistaken for a
1863 // dead one: the floor holds even where every measured frame was
1864 // instant, which the stand-in encoder's are.
1865 assert!(waited >= Duration::from_secs(2), "waited only {waited:.2?}");
1866 });
1867}
1868
1869/// The same death at the *open*: the child never gets far enough to say yes, so
1870/// there is no hardware seat at all and the software one takes the export from
1871/// the first frame. A refusal, not a crash, and the file is whole.
1872#[test]
1873fn a_hardware_encoder_killed_at_its_open_is_simply_no_seat() {
1874 let source = asset("test_baseline.mp4");
1875 let (project, meta) = short_edit(&source, 12);
1876 let out = out_path("hw_child_abort_init");
1877
1878 injected(Some("init"), None, || {
1879 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
1880 wait(&handle, Duration::from_secs(180)).expect("the export survived the open");
1881 });
1882
1883 let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1884 assert_eq!(written.frame_count, 12);
1885 std::fs::remove_file(&out).unwrap();
1886}
1887
1888/// ...and at the finalize, which is the third place a ring resets: every
1889/// picture is fed and the encoder is being flushed when it dies.
1890#[test]
1891fn a_hardware_encoder_killed_at_the_drain_costs_the_file_nothing() {
1892 let source = asset("test_baseline.mp4");
1893 let (project, meta) = short_edit(&source, 12);
1894 let out = out_path("hw_child_abort_drain");
1895
1896 injected(Some("drain"), None, || {
1897 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
1898 wait(&handle, Duration::from_secs(180)).expect("the export survived the drain");
1899 });
1900
1901 let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1902 assert_eq!(written.frame_count, 12);
1903 assert_eq!(decode_all(&out).len(), 12);
1904 std::fs::remove_file(&out).unwrap();
1905}
1906
1907/// Invariant 4: a ring can wedge *without* anything dying -- the child stays
1908/// alive and simply stops answering. The parent gives it `VE_HW_TIMEOUT_MS` and
1909/// then kills it, which lands on the same fallback a death does. "Contained"
1910/// here means bounded, so the wait is what is really being measured: an export
1911/// that sat on a stuck child forever would be the hang this refuses.
1912#[test]
1913fn a_hardware_encoder_that_stops_answering_is_killed_and_replaced() {
1914 let source = asset("test_baseline.mp4");
1915 let (project, meta) = short_edit(&source, 12);
1916 let out = out_path("hw_child_hang");
1917
1918 let started = Instant::now();
1919 injected(None, Some("2"), || {
1920 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
1921 wait(&handle, Duration::from_secs(180)).expect("the export outlived the wedge");
1922 });
1923 println!(
1924 "hung child: contained in {:.2} s",
1925 started.elapsed().as_secs_f64()
1926 );
1927
1928 let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1929 assert_eq!(written.frame_count, 12);
1930 assert_eq!(decode_all(&out).len(), 12);
1931 std::fs::remove_file(&out).unwrap();
1932}
1933
1934/// ...and the export that does **not** get written again: a person who picked
1935/// the GPU on the export card asked for it by name, so a dead hardware seat is
1936/// refused in words rather than answered with an hour in an encoder nobody
1937/// chose. The same posture [`engine::export::start`] already takes for a machine
1938/// with no hardware seat at all -- and the guard that separates the two is the
1939/// one every test above depends on being narrow.
1940///
1941/// The process is alive either way, which is the invariant; what differs is who
1942/// is told.
1943#[test]
1944fn an_export_that_asked_for_the_gpu_by_name_refuses_instead_of_falling_back() {
1945 let source = asset("test_baseline.mp4");
1946 let (project, meta) = short_edit(&source, 12);
1947 let out = out_path("hw_child_named_seat");
1948
1949 let error = injected(Some("2"), None, || {
1950 let settings = ExportSettings {
1951 seat: engine::export::EncoderSeat::Hardware,
1952 ..Default::default()
1953 };
1954 let handle = engine::export::start(project, meta, &out, &settings, None);
1955 wait(&handle, Duration::from_secs(180))
1956 .expect_err("a named hardware seat that died is not written again in software")
1957 });
1958
1959 println!("named hardware seat: {error}");
1960 assert!(
1961 engine::hwproc::is_lost(&error),
1962 "the refusal has to name the hardware failure: {error}"
1963 );
1964 assert!(
1965 !out.exists(),
1966 "a refused export still wrote {}",
1967 out.display()
1968 );
1969 assert!(!part_path(&out).exists(), "the .part outlived the refusal");
1970}
1971
1972/// The seat's own contract, under the same injection and with no export around
1973/// it: a killed child comes back as an error carrying
1974/// [`engine::hwproc::HW_LOST`], every later call gives the same answer instead
1975/// of blocking on a socket nobody holds, and the process doing the asking is
1976/// still running to be asked.
1977#[test]
1978fn a_dead_encoder_answers_every_later_call_the_same_way() {
1979 let (width, height) = (320u32, 240u32);
1980 injected(Some("1"), None, || {
1981 let mut encoder =
1982 HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened");
1983 let (y, u, v) = synthetic(0, width as usize, height as usize);
1984 assert!(
1985 encoder.encode(&y, &u, &v, width, height, false).is_ok(),
1986 "the first picture is before the injection point"
1987 );
1988 let died = encoder
1989 .encode(&y, &u, &v, width, height, false)
1990 .expect_err("the second picture kills the child");
1991 assert!(
1992 engine::hwproc::is_lost(&died),
1993 "an encoder death must say so: {died}"
1994 );
1995 // The second ask is the one that would hang if the child were not
1996 // reaped, and it must not spend the timeout answering either.
1997 let again = Instant::now();
1998 let repeat = encoder.drain().expect_err("the seat stays dead");
1999 assert!(engine::hwproc::is_lost(&repeat), "{repeat}");
2000 assert!(
2001 again.elapsed() < Duration::from_millis(500),
2002 "a dead seat answered only after waiting"
2003 );
2004 });
2005}
2006
2007/// A whole-clip template on one source: the shape `exports_the_audio_stream_
2008/// the_timeline_plays` builds, parameterised by the fade and the length the
2009/// clip claims.
2010fn one_source_clip(source: &Path, fade_in: u32, out_frame: u32) -> (Project, engine::VideoMeta) {
2011 let (meta, _) = engine::demux::Demuxer::open(source).expect("open the fixture");
2012 let whole = engine::Clip {
2013 fade_in,
2014 fade_out: 0,
2015 transition_out: 0,
2016 visualizer: 0,
2017 viz_paint: 0,
2018 start: 0,
2019 in_frame: 0,
2020 out_frame,
2021 source: 0,
2022 link: Some(0),
2023 eq: None,
2024 color: None,
2025 transform: None,
2026 fit: FitPolicy::default(),
2027 speed: Speed::NORMAL,
2028 };
2029 let project = Project::from_parts(
2030 vec![Source {
2031 path: source.to_path_buf(),
2032 audio_stream: 0,
2033 }],
2034 vec![
2035 (engine::project::LaneKind::Video, vec![whole.clone()]),
2036 (engine::project::LaneKind::Audio, vec![whole]),
2037 ],
2038 Vec::new(),
2039 Vec::new(),
2040 Vec::new(),
2041 )
2042 .expect("a one-source project");
2043 (project, meta)
2044}
2045
2046/// Interleaved-stereo RMS of `samples`.
2047fn rms(samples: &[f32]) -> f64 {
2048 let sum: f64 = samples
2049 .chunks_exact(2)
2050 .map(|c| f64::from(c[0]) * f64::from(c[0]) + f64::from(c[1]) * f64::from(c[1]))
2051 .sum();
2052 (sum / samples.len().max(1) as f64).sqrt()
2053}
2054
2055/// D1: a fade is gain on decoded samples, which a packet copy cannot carry --
2056/// so a clip with a fade must leave through the encode even where the rest of
2057/// the timeline could copy, and the fade must reach the file: the head of the
2058/// output ramps in by the fade's own dB, where a copy writes the source flat.
2059#[test]
2060fn a_faded_clip_encodes_and_the_fade_reaches_the_file() {
2061 let _seat = pin_software();
2062 let source = asset("test_multiaudio.mp4"); // flat -21 dB tone, 60 frames
2063 let (project, meta) =
2064 one_source_clip(&source, (FPS * 3.0 / 2.0) as u32, meta_frame_count(&source));
2065 let out = out_path("faded");
2066 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2067 wait(&handle, Duration::from_secs(600)).expect("export");
2068
2069 let line = handle.encoders().expect("the seats were published");
2070 assert!(
2071 line.contains("ec-aac"),
2072 "the sound left through the copy, not the encode: {line}"
2073 );
2074
2075 let (audio, rx) = engine::AudioSession::open(&out)
2076 .expect("reopen export audio")
2077 .expect("the export has audio");
2078 // Quarter of a second of interleaved stereo, and the fade-in is 1.5 s of
2079 // an equal-power ramp ([`engine::project::Fade::gain_at`]'s `sin`), so the
2080 // windows below sit deep in the ramp, either side of where it ends, and
2081 // past it.
2082 let quarter = audio.sample_rate as usize * 2 / 4;
2083 let mut samples = Vec::new();
2084 for chunk in rx {
2085 samples.extend_from_slice(&chunk.samples);
2086 }
2087 let envelope: Vec<f64> = samples.chunks_exact(quarter).take(6).map(rms).collect();
2088 let flat = rms(&samples[samples.len() - quarter..]);
2089 assert!(
2090 flat > 0.05,
2091 "the fixture's own tone is not in the file at all: tail rms {flat}"
2092 );
2093 assert!(
2094 envelope[0] < 0.4 * flat,
2095 "the fade-in is absent -- a copy writes the source flat: {envelope:?} against {flat}"
2096 );
2097 assert!(
2098 envelope[0] > 0.02 * flat,
2099 "the head is silence, so what is missing is the sound, not the fade: {envelope:?}"
2100 );
2101 assert!(
2102 envelope[..4].windows(2).all(|w| w[1] > w[0]),
2103 "the level does not ramp through the fade's own 1.5 s: {envelope:?}"
2104 );
2105 assert!(
2106 (envelope[4] - flat).abs() < 0.15 * flat && (envelope[5] - flat).abs() < 0.15 * flat,
2107 "the ramp never reaches unity past the fade, so this is not it: {envelope:?} against {flat}"
2108 );
2109 std::fs::remove_file(&out).unwrap();
2110}
2111
2112fn meta_frame_count(source: &Path) -> u32 {
2113 engine::demux::Demuxer::open(source)
2114 .expect("open the fixture")
2115 .0
2116 .frame_count
2117}
2118
2119/// D4: a clip asking for more pictures than its file has used to end the span
2120/// with no notice -- the export completed as if the whole edit were in the
2121/// file. The seat line now carries the count.
2122#[test]
2123fn a_clip_that_outlives_its_source_says_so_on_the_card() {
2124 let _seat = pin_software();
2125 let source = asset("test_multiaudio.mp4"); // 60 frames
2126 let count = meta_frame_count(&source);
2127 let (project, meta) = one_source_clip(&source, 0, count + 40);
2128 let out = out_path("truncated");
2129 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2130 wait(&handle, Duration::from_secs(600)).expect("export");
2131 let line = handle.encoders().expect("the seats were published");
2132 assert!(
2133 line.contains("40 frames of the edit past the last picture"),
2134 "the truncation is silent: {line}"
2135 );
2136 std::fs::remove_file(&out).unwrap();
2137}
2138
2139/// Two whole-clip spans of one source, both lanes: an edit whose first take is
2140/// short and whose second one is whole. Both clips read the file from its own
2141/// first frame, so the walk keeps two spans rather than fusing them into one
2142/// window -- a span is continued only where the source window continues.
2143fn two_clip_edit(source: &Path, first: u32, second: u32) -> (Project, engine::VideoMeta) {
2144 let (meta, _) = engine::demux::Demuxer::open(source).expect("open the fixture");
2145 let clip = |start: u32, out_frame: u32| engine::Clip {
2146 fade_in: 0,
2147 fade_out: 0,
2148 transition_out: 0,
2149 visualizer: 0,
2150 viz_paint: 0,
2151 start,
2152 in_frame: 0,
2153 out_frame,
2154 source: 0,
2155 link: None,
2156 eq: None,
2157 color: None,
2158 transform: None,
2159 fit: FitPolicy::default(),
2160 speed: Speed::NORMAL,
2161 };
2162 let clips = vec![clip(0, first), clip(first, second)];
2163 let project = Project::from_parts(
2164 vec![Source {
2165 path: source.to_path_buf(),
2166 audio_stream: 0,
2167 }],
2168 vec![
2169 (engine::project::LaneKind::Video, clips.clone()),
2170 (engine::project::LaneKind::Audio, clips),
2171 ],
2172 Vec::new(),
2173 Vec::new(),
2174 Vec::new(),
2175 )
2176 .expect("a two-clip project");
2177 (project, meta)
2178}
2179
2180/// D4, the half the single-clip test cannot see: the walk carries on with the
2181/// spans *after* a file runs out, so what went missing is that span's own tail
2182/// and not everything the edit still had. Counting the rest would put 100 on
2183/// the line for a file that holds 120 of the edit's 160 pictures.
2184#[test]
2185fn a_two_clip_timeline_reports_only_the_pictures_that_were_skipped() {
2186 let _seat = pin_software();
2187 let source = asset("test_multiaudio.mp4"); // 60 frames
2188 let count = meta_frame_count(&source);
2189 // The first take asks for 40 pictures the file has not got; the second one
2190 // is whole and is written after the break.
2191 let (project, meta) = two_clip_edit(&source, count + 40, count);
2192 let out = out_path("truncated_two_clip");
2193 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2194 wait(&handle, Duration::from_secs(900)).expect("export");
2195 let line = handle.encoders().expect("the seats were published");
2196 assert!(
2197 line.contains("40 frames of the edit past the last picture"),
2198 "the notice counts more than the file lost: {line}"
2199 );
2200 // ...and the file really holds both spans' pictures, which is what makes
2201 // this the count of a tail and not of the whole rest of the edit: 60 of the
2202 // short take plus all 60 of the second one.
2203 assert_eq!(
2204 decode_all(&out).len(),
2205 (count * 2) as usize,
2206 "the span after the break was not written"
2207 );
2208 std::fs::remove_file(&out).unwrap();
2209}
2210
2211/// D4's control: an edit whose every span ends on a picture its file really has
2212/// carries no notice at all -- the count must never be invented.
2213#[test]
2214fn a_healthy_two_clip_timeline_carries_no_truncation_notice() {
2215 let _seat = pin_software();
2216 let source = asset("test_multiaudio.mp4"); // 60 frames
2217 let count = meta_frame_count(&source);
2218 let (project, meta) = two_clip_edit(&source, count, count);
2219 let out = out_path("truncated_control");
2220 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2221 wait(&handle, Duration::from_secs(900)).expect("export");
2222 let line = handle.encoders().expect("the seats were published");
2223 let notice = line.contains("past the last picture");
2224 assert_eq!(
2225 notice, false,
2226 "a whole export says it was truncated: {line}"
2227 );
2228 assert_eq!(
2229 decode_all(&out).len(),
2230 (count * 2) as usize,
2231 "both spans were written"
2232 );
2233 std::fs::remove_file(&out).unwrap();
2234}
2235
2236/// D3: the catch_unwind branch settled the worker's slot but left the `.part`
2237/// on disk, against the module promise that every error path deletes it. The
2238/// panic is injected at the first coded picture, so the `.part` is provably
2239/// on disk when the worker dies.
2240#[test]
2241fn a_panicking_worker_deletes_the_part_file() {
2242 let _exclusive = SEAT.write().unwrap_or_else(|p| p.into_inner());
2243 let source = asset("test_baseline.mp4");
2244 let (project, meta) = short_edit(&source, 20);
2245 let out = out_path("panic");
2246 let part = part_path(&out);
2247 unsafe {
2248 std::env::set_var("VE_EXPORT_TEST_PANIC", part.as_os_str().to_owned());
2249 }
2250 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
2251 let result = wait(&handle, Duration::from_secs(120));
2252 unsafe {
2253 std::env::remove_var("VE_EXPORT_TEST_PANIC");
2254 }
2255 let error = result.expect_err("the injected panic is the outcome");
2256 assert!(
2257 error.to_string().contains("export worker panicked"),
2258 "the panic is the outcome: {error}"
2259 );
2260 assert!(!out.exists(), "a panicked export wrote {}", out.display());
2261 assert!(!part.exists(), "the .part outlived the panic");
2262}