forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

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