forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

library.rs821 lines, 27.7 KiBHistoryRawDownload
1//! His library, not fixtures: open, list, decode and seek real files, and
2//! compare what the probe says against ffprobe file by file.
3//!
4//! Driven by `fixtures/real-library-manifest.tsv` (written by
5//! `scripts/scan-real-library.sh`). Files that have since moved are skipped and
6//! reported, never failed — the manifest is a snapshot of a moving library.
7
8use std::fs::File;
9use std::io::{Read, Seek, SeekFrom};
10use std::path::{Path, PathBuf};
11use std::process::Command;
12use std::sync::{
13 Arc,
14 atomic::{AtomicU64, Ordering},
15};
16use std::time::Instant;
17
18use ec_core::registry::{CodecId, MediaType, SeekMode};
19use ec_core::timebase::{TimeBase, Timestamp};
20use ec_probe::Reader;
21
22fn manifest() -> Vec<(PathBuf, String, String, f64)> {
23 let path =
24 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
25 let Ok(text) = std::fs::read_to_string(path) else {
26 return Vec::new();
27 };
28 text.lines()
29 .skip(1)
30 .filter_map(|line| {
31 let f: Vec<&str> = line.split('\t').collect();
32 let path = PathBuf::from(f.first()?);
33 let acodecs = f
34 .get(7)
35 .filter(|s| **s != "-")
36 .map_or_else(String::new, |s| (*s).to_string());
37 Some((
38 path,
39 (*f.get(1)?).to_string(),
40 acodecs,
41 f.get(8)?.parse().unwrap_or(0.0),
42 ))
43 })
44 .collect()
45}
46
47/// Decode `secs` of audio from the current position; answers sample frames.
48fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result<u64, String> {
49 let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
50 let rate = f64::from(decoder.sample_rate().max(1));
51 let want = (secs * rate) as u64;
52 let mut out = Vec::new();
53 let mut frames = 0u64;
54 while frames < want {
55 let packet = match reader.next_packet() {
56 Ok(p) => p,
57 Err(e) if e.is_eof() => break,
58 Err(e) => return Err(format!("demux: {e}")),
59 };
60 if packet.stream != stream {
61 continue;
62 }
63 decoder
64 .decode(&packet, &mut out)
65 .map_err(|e| format!("decode: {e}"))?;
66 frames += (out.len() / decoder.channels().max(1)) as u64;
67 }
68 Ok(frames)
69}
70
71fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>, String> {
72 let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
73 let channels = decoder.channels().max(1);
74 let want = (secs * f64::from(decoder.sample_rate().max(1)) * channels as f64) as usize;
75 let mut scratch = Vec::new();
76 let mut pcm = Vec::new();
77 while pcm.len() < want {
78 let packet = match reader.next_packet() {
79 Ok(p) => p,
80 Err(e) if e.is_eof() => break,
81 Err(e) => return Err(format!("demux: {e}")),
82 };
83 if packet.stream != stream {
84 continue;
85 }
86 decoder
87 .decode(&packet, &mut scratch)
88 .map_err(|e| format!("decode: {e}"))?;
89 pcm.extend_from_slice(&scratch);
90 }
91 pcm.truncate(want);
92 Ok(pcm)
93}
94
95fn reference_seek_window(path: &Path, at: f64) -> Vec<f32> {
96 let out = Command::new("ffmpeg")
97 .args(["-v", "error", "-ss", &format!("{at:.6}"), "-i"])
98 .arg(path)
99 .args([
100 "-t",
101 "2",
102 "-map",
103 "0:a:0",
104 "-f",
105 "f32le",
106 "-acodec",
107 "pcm_f32le",
108 "-",
109 ])
110 .output()
111 .expect("reference decoder runs");
112 assert!(
113 out.status.success(),
114 "{}",
115 String::from_utf8_lossy(&out.stderr)
116 );
117 out.stdout
118 .chunks_exact(4)
119 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
120 .collect()
121}
122
123struct CountedFile {
124 inner: File,
125 bytes: Arc<AtomicU64>,
126}
127
128impl Read for CountedFile {
129 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
130 let n = self.inner.read(buf)?;
131 self.bytes.fetch_add(n as u64, Ordering::Relaxed);
132 Ok(n)
133 }
134}
135
136impl Seek for CountedFile {
137 fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
138 self.inner.seek(pos)
139 }
140}
141
142fn hive_avi_files() -> Vec<PathBuf> {
143 let root = Path::new("/home/user/Downloads");
144 let Ok(entries) = std::fs::read_dir(root) else {
145 return Vec::new();
146 };
147 let mut files = Vec::new();
148 for entry in entries.flatten() {
149 let path = entry.path();
150 if !path
151 .file_name()
152 .and_then(|n| n.to_str())
153 .is_some_and(|n| n.contains("Hive-CM8"))
154 {
155 continue;
156 }
157 let Ok(children) = std::fs::read_dir(path) else {
158 continue;
159 };
160 for child in children.flatten() {
161 let path = child.path();
162 if path.extension().and_then(|e| e.to_str()) == Some("avi") {
163 files.push(path);
164 }
165 }
166 }
167 files.sort_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(u64::MAX));
168 files
169}
170
171fn assert_avi_index_is_bounded(path: &Path) {
172 let file_size = std::fs::metadata(path).expect("AVI metadata").len();
173 let index_len = ec_riff::AviReader::new(File::open(path).expect("open AVI"))
174 .expect("AVI index builds")
175 .index_len();
176 assert!(
177 u64::try_from(index_len).expect("index count fits u64") <= file_size / 8,
178 "{}: index has {index_len} chunks for {file_size} bytes",
179 path.display()
180 );
181 eprintln!(
182 "{}: AVI index {index_len} chunks / {file_size} bytes",
183 path.display()
184 );
185}
186
187fn avi_indexed_point(path: &Path, target: u64, after: bool) -> (ec_riff::AviIndexPoint, f64) {
188 let reader =
189 ec_riff::AviReader::new(File::open(path).expect("open AVI")).expect("AVI index builds");
190 let stream = *reader.audio_streams().first().expect("AVI audio stream");
191 let interval = f64::from(stream.length) * f64::from(stream.scale)
192 / f64::from(stream.rate)
193 / reader.index_len() as f64;
194 (
195 reader
196 .indexed_point(stream.index, target, after)
197 .expect("AVI indexed point"),
198 interval,
199 )
200}
201
202fn samples_to_avi_units(stream: ec_riff::AviAudioStream, samples: u64, round_up: bool) -> u64 {
203 let denominator = u128::from(stream.scale) * u128::from(stream.sample_rate);
204 let numerator = u128::from(samples) * u128::from(stream.rate);
205 let units = if round_up {
206 numerator.saturating_add(denominator.saturating_sub(1)) / denominator
207 } else {
208 numerator / denominator
209 };
210 units.min(u128::from(u64::MAX)) as u64
211}
212
213fn avi_codec_preroll(codec: CodecId, rate: u32) -> f64 {
214 match codec {
215 CodecId::Mp3 => 1728.0 / f64::from(rate),
216 CodecId::Aac => 1024.0 / f64::from(rate),
217 _ => 0.0,
218 }
219}
220
221fn decode_stream_to_eof(
222 reader: &mut Reader,
223 stream: u32,
224 collect: bool,
225) -> Result<(u64, u64, Vec<f32>), String> {
226 let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
227 let mut scratch = Vec::new();
228 let mut pcm = Vec::new();
229 let mut packets = 0u64;
230 let mut frames = 0u64;
231 loop {
232 let packet = match reader.next_packet() {
233 Ok(p) => p,
234 Err(e) if e.is_eof() => break,
235 Err(e) => return Err(format!("demux: {e}")),
236 };
237 if packet.stream != stream {
238 continue;
239 }
240 decoder
241 .decode(&packet, &mut scratch)
242 .map_err(|e| format!("decode: {e}"))?;
243 packets += 1;
244 frames += (scratch.len() / decoder.channels().max(1)) as u64;
245 if collect {
246 pcm.extend_from_slice(&scratch);
247 }
248 }
249 decoder
250 .flush(&mut scratch)
251 .map_err(|e| format!("flush: {e}"))?;
252 frames += (scratch.len() / decoder.channels().max(1)) as u64;
253 if collect {
254 pcm.extend_from_slice(&scratch);
255 }
256 Ok((packets, frames, pcm))
257}
258
259fn corr(a: &[f32], b: &[f32]) -> f64 {
260 let n = a.len().min(b.len());
261 let (mut num, mut a2, mut b2) = (0.0f64, 0.0f64, 0.0f64);
262 for i in 0..n {
263 let (x, y) = (a[i] as f64, b[i] as f64);
264 num += x * y;
265 a2 += x * x;
266 b2 += y * y;
267 }
268 num / (a2.sqrt() * b2.sqrt()).max(1e-12)
269}
270
271fn best_frame_corr(
272 ours: &[f32],
273 theirs: &[f32],
274 channels: usize,
275 frame_samples: usize,
276) -> (i32, f64) {
277 let frame = channels * frame_samples;
278 (-1..=1)
279 .map(|lag| {
280 let (ours, theirs) = if lag < 0 {
281 (ours, theirs.get(frame..).unwrap_or(&[]))
282 } else {
283 (ours.get(frame * lag as usize..).unwrap_or(&[]), theirs)
284 };
285 (lag, corr(ours, theirs))
286 })
287 .max_by(|(_, a), (_, b)| a.total_cmp(b))
288 .unwrap()
289}
290
291fn assert_avi_seeks_match_reference(path: &Path) {
292 assert_avi_index_is_bounded(path);
293 let bytes = Arc::new(AtomicU64::new(0));
294 let src = CountedFile {
295 inner: File::open(path).expect("open AVI"),
296 bytes: bytes.clone(),
297 };
298 let mut reader = Reader::new(src, Some("avi")).expect("AVI opens");
299 let audio = reader
300 .default_stream(MediaType::Audio)
301 .expect("AVI audio stream")
302 .clone();
303 let rate = audio.params.audio().unwrap().sample_rate.max(1);
304 let channels = audio.params.audio().unwrap().layout.channel_count().max(1);
305 let frame_samples = match audio.params.codec {
306 CodecId::Ac3 | CodecId::EAc3 => 1536,
307 CodecId::Mp3 => 1152,
308 _ => 1,
309 };
310 let avi_stream = *ec_riff::AviReader::new(File::open(path).expect("open AVI"))
311 .expect("AVI index builds")
312 .audio_streams()
313 .first()
314 .expect("AVI audio stream");
315 let duration = reader.duration().expect("AVI duration").as_secs_f64();
316 let codec_preroll = avi_codec_preroll(audio.params.codec, rate);
317 for fraction in [0.10, 0.50, 0.90] {
318 let target = duration * fraction;
319 let ticks = (target * f64::from(rate)) as i64;
320 for (mode, label) in [
321 (SeekMode::SyncBefore, "before"),
322 (SeekMode::SyncAfter, "after"),
323 ] {
324 let target_units = samples_to_avi_units(
325 avi_stream,
326 ticks.max(0) as u64,
327 matches!(mode, SeekMode::SyncAfter),
328 );
329 let (point, chunk_interval) =
330 avi_indexed_point(path, target_units, matches!(mode, SeekMode::SyncAfter));
331 let before = bytes.load(Ordering::Relaxed);
332 let started = Instant::now();
333 let landed = reader
334 .seek(
335 audio.index,
336 Timestamp::new(ticks, TimeBase::from_rate(rate)),
337 mode,
338 )
339 .expect("AVI seek");
340 let elapsed = started.elapsed();
341 let read = bytes.load(Ordering::Relaxed) - before;
342 let at = landed.as_secs_f64();
343 eprintln!(
344 "{} @{:.0}% {label}: requested {target_units} units, idx1 entry {} offset {} unit {}, pre-roll 0 units 0 frames, first packet pts {}, target {target:.3}s landed {at:.3}s read {read} bytes seek {:?}",
345 path.display(),
346 fraction * 100.0,
347 point.index,
348 point.offset,
349 point.time,
350 landed.ticks,
351 elapsed,
352 );
353 assert!(
354 read < 8 * 1024 * 1024,
355 "{} @{fraction:.0}% {label}: seek read {read} bytes",
356 path.display()
357 );
358 if !cfg!(debug_assertions) {
359 assert!(
360 elapsed.as_millis() < 200,
361 "{} @{:.0}% {label}: seek took {:?}",
362 path.display(),
363 fraction * 100.0,
364 elapsed
365 );
366 }
367 match mode {
368 SeekMode::SyncBefore => {
369 assert!(
370 at <= target,
371 "{} @{fraction:.0}%: SyncBefore landed {at:.3}s after target {target:.3}s",
372 path.display()
373 );
374 let bound = (2.0 * chunk_interval).max(codec_preroll);
375 assert!(
376 target - at <= bound,
377 "{} @{fraction:.0}%: SyncBefore landed {:.3}s before target {target:.3}s (bound {bound:.3}s)",
378 path.display(),
379 target - at,
380 );
381 let ours =
382 decode_window(&mut reader, audio.index, 2.0).expect("decode after seek");
383 let theirs = reference_seek_window(path, at);
384 let (lag, score) = best_frame_corr(&ours, &theirs, channels, frame_samples);
385 assert!(
386 score >= 0.999,
387 "{} @{:.0}% {label}: target {target:.3}s landed {at:.3}s lag {lag} frames corr vs reference decoder = {score}",
388 path.display(),
389 fraction * 100.0,
390 );
391 }
392 SeekMode::SyncAfter => {
393 assert!(
394 at >= target,
395 "{} @{fraction:.0}%: SyncAfter landed {at:.3}s before target {target:.3}s",
396 path.display()
397 );
398 assert!(
399 at - target <= chunk_interval,
400 "{} @{fraction:.0}%: SyncAfter landed {:.3}s after target {target:.3}s (chunk interval {chunk_interval:.3}s)",
401 path.display(),
402 at - target,
403 );
404 }
405 SeekMode::Exact => unreachable!("oracle checks indexed seeks only"),
406 }
407 }
408 }
409}
410
411fn synthetic_mp3_avi() -> Option<PathBuf> {
412 if !Command::new("ffmpeg")
413 .args(["-version"])
414 .output()
415 .is_ok_and(|out| out.status.success())
416 {
417 eprintln!("reference encoder/decoder absent, skipping synthetic AVI");
418 return None;
419 }
420 let root = PathBuf::from(std::env::var_os("HOME").expect("HOME")).join(".cache/aviseek");
421 std::fs::create_dir_all(&root).expect("create scratch directory");
422 let path = root.join(format!("seek-oracle-{}.avi", std::process::id()));
423 let out = Command::new("ffmpeg")
424 .args([
425 "-v",
426 "error",
427 "-f",
428 "lavfi",
429 "-i",
430 "sine=frequency=997:sample_rate=48000:duration=30",
431 "-c:a",
432 "libmp3lame",
433 "-f",
434 "avi",
435 "-y",
436 ])
437 .arg(&path)
438 .output()
439 .expect("reference encoder runs");
440 assert!(
441 out.status.success(),
442 "{}",
443 String::from_utf8_lossy(&out.stderr)
444 );
445 Some(path)
446}
447
448/// Ten files with sound, standalone audio first, then Matroska — opened,
449/// decoded and seeked, with a per-file row in the report.
450#[test]
451fn a_real_library_sweep() {
452 let files = manifest();
453 if files.is_empty() {
454 eprintln!("no manifest — run scripts/scan-real-library.sh");
455 return;
456 }
457 // Half standalone audio, half Matroska: the two paths this crate owns, and
458 // one row per distinct audio codec the library actually holds rather than
459 // ten copies of the same aac remux.
460 let standalone = |p: &Path| {
461 let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
462 [
463 "mp3", "flac", "wav", "ogg", "opus", "m4a", "aac", "mp4", "mov",
464 ]
465 .contains(&ext)
466 };
467 let mut chosen: Vec<_> = Vec::new();
468 let mut seen = Vec::new();
469 for want_mkv in [false, true] {
470 let mut taken = 0;
471 for f in &files {
472 let (p, container, acodecs, _) = f;
473 if acodecs.is_empty() || !p.exists() || taken >= 5 {
474 continue;
475 }
476 let is_mkv = container.contains("matroska");
477 if is_mkv != want_mkv || (!is_mkv && !standalone(p)) {
478 continue;
479 }
480 // One file per (container, codec set): variety beats repetition.
481 let key = format!("{is_mkv}:{acodecs}");
482 if seen.contains(&key) {
483 continue;
484 }
485 seen.push(key);
486 chosen.push(f);
487 taken += 1;
488 }
489 }
490 assert!(!chosen.is_empty(), "no readable files in the manifest");
491
492 let mut rows = Vec::new();
493 let mut failures = Vec::new();
494 for (path, container, acodecs, duration) in &chosen {
495 let name = path.file_name().unwrap().to_string_lossy().to_string();
496 let mut reader = match Reader::open(path) {
497 Ok(r) => r,
498 Err(e) => {
499 failures.push(format!("{name}: open failed: {e}"));
500 continue;
501 }
502 };
503 // The first audio stream that actually decodes, which is what a player
504 // plays; the ones that do not are named below rather than skipped over.
505 let audio = reader
506 .streams()
507 .iter()
508 .find(|s| {
509 s.params.codec.media_type() == MediaType::Audio
510 && reader.make_decoder(s.index).is_ok()
511 })
512 .or_else(|| reader.default_stream(MediaType::Audio))
513 .cloned();
514 let Some(audio) = audio else {
515 failures.push(format!("{name}: no audio stream, ffprobe says {acodecs}"));
516 continue;
517 };
518 let unsupported = reader.unsupported();
519 // Every codec ffprobe lists is either decodable here or named as not.
520 let listed: Vec<String> = reader
521 .streams()
522 .iter()
523 .filter(|s| s.params.codec.media_type() == MediaType::Audio)
524 .map(|s| s.params.codec.name().to_string())
525 .collect();
526 let decoded = decode_some(&mut reader, audio.index, 1.0);
527 let rate = audio.params.audio().map_or(0, |a| a.sample_rate).max(1);
528 let landing = if *duration > 4.0 {
529 let ticks = (duration / 2.0 * f64::from(rate)) as i64;
530 reader
531 .seek(
532 audio.index,
533 Timestamp::new(ticks, TimeBase::from_rate(rate)),
534 SeekMode::SyncBefore,
535 )
536 .map(|t| t.as_secs_f64())
537 .map_err(|e| e.to_string())
538 } else {
539 Ok(0.0)
540 };
541 let after_seek = landing
542 .as_ref()
543 .ok()
544 .map(|_| decode_some(&mut reader, audio.index, 0.5));
545
546 let ok = decoded.is_ok()
547 && landing.is_ok()
548 && matches!(after_seek, Some(Ok(n)) if n > 0)
549 && listed.iter().any(|c| acodecs.split(',').any(|a| a == c));
550 if !ok {
551 failures.push(format!(
552 "{name}: decode {decoded:?} seek {landing:?} after {after_seek:?} \
553 codecs {listed:?} vs ffprobe {acodecs}"
554 ));
555 }
556 rows.push(format!(
557 "{:<52} {:<16} {:<14} {:>7} frames seek->{:>8} {}",
558 name.chars().take(52).collect::<String>(),
559 container.split(',').next().unwrap_or(container),
560 listed.join(","),
561 decoded.clone().unwrap_or(0),
562 landing
563 .as_ref()
564 .map(|s| format!("{s:.2}s"))
565 .unwrap_or_else(|e| e.clone()),
566 match unsupported.is_empty() {
567 true => "all decodable".to_string(),
568 false => unsupported
569 .iter()
570 .map(|u| format!("unsupported: {} ({})", u.codec.name(), u.reason))
571 .collect::<Vec<_>>()
572 .join("; "),
573 }
574 ));
575 }
576 eprintln!(
577 "real-library sweep ({} files):\n{}",
578 rows.len(),
579 rows.join("\n")
580 );
581 assert!(failures.is_empty(), "{}", failures.join("\n"));
582}
583
584#[test]
585fn avi_audio_chunks_end_cleanly_on_real_files() {
586 let files = [
587 "/home/user/Downloads/reele/reele.avi",
588 "/home/user/Downloads/reele/sample.avi",
589 ];
590 let mut present = 0;
591 for path in files {
592 let path = Path::new(path);
593 if !path.exists() {
594 continue;
595 }
596 present += 1;
597 let mut reader = Reader::open(path).expect("AVI opens");
598 let audio = reader
599 .default_stream(MediaType::Audio)
600 .expect("AVI audio stream")
601 .index;
602 let (packets, frames, _) =
603 decode_stream_to_eof(&mut reader, audio, false).unwrap_or_else(|e| {
604 panic!("{}: {e}", path.display());
605 });
606 eprintln!(
607 "{}: open ok, packets {packets}, decode-to-EOF {frames} frames",
608 path.display()
609 );
610 assert!(packets > 0, "{}: no audio packets", path.display());
611 assert!(frames > 0, "{}: no decoded audio", path.display());
612 }
613 if present == 0 {
614 // The library is his, so a file can leave it; the sibling AVI tests
615 // skip the same way rather than failing a run on a deleted download.
616 eprintln!("AVI files absent, skipping");
617 }
618}
619
620#[test]
621fn avi_ac3_matches_reference_decoder_on_real_sample() {
622 let path = Path::new(
623 "/home/user/Downloads/reele/sample.avi",
624 );
625 if !path.exists() {
626 eprintln!("file not present, skipping");
627 return;
628 }
629
630 let mut reader = Reader::open(path).expect("AVI opens");
631 let audio = reader
632 .default_stream(MediaType::Audio)
633 .expect("AVI audio stream")
634 .index;
635 let (packets, frames, ours) =
636 decode_stream_to_eof(&mut reader, audio, true).expect("AVI decodes to EOF");
637 assert!(packets > 0, "no packets");
638 assert!(frames > 0, "no decoded frames");
639
640 let out = Command::new("ffmpeg")
641 .args(["-v", "error", "-i"])
642 .arg(path)
643 .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
644 .output()
645 .expect("reference decoder runs");
646 assert!(
647 out.status.success(),
648 "{}",
649 String::from_utf8_lossy(&out.stderr)
650 );
651 let theirs: Vec<f32> = out
652 .stdout
653 .chunks_exact(4)
654 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
655 .collect();
656 let score = corr(&ours, &theirs);
657 eprintln!(
658 "{}: open ok, packets {packets}, decode-to-EOF {frames} frames, corr {score:.6}",
659 path.display()
660 );
661 assert!(score > 0.999, "corr vs reference decoder = {score}");
662}
663
664#[test]
665fn avi_seek_matches_reference_decoder_on_real_files() {
666 let files = hive_avi_files();
667 if files.is_empty() {
668 eprintln!("AVI files absent, skipping");
669 return;
670 }
671 for path in files {
672 assert_avi_seeks_match_reference(&path);
673 }
674}
675
676#[test]
677fn avi_seek_matches_reference_decoder_on_synthetic_mp3() {
678 let Some(path) = synthetic_mp3_avi() else {
679 return;
680 };
681 assert_avi_seeks_match_reference(&path);
682 std::fs::remove_file(path).expect("remove synthetic AVI");
683}
684
685/// The TrueHD remux in his library: the track decodes through the unified
686/// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too.
687#[test]
688fn a_truehd_track_decodes() {
689 let Some((path, ..)) = manifest()
690 .into_iter()
691 .find(|(p, _, acodecs, _)| acodecs.contains("truehd") && p.exists())
692 else {
693 eprintln!("no TrueHD file in the manifest — skipping");
694 return;
695 };
696 let mut reader = Reader::open(&path).expect("open");
697 let truehd = reader
698 .streams()
699 .iter()
700 .find(|s| s.params.codec.name() == "truehd")
701 .cloned()
702 .expect("the TrueHD track is listed");
703 let decoder = reader.make_decoder(truehd.index).expect("truehd decoder");
704 assert_eq!(decoder.channels(), 8, "7.1 TrueHD is 8 channels");
705 assert_eq!(decoder.sample_rate(), 48_000);
706 let frames = decode_some(&mut reader, truehd.index, 1.0).expect("decode");
707 assert!(frames > 0, "no TrueHD audio came out");
708 // ...and the AC-3 track beside it still decodes.
709 let decodable: Vec<_> = reader
710 .streams()
711 .iter()
712 .filter(|s| s.params.codec.media_type() == MediaType::Audio)
713 .filter(|s| reader.make_decoder(s.index).is_ok())
714 .map(|s| s.params.codec.name())
715 .collect();
716 assert!(
717 decodable.contains(&"ac3") || decodable.contains(&"truehd"),
718 "a file with a TrueHD track and an AC-3 one came out with nothing to play: {decodable:?}"
719 );
720 eprintln!(
721 "{}: truehd decoded {frames} frames, tracks {decodable:?}",
722 path.file_name().unwrap().to_string_lossy(),
723 );
724}
725
726/// ffprobe's stream count for the same file, as a cross-check that nothing is
727/// being hidden.
728#[allow(dead_code)]
729fn ffprobe_audio_codecs(path: &Path) -> Vec<String> {
730 let out = Command::new("ffprobe")
731 .args([
732 "-v",
733 "error",
734 "-select_streams",
735 "a",
736 "-show_entries",
737 "stream=codec_name",
738 "-of",
739 "default=nw=1:nk=1",
740 ])
741 .arg(path)
742 .output()
743 .expect("ffprobe");
744 String::from_utf8_lossy(&out.stdout)
745 .lines()
746 .map(|l| l.trim().to_string())
747 .collect()
748}
749
750/// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole
751/// image ahead of the first frame; opening must skip the tag by its own
752/// syncsafe size and never confuse the codec/window prefixes it hunts for
753/// sync in with that image's bytes. Matched against ffmpeg's own decode of
754/// the same first second, not just "it opened".
755#[test]
756fn a_cover_art_tagged_mp3_opens() {
757 let path = Path::new("/home/user/Music/reeli.mp3");
758 if !path.exists() {
759 eprintln!("file not present, skipping");
760 return;
761 }
762 let mut reader = Reader::open(path).expect("open");
763 let audio = reader
764 .default_stream(MediaType::Audio)
765 .cloned()
766 .expect("audio stream");
767 let mut decoder = reader.make_decoder(audio.index).expect("decoder");
768 let rate = decoder.sample_rate();
769 let channels = decoder.channels().max(1) as u32;
770 // The raw decoder hands back every sample the bitstream carries,
771 // including the LAME/Xing encoder's lead-in; `initial_padding` (parsed
772 // from that header) is how many of them a player is meant to drop
773 // (ec-core registry.rs: "audible length is duration - initial_padding").
774 // ffmpeg does that trim itself before writing PCM, so match it here.
775 let lead_in = audio.initial_padding * channels;
776 let mut ours = Vec::new();
777 let mut scratch = Vec::new();
778 let mut n = 0;
779 while (ours.len() as u32) < rate + lead_in {
780 let packet = match reader.next_packet() {
781 Ok(p) => p,
782 Err(e) => panic!("next_packet after {n} packets, {} samples: {e}", ours.len()),
783 };
784 n += 1;
785 if packet.stream != audio.index {
786 continue;
787 }
788 decoder.decode(&packet, &mut scratch).expect("decode 1s");
789 ours.extend_from_slice(&scratch);
790 }
791 let ours = &ours[lead_in as usize..];
792 assert!(ours.len() as u32 >= rate / 2, "decoded too little audio");
793
794 let out = Command::new("ffmpeg")
795 .args(["-v", "error", "-t", "1", "-i"])
796 .arg(path)
797 .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
798 .output()
799 .expect("ffmpeg runs");
800 assert!(
801 out.status.success(),
802 "{}",
803 String::from_utf8_lossy(&out.stderr)
804 );
805 let theirs: Vec<f32> = out
806 .stdout
807 .chunks_exact(4)
808 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
809 .collect();
810
811 let n = ours.len().min(theirs.len());
812 let (mut num, mut a2, mut b2) = (0.0f64, 0.0f64, 0.0f64);
813 for i in 0..n {
814 let (a, b) = (ours[i] as f64, theirs[i] as f64);
815 num += a * b;
816 a2 += a * a;
817 b2 += b * b;
818 }
819 let corr = num / (a2.sqrt() * b2.sqrt()).max(1e-12);
820 assert!(corr >= 0.999, "corr vs ffmpeg = {corr}");
821}