forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_export.rs1619 lines, 58.3 KiBHistoryRawDownload
1//! The timeline's audio written out on its own, as a WAV or a FLAC, and read
2//! straight back in through the engine's own reader — which is the check that
3//! matters: a file this program cannot reopen is a file it had no business
4//! writing.
5//!
6//! The fixtures carry a 1 Hz volume pulse (`gen_fixtures.sh`), so a second of
7//! exported audio has a measurable shape and not just a level: the pattern is
8//! asserted as a peak/dip *ratio*, never an absolute level, because ffmpeg's
9//! sine fixtures peak around 0.12.
10//!
11//! No picture is decoded anywhere here, so nothing needs the plugin and the
12//! whole file runs on any machine.
13
14use std::fs::File;
15use std::io::BufReader;
16use std::path::{Path, PathBuf};
17use std::time::{Duration, Instant};
18
19use ec_core::Demuxer as _;
20
21use engine::export::{ExportSettings, Format};
22use engine::project::{Lane, LaneKind, Source, Speed};
23use engine::scale::FitPolicy;
24use engine::scratch::Scratch;
25use engine::{AudioSession, Clip, ExportHandle, Project, Rotation};
26
27const RATE: u32 = 44_100;
28
29fn asset(name: &str) -> PathBuf {
30 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
31 .join("../../assets")
32 .join(name)
33}
34
35/// Its own directory, gone with the value: two suites at once must not delete
36/// each other's output, and nothing may outlive the test that wrote it.
37fn out_path(name: &str, ext: &str) -> Scratch {
38 Scratch::file(&format!("ve_audio_{name}"), ext)
39}
40
41fn part_path(out: &Path) -> PathBuf {
42 PathBuf::from(format!("{}.part", out.display()))
43}
44
45fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
46 let started = Instant::now();
47 while !handle.is_finished() {
48 assert!(
49 started.elapsed() < limit,
50 "export did not finish in {limit:?}"
51 );
52 std::thread::sleep(Duration::from_millis(10));
53 }
54 handle.result().expect("a finished export has an outcome")
55}
56
57/// One second of `test_av`, one second of hole, one second of `test_tone.mp3`.
58///
59/// Three things at once: a cut, a gap (which must arrive as silence), and a
60/// source no mp4 sample table holds — an mp3, which the mp4 path decodes and
61/// re-encodes today and once refused outright.
62fn mixed_project() -> Project {
63 let clip = |start, source| Clip {
64 speed_keys: Vec::new(),
65 reversed: false,
66 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
67 angle: Default::default(),
68 fade_in: 0,
69 fade_out: 0,
70 transition_out: 0,
71 transition_kind: Default::default(),
72 visualizer: 0,
73 viz_paint: 0,
74 gain_db: 0.0,
75 gain_keys: Vec::new(),
76 pan: 0,
77 pitch: 0.0,
78 transform_keys: Vec::new(),
79 opacity_keys: Vec::new(),
80 color_keys: Vec::new(),
81 effects: Vec::new(),
82 start,
83 in_frame: 0,
84 out_frame: 30,
85 source,
86 link: None,
87 eq: None,
88 color: None,
89 fit: FitPolicy::default(),
90 speed: Speed::NORMAL,
91 transform: None,
92 };
93 Project::from_parts(
94 vec![
95 Source::new(asset("test_av.mp4"), 0),
96 Source::new(asset("test_tone.mp3"), 0),
97 ],
98 // The picture is beside the point here, but a project has two lanes and
99 // the timeline's length is the longer of them: three seconds of video
100 // is what makes the third second of audio part of the timeline.
101 vec![
102 (
103 LaneKind::Video,
104 vec![Clip {
105 speed_keys: Vec::new(),
106 reversed: false,
107 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
108 angle: Default::default(),
109 fade_in: 0,
110 fade_out: 0,
111 transition_out: 0,
112 transition_kind: Default::default(),
113 visualizer: 0,
114 viz_paint: 0,
115 gain_db: 0.0,
116 gain_keys: Vec::new(),
117 pan: 0,
118 pitch: 0.0,
119 transform_keys: Vec::new(),
120 opacity_keys: Vec::new(),
121 color_keys: Vec::new(),
122 effects: Vec::new(),
123 start: 0,
124 in_frame: 0,
125 out_frame: 90,
126 source: 0,
127 link: None,
128 eq: None,
129 color: None,
130 fit: FitPolicy::default(),
131 speed: Speed::NORMAL,
132 transform: None,
133 }],
134 ),
135 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
136 ],
137 Vec::new(),
138 Vec::new(),
139 Vec::new(),
140 )
141 .expect("a two-source project with a hole in the audio lane")
142}
143
144fn meta() -> engine::VideoMeta {
145 engine::demux::Demuxer::open(&asset("test_av.mp4"))
146 .expect("open test_av")
147 .0
148}
149
150/// Interleaved samples of a written file, through the engine's own reader --
151/// the same door an import comes in through, so a pass here means the export
152/// can be brought back into a timeline.
153fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) {
154 let (meta, chunks) = AudioSession::open(path)
155 .expect("reopen the export")
156 .expect("the export has audio");
157 let mut samples = Vec::new();
158 for chunk in chunks {
159 samples.extend(chunk.samples);
160 }
161 (meta, samples)
162}
163
164/// Root mean square of `[from, to)` seconds of an interleaved stereo buffer.
165fn rms(samples: &[f32], channels: usize, from: f64, to: f64) -> f64 {
166 let at = |secs: f64| (secs * f64::from(RATE)) as usize * channels;
167 let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
168 assert!(!window.is_empty(), "no samples in [{from}, {to})");
169 (window
170 .iter()
171 .map(|s| f64::from(*s) * f64::from(*s))
172 .sum::<f64>()
173 / window.len() as f64)
174 .sqrt()
175}
176
177/// What every audio export must be, whatever encoded it: exactly as long as the
178/// timeline, silent where the timeline is empty, and audible where it is not --
179/// with the fixtures' 1 Hz pulse still in it, which is what says the samples are
180/// the *edit's* and not just noise of the right length.
181///
182/// `gap_ceiling` is how loud the hole in the middle may be as a fraction of the
183/// first second: `0.0` for a lossless format, where the silence is the samples
184/// themselves, and a real fraction for a lossy one, where a block straddling the
185/// cut rings into it. Never an absolute level -- the fixtures peak around 0.12.
186fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32], gap_ceiling: f64) {
187 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2), "as decoded");
188 let channels = usize::from(meta.channels);
189 // Three seconds of timeline, to the sample: the segments round their own
190 // windows and the mp3 need not end where the second does, so this is the
191 // export's own trim/pad and not an accident of the sources.
192 let frames = (3.0 * f64::from(RATE)) as usize;
193 assert_eq!(
194 samples.len(),
195 frames * channels,
196 "timeline length in samples"
197 );
198
199 // Second 0 is test_av, second 2 is the mp3; both carry the tone.
200 let av = rms(samples, channels, 0.05, 0.95);
201 let tone = rms(samples, channels, 2.05, 2.95);
202 // Second 1 is the hole. Silence, not a stall and not a skip: it occupies
203 // its full second, which is what the sample count above already proved.
204 let gap = rms(samples, channels, 1.0, 2.0);
205 println!("rms: av {av:.4} gap {gap:.6} mp3 {tone:.4}");
206 assert!(av > 0.01, "the first second is audible");
207 assert!(tone > 0.01, "the mp3 second is audible");
208 assert!(
209 gap <= av * gap_ceiling,
210 "the gap is silence: {gap:.6} against {av:.4} of first second"
211 );
212
213 // The 1 Hz pulse: `volume = 0.5 + 0.5 sin(2 pi t)`, so a peak sits at
214 // t = 0.25 and the dip at t = 0.75. Ratio, never an absolute level.
215 let peak = rms(samples, channels, 0.2, 0.3);
216 let dip = rms(samples, channels, 0.7, 0.8);
217 println!(
218 "pulse: peak {peak:.4} dip {dip:.4} ratio {:.1}",
219 peak / dip
220 );
221 assert!(
222 peak > dip * 4.0,
223 "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}"
224 );
225}
226
227/// The RIFF header itself, byte for byte: ec-riff writes it, but what a player
228/// reads is the bytes, and a wrong rate or a wrong `data` size is a file that
229/// decodes at the wrong speed rather than one that fails to open.
230fn assert_wav_header(path: &Path, frames: usize) {
231 let bytes = std::fs::read(path).expect("read the wav back");
232 let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]);
233 let u32_at =
234 |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]);
235 assert_eq!(&bytes[0..4], b"RIFF");
236 assert_eq!(&bytes[8..12], b"WAVE");
237 assert_eq!(&bytes[12..16], b"fmt ");
238 assert_eq!(u32_at(4) as usize, bytes.len() - 8, "RIFF size");
239 assert_eq!(u16_at(20), 1, "PCM, not a float or a compressed tag");
240 assert_eq!(u16_at(22), 2, "stereo");
241 assert_eq!(u32_at(24), RATE, "sample rate");
242 assert_eq!(u32_at(28), RATE * 2 * 2, "byte rate = rate * channels * 2");
243 assert_eq!(u16_at(32), 4, "block align");
244 assert_eq!(u16_at(34), 16, "bits per sample");
245 // The `data` chunk carries every sample and nothing else. A `fact` chunk may
246 // come first, so it is found rather than assumed to be at 36.
247 let data = bytes
248 .windows(4)
249 .position(|w| w == b"data")
250 .expect("a data chunk");
251 assert_eq!(u32_at(data + 4) as usize, frames * 2 * 2, "data chunk size");
252}
253
254#[test]
255fn exports_the_timeline_as_a_wav() {
256 let out = out_path("wav", "wav");
257 let handle = engine::export::start(
258 mixed_project(),
259 meta(),
260 &out,
261 &ExportSettings {
262 format: Format::Wav,
263 ..Default::default()
264 },
265 None,
266 );
267 wait(&handle, Duration::from_secs(60)).expect("wav export");
268 assert_eq!(handle.progress(), 1.0, "finished at full progress");
269 assert!(!part_path(&out).exists(), "the .part was renamed away");
270
271 let (meta, samples) = decode(&out);
272 assert_timeline_shape(&meta, &samples, 0.0);
273 assert_wav_header(&out, samples.len() / usize::from(meta.channels));
274 std::fs::remove_file(&out).unwrap();
275}
276
277/// The WAV is what ffprobe and ffmpeg say it is, and ffmpeg decodes it to the
278/// very samples ec-riff wrote: the file is read by the reference decoder, not
279/// only by the reader that wrote it.
280#[test]
281fn the_wav_export_is_ffprobe_clean_and_decodes_to_the_same_pcm() {
282 use std::process::{Command, Stdio};
283 let have = |bin: &str| {
284 Command::new(bin)
285 .arg("-version")
286 .stdout(Stdio::null())
287 .stderr(Stdio::null())
288 .status()
289 .map(|s| s.success())
290 .unwrap_or(false)
291 };
292 if !(have("ffmpeg") && have("ffprobe")) {
293 eprintln!("skipped: no ffmpeg/ffprobe to read the export back");
294 return;
295 }
296 let out = out_path("wav_ffmpeg", "wav");
297 let handle = engine::export::start(
298 mixed_project(),
299 meta(),
300 &out,
301 &ExportSettings {
302 format: Format::Wav,
303 ..Default::default()
304 },
305 None,
306 );
307 wait(&handle, Duration::from_secs(60)).expect("wav export");
308
309 let mut reader = ec_riff::WavReader::open(&out).expect("ec-riff reopens the wav");
310 let spec = reader.spec();
311 let samples = reader.read_all_i32().expect("the samples");
312 let frames = samples.len() / usize::from(spec.channels);
313
314 let probe = Command::new("ffprobe")
315 .args([
316 "-v",
317 "error",
318 "-show_entries",
319 "stream=codec_name,channels,sample_rate:format=duration",
320 "-of",
321 "default=nw=1",
322 ])
323 .arg(&out)
324 .output()
325 .expect("run ffprobe");
326 assert!(
327 probe.status.success(),
328 "ffprobe: {}",
329 String::from_utf8_lossy(&probe.stderr)
330 );
331 let text = String::from_utf8_lossy(&probe.stdout).to_string();
332 assert!(
333 text.contains("codec_name=pcm_s16le"),
334 "ffprobe says: {text}"
335 );
336 assert!(
337 text.contains(&format!("channels={}", spec.channels)),
338 "ffprobe says: {text}"
339 );
340 assert!(
341 text.contains(&format!("sample_rate={}", spec.sample_rate)),
342 "ffprobe says: {text}"
343 );
344 let duration: f64 = text
345 .lines()
346 .find_map(|l| l.strip_prefix("duration="))
347 .and_then(|d| d.trim().parse().ok())
348 .expect("ffprobe gives a duration");
349 let expected = frames as f64 / f64::from(spec.sample_rate);
350 assert!(
351 (duration - expected).abs() < 0.001,
352 "ffprobe {duration}s, file {expected}s"
353 );
354
355 let decoded = Command::new("ffmpeg")
356 .args(["-v", "error", "-i"])
357 .arg(&out)
358 .args(["-f", "s16le", "-"])
359 .output()
360 .expect("run ffmpeg");
361 assert!(
362 decoded.status.success(),
363 "ffmpeg: {}",
364 String::from_utf8_lossy(&decoded.stderr)
365 );
366 let expected_pcm: Vec<u8> = samples
367 .iter()
368 .flat_map(|&s| (s as i16).to_le_bytes())
369 .collect();
370 assert_eq!(
371 decoded.stdout.len(),
372 expected_pcm.len(),
373 "ffmpeg's sample count"
374 );
375 assert!(
376 decoded.stdout == expected_pcm,
377 "ffmpeg decodes different PCM than was written"
378 );
379 std::fs::remove_file(&out).unwrap();
380}
381
382#[test]
383fn exports_the_timeline_as_a_flac() {
384 let out = out_path("flac", "flac");
385 let handle = engine::export::start(
386 mixed_project(),
387 meta(),
388 &out,
389 &ExportSettings {
390 format: Format::Flac,
391 ..Default::default()
392 },
393 None,
394 );
395 wait(&handle, Duration::from_secs(60)).expect("flac export");
396 assert_eq!(handle.progress(), 1.0, "finished at full progress");
397
398 let bytes = std::fs::read(&out).expect("read the flac back");
399 assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic");
400 // Lossless is a claim about the samples, so it is checked on the samples:
401 // the same shape the WAV of the same timeline has.
402 let (meta, samples) = decode(&out);
403 assert_timeline_shape(&meta, &samples, 0.0);
404 // Smaller than the PCM it encodes, or the whole point of the row is gone.
405 let pcm = samples.len() * 2;
406 println!("flac {} bytes for {pcm} bytes of PCM", bytes.len());
407 assert!(bytes.len() < pcm, "compressed");
408 std::fs::remove_file(&out).unwrap();
409}
410
411/// The third audio row, and the one that used to be a licence note: `ec-mp3`
412/// encodes it, and the file is read straight back through symphonia's mp3
413/// decoder -- the very door an mp3 *import* comes in through, so an export can
414/// be dropped back onto the timeline it came from.
415///
416/// The shape is checked loosely where MP3 cannot be exact: the encoder pads its
417/// tail to a whole 1152-frame frame and the decoder hands back the padding, so
418/// the length is asserted to within a frame instead of to the sample. What is
419/// exact is the edit -- audible, silent, audible -- and the fixtures' 1 Hz
420/// pulse inside the first second.
421#[test]
422fn exports_the_timeline_as_an_mp3() {
423 let out = out_path("mp3", "mp3");
424 let handle = engine::export::start(
425 mixed_project(),
426 meta(),
427 &out,
428 &ExportSettings {
429 format: Format::Mp3,
430 ..Default::default()
431 },
432 None,
433 );
434 wait(&handle, Duration::from_secs(120)).expect("mp3 export");
435 assert_eq!(handle.progress(), 1.0, "finished at full progress");
436 assert!(!part_path(&out).exists(), "the .part was renamed away");
437
438 let (meta, samples) = decode(&out);
439 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
440 let channels = usize::from(meta.channels);
441 let frames = samples.len() / channels;
442 let timeline = (3.0 * f64::from(RATE)) as usize;
443 assert!(
444 frames >= timeline && frames <= timeline + 2 * 1152,
445 "{frames} frames for a three-second timeline ({timeline})"
446 );
447 let av = rms(&samples, channels, 0.05, 0.95);
448 let gap = rms(&samples, channels, 1.1, 1.9);
449 let tone = rms(&samples, channels, 2.05, 2.95);
450 println!("mp3 rms: av {av:.4} gap {gap:.6} mp3 second {tone:.4}");
451 assert!(av > 0.01, "the first second is audible");
452 assert!(tone > 0.01, "the mp3 second is audible");
453 assert!(gap < av / 20.0, "the hole is silence: {gap:.6}");
454 let peak = rms(&samples, channels, 0.2, 0.3);
455 let dip = rms(&samples, channels, 0.7, 0.8);
456 assert!(
457 peak > dip * 4.0,
458 "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}"
459 );
460 std::fs::remove_file(&out).unwrap();
461}
462
463/// The failure a user hit, as a test: a still picture and a song, exported as an
464/// **mp4**. There is no AAC track anywhere in that timeline to copy -- an mp3
465/// holds no such packets and a png holds nothing at all -- so this used to be
466/// refused by name and the only way out was a WAV beside a picture nobody had.
467/// The song is decoded and encoded as AAC instead (`export::copy_audio` falls
468/// through to `encode_audio`), and the file comes back with picture *and* sound.
469#[test]
470fn a_still_and_a_song_export_as_an_mp4_with_sound() {
471 let song = asset("test_tone.mp3");
472 let still = asset("test_still.png");
473 let clip = |source, frames| Clip {
474 speed_keys: Vec::new(),
475 reversed: false,
476 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
477 angle: Default::default(),
478 fade_in: 0,
479 fade_out: 0,
480 transition_out: 0,
481 transition_kind: Default::default(),
482 visualizer: 0,
483 viz_paint: 0,
484 gain_db: 0.0,
485 gain_keys: Vec::new(),
486 pan: 0,
487 pitch: 0.0,
488 transform_keys: Vec::new(),
489 opacity_keys: Vec::new(),
490 color_keys: Vec::new(),
491 effects: Vec::new(),
492 start: 0,
493 in_frame: 0,
494 out_frame: frames,
495 source,
496 link: None,
497 eq: None,
498 color: None,
499 fit: FitPolicy::default(),
500 speed: Speed::NORMAL,
501 transform: None,
502 };
503 // Two seconds of each at the project's own 30 fps: a still has no length of
504 // its own and the song is longer than what is placed.
505 let project = Project::from_parts(
506 vec![Source::new(still, 0), Source::new(song, 0)],
507 vec![
508 (LaneKind::Video, vec![clip(0, 60)]),
509 (LaneKind::Audio, vec![clip(1, 60)]),
510 ],
511 Vec::new(),
512 Vec::new(),
513 Vec::new(),
514 )
515 .expect("a still under a song");
516 // The project's own picture size and rate: the still decides the one and
517 // the scaffold the other, exactly as opening a png in the editor does.
518 let meta = engine::VideoMeta {
519 width: 640,
520 height: 360,
521 frame_rate: 30.0,
522 frame_count: 60,
523 codec: engine::Codec::H264,
524 color: Default::default(),
525 matrix_assumed: false,
526 rotation: Rotation::None,
527 // Square pixels, coded where they are declared: a meta no container
528 // wrote, so nothing was read to disagree with it.
529 coded_width: 640,
530 coded_height: 360,
531 pixel_aspect: engine::demux::PixelAspect::SQUARE,
532 };
533 let out = out_path("still_song", "mp4");
534 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
535 wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");
536
537 // Picture: two seconds of it, through the demuxer an import uses.
538 let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
539 assert_eq!((written.width, written.height), (640, 360));
540 assert_eq!(written.frame_count, 60, "two seconds at 30 fps");
541 // ...and sound, which is the half that used to be missing.
542 let (audio, samples) = decode(&out);
543 let channels = usize::from(audio.channels);
544 let heard = rms(&samples, channels, 0.2, 1.8);
545 println!("still+song: {} Hz, rms {heard:.4}", audio.sample_rate);
546 assert!(heard > 0.01, "the song is in the file (rms {heard:.4})");
547 std::fs::remove_file(&out).unwrap();
548}
549
550/// Cancel leaves nothing behind -- not the output, not the `.part`. The
551/// timeline is long enough (a minute of audio) that the escape lands mid-decode
552/// rather than after the file is already closed.
553/// What the two mix settings do to a *written file*, which is the only place
554/// the claim can be checked: a track's fader is that track's alone, and the
555/// master limiter holds the sum of them under its ceiling instead of letting it
556/// square off at full scale.
557///
558/// Four audio tracks of the same second, so the sum is four times one file and
559/// well past what a sample can hold. Measured as the peak of the WAV read back
560/// through the engine's own reader -- a level, not a shape, because that is
561/// exactly what a limiter promises.
562#[test]
563fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() {
564 let clip = Clip {
565 speed_keys: Vec::new(),
566 reversed: false,
567 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
568 angle: Default::default(),
569 fade_in: 0,
570 fade_out: 0,
571 transition_out: 0,
572 transition_kind: Default::default(),
573 visualizer: 0,
574 viz_paint: 0,
575 gain_db: 0.0,
576 gain_keys: Vec::new(),
577 pan: 0,
578 pitch: 0.0,
579 transform_keys: Vec::new(),
580 opacity_keys: Vec::new(),
581 color_keys: Vec::new(),
582 effects: Vec::new(),
583 start: 0,
584 in_frame: 0,
585 out_frame: 30,
586 source: 0,
587 link: None,
588 eq: None,
589 color: None,
590 fit: FitPolicy::default(),
591 speed: Speed::NORMAL,
592 transform: None,
593 };
594 let four = || {
595 Project::from_parts(
596 vec![Source::new(asset("test_av.mp4"), 0)],
597 vec![
598 (LaneKind::Video, vec![clip.clone()]),
599 (LaneKind::Audio, vec![clip.clone()]),
600 (LaneKind::Audio, vec![clip.clone()]),
601 (LaneKind::Audio, vec![clip.clone()]),
602 (LaneKind::Audio, vec![clip.clone()]),
603 ],
604 Vec::new(),
605 Vec::new(),
606 Vec::new(),
607 )
608 .expect("one second on four audio tracks")
609 };
610 let write = |project: Project, name: &str| {
611 let out = out_path(name, "wav");
612 let handle = engine::export::start(
613 project,
614 meta(),
615 &out,
616 &ExportSettings {
617 format: Format::Wav,
618 ..Default::default()
619 },
620 None,
621 );
622 wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}"));
623 let (audio, samples) = decode(&out);
624 let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
625 let level = rms(&samples, usize::from(audio.channels), 0.05, 0.95);
626 let _ = std::fs::remove_file(&out);
627 (peak, level)
628 };
629
630 // Four copies of one file, each fader all the way up: the sum is well past
631 // what a sample can hold, and with no limiter it is clamped at full scale
632 // by the mixer's own backstop -- which is the clipping this exists for.
633 let hot = || {
634 let mut project = four();
635 for ord in 0..4 {
636 assert!(project.set_lane_gain_db(
637 Lane::new(LaneKind::Audio, ord),
638 engine::project::MAX_GAIN_DB
639 ));
640 }
641 project
642 };
643 let (flat_peak, flat_level) = write(hot(), "mix_flat");
644 println!("flat: peak {flat_peak:.4} rms {flat_level:.4}");
645
646 // One track's fader, and one track's only: A2, A3 and A4 all the way down
647 // leaves a quarter of the sum, so the level drops by ~12 dB against the
648 // four of them at the same setting. A whole-band
649 // change -- there is no frequency in this claim, which is what makes it a
650 // different control from the equalizer.
651 let (unity_peak, unity_level) = write(four(), "mix_unity");
652 let mut down = four();
653 for ord in 1..4 {
654 assert!(down.set_lane_gain_db(
655 Lane::new(LaneKind::Audio, ord),
656 engine::project::MIN_GAIN_DB
657 ));
658 }
659 let (_, quiet_level) = write(down, "mix_fader");
660 let drop_db = 20.0 * (quiet_level / unity_level).log10();
661 println!("one track alone: rms {quiet_level:.4} ({drop_db:.1} dB)");
662 assert!(
663 (drop_db + 12.0).abs() < 1.5,
664 "three of four tracks down left {drop_db:.1} dB, not ~-12"
665 );
666
667 // The limiter over the same hot sum: the peak lands under the ceiling, and
668 // the sound is still there (a limiter that silenced the mix would pass a
669 // peak test and fail every ear).
670 let ceiling_db = -3.0;
671 let mut limited = hot();
672 assert!(limited.set_limiter(engine::limiter::Limiter {
673 ceiling_db,
674 on: true,
675 }));
676 let (peak, level) = write(limited, "mix_limited");
677 let ceiling = 10f32.powf(ceiling_db / 20.0);
678 println!("limited: peak {peak:.4} vs ceiling {ceiling:.4} rms {level:.4}");
679 assert!(
680 flat_peak > ceiling,
681 "the flat mix was not hot to begin with"
682 );
683 assert!(
684 peak <= ceiling + 1e-3,
685 "peak {peak:.4} passed the {ceiling:.4} ceiling"
686 );
687 assert!(level > unity_level, "the limiter took the mix out");
688 assert!(
689 unity_peak < 1.0,
690 "four at unity fit; the +12 dB four did not"
691 );
692}
693
694#[test]
695fn a_cancelled_audio_export_leaves_no_file() {
696 let source = asset("test_av.mp4");
697 let (meta, _) = engine::demux::Demuxer::open(&source).expect("open test_av");
698 let mut project = Project::single(&source, meta.frame_count);
699 for _ in 0..11 {
700 assert!(project.append_clip(0, meta.frame_count), "a minute of it");
701 }
702 let out = out_path("cancel", "wav");
703 let handle = engine::export::start(
704 project,
705 meta,
706 &out,
707 &ExportSettings {
708 format: Format::Wav,
709 ..Default::default()
710 },
711 None,
712 );
713 handle.cancel();
714 let outcome = wait(&handle, Duration::from_secs(120));
715 let text = outcome.expect_err("a cancelled export fails").to_string();
716 assert!(text.contains("cancelled"), "{text}");
717 assert!(!out.exists(), "no output file");
718 assert!(!part_path(&out).exists(), "no half-written .part either");
719}
720
721/// The rate an MP3 file *declares*, read out of its own frame headers -- the
722/// only place the claim can be checked, since a caller's kbps is a request until
723/// the bytes say so. MPEG-1 Layer III, whose bitrate index is the high nibble of
724/// the third header byte.
725fn mp3_declared_kbps(path: &Path) -> u32 {
726 const KBPS: [u32; 16] = [
727 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0,
728 ];
729 let bytes = std::fs::read(path).expect("read the mp3 back");
730 let at = bytes
731 .windows(4)
732 .position(|w| w[0] == 0xFF && w[1] & 0xE0 == 0xE0)
733 .expect("an MPEG frame sync");
734 let header = &bytes[at..at + 4];
735 assert_eq!(header[1] >> 3 & 0x3, 0b11, "MPEG-1");
736 assert_eq!(header[1] >> 1 & 0x3, 0b01, "Layer III");
737 let kbps = KBPS[usize::from(header[2] >> 4)];
738 assert!(kbps > 0, "a free-format or invalid bitrate index");
739 kbps
740}
741
742/// What an mp4's AAC track is really coded at: its sample bytes over the time
743/// they play, in kbps. Every AAC-LC packet is 1024 frames per channel, so the
744/// duration comes out of the packet count and needs no timescale of the file's
745/// own -- and the bytes are what a player downloads, which is what a bitrate is.
746fn mp4_aac_kbps(path: &Path, sample_rate: f64) -> f64 {
747 let file = File::open(path).expect("reopen the mp4");
748 let mut reader = ec_mp4::Mp4Demuxer::new(BufReader::new(file)).expect("mp4 header");
749 let stream = reader
750 .streams()
751 .iter()
752 .find(|s| s.params.codec == ec_core::CodecId::Aac)
753 .expect("an AAC track")
754 .index;
755 let count = reader.samples(stream).len();
756 let mut bytes = 0usize;
757 for index in 0..count {
758 bytes += reader
759 .read_sample(stream, index)
760 .expect("a sample at every id")
761 .data
762 .len();
763 }
764 let seconds = count as f64 * 1024.0 / sample_rate;
765 bytes as f64 * 8.0 / seconds / 1000.0
766}
767
768/// The sound's rate is the caller's, in both kinds of file -- and the file
769/// nobody asked a rate of is the one this program always wrote.
770///
771/// MP3 declares its rate in every frame header, so that half is exact. The AAC
772/// half is measured off the mp4's own sample table: a rate control lands *near*
773/// its target rather than on it, so the tolerance is a fifth, which is far
774/// tighter than the gap between two offered rates.
775#[test]
776fn the_sound_is_written_at_the_rate_that_was_asked_for() {
777 // Untouched settings first: this is the byte-behaviour a user who never
778 // opens the row is entitled to keep.
779 for (kbps, want) in [
780 (None, engine::export::DEFAULT_AUDIO_KBPS),
781 (Some(128), 128),
782 (Some(320), 320),
783 ] {
784 let out = out_path(&format!("mp3_{}", want), "mp3");
785 let handle = engine::export::start(
786 mixed_project(),
787 meta(),
788 &out,
789 &ExportSettings {
790 format: Format::Mp3,
791 audio_kbps: kbps,
792 ..Default::default()
793 },
794 None,
795 );
796 wait(&handle, Duration::from_secs(120)).expect("mp3 export");
797 let got = mp3_declared_kbps(&out);
798 println!("mp3 asked {kbps:?}, header says {got} kbps");
799 assert_eq!(got, want, "the mp3 frames declare the rate that was picked");
800 // ...and it is still the edit, not just bytes at the right rate.
801 let (meta, samples) = decode(&out);
802 let channels = usize::from(meta.channels);
803 assert!(rms(&samples, channels, 0.05, 0.95) > 0.01, "audible");
804 std::fs::remove_file(&out).unwrap();
805 }
806
807 // The same choice inside a video export, where the sound is AAC: a song
808 // under a still, which no mp4 sample table can be copied from, so the
809 // encoder really runs.
810 let project = Project::from_parts(
811 vec![
812 Source::new(asset("test_still.png"), 0),
813 Source::new(asset("test_tone.mp3"), 0),
814 ],
815 vec![
816 (
817 LaneKind::Video,
818 vec![Clip {
819 speed_keys: Vec::new(),
820 reversed: false,
821 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
822 angle: Default::default(),
823 fade_in: 0,
824 fade_out: 0,
825 transition_out: 0,
826 transition_kind: Default::default(),
827 visualizer: 0,
828 viz_paint: 0,
829 gain_db: 0.0,
830 gain_keys: Vec::new(),
831 pan: 0,
832 pitch: 0.0,
833 transform_keys: Vec::new(),
834 opacity_keys: Vec::new(),
835 color_keys: Vec::new(),
836 effects: Vec::new(),
837 start: 0,
838 in_frame: 0,
839 out_frame: 60,
840 source: 0,
841 link: None,
842 eq: None,
843 color: None,
844 fit: FitPolicy::default(),
845 speed: Speed::NORMAL,
846 transform: None,
847 }],
848 ),
849 (
850 LaneKind::Audio,
851 vec![Clip {
852 speed_keys: Vec::new(),
853 reversed: false,
854 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
855 angle: Default::default(),
856 fade_in: 0,
857 fade_out: 0,
858 transition_out: 0,
859 transition_kind: Default::default(),
860 visualizer: 0,
861 viz_paint: 0,
862 gain_db: 0.0,
863 gain_keys: Vec::new(),
864 pan: 0,
865 pitch: 0.0,
866 transform_keys: Vec::new(),
867 opacity_keys: Vec::new(),
868 color_keys: Vec::new(),
869 effects: Vec::new(),
870 start: 0,
871 in_frame: 0,
872 out_frame: 60,
873 source: 1,
874 link: None,
875 eq: None,
876 color: None,
877 fit: FitPolicy::default(),
878 speed: Speed::NORMAL,
879 transform: None,
880 }],
881 ),
882 ],
883 Vec::new(),
884 Vec::new(),
885 Vec::new(),
886 )
887 .expect("a still under a song");
888 let meta = engine::VideoMeta {
889 width: 640,
890 height: 360,
891 frame_rate: 30.0,
892 frame_count: 60,
893 codec: engine::Codec::H264,
894 color: Default::default(),
895 matrix_assumed: false,
896 rotation: Rotation::None,
897 // Square pixels, coded where they are declared: a meta no container
898 // wrote, so nothing was read to disagree with it.
899 coded_width: 640,
900 coded_height: 360,
901 pixel_aspect: engine::demux::PixelAspect::SQUARE,
902 };
903 for want in [128u32, 320] {
904 let out = out_path(&format!("mp4_aac_{want}"), "mp4");
905 let handle = engine::export::start(
906 project.clone(),
907 meta,
908 &out,
909 &ExportSettings {
910 audio_kbps: Some(want),
911 ..Default::default()
912 },
913 None,
914 );
915 wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");
916 let got = mp4_aac_kbps(&out, f64::from(RATE));
917 println!("mp4 asked {want} kbps, the track measures {got:.1}");
918 assert!(
919 (got - f64::from(want)).abs() < f64::from(want) / 5.0,
920 "{got:.1} kbps for a {want} kbps request"
921 );
922 std::fs::remove_file(&out).unwrap();
923 }
924}
925
926/// The samples a silent take contributes: a clip of a file with no audio track
927/// is silence for exactly its span, between two clips that are heard. This is
928/// what makes `PlaybackSession::import` letting such a file in honest -- the
929/// export reads the same play list playback does, so a hole here is a hole in
930/// the ear too.
931#[test]
932fn a_silent_clip_exports_as_silence_over_its_own_span() {
933 let clip = |start, source| Clip {
934 speed_keys: Vec::new(),
935 reversed: false,
936 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
937 angle: Default::default(),
938 fade_in: 0,
939 fade_out: 0,
940 transition_out: 0,
941 transition_kind: Default::default(),
942 visualizer: 0,
943 viz_paint: 0,
944 gain_db: 0.0,
945 gain_keys: Vec::new(),
946 pan: 0,
947 pitch: 0.0,
948 transform_keys: Vec::new(),
949 opacity_keys: Vec::new(),
950 color_keys: Vec::new(),
951 effects: Vec::new(),
952 start,
953 in_frame: 0,
954 out_frame: 30,
955 source,
956 link: None,
957 eq: None,
958 color: None,
959 fit: FitPolicy::default(),
960 speed: Speed::NORMAL,
961 transform: None,
962 };
963 let project = Project::from_parts(
964 vec![
965 Source::new(asset("test_av.mp4"), 0),
966 // Video only, no audio track at all: the silent take.
967 Source::new(asset("test_mismatch.mp4"), 0),
968 ],
969 vec![
970 (LaneKind::Video, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
971 (LaneKind::Audio, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
972 ],
973 Vec::new(),
974 Vec::new(),
975 Vec::new(),
976 )
977 .expect("a project whose middle take is silent");
978
979 let out = out_path("silent_clip", "wav");
980 let handle = engine::export::start(
981 project,
982 meta(),
983 &out,
984 &ExportSettings {
985 format: Format::Wav,
986 ..Default::default()
987 },
988 None,
989 );
990 wait(&handle, Duration::from_secs(60)).expect("wav export");
991 let (audio, samples) = decode(&out);
992 let channels = usize::from(audio.channels);
993 assert_eq!(
994 samples.len(),
995 (3.0 * f64::from(RATE)) as usize * channels,
996 "three seconds of timeline, silent take included"
997 );
998 let heard = rms(&samples, channels, 0.05, 0.95);
999 let quiet = rms(&samples, channels, 1.0, 2.0);
1000 let again = rms(&samples, channels, 2.05, 2.95);
1001 println!("rms: heard {heard:.4} silent take {quiet:.6} heard {again:.4}");
1002 assert!(heard > 0.01, "the first take is audible");
1003 assert!(again > 0.01, "the third take is audible");
1004 assert_eq!(quiet, 0.0, "the silent take is exact silence, not a stall");
1005 std::fs::remove_file(&out).unwrap();
1006}
1007
1008/// A silent timeline cannot become an audio file, and says so rather than
1009/// writing zero samples that a user would take for a broken microphone.
1010#[test]
1011fn a_silent_timeline_refuses_an_audio_export() {
1012 let source = asset("test_mismatch.mp4"); // video only, no audio track
1013 let (meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture");
1014 let out = out_path("silent", "wav");
1015 let handle = engine::export::start(
1016 Project::single(&source, meta.frame_count),
1017 meta,
1018 &out,
1019 &ExportSettings {
1020 format: Format::Wav,
1021 ..Default::default()
1022 },
1023 None,
1024 );
1025 let text = wait(&handle, Duration::from_secs(60))
1026 .expect_err("no audio to export")
1027 .to_string();
1028 assert!(text.contains("no audio"), "{text}");
1029 assert!(
1030 !out.exists() && !part_path(&out).exists(),
1031 "nothing written"
1032 );
1033}
1034
1035/// An AC-3 source through the audio-only door: the mp4 export cannot
1036/// copy a syncframe into an `mp4a` track, but a WAV of the same timeline
1037/// decodes, downmixes and reopens through the engine's own reader.
1038#[test]
1039fn a_51_ac3_source_round_trips_through_a_wav() {
1040 let source = asset("test_ac3_51.mp4");
1041 let project = Project::from_parts(
1042 vec![Source::new(source.clone(), 0)],
1043 vec![(
1044 LaneKind::Audio,
1045 vec![Clip {
1046 speed_keys: Vec::new(),
1047 reversed: false,
1048 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1049 angle: Default::default(),
1050 fade_in: 0,
1051 fade_out: 0,
1052 transition_out: 0,
1053 transition_kind: Default::default(),
1054 visualizer: 0,
1055 viz_paint: 0,
1056 gain_db: 0.0,
1057 gain_keys: Vec::new(),
1058 pan: 0,
1059 pitch: 0.0,
1060 transform_keys: Vec::new(),
1061 opacity_keys: Vec::new(),
1062 color_keys: Vec::new(),
1063 effects: Vec::new(),
1064 start: 0,
1065 in_frame: 0,
1066 out_frame: 30,
1067 source: 0,
1068 link: None,
1069 eq: None,
1070 color: None,
1071 fit: FitPolicy::default(),
1072 speed: Speed::NORMAL,
1073 transform: None,
1074 }],
1075 )],
1076 Vec::new(),
1077 Vec::new(),
1078 Vec::new(),
1079 )
1080 .expect("a one-source AC-3 project");
1081 let video = engine::demux::Demuxer::open(&source)
1082 .expect("open the fixture")
1083 .0;
1084
1085 let out = out_path("ac3", "wav");
1086 let handle = engine::export::start(
1087 project,
1088 video,
1089 &out,
1090 &ExportSettings {
1091 format: Format::Wav,
1092 ..Default::default()
1093 },
1094 None,
1095 );
1096 wait(&handle, Duration::from_secs(60)).expect("wav export of an AC-3 source");
1097
1098 let (meta, samples) = decode(&out);
1099 assert_eq!(
1100 (meta.sample_rate, meta.channels),
1101 (48_000, 2),
1102 "the §7.8 downmix is what reaches the file"
1103 );
1104 let secs = (samples.len() / 2) as f64 / 48_000.;
1105 assert!(
1106 (0.9..1.1).contains(&secs),
1107 "one second of clip, got {secs:.3}s"
1108 );
1109 let energy = (samples
1110 .iter()
1111 .map(|s| f64::from(*s) * f64::from(*s))
1112 .sum::<f64>()
1113 / samples.len() as f64)
1114 .sqrt();
1115 assert!(
1116 energy > 0.005,
1117 "the exported AC-3 is silence: RMS {energy:.6}"
1118 );
1119 std::fs::remove_file(&out).unwrap();
1120}
1121
1122/// The fourth audio row, and the one that used to be a refusal: Vorbis in an Ogg
1123/// container, `ec-vorbis` encoding and `ec-ogg` paging, read straight
1124/// back through the engine's own reader like every other export here.
1125///
1126/// The shape is asserted *exactly* -- `assert_timeline_shape`, the same the WAV
1127/// and the FLAC are held to, and not the MP3's within-a-frame slack. The old
1128/// seat needed two corrections in `export::write_ogg` to earn that (its granule
1129/// numbering ran a hop early and its block grid overran the tail); `ec-vorbis`
1130/// reports spec granules and clamps its last one to the mix's own length, so
1131/// the file is written straight through and still lands here. The 1 Hz pulse
1132/// is what proves the *timing* rather than merely the length -- a stream
1133/// shifted by a block lands its peak nearer where the dip belongs.
1134#[test]
1135fn exports_the_timeline_as_an_ogg_vorbis() {
1136 let out = out_path("ogg", "ogg");
1137 let handle = engine::export::start(
1138 mixed_project(),
1139 meta(),
1140 &out,
1141 &ExportSettings {
1142 format: Format::Ogg,
1143 ..Default::default()
1144 },
1145 None,
1146 );
1147 wait(&handle, Duration::from_secs(180)).expect("ogg export");
1148 assert_eq!(handle.progress(), 1.0, "finished at full progress");
1149 assert!(!part_path(&out).exists(), "the .part was renamed away");
1150
1151 let bytes = std::fs::read(&out).expect("read the ogg back");
1152 assert_eq!(&bytes[0..4], b"OggS", "an Ogg stream, by its own magic");
1153 // Lossy, so a block straddling the cut rings into the hole: the same
1154 // 1/20-of-the-signal bar the MP3 row is held to.
1155 let (meta, samples) = decode(&out);
1156 assert_timeline_shape(&meta, &samples, 0.05);
1157 // Lossy, so it had better be well under the PCM it stands for: the
1158 // 2026-08-11 bench measured 144-176 kbps across this suite's fixtures at
1159 // this quality, against 1411 kbps of 44.1 kHz stereo PCM.
1160 let pcm = samples.len() * 2;
1161 println!("ogg {} bytes for {pcm} bytes of PCM", bytes.len());
1162 assert!(bytes.len() < pcm / 4, "lossy: {} vs {pcm}", bytes.len());
1163 std::fs::remove_file(&out).unwrap();
1164}
1165
1166/// A synthetic 44.1 kHz stereo WAV of a constant-amplitude 440 Hz tone,
1167/// `secs` long, as plain a RIFF header as `a_mono_timeline_exports_as_dual_mono_ogg`
1168/// writes -- no fixture needed, since a fade's shape is a claim about level
1169/// over time and a flat tone is the cleanest body to shape.
1170fn tone_wav(path: &Path, secs: f64) {
1171 let frames = (secs * f64::from(RATE)) as usize;
1172 let data = (frames * 4) as u32; // stereo, 16-bit
1173 let mut wav = Vec::with_capacity(44 + frames * 4);
1174 wav.extend_from_slice(b"RIFF");
1175 wav.extend_from_slice(&(36 + data).to_le_bytes());
1176 wav.extend_from_slice(b"WAVEfmt ");
1177 wav.extend_from_slice(&16u32.to_le_bytes());
1178 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
1179 wav.extend_from_slice(&2u16.to_le_bytes()); // stereo
1180 wav.extend_from_slice(&RATE.to_le_bytes());
1181 wav.extend_from_slice(&(RATE * 4).to_le_bytes()); // byte rate
1182 wav.extend_from_slice(&4u16.to_le_bytes()); // block align
1183 wav.extend_from_slice(&16u16.to_le_bytes());
1184 wav.extend_from_slice(b"data");
1185 wav.extend_from_slice(&data.to_le_bytes());
1186 for i in 0..frames {
1187 let t = i as f64 / f64::from(RATE);
1188 let s = (0.8 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() * 32767.0) as i16;
1189 wav.extend_from_slice(&s.to_le_bytes());
1190 wav.extend_from_slice(&s.to_le_bytes());
1191 }
1192 std::fs::write(path, &wav).expect("write the tone fixture");
1193}
1194
1195/// Regression for the export that drew a fade in the UI and stored it on the
1196/// clip but never carried it into the written file: a single clip with a
1197/// 1.5 s fade-in, exported as a WAV, must actually be quiet at the start and
1198/// rise across the ramp -- not the source's own flat level from sample zero.
1199#[test]
1200fn a_fade_in_reaches_the_exported_audio() {
1201 let src = out_path("fadein_src", "wav");
1202 tone_wav(&src, 3.0);
1203 let fps = 30.0;
1204 let clip = Clip {
1205 speed_keys: Vec::new(),
1206 reversed: false,
1207 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1208 angle: Default::default(),
1209 fade_in: 45, // 1.5 s at 30 fps
1210 fade_out: 0,
1211 transition_out: 0,
1212 transition_kind: Default::default(),
1213 visualizer: 0,
1214 viz_paint: 0,
1215 gain_db: 0.0,
1216 gain_keys: Vec::new(),
1217 pan: 0,
1218 pitch: 0.0,
1219 transform_keys: Vec::new(),
1220 opacity_keys: Vec::new(),
1221 color_keys: Vec::new(),
1222 effects: Vec::new(),
1223 start: 0,
1224 in_frame: 0,
1225 out_frame: 90, // 3.0 s at 30 fps
1226 source: 0,
1227 link: None,
1228 eq: None,
1229 color: None,
1230 fit: FitPolicy::default(),
1231 speed: Speed::NORMAL,
1232 transform: None,
1233 };
1234 let project = Project::from_parts(
1235 vec![Source::new(&src, 0)],
1236 vec![(LaneKind::Audio, vec![clip])],
1237 Vec::new(),
1238 Vec::new(),
1239 Vec::new(),
1240 )
1241 .expect("a one-clip fade-in project");
1242 let meta = engine::VideoMeta {
1243 width: 1,
1244 height: 1,
1245 frame_rate: fps,
1246 frame_count: 90,
1247 codec: engine::Codec::H264,
1248 color: Default::default(),
1249 matrix_assumed: false,
1250 rotation: Rotation::None,
1251 // Square pixels, coded where they are declared: a meta no container
1252 // wrote, so nothing was read to disagree with it.
1253 coded_width: 640,
1254 coded_height: 360,
1255 pixel_aspect: engine::demux::PixelAspect::SQUARE,
1256 };
1257 let out = out_path("fadein", "wav");
1258 let handle = engine::export::start(
1259 project,
1260 meta,
1261 &out,
1262 &ExportSettings {
1263 format: Format::Wav,
1264 ..Default::default()
1265 },
1266 None,
1267 );
1268 wait(&handle, Duration::from_secs(60)).expect("wav export of a faded clip");
1269
1270 let (audio, samples) = decode(&out);
1271 let channels = usize::from(audio.channels);
1272 let body = rms(&samples, channels, 2.0, 2.9);
1273 let start = rms(&samples, channels, 0.0, 0.1);
1274 let quarter = rms(&samples, channels, 0.3, 0.4);
1275 let half = rms(&samples, channels, 0.7, 0.8);
1276 let near_end = rms(&samples, channels, 1.35, 1.45);
1277 println!(
1278 "fade-in rms: start {start:.4} quarter {quarter:.4} half {half:.4} \
1279 near-end {near_end:.4} body {body:.4}"
1280 );
1281 assert!(body > 0.3, "the tone's own body is audible: {body:.4}");
1282 assert!(
1283 start < body * 0.1,
1284 "the very start is quiet: {start:.4} vs body {body:.4}"
1285 );
1286 assert!(
1287 quarter < half,
1288 "the envelope rises: {quarter:.4} -> {half:.4}"
1289 );
1290 assert!(
1291 half < near_end,
1292 "the envelope keeps rising into the ramp's end: {half:.4} -> {near_end:.4}"
1293 );
1294 assert!(
1295 (near_end - body).abs() < body * 0.15,
1296 "past the ramp the level settles at the body's own: {near_end:.4} vs {body:.4}"
1297 );
1298 std::fs::remove_file(&out).unwrap();
1299 std::fs::remove_file(&src).unwrap();
1300}
1301
1302/// Regression for the worse of the two bugs: a clip split in two and
1303/// cross-faded at the join used to go silent for its *entire* remaining
1304/// length once the fade's frame count (a handful of fps-frames) was read as
1305/// a sample count (a mixed-rate quantity thousands of times larger) -- the
1306/// gain curve's tail condition was true from a few milliseconds in to the
1307/// end of the segment. The first half's own interior, well clear of either
1308/// edge, must still be at the tone's own level.
1309#[test]
1310fn a_split_and_crossfaded_clip_has_no_muted_interior() {
1311 let src = out_path("crossfade_src", "wav");
1312 tone_wav(&src, 3.0);
1313 let fps = 30.0;
1314 let clip = |start, in_frame, out_frame| Clip {
1315 speed_keys: Vec::new(),
1316 reversed: false,
1317 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1318 angle: Default::default(),
1319 fade_in: 0,
1320 fade_out: 0,
1321 transition_out: 0,
1322 transition_kind: Default::default(),
1323 visualizer: 0,
1324 viz_paint: 0,
1325 gain_db: 0.0,
1326 gain_keys: Vec::new(),
1327 pan: 0,
1328 pitch: 0.0,
1329 transform_keys: Vec::new(),
1330 opacity_keys: Vec::new(),
1331 color_keys: Vec::new(),
1332 effects: Vec::new(),
1333 start,
1334 in_frame,
1335 out_frame,
1336 source: 0,
1337 link: None,
1338 eq: None,
1339 color: None,
1340 fit: FitPolicy::default(),
1341 speed: Speed::NORMAL,
1342 transform: None,
1343 };
1344 // The clip split at 1.5 s (45 frames @ 30 fps) into two adjacent halves,
1345 // exactly what `Project::split` leaves behind.
1346 let mut project = Project::from_parts(
1347 vec![Source::new(&src, 0)],
1348 vec![(LaneKind::Audio, vec![clip(0, 0, 45), clip(45, 45, 90)])],
1349 Vec::new(),
1350 Vec::new(),
1351 Vec::new(),
1352 )
1353 .expect("a split clip on one audio lane");
1354 assert!(
1355 project.crossfade(Lane::new(LaneKind::Audio, 0), 0, 15),
1356 "adjacent halves cross-fade at their join"
1357 );
1358 let meta = engine::VideoMeta {
1359 width: 1,
1360 height: 1,
1361 frame_rate: fps,
1362 frame_count: 90,
1363 codec: engine::Codec::H264,
1364 color: Default::default(),
1365 matrix_assumed: false,
1366 rotation: Rotation::None,
1367 // Square pixels, coded where they are declared: a meta no container
1368 // wrote, so nothing was read to disagree with it.
1369 coded_width: 640,
1370 coded_height: 360,
1371 pixel_aspect: engine::demux::PixelAspect::SQUARE,
1372 };
1373 let out = out_path("crossfade", "wav");
1374 let handle = engine::export::start(
1375 project,
1376 meta,
1377 &out,
1378 &ExportSettings {
1379 format: Format::Wav,
1380 ..Default::default()
1381 },
1382 None,
1383 );
1384 wait(&handle, Duration::from_secs(60)).expect("wav export of a cross-faded split");
1385
1386 let (audio, samples) = decode(&out);
1387 let channels = usize::from(audio.channels);
1388 // The source's own flat level, read off a stretch with no fade anywhere
1389 // near it (the second half's own interior, past its fade-in).
1390 let reference = rms(&samples, channels, 2.0, 2.9);
1391 // The first half's interior: from just past 0 to well before its own
1392 // fade-out starts at 1.0 s (45 - 15 frames = 30 frames @ 30 fps).
1393 let interior = rms(&samples, channels, 0.1, 0.9);
1394 println!("crossfade rms: interior {interior:.4} reference {reference:.4}");
1395 assert!(
1396 interior > reference * 0.7,
1397 "the first half's interior is not muted: {interior:.4} vs reference {reference:.4}"
1398 );
1399 std::fs::remove_file(&out).unwrap();
1400 std::fs::remove_file(&src).unwrap();
1401}
1402
1403/// A **mono** timeline through the same door. The format row promises stereo,
1404/// so `export::write_ogg` writes a mono mix as dual mono (the encoder itself
1405/// would serve a mono stream; the row is the contract). This is the test that
1406/// it is *dual mono* and not a widening: both channels come back
1407/// bit-identical, so folding the file back down gives exactly what was mixed.
1408#[test]
1409fn a_mono_timeline_exports_as_dual_mono_ogg() {
1410 // A mono fixture, written here because the suite has none: one second of
1411 // 440 Hz at -6 dBFS, 44.1 kHz, as plain a RIFF header as ec-riff writes.
1412 let src = out_path("mono_src", "wav");
1413 let frames = RATE as usize;
1414 let data = (frames * 2) as u32;
1415 let mut wav = Vec::with_capacity(44 + frames * 2);
1416 wav.extend_from_slice(b"RIFF");
1417 wav.extend_from_slice(&(36 + data).to_le_bytes());
1418 wav.extend_from_slice(b"WAVEfmt ");
1419 wav.extend_from_slice(&16u32.to_le_bytes());
1420 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
1421 wav.extend_from_slice(&1u16.to_le_bytes()); // one channel
1422 wav.extend_from_slice(&RATE.to_le_bytes());
1423 wav.extend_from_slice(&(RATE * 2).to_le_bytes()); // byte rate
1424 wav.extend_from_slice(&2u16.to_le_bytes()); // block align
1425 wav.extend_from_slice(&16u16.to_le_bytes());
1426 wav.extend_from_slice(b"data");
1427 wav.extend_from_slice(&data.to_le_bytes());
1428 for i in 0..frames {
1429 let t = i as f64 / f64::from(RATE);
1430 let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() * 32767.0) as i16;
1431 wav.extend_from_slice(&s.to_le_bytes());
1432 }
1433 std::fs::write(&src, &wav).expect("write the mono fixture");
1434
1435 let project = Project::from_parts(
1436 vec![Source::new(&src, 0)],
1437 vec![(
1438 LaneKind::Audio,
1439 vec![Clip {
1440 speed_keys: Vec::new(),
1441 reversed: false,
1442 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1443 angle: Default::default(),
1444 fade_in: 0,
1445 fade_out: 0,
1446 transition_out: 0,
1447 transition_kind: Default::default(),
1448 visualizer: 0,
1449 viz_paint: 0,
1450 gain_db: 0.0,
1451 gain_keys: Vec::new(),
1452 pan: 0,
1453 pitch: 0.0,
1454 transform_keys: Vec::new(),
1455 opacity_keys: Vec::new(),
1456 color_keys: Vec::new(),
1457 effects: Vec::new(),
1458 start: 0,
1459 in_frame: 0,
1460 out_frame: 30,
1461 source: 0,
1462 link: None,
1463 eq: None,
1464 color: None,
1465 fit: FitPolicy::default(),
1466 speed: Speed::NORMAL,
1467 transform: None,
1468 }],
1469 )],
1470 Vec::new(),
1471 Vec::new(),
1472 Vec::new(),
1473 )
1474 .expect("a one-source mono project");
1475
1476 let out = out_path("mono", "ogg");
1477 let handle = engine::export::start(
1478 project,
1479 meta(),
1480 &out,
1481 &ExportSettings {
1482 format: Format::Ogg,
1483 ..Default::default()
1484 },
1485 None,
1486 );
1487 wait(&handle, Duration::from_secs(180)).expect("ogg export of a mono timeline");
1488
1489 let (meta, samples) = decode(&out);
1490 assert_eq!(meta.channels, 2, "written as stereo, since Vorbis must be");
1491 assert_eq!(meta.sample_rate, RATE);
1492 // One second of clip, to the sample: the mono path gets the same trim the
1493 // stereo one does.
1494 assert_eq!(
1495 samples.len() / 2,
1496 RATE as usize,
1497 "one second, to the sample"
1498 );
1499 let worst = samples
1500 .as_chunks::<2>().0.iter()
1501 .map(|lr| f64::from(lr[0] - lr[1]).abs())
1502 .fold(0.0f64, f64::max);
1503 println!("dual mono: worst |L-R| = {worst:e}");
1504 assert_eq!(worst, 0.0, "both channels are the same signal, to the bit");
1505 let energy = (samples
1506 .iter()
1507 .map(|s| f64::from(*s) * f64::from(*s))
1508 .sum::<f64>()
1509 / samples.len() as f64)
1510 .sqrt();
1511 println!("dual mono rms {energy:.4} (the source's own is 0.354)");
1512 assert!(energy > 0.25, "the mono export is silence: RMS {energy:.6}");
1513 std::fs::remove_file(&out).unwrap();
1514 std::fs::remove_file(&src).unwrap();
1515}
1516
1517/// A WAV of a 440 Hz tone `channels` wide (1 or 2), for the layout tests: the
1518/// same file [`tone_wav`] writes, only as many channels as asked for.
1519fn tone_wav_of(path: &Path, secs: f64, channels: u16) {
1520 let frames = (secs * f64::from(RATE)) as usize;
1521 let width = usize::from(channels) * 2; // 16-bit
1522 let data = (frames * width) as u32;
1523 let mut wav = Vec::with_capacity(44 + frames * width);
1524 wav.extend_from_slice(b"RIFF");
1525 wav.extend_from_slice(&(36 + data).to_le_bytes());
1526 wav.extend_from_slice(b"WAVEfmt ");
1527 wav.extend_from_slice(&16u32.to_le_bytes());
1528 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
1529 wav.extend_from_slice(&channels.to_le_bytes());
1530 wav.extend_from_slice(&RATE.to_le_bytes());
1531 wav.extend_from_slice(&(RATE * width as u32).to_le_bytes());
1532 wav.extend_from_slice(&(width as u16).to_le_bytes()); // block align
1533 wav.extend_from_slice(&16u16.to_le_bytes());
1534 wav.extend_from_slice(b"data");
1535 wav.extend_from_slice(&data.to_le_bytes());
1536 for i in 0..frames {
1537 let t = i as f64 / f64::from(RATE);
1538 let s = (0.8 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() * 32767.0) as i16;
1539 for _ in 0..channels {
1540 wav.extend_from_slice(&s.to_le_bytes());
1541 }
1542 }
1543 std::fs::write(path, &wav).expect("write the layout fixture");
1544}
1545
1546/// One audio clip of `out_frame` frames from `source`, placed at 0.
1547fn plain_clip(source: usize, out_frame: u32) -> Clip {
1548 Clip {
1549 speed_keys: Vec::new(),
1550 reversed: false,
1551 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1552 angle: Default::default(),
1553 fade_in: 0,
1554 fade_out: 0,
1555 transition_out: 0,
1556 transition_kind: Default::default(),
1557 visualizer: 0,
1558 viz_paint: 0,
1559 gain_db: 0.0,
1560 gain_keys: Vec::new(),
1561 pan: 0,
1562 pitch: 0.0,
1563 transform_keys: Vec::new(),
1564 opacity_keys: Vec::new(),
1565 color_keys: Vec::new(),
1566 effects: Vec::new(),
1567 start: 0,
1568 in_frame: 0,
1569 out_frame,
1570 source,
1571 link: None,
1572 eq: None,
1573 color: None,
1574 fit: FitPolicy::default(),
1575 speed: Speed::NORMAL,
1576 transform: None,
1577 }
1578}
1579
1580/// Regression: a mono voiceover on A1 with a stereo music bed on A2 exported
1581/// as an mp4 came out mono, because the timeline's width was the first
1582/// source's and the bed was folded down into it. The widest source sets the
1583/// width now, and the voiceover is widened into both channels.
1584#[test]
1585fn a_mono_voiceover_under_a_stereo_bed_exports_stereo() {
1586 let voice = out_path("voice_mono", "wav");
1587 tone_wav_of(&voice, 2.0, 1);
1588 let out = out_path("vo_bed", "mp4");
1589 let project = Project::from_parts(
1590 vec![
1591 Source::new(asset("test_av.mp4"), 0),
1592 Source::new(&voice, 0),
1593 Source::new(asset("test_tone.wav"), 0),
1594 ],
1595 vec![
1596 (LaneKind::Video, vec![plain_clip(0, 90)]),
1597 (LaneKind::Audio, vec![plain_clip(1, 30)]),
1598 (LaneKind::Audio, vec![plain_clip(2, 30)]),
1599 ],
1600 Vec::new(),
1601 Vec::new(),
1602 Vec::new(),
1603 )
1604 .expect("a mono voiceover and a stereo bed");
1605 let handle = engine::export::start(
1606 project,
1607 meta(),
1608 &out,
1609 &ExportSettings {
1610 format: Format::Mp4,
1611 ..Default::default()
1612 },
1613 None,
1614 );
1615 wait(&handle, Duration::from_secs(120)).expect("mp4 export of a mono and a stereo lane");
1616 let (meta, _) = decode(&out);
1617 assert_eq!(meta.channels, 2, "the mix is stereo when one clip is");
1618 std::fs::remove_file(&out).unwrap();
1619}