forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

ao.rs310 lines, 11.1 KiBHistoryRawDownload
1//! Audio output: a PulseAudio native-protocol playback stream ([`crate::pulse`]),
2//! served by pipewire-pulse or PulseAudio, or a silent wall-clock stand-in.
3//!
4//! Anything that goes wrong -- no server, the server refuses us, an unusable
5//! format -- leaves us with `None` and the caller plays on a wall clock. Nothing
6//! here links a C library or needs `unsafe`.
7//!
8//! `VE_NO_AO=1` (and cargo-test binaries under `target/*/deps/`) open a silent
9//! sink instead: the session, the clock and the feeder stay, and the server is
10//! never touched. `VE_AO=1` forces the real server, which is what the ignored
11//! `ao_output` suite needs.
12
13use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering};
14use std::sync::LazyLock;
15use std::time::Instant;
16
17use crate::pulse::{self, Playback};
18
19static DEVICES_OPENED: AtomicU64 = AtomicU64::new(0);
20
21fn env_is(name: &str, value: &str) -> bool {
22 crate::envcfg::var_os(name).is_some_and(|v| v == value)
23}
24
25/// A cargo-test binary lives in `target/<profile>/deps/<name>-<hash>`. The
26/// editor itself is `target/<profile>/edith`, which is what the harness
27/// launches, so this never mutes a real session.
28fn cargo_test_binary() -> bool {
29 std::env::current_exe()
30 .ok()
31 .and_then(|p| p.parent().map(|d| d.ends_with("deps")))
32 .unwrap_or(false)
33}
34
35/// Set by [`set_silent_output`]: this process opens silent sinks from then on.
36static NO_AO: AtomicBool = AtomicBool::new(false);
37
38/// Makes every audio session this process opens silent, the same as `VE_NO_AO=1`
39/// does, without touching the process environment (which is `unsafe` to edit in
40/// Rust 2024). One-way and process-wide; `VE_AO=1` still forces the real device.
41pub fn set_silent_output() {
42 NO_AO.store(true, Ordering::SeqCst);
43}
44
45fn silent_output() -> bool {
46 if env_is("VE_AO", "1") {
47 return false;
48 }
49 NO_AO.load(Ordering::SeqCst) || env_is("VE_NO_AO", "1") || cargo_test_binary()
50}
51
52/// An open playback stream. Dropping it stops playback and closes the session.
53pub struct AoSession {
54 backend: Backend,
55}
56
57enum Backend {
58 Server(Playback),
59 /// Wall-clock paced, samples discarded. Same contract as the server stream
60 /// (paused until `set_active`, position is samples per channel) without a
61 /// sink-input on the user's speakers.
62 Silent(Silent),
63}
64
65struct Silent {
66 rate: f64,
67 /// Samples already accounted for; `-1` until the stream has run.
68 base: AtomicI64,
69 /// 0 = paused; otherwise milliseconds from [`epoch`] at the last resume.
70 origin_ms: AtomicU64,
71 /// The gain last pushed, so the silent sink answers the same question the
72 /// real stream does: what is this stream actually multiplying by. Without it
73 /// every gain read back as a shrug, and a device that had been re-armed at
74 /// full volume looked exactly like one that had kept its level.
75 gain: AtomicU32,
76}
77
78fn epoch() -> Instant {
79 static EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
80 *EPOCH
81}
82
83fn now_ms() -> u64 {
84 epoch().elapsed().as_millis() as u64
85}
86
87impl Silent {
88 fn new(sample_rate: u32) -> Self {
89 Self {
90 rate: f64::from(sample_rate),
91 base: AtomicI64::new(-1),
92 origin_ms: AtomicU64::new(0),
93 gain: AtomicU32::new(1.0f32.to_bits()),
94 }
95 }
96
97 fn gain(&self) -> f32 {
98 f32::from_bits(self.gain.load(Ordering::Relaxed))
99 }
100
101 fn set_gain(&self, gain: f32) {
102 self.gain.store(gain.to_bits(), Ordering::Relaxed);
103 }
104
105 fn extra(&self) -> i64 {
106 match self.origin_ms.load(Ordering::Relaxed) {
107 0 => 0,
108 origin => {
109 let ms = now_ms().saturating_sub(origin) as f64;
110 (ms / 1000.0 * self.rate).round() as i64
111 }
112 }
113 }
114
115 fn position(&self) -> Option<i64> {
116 let base = self.base.load(Ordering::Relaxed);
117 let extra = self.extra();
118 if base < 0 && self.origin_ms.load(Ordering::Relaxed) == 0 {
119 None
120 } else {
121 Some(base.max(0) + extra.max(0))
122 }
123 }
124
125 fn set_active(&self, active: bool) {
126 if active {
127 if self.origin_ms.load(Ordering::Relaxed) == 0 {
128 self.base
129 .compare_exchange(-1, 0, Ordering::Relaxed, Ordering::Relaxed)
130 .ok();
131 self.origin_ms.store(now_ms().max(1), Ordering::Relaxed);
132 }
133 } else {
134 let origin = self.origin_ms.swap(0, Ordering::Relaxed);
135 if origin != 0 {
136 let ms = now_ms().saturating_sub(origin) as f64;
137 let extra = (ms / 1000.0 * self.rate).round() as i64;
138 self.base
139 .compare_exchange(-1, 0, Ordering::Relaxed, Ordering::Relaxed)
140 .ok();
141 self.base.fetch_add(extra.max(0), Ordering::Relaxed);
142 }
143 }
144 }
145}
146
147impl AoSession {
148 /// Connects a playback stream for interleaved f32 at `sample_rate`.
149 /// `None` covers everything: no server, a refused client, unusable format.
150 /// A silent pin still returns `Some`: the timeline keeps an audio clock.
151 pub fn open(sample_rate: u32, channels: u32) -> Option<Self> {
152 if silent_output() {
153 return Some(Self {
154 backend: Backend::Silent(Silent::new(sample_rate)),
155 });
156 }
157 let playback = Playback::open(sample_rate, channels)?;
158 DEVICES_OPENED.fetch_add(1, Ordering::Relaxed);
159 Some(Self {
160 backend: Backend::Server(playback),
161 })
162 }
163
164 /// How many times this process has opened a real server stream. The silent
165 /// sink does not count: that is the whole point of the pin.
166 pub fn devices_opened() -> u64 {
167 DEVICES_OPENED.load(Ordering::Relaxed)
168 }
169
170 /// Whether this session is the silent sink rather than a real stream --
171 /// what the `VE_NO_AO` pin buys, and the one form of that claim a caller can
172 /// own: [`AoSession::devices_opened`] is process-wide and moves under any
173 /// other session this process opens.
174 pub fn is_silent(&self) -> bool {
175 matches!(self.backend, Backend::Silent(_))
176 }
177
178 /// Whether a server is there to talk to: its socket exists. Says nothing
179 /// about whether it will take a stream -- only [`AoSession::open`] answers
180 /// that, and it is cheap enough to be the real probe.
181 pub fn probe() -> bool {
182 pulse::server_path().is_some_and(|path| path.exists())
183 }
184
185 /// Queues interleaved samples, returning how many were accepted; a short
186 /// count means the queue is full and the caller should come back later.
187 /// `None` once the output has died (server gone).
188 pub fn write(&mut self, samples: &[f32]) -> Option<usize> {
189 match &mut self.backend {
190 Backend::Silent(_) => Some(samples.len()),
191 Backend::Server(playback) => playback.write(samples),
192 }
193 }
194
195 /// Samples per channel actually played at the device -- the master clock.
196 /// `None` until the stream has started.
197 pub fn position(&self) -> Option<i64> {
198 match &self.backend {
199 Backend::Silent(s) => s.position(),
200 Backend::Server(playback) => playback.position(),
201 }
202 }
203
204 /// Says the last sample of this stream has been queued: the queue plays out
205 /// as it is, and the silence after it is not counted against a decoder that
206 /// has already finished.
207 pub fn stream_ended(&self) {
208 if let Backend::Server(playback) = &self.backend {
209 playback.stream_ended();
210 }
211 }
212
213 /// Pauses or resumes playback; while paused the position stays put.
214 pub fn set_active(&self, active: bool) -> bool {
215 match &self.backend {
216 Backend::Silent(s) => {
217 s.set_active(active);
218 true
219 }
220 Backend::Server(playback) => playback.set_active(active),
221 }
222 }
223
224 /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's
225 /// volume and its mute are the same knob by the time they get here. The
226 /// clock is unaffected -- a silenced stream still plays, so the picture
227 /// keeps running against it. `false` for a gain outside the range.
228 pub fn set_volume(&self, gain: f32) -> bool {
229 if !(0.0..=1.0).contains(&gain) {
230 return false;
231 }
232 match &self.backend {
233 Backend::Silent(s) => {
234 s.set_gain(gain);
235 true
236 }
237 Backend::Server(playback) => playback.set_volume(gain),
238 }
239 }
240
241 /// The gain this stream is actually running at. Always answered: the gain is
242 /// applied in this process, so the stream knows it exactly.
243 pub fn gain(&self) -> Option<f32> {
244 match &self.backend {
245 Backend::Silent(s) => Some(s.gain()),
246 Backend::Server(playback) => Some(playback.gain()),
247 }
248 }
249
250 /// Drops everything still queued, so the next samples written play right
251 /// away -- what a seek needs. The played position keeps counting.
252 pub fn flush(&self) -> bool {
253 match &self.backend {
254 Backend::Silent(_) => true,
255 Backend::Server(playback) => playback.flush(),
256 }
257 }
258
259 /// Starved callbacks so far, and the device position (samples per channel)
260 /// the last of them was seen at -- `None` for a stream that has never run
261 /// dry. Cheap enough to poll: it reads the counters the reader thread keeps.
262 pub fn underruns(&self) -> (u64, Option<i64>) {
263 match &self.backend {
264 Backend::Silent(_) => (0, None),
265 Backend::Server(playback) => playback.underruns(),
266 }
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::AoSession;
273
274 /// This module's counter assertions, one test at a time: the counters are
275 /// process-wide, so two of these tests measuring at once would see each
276 /// other's opens. Same shape as `waveform::counters_serial`, and for the
277 /// same reason -- the counters stay readable, and one at a time is the
278 /// whole point.
279 fn counters_serial() -> std::sync::MutexGuard<'static, ()> {
280 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
281 LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
282 }
283
284 #[test]
285 fn a_silent_pin_never_opens_a_device() {
286 let _serial = counters_serial();
287 super::set_silent_output();
288 let before = AoSession::devices_opened();
289 let mut ao = AoSession::open(48_000, 2).expect("silent opens");
290 // The pin's effect, on the session this test owns: no other test in
291 // this binary can open one for it, and no absolute claim is made on a
292 // counter *any* session in the process moves.
293 assert!(
294 ao.is_silent(),
295 "the pin must route the open to the silent sink"
296 );
297 assert_eq!(
298 AoSession::devices_opened(),
299 before,
300 "the silent open moved the process's device counter"
301 );
302 assert!(ao.set_volume(0.0));
303 assert!(!ao.set_volume(1.5));
304 assert!(ao.set_active(true));
305 assert_eq!(ao.write(&[0.0; 64]), Some(64));
306 assert!(ao.flush());
307 ao.stream_ended();
308 assert_eq!(ao.underruns(), (0, None));
309 }
310}