forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

mod.rs981 lines, 37.4 KiBHistoryRawDownload
1//! A pure-Rust client for the PulseAudio native protocol, carrying the one
2//! playback stream the editor's audio output needs.
3//!
4//! pipewire-pulse serves the protocol on `$XDG_RUNTIME_DIR/pulse/native`, or on
5//! the socket named by `$PULSE_SERVER`, and PulseAudio does the same. The
6//! client talks to it over std's `UnixStream`: no C library, no `-sys` crate,
7//! no `unsafe`. Samples go out inline as memblock packets, paced by the
8//! server's REQUEST credits, and a reader thread takes the replies and events.
9//!
10//! Only the calls the output uses are here: authenticate, name the client,
11//! create a stream, write, cork and uncork, flush, read the playback position
12//! (GET_PLAYBACK_LATENCY), count underflows, delete the stream. Volume is
13//! applied to the samples before they leave, not through the server: a
14//! server-side stream volume is saved by the session's restore state, and a mute
15//! here would come back in the system mixer tomorrow.
16
17#![forbid(unsafe_code)]
18
19pub mod wire;
20
21use std::collections::{HashMap, VecDeque};
22use std::ffi::OsStr;
23use std::io::{Read, Write};
24use std::os::unix::net::UnixStream;
25use std::path::{Path, PathBuf};
26use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
27use std::sync::{Arc, Mutex, MutexGuard, mpsc};
28use std::thread::JoinHandle;
29use std::time::Duration;
30
31use wire::{Reader, Tags, command};
32
33/// The client name the server shows for the stream.
34pub(crate) const APP_NAME: &str = "edith";
35/// Longest wait for one reply. A healthy server answers in well under a
36/// millisecond; this only fires when the server has stopped answering.
37const REPLY_TIMEOUT: Duration = Duration::from_secs(2);
38/// How far ahead of the device the server is asked to keep the stream.
39const LATENCY_MS: u64 = 100;
40/// The smallest request the server should make of us.
41const MINREQ_MS: u64 = 10;
42/// Most a stream holds that the server has not yet taken, in seconds of audio.
43/// Writes beyond it are refused, as a full ring refuses them.
44const QUEUE_SECONDS: usize = 1;
45/// Largest packet payload the reader accepts; anything bigger is a broken
46/// stream, not a reply.
47const MAX_PAYLOAD: usize = 16 << 20;
48/// Most a recording holds that nobody has read, in seconds of audio. Past it the
49/// oldest samples go.
50const MAX_CAPTURE_SECONDS: usize = 2;
51/// How much audio the server packs into one recording packet, in milliseconds.
52const RECORD_FRAGMENT_MS: u64 = 10;
53
54/// Where the server listens: `$PULSE_SERVER` when set (its `unix:` path, or a
55/// bare absolute path), else `$XDG_RUNTIME_DIR/pulse/native`. `None` when the
56/// server is somewhere this client cannot reach, such as TCP.
57pub fn server_path() -> Option<PathBuf> {
58 server_path_from(
59 crate::envcfg::var("PULSE_SERVER").as_deref(),
60 crate::envcfg::var_os("XDG_RUNTIME_DIR").as_deref(),
61 )
62}
63
64fn server_path_from(server: Option<&str>, runtime_dir: Option<&OsStr>) -> Option<PathBuf> {
65 match server {
66 Some(server) => {
67 let first = server
68 .split(|c: char| c.is_whitespace() || c == ';')
69 .find(|entry| !entry.is_empty())?;
70 match first.strip_prefix("unix:") {
71 Some(path) => Some(PathBuf::from(path)),
72 None if first.starts_with('/') => Some(PathBuf::from(first)),
73 None => None,
74 }
75 }
76 None => Some(Path::new(runtime_dir?).join("pulse/native")),
77 }
78}
79
80/// The authentication cookie: `$PULSE_COOKIE`, else `pulse/cookie` under the
81/// config home. Zeros when there is none, which pipewire-pulse accepts from a
82/// local client.
83fn cookie() -> Vec<u8> {
84 let path = crate::envcfg::var_os("PULSE_COOKIE").map(PathBuf::from).or_else(|| {
85 let config = crate::envcfg::var_os("XDG_CONFIG_HOME")
86 .map(PathBuf::from)
87 .or_else(|| crate::envcfg::var_os("HOME").map(|home| Path::new(&home).join(".config")))?;
88 Some(config.join("pulse/cookie"))
89 });
90 path.and_then(|path| std::fs::read(path).ok())
91 .filter(|bytes| !bytes.is_empty())
92 .unwrap_or_else(|| vec![0; 256])
93}
94
95type Reply = Result<Vec<u8>, u32>;
96
97/// What the reader thread and the caller both touch. The socket and the state
98/// have their own locks, and neither is held across a blocking socket write, so
99/// the reader can always take the state to record what the server said.
100struct Shared {
101 socket: Mutex<UnixStream>,
102 state: Mutex<State>,
103 /// Output gain as f32 bits, applied to the samples as they are sent.
104 gain: AtomicU32,
105 /// Set once the connection is gone or the server removed the stream.
106 dead: AtomicBool,
107}
108
109struct State {
110 /// The stream's channel, from the CREATE reply. It addresses the stream in
111 /// the memblock headers and in the commands that name it (cork, flush,
112 /// latency, delete), not the sink input the reply also carries.
113 channel: u32,
114 channels: usize,
115 rate: u32,
116 /// Bytes the server has asked for and we have not sent yet.
117 credits: u64,
118 /// Accepted samples not yet sent, interleaved, in whole frames.
119 pending: VecDeque<f32>,
120 capacity: usize,
121 /// Set by the first accepted write, cleared by flush and by `stream_ended`:
122 /// an underflow only counts once there is something to play
123 /// ([`crate::ao`] documents the same rule for the old plugin).
124 primed: bool,
125 /// Replies still expected, by tag.
126 waiters: HashMap<u32, mpsc::Sender<Reply>>,
127 next_tag: u32,
128 underruns: u64,
129 /// Device position at the most recent underrun, -1 until one happens.
130 last_underrun: i64,
131 /// Device position last read, the one an underrun is stamped with.
132 last_position: i64,
133 /// Whether the server has reported the stream playing; the clock says
134 /// nothing before that, as the plugin's did not.
135 started: bool,
136 /// Set by a recording: the samples the server pushes on the stream's
137 /// channel queue in `capture` until they are read.
138 capturing: bool,
139 capture: VecDeque<f32>,
140}
141
142/// Locks, recovering the guard if a thread panicked while holding it: the state
143/// is plain counters and queues, valid at any point.
144fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
145 mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
146}
147
148/// Writes the packets that the credits allow out of `pending`, scaled by the
149/// gain, and returns them ready for the socket. Empty when nothing can go.
150fn take_packets(state: &mut State, gain: f32) -> Vec<u8> {
151 let stride = 4 * state.channels;
152 let by_credit = (state.credits as usize / stride) * state.channels;
153 let count = by_credit.min(state.pending.len());
154 if count == 0 {
155 return Vec::new();
156 }
157 let mut data = Vec::with_capacity(count * 4);
158 for sample in state.pending.drain(..count) {
159 let value = if gain == 1.0 { sample } else { sample * gain };
160 data.extend_from_slice(&value.to_le_bytes());
161 }
162 state.credits -= data.len() as u64;
163 let mut packet = wire::header(data.len() as u32, state.channel, 0, 0).to_vec();
164 packet.extend_from_slice(&data);
165 packet
166}
167
168/// Sends bytes whole. A failed write means the connection is gone.
169fn send(shared: &Shared, bytes: &[u8]) -> bool {
170 if bytes.is_empty() {
171 return true;
172 }
173 if shared.dead.load(Ordering::Acquire) {
174 return false;
175 }
176 let sent = lock(&shared.socket).write_all(bytes).is_ok();
177 if !sent {
178 shared.dead.store(true, Ordering::Release);
179 }
180 sent
181}
182
183fn read_loop(mut socket: UnixStream, shared: Arc<Shared>) {
184 let mut header = [0u8; wire::HEADER_LEN];
185 loop {
186 if socket.read_exact(&mut header).is_err() {
187 break;
188 }
189 let (len, channel, _, _) = wire::parse_header(&header);
190 if len as usize > MAX_PAYLOAD {
191 break;
192 }
193 let mut payload = vec![0u8; len as usize];
194 if socket.read_exact(&mut payload).is_err() {
195 break;
196 }
197 if channel == wire::CONTROL_CHANNEL {
198 dispatch(&shared, &payload);
199 } else {
200 capture(&shared, channel, &payload);
201 }
202 }
203 shared.dead.store(true, Ordering::Release);
204 // Dropping the senders wakes every caller still waiting for a reply.
205 lock(&shared.state).waiters.clear();
206}
207
208/// Queues a recording's samples: the memblock packets the server pushes on the
209/// stream's channel. Playback streams never set `capturing`, so their packets
210/// (there are none) fall through.
211fn capture(shared: &Shared, channel: u32, payload: &[u8]) {
212 let mut state = lock(&shared.state);
213 if !state.capturing || channel != state.channel {
214 return;
215 }
216 let cap = state.rate as usize * state.channels * MAX_CAPTURE_SECONDS;
217 let (samples, _) = payload.as_chunks::<4>();
218 state.capture.extend(samples.iter().map(|b| f32::from_le_bytes(*b)));
219 let excess = state.capture.len().saturating_sub(cap);
220 state.capture.drain(..excess);
221}
222
223fn dispatch(shared: &Shared, payload: &[u8]) {
224 let mut reader = Reader::new(payload);
225 let (Some(cmd), Some(tag)) = (reader.u32(), reader.u32()) else {
226 return;
227 };
228 match cmd {
229 command::REPLY => {
230 if let Some(waiter) = lock(&shared.state).waiters.remove(&tag) {
231 let _ = waiter.send(Ok(reader.rest().to_vec()));
232 }
233 }
234 command::ERROR => {
235 let code = reader.u32().unwrap_or(0);
236 if let Some(waiter) = lock(&shared.state).waiters.remove(&tag) {
237 let _ = waiter.send(Err(code));
238 }
239 }
240 command::REQUEST => {
241 let (Some(channel), Some(len)) = (reader.u32(), reader.u32()) else {
242 return;
243 };
244 let packet = {
245 let mut state = lock(&shared.state);
246 if channel != state.channel {
247 return;
248 }
249 state.credits += u64::from(len);
250 take_packets(&mut state, f32::from_bits(shared.gain.load(Ordering::Relaxed)))
251 };
252 send(shared, &packet);
253 }
254 command::UNDERFLOW => {
255 let mut state = lock(&shared.state);
256 if state.primed {
257 state.underruns += 1;
258 state.last_underrun = state.last_position;
259 }
260 }
261 command::PLAYBACK_STREAM_KILLED | command::RECORD_STREAM_KILLED => shared.dead.store(true, Ordering::Release),
262 _ => {}
263 }
264}
265
266/// Opens the socket at `path` and starts the reader thread. The stream is not
267/// created yet: the caller greets the server and creates its stream.
268fn connect(path: &Path, rate: u32, channels: u32) -> Option<(Arc<Shared>, JoinHandle<()>)> {
269 if !(8_000..=768_000).contains(&rate) || !(1..=32).contains(&channels) {
270 return None;
271 }
272 let socket = UnixStream::connect(path).ok()?;
273 socket.set_write_timeout(Some(REPLY_TIMEOUT)).ok()?;
274 let reader = socket.try_clone().ok()?;
275 let shared = Arc::new(Shared {
276 socket: Mutex::new(socket),
277 state: Mutex::new(State {
278 channel: 0,
279 channels: channels as usize,
280 rate,
281 credits: 0,
282 pending: VecDeque::new(),
283 capacity: rate as usize * channels as usize * QUEUE_SECONDS,
284 primed: false,
285 waiters: HashMap::new(),
286 next_tag: 1,
287 underruns: 0,
288 last_underrun: -1,
289 last_position: -1,
290 started: false,
291 capturing: false,
292 capture: VecDeque::new(),
293 }),
294 gain: AtomicU32::new(1.0f32.to_bits()),
295 dead: AtomicBool::new(false),
296 });
297 let thread = {
298 let shared = shared.clone();
299 std::thread::spawn(move || read_loop(reader, shared))
300 };
301 Some((shared, thread))
302}
303
304/// Authenticates and names the client: what every stream starts with.
305fn greet(shared: &Shared) -> bool {
306 let Some(_) = call(shared, command::AUTH, Tags::new().u32(wire::PROTOCOL_VERSION).arbitrary(&cookie())) else {
307 eprintln!("pulse: the server refused the connection");
308 return false;
309 };
310 call(shared, command::SET_CLIENT_NAME, Tags::new().proplist(&[("application.name", APP_NAME)])).is_some()
311}
312
313/// Sends one command and waits for its reply. `None` on a refusal, a timeout,
314/// or a dead connection.
315fn call(shared: &Shared, cmd: u32, args: Tags) -> Option<Vec<u8>> {
316 let (tx, rx) = mpsc::channel();
317 let tag = {
318 let mut state = lock(&shared.state);
319 let tag = state.next_tag;
320 state.next_tag = state.next_tag.wrapping_add(1);
321 state.waiters.insert(tag, tx);
322 tag
323 };
324 if !send(shared, &wire::control(cmd, tag, args)) {
325 lock(&shared.state).waiters.remove(&tag);
326 return None;
327 }
328 match rx.recv_timeout(REPLY_TIMEOUT) {
329 Ok(Ok(payload)) => Some(payload),
330 Ok(Err(_)) | Err(_) => {
331 lock(&shared.state).waiters.remove(&tag);
332 None
333 }
334 }
335}
336
337/// An open playback stream. Dropping it deletes the stream on the server and
338/// closes the connection.
339pub struct Playback {
340 shared: Arc<Shared>,
341 reader: Option<JoinHandle<()>>,
342}
343
344impl Playback {
345 /// Connects to the server and creates an interleaved f32 stream at `rate`
346 /// with `channels` channels. Starts running. `None` when there is no server,
347 /// it refuses the client, or the format is not one it can carry.
348 pub fn open(rate: u32, channels: u32) -> Option<Self> {
349 Self::open_at(&server_path()?, rate, channels)
350 }
351
352 /// [`Playback::open`] against an explicit socket path.
353 pub fn open_at(path: &Path, rate: u32, channels: u32) -> Option<Self> {
354 let (shared, reader) = connect(path, rate, channels)?;
355 let mut playback = Self {
356 shared,
357 reader: Some(reader),
358 };
359 playback.handshake(rate, channels).then_some(playback)
360 }
361
362 fn handshake(&mut self, rate: u32, channels: u32) -> bool {
363 if !greet(&self.shared) {
364 return false;
365 }
366 let bytes_per_second = u64::from(rate) * u64::from(channels) * 4;
367 let tlength = (bytes_per_second * LATENCY_MS / 1000) as u32;
368 let minreq = (bytes_per_second * MINREQ_MS / 1000) as u32;
369 let args = wire::create_playback_stream_args(rate, channels as u8, tlength, minreq, wire::VOLUME_NORM);
370 let Some(reply) = self.request(command::CREATE_PLAYBACK_STREAM, args) else {
371 eprintln!("pulse: the server would not create a {rate} Hz, {channels}-channel stream");
372 return false;
373 };
374 // The reply opens with the memblock channel, the stream's index and the
375 // bytes the server wants straight away. The rest describes the buffer.
376 let mut reader = Reader::new(&reply);
377 let (Some(channel), Some(_sink_input), Some(requested)) = (reader.u32(), reader.u32(), reader.u32()) else {
378 return false;
379 };
380 let mut state = lock(&self.shared.state);
381 state.channel = channel;
382 state.credits = u64::from(requested);
383 true
384 }
385
386 /// Sends one command and waits for its reply. `None` on a refusal, a
387 /// timeout, or a dead connection.
388 fn request(&self, cmd: u32, args: Tags) -> Option<Vec<u8>> {
389 call(&self.shared, cmd, args)
390 }
391
392 /// Sends a command that the server answers and nobody waits for.
393 fn tell(&self, cmd: u32, args: Tags) -> bool {
394 send(&self.shared, &wire::control(cmd, 0, args))
395 }
396
397 fn channel(&self) -> u32 {
398 lock(&self.shared.state).channel
399 }
400
401 /// Queues interleaved samples and sends what the server has room for.
402 /// Returns how many were taken, in whole frames: a short count means the
403 /// queue is full and the caller should come back later. `None` once the
404 /// output has died.
405 pub fn write(&mut self, samples: &[f32]) -> Option<usize> {
406 if self.shared.dead.load(Ordering::Acquire) {
407 return None;
408 }
409 let gain = f32::from_bits(self.shared.gain.load(Ordering::Relaxed));
410 let (taken, packet) = {
411 let mut state = lock(&self.shared.state);
412 let frame = state.channels;
413 let room = state.capacity.saturating_sub(state.pending.len());
414 let taken = samples.len().min(room) / frame * frame;
415 state.pending.extend(&samples[..taken]);
416 if taken > 0 {
417 state.primed = true;
418 }
419 (taken, take_packets(&mut state, gain))
420 };
421 send(&self.shared, &packet).then_some(taken)
422 }
423
424 /// Samples per channel the device has actually played: what the server has
425 /// read out of the stream, less what its sink still holds. `None` until the
426 /// stream has started playing.
427 pub fn position(&self) -> Option<i64> {
428 let args = Tags::new().u32(self.channel()).timeval(0, 0);
429 let reply = self.request(command::GET_PLAYBACK_LATENCY, args)?;
430 let mut reader = Reader::new(&reply);
431 let sink_usec = reader.u64()?;
432 let _source_usec = reader.u64()?;
433 let playing = reader.bool()?;
434 reader.timeval()?;
435 reader.timeval()?;
436 let _write_index = reader.i64()?;
437 let read_index = reader.i64()?;
438 let mut state = lock(&self.shared.state);
439 state.started |= playing;
440 if !state.started || read_index < 0 {
441 return None;
442 }
443 let stride = 4 * state.channels as i64;
444 let frames = read_index / stride;
445 let sink_frames = (sink_usec as i64).saturating_mul(i64::from(state.rate)) / 1_000_000;
446 let played = (frames - sink_frames).max(0);
447 state.last_position = played;
448 Some(played)
449 }
450
451 /// Says the last sample of this stream has been queued: the silence after
452 /// it stops counting as a late decoder. The next accepted write counts again.
453 pub fn stream_ended(&self) {
454 lock(&self.shared.state).primed = false;
455 }
456
457 /// Pauses (`false`) or resumes (`true`) playback. While paused the position
458 /// stays put.
459 pub fn set_active(&self, active: bool) -> bool {
460 self.request(command::CORK_PLAYBACK_STREAM, Tags::new().u32(self.channel()).bool(!active))
461 .is_some()
462 }
463
464 /// Sets the output gain, 0.0 (silent) to 1.0 (as written). It applies to
465 /// the samples sent from now on, so the change lands within the server's
466 /// latency. `false` for a gain outside the range.
467 pub fn set_volume(&self, gain: f32) -> bool {
468 if !(0.0..=1.0).contains(&gain) {
469 return false;
470 }
471 self.shared.gain.store(gain.to_bits(), Ordering::Relaxed);
472 true
473 }
474
475 /// The gain in force.
476 pub fn gain(&self) -> f32 {
477 f32::from_bits(self.shared.gain.load(Ordering::Relaxed))
478 }
479
480 /// Drops everything queued, here and on the server, so the next samples
481 /// written play right away. The played position keeps counting.
482 pub fn flush(&self) -> bool {
483 {
484 let mut state = lock(&self.shared.state);
485 state.pending.clear();
486 state.primed = false;
487 }
488 self.request(command::FLUSH_PLAYBACK_STREAM, Tags::new().u32(self.channel())).is_some()
489 }
490
491 /// Underflows so far, and the device position the newest was seen at.
492 pub fn underruns(&self) -> (u64, Option<i64>) {
493 let state = lock(&self.shared.state);
494 (state.underruns, (state.last_underrun >= 0).then_some(state.last_underrun))
495 }
496}
497
498impl Drop for Playback {
499 fn drop(&mut self) {
500 if !self.shared.dead.load(Ordering::Acquire) {
501 self.tell(command::DELETE_PLAYBACK_STREAM, Tags::new().u32(self.channel()));
502 }
503 let underruns = lock(&self.shared.state).underruns;
504 if underruns > 0 {
505 eprintln!("pulse: {underruns} underruns");
506 }
507 let _ = lock(&self.shared.socket).shutdown(std::net::Shutdown::Both);
508 if let Some(reader) = self.reader.take() {
509 let _ = reader.join();
510 }
511 }
512}
513
514/// An open recording stream: the server's input pushed in as interleaved f32
515/// samples. Dropping it deletes the stream on the server.
516pub struct Recording {
517 shared: Arc<Shared>,
518 reader: Option<JoinHandle<()>>,
519}
520
521impl Recording {
522 /// Connects and starts recording `channels` channels at `rate`, from the
523 /// source named, or the server's default. `None` when there is no server,
524 /// it refuses the client, or it cannot record that format from that source.
525 pub fn open(rate: u32, channels: u32, source: Option<&str>) -> Option<Self> {
526 Self::open_at(&server_path()?, rate, channels, source)
527 }
528
529 /// [`Recording::open`] against an explicit socket path.
530 pub fn open_at(path: &Path, rate: u32, channels: u32, source: Option<&str>) -> Option<Self> {
531 let (shared, reader) = connect(path, rate, channels)?;
532 let mut recording = Self {
533 shared,
534 reader: Some(reader),
535 };
536 recording.handshake(rate, channels, source).then_some(recording)
537 }
538
539 fn handshake(&mut self, rate: u32, channels: u32, source: Option<&str>) -> bool {
540 if !greet(&self.shared) {
541 return false;
542 }
543 let fragsize = (u64::from(rate) * u64::from(channels) * 4 * RECORD_FRAGMENT_MS / 1000) as u32;
544 let args = wire::create_record_stream_args(rate, channels as u8, source, fragsize);
545 let Some(reply) = call(&self.shared, command::CREATE_RECORD_STREAM, args) else {
546 eprintln!("pulse: the server would not record {rate} Hz, {channels} channels");
547 return false;
548 };
549 // The reply opens with the memblock channel the samples arrive on.
550 let Some(channel) = Reader::new(&reply).u32() else {
551 return false;
552 };
553 let mut state = lock(&self.shared.state);
554 state.channel = channel;
555 state.capturing = true;
556 true
557 }
558
559 /// Takes the samples captured since the last call: interleaved f32, in
560 /// whole frames.
561 pub fn read(&self) -> Vec<f32> {
562 lock(&self.shared.state).capture.drain(..).collect()
563 }
564
565 /// `false` once the connection or the stream is gone.
566 pub fn alive(&self) -> bool {
567 !self.shared.dead.load(Ordering::Acquire)
568 }
569
570 /// Starts (`true`) or stops (`false`) the stream. Stopping before the
571 /// delete keeps the server from sending more samples.
572 pub fn set_active(&self, active: bool) -> bool {
573 let channel = lock(&self.shared.state).channel;
574 call(&self.shared, command::CORK_RECORD_STREAM, Tags::new().u32(channel).bool(!active)).is_some()
575 }
576}
577
578impl Drop for Recording {
579 fn drop(&mut self) {
580 if !self.shared.dead.load(Ordering::Acquire) {
581 let channel = lock(&self.shared.state).channel;
582 send(&self.shared, &wire::control(command::DELETE_RECORD_STREAM, 0, Tags::new().u32(channel)));
583 }
584 let _ = lock(&self.shared.socket).shutdown(std::net::Shutdown::Both);
585 if let Some(reader) = self.reader.take() {
586 let _ = reader.join();
587 }
588 }
589}
590
591/// A capture source, as the server lists it.
592#[derive(Clone, Debug, PartialEq)]
593pub struct Source {
594 /// The name to open it by, such as `edtest.monitor`.
595 pub name: String,
596 pub description: String,
597 /// Whether it is a monitor: the output of a sink, not a microphone.
598 pub monitor: bool,
599}
600
601/// The server's sources, monitors included, in its order. `None` when there is
602/// no server or it does not answer.
603pub fn list_sources() -> Option<Vec<Source>> {
604 list_sources_at(&server_path()?)
605}
606
607/// [`list_sources`] against an explicit socket path.
608pub fn list_sources_at(path: &Path) -> Option<Vec<Source>> {
609 let (shared, reader) = connect(path, 48_000, 2)?;
610 let sources = greet(&shared)
611 .then(|| call(&shared, command::GET_SOURCE_INFO_LIST, Tags::new()))
612 .flatten()
613 .and_then(|reply| parse_sources(&reply));
614 let _ = lock(&shared.socket).shutdown(std::net::Shutdown::Both);
615 let _ = reader.join();
616 sources
617}
618
619/// Reads the source list reply, the fields of `source_fill_tagstruct` at
620/// protocol version 35 (`pulsecore/protocol-native.c`).
621fn parse_sources(reply: &[u8]) -> Option<Vec<Source>> {
622 let mut r = Reader::new(reply);
623 let mut sources = Vec::new();
624 while !r.rest().is_empty() {
625 r.u32()?; // index
626 let name = r.string_or_null()?.unwrap_or_default();
627 let description = r.string_or_null()?.unwrap_or_default();
628 r.sample_spec()?;
629 r.channel_map()?;
630 r.u32()?; // module
631 r.cvolume()?;
632 r.bool()?; // muted
633 let monitor_of = r.u32()?;
634 r.string_or_null()?; // the sink it monitors
635 r.u64()?; // latency
636 r.string_or_null()?; // driver
637 r.u32()?; // flags
638 r.skip_proplist()?;
639 r.u64()?; // requested latency
640 r.volume()?; // base volume
641 r.u32()?; // state
642 r.u32()?; // volume steps
643 r.u32()?; // card
644 for _ in 0..r.u32()? {
645 r.string_or_null()?; // port name
646 r.string_or_null()?; // port description
647 r.u32()?; // priority
648 r.u32()?; // available
649 r.string_or_null()?; // availability group
650 r.u32()?; // port type
651 }
652 r.string_or_null()?; // active port
653 for _ in 0..r.u8()? {
654 r.format_info()?;
655 }
656 sources.push(Source {
657 name,
658 description,
659 monitor: monitor_of != wire::DEFAULT,
660 });
661 }
662 Some(sources)
663}
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668 use std::os::unix::net::UnixListener;
669 use std::time::Instant;
670
671 /// One packet the client sent, split into its parts.
672 struct Sent {
673 channel: u32,
674 /// For control packets: the command, its tag, and the arguments after.
675 command: u32,
676 tag: u32,
677 args: Vec<u8>,
678 /// For memblock packets: the samples' bytes.
679 data: Vec<u8>,
680 }
681
682 /// The server's end of the socket, driven by the test: every packet the
683 /// client sends arrives on `rx`, and the test answers by hand.
684 struct Mock {
685 /// The server's end, taken from `accepted` on first use: the client
686 /// connects after `bind` returns.
687 socket: Option<UnixStream>,
688 accepted: mpsc::Receiver<UnixStream>,
689 rx: mpsc::Receiver<Sent>,
690 dir: PathBuf,
691 }
692
693 impl Mock {
694 fn bind(name: &str) -> (Self, PathBuf) {
695 let dir = std::env::temp_dir().join(format!("edith-pulse-{}-{name}", std::process::id()));
696 let _ = std::fs::remove_dir_all(&dir);
697 std::fs::create_dir_all(&dir).unwrap();
698 let path = dir.join("native");
699 let listener = UnixListener::bind(&path).unwrap();
700 let (tx, rx) = mpsc::channel();
701 let (accepted_tx, accepted_rx) = mpsc::channel();
702 std::thread::spawn(move || {
703 let (socket, _) = listener.accept().unwrap();
704 let reader = socket.try_clone().unwrap();
705 accepted_tx.send(socket).unwrap();
706 let mut reader = reader;
707 let mut header = [0u8; wire::HEADER_LEN];
708 while reader.read_exact(&mut header).is_ok() {
709 let (len, channel, _, _) = wire::parse_header(&header);
710 let mut payload = vec![0u8; len as usize];
711 if reader.read_exact(&mut payload).is_err() {
712 break;
713 }
714 let sent = if channel == wire::CONTROL_CHANNEL {
715 let mut r = Reader::new(&payload);
716 let command = r.u32().unwrap();
717 let tag = r.u32().unwrap();
718 Sent { channel, command, tag, args: r.rest().to_vec(), data: Vec::new() }
719 } else {
720 Sent { channel, command: u32::MAX, tag: 0, args: Vec::new(), data: payload }
721 };
722 if tx.send(sent).is_err() {
723 break;
724 }
725 }
726 });
727 (
728 Self {
729 socket: None,
730 accepted: accepted_rx,
731 rx,
732 dir: dir.clone(),
733 },
734 path,
735 )
736 }
737
738 fn expect(&self, command: u32) -> Sent {
739 let deadline = Instant::now() + Duration::from_secs(3);
740 loop {
741 let left = deadline.saturating_duration_since(Instant::now());
742 let sent = self.rx.recv_timeout(left).expect("the client sent nothing in time");
743 if sent.command == command {
744 return sent;
745 }
746 }
747 }
748
749 /// Whatever memblock data arrives within `wait`, concatenated.
750 fn memblock_within(&self, wait: Duration) -> Vec<u8> {
751 let deadline = Instant::now() + wait;
752 let mut data = Vec::new();
753 loop {
754 let left = deadline.saturating_duration_since(Instant::now());
755 match self.rx.recv_timeout(left) {
756 Ok(sent) if sent.channel != wire::CONTROL_CHANNEL => data.extend(sent.data),
757 Ok(_) => {}
758 Err(_) => return data,
759 }
760 }
761 }
762
763 fn send(&mut self, packet: &[u8]) {
764 if self.socket.is_none() {
765 self.socket = Some(self.accepted.recv().unwrap());
766 }
767 self.socket.as_mut().unwrap().write_all(packet).unwrap();
768 }
769
770 /// The server goes away: the client sees the end of the socket.
771 fn close(&mut self) {
772 if let Some(socket) = &self.socket {
773 let _ = socket.shutdown(std::net::Shutdown::Both);
774 }
775 }
776
777 fn reply(&mut self, tag: u32, args: Tags) {
778 let packet = wire::control(command::REPLY, tag, args);
779 self.send(&packet);
780 }
781
782 fn request_bytes(&mut self, channel: u32, len: u32) {
783 let packet = wire::control(command::REQUEST, u32::MAX, Tags::new().u32(channel).u32(len));
784 self.send(&packet);
785 }
786
787 fn underflow(&mut self, channel: u32) {
788 let packet = wire::control(command::UNDERFLOW, u32::MAX, Tags::new().u32(channel).i64(0));
789 self.send(&packet);
790 }
791
792 /// Answers the three handshake commands; the stream starts with
793 /// `requested` bytes of credit.
794 fn handshake(&mut self, requested: u32) -> Sent {
795 let auth = self.expect(command::AUTH);
796 let mut r = Reader::new(&auth.args);
797 assert_eq!(r.u32(), Some(wire::PROTOCOL_VERSION));
798 assert_eq!(r.arbitrary().map(<[u8]>::len), Some(256), "the cookie is sent");
799 self.reply(auth.tag, Tags::new().u32(wire::PROTOCOL_VERSION));
800 let name = self.expect(command::SET_CLIENT_NAME);
801 self.reply(name.tag, Tags::new().u32(1));
802 let create = self.expect(command::CREATE_PLAYBACK_STREAM);
803 self.reply(
804 create.tag,
805 Tags::new()
806 .u32(0)
807 .u32(7)
808 .u32(requested)
809 .u32(wire::DEFAULT)
810 .u32(38_400)
811 .u32(38_400)
812 .u32(1_920),
813 );
814 create
815 }
816 }
817
818 impl Drop for Mock {
819 fn drop(&mut self) {
820 self.close();
821 let _ = std::fs::remove_dir_all(&self.dir);
822 }
823 }
824
825 /// Runs a call that waits for one reply, answers that reply with an empty
826 /// success, and gives back the call's result, the playback, and the command's
827 /// arguments. The call runs on its own thread, since it blocks until answered.
828 fn answered<T: Send + 'static>(
829 mock: &mut Mock,
830 playback: Playback,
831 cmd: u32,
832 call: impl FnOnce(&Playback) -> T + Send + 'static,
833 ) -> (T, Playback, Vec<u8>) {
834 let asking = std::thread::spawn(move || {
835 let out = call(&playback);
836 (out, playback)
837 });
838 let sent = mock.expect(cmd);
839 mock.reply(sent.tag, Tags::new());
840 let (out, playback) = asking.join().unwrap();
841 (out, playback, sent.args)
842 }
843
844 fn open(path: PathBuf) -> JoinHandle<Option<Playback>> {
845 std::thread::spawn(move || Playback::open_at(&path, 48_000, 2))
846 }
847
848 fn stereo_samples(frames: usize, value: f32) -> Vec<f32> {
849 vec![value; frames * 2]
850 }
851
852 fn as_f32s(bytes: &[u8]) -> Vec<f32> {
853 bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()
854 }
855
856 #[test]
857 fn handshake_stream_credits_and_clock() {
858 let (mut mock, path) = Mock::bind("handshake");
859 let handle = open(path);
860 let create = mock.handshake(4_096);
861 let mut playback = handle.join().unwrap().expect("the handshake completes");
862 // The create arguments open with the sample spec, and the stream starts running.
863 assert_eq!(&create.args[..7], &[b'a', 5, 2, 0, 0, 0xbb, 0x80]);
864 assert_eq!(create.args[22], b'0');
865 assert_eq!(playback.channel(), 0);
866
867 // 4096 bytes of credit releases 1024 samples; the rest waits for a REQUEST.
868 let samples: Vec<f32> = (0..4096).map(|i| i as f32).collect();
869 assert_eq!(playback.write(&samples), Some(4096));
870 let first = mock.memblock_within(Duration::from_millis(200));
871 assert_eq!(as_f32s(&first), samples[..1024].to_vec());
872 mock.request_bytes(0, 100_000);
873 let rest = mock.memblock_within(Duration::from_millis(200));
874 assert_eq!(as_f32s(&rest), samples[1024..].to_vec());
875
876 // The clock: nothing until the server reports playing, then the read
877 // index less the sink's latency.
878 let (position, playback) = ask_position(playback, &mut mock, 20_000, false, 0);
879 assert_eq!(position, None);
880 let (position, playback) = ask_position(playback, &mut mock, 20_000, true, 48_000 * 8);
881 assert_eq!(position, Some(48_000 - 960));
882
883 // A lost server stops the writes.
884 mock.close();
885 std::thread::sleep(Duration::from_millis(100));
886 let mut playback = playback;
887 assert_eq!(playback.write(&stereo_samples(4, 0.0)), None);
888 }
889
890 #[test]
891 fn pause_volume_flush_underflow_and_close() {
892 let (mut mock, path) = Mock::bind("controls");
893 let handle = open(path);
894 mock.handshake(1 << 20);
895 let playback = handle.join().unwrap().unwrap();
896
897 // A dry stream before anything was written is the head of the start.
898 mock.underflow(0);
899 std::thread::sleep(Duration::from_millis(50));
900 assert_eq!(playback.underruns(), (0, None));
901
902 let (ok, playback, args) = answered(&mut mock, playback, command::CORK_PLAYBACK_STREAM, |p| p.set_active(true));
903 assert!(ok);
904 assert_eq!(args, Tags::new().u32(0).bool(false).into_bytes());
905 let (ok, mut playback, args) = answered(&mut mock, playback, command::CORK_PLAYBACK_STREAM, |p| p.set_active(false));
906 assert!(ok);
907 assert_eq!(args, Tags::new().u32(0).bool(true).into_bytes());
908
909 // Gain scales what is sent; out of range is refused.
910 assert!(playback.set_volume(0.5));
911 assert!(!playback.set_volume(1.5));
912 assert_eq!(playback.write(&stereo_samples(2, 1.0)), Some(4));
913 assert_eq!(as_f32s(&mock.memblock_within(Duration::from_millis(100))), vec![0.5; 4]);
914
915 // Fed, a dry stream is late and counted.
916 mock.underflow(0);
917 std::thread::sleep(Duration::from_millis(50));
918 assert_eq!(playback.underruns().0, 1);
919
920 // A flush drops what is queued, here and on the server.
921 let (ok, playback, _) = answered(&mut mock, playback, command::FLUSH_PLAYBACK_STREAM, |p| p.flush());
922 assert!(ok);
923 mock.request_bytes(0, 100_000);
924 assert!(mock.memblock_within(Duration::from_millis(100)).is_empty());
925
926 // Dropping the stream deletes it on the server.
927 drop(playback);
928 let delete = mock.expect(command::DELETE_PLAYBACK_STREAM);
929 assert_eq!(delete.args, Tags::new().u32(0).into_bytes());
930 }
931
932 #[test]
933 fn no_server_means_no_stream_and_the_path_follows_the_environment() {
934 let runtime = OsStr::new("/run/user/1000");
935 assert_eq!(
936 server_path_from(None, Some(runtime)),
937 Some(PathBuf::from("/run/user/1000/pulse/native"))
938 );
939 assert_eq!(
940 server_path_from(Some("unix:/tmp/x/native"), Some(runtime)),
941 Some(PathBuf::from("/tmp/x/native"))
942 );
943 assert_eq!(server_path_from(Some("tcp:127.0.0.1:4713"), Some(runtime)), None);
944 let path = std::env::temp_dir().join(format!("edith-pulse-absent-{}", std::process::id()));
945 assert!(Playback::open_at(&path, 48_000, 2).is_none());
946 }
947
948 /// Asks the playback for its position on another thread while the test
949 /// answers the GET_PLAYBACK_LATENCY it sends.
950 fn ask_position(
951 playback: Playback,
952 mock: &mut Mock,
953 sink_usec: u64,
954 playing: bool,
955 read_index: i64,
956 ) -> (Option<i64>, Playback) {
957 let asking = std::thread::spawn(move || {
958 let position = playback.position();
959 (position, playback)
960 });
961 let latency = mock.expect(command::GET_PLAYBACK_LATENCY);
962 mock.reply(latency.tag, latency_reply(sink_usec, playing, read_index));
963 asking.join().unwrap()
964 }
965
966 /// The GET_PLAYBACK_LATENCY reply: sink and source latency, playing, the two
967 /// timevals, the write and read indexes, then the two underrun counters.
968 fn latency_reply(sink_usec: u64, playing: bool, read_index: i64) -> Tags {
969 Tags::new()
970 .usec(sink_usec)
971 .usec(0)
972 .bool(playing)
973 .timeval(0, 0)
974 .timeval(0, 0)
975 .i64(read_index)
976 .i64(read_index)
977 .u64(0)
978 .u64(0)
979 }
980
981}