forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

audio_export.rs361 lines, 13.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::path::{Path, PathBuf};
15use std::time::{Duration, Instant};
16
17use engine::export::{ExportSettings, Format};
18use engine::project::LaneKind;
19use engine::project::Source;
20use engine::scale::FitPolicy;
21use engine::{AudioSession, Clip, ExportHandle, Project};
22
23const RATE: u32 = 44_100;
24
25fn asset(name: &str) -> PathBuf {
26 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
27 .join("../../assets")
28 .join(name)
29}
30
31/// Per-run unique, like the mp4 suite's: two suites at once must not delete
32/// each other's output.
33fn out_path(name: &str, ext: &str) -> PathBuf {
34 let path = std::env::temp_dir().join(format!("ve_audio_{name}_{}.{ext}", std::process::id()));
35 let _ = std::fs::remove_file(&path);
36 let _ = std::fs::remove_file(part_path(&path));
37 path
38}
39
40fn part_path(out: &Path) -> PathBuf {
41 PathBuf::from(format!("{}.part", out.display()))
42}
43
44fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
45 let started = Instant::now();
46 while !handle.is_finished() {
47 assert!(
48 started.elapsed() < limit,
49 "export did not finish in {limit:?}"
50 );
51 std::thread::sleep(Duration::from_millis(10));
52 }
53 handle.result().expect("a finished export has an outcome")
54}
55
56/// One second of `test_av`, one second of hole, one second of `test_tone.mp3`.
57///
58/// Three things at once: a cut, a gap (which must arrive as silence), and a
59/// source the mp4 export flatly refuses — there is no AAC encoder here, so an
60/// mp3 on the timeline can *only* leave through this door.
61fn mixed_project() -> Project {
62 let clip = |start, source| Clip {
63 start,
64 in_frame: 0,
65 out_frame: 30,
66 source,
67 link: None,
68 eq: None,
69 color: None,
70 fit: FitPolicy::default(),
71 };
72 Project::from_parts(
73 vec![
74 Source::new(asset("test_av.mp4"), 0),
75 Source::new(asset("test_tone.mp3"), 0),
76 ],
77 // The picture is beside the point here, but a project has two lanes and
78 // the timeline's length is the longer of them: three seconds of video
79 // is what makes the third second of audio part of the timeline.
80 vec![
81 (
82 LaneKind::Video,
83 vec![Clip {
84 start: 0,
85 in_frame: 0,
86 out_frame: 90,
87 source: 0,
88 link: None,
89 eq: None,
90 color: None,
91 fit: FitPolicy::default(),
92 }],
93 ),
94 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
95 ],
96 Vec::new(),
97 Vec::new(),
98 )
99 .expect("a two-source project with a hole in the audio lane")
100}
101
102fn meta() -> engine::VideoMeta {
103 engine::demux::Demuxer::open(&asset("test_av.mp4"))
104 .expect("open test_av")
105 .0
106}
107
108/// Interleaved samples of a written file, through the engine's own reader --
109/// the same door an import comes in through, so a pass here means the export
110/// can be brought back into a timeline.
111fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) {
112 let (meta, chunks) = AudioSession::open(path)
113 .expect("reopen the export")
114 .expect("the export has audio");
115 let mut samples = Vec::new();
116 for chunk in chunks {
117 samples.extend(chunk.samples);
118 }
119 (meta, samples)
120}
121
122/// Root mean square of `[from, to)` seconds of an interleaved stereo buffer.
123fn rms(samples: &[f32], channels: usize, from: f64, to: f64) -> f64 {
124 let at = |secs: f64| (secs * f64::from(RATE)) as usize * channels;
125 let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
126 assert!(!window.is_empty(), "no samples in [{from}, {to})");
127 (window
128 .iter()
129 .map(|s| f64::from(*s) * f64::from(*s))
130 .sum::<f64>()
131 / window.len() as f64)
132 .sqrt()
133}
134
135/// What every audio export must be, whatever encoded it: exactly as long as the
136/// timeline, silent where the timeline is empty, and audible where it is not --
137/// with the fixtures' 1 Hz pulse still in it, which is what says the samples are
138/// the *edit's* and not just noise of the right length.
139fn assert_timeline_shape(meta: &engine::AudioMeta, samples: &[f32]) {
140 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2), "as decoded");
141 let channels = usize::from(meta.channels);
142 // Three seconds of timeline, to the sample: the segments round their own
143 // windows and the mp3 need not end where the second does, so this is the
144 // export's own trim/pad and not an accident of the sources.
145 let frames = (3.0 * f64::from(RATE)) as usize;
146 assert_eq!(
147 samples.len(),
148 frames * channels,
149 "timeline length in samples"
150 );
151
152 // Second 0 is test_av, second 2 is the mp3; both carry the tone.
153 let av = rms(samples, channels, 0.05, 0.95);
154 let tone = rms(samples, channels, 2.05, 2.95);
155 // Second 1 is the hole. Silence, not a stall and not a skip: it occupies
156 // its full second, which is what the sample count above already proved.
157 let gap = rms(samples, channels, 1.0, 2.0);
158 println!("rms: av {av:.4} gap {gap:.6} mp3 {tone:.4}");
159 assert!(av > 0.01, "the first second is audible");
160 assert!(tone > 0.01, "the mp3 second is audible");
161 assert_eq!(gap, 0.0, "the gap is exact silence");
162
163 // The 1 Hz pulse: `volume = 0.5 + 0.5 sin(2 pi t)`, so a peak sits at
164 // t = 0.25 and the dip at t = 0.75. Ratio, never an absolute level.
165 let peak = rms(samples, channels, 0.2, 0.3);
166 let dip = rms(samples, channels, 0.7, 0.8);
167 println!(
168 "pulse: peak {peak:.4} dip {dip:.4} ratio {:.1}",
169 peak / dip
170 );
171 assert!(
172 peak > dip * 4.0,
173 "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}"
174 );
175}
176
177/// The RIFF header itself, byte for byte: hound writes it, but what a player
178/// reads is the bytes, and a wrong rate or a wrong `data` size is a file that
179/// decodes at the wrong speed rather than one that fails to open.
180fn assert_wav_header(path: &Path, frames: usize) {
181 let bytes = std::fs::read(path).expect("read the wav back");
182 let u16_at = |i: usize| u16::from_le_bytes([bytes[i], bytes[i + 1]]);
183 let u32_at =
184 |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]);
185 assert_eq!(&bytes[0..4], b"RIFF");
186 assert_eq!(&bytes[8..12], b"WAVE");
187 assert_eq!(&bytes[12..16], b"fmt ");
188 assert_eq!(u32_at(4) as usize, bytes.len() - 8, "RIFF size");
189 assert_eq!(u16_at(20), 1, "PCM, not a float or a compressed tag");
190 assert_eq!(u16_at(22), 2, "stereo");
191 assert_eq!(u32_at(24), RATE, "sample rate");
192 assert_eq!(u32_at(28), RATE * 2 * 2, "byte rate = rate * channels * 2");
193 assert_eq!(u16_at(32), 4, "block align");
194 assert_eq!(u16_at(34), 16, "bits per sample");
195 // The `data` chunk carries every sample and nothing else. hound may write a
196 // `fact` chunk first, so it is found rather than assumed to be at 36.
197 let data = bytes
198 .windows(4)
199 .position(|w| w == b"data")
200 .expect("a data chunk");
201 assert_eq!(u32_at(data + 4) as usize, frames * 2 * 2, "data chunk size");
202}
203
204#[test]
205fn exports_the_timeline_as_a_wav() {
206 let out = out_path("wav", "wav");
207 let handle = engine::export::start(
208 mixed_project(),
209 meta(),
210 &out,
211 &ExportSettings {
212 format: Format::Wav,
213 ..Default::default()
214 },
215 );
216 wait(&handle, Duration::from_secs(60)).expect("wav export");
217 assert_eq!(handle.progress(), 1.0, "finished at full progress");
218 assert!(!part_path(&out).exists(), "the .part was renamed away");
219
220 let (meta, samples) = decode(&out);
221 assert_timeline_shape(&meta, &samples);
222 assert_wav_header(&out, samples.len() / usize::from(meta.channels));
223 std::fs::remove_file(&out).unwrap();
224}
225
226#[test]
227fn exports_the_timeline_as_a_flac() {
228 let out = out_path("flac", "flac");
229 let handle = engine::export::start(
230 mixed_project(),
231 meta(),
232 &out,
233 &ExportSettings {
234 format: Format::Flac,
235 ..Default::default()
236 },
237 );
238 wait(&handle, Duration::from_secs(60)).expect("flac export");
239 assert_eq!(handle.progress(), 1.0, "finished at full progress");
240
241 let bytes = std::fs::read(&out).expect("read the flac back");
242 assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic");
243 // Lossless is a claim about the samples, so it is checked on the samples:
244 // the same shape the WAV of the same timeline has.
245 let (meta, samples) = decode(&out);
246 assert_timeline_shape(&meta, &samples);
247 // Smaller than the PCM it encodes, or the whole point of the row is gone.
248 let pcm = samples.len() * 2;
249 println!("flac {} bytes for {pcm} bytes of PCM", bytes.len());
250 assert!(bytes.len() < pcm, "compressed");
251 std::fs::remove_file(&out).unwrap();
252}
253
254/// Cancel leaves nothing behind -- not the output, not the `.part`. The
255/// timeline is long enough (a minute of audio) that the escape lands mid-decode
256/// rather than after the file is already closed.
257#[test]
258fn a_cancelled_audio_export_leaves_no_file() {
259 let source = asset("test_av.mp4");
260 let (meta, _) = engine::demux::Demuxer::open(&source).expect("open test_av");
261 let mut project = Project::single(&source, meta.frame_count);
262 for _ in 0..11 {
263 assert!(project.append_clip(0, meta.frame_count), "a minute of it");
264 }
265 let out = out_path("cancel", "wav");
266 let handle = engine::export::start(
267 project,
268 meta,
269 &out,
270 &ExportSettings {
271 format: Format::Wav,
272 ..Default::default()
273 },
274 );
275 handle.cancel();
276 let outcome = wait(&handle, Duration::from_secs(120));
277 let text = outcome.expect_err("a cancelled export fails").to_string();
278 assert!(text.contains("cancelled"), "{text}");
279 assert!(!out.exists(), "no output file");
280 assert!(!part_path(&out).exists(), "no half-written .part either");
281}
282
283/// A silent timeline cannot become an audio file, and says so rather than
284/// writing zero samples that a user would take for a broken microphone.
285#[test]
286fn a_silent_timeline_refuses_an_audio_export() {
287 let source = asset("test_mismatch.mp4"); // video only, no audio track
288 let (meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture");
289 let out = out_path("silent", "wav");
290 let handle = engine::export::start(
291 Project::single(&source, meta.frame_count),
292 meta,
293 &out,
294 &ExportSettings {
295 format: Format::Wav,
296 ..Default::default()
297 },
298 );
299 let text = wait(&handle, Duration::from_secs(60))
300 .expect_err("no audio to export")
301 .to_string();
302 assert!(text.contains("no audio"), "{text}");
303 assert!(
304 !out.exists() && !part_path(&out).exists(),
305 "nothing written"
306 );
307}
308
309/// An AC-3 source leaves through this door and no other: the mp4 export cannot
310/// copy a syncframe into an `mp4a` track (no AAC encoder here), but a WAV of the
311/// same timeline decodes, downmixes and reopens through the engine's own reader.
312#[test]
313fn a_51_ac3_source_round_trips_through_a_wav() {
314 let source = asset("test_ac3_51.mp4");
315 let project = Project::from_parts(
316 vec![Source::new(source.clone(), 0)],
317 vec![(
318 LaneKind::Audio,
319 vec![Clip {
320 start: 0,
321 in_frame: 0,
322 out_frame: 30,
323 source: 0,
324 link: None,
325 eq: None,
326 color: None,
327 fit: FitPolicy::default(),
328 }],
329 )],
330 Vec::new(),
331 Vec::new(),
332 )
333 .expect("a one-source AC-3 project");
334 let video = engine::demux::Demuxer::open(&source).expect("open the fixture").0;
335
336 let out = out_path("ac3", "wav");
337 let handle = engine::export::start(
338 project,
339 video,
340 &out,
341 &ExportSettings {
342 format: Format::Wav,
343 ..Default::default()
344 },
345 );
346 wait(&handle, Duration::from_secs(60)).expect("wav export of an AC-3 source");
347
348 let (meta, samples) = decode(&out);
349 assert_eq!(
350 (meta.sample_rate, meta.channels),
351 (48_000, 2),
352 "the §7.8 downmix is what reaches the file"
353 );
354 let secs = (samples.len() / 2) as f64 / 48_000.;
355 assert!((0.9..1.1).contains(&secs), "one second of clip, got {secs:.3}s");
356 let energy = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
357 / samples.len() as f64)
358 .sqrt();
359 assert!(energy > 0.005, "the exported AC-3 is silence: RMS {energy:.6}");
360 std::fs::remove_file(&out).unwrap();
361}