forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

audio_decode.rs140 lines, 4.5 KiBHistoryRawDownload
1use std::path::PathBuf;
2use std::time::Instant;
3
4use engine::audio::AudioSession;
5
6const RATE: u32 = 44100;
7const SECONDS: u32 = 5;
8/// One AAC-LC packet; the container's tail padding is not trimmed, so the
9/// decoded length may run up to a frame past the nominal duration.
10const FRAME: i64 = 1024;
11
12fn asset(name: &str) -> PathBuf {
13 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14 .join("../../assets")
15 .join(name)
16}
17
18/// Sign changes ignoring exact zeros, so the 1 Hz volume pulse touching zero
19/// does not register as a crossing.
20fn zero_crossings(samples: &[f32]) -> usize {
21 let mut crossings = 0;
22 let mut last = 0f32;
23 for &s in samples {
24 if s == 0.0 {
25 continue;
26 }
27 if last != 0.0 && (s > 0.0) != (last > 0.0) {
28 crossings += 1;
29 }
30 last = s;
31 }
32 crossings
33}
34
35#[test]
36fn decodes_av_mp4_audio() {
37 let start = Instant::now();
38 let (meta, rx) = AudioSession::open(asset("test_av.mp4"))
39 .expect("open")
40 .expect("test_av.mp4 has an audio track");
41 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
42
43 let mut left = Vec::new();
44 let mut right = Vec::new();
45 let mut next_sample = 0u64;
46 let mut chunks = 0usize;
47 for chunk in rx {
48 // d. no gaps, no overlaps.
49 assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start");
50 assert!(!chunk.samples.is_empty(), "empty chunk {chunks}");
51 assert_eq!(
52 chunk.samples.len() % 2,
53 0,
54 "partial frame in chunk {chunks}"
55 );
56 next_sample += (chunk.samples.len() / 2) as u64;
57 left.extend(chunk.samples.iter().step_by(2));
58 right.extend(chunk.samples[1..].iter().step_by(2));
59 chunks += 1;
60 }
61 let elapsed = start.elapsed();
62 let frames = left.len();
63 assert!(frames > 0, "no audio decoded");
64
65 // b. ~5 s of audio, priming trimmed, at most a frame of tail padding over.
66 let want = (RATE * SECONDS) as i64;
67 let slack = frames as i64 - want;
68 assert!(
69 (0..=FRAME).contains(&slack),
70 "{frames} frames per channel, want {want} (+0..={FRAME})"
71 );
72 assert_eq!(right.len(), frames, "channel lengths differ");
73
74 // c. channel identity: L is 440 Hz, R is 880 Hz. A swap or a bad interleave
75 // shows up as the wrong crossing count.
76 let secs = frames as f64 / RATE as f64;
77 for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] {
78 let want = 2.0 * hz * secs;
79 let got = zero_crossings(samples) as f64;
80 assert!(
81 (got - want).abs() <= 0.05 * want,
82 "{name}: {got} zero crossings, want {want} +/-5%"
83 );
84 }
85
86 // Priming trimmed: the sine starts at a rising zero crossing, and audio is
87 // present immediately rather than after a silent or garbage run-in.
88 assert!(
89 left[0].abs() < 0.05,
90 "first sample {} not near zero",
91 left[0]
92 );
93 assert!(left[1] > 0.0, "first sine quarter is not rising");
94 let head_peak = left[..FRAME as usize]
95 .iter()
96 .fold(0f32, |m, s| m.max(s.abs()));
97 assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}");
98
99 eprintln!(
100 "{frames} frames/ch in {chunks} chunks, {elapsed:?} ({:?}/packet)",
101 elapsed / chunks as u32
102 );
103}
104
105#[test]
106fn video_only_file_has_no_audio() {
107 assert!(
108 AudioSession::open(asset("test_baseline.mp4"))
109 .expect("open")
110 .is_none()
111 );
112 assert!(
113 AudioSession::unsupported(asset("test_baseline.mp4"))
114 .expect("probe")
115 .is_none(),
116 "a file with no audio track is not a complaint"
117 );
118}
119
120/// Sound we cannot decode must not be silence we say nothing about: the AC-3
121/// fixture opens as picture-only and the session carries the reason a
122/// front-end shows (`Player::open_media`).
123#[test]
124fn an_undecodable_audio_track_is_named() {
125 let path = asset("test_ac3.mp4");
126 assert!(
127 AudioSession::open(&path).expect("open").is_none(),
128 "AC-3 is not decodable here"
129 );
130 let reason = AudioSession::unsupported(&path)
131 .expect("probe")
132 .expect("the file has an audio track, so it owes a reason");
133 assert!(reason.contains("decode"), "unhelpful reason: {reason}");
134 let session = engine::PlaybackSession::open(&path).expect("open for playback");
135 assert_eq!(
136 session.audio_disabled_reason(),
137 Some(reason.as_str()),
138 "the session must carry it to the front-end"
139 );
140}