forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

export.rs771 lines, 30.1 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 -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//! Both env pins are process-wide, hence `--test-threads=1` for the ignored run.
15
16use std::fs::File;
17use std::io::BufReader;
18use std::path::{Path, PathBuf};
19use std::sync::Once;
20use std::time::{Duration, Instant};
21
22use engine::export::ExportSettings;
23use engine::hw::HwEncoder;
24use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
25use engine::project::Lane;
26use engine::project::Source;
27use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
28
29const FPS: f64 = 30.0;
30
31fn asset(name: &str) -> PathBuf {
32 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
33 .join("../../assets")
34 .join(name)
35}
36
37/// Per-run unique: two suite runs at once (a release sweep beside a debug one,
38/// or two agents) would otherwise write and delete each other's export.
39fn out_path(name: &str) -> PathBuf {
40 let path = std::env::temp_dir().join(format!("ve_export_{name}_{}.mp4", std::process::id()));
41 let _ = std::fs::remove_file(&path);
42 let _ = std::fs::remove_file(part_path(&path));
43 path
44}
45
46/// What the worker actually writes to until it succeeds; the engine appends the
47/// suffix rather than replacing the extension.
48fn part_path(out: &Path) -> PathBuf {
49 PathBuf::from(format!("{}.part", out.display()))
50}
51
52/// Pins both paths to software for the whole test binary, so the default suite
53/// proves the fallback that every machine has.
54fn pin_software() {
55 static PIN: Once = Once::new();
56 PIN.call_once(|| unsafe {
57 std::env::set_var("VE_SW", "1");
58 std::env::set_var("VE_SW_ENC", "1");
59 });
60}
61
62/// Removes both pins, for the hardware twins.
63fn pin_hardware() {
64 static PIN: Once = Once::new();
65 PIN.call_once(|| unsafe {
66 std::env::remove_var("VE_SW");
67 std::env::remove_var("VE_SW_ENC");
68 });
69}
70
71/// `[0,30) + [60,150)` of the source: two cuts and a delete, so the export has
72/// to seek, and the join is a real discontinuity rather than a formality.
73fn edited(source: &Path) -> PlaybackSession {
74 let mut session = PlaybackSession::open(source).expect("open source");
75 assert!(session.cut_at(30.0 / FPS), "cut at frame 30");
76 assert!(session.cut_at(60.0 / FPS), "cut at frame 60");
77 assert!(session.delete_clip(1), "drop the middle clip");
78 assert_eq!(session.clip_spans().len(), 2);
79 session
80}
81
82fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
83 let started = Instant::now();
84 while !handle.is_finished() {
85 assert!(
86 started.elapsed() < limit,
87 "export did not finish in {limit:?}"
88 );
89 std::thread::sleep(Duration::from_millis(20));
90 }
91 handle.result().expect("a finished export has an outcome")
92}
93
94/// Every frame of `path`, BGRA, in timeline order.
95fn decode_all(path: &Path) -> Vec<Vec<u8>> {
96 let (_, frames) = DecodeSession::open(path).expect("open export");
97 frames.into_iter().map(|frame| frame.bgra).collect()
98}
99
100/// One frame of `path` by absolute index.
101fn frame_at(path: &Path, index: u32) -> Vec<u8> {
102 let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source");
103 frames.recv().expect("frame present").bgra
104}
105
106fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
107 assert_eq!(a.len(), b.len(), "frame sizes differ");
108 a.iter()
109 .zip(b)
110 .map(|(x, y)| f64::from(x.abs_diff(*y)))
111 .sum::<f64>()
112 / a.len() as f64
113}
114
115/// The whole point of the slice: an edited timeline survives the trip out to
116/// disk and back, frame for frame and picture for picture.
117fn round_trip(name: &str, limit: Duration) {
118 let source = asset("test_baseline.mp4");
119 let mut session = edited(&source);
120 session.pause();
121 let out = out_path(name);
122
123 let started = Instant::now();
124 let handle = session.export_to(&out);
125 wait(&handle, limit).expect("export");
126 let spent = started.elapsed();
127 println!(
128 "{name}: 120 frames in {:.2} s = {:.2} ms/frame",
129 spent.as_secs_f64(),
130 spent.as_secs_f64() * 1000.0 / 120.0
131 );
132 assert_eq!(handle.progress(), 1.0, "finished at full progress");
133
134 let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen export");
135 assert_eq!(meta.frame_count, 120, "timeline frames written");
136 assert_eq!((meta.width, meta.height), (1280, 720));
137 assert_eq!(meta.frame_rate.round(), FPS);
138
139 let file = File::open(&out).unwrap();
140 let size = file.metadata().unwrap().len();
141 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
142 let duration = reader.duration().as_secs_f64();
143 assert!(
144 (duration - 120.0 / FPS).abs() <= 1.0 / FPS,
145 "duration {duration} s is more than a frame off 4.0 s"
146 );
147
148 let frames = decode_all(&out);
149 assert_eq!(frames.len(), 120, "every written frame decodes back");
150
151 // Timeline -> source: [0,30) maps to itself, [30,120) to [60,150).
152 for (timeline, source_frame) in [(0u32, 0u32), (59, 89), (119, 149)] {
153 let diff = mean_abs_diff(&frames[timeline as usize], &frame_at(&source, source_frame));
154 println!("timeline {timeline} vs source {source_frame}: mean abs diff {diff:.2}");
155 assert!(
156 diff < 6.0,
157 "timeline frame {timeline} drifted by {diff:.2} from source frame {source_frame}"
158 );
159 }
160 std::fs::remove_file(&out).unwrap();
161}
162
163#[test]
164fn exports_an_edited_timeline_in_software() {
165 pin_software();
166 round_trip("sw", Duration::from_secs(120));
167}
168
169/// Same trip through the plugin, and the only place the end-to-end hardware
170/// cost (decode + encode + mux) is measured.
171#[test]
172#[ignore]
173fn exports_an_edited_timeline_in_hardware() {
174 pin_hardware();
175 round_trip("hw", Duration::from_secs(60));
176}
177
178/// The trap this slice exists to close: a timeline playing a file's *second*
179/// audio stream must export that stream's packets. Playing one stream and
180/// exporting another is a file that sounds nothing like what was edited, and
181/// nothing in it would say so -- so the check is the copied bytes, not just the
182/// header. Software only: the picture is beside the point here.
183#[test]
184fn exports_the_audio_stream_the_timeline_plays() {
185 pin_software();
186 let multi = asset("test_multiaudio.mp4");
187 let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture");
188 let whole = engine::Clip {
189 start: 0,
190 in_frame: 0,
191 out_frame: meta.frame_count,
192 source: 0,
193 link: Some(0),
194 };
195 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
196 // stereo. A project may only hold streams that agree, so this timeline is
197 // stream 1 alone -- which is exactly what an export must carry.
198 let project = Project::from_parts(
199 vec![Source {
200 path: multi.clone(),
201 audio_stream: 1,
202 }],
203 vec![whole],
204 vec![whole],
205 )
206 .expect("a one-source project on stream 1");
207 let out = out_path("stream1");
208 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
209 wait(&handle, Duration::from_secs(120)).expect("export");
210
211 let (audio, _) = engine::AudioSession::open(&out)
212 .expect("reopen export audio")
213 .expect("the export has audio");
214 assert_eq!(
215 (audio.sample_rate, audio.channels),
216 (22_050, 1),
217 "the export carries stream 0's parameters, not the stream that played"
218 );
219
220 // Byte for byte: the exported track is the copy of stream 1, and it is not
221 // the copy of stream 0 -- the second assert is what makes the first one
222 // mean something.
223 let segs = [(Some(0), 0.0, f64::from(meta.frame_count) / FPS)];
224 let copy = |stream| {
225 engine::AudioSession::copy_multi_streams(&[(multi.clone(), stream)], &segs)
226 .expect("copy")
227 .expect("has audio")
228 .1
229 .into_iter()
230 .map(|p| p.bytes)
231 .collect::<Vec<_>>()
232 };
233 let (one, zero) = (copy(1), copy(0));
234 assert_ne!(one, zero, "the two streams are not the same bytes");
235
236 let file = File::open(&out).unwrap();
237 let size = file.metadata().unwrap().len();
238 let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
239 let track = *reader
240 .tracks()
241 .keys()
242 .find(|id| reader.sample_count(**id).unwrap_or(0) as usize == one.len())
243 .unwrap_or(&2);
244 let written: Vec<Vec<u8>> = (1..=reader.sample_count(track).expect("audio track"))
245 .map(|id| {
246 reader
247 .read_sample(track, id)
248 .expect("sample")
249 .expect("present")
250 .bytes
251 .to_vec()
252 })
253 .collect();
254 assert_eq!(written, one, "the exported packets are stream 1's");
255 std::fs::remove_file(&out).unwrap();
256}
257
258/// `test_av[0,120)` then the whole of `test_av2`: the last second of the first
259/// source is deleted, so timeline frame 120 is both a cut and a file change --
260/// the join the multi-source export exists for.
261fn two_sources() -> Project {
262 let (av, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open test_av");
263 let (av2, _) = engine::demux::Demuxer::open(&asset("test_av2.mp4")).expect("open test_av2");
264 assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a");
265
266 let mut project = Project::single(asset("test_av.mp4"), av.frame_count);
267 let second = project.import(asset("test_av2.mp4"), 0);
268 assert_eq!(second, 1, "a second file is a second source");
269 assert!(project.append_clip(second, av2.frame_count));
270 assert!(project.split(120), "cut a second before the end of test_av");
271 assert!(project.delete(1), "drop test_av's tail");
272 assert_eq!(project.timeline_frames(), 120 + av2.frame_count);
273 assert_eq!(
274 project.clips().iter().map(|c| c.source).collect::<Vec<_>>(),
275 vec![0, 1]
276 );
277 project
278}
279
280/// A timeline spanning two files exports as one: every clip is decoded from its
281/// own source, the audio is copied across the join, and the result reopens as a
282/// single stream whose frame at the join is the second file's first frame.
283fn multi_source_round_trip(name: &str, limit: Duration) {
284 let project = two_sources();
285 let total = project.timeline_frames();
286 let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap();
287 let out = out_path(name);
288
289 let started = Instant::now();
290 let handle = engine::export::start(project.clone(), meta, &out, &ExportSettings::default());
291 wait(&handle, limit).expect("export");
292 println!(
293 "{name}: {total} frames of two sources in {:.2} s",
294 started.elapsed().as_secs_f64()
295 );
296
297 let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen export");
298 assert_eq!(written.frame_count, total, "timeline frames written");
299 assert_eq!((written.width, written.height), (1280, 720));
300
301 let frames = decode_all(&out);
302 assert_eq!(
303 frames.len() as u32,
304 total,
305 "every written frame decodes back"
306 );
307 // The join: timeline 120 is test_av2's frame 0, timeline 119 still test_av's.
308 for (timeline, source, source_frame) in [
309 (0u32, "test_av.mp4", 0u32),
310 (119, "test_av.mp4", 119),
311 (120, "test_av2.mp4", 0),
312 (total - 1, "test_av2.mp4", total - 121),
313 ] {
314 let diff = mean_abs_diff(
315 &frames[timeline as usize],
316 &frame_at(&asset(source), source_frame),
317 );
318 println!("timeline {timeline} vs {source} {source_frame}: mean abs diff {diff:.2}");
319 assert!(
320 diff < 6.0,
321 "timeline frame {timeline} drifted by {diff:.2} from {source} frame {source_frame}"
322 );
323 }
324
325 // Audio across the join: 1 + 172 + 173. Both segments ask for 4.0 s =
326 // 172.27 packets, and the head is test_av's own priming packet (the first
327 // segment's alone -- the join must not add a second one). The first segment
328 // copies 172 and owes 272 samples, and it is that *carried* debt that makes
329 // the second copy 173: rounding each source on its own would give 345, so
330 // this number is the proof the accumulator survives a source change.
331 let file = File::open(&out).unwrap();
332 let size = file.metadata().unwrap().len();
333 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
334 let packets = reader.sample_count(2).expect("audio track");
335 assert_eq!(packets, 346, "packet total across the source join");
336 let wanted = f64::from(total) / FPS * 44_100.0;
337 assert!(
338 (f64::from(packets * 1024) - wanted).abs() < 3.0 * 1024.0,
339 "audio length {} samples drifted from {wanted}",
340 packets * 1024
341 );
342 let (audio, _) = engine::AudioSession::open(&out)
343 .expect("reopen export audio")
344 .expect("export has an audio track");
345 assert_eq!((audio.sample_rate, audio.channels), (44_100, 2));
346 std::fs::remove_file(&out).unwrap();
347}
348
349#[test]
350fn exports_two_sources_as_one_timeline_in_software() {
351 pin_software();
352 multi_source_round_trip("multi_sw", Duration::from_secs(180));
353}
354
355#[test]
356#[ignore]
357fn exports_two_sources_as_one_timeline_in_hardware() {
358 pin_hardware();
359 multi_source_round_trip("multi_hw", Duration::from_secs(60));
360}
361
362/// The bitrate setting is the one knob a user turns for quality, so it has to
363/// reach the encoder: the same 120-frame timeline at 1, 4 and 8 Mbps has to come
364/// back as three strictly growing files. `force_sw` pins the software encoder,
365/// whose rate control is the one every machine has.
366#[test]
367fn a_higher_bitrate_writes_a_bigger_file() {
368 pin_software();
369 let mut sizes = Vec::new();
370 for bitrate in [1_000_000u64, 4_000_000, 8_000_000] {
371 let mut session = edited(&asset("test_baseline.mp4"));
372 session.pause();
373 let out = out_path(&format!("bitrate_{bitrate}"));
374 let settings = ExportSettings {
375 bitrate: Some(bitrate),
376 force_sw: true,
377 };
378 let handle = session.export_to_with(&out, &settings);
379 wait(&handle, Duration::from_secs(180)).expect("export");
380 let size = std::fs::metadata(&out).expect("export exists").len();
381 println!("{} Mbps: {size} bytes", bitrate / 1_000_000);
382 sizes.push(size);
383 std::fs::remove_file(&out).unwrap();
384 }
385 assert!(
386 sizes[0] < sizes[1] && sizes[1] < sizes[2],
387 "file sizes {sizes:?} are not strictly growing with the bitrate"
388 );
389}
390
391/// A source that disappears between the edit and the export fails the export
392/// rather than silently writing a shorter file -- and leaves neither an output
393/// nor a `.part`. Both sources are silent, so the failure is the per-clip open
394/// (the audio pass never touches the second file).
395#[test]
396fn a_vanished_source_fails_the_export() {
397 pin_software();
398 let baseline = asset("test_baseline.mp4");
399 let doomed = std::env::temp_dir().join("ve_export_vanished_source.mp4");
400 std::fs::copy(&baseline, &doomed).expect("copy a second source");
401 let (meta, _) = engine::demux::Demuxer::open(&baseline).unwrap();
402
403 // Five frames of each: the export has to get going and then fail.
404 let mut project = Project::single(&baseline, meta.frame_count);
405 assert!(project.split(5));
406 assert!(project.delete(1));
407 let second = project.import(&doomed, 0);
408 assert!(project.append_clip(second, meta.frame_count));
409 assert!(project.split(10));
410 assert!(project.delete(2));
411 assert_eq!(project.timeline_frames(), 10);
412
413 std::fs::remove_file(&doomed).expect("unlink the second source");
414 let out = out_path("vanished");
415 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
416 let result = wait(&handle, Duration::from_secs(60));
417 let error = result.expect_err("an export of a missing file cannot succeed");
418 println!("vanished source: {error}");
419 assert!(
420 !out.exists(),
421 "a failed export still wrote {}",
422 out.display()
423 );
424 assert!(!part_path(&out).exists(), "the .part outlived the failure");
425}
426
427/// A cancelled export leaves nothing behind -- the half-written file is the
428/// thing a user would otherwise try to play.
429#[test]
430fn cancelling_leaves_no_file() {
431 pin_software();
432 let mut session = edited(&asset("test_baseline.mp4"));
433 session.pause();
434 let out = out_path("cancel");
435
436 let handle = session.export_to(&out);
437 let started = Instant::now();
438 while handle.progress() < 0.1 {
439 assert!(
440 started.elapsed() < Duration::from_secs(60),
441 "export never got going"
442 );
443 assert!(
444 !handle.is_finished(),
445 "export finished before it was cancelled"
446 );
447 std::thread::sleep(Duration::from_millis(10));
448 }
449 handle.cancel();
450 let result = wait(&handle, Duration::from_secs(5));
451 assert!(result.is_err(), "a cancelled export is an error");
452 assert!(!out.exists(), "no partial file survives a cancel");
453 assert!(!part_path(&out).exists(), "the .part is cleaned up too");
454}
455
456/// The late window: cancel after the last frame, while the export is draining,
457/// writing audio and closing the file. Progress already reads 100% there, and
458/// before the cancel checkpoints outside the frame loop the export completed
459/// anyway and left a file the user never asked for.
460///
461/// Landing in that window is a race, so the attempt is repeated; whichever side
462/// of it an attempt lands on, the invariant is the same -- a finished file or no
463/// file, never a `.part`.
464#[test]
465fn cancelling_after_the_last_frame_leaves_no_file() {
466 pin_software();
467 let out = out_path("late");
468 let part = part_path(&out);
469 for attempt in 1..=5 {
470 let mut session = edited(&asset("test_baseline.mp4"));
471 session.pause();
472 let handle = session.export_to(&out);
473 // Sleep while there is time to sleep, then spin: the window is the few
474 // milliseconds between the last frame and `finish`.
475 let started = Instant::now();
476 while handle.progress() < 0.9 && !handle.is_finished() {
477 assert!(
478 started.elapsed() < Duration::from_secs(120),
479 "export stalled"
480 );
481 std::thread::sleep(Duration::from_millis(20));
482 }
483 while handle.progress() < 1.0 && !handle.is_finished() {
484 std::hint::spin_loop();
485 }
486 handle.cancel();
487
488 let result = wait(&handle, Duration::from_secs(30));
489 assert!(!part.exists(), "attempt {attempt} left a .part behind");
490 if result.is_err() {
491 assert!(!out.exists(), "a late cancel still wrote {}", out.display());
492 return;
493 }
494 // The export beat the cancel; then it must be a whole file, not a stump.
495 assert_eq!(
496 engine::demux::Demuxer::open(&out).unwrap().0.frame_count,
497 120
498 );
499 std::fs::remove_file(&out).unwrap();
500 }
501 panic!("cancel never landed in the drain/audio/finish window");
502}
503
504/// Audio: the copied AAC packets have to land in the export as a track a reader
505/// can open again, at a length the video agrees with.
506#[test]
507#[ignore]
508fn exports_audio_alongside_the_video() {
509 pin_hardware();
510 let source = asset("test_av.mp4");
511 let mut session = PlaybackSession::open(&source).expect("open source");
512 // One cut: the timeline is unchanged but the audio copy now runs as two
513 // segments, so the packet-boundary rounding at the join is exercised.
514 assert!(session.cut_at(2.0));
515 session.pause();
516 let timeline = session.timeline_duration();
517 let out = out_path("av");
518
519 let handle = session.export_to(&out);
520 wait(&handle, Duration::from_secs(120)).expect("export");
521
522 let file = File::open(&out).unwrap();
523 let size = file.metadata().unwrap().len();
524 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
525 let packets = reader.sample_count(2).expect("audio track");
526 let expected = engine::AudioSession::copy_segments(&source, &[(0.0, 2.0), (2.0, 5.0)])
527 .unwrap()
528 .expect("source has audio")
529 .1
530 .len() as u32;
531 assert_eq!(packets, expected, "every copied packet reached the file");
532 // Independently of the copier: the rounding stays inside one packet per join
533 // plus the priming packet it starts with.
534 let samples = f64::from(packets * 1024);
535 let wanted = timeline * 44_100.0;
536 println!("audio: {packets} packets = {samples} samples for {wanted} of timeline");
537 assert!(
538 (samples - wanted).abs() < 3.0 * 1024.0,
539 "audio length {samples} drifted from {wanted}"
540 );
541
542 let (meta, chunks) = engine::AudioSession::open(&out)
543 .expect("reopen export audio")
544 .expect("export has an audio track");
545 assert_eq!(meta.sample_rate, 44_100);
546 assert_eq!(meta.channels, 2);
547 let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum();
548 assert!(
549 decoded as f64 / 2.0 > wanted - 3.0 * 1024.0,
550 "only {decoded} samples decoded back out"
551 );
552
553 let (video, _) = engine::demux::Demuxer::open(&out).unwrap();
554 assert_eq!(video.frame_count, 150, "video track unaffected by the cut");
555 std::fs::remove_file(&out).unwrap();
556}
557
558/// Hardware-encoded access units had never been through the muxer before this
559/// slice: the Mesa slice-header fixup and the parameter-set placement were only
560/// ever proven against a raw decoder.
561#[test]
562#[ignore]
563fn hardware_access_units_repack_into_mp4() {
564 let (w, h) = (640u32, 480u32);
565 let mut encoder =
566 HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver");
567 let out = out_path("hwmux");
568 let mut muxer: Option<Mp4Muxer> = None;
569 let mut written = 0;
570 for index in 0..10u32 {
571 let (y, u, v) = synthetic(index, w as usize, h as usize);
572 let Some(au) = encoder.encode(&y, &u, &v, w, h, false).expect("encode") else {
573 continue;
574 };
575 if muxer.is_none() {
576 let (sps, pps) = parameter_sets(au).expect("first access unit carries SPS+PPS");
577 muxer = Some(
578 Mp4Muxer::create(
579 &out,
580 &VideoParams {
581 width: w,
582 height: h,
583 frame_rate: 30.0,
584 sps,
585 pps,
586 },
587 None,
588 )
589 .expect("create"),
590 );
591 }
592 muxer.as_mut().unwrap().write_video_au(au).expect("write");
593 written += 1;
594 }
595 while let Some(au) = encoder.drain().expect("drain") {
596 muxer.as_mut().unwrap().write_video_au(au).expect("write");
597 written += 1;
598 }
599 muxer.unwrap().finish().expect("finish");
600 assert_eq!(written, 10);
601
602 let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap();
603 assert_eq!(meta.frame_count, 10);
604 let mut decoder = rusty_h264::Decoder::new();
605 let mut decoded = 0;
606 while let Some(au) = demuxer.next_access_unit().unwrap() {
607 if decoder
608 .decode(&au)
609 .expect("software decode of the remuxed stream")
610 .is_some()
611 {
612 decoded += 1;
613 }
614 }
615 assert_eq!(decoded, 10, "every remuxed picture decodes again");
616 std::fs::remove_file(&out).unwrap();
617}
618
619/// A moving diagonal gradient: something that costs bits, so the encoder cannot
620/// pass the check by emitting skip frames.
621fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
622 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
623 let mut y = vec![0u8; width * height];
624 for row in 0..height {
625 for col in 0..width {
626 y[row * width + col] = (row + col + index as usize * 5) as u8;
627 }
628 }
629 (
630 y,
631 vec![64u8.wrapping_add(index as u8); cw * ch],
632 vec![192u8.wrapping_sub(index as u8); cw * ch],
633 )
634}
635
636/// A timeline whose *first* second of sound was lifted. A reader drops the
637/// first packet of an AAC track as encoder priming, so a track that opens on a
638/// hole has to carry one extra packet of silence for it to drop -- without it
639/// the drop comes out of the hole and every sound after the hole plays 23 ms
640/// early, which is a lip sync error for the whole export.
641#[test]
642fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() {
643 pin_software();
644 let source = asset("test_av.mp4");
645 let mut session = PlaybackSession::open(&source).expect("open source");
646 assert!(session.cut_at(1.0), "cut at 1 s");
647 assert!(session.lift_clip(Lane::Audio, 0), "lift the first second");
648 session.pause();
649 let out = out_path("leading_gap");
650 let handle = session.export_to(&out);
651 wait(&handle, Duration::from_secs(180)).expect("export");
652
653 let (_, chunks) = engine::AudioSession::open(&out)
654 .expect("reopen export audio")
655 .expect("export has an audio track");
656 let mut pcm: Vec<f32> = Vec::new();
657 while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) {
658 pcm.resize(chunk.start_sample as usize * 2, 0.0);
659 pcm.extend_from_slice(&chunk.samples);
660 }
661 // Where the sound starts, measured in whole packets so the MDCT leak either
662 // side of the splice cannot be mistaken for the onset: the first block
663 // carrying a quarter of the export's own peak.
664 let block = 1024 * 2;
665 let peak = |b: &[f32]| b.iter().fold(0.0f32, |m, s| m.max(s.abs()));
666 let loud = peak(&pcm) / 4.0;
667 let onset = pcm
668 .chunks(block)
669 .position(|b| peak(b) > loud)
670 .expect("the export has no sound at all") as f64
671 * 1024.0;
672 println!("leading gap: sound starts at sample {onset} of an expected 44100");
673 assert!(
674 (onset - 44_100.0).abs() <= 1024.0,
675 "the sound after the gap is at {onset}, not at the 1 s hole's end"
676 );
677 // ...and the hole really is a hole, not the first second played quietly.
678 let quiet = peak(&pcm[..(0.9 * 44_100.0) as usize * 2]);
679 assert!(quiet < 1e-3, "the lifted second is not silent: {quiet}");
680
681 std::fs::remove_file(&out).unwrap();
682}
683
684/// A timeline with a hole in each lane, exported. The video gap is encoded as
685/// black rather than skipped -- the file is as long as the timeline, frame for
686/// frame -- and the audio gap is copied as real silent packets, so the audio
687/// track covers the whole timeline inside the bresenham bound instead of ending
688/// a second early.
689#[test]
690fn exports_a_gapped_timeline_as_black_and_silence() {
691 pin_software();
692 let source = asset("test_av.mp4");
693 let mut session = PlaybackSession::open(&source).expect("open source");
694 assert!(session.cut_at(1.0), "split at 1 s");
695 assert!(session.cut_at(2.0), "split at 2 s");
696 // Lift the middle out of *both* lanes: one second of black and silence in
697 // the middle of a five-second timeline, with the length unchanged.
698 assert!(session.lift_clip(Lane::Video, 1));
699 assert!(session.lift_clip(Lane::Audio, 1));
700 session.pause();
701 let timeline = session.timeline_duration();
702 let frames = (timeline * FPS).round() as u32;
703 let out = out_path("gapped");
704
705 let handle = session.export_to(&out);
706 wait(&handle, Duration::from_secs(180)).expect("export");
707
708 // Every frame is there, and the ones over the hole are black.
709 let (video, _) = engine::demux::Demuxer::open(&out).unwrap();
710 assert_eq!(
711 video.frame_count, frames,
712 "a gap is encoded, not skipped: {} frames for a {timeline:.3}s timeline",
713 video.frame_count
714 );
715 let pictures = decode_all(&out);
716 assert_eq!(pictures.len() as u32, frames);
717 let (hole, hole_end) = ((1.0 * FPS) as usize, (2.0 * FPS) as usize);
718 // Encoded black, so not bit-exact: a mean absolute distance from true black
719 // well under one code value per channel is what "black" can mean here.
720 let black = [0u8, 0, 0, 255].repeat(pictures[0].len() / 4);
721 for (i, picture) in pictures.iter().enumerate() {
722 let diff = mean_abs_diff(picture, &black);
723 if (hole..hole_end).contains(&i) {
724 assert!(
725 diff < 4.0,
726 "frame {i} of the gap is not black (MAE {diff:.2})"
727 );
728 }
729 }
730 let lit = mean_abs_diff(&pictures[0], &black);
731 assert!(lit > 4.0, "the clips around the gap came out black too");
732
733 // The audio track spans the whole timeline in packets: the hole is real
734 // silent access units, so the bresenham bound the copier promises -- half a
735 // packet per join, carried through the gap -- covers the gap too.
736 let file = File::open(&out).unwrap();
737 let size = file.metadata().unwrap().len();
738 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
739 let count = reader.sample_count(2).expect("audio track");
740 let samples = f64::from(count * 1024);
741 let wanted = timeline * 44_100.0;
742 println!("gapped export: {count} packets = {samples} samples for {wanted}");
743 assert!(
744 (samples - wanted).abs() < 3.0 * 1024.0,
745 "audio length {samples} drifted from {wanted} across the gap"
746 );
747
748 // ...and the silence is really silent, where the lift was.
749 let (_, chunks) = engine::AudioSession::open(&out)
750 .expect("reopen export audio")
751 .expect("export has an audio track");
752 let mut pcm: Vec<f32> = Vec::new();
753 while let Ok(chunk) = chunks.recv_timeout(Duration::from_secs(10)) {
754 pcm.resize(chunk.start_sample as usize * 2, 0.0);
755 pcm.extend_from_slice(&chunk.samples);
756 }
757 let window = |from: f64, to: f64| {
758 let (a, b) = ((from * 44_100.0) as usize * 2, (to * 44_100.0) as usize * 2);
759 pcm[a.min(pcm.len())..b.min(pcm.len())]
760 .iter()
761 .fold(0.0f32, |m, s| m.max(s.abs()))
762 };
763 // Inside the hole, off its own edges: AAC is lapped, so the packets either
764 // side of a splice carry a little of their neighbour.
765 let quiet = window(1.2, 1.8);
766 assert!(quiet < 1e-3, "the gap is not silent: {quiet}");
767 assert!(window(0.1, 0.9) > 1e-2, "the sound before it went missing");
768 assert!(window(2.2, 4.9) > 1e-2, "the sound after it went missing");
769
770 std::fs::remove_file(&out).unwrap();
771}