forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

ao_output.rs203 lines, 8.6 KiBHistoryRawDownload
1//! Audio output checks. These need a PulseAudio-protocol server (pipewire-pulse
2//! or PulseAudio), so they are `#[ignore]`d by default. They only ever talk to
3//! the server named by `PULSE_SERVER`, and refuse to run against the default
4//! one under `$XDG_RUNTIME_DIR`: point them at a private instance. Run them with:
5//!
6//! ```text
7//! PULSE_SERVER=unix:/path/to/private/pulse/native \
8//! cargo test -p engine --release --test ao_output -- --ignored --nocapture --test-threads=1
9//! ```
10//!
11//! `no_daemon_opens_nothing` re-runs itself as a child process with
12//! `PULSE_SERVER` pointed at a missing socket, since the client reads the real
13//! environment.
14
15use std::f32::consts::TAU;
16use std::time::{Duration, Instant};
17
18use engine::ao::AoSession;
19
20const RATE: u32 = 44100;
21const CHANNELS: u32 = 2;
22
23/// Half a second of a quiet 1 kHz tone, interleaved stereo.
24fn tone() -> Vec<f32> {
25 let frames = RATE as usize / 2;
26 let mut samples = Vec::with_capacity(frames * CHANNELS as usize);
27 for i in 0..frames {
28 let value = (i as f32 * TAU * 1000.0 / RATE as f32).sin() * 0.2;
29 samples.extend([value; CHANNELS as usize]);
30 }
31 samples
32}
33
34/// Opens the device the way this suite wants it: connected for real, and
35/// silent. Everything these tests assert -- that the clock runs, at the right
36/// rate, and stops when the stream is paused -- is measured from the device's
37/// own position, which the gain does not touch: the frames are still consumed,
38/// only the last multiply before the speaker is zero.
39///
40/// corner-cut: it does mean the suite is deaf, so a gain stuck at zero would pass
41/// it. Nothing here could ever hear that -- the checks that can are the gain unit
42/// test in `pulse` and a person with the app open. The upgrade path is recording
43/// a null sink and asserting on the samples that come back.
44fn open_silent() -> AoSession {
45 want_real_device();
46 let ao = AoSession::open(RATE, CHANNELS).expect("no PulseAudio-protocol server available");
47 assert!(ao.set_volume(0.0), "mute rejected");
48 ao
49}
50
51/// Routes the opens in this suite to the real server, and only to a server the
52/// caller named: a suite that fell through to the default socket would play
53/// through the person's own sound. A session's own server lives under
54/// `/run/user/<uid>`, so that prefix is refused.
55fn want_real_device() {
56 let server = engine::envcfg::var("PULSE_SERVER").expect("set PULSE_SERVER to a private server");
57 assert!(
58 !server.contains("/run/user/"),
59 "PULSE_SERVER names a session's own server; use a private one"
60 );
61 engine::envcfg::set("VE_AO", "1");
62}
63
64/// Waits up to `limit` for the clock to report a played position past zero.
65fn wait_for_playback(ao: &AoSession, limit: Duration) -> i64 {
66 let start = Instant::now();
67 loop {
68 if let Some(position) = ao.position()
69 && position > 0
70 {
71 return position;
72 }
73 assert!(start.elapsed() < limit, "playback position never advanced");
74 std::thread::sleep(Duration::from_millis(10));
75 }
76}
77
78#[test]
79#[ignore = "needs a private pulse-protocol server (PULSE_SERVER)"]
80fn plays_and_tracks_position() {
81 assert!(AoSession::probe(), "no server socket");
82 let mut ao = open_silent();
83
84 // The ring holds a second, so two halves go in whole -- enough real audio
85 // to cover the measurement below without starving.
86 let samples = tone();
87 assert_eq!(ao.write(&samples), Some(samples.len()), "short write");
88 assert_eq!(ao.write(&samples), Some(samples.len()), "short write");
89
90 // Over 400 ms the clock must run at the rate we asked for, not at the
91 // device's: the plugin converts the server's ticks out of its graph rate.
92 let first = wait_for_playback(&ao, Duration::from_secs(2));
93 std::thread::sleep(Duration::from_millis(400));
94 let second = ao.position().expect("position went unknown");
95 let advanced = second - first;
96 let expected = RATE as i64 * 400 / 1000;
97 eprintln!("clock advanced {advanced} samples in 400 ms (expected ~{expected})");
98 assert!(
99 (advanced - expected).abs() < expected / 10,
100 "clock runs at the wrong rate: {advanced} samples in 400 ms"
101 );
102
103 // Paused means the device plays nothing, so the master clock must not move.
104 assert!(ao.set_active(false), "pause rejected");
105 std::thread::sleep(Duration::from_millis(150));
106 let paused = ao.position().expect("position went unknown");
107 std::thread::sleep(Duration::from_millis(100));
108 assert_eq!(
109 ao.position(),
110 Some(paused),
111 "position moved while paused: {paused}"
112 );
113
114 ao.write(&samples).expect("write after pause");
115 assert!(ao.set_active(true), "resume rejected");
116 std::thread::sleep(Duration::from_millis(200));
117 let resumed = ao.position().expect("position went unknown");
118 assert!(
119 resumed > paused,
120 "clock did not resume: {paused} -> {resumed}"
121 );
122}
123
124/// Muting is not pausing: the device keeps consuming and the master clock keeps
125/// running, which is the whole reason the picture can play on through a mute.
126/// That the samples really go quiet is the gain unit test in `pulse` -- nothing
127/// out here can hear the device.
128#[test]
129#[ignore = "needs a private pulse-protocol server (PULSE_SERVER)"]
130fn muting_silences_without_stopping_the_clock() {
131 assert!(AoSession::probe(), "no server socket");
132 let mut ao = open_silent();
133
134 let samples = tone();
135 assert_eq!(ao.write(&samples), Some(samples.len()), "short write");
136 let first = wait_for_playback(&ao, Duration::from_secs(2));
137
138 // Muted and fed: the position must move exactly as it would have.
139 assert_eq!(ao.write(&samples), Some(samples.len()), "short write");
140 std::thread::sleep(Duration::from_millis(300));
141 let muted = ao.position().expect("position went unknown");
142 let advanced = muted - first;
143 let expected = RATE as i64 * 300 / 1000;
144 eprintln!("clock advanced {advanced} samples in 300 ms while muted (expected ~{expected})");
145 assert!(
146 (advanced - expected).abs() < expected / 5,
147 "the clock stalled while muted: {advanced} samples in 300 ms"
148 );
149
150 // Every level in range is taken, and the two ends are in range. Done on an
151 // emptied ring and left back at zero, so that the audible gains this walks
152 // through have nothing but the underrun fill to be applied to: whoever runs
153 // the suite should not have to hear it prove that 1.0 is a legal number.
154 assert!(ao.flush(), "flush rejected");
155 // A flush lands on the next callback and the ring refuses writes until it
156 // does, so give it a couple of quanta before asking for anything else.
157 std::thread::sleep(Duration::from_millis(50));
158 for gain in [0.5, 1.0, 0.0] {
159 assert!(ao.set_volume(gain), "gain {gain} rejected");
160 }
161 // Out of range is refused at the ABI rather than multiplied into the
162 // speakers -- a NaN would otherwise reach the RT thread and stay there.
163 for gain in [-0.1, 1.5, f32::NAN, f32::INFINITY] {
164 assert!(!ao.set_volume(gain), "gain {gain} accepted");
165 }
166 // ...and a refusal changes nothing: the last accepted gain still stands.
167 assert_eq!(ao.write(&samples), Some(samples.len()), "short write");
168 std::thread::sleep(Duration::from_millis(100));
169 assert!(
170 ao.position().expect("position went unknown") > muted,
171 "clock stopped after a refused gain"
172 );
173}
174
175/// No reachable daemon must fail the open cleanly and quickly, never hang.
176#[test]
177#[ignore = "needs a private pulse-protocol server (PULSE_SERVER)"]
178fn no_daemon_opens_nothing() {
179 // The client reads `PULSE_SERVER` from the real environment, which this
180 // process may not edit safely, so the test runs itself again as a child with
181 // the variable set and does the open there.
182 const CHILD: &str = "EDITH_AO_NO_DAEMON_CHILD";
183 if std::env::var_os(CHILD).is_none() {
184 let status = std::process::Command::new(std::env::current_exe().expect("test binary"))
185 .arg("no_daemon_opens_nothing")
186 .args(["--exact", "--ignored", "--nocapture", "--test-threads=1"])
187 .env(CHILD, "1")
188 .env("PULSE_SERVER", "unix:/nonexistent/pulse/native")
189 .status()
190 .expect("re-run the test binary");
191 assert!(status.success(), "the no-daemon child failed: {status}");
192 return;
193 }
194 want_real_device();
195 let start = Instant::now();
196 let session = AoSession::open(RATE, CHANNELS);
197
198 let elapsed = start.elapsed();
199
200 assert!(session.is_none(), "opened a stream with no daemon");
201 assert!(elapsed < Duration::from_secs(2), "open took {elapsed:?}");
202 eprintln!("open with no daemon failed in {elapsed:?}");
203}