forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

audio_decode.rs628 lines, 26.0 KiBHistoryRawDownload
1use std::path::PathBuf;
2use std::time::{Duration, Instant};
3
4use engine::audio::AudioSession;
5use engine::scratch::Scratch;
6
7const RATE: u32 = 44100;
8const SECONDS: u32 = 5;
9/// One AAC-LC packet; the container's tail padding is not trimmed, so the
10/// decoded length may run up to a frame past the nominal duration.
11const FRAME: i64 = 1024;
12
13fn asset(name: &str) -> PathBuf {
14 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15 .join("../../assets")
16 .join(name)
17}
18
19/// Sign changes ignoring exact zeros, so the 1 Hz volume pulse touching zero
20/// does not register as a crossing.
21fn zero_crossings(samples: &[f32]) -> usize {
22 let mut crossings = 0;
23 let mut last = 0f32;
24 for &s in samples {
25 if s == 0.0 {
26 continue;
27 }
28 if last != 0.0 && (s > 0.0) != (last > 0.0) {
29 crossings += 1;
30 }
31 last = s;
32 }
33 crossings
34}
35
36#[test]
37fn decodes_av_mp4_audio() {
38 let start = Instant::now();
39 let (meta, rx) = AudioSession::open(asset("test_av.mp4"))
40 .expect("open")
41 .expect("test_av.mp4 has an audio track");
42 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
43
44 let mut left = Vec::new();
45 let mut right = Vec::new();
46 let mut next_sample = 0u64;
47 let mut chunks = 0usize;
48 for chunk in rx {
49 // d. no gaps, no overlaps.
50 assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start");
51 assert!(!chunk.samples.is_empty(), "empty chunk {chunks}");
52 assert_eq!(
53 chunk.samples.len() % 2,
54 0,
55 "partial frame in chunk {chunks}"
56 );
57 next_sample += (chunk.samples.len() / 2) as u64;
58 left.extend(chunk.samples.iter().step_by(2));
59 right.extend(chunk.samples[1..].iter().step_by(2));
60 chunks += 1;
61 }
62 let elapsed = start.elapsed();
63 let frames = left.len();
64 assert!(frames > 0, "no audio decoded");
65
66 // b. ~5 s of audio, priming trimmed, at most a frame of tail padding over.
67 let want = (RATE * SECONDS) as i64;
68 let slack = frames as i64 - want;
69 assert!(
70 (0..=FRAME).contains(&slack),
71 "{frames} frames per channel, want {want} (+0..={FRAME})"
72 );
73 assert_eq!(right.len(), frames, "channel lengths differ");
74
75 // c. channel identity: L is 440 Hz, R is 880 Hz. A swap or a bad interleave
76 // shows up as the wrong crossing count.
77 let secs = frames as f64 / RATE as f64;
78 for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] {
79 let want = 2.0 * hz * secs;
80 let got = zero_crossings(samples) as f64;
81 assert!(
82 (got - want).abs() <= 0.05 * want,
83 "{name}: {got} zero crossings, want {want} +/-5%"
84 );
85 }
86
87 // Priming trimmed: the sine starts at a rising zero crossing, and audio is
88 // present immediately rather than after a silent or garbage run-in.
89 assert!(
90 left[0].abs() < 0.05,
91 "first sample {} not near zero",
92 left[0]
93 );
94 assert!(left[1] > 0.0, "first sine quarter is not rising");
95 let head_peak = left[..FRAME as usize]
96 .iter()
97 .fold(0f32, |m, s| m.max(s.abs()));
98 assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}");
99
100 eprintln!(
101 "{frames} frames/ch in {chunks} chunks, {elapsed:?} ({:?}/packet)",
102 elapsed / chunks as u32
103 );
104}
105
106/// A QuickTime-brand `.mov` -- Resolve's, Final Cut's, `ffmpeg -f mov`'s --
107/// keeps its AAC `esds` behind a version-1 SoundDescription and inside a
108/// `wave` wrapper. Stock mp4 0.14 read neither and refused the track as
109/// "esds not found", so a `.mov` opened as a silent film (a Resolve export,
110/// 2026-09-06); the vendored crate reads both. The tone is the fixture's
111/// 440 Hz left / 880 Hz right, so this also proves the config it found is the
112/// right one and not a guess: a wrong rate or layout moves the crossings.
113#[test]
114fn a_quicktime_mov_keeps_its_aac_behind_a_wave_wrapper() {
115 let (meta, rx) = AudioSession::open(asset("test_qt.mov"))
116 .expect("open")
117 .expect("test_qt.mov has an audio track");
118 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
119
120 let mut left = Vec::new();
121 let mut right = Vec::new();
122 for chunk in rx {
123 left.extend(chunk.samples.iter().step_by(2));
124 right.extend(chunk.samples[1..].iter().step_by(2));
125 }
126 let frames = left.len();
127 let want = (RATE * 2) as i64;
128 let slack = frames as i64 - want;
129 assert!(
130 (0..=FRAME).contains(&slack),
131 "{frames} frames per channel, want {want} (+0..={FRAME})"
132 );
133 let secs = frames as f64 / RATE as f64;
134 for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] {
135 let want = 2.0 * hz * secs;
136 let got = zero_crossings(samples) as f64;
137 assert!(
138 (got - want).abs() <= 0.05 * want,
139 "{name}: {got} zero crossings, want {want} +/-5%"
140 );
141 }
142}
143
144#[test]
145fn video_only_file_has_no_audio() {
146 assert!(
147 AudioSession::open(asset("test_baseline.mp4"))
148 .expect("open")
149 .is_none()
150 );
151 assert!(
152 AudioSession::unsupported(asset("test_baseline.mp4"))
153 .expect("probe")
154 .is_none(),
155 "a file with no audio track is not a complaint"
156 );
157}
158
159/// Both ends of the AC-3 path decode: the 44.1 kHz **mono** fixture stays the
160/// mono source it is, and the 48 kHz **5.1** one — the shape a BluRay remux has
161/// — arrives as stereo, downmixed by the decoder itself (A/52 §7.8). Both play
162/// their two seconds, at a level that is neither silence nor clipping, and
163/// neither owes the session an excuse.
164#[test]
165fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
166 for (name, rate, channels) in [("test_ac3.mp4", 44100, 1), ("test_ac3_51.mp4", 48000, 2)] {
167 let path = asset(name);
168 let (meta, rx) = AudioSession::open(&path)
169 .expect("open")
170 .expect("AC-3 decodes now");
171 assert_eq!((meta.sample_rate, meta.channels), (rate, channels), "{name}");
172 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
173 let secs = (samples.len() / channels as usize) as f64 / f64::from(rate);
174 assert!(
175 (1.9..2.1).contains(&secs),
176 "{name} is two seconds, decoded {secs:.3}s"
177 );
178 // The 440 Hz sine survives at a sane level. The vetting caveat was an
179 // LFE passthrough running hot, which the built-in downmix is what
180 // avoids; this is that level check, and it is also what catches a
181 // downmix that comes out silent.
182 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
183 / samples.len() as f64)
184 .sqrt();
185 assert!(
186 (0.005..0.75).contains(&rms),
187 "{name}: RMS {rms:.6} is not a sine at a sane level"
188 );
189 assert!(
190 samples.iter().all(|s| s.abs() <= 1.0),
191 "{name}: the decode must not leave the device's range"
192 );
193 let session = engine::PlaybackSession::open(&path).expect("open for playback");
194 assert_eq!(
195 session.audio_disabled_reason(),
196 None,
197 "{name}: a track that decodes owes no excuse"
198 );
199 }
200}
201
202/// Opus, which used to be the codec the refusal string was *for*: a standalone
203/// `.opus`, the `.webm` sound off the web, and the 5.1 in an `.mka` that a film
204/// soundtrack is -- four Opus streams with a channel mapping table, decoded by
205/// `ec-opus` and folded to stereo by the same fold the AC-3 and AAC paths use.
206///
207/// The 5.1 fixture is the channel-order check as well: its tone is in FL and BR
208/// and silent in between, so both output channels carry sound only if the
209/// decoder's Vorbis order (FL, FC, FR, BL, BR, LFE) was put into the film order
210/// the fold reads (FL, FR, FC, LFE, BL, BR). Skipping that permutation folds BR
211/// as if it were BL and the right channel comes out silent.
212#[test]
213fn opus_decodes_from_every_container_and_51_comes_down_in_order() {
214 for (name, secs, channels) in [("test_tone.opus", 3.0, 2), ("test_vp9.webm", 2.0, 1)] {
215 let path = asset(name);
216 let (meta, rx) = AudioSession::open(&path)
217 .expect("open")
218 .expect("Opus decodes now");
219 assert_eq!((meta.sample_rate, meta.channels), (48000, channels), "{name}");
220 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
221 let decoded = (samples.len() / channels as usize) as f64 / 48000.0;
222 assert!(
223 (secs - decoded).abs() < 0.1,
224 "{name} is {secs}s, decoded {decoded:.3}s"
225 );
226 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
227 / samples.len() as f64)
228 .sqrt();
229 assert!(
230 (0.005..0.75).contains(&rms),
231 "{name}: RMS {rms:.6} is not a sine at a sane level"
232 );
233 assert!(
234 samples.iter().all(|s| s.abs() <= 1.0),
235 "{name}: the decode must not leave the device's range"
236 );
237 // ...and the same file as a session, where the picture allows it: the
238 // webm's is VP9, which is the VA-API plugin's and not this test's.
239 if !name.ends_with(".webm") {
240 let session = engine::PlaybackSession::open(&path).expect("open for playback");
241 assert_eq!(
242 session.audio_disabled_reason(),
243 None,
244 "{name}: a track that decodes owes no excuse"
245 );
246 }
247 }
248
249 let path = asset("test_opus_51.mka");
250 let (meta, rx) = AudioSession::open(&path)
251 .expect("open")
252 .expect("5.1 Opus decodes now");
253 assert_eq!((meta.sample_rate, meta.channels), (48000, 2));
254 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
255 let rms = |channel: usize| {
256 let side: Vec<f64> = samples[channel..]
257 .iter()
258 .step_by(2)
259 .map(|s| f64::from(*s) * f64::from(*s))
260 .collect();
261 (side.iter().sum::<f64>() / side.len() as f64).sqrt()
262 };
263 let (left, right) = (rms(0), rms(1));
264 assert!(left > 0.02, "the 5.1 fold came out silent on the left: {left}");
265 assert!(
266 right > 0.3 * left,
267 "BR was folded as if it were BL: left {left:.4}, right {right:.4}"
268 );
269 // ...and it is the *tone* on each side, not noise at the right level. This is
270 // the assert that bites: a multistream decoder that mis-slices the packet
271 // (all but the last stream of an Opus 5.1 packet are self-delimited) hands
272 // back full-scale hash whose RMS passes every level check above -- measured
273 // -13 dBFS of it on a film, where the film is silent.
274 let secs = (samples.len() / 2) as f64 / 48000.0;
275 for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] {
276 let side: Vec<f32> = samples[channel..].iter().step_by(2).copied().collect();
277 let want = 2.0 * hz * secs;
278 let got = zero_crossings(&side) as f64;
279 assert!(
280 (got - want).abs() <= 0.05 * want,
281 "{name}: {got} zero crossings, want {want} +/-5% -- a decode this far off is noise"
282 );
283 }
284}
285
286/// The amplitude of an `hz` sine inside `samples`, by Goertzel. The window is a
287/// whole second at 48 kHz, so every frequency this asks about is an exact bin
288/// and there is no leakage to correct for; a real sine of amplitude A puts
289/// `A * N / 2` in its bin.
290fn amplitude(samples: &[f32], hz: f64) -> f64 {
291 let n = samples.len() as f64;
292 let w = 2.0 * std::f64::consts::PI * hz / 48_000.0;
293 let coeff = 2.0 * w.cos();
294 let (mut s1, mut s2) = (0.0, 0.0);
295 for &sample in samples {
296 let s0 = f64::from(sample) + coeff * s1 - s2;
297 s2 = s1;
298 s1 = s0;
299 }
300 2.0 * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n
301}
302
303/// **7.1 Opus**, the widest layout the fold has a table for and the one the
304/// largest film carries: five Opus streams, three coupled, arriving on the
305/// timeline as an ordinary stereo source instead of the import refusal it used
306/// to be ("unsupported channel layout: 8 channels (max stereo)").
307///
308/// The fixture puts one frequency in each of four channels and silence in the
309/// rest (`gen_fixtures.sh`), so the whole downmix is one measurement: 440 in FL
310/// is left only, 880 in FC is both sides at -3 dB, 1320 in the LFE must be gone
311/// entirely, and 1760 in SR is right only. Every coefficient and the whole
312/// Vorbis-to-film permutation at this width fail visibly here.
313#[test]
314fn seven_one_opus_folds_to_the_stereo_the_timeline_carries() {
315 let path = asset("test_opus_71.mka");
316 let streams = AudioSession::probe_streams(&path).expect("streams");
317 assert_eq!(streams.len(), 1);
318 assert!(streams[0].decodable, "a 7.1 row is not greyed out any more");
319 assert_eq!(streams[0].channels, 2, "what reaches the timeline is a pair");
320
321 let (meta, rx) = AudioSession::open(&path)
322 .expect("open")
323 .expect("7.1 Opus decodes now");
324 assert_eq!((meta.sample_rate, meta.channels), (48000, 2));
325 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
326 assert!(
327 samples.iter().all(|s| s.abs() <= 1.0),
328 "the fold must not leave the device's range"
329 );
330 // One whole second out of the middle, past any codec fade-in.
331 let second = |channel: usize| -> Vec<f32> {
332 samples[channel..]
333 .iter()
334 .step_by(2)
335 .skip(48_000)
336 .take(48_000)
337 .copied()
338 .collect()
339 };
340 // 1 + 3 * (-3 dB): FL/FR keep their side, FC and both surround pairs are the
341 // three that join it. Nothing may come out above full scale, which is what
342 // dividing by the coefficient sum buys.
343 let norm = 1.0 + 3.0 * f64::from(std::f32::consts::FRAC_1_SQRT_2);
344 let c = f64::from(std::f32::consts::FRAC_1_SQRT_2);
345 let (left, right) = (second(0), second(1));
346 // FL is the one channel that keeps its side at unity, so what it comes out
347 // as names the tone the fixture was written with -- `sine` peaks at 0.125 in
348 // ffmpeg, and reading that off the fold rather than hard-coding it keeps the
349 // coefficients below the claim instead of the generator's level. A fold that
350 // lost FL, or scaled the pair, leaves this band.
351 let source = amplitude(&left, 440.0) * norm;
352 assert!(
353 (0.10..0.15).contains(&source),
354 "FL came out as a {source:.4} tone; the fixture's is 0.125"
355 );
356 for (side, cut, want) in [
357 ("left", &left, [(440.0, 1.0), (880.0, c), (1320.0, 0.0), (1760.0, 0.0)]),
358 ("right", &right, [(440.0, 0.0), (880.0, c), (1320.0, 0.0), (1760.0, c)]),
359 ] {
360 for (hz, coeff) in want {
361 let got = amplitude(cut, hz);
362 let expect = source * coeff / norm;
363 match coeff {
364 // The LFE, and the channels this side has none of: what is left
365 // is codec noise and bleed, an order below the quietest tone.
366 0.0 => assert!(
367 got < 0.1 * source / norm,
368 "{side}: {hz} Hz came through at {got:.4}, and nothing there should"
369 ),
370 _ => assert!(
371 (got - expect).abs() < 0.15 * expect,
372 "{side}: {hz} Hz at {got:.4}, want {expect:.4} +/-15%"
373 ),
374 }
375 }
376 }
377}
378
379/// A real 7.1 remux, which is the file this whole change exists for: 12.9 GB of
380/// 2160p AV1 with an 8-channel Opus track that used to come back "IMPORT FAILED:
381/// unsupported channel layout: 8 channels (max stereo)" and take the picture
382/// with it.
383///
384/// Skipped, not failed, on a machine that does not have the film: a fixture
385/// cannot stand in for the claim (the refusal was measured on *this* file) and a
386/// test that cannot make it must say nothing rather than something false.
387#[test]
388fn his_seven_one_remux_imports_and_plays() {
389 let Some(film) = engine::real_library::film("av1_opus_71") else {
390 return;
391 };
392 // The import gate itself: this is the call whose `Err` the app printed.
393 let probe = AudioSession::probe(&film, 0)
394 .expect("the 7.1 track no longer refuses the import")
395 .expect("the film has audio");
396 assert_eq!(
397 (probe.sample_rate, probe.channels),
398 (48_000, 2),
399 "7.1 reaches the timeline as a pair"
400 );
401 // ...and every one of its three tracks is offered, none greyed out.
402 let streams = AudioSession::probe_streams(&film).expect("streams");
403 assert_eq!(streams.len(), 3, "7.1 plus two 5.1 commentary tracks");
404 assert!(
405 streams.iter().all(|s| s.decodable && s.channels == 2),
406 "{streams:?}"
407 );
408
409 // Ten seconds out of the middle of the film, through the very worker
410 // playback and a WAV export both feed from -- with sound on *both* sides,
411 // which a fold that dropped half the layout would not have.
412 let (meta, rx) = AudioSession::open_segments(&film, &[(600.0, 610.0)])
413 .expect("open")
414 .expect("the film has audio");
415 assert_eq!((meta.sample_rate, meta.channels), (48_000, 2));
416 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
417 let secs = (samples.len() / 2) as f64 / 48_000.0;
418 assert!((9.9..10.1).contains(&secs), "{secs:.3} s decoded, want 10");
419 assert!(
420 samples.iter().all(|s| s.abs() <= 1.0),
421 "the fold must not leave the device's range"
422 );
423 for (side, channel) in [("left", 0), ("right", 1)] {
424 let one: Vec<f64> = samples[channel..].iter().step_by(2).map(|s| f64::from(*s)).collect();
425 let rms = (one.iter().map(|s| s * s).sum::<f64>() / one.len() as f64).sqrt();
426 assert!(rms > 0.001, "{side} came out silent: RMS {rms:.6}");
427 eprintln!("{side}: RMS {rms:.6} over {secs:.2}s from 600s");
428 }
429
430 // ...and the whole way out: the file on a timeline, trimmed to ten seconds,
431 // written as a WAV by the export path and read back through this engine's
432 // own reader. A session open is what the app's Import does, so a picture
433 // this size failing to open would fail here rather than in use.
434 let mut session = engine::PlaybackSession::open(&film).expect("the film opens as a timeline");
435 assert_eq!(
436 session.audio_disabled_reason(),
437 None,
438 "a track that decodes owes no excuse"
439 );
440 let frames = (10.0 * session.meta().frame_rate).round() as u32;
441 for lane in session.lanes() {
442 session.trim_clip(lane, 0, engine::project::Edge::End, frames);
443 }
444 let out = Scratch::file("ve_seven_one", "wav");
445 let handle = session.export_to_with(
446 &out,
447 &engine::export::ExportSettings {
448 format: engine::export::Format::Wav,
449 ..Default::default()
450 },
451 );
452 let started = Instant::now();
453 while !handle.is_finished() {
454 assert!(started.elapsed() < Duration::from_secs(300), "export hung");
455 std::thread::sleep(Duration::from_millis(50));
456 }
457 handle.result().expect("outcome").expect("the WAV is written");
458 let (wav, rx) = AudioSession::open(&out)
459 .expect("the WAV reopens")
460 .expect("it has sound");
461 let written: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
462 let channels = usize::from(wav.channels);
463 assert_eq!(channels, 2, "a stereo WAV out of a 7.1 source");
464 for (side, channel) in [("left", 0), ("right", 1)] {
465 let one: Vec<f64> = written[channel..]
466 .iter()
467 .step_by(channels)
468 .map(|s| f64::from(*s))
469 .collect();
470 let rms = (one.iter().map(|s| s * s).sum::<f64>() / one.len() as f64).sqrt();
471 assert!(rms > 0.001, "the exported {side} is silent: RMS {rms:.6}");
472 eprintln!(
473 "exported {side}: RMS {rms:.6} over {:.2}s at {} Hz",
474 one.len() as f64 / f64::from(wav.sample_rate),
475 wav.sample_rate
476 );
477 }
478}
479
480/// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and
481/// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)"
482/// refusal used to fire on -- both come out of the blocks, both arrive as the
483/// stereo the §7.8 downmix hands the timeline, and neither owes the session an
484/// excuse any more.
485#[test]
486fn matroska_ac3_and_eac3_decode_out_of_the_blocks() {
487 for (name, codec) in [("test_ac3.mkv", "ac-3"), ("test_eac3.mkv", "e-ac-3")] {
488 let path = asset(name);
489 let (meta, rx) = AudioSession::open(&path)
490 .expect("open")
491 .expect("Matroska AC-3 decodes now");
492 assert_eq!((meta.sample_rate, meta.channels), (48000, 2), "{name}");
493 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
494 let secs = (samples.len() / 2) as f64 / 48000.0;
495 assert!(
496 (1.9..2.1).contains(&secs),
497 "{name} is two seconds, decoded {secs:.3}s"
498 );
499 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
500 / samples.len() as f64)
501 .sqrt();
502 assert!(
503 (0.005..0.75).contains(&rms),
504 "{name}: RMS {rms:.6} is not a sine at a sane level"
505 );
506 assert!(
507 samples.iter().all(|s| s.abs() <= 1.0),
508 "{name}: the decode must not leave the device's range"
509 );
510 // The user-facing half: the session comes up with sound and no notice,
511 // and the file's one audio stream is offered by the name it is in.
512 let session = engine::PlaybackSession::open(&path).expect("open for playback");
513 assert_eq!(
514 session.audio_disabled_reason(),
515 None,
516 "{name}: a track that decodes owes no excuse"
517 );
518 let streams = AudioSession::probe_streams(&path).expect("streams");
519 assert_eq!(streams.len(), 1, "{name}: one audio track, one row");
520 assert_eq!(streams[0].codec, codec, "{name}");
521 assert!(streams[0].decodable, "{name}");
522 assert_eq!(
523 AudioSession::unsupported(&path).expect("unsupported"),
524 None,
525 "{name}: nothing to excuse when it plays"
526 );
527 }
528 // The invariant, stated as an assert: the AAC track of a Matroska file is
529 // still symphonia's, listed and decoded exactly as it was.
530 let streams = AudioSession::probe_streams(asset("test_av1.mkv")).expect("streams");
531 assert_eq!(streams.len(), 1);
532 assert_eq!(streams[0].codec, "aac", "AAC in an mkv is untouched by this");
533 assert!(
534 AudioSession::open(asset("test_av1.mkv"))
535 .expect("open")
536 .is_some(),
537 "AAC in an mkv still decodes"
538 );
539}
540
541/// A seek into a Matroska AC-3 track: Matroska indexes no samples, so the block
542/// a decode starts on is found by the blocks' own timestamps -- and getting that
543/// wrong is a tail that is the wrong length or lands in the wrong place. It is
544/// the same check `audio_seek` makes of the mp4 path, on the container that has
545/// no sample table.
546#[test]
547fn a_seek_into_a_matroska_ac3_track_is_the_tail_of_a_full_run() {
548 let path = asset("test_eac3.mkv");
549 let full: Vec<f32> = AudioSession::open(&path)
550 .expect("open")
551 .expect("audio")
552 .1
553 .into_iter()
554 .flat_map(|c| c.samples)
555 .collect();
556 let start = 48_000u64; // one second in, in frames per channel
557 let mut next = start;
558 let mut tail = Vec::new();
559 for chunk in AudioSession::open_at(&path, 1.0).expect("open").expect("audio").1 {
560 assert_eq!(chunk.start_sample, next, "a seeked run numbers from the seek");
561 next += (chunk.samples.len() / 2) as u64;
562 tail.extend(chunk.samples);
563 }
564 let want = &full[start as usize * 2..];
565 assert_eq!(tail.len(), want.len(), "the seeked run is a different length");
566 let diff = tail
567 .iter()
568 .zip(want)
569 .map(|(a, b)| (a - b).abs())
570 .fold(0.0f32, f32::max);
571 // One syncframe of pre-roll is what the 256-sample overlap-add needs, so
572 // this is exact in practice; the tolerance is for a decoder that carries
573 // more state than the frame before, not for a wrong block.
574 assert!(diff < 1e-3, "max abs diff {diff} after the seek");
575}
576
577/// An AC-3 syncframe is not something an `mp4a` sample table holds, so the
578/// *copy* path names it and hands the export on to the re-encode (which decodes
579/// this very source: the downmix above is what it encodes). Named either way --
580/// never a silent export.
581#[test]
582fn an_ac3_source_refuses_an_mp4_audio_copy() {
583 let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else {
584 panic!("AC-3 cannot become an mp4a track");
585 };
586 let err = err.to_string();
587 assert!(
588 err.contains("needs AAC in an mp4") && err.contains("AC-3"),
589 "unhelpful refusal: {err}"
590 );
591}
592
593/// The two things a Matroska file with no *readable* sound can be, told apart:
594/// a file with no audio track is the silent source it says it is, and a file
595/// whose audio will not open at all is an error. They used to be the same
596/// answer -- silence -- so a broken track played and exported as a hole with
597/// nothing but an `eprintln` to say why.
598#[test]
599fn a_matroska_with_no_track_is_silent_and_a_broken_one_is_an_error() {
600 // No audio track at all: a picture and two subtitle tracks. Silent, and the
601 // stream picker offers nothing rather than refusing the file.
602 let subs = asset("test_subs.mkv");
603 assert!(
604 AudioSession::probe(&subs, 0)
605 .expect("no audio is not an error")
606 .is_none(),
607 "an mkv with no audio track is a silent source"
608 );
609 assert!(AudioSession::probe_streams(&subs).expect("list").is_empty());
610 assert!(
611 AudioSession::open(&subs).expect("open").is_none(),
612 "no sound"
613 );
614
615 // ...and a file that will not parse at all, under the same extension: an
616 // `Err` a front-end can show, not a silent import.
617 let broken = Scratch::file("ve_broken", "mkv");
618 std::fs::write(&broken, b"\x1a\x45\xdf\xa3not a matroska file at all").expect("write");
619 let err = AudioSession::probe(&broken, 0)
620 .expect_err("a broken file must not pass for a silent one")
621 .to_string();
622 assert!(!err.is_empty(), "the refusal says something");
623 assert!(
624 AudioSession::probe_streams(&broken).is_err(),
625 "and so does the listing"
626 );
627 std::fs::remove_file(&broken).unwrap();
628}