1use std::cmp::{max, min};
2use std::convert::{TryFrom, TryInto};
3use std::io;
4use std::os::fd::BorrowedFd;
5use std::os::fd::{IntoRawFd as _, RawFd};
6use std::sync::{Arc, Mutex, Weak};
7use std::thread;
8
9use libc::c_void;
10use libpulse_binding::callbacks::ListResult;
11use libpulse_binding::context::{
12 Context, FlagSet, State as PulseState, introspect::ServerInfo, introspect::SinkInfo,
13 introspect::SourceInfo, subscribe::Facility, subscribe::InterestMaskSet,
14};
15use libpulse_binding::mainloop::api::MainloopApi;
16use libpulse_binding::mainloop::standard::{IterateResult, Mainloop};
17use libpulse_binding::proplist::{Proplist, properties};
18use libpulse_binding::volume::{ChannelVolumes, Volume};
19use tokio::sync::Notify;
20
21use super::super::prelude::*;
22use super::{DeviceKind, SoundDevice};
23
24static CLIENT: LazyLock<Result<Client>> = LazyLock::new(Client::new);
25static EVENT_LISTENER: Mutex<Vec<Weak<Notify>>> = Mutex::new(Vec::new());
26static DEVICES: LazyLock<Mutex<HashMap<(DeviceKind, String), VolInfo>>> = LazyLock::new(default);
27
28pub(super) static DEFAULT_SOURCE: Mutex<Cow<'static, str>> =
30 Mutex::new(Cow::Borrowed("@DEFAULT_SOURCE@"));
31pub(super) static DEFAULT_SINK: Mutex<Cow<'static, str>> =
32 Mutex::new(Cow::Borrowed("@DEFAULT_SINK@"));
33
34impl DeviceKind {
35 pub fn default_name(self) -> Cow<'static, str> {
36 match self {
37 Self::Sink => DEFAULT_SINK.lock().unwrap().clone(),
38 Self::Source => DEFAULT_SOURCE.lock().unwrap().clone(),
39 }
40 }
41}
42
43pub(super) struct Device {
44 name: Option<String>,
45 description: Option<String>,
46 active_port: Option<String>,
47 form_factor: Option<String>,
48 device_kind: DeviceKind,
49 volume: Option<ChannelVolumes>,
50 volume_avg: u32,
51 muted: bool,
52 notify: Arc<Notify>,
53}
54
55struct Connection {
56 mainloop: Mainloop,
57 context: Context,
58}
59
60struct Client {
61 send_req: std::sync::mpsc::Sender<ClientRequest>,
62 ml_waker: MainloopWaker,
63}
64
65#[derive(Debug)]
66struct VolInfo {
67 volume: ChannelVolumes,
68 mute: bool,
69 name: String,
70 description: Option<String>,
71 active_port: Option<String>,
72 form_factor: Option<String>,
73}
74
75impl TryFrom<&SourceInfo<'_>> for VolInfo {
76 type Error = ();
77
78 fn try_from(source_info: &SourceInfo) -> std::result::Result<Self, Self::Error> {
79 match source_info.name.as_ref() {
80 None => Err(()),
81 Some(name) => Ok(VolInfo {
82 volume: source_info.volume,
83 mute: source_info.mute,
84 name: name.to_string(),
85 description: source_info.description.as_ref().map(|d| d.to_string()),
86 active_port: source_info
87 .active_port
88 .as_ref()
89 .and_then(|a| a.name.as_ref().map(|n| n.to_string())),
90 form_factor: source_info.proplist.get_str(properties::DEVICE_FORM_FACTOR),
91 }),
92 }
93 }
94}
95
96impl TryFrom<&SinkInfo<'_>> for VolInfo {
97 type Error = ();
98
99 fn try_from(sink_info: &SinkInfo) -> std::result::Result<Self, Self::Error> {
100 match sink_info.name.as_ref() {
101 None => Err(()),
102 Some(name) => Ok(VolInfo {
103 volume: sink_info.volume,
104 mute: sink_info.mute,
105 name: name.to_string(),
106 description: sink_info.description.as_ref().map(|d| d.to_string()),
107 active_port: sink_info
108 .active_port
109 .as_ref()
110 .and_then(|a| a.name.as_ref().map(|n| n.to_string())),
111 form_factor: sink_info.proplist.get_str(properties::DEVICE_FORM_FACTOR),
112 }),
113 }
114 }
115}
116
117#[derive(Debug)]
118enum ClientRequest {
119 GetDefaultDevice,
120 GetInfoByName(DeviceKind, String),
121 SetVolumeByName(DeviceKind, String, ChannelVolumes),
122 SetMuteByName(DeviceKind, String, bool),
123}
124
125impl Connection {
126 fn new() -> Result<Self> {
127 let mut proplist = Proplist::new().unwrap();
128 proplist
129 .set_str(properties::APPLICATION_NAME, env!("CARGO_PKG_NAME"))
130 .map_err(|_| Error::new("Could not set pulseaudio APPLICATION_NAME property"))?;
131
132 let mainloop = Mainloop::new().error("Failed to create pulseaudio mainloop")?;
133
134 let mut context = Context::new_with_proplist(
135 &mainloop,
136 concat!(env!("CARGO_PKG_NAME"), "_context"),
137 &proplist,
138 )
139 .error("Failed to create new pulseaudio context")?;
140
141 context
142 .connect(None, FlagSet::NOFLAGS, None)
143 .error("Failed to connect to pulseaudio context")?;
144
145 let mut connection = Connection { mainloop, context };
146
147 loop {
149 connection.iterate(false)?;
150 match connection.context.get_state() {
151 PulseState::Ready => {
152 break;
153 }
154 PulseState::Failed | PulseState::Terminated => {
155 return Err(Error::new("pulseaudio context state failed/terminated"));
156 }
157 _ => {}
158 }
159 }
160
161 Ok(connection)
162 }
163
164 fn iterate(&mut self, blocking: bool) -> Result<()> {
165 match self.mainloop.iterate(blocking) {
166 IterateResult::Quit(_) | IterateResult::Err(_) => {
167 Err(Error::new("failed to iterate pulseaudio state"))
168 }
169 IterateResult::Success(_) => Ok(()),
170 }
171 }
172
173 fn spawn(thread_name: &str, f: impl Fn(Self) -> bool + Send + 'static) -> Result<()> {
177 let (tx, rx) = std::sync::mpsc::sync_channel(0);
178 thread::Builder::new()
179 .name(thread_name.to_owned())
180 .spawn(move || match Self::new() {
181 Ok(mut conn) => {
182 tx.send(Ok(())).unwrap();
183 while f(conn) {
184 let mut try_i = 0usize;
185 loop {
186 try_i += 1;
187 let delay =
188 Duration::from_millis(if try_i <= 10 { 100 } else { 5_000 });
189 eprintln!("reconnecting to pulseaudio in {delay:?}... (try {try_i})");
190 thread::sleep(delay);
191 if let Ok(c) = Self::new() {
192 eprintln!("reconnected to pulseaudio");
193 conn = c;
194 break;
195 }
196 }
197 }
198 }
199 Err(err) => {
200 tx.send(Err(err)).unwrap();
201 }
202 })
203 .error("failed to spawn a thread")?;
204 rx.recv().error("channel closed")?
205 }
206}
207
208impl Client {
209 fn new() -> Result<Client> {
210 let (send_req, recv_req) = std::sync::mpsc::channel();
211 let ml_waker = MainloopWaker::new().unwrap();
212
213 Connection::spawn("sound_pulseaudio", move |mut connection| {
214 ml_waker.attach(connection.mainloop.get_api());
215
216 let introspector = connection.context.introspect();
217 connection
218 .context
219 .set_subscribe_callback(Some(Box::new(move |facility, _, index| match facility {
220 Some(Facility::Server) => {
221 introspector.get_server_info(Client::server_info_callback);
222 }
223 Some(Facility::Sink) => {
224 introspector.get_sink_info_by_index(index, Client::sink_info_callback);
225 }
226 Some(Facility::Source) => {
227 introspector.get_source_info_by_index(index, Client::source_info_callback);
228 }
229 _ => (),
230 })));
231
232 connection.context.subscribe(
233 InterestMaskSet::SERVER | InterestMaskSet::SINK | InterestMaskSet::SOURCE,
234 |_| (),
235 );
236
237 let mut introspector = connection.context.introspect();
238
239 loop {
240 loop {
241 connection.iterate(true).unwrap();
242 match connection.context.get_state() {
243 PulseState::Ready => break,
244 PulseState::Failed => return true,
245 _ => (),
246 }
247 }
248
249 loop {
250 use std::sync::mpsc::TryRecvError;
251 let req = match recv_req.try_recv() {
252 Ok(x) => x,
253 Err(TryRecvError::Empty) => break,
254 Err(TryRecvError::Disconnected) => return false,
255 };
256
257 use ClientRequest::*;
258 match req {
259 GetDefaultDevice => {
260 introspector.get_server_info(Client::server_info_callback);
261 }
262 GetInfoByName(DeviceKind::Sink, name) => {
263 introspector.get_sink_info_by_name(&name, Client::sink_info_callback);
264 }
265 GetInfoByName(DeviceKind::Source, name) => {
266 introspector
267 .get_source_info_by_name(&name, Client::source_info_callback);
268 }
269 SetVolumeByName(DeviceKind::Sink, name, volumes) => {
270 introspector.set_sink_volume_by_name(&name, &volumes, None);
271 }
272 SetVolumeByName(DeviceKind::Source, name, volumes) => {
273 introspector.set_source_volume_by_name(&name, &volumes, None);
274 }
275 SetMuteByName(DeviceKind::Sink, name, mute) => {
276 introspector.set_sink_mute_by_name(&name, mute, None);
277 }
278 SetMuteByName(DeviceKind::Source, name, mute) => {
279 introspector.set_source_mute_by_name(&name, mute, None);
280 }
281 };
282 }
283 }
284 })?;
285
286 Ok(Client { send_req, ml_waker })
287 }
288
289 fn send(request: ClientRequest) -> Result<()> {
290 match CLIENT.as_ref() {
291 Ok(client) => {
292 client.send_req.send(request).unwrap();
293 client.ml_waker.wake().unwrap();
294 Ok(())
295 }
296 Err(err) => Err(Error::new(format!(
297 "pulseaudio connection failed with error: {err}",
298 ))),
299 }
300 }
301
302 fn server_info_callback(server_info: &ServerInfo) {
303 if let Some(default_sink) = server_info.default_sink_name.as_ref() {
304 *DEFAULT_SINK.lock().unwrap() = default_sink.to_string().into();
305 }
306
307 if let Some(default_source) = server_info.default_source_name.as_ref() {
308 *DEFAULT_SOURCE.lock().unwrap() = default_source.to_string().into();
309 }
310
311 Client::send_update_event();
312 }
313
314 fn get_info_callback<I: TryInto<VolInfo>>(result: ListResult<I>) -> Option<VolInfo> {
315 match result {
316 ListResult::End | ListResult::Error => None,
317 ListResult::Item(info) => info.try_into().ok(),
318 }
319 }
320
321 fn sink_info_callback(result: ListResult<&SinkInfo>) {
322 if let Some(vol_info) = Self::get_info_callback(result) {
323 DEVICES
324 .lock()
325 .unwrap()
326 .insert((DeviceKind::Sink, vol_info.name.to_string()), vol_info);
327
328 Client::send_update_event();
329 }
330 }
331
332 fn source_info_callback(result: ListResult<&SourceInfo>) {
333 if let Some(vol_info) = Self::get_info_callback(result) {
334 DEVICES
335 .lock()
336 .unwrap()
337 .insert((DeviceKind::Source, vol_info.name.to_string()), vol_info);
338
339 Client::send_update_event();
340 }
341 }
342
343 fn send_update_event() {
344 EVENT_LISTENER
345 .lock()
346 .unwrap()
347 .retain(|notify| notify.upgrade().inspect(|x| x.notify_one()).is_some());
348 }
349}
350
351impl Device {
352 pub(super) fn new(device_kind: DeviceKind, name: Option<String>) -> Result<Self> {
353 let notify = Arc::new(Notify::new());
354 EVENT_LISTENER.lock().unwrap().push(Arc::downgrade(¬ify));
355
356 Client::send(ClientRequest::GetDefaultDevice)?;
357
358 let device = Device {
359 name,
360 description: None,
361 active_port: None,
362 form_factor: None,
363 device_kind,
364 volume: None,
365 volume_avg: 0,
366 muted: false,
367 notify,
368 };
369
370 Client::send(ClientRequest::GetInfoByName(device_kind, device.name()))?;
371
372 Ok(device)
373 }
374
375 fn name(&self) -> String {
376 self.name
377 .clone()
378 .unwrap_or_else(|| self.device_kind.default_name().into())
379 }
380
381 fn volume(&mut self, volume: ChannelVolumes) {
382 self.volume = Some(volume);
383 self.volume_avg = (volume.avg().0 as f32 / Volume::NORMAL.0 as f32 * 100.0).round() as u32;
384 }
385}
386
387#[async_trait::async_trait]
388impl SoundDevice for Device {
389 fn volume(&self) -> u32 {
390 self.volume_avg
391 }
392
393 fn muted(&self) -> bool {
394 self.muted
395 }
396
397 fn output_name(&self) -> String {
398 self.name()
399 }
400
401 fn output_description(&self) -> Option<String> {
402 self.description.clone()
403 }
404
405 fn active_port(&self) -> Option<String> {
406 self.active_port.clone()
407 }
408
409 fn form_factor(&self) -> Option<&str> {
410 self.form_factor.as_deref()
411 }
412
413 async fn get_info(&mut self) -> Result<()> {
414 let devices = DEVICES.lock().unwrap();
415
416 if let Some(info) = devices.get(&(self.device_kind, self.name())) {
417 self.volume(info.volume);
418 self.muted = info.mute;
419 self.description.clone_from(&info.description);
420 self.active_port.clone_from(&info.active_port);
421 self.form_factor.clone_from(&info.form_factor);
422 }
423
424 Ok(())
425 }
426
427 async fn set_volume(&mut self, step: i32, max_vol: Option<u32>) -> Result<()> {
428 let mut volume = self.volume.error("Volume unknown")?;
429
430 let step = (step as f32 * Volume::NORMAL.0 as f32 / 100.0).round() as i32;
432 for vol in volume.get_mut().iter_mut() {
433 let uncapped_vol = max(0, vol.0 as i32 + step) as u32;
434 let capped_vol = if let Some(vol_cap) = max_vol {
435 min(
436 uncapped_vol,
437 (vol_cap as f32 * Volume::NORMAL.0 as f32 / 100.0).round() as u32,
438 )
439 } else {
440 uncapped_vol
441 };
442 vol.0 = min(capped_vol, Volume::MAX.0);
443 }
444
445 self.volume(volume);
447 Client::send(ClientRequest::SetVolumeByName(
448 self.device_kind,
449 self.name(),
450 volume,
451 ))?;
452
453 Ok(())
454 }
455
456 async fn toggle(&mut self) -> Result<()> {
457 self.muted = !self.muted;
458
459 Client::send(ClientRequest::SetMuteByName(
460 self.device_kind,
461 self.name(),
462 self.muted,
463 ))?;
464
465 Ok(())
466 }
467
468 async fn wait_for_update(&mut self) -> Result<()> {
469 self.notify.notified().await;
470 Ok(())
471 }
472}
473
474#[derive(Debug, Clone, Copy)]
478struct MainloopWaker {
479 pipe_tx: RawFd,
481 pipe_rx: RawFd,
482}
483
484impl MainloopWaker {
485 fn new() -> io::Result<Self> {
487 let (pipe_rx, pipe_tx) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?;
488 Ok(Self {
489 pipe_tx: pipe_tx.into_raw_fd(),
490 pipe_rx: pipe_rx.into_raw_fd(),
491 })
492 }
493
494 fn attach(self, ml: &MainloopApi) {
498 extern "C" fn wake_cb(
499 _: *const MainloopApi,
500 _: *mut libpulse_binding::mainloop::events::io::IoEventInternal,
501 fd: RawFd,
502 _: libpulse_binding::mainloop::events::io::FlagSet,
503 _: *mut c_void,
504 ) {
505 let ufd = unsafe { BorrowedFd::borrow_raw(fd) };
506 nix::unistd::read(ufd, &mut [0; 32]).unwrap();
507 }
508
509 (ml.io_new.unwrap())(
510 ml as *const _,
511 self.pipe_rx,
512 libpulse_binding::mainloop::events::io::FlagSet::INPUT,
513 Some(wake_cb),
514 std::ptr::null_mut(),
515 );
516 }
517
518 fn wake(self) -> io::Result<()> {
520 let buf = [0u8];
521 let res = unsafe { libc::write(self.pipe_tx, buf.as_ptr().cast(), 1) };
522 if res == -1 {
523 Err(io::Error::last_os_error())
524 } else {
525 Ok(())
526 }
527 }
528}