forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf2bee6bTahinli2 months ago781 commits

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