forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

audio_export.rs1265 lines, 46.2 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 mp4::{MediaType, Mp4Reader};
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 fade_in: 0,
65 fade_out: 0,
66 transition_out: 0,
67 visualizer: 0,
68 viz_paint: 0,
69 start,
70 in_frame: 0,
71 out_frame: 30,
72 source,
73 link: None,
74 eq: None,
75 color: None,
76 fit: FitPolicy::default(),
77 speed: Speed::NORMAL,
78 transform: None,
79 };
80 Project::from_parts(
81 vec![
82 Source::new(asset("test_av.mp4"), 0),
83 Source::new(asset("test_tone.mp3"), 0),
84 ],
85 // The picture is beside the point here, but a project has two lanes and
86 // the timeline's length is the longer of them: three seconds of video
87 // is what makes the third second of audio part of the timeline.
88 vec![
89 (
90 LaneKind::Video,
91 vec![Clip {
92 fade_in: 0,
93 fade_out: 0,
94 transition_out: 0,
95 visualizer: 0,
96 viz_paint: 0,
97 start: 0,
98 in_frame: 0,
99 out_frame: 90,
100 source: 0,
101 link: None,
102 eq: None,
103 color: None,
104 fit: FitPolicy::default(),
105 speed: Speed::NORMAL,
106 transform: None,
107 }],
108 ),
109 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
110 ],
111 Vec::new(),
112 Vec::new(),
113 Vec::new(),
114 )
115 .expect("a two-source project with a hole in the audio lane")
116}
117
118fn meta() -> engine::VideoMeta {
119 engine::demux::Demuxer::open(&asset("test_av.mp4"))
120 .expect("open test_av")
121 .0
122}
123
124/// Interleaved samples of a written file, through the engine's own reader --
125/// the same door an import comes in through, so a pass here means the export
126/// can be brought back into a timeline.
127fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) {
128 let (meta, chunks) = AudioSession::open(path)
129 .expect("reopen the export")
130 .expect("the export has audio");
131 let mut samples = Vec::new();
132 for chunk in chunks {
133 samples.extend(chunk.samples);
134 }
135 (meta, samples)
136}
137
138/// Root mean square of `[from, to)` seconds of an interleaved stereo buffer.
139fn rms(samples: &[f32], channels: usize, from: f64, to: f64) -> f64 {
140 let at = |secs: f64| (secs * f64::from(RATE)) as usize * channels;
141 let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
142 assert!(!window.is_empty(), "no samples in [{from}, {to})");
143 (window
144 .iter()
145 .map(|s| f64::from(*s) * f64::from(*s))
146 .sum::<f64>()
147 / window.len() as f64)
148 .sqrt()
149}
150
151/// What every audio export must be, whatever encoded it: exactly as long as the
152/// timeline, silent where the timeline is empty, and audible where it is not --
153/// with the fixtures' 1 Hz pulse still in it, which is what says the samples are
154/// the *edit's* and not just noise of the right length.
155///
156/// `gap_ceiling` is how loud the hole in the middle may be as a fraction of the
157/// first second: `0.0` for a lossless format, where the silence is the samples
158/// themselves, and a real fraction for a lossy one, where a block straddling the
159/// cut rings into it. Never an absolute level -- the fixtures peak around 0.12.
160fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32], gap_ceiling: f64) {
161 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2), "as decoded");
162 let channels = usize::from(meta.channels);
163 // Three seconds of timeline, to the sample: the segments round their own
164 // windows and the mp3 need not end where the second does, so this is the
165 // export's own trim/pad and not an accident of the sources.
166 let frames = (3.0 * f64::from(RATE)) as usize;
167 assert_eq!(
168 samples.len(),
169 frames * channels,
170 "timeline length in samples"
171 );
172
173 // Second 0 is test_av, second 2 is the mp3; both carry the tone.
174 let av = rms(samples, channels, 0.05, 0.95);
175 let tone = rms(samples, channels, 2.05, 2.95);
176 // Second 1 is the hole. Silence, not a stall and not a skip: it occupies
177 // its full second, which is what the sample count above already proved.
178 let gap = rms(samples, channels, 1.0, 2.0);
179 println!("rms: av {av:.4} gap {gap:.6} mp3 {tone:.4}");
180 assert!(av > 0.01, "the first second is audible");
181 assert!(tone > 0.01, "the mp3 second is audible");
182 assert!(
183 gap <= av * gap_ceiling,
184 "the gap is silence: {gap:.6} against {av:.4} of first second"
185 );
186
187 // The 1 Hz pulse: `volume = 0.5 + 0.5 sin(2 pi t)`, so a peak sits at
188 // t = 0.25 and the dip at t = 0.75. Ratio, never an absolute level.
189 let peak = rms(samples, channels, 0.2, 0.3);
190 let dip = rms(samples, channels, 0.7, 0.8);
191 println!(
192 "pulse: peak {peak:.4} dip {dip:.4} ratio {:.1}",
193 peak / dip
194 );
195 assert!(
196 peak > dip * 4.0,
197 "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}"
198 );
199}
200
201/// The RIFF header itself, byte for byte: hound writes it, but what a player
202/// reads is the bytes, and a wrong rate or a wrong `data` size is a file that
203/// decodes at the wrong speed rather than one that fails to open.
204fn assert_wav_header(path: &Path, frames: usize) {
205 let bytes = std::fs::read(path).expect("read the wav back");
206 let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]);
207 let u32_at =
208 |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]);
209 assert_eq!(&bytes[0..4], b"RIFF");
210 assert_eq!(&bytes[8..12], b"WAVE");
211 assert_eq!(&bytes[12..16], b"fmt ");
212 assert_eq!(u32_at(4) as usize, bytes.len() - 8, "RIFF size");
213 assert_eq!(u16_at(20), 1, "PCM, not a float or a compressed tag");
214 assert_eq!(u16_at(22), 2, "stereo");
215 assert_eq!(u32_at(24), RATE, "sample rate");
216 assert_eq!(u32_at(28), RATE * 2 * 2, "byte rate = rate * channels * 2");
217 assert_eq!(u16_at(32), 4, "block align");
218 assert_eq!(u16_at(34), 16, "bits per sample");
219 // The `data` chunk carries every sample and nothing else. hound may write a
220 // `fact` chunk first, so it is found rather than assumed to be at 36.
221 let data = bytes
222 .windows(4)
223 .position(|w| w == b"data")
224 .expect("a data chunk");
225 assert_eq!(u32_at(data + 4) as usize, frames * 2 * 2, "data chunk size");
226}
227
228#[test]
229fn exports_the_timeline_as_a_wav() {
230 let out = out_path("wav", "wav");
231 let handle = engine::export::start(
232 mixed_project(),
233 meta(),
234 &out,
235 &ExportSettings {
236 format: Format::Wav,
237 ..Default::default()
238 },
239 None,
240 );
241 wait(&handle, Duration::from_secs(60)).expect("wav export");
242 assert_eq!(handle.progress(), 1.0, "finished at full progress");
243 assert!(!part_path(&out).exists(), "the .part was renamed away");
244
245 let (meta, samples) = decode(&out);
246 assert_timeline_shape(&meta, &samples, 0.0);
247 assert_wav_header(&out, samples.len() / usize::from(meta.channels));
248 std::fs::remove_file(&out).unwrap();
249}
250
251#[test]
252fn exports_the_timeline_as_a_flac() {
253 let out = out_path("flac", "flac");
254 let handle = engine::export::start(
255 mixed_project(),
256 meta(),
257 &out,
258 &ExportSettings {
259 format: Format::Flac,
260 ..Default::default()
261 },
262 None,
263 );
264 wait(&handle, Duration::from_secs(60)).expect("flac export");
265 assert_eq!(handle.progress(), 1.0, "finished at full progress");
266
267 let bytes = std::fs::read(&out).expect("read the flac back");
268 assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic");
269 // Lossless is a claim about the samples, so it is checked on the samples:
270 // the same shape the WAV of the same timeline has.
271 let (meta, samples) = decode(&out);
272 assert_timeline_shape(&meta, &samples, 0.0);
273 // Smaller than the PCM it encodes, or the whole point of the row is gone.
274 let pcm = samples.len() * 2;
275 println!("flac {} bytes for {pcm} bytes of PCM", bytes.len());
276 assert!(bytes.len() < pcm, "compressed");
277 std::fs::remove_file(&out).unwrap();
278}
279
280/// The third audio row, and the one that used to be a licence note: `ec-mp3`
281/// encodes it, and the file is read straight back through symphonia's mp3
282/// decoder -- the very door an mp3 *import* comes in through, so an export can
283/// be dropped back onto the timeline it came from.
284///
285/// The shape is checked loosely where MP3 cannot be exact: the encoder pads its
286/// tail to a whole 1152-frame frame and the decoder hands back the padding, so
287/// the length is asserted to within a frame instead of to the sample. What is
288/// exact is the edit -- audible, silent, audible -- and the fixtures' 1 Hz
289/// pulse inside the first second.
290#[test]
291fn exports_the_timeline_as_an_mp3() {
292 let out = out_path("mp3", "mp3");
293 let handle = engine::export::start(
294 mixed_project(),
295 meta(),
296 &out,
297 &ExportSettings {
298 format: Format::Mp3,
299 ..Default::default()
300 },
301 None,
302 );
303 wait(&handle, Duration::from_secs(120)).expect("mp3 export");
304 assert_eq!(handle.progress(), 1.0, "finished at full progress");
305 assert!(!part_path(&out).exists(), "the .part was renamed away");
306
307 let (meta, samples) = decode(&out);
308 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
309 let channels = usize::from(meta.channels);
310 let frames = samples.len() / channels;
311 let timeline = (3.0 * f64::from(RATE)) as usize;
312 assert!(
313 frames >= timeline && frames <= timeline + 2 * 1152,
314 "{frames} frames for a three-second timeline ({timeline})"
315 );
316 let av = rms(&samples, channels, 0.05, 0.95);
317 let gap = rms(&samples, channels, 1.1, 1.9);
318 let tone = rms(&samples, channels, 2.05, 2.95);
319 println!("mp3 rms: av {av:.4} gap {gap:.6} mp3 second {tone:.4}");
320 assert!(av > 0.01, "the first second is audible");
321 assert!(tone > 0.01, "the mp3 second is audible");
322 assert!(gap < av / 20.0, "the hole is silence: {gap:.6}");
323 let peak = rms(&samples, channels, 0.2, 0.3);
324 let dip = rms(&samples, channels, 0.7, 0.8);
325 assert!(
326 peak > dip * 4.0,
327 "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}"
328 );
329 std::fs::remove_file(&out).unwrap();
330}
331
332/// The failure a user hit, as a test: a still picture and a song, exported as an
333/// **mp4**. There is no AAC track anywhere in that timeline to copy -- an mp3
334/// holds no such packets and a png holds nothing at all -- so this used to be
335/// refused by name and the only way out was a WAV beside a picture nobody had.
336/// The song is decoded and encoded as AAC instead (`export::copy_audio` falls
337/// through to `encode_audio`), and the file comes back with picture *and* sound.
338#[test]
339fn a_still_and_a_song_export_as_an_mp4_with_sound() {
340 let song = asset("test_tone.mp3");
341 let still = asset("test_still.png");
342 let clip = |source, frames| Clip {
343 fade_in: 0,
344 fade_out: 0,
345 transition_out: 0,
346 visualizer: 0,
347 viz_paint: 0,
348 start: 0,
349 in_frame: 0,
350 out_frame: frames,
351 source,
352 link: None,
353 eq: None,
354 color: None,
355 fit: FitPolicy::default(),
356 speed: Speed::NORMAL,
357 transform: None,
358 };
359 // Two seconds of each at the project's own 30 fps: a still has no length of
360 // its own and the song is longer than what is placed.
361 let project = Project::from_parts(
362 vec![Source::new(still, 0), Source::new(song, 0)],
363 vec![
364 (LaneKind::Video, vec![clip(0, 60)]),
365 (LaneKind::Audio, vec![clip(1, 60)]),
366 ],
367 Vec::new(),
368 Vec::new(),
369 Vec::new(),
370 )
371 .expect("a still under a song");
372 // The project's own picture size and rate: the still decides the one and
373 // the scaffold the other, exactly as opening a png in the editor does.
374 let meta = engine::VideoMeta {
375 width: 640,
376 height: 360,
377 frame_rate: 30.0,
378 frame_count: 60,
379 codec: engine::Codec::H264,
380 color: Default::default(),
381 rotation: Rotation::None,
382 // Square pixels, coded where they are declared: a meta no container
383 // wrote, so nothing was read to disagree with it.
384 coded_width: 640,
385 coded_height: 360,
386 pixel_aspect: engine::demux::PixelAspect::SQUARE,
387 };
388 let out = out_path("still_song", "mp4");
389 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
390 wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");
391
392 // Picture: two seconds of it, through the demuxer an import uses.
393 let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
394 assert_eq!((written.width, written.height), (640, 360));
395 assert_eq!(written.frame_count, 60, "two seconds at 30 fps");
396 // ...and sound, which is the half that used to be missing.
397 let (audio, samples) = decode(&out);
398 let channels = usize::from(audio.channels);
399 let heard = rms(&samples, channels, 0.2, 1.8);
400 println!("still+song: {} Hz, rms {heard:.4}", audio.sample_rate);
401 assert!(heard > 0.01, "the song is in the file (rms {heard:.4})");
402 std::fs::remove_file(&out).unwrap();
403}
404
405/// Cancel leaves nothing behind -- not the output, not the `.part`. The
406/// timeline is long enough (a minute of audio) that the escape lands mid-decode
407/// rather than after the file is already closed.
408/// What the two mix settings do to a *written file*, which is the only place
409/// the claim can be checked: a track's fader is that track's alone, and the
410/// master limiter holds the sum of them under its ceiling instead of letting it
411/// square off at full scale.
412///
413/// Four audio tracks of the same second, so the sum is four times one file and
414/// well past what a sample can hold. Measured as the peak of the WAV read back
415/// through the engine's own reader -- a level, not a shape, because that is
416/// exactly what a limiter promises.
417#[test]
418fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() {
419 let clip = Clip {
420 fade_in: 0,
421 fade_out: 0,
422 transition_out: 0,
423 visualizer: 0,
424 viz_paint: 0,
425 start: 0,
426 in_frame: 0,
427 out_frame: 30,
428 source: 0,
429 link: None,
430 eq: None,
431 color: None,
432 fit: FitPolicy::default(),
433 speed: Speed::NORMAL,
434 transform: None,
435 };
436 let four = || {
437 Project::from_parts(
438 vec![Source::new(asset("test_av.mp4"), 0)],
439 vec![
440 (LaneKind::Video, vec![clip]),
441 (LaneKind::Audio, vec![clip]),
442 (LaneKind::Audio, vec![clip]),
443 (LaneKind::Audio, vec![clip]),
444 (LaneKind::Audio, vec![clip]),
445 ],
446 Vec::new(),
447 Vec::new(),
448 Vec::new(),
449 )
450 .expect("one second on four audio tracks")
451 };
452 let write = |project: Project, name: &str| {
453 let out = out_path(name, "wav");
454 let handle = engine::export::start(
455 project,
456 meta(),
457 &out,
458 &ExportSettings {
459 format: Format::Wav,
460 ..Default::default()
461 },
462 None,
463 );
464 wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}"));
465 let (audio, samples) = decode(&out);
466 let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
467 let level = rms(&samples, usize::from(audio.channels), 0.05, 0.95);
468 let _ = std::fs::remove_file(&out);
469 (peak, level)
470 };
471
472 // Four copies of one file, each fader all the way up: the sum is well past
473 // what a sample can hold, and with no limiter it is clamped at full scale
474 // by the mixer's own backstop -- which is the clipping this exists for.
475 let hot = || {
476 let mut project = four();
477 for ord in 0..4 {
478 assert!(project.set_lane_gain_db(
479 Lane::new(LaneKind::Audio, ord),
480 engine::project::MAX_GAIN_DB
481 ));
482 }
483 project
484 };
485 let (flat_peak, flat_level) = write(hot(), "mix_flat");
486 println!("flat: peak {flat_peak:.4} rms {flat_level:.4}");
487
488 // One track's fader, and one track's only: A2, A3 and A4 all the way down
489 // leaves a quarter of the sum, so the level drops by ~12 dB against the
490 // four of them at the same setting. A whole-band
491 // change -- there is no frequency in this claim, which is what makes it a
492 // different control from the equalizer.
493 let (unity_peak, unity_level) = write(four(), "mix_unity");
494 let mut down = four();
495 for ord in 1..4 {
496 assert!(down.set_lane_gain_db(
497 Lane::new(LaneKind::Audio, ord),
498 engine::project::MIN_GAIN_DB
499 ));
500 }
501 let (_, quiet_level) = write(down, "mix_fader");
502 let drop_db = 20.0 * (quiet_level / unity_level).log10();
503 println!("one track alone: rms {quiet_level:.4} ({drop_db:.1} dB)");
504 assert!(
505 (drop_db + 12.0).abs() < 1.5,
506 "three of four tracks down left {drop_db:.1} dB, not ~-12"
507 );
508
509 // The limiter over the same hot sum: the peak lands under the ceiling, and
510 // the sound is still there (a limiter that silenced the mix would pass a
511 // peak test and fail every ear).
512 let ceiling_db = -3.0;
513 let mut limited = hot();
514 assert!(limited.set_limiter(engine::limiter::Limiter {
515 ceiling_db,
516 on: true,
517 }));
518 let (peak, level) = write(limited, "mix_limited");
519 let ceiling = 10f32.powf(ceiling_db / 20.0);
520 println!("limited: peak {peak:.4} vs ceiling {ceiling:.4} rms {level:.4}");
521 assert!(
522 flat_peak > ceiling,
523 "the flat mix was not hot to begin with"
524 );
525 assert!(
526 peak <= ceiling + 1e-3,
527 "peak {peak:.4} passed the {ceiling:.4} ceiling"
528 );
529 assert!(level > unity_level, "the limiter took the mix out");
530 assert!(
531 unity_peak < 1.0,
532 "four at unity fit; the +12 dB four did not"
533 );
534}
535
536#[test]
537fn a_cancelled_audio_export_leaves_no_file() {
538 let source = asset("test_av.mp4");
539 let (meta, _) = engine::demux::Demuxer::open(&source).expect("open test_av");
540 let mut project = Project::single(&source, meta.frame_count);
541 for _ in 0..11 {
542 assert!(project.append_clip(0, meta.frame_count), "a minute of it");
543 }
544 let out = out_path("cancel", "wav");
545 let handle = engine::export::start(
546 project,
547 meta,
548 &out,
549 &ExportSettings {
550 format: Format::Wav,
551 ..Default::default()
552 },
553 None,
554 );
555 handle.cancel();
556 let outcome = wait(&handle, Duration::from_secs(120));
557 let text = outcome.expect_err("a cancelled export fails").to_string();
558 assert!(text.contains("cancelled"), "{text}");
559 assert!(!out.exists(), "no output file");
560 assert!(!part_path(&out).exists(), "no half-written .part either");
561}
562
563/// The rate an MP3 file *declares*, read out of its own frame headers -- the
564/// only place the claim can be checked, since a caller's kbps is a request until
565/// the bytes say so. MPEG-1 Layer III, whose bitrate index is the high nibble of
566/// the third header byte.
567fn mp3_declared_kbps(path: &Path) -> u32 {
568 const KBPS: [u32; 16] = [
569 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0,
570 ];
571 let bytes = std::fs::read(path).expect("read the mp3 back");
572 let at = bytes
573 .windows(4)
574 .position(|w| w[0] == 0xFF && w[1] & 0xE0 == 0xE0)
575 .expect("an MPEG frame sync");
576 let header = &bytes[at..at + 4];
577 assert_eq!(header[1] >> 3 & 0x3, 0b11, "MPEG-1");
578 assert_eq!(header[1] >> 1 & 0x3, 0b01, "Layer III");
579 let kbps = KBPS[usize::from(header[2] >> 4)];
580 assert!(kbps > 0, "a free-format or invalid bitrate index");
581 kbps
582}
583
584/// What an mp4's AAC track is really coded at: its sample bytes over the time
585/// they play, in kbps. Every AAC-LC packet is 1024 frames per channel, so the
586/// duration comes out of the packet count and needs no timescale of the file's
587/// own -- and the bytes are what a player downloads, which is what a bitrate is.
588fn mp4_aac_kbps(path: &Path, sample_rate: f64) -> f64 {
589 let file = File::open(path).expect("reopen the mp4");
590 let size = file.metadata().unwrap().len();
591 let mut reader = Mp4Reader::read_header(BufReader::new(file), size).expect("mp4 header");
592 let track = reader
593 .tracks()
594 .values()
595 .find(|t| matches!(t.media_type(), Ok(MediaType::AAC)))
596 .expect("an AAC track")
597 .track_id();
598 let count = reader.sample_count(track).expect("sample count");
599 let mut bytes = 0usize;
600 for id in 1..=count {
601 bytes += reader
602 .read_sample(track, id)
603 .expect("read a sample")
604 .expect("a sample at every id")
605 .bytes
606 .len();
607 }
608 let seconds = f64::from(count) * 1024.0 / sample_rate;
609 bytes as f64 * 8.0 / seconds / 1000.0
610}
611
612/// The sound's rate is the caller's, in both kinds of file -- and the file
613/// nobody asked a rate of is the one this program always wrote.
614///
615/// MP3 declares its rate in every frame header, so that half is exact. The AAC
616/// half is measured off the mp4's own sample table: a rate control lands *near*
617/// its target rather than on it, so the tolerance is a fifth, which is far
618/// tighter than the gap between two offered rates.
619#[test]
620fn the_sound_is_written_at_the_rate_that_was_asked_for() {
621 // Untouched settings first: this is the byte-behaviour a user who never
622 // opens the row is entitled to keep.
623 for (kbps, want) in [
624 (None, engine::export::DEFAULT_AUDIO_KBPS),
625 (Some(128), 128),
626 (Some(320), 320),
627 ] {
628 let out = out_path(&format!("mp3_{}", want), "mp3");
629 let handle = engine::export::start(
630 mixed_project(),
631 meta(),
632 &out,
633 &ExportSettings {
634 format: Format::Mp3,
635 audio_kbps: kbps,
636 ..Default::default()
637 },
638 None,
639 );
640 wait(&handle, Duration::from_secs(120)).expect("mp3 export");
641 let got = mp3_declared_kbps(&out);
642 println!("mp3 asked {kbps:?}, header says {got} kbps");
643 assert_eq!(got, want, "the mp3 frames declare the rate that was picked");
644 // ...and it is still the edit, not just bytes at the right rate.
645 let (meta, samples) = decode(&out);
646 let channels = usize::from(meta.channels);
647 assert!(rms(&samples, channels, 0.05, 0.95) > 0.01, "audible");
648 std::fs::remove_file(&out).unwrap();
649 }
650
651 // The same choice inside a video export, where the sound is AAC: a song
652 // under a still, which no mp4 sample table can be copied from, so the
653 // encoder really runs.
654 let project = Project::from_parts(
655 vec![
656 Source::new(asset("test_still.png"), 0),
657 Source::new(asset("test_tone.mp3"), 0),
658 ],
659 vec![
660 (
661 LaneKind::Video,
662 vec![Clip {
663 fade_in: 0,
664 fade_out: 0,
665 transition_out: 0,
666 visualizer: 0,
667 viz_paint: 0,
668 start: 0,
669 in_frame: 0,
670 out_frame: 60,
671 source: 0,
672 link: None,
673 eq: None,
674 color: None,
675 fit: FitPolicy::default(),
676 speed: Speed::NORMAL,
677 transform: None,
678 }],
679 ),
680 (
681 LaneKind::Audio,
682 vec![Clip {
683 fade_in: 0,
684 fade_out: 0,
685 transition_out: 0,
686 visualizer: 0,
687 viz_paint: 0,
688 start: 0,
689 in_frame: 0,
690 out_frame: 60,
691 source: 1,
692 link: None,
693 eq: None,
694 color: None,
695 fit: FitPolicy::default(),
696 speed: Speed::NORMAL,
697 transform: None,
698 }],
699 ),
700 ],
701 Vec::new(),
702 Vec::new(),
703 Vec::new(),
704 )
705 .expect("a still under a song");
706 let meta = engine::VideoMeta {
707 width: 640,
708 height: 360,
709 frame_rate: 30.0,
710 frame_count: 60,
711 codec: engine::Codec::H264,
712 color: Default::default(),
713 rotation: Rotation::None,
714 // Square pixels, coded where they are declared: a meta no container
715 // wrote, so nothing was read to disagree with it.
716 coded_width: 640,
717 coded_height: 360,
718 pixel_aspect: engine::demux::PixelAspect::SQUARE,
719 };
720 for want in [128u32, 320] {
721 let out = out_path(&format!("mp4_aac_{want}"), "mp4");
722 let handle = engine::export::start(
723 project.clone(),
724 meta,
725 &out,
726 &ExportSettings {
727 audio_kbps: Some(want),
728 ..Default::default()
729 },
730 None,
731 );
732 wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song");
733 let got = mp4_aac_kbps(&out, f64::from(RATE));
734 println!("mp4 asked {want} kbps, the track measures {got:.1}");
735 assert!(
736 (got - f64::from(want)).abs() < f64::from(want) / 5.0,
737 "{got:.1} kbps for a {want} kbps request"
738 );
739 std::fs::remove_file(&out).unwrap();
740 }
741}
742
743/// The samples a silent take contributes: a clip of a file with no audio track
744/// is silence for exactly its span, between two clips that are heard. This is
745/// what makes `PlaybackSession::import` letting such a file in honest -- the
746/// export reads the same play list playback does, so a hole here is a hole in
747/// the ear too.
748#[test]
749fn a_silent_clip_exports_as_silence_over_its_own_span() {
750 let clip = |start, source| Clip {
751 fade_in: 0,
752 fade_out: 0,
753 transition_out: 0,
754 visualizer: 0,
755 viz_paint: 0,
756 start,
757 in_frame: 0,
758 out_frame: 30,
759 source,
760 link: None,
761 eq: None,
762 color: None,
763 fit: FitPolicy::default(),
764 speed: Speed::NORMAL,
765 transform: None,
766 };
767 let project = Project::from_parts(
768 vec![
769 Source::new(asset("test_av.mp4"), 0),
770 // Video only, no audio track at all: the silent take.
771 Source::new(asset("test_mismatch.mp4"), 0),
772 ],
773 vec![
774 (LaneKind::Video, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
775 (LaneKind::Audio, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
776 ],
777 Vec::new(),
778 Vec::new(),
779 Vec::new(),
780 )
781 .expect("a project whose middle take is silent");
782
783 let out = out_path("silent_clip", "wav");
784 let handle = engine::export::start(
785 project,
786 meta(),
787 &out,
788 &ExportSettings {
789 format: Format::Wav,
790 ..Default::default()
791 },
792 None,
793 );
794 wait(&handle, Duration::from_secs(60)).expect("wav export");
795 let (audio, samples) = decode(&out);
796 let channels = usize::from(audio.channels);
797 assert_eq!(
798 samples.len(),
799 (3.0 * f64::from(RATE)) as usize * channels,
800 "three seconds of timeline, silent take included"
801 );
802 let heard = rms(&samples, channels, 0.05, 0.95);
803 let quiet = rms(&samples, channels, 1.0, 2.0);
804 let again = rms(&samples, channels, 2.05, 2.95);
805 println!("rms: heard {heard:.4} silent take {quiet:.6} heard {again:.4}");
806 assert!(heard > 0.01, "the first take is audible");
807 assert!(again > 0.01, "the third take is audible");
808 assert_eq!(quiet, 0.0, "the silent take is exact silence, not a stall");
809 std::fs::remove_file(&out).unwrap();
810}
811
812/// A silent timeline cannot become an audio file, and says so rather than
813/// writing zero samples that a user would take for a broken microphone.
814#[test]
815fn a_silent_timeline_refuses_an_audio_export() {
816 let source = asset("test_mismatch.mp4"); // video only, no audio track
817 let (meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture");
818 let out = out_path("silent", "wav");
819 let handle = engine::export::start(
820 Project::single(&source, meta.frame_count),
821 meta,
822 &out,
823 &ExportSettings {
824 format: Format::Wav,
825 ..Default::default()
826 },
827 None,
828 );
829 let text = wait(&handle, Duration::from_secs(60))
830 .expect_err("no audio to export")
831 .to_string();
832 assert!(text.contains("no audio"), "{text}");
833 assert!(
834 !out.exists() && !part_path(&out).exists(),
835 "nothing written"
836 );
837}
838
839/// An AC-3 source through the audio-only door: the mp4 export cannot
840/// copy a syncframe into an `mp4a` track, but a WAV of the same timeline
841/// decodes, downmixes and reopens through the engine's own reader.
842#[test]
843fn a_51_ac3_source_round_trips_through_a_wav() {
844 let source = asset("test_ac3_51.mp4");
845 let project = Project::from_parts(
846 vec![Source::new(source.clone(), 0)],
847 vec![(
848 LaneKind::Audio,
849 vec![Clip {
850 fade_in: 0,
851 fade_out: 0,
852 transition_out: 0,
853 visualizer: 0,
854 viz_paint: 0,
855 start: 0,
856 in_frame: 0,
857 out_frame: 30,
858 source: 0,
859 link: None,
860 eq: None,
861 color: None,
862 fit: FitPolicy::default(),
863 speed: Speed::NORMAL,
864 transform: None,
865 }],
866 )],
867 Vec::new(),
868 Vec::new(),
869 Vec::new(),
870 )
871 .expect("a one-source AC-3 project");
872 let video = engine::demux::Demuxer::open(&source)
873 .expect("open the fixture")
874 .0;
875
876 let out = out_path("ac3", "wav");
877 let handle = engine::export::start(
878 project,
879 video,
880 &out,
881 &ExportSettings {
882 format: Format::Wav,
883 ..Default::default()
884 },
885 None,
886 );
887 wait(&handle, Duration::from_secs(60)).expect("wav export of an AC-3 source");
888
889 let (meta, samples) = decode(&out);
890 assert_eq!(
891 (meta.sample_rate, meta.channels),
892 (48_000, 2),
893 "the §7.8 downmix is what reaches the file"
894 );
895 let secs = (samples.len() / 2) as f64 / 48_000.;
896 assert!(
897 (0.9..1.1).contains(&secs),
898 "one second of clip, got {secs:.3}s"
899 );
900 let energy = (samples
901 .iter()
902 .map(|s| f64::from(*s) * f64::from(*s))
903 .sum::<f64>()
904 / samples.len() as f64)
905 .sqrt();
906 assert!(
907 energy > 0.005,
908 "the exported AC-3 is silence: RMS {energy:.6}"
909 );
910 std::fs::remove_file(&out).unwrap();
911}
912
913/// The fourth audio row, and the one that used to be a refusal: Vorbis in an Ogg
914/// container, `ec-vorbis` encoding and `oxideav-ogg` paging, read straight
915/// back through the engine's own reader like every other export here.
916///
917/// The shape is asserted *exactly* -- `assert_timeline_shape`, the same the WAV
918/// and the FLAC are held to, and not the MP3's within-a-frame slack. The old
919/// seat needed two corrections in `export::write_ogg` to earn that (its granule
920/// numbering ran a hop early and its block grid overran the tail); `ec-vorbis`
921/// reports spec granules and clamps its last one to the mix's own length, so
922/// the file is written straight through and still lands here. The 1 Hz pulse
923/// is what proves the *timing* rather than merely the length -- a stream
924/// shifted by a block lands its peak nearer where the dip belongs.
925#[test]
926fn exports_the_timeline_as_an_ogg_vorbis() {
927 let out = out_path("ogg", "ogg");
928 let handle = engine::export::start(
929 mixed_project(),
930 meta(),
931 &out,
932 &ExportSettings {
933 format: Format::Ogg,
934 ..Default::default()
935 },
936 None,
937 );
938 wait(&handle, Duration::from_secs(180)).expect("ogg export");
939 assert_eq!(handle.progress(), 1.0, "finished at full progress");
940 assert!(!part_path(&out).exists(), "the .part was renamed away");
941
942 let bytes = std::fs::read(&out).expect("read the ogg back");
943 assert_eq!(&bytes[0..4], b"OggS", "an Ogg stream, by its own magic");
944 // Lossy, so a block straddling the cut rings into the hole: the same
945 // 1/20-of-the-signal bar the MP3 row is held to.
946 let (meta, samples) = decode(&out);
947 assert_timeline_shape(&meta, &samples, 0.05);
948 // Lossy, so it had better be well under the PCM it stands for: the
949 // 2026-08-11 bench measured 144-176 kbps across this suite's fixtures at
950 // this quality, against 1411 kbps of 44.1 kHz stereo PCM.
951 let pcm = samples.len() * 2;
952 println!("ogg {} bytes for {pcm} bytes of PCM", bytes.len());
953 assert!(bytes.len() < pcm / 4, "lossy: {} vs {pcm}", bytes.len());
954 std::fs::remove_file(&out).unwrap();
955}
956
957/// A synthetic 44.1 kHz stereo WAV of a constant-amplitude 440 Hz tone,
958/// `secs` long, as plain a RIFF header as `a_mono_timeline_exports_as_dual_mono_ogg`
959/// writes -- no fixture needed, since a fade's shape is a claim about level
960/// over time and a flat tone is the cleanest body to shape.
961fn tone_wav(path: &Path, secs: f64) {
962 let frames = (secs * f64::from(RATE)) as usize;
963 let data = (frames * 4) as u32; // stereo, 16-bit
964 let mut wav = Vec::with_capacity(44 + frames * 4);
965 wav.extend_from_slice(b"RIFF");
966 wav.extend_from_slice(&(36 + data).to_le_bytes());
967 wav.extend_from_slice(b"WAVEfmt ");
968 wav.extend_from_slice(&16u32.to_le_bytes());
969 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
970 wav.extend_from_slice(&2u16.to_le_bytes()); // stereo
971 wav.extend_from_slice(&RATE.to_le_bytes());
972 wav.extend_from_slice(&(RATE * 4).to_le_bytes()); // byte rate
973 wav.extend_from_slice(&4u16.to_le_bytes()); // block align
974 wav.extend_from_slice(&16u16.to_le_bytes());
975 wav.extend_from_slice(b"data");
976 wav.extend_from_slice(&data.to_le_bytes());
977 for i in 0..frames {
978 let t = i as f64 / f64::from(RATE);
979 let s = (0.8 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() * 32767.0) as i16;
980 wav.extend_from_slice(&s.to_le_bytes());
981 wav.extend_from_slice(&s.to_le_bytes());
982 }
983 std::fs::write(path, &wav).expect("write the tone fixture");
984}
985
986/// Regression for the export that drew a fade in the UI and stored it on the
987/// clip but never carried it into the written file: a single clip with a
988/// 1.5 s fade-in, exported as a WAV, must actually be quiet at the start and
989/// rise across the ramp -- not the source's own flat level from sample zero.
990#[test]
991fn a_fade_in_reaches_the_exported_audio() {
992 let src = out_path("fadein_src", "wav");
993 tone_wav(&src, 3.0);
994 let fps = 30.0;
995 let clip = Clip {
996 fade_in: 45, // 1.5 s at 30 fps
997 fade_out: 0,
998 transition_out: 0,
999 visualizer: 0,
1000 viz_paint: 0,
1001 start: 0,
1002 in_frame: 0,
1003 out_frame: 90, // 3.0 s at 30 fps
1004 source: 0,
1005 link: None,
1006 eq: None,
1007 color: None,
1008 fit: FitPolicy::default(),
1009 speed: Speed::NORMAL,
1010 transform: None,
1011 };
1012 let project = Project::from_parts(
1013 vec![Source::new(src.to_path_buf(), 0)],
1014 vec![(LaneKind::Audio, vec![clip])],
1015 Vec::new(),
1016 Vec::new(),
1017 Vec::new(),
1018 )
1019 .expect("a one-clip fade-in project");
1020 let meta = engine::VideoMeta {
1021 width: 1,
1022 height: 1,
1023 frame_rate: fps,
1024 frame_count: 90,
1025 codec: engine::Codec::H264,
1026 color: Default::default(),
1027 rotation: Rotation::None,
1028 // Square pixels, coded where they are declared: a meta no container
1029 // wrote, so nothing was read to disagree with it.
1030 coded_width: 640,
1031 coded_height: 360,
1032 pixel_aspect: engine::demux::PixelAspect::SQUARE,
1033 };
1034 let out = out_path("fadein", "wav");
1035 let handle = engine::export::start(
1036 project,
1037 meta,
1038 &out,
1039 &ExportSettings {
1040 format: Format::Wav,
1041 ..Default::default()
1042 },
1043 None,
1044 );
1045 wait(&handle, Duration::from_secs(60)).expect("wav export of a faded clip");
1046
1047 let (audio, samples) = decode(&out);
1048 let channels = usize::from(audio.channels);
1049 let body = rms(&samples, channels, 2.0, 2.9);
1050 let start = rms(&samples, channels, 0.0, 0.1);
1051 let quarter = rms(&samples, channels, 0.3, 0.4);
1052 let half = rms(&samples, channels, 0.7, 0.8);
1053 let near_end = rms(&samples, channels, 1.35, 1.45);
1054 println!(
1055 "fade-in rms: start {start:.4} quarter {quarter:.4} half {half:.4} \
1056 near-end {near_end:.4} body {body:.4}"
1057 );
1058 assert!(body > 0.3, "the tone's own body is audible: {body:.4}");
1059 assert!(
1060 start < body * 0.1,
1061 "the very start is quiet: {start:.4} vs body {body:.4}"
1062 );
1063 assert!(
1064 quarter < half,
1065 "the envelope rises: {quarter:.4} -> {half:.4}"
1066 );
1067 assert!(
1068 half < near_end,
1069 "the envelope keeps rising into the ramp's end: {half:.4} -> {near_end:.4}"
1070 );
1071 assert!(
1072 (near_end - body).abs() < body * 0.15,
1073 "past the ramp the level settles at the body's own: {near_end:.4} vs {body:.4}"
1074 );
1075 std::fs::remove_file(&out).unwrap();
1076 std::fs::remove_file(&src).unwrap();
1077}
1078
1079/// Regression for the worse of the two bugs: a clip split in two and
1080/// cross-faded at the join used to go silent for its *entire* remaining
1081/// length once the fade's frame count (a handful of fps-frames) was read as
1082/// a sample count (a mixed-rate quantity thousands of times larger) -- the
1083/// gain curve's tail condition was true from a few milliseconds in to the
1084/// end of the segment. The first half's own interior, well clear of either
1085/// edge, must still be at the tone's own level.
1086#[test]
1087fn a_split_and_crossfaded_clip_has_no_muted_interior() {
1088 let src = out_path("crossfade_src", "wav");
1089 tone_wav(&src, 3.0);
1090 let fps = 30.0;
1091 let clip = |start, in_frame, out_frame| Clip {
1092 fade_in: 0,
1093 fade_out: 0,
1094 transition_out: 0,
1095 visualizer: 0,
1096 viz_paint: 0,
1097 start,
1098 in_frame,
1099 out_frame,
1100 source: 0,
1101 link: None,
1102 eq: None,
1103 color: None,
1104 fit: FitPolicy::default(),
1105 speed: Speed::NORMAL,
1106 transform: None,
1107 };
1108 // The clip split at 1.5 s (45 frames @ 30 fps) into two adjacent halves,
1109 // exactly what `Project::split` leaves behind.
1110 let mut project = Project::from_parts(
1111 vec![Source::new(src.to_path_buf(), 0)],
1112 vec![(LaneKind::Audio, vec![clip(0, 0, 45), clip(45, 45, 90)])],
1113 Vec::new(),
1114 Vec::new(),
1115 Vec::new(),
1116 )
1117 .expect("a split clip on one audio lane");
1118 assert!(
1119 project.crossfade(Lane::new(LaneKind::Audio, 0), 0, 15),
1120 "adjacent halves cross-fade at their join"
1121 );
1122 let meta = engine::VideoMeta {
1123 width: 1,
1124 height: 1,
1125 frame_rate: fps,
1126 frame_count: 90,
1127 codec: engine::Codec::H264,
1128 color: Default::default(),
1129 rotation: Rotation::None,
1130 // Square pixels, coded where they are declared: a meta no container
1131 // wrote, so nothing was read to disagree with it.
1132 coded_width: 640,
1133 coded_height: 360,
1134 pixel_aspect: engine::demux::PixelAspect::SQUARE,
1135 };
1136 let out = out_path("crossfade", "wav");
1137 let handle = engine::export::start(
1138 project,
1139 meta,
1140 &out,
1141 &ExportSettings {
1142 format: Format::Wav,
1143 ..Default::default()
1144 },
1145 None,
1146 );
1147 wait(&handle, Duration::from_secs(60)).expect("wav export of a cross-faded split");
1148
1149 let (audio, samples) = decode(&out);
1150 let channels = usize::from(audio.channels);
1151 // The source's own flat level, read off a stretch with no fade anywhere
1152 // near it (the second half's own interior, past its fade-in).
1153 let reference = rms(&samples, channels, 2.0, 2.9);
1154 // The first half's interior: from just past 0 to well before its own
1155 // fade-out starts at 1.0 s (45 - 15 frames = 30 frames @ 30 fps).
1156 let interior = rms(&samples, channels, 0.1, 0.9);
1157 println!("crossfade rms: interior {interior:.4} reference {reference:.4}");
1158 assert!(
1159 interior > reference * 0.7,
1160 "the first half's interior is not muted: {interior:.4} vs reference {reference:.4}"
1161 );
1162 std::fs::remove_file(&out).unwrap();
1163 std::fs::remove_file(&src).unwrap();
1164}
1165
1166/// A **mono** timeline through the same door. The format row promises stereo,
1167/// so `export::write_ogg` writes a mono mix as dual mono (the encoder itself
1168/// would serve a mono stream; the row is the contract). This is the test that
1169/// it is *dual mono* and not a widening: both channels come back
1170/// bit-identical, so folding the file back down gives exactly what was mixed.
1171#[test]
1172fn a_mono_timeline_exports_as_dual_mono_ogg() {
1173 // A mono fixture, written here because the suite has none: one second of
1174 // 440 Hz at -6 dBFS, 44.1 kHz, as plain a RIFF header as hound writes.
1175 let src = out_path("mono_src", "wav");
1176 let frames = RATE as usize;
1177 let data = (frames * 2) as u32;
1178 let mut wav = Vec::with_capacity(44 + frames * 2);
1179 wav.extend_from_slice(b"RIFF");
1180 wav.extend_from_slice(&(36 + data).to_le_bytes());
1181 wav.extend_from_slice(b"WAVEfmt ");
1182 wav.extend_from_slice(&16u32.to_le_bytes());
1183 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
1184 wav.extend_from_slice(&1u16.to_le_bytes()); // one channel
1185 wav.extend_from_slice(&RATE.to_le_bytes());
1186 wav.extend_from_slice(&(RATE * 2).to_le_bytes()); // byte rate
1187 wav.extend_from_slice(&2u16.to_le_bytes()); // block align
1188 wav.extend_from_slice(&16u16.to_le_bytes());
1189 wav.extend_from_slice(b"data");
1190 wav.extend_from_slice(&data.to_le_bytes());
1191 for i in 0..frames {
1192 let t = i as f64 / f64::from(RATE);
1193 let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() * 32767.0) as i16;
1194 wav.extend_from_slice(&s.to_le_bytes());
1195 }
1196 std::fs::write(&src, &wav).expect("write the mono fixture");
1197
1198 let project = Project::from_parts(
1199 vec![Source::new(src.to_path_buf(), 0)],
1200 vec![(
1201 LaneKind::Audio,
1202 vec![Clip {
1203 fade_in: 0,
1204 fade_out: 0,
1205 transition_out: 0,
1206 visualizer: 0,
1207 viz_paint: 0,
1208 start: 0,
1209 in_frame: 0,
1210 out_frame: 30,
1211 source: 0,
1212 link: None,
1213 eq: None,
1214 color: None,
1215 fit: FitPolicy::default(),
1216 speed: Speed::NORMAL,
1217 transform: None,
1218 }],
1219 )],
1220 Vec::new(),
1221 Vec::new(),
1222 Vec::new(),
1223 )
1224 .expect("a one-source mono project");
1225
1226 let out = out_path("mono", "ogg");
1227 let handle = engine::export::start(
1228 project,
1229 meta(),
1230 &out,
1231 &ExportSettings {
1232 format: Format::Ogg,
1233 ..Default::default()
1234 },
1235 None,
1236 );
1237 wait(&handle, Duration::from_secs(180)).expect("ogg export of a mono timeline");
1238
1239 let (meta, samples) = decode(&out);
1240 assert_eq!(meta.channels, 2, "written as stereo, since Vorbis must be");
1241 assert_eq!(meta.sample_rate, RATE);
1242 // One second of clip, to the sample: the mono path gets the same trim the
1243 // stereo one does.
1244 assert_eq!(
1245 samples.len() / 2,
1246 RATE as usize,
1247 "one second, to the sample"
1248 );
1249 let worst = samples
1250 .chunks_exact(2)
1251 .map(|lr| f64::from(lr[0] - lr[1]).abs())
1252 .fold(0.0f64, f64::max);
1253 println!("dual mono: worst |L-R| = {worst:e}");
1254 assert_eq!(worst, 0.0, "both channels are the same signal, to the bit");
1255 let energy = (samples
1256 .iter()
1257 .map(|s| f64::from(*s) * f64::from(*s))
1258 .sum::<f64>()
1259 / samples.len() as f64)
1260 .sqrt();
1261 println!("dual mono rms {energy:.4} (the source's own is 0.354)");
1262 assert!(energy > 0.25, "the mono export is silence: RMS {energy:.6}");
1263 std::fs::remove_file(&out).unwrap();
1264 std::fs::remove_file(&src).unwrap();
1265}