1use std::cell::{Cell, OnceCell, RefCell};
11use std::rc::Rc;
12use std::sync::{Arc, Once};
13use std::time::{Duration, Instant};
14
15use calloop::channel::Sender;
16use calloop::timer::TimeoutAction;
17use crabshell_reactive::{Owner, ReadSignal, Signal};
18use crabshell_ui::Cx;
19use libpulse_binding::callbacks::ListResult;
20use libpulse_binding::channelmap::{Map, Position};
21use libpulse_binding::context::introspect::{
22 Introspector, ServerInfo, SinkInfo, SinkInputInfo, SourceInfo,
23};
24use libpulse_binding::context::subscribe::{Facility, InterestMaskSet};
25use libpulse_binding::context::{Context, FlagSet, State};
26use libpulse_binding::def::SinkState;
27use libpulse_binding::mainloop::threaded::Mainloop;
28use libpulse_binding::volume::{ChannelVolumes, Volume};
29
30use crate::Shared;
31use crate::dbus::set_changed;
32
33mod peaks;
34mod sound;
35#[cfg(test)]
36mod tests;
37
38pub use peaks::PeakTarget;
39
40pub(crate) const RETRY: Duration = Duration::from_secs(2);
42
43pub(crate) const RETRY_FOR: Duration = Duration::from_secs(60);
46
47pub(crate) const SETTLE: Duration = Duration::from_millis(250);
49
50const MAX_NODES: usize = 128;
52
53pub(crate) struct Server {
55 pub(crate) address: Option<String>,
58 pub(crate) retry: Duration,
60 pub(crate) retry_for: Duration,
62}
63
64#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Sink {
67 pub name: String,
70 pub volume_percent: u32,
73 pub muted: bool,
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct AudioNode {
81 pub name: String,
83 pub description: String,
85 pub volume_percent: u32,
87 pub volumes: Vec<u32>,
90 pub channels: Vec<AudioChannel>,
93 pub muted: bool,
95}
96
97#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct AudioStream {
100 pub index: u32,
102 pub app_name: String,
104 pub title: String,
106 pub icon_name: String,
108 pub sink: String,
110 pub volume_percent: u32,
112 pub volumes: Vec<u32>,
114 pub channels: Vec<AudioChannel>,
116 pub muted: bool,
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123#[allow(missing_docs, reason = "each name says where it plays")]
124pub enum AudioChannel {
125 Mono,
126 FrontLeft,
127 FrontRight,
128 FrontCenter,
129 RearCenter,
130 RearLeft,
131 RearRight,
132 LowFrequencyEffects,
133 FrontLeftCenter,
134 FrontRightCenter,
135 SideLeft,
136 SideRight,
137 Aux(u8),
139 TopCenter,
140 TopFrontLeft,
141 TopFrontRight,
142 TopFrontCenter,
143 TopRearLeft,
144 TopRearRight,
145 TopRearCenter,
146 Unknown,
148}
149
150#[derive(Clone)]
152pub struct Audio {
153 sink: ReadSignal<Option<Sink>>,
154 lists: ReadLists,
155 owner: Owner,
157 no_peaks: ReadSignal<Vec<f32>>,
159 service: Option<Rc<AudioService>>,
161}
162
163impl Audio {
164 pub fn default_sink(&self) -> ReadSignal<Option<Sink>> {
167 self.sink
168 }
169
170 pub fn change_volume(&self, percent: i32) {
176 self.command(|pulse| pulse.change_volume(percent));
177 }
178
179 pub fn toggle_mute(&self) {
182 self.command(Pulse::toggle_mute);
183 }
184
185 pub fn sinks(&self) -> ReadSignal<Vec<AudioNode>> {
187 self.lists.sinks
188 }
189
190 pub fn sources(&self) -> ReadSignal<Vec<AudioNode>> {
192 self.lists.sources
193 }
194
195 pub fn default_source(&self) -> ReadSignal<Option<AudioNode>> {
197 self.lists.default_source
198 }
199
200 pub fn streams(&self) -> ReadSignal<Vec<AudioStream>> {
202 self.lists.streams
203 }
204
205 pub fn set_default_sink(&self, name: &str) {
207 let name = name.to_owned();
208 self.command(move |pulse| pulse.set_default(Kind::Sink, &name));
209 }
210
211 pub fn set_default_source(&self, name: &str) {
213 let name = name.to_owned();
214 self.command(move |pulse| pulse.set_default(Kind::Source, &name));
215 }
216
217 pub fn set_sink_volume(&self, name: &str, percent: u32) {
220 let name = name.to_owned();
221 self.command(move |pulse| pulse.set_node_volume(Kind::Sink, &name, percent));
222 }
223
224 pub fn set_sink_volumes(&self, name: &str, percents: &[u32]) {
229 let (name, percents) = (name.to_owned(), percents.to_vec());
230 self.command(move |pulse| pulse.set_node_volumes(Kind::Sink, &name, &percents));
231 }
232
233 pub fn set_sink_mute(&self, name: &str, muted: bool) {
235 let name = name.to_owned();
236 self.command(move |pulse| pulse.set_node_mute(Kind::Sink, &name, muted));
237 }
238
239 pub fn set_source_volume(&self, name: &str, percent: u32) {
242 let name = name.to_owned();
243 self.command(move |pulse| pulse.set_node_volume(Kind::Source, &name, percent));
244 }
245
246 pub fn set_source_volumes(&self, name: &str, percents: &[u32]) {
249 let (name, percents) = (name.to_owned(), percents.to_vec());
250 self.command(move |pulse| pulse.set_node_volumes(Kind::Source, &name, &percents));
251 }
252
253 pub fn set_source_mute(&self, name: &str, muted: bool) {
256 let name = name.to_owned();
257 self.command(move |pulse| pulse.set_node_mute(Kind::Source, &name, muted));
258 }
259
260 pub fn set_stream_volume(&self, index: u32, percent: u32) {
263 self.command(move |pulse| pulse.set_stream_volume(index, percent));
264 }
265
266 pub fn set_stream_volumes(&self, index: u32, percents: &[u32]) {
269 let percents = percents.to_vec();
270 self.command(move |pulse| pulse.set_stream_volumes(index, &percents));
271 }
272
273 pub fn set_stream_mute(&self, index: u32, muted: bool) {
275 self.command(move |pulse| pulse.set_stream_mute(index, muted));
276 }
277
278 pub fn move_stream(&self, index: u32, sink: &str) {
280 let sink = sink.to_owned();
281 self.command(move |pulse| pulse.move_stream(index, &sink));
282 }
283
284 fn command(&self, command: impl FnOnce(&mut Pulse)) {
285 let mut pulse = self
286 .service
287 .as_ref()
288 .map(|service| service.pulse.borrow_mut());
289 match pulse.as_deref_mut().and_then(Option::as_mut) {
290 Some(pulse) => command(pulse),
291 None => tracing::debug!("no audio service: nothing to change"),
292 }
293 }
294}
295
296pub(crate) fn audio(cx: &Cx) -> Audio {
298 if let Some(service) = cx.service::<AudioService>() {
299 return service.audio(cx.owner());
300 }
301 static LOGGED: Once = Once::new();
302 LOGGED.call_once(|| {
303 tracing::warn!("cx.audio() needs the services the shell provides; there is no sink");
304 });
305 Audio {
306 sink: cx.signal(None).read_only(),
307 lists: Lists {
308 sinks: cx.signal(Vec::new()).read_only(),
309 sources: cx.signal(Vec::new()).read_only(),
310 streams: cx.signal(Vec::new()).read_only(),
311 default_source: cx.signal(None).read_only(),
312 },
313 owner: cx.owner(),
314 no_peaks: cx.signal(Vec::new()).read_only(),
315 service: None,
316 }
317}
318
319#[derive(Clone, Copy)]
321struct Lists<N, S, D> {
322 sinks: N,
323 sources: N,
324 streams: S,
325 default_source: D,
326}
327
328type ReadLists =
329 Lists<ReadSignal<Vec<AudioNode>>, ReadSignal<Vec<AudioStream>>, ReadSignal<Option<AudioNode>>>;
330
331type ListSignals =
332 Lists<Signal<Vec<AudioNode>>, Signal<Vec<AudioStream>>, Signal<Option<AudioNode>>>;
333
334impl ListSignals {
335 fn read_only(&self) -> ReadLists {
336 Lists {
337 sinks: self.sinks.read_only(),
338 sources: self.sources.read_only(),
339 streams: self.streams.read_only(),
340 default_source: self.default_source.read_only(),
341 }
342 }
343}
344
345#[derive(Clone, Copy, Debug)]
347enum Kind {
348 Sink,
349 Source,
350}
351
352pub(crate) struct AudioService {
354 shared: Rc<Shared>,
355 sink: OnceCell<Signal<Option<Sink>>>,
357 lists: OnceCell<ListSignals>,
359 pulse: RefCell<Option<Pulse>>,
362 meters: RefCell<Vec<peaks::Wanted>>,
364 next_meter: Cell<u64>,
365 no_peaks: OnceCell<Signal<Vec<f32>>>,
367 bad_sounds: RefCell<sound::BadSounds>,
368 waiting_sounds: RefCell<sound::Waiting>,
370}
371
372pub(crate) type Message = (u32, Event);
375
376pub(crate) enum Event {
377 State,
379 Server,
381 Sink(u32),
383 Default(Option<String>),
385 DefaultSource(Option<String>),
387 Source,
389 Stream,
391 Sinks(Vec<NodeInfo>),
393 Sources(Vec<NodeInfo>),
395 Streams(Vec<StreamInfo>),
397 Info(Option<Info>),
399 Peaks(u64),
401 MeterState(u64),
403 Closing,
405 Sound(u64),
407 SoundDone(u64),
409}
410
411impl AudioService {
412 pub(crate) fn new(shared: Rc<Shared>) -> AudioService {
413 AudioService {
414 shared,
415 sink: OnceCell::new(),
416 lists: OnceCell::new(),
417 pulse: RefCell::new(None),
418 meters: RefCell::new(Vec::new()),
419 next_meter: Cell::new(0),
420 no_peaks: OnceCell::new(),
421 bad_sounds: RefCell::default(),
422 waiting_sounds: RefCell::default(),
423 }
424 }
425
426 fn audio(self: &Rc<Self>, owner: Owner) -> Audio {
427 let sink = *self.sink.get_or_init(|| {
428 self.after(Duration::ZERO, AudioService::start);
430 self.shared.root.signal(None)
431 });
432 let lists = *self.lists.get_or_init(|| {
433 let root = &self.shared.root;
434 Lists {
435 sinks: root.signal(Vec::new()),
436 sources: root.signal(Vec::new()),
437 streams: root.signal(Vec::new()),
438 default_source: root.signal(None),
439 }
440 });
441 let no_peaks = *self
442 .no_peaks
443 .get_or_init(|| self.shared.root.signal(Vec::new()));
444 Audio {
445 sink: sink.read_only(),
446 lists: lists.read_only(),
447 owner,
448 no_peaks: no_peaks.read_only(),
449 service: Some(Rc::clone(self)),
450 }
451 }
452
453 fn start(self: &Rc<Self>) {
456 let Some(server) = &self.shared.config.audio else {
457 return tracing::info!("no audio server is set, so there is no sink");
458 };
459 let sink = *self
460 .sink
461 .get()
462 .expect("the sink is made before libpulse starts");
463 let lists = *self
464 .lists
465 .get()
466 .expect("the lists are made before libpulse starts");
467 let Some(event_loop) = self.shared.event_loop() else {
468 return;
469 };
470 let Some(mut mainloop) = Mainloop::new() else {
471 tracing::error!("libpulse couldn't make its mainloop: no audio");
472 return;
473 };
474 if let Err(error) = mainloop.start() {
475 tracing::error!(%error, "libpulse's thread didn't start: no audio");
476 return;
477 }
478 let (sender, channel) = calloop::channel::channel();
479 let pulse = Pulse {
481 meters: Vec::new(),
482 closing: Vec::new(),
483 sounds: Vec::new(),
484 next_sound: 0,
485 own_client: None,
486 intro: None,
487 context: None,
488 mainloop,
489 sender: Arc::new(sender),
490 generation: 0,
491 shown: None,
492 asked: None,
493 sink,
494 lists,
495 nodes: Nodes::default(),
496 down: false,
497 retry_until: Instant::now() + server.retry_for,
498 };
499 let service = Rc::clone(self);
500 let on_message = Box::new(move |message| service.on_message(message));
501 if event_loop.insert_audio_channel(channel, on_message) {
502 *self.pulse.borrow_mut() = Some(pulse);
503 self.connect();
504 }
505 }
506
507 fn connect(self: &Rc<Self>) {
509 let mut pulse = self.pulse.borrow_mut();
510 let (Some(pulse), Some(server)) = (pulse.as_mut(), &self.shared.config.audio) else {
511 return;
512 };
513 if pulse.sink.try_with(|_| ()).is_none() {
515 return;
516 }
517 if let Err(why) = pulse.connect(server.address.as_deref()) {
518 self.lost(pulse, &why);
519 }
520 }
521
522 fn on_message(self: &Rc<Self>, (generation, event): Message) {
523 let mut pulse = self.pulse.borrow_mut();
524 let Some(pulse) = pulse
526 .as_mut()
527 .filter(|pulse| pulse.generation == generation)
528 else {
529 return;
530 };
531 match event {
532 Event::State => match pulse.on_state() {
533 Err(why) => self.lost(pulse, &why),
534 Ok(()) if pulse.intro.is_some() => self.play_waiting(pulse),
535 Ok(()) => {}
536 },
537 Event::Server => {
538 pulse.read_default();
539 pulse.read_lists();
540 }
541 Event::Sink(index) => {
542 if pulse.shown.as_ref().is_some_and(|s| s.index == index) {
543 pulse.read_default();
544 }
545 pulse.read_sinks();
546 }
547 Event::Default(name) => pulse.read_sink(name),
548 Event::Info(info) => pulse.show(info),
549 Event::DefaultSource(name) => {
550 pulse.nodes.default_source = name;
551 pulse.show_lists();
552 }
553 Event::Source => pulse.read_sources(),
554 Event::Stream => pulse.read_streams(),
555 Event::Sinks(sinks) => {
556 pulse.nodes.sinks = sinks;
557 self.show_lists(pulse);
558 }
559 Event::Sources(sources) => {
560 pulse.nodes.sources = sources;
561 self.show_lists(pulse);
562 }
563 Event::Streams(streams) => {
564 pulse.nodes.streams = streams;
565 self.show_lists(pulse);
566 }
567 Event::Peaks(id) => pulse.read_peaks(id),
568 Event::MeterState(id) => pulse.on_meter_state(id),
569 Event::Closing => pulse.on_closing(),
570 Event::Sound(id) => pulse.feed_sound(id),
571 Event::SoundDone(id) => pulse.sound_done(id),
572 }
573 }
574
575 fn show_lists(&self, pulse: &mut Pulse) {
577 pulse.show_lists();
578 pulse.sync_meters(&self.meters.borrow());
579 }
580
581 fn lost(self: &Rc<Self>, pulse: &mut Pulse, why: &str) {
586 let Some(Server {
587 retry, retry_for, ..
588 }) = self.shared.config.audio
589 else {
590 return;
591 };
592 self.drop_waiting();
593 let now = Instant::now();
594 if pulse.intro.is_some() {
596 pulse.retry_until = now + retry_for;
597 }
598 if pulse.disconnect() {
599 tracing::warn!(
600 reason = why,
601 "no audio server, trying again every {retry:?} for up to {retry_for:?}"
602 );
603 }
604 if now + retry > pulse.retry_until {
605 return tracing::info!(
607 "stopped trying to reach the audio server; it is tried again when the shell restarts"
608 );
609 }
610 self.after(retry, AudioService::connect);
611 }
612
613 fn after(self: &Rc<Self>, delay: Duration, f: fn(&Rc<AudioService>)) {
615 let Some(event_loop) = self.shared.event_loop() else {
616 return;
617 };
618 let service = Rc::clone(self);
619 let once = move || {
620 f(&service);
621 TimeoutAction::Drop
622 };
623 event_loop.insert_timer(Instant::now() + delay, Box::new(once));
624 }
625}
626
627struct Pulse {
631 meters: Vec<peaks::Meter>,
634 closing: Vec<peaks::Recording>,
636 sounds: Vec<sound::Sound>,
637 next_sound: u64,
638 own_client: Option<u32>,
641 intro: Option<Introspector>,
642 context: Option<Context>,
643 mainloop: Mainloop,
644 sender: Arc<Sender<Message>>,
648 generation: u32,
651 shown: Option<Info>,
653 asked: Option<(Info, Instant)>,
658 sink: Signal<Option<Sink>>,
659 lists: ListSignals,
660 nodes: Nodes,
662 down: bool,
664 retry_until: Instant,
666}
667
668#[derive(Default)]
670struct Nodes {
671 sinks: Vec<NodeInfo>,
672 sources: Vec<NodeInfo>,
673 streams: Vec<StreamInfo>,
674 default_source: Option<String>,
675}
676
677#[derive(Clone, PartialEq)]
679pub(crate) struct NodeInfo {
680 index: u32,
681 name: String,
682 description: String,
683 volumes: ChannelVolumes,
684 map: Map,
685 muted: bool,
686 monitor: bool,
688 monitor_source: Option<String>,
690 running: bool,
692}
693
694impl NodeInfo {
695 fn node(&self) -> AudioNode {
696 let (volumes, channels) = each_channel(&self.volumes, &self.map);
697 AudioNode {
698 name: self.name.clone(),
699 description: self.description.clone(),
700 volume_percent: percent(self.volumes.avg()),
701 volumes,
702 channels,
703 muted: self.muted,
704 }
705 }
706}
707
708#[derive(Clone, PartialEq)]
710pub(crate) struct StreamInfo {
711 index: u32,
712 app_name: String,
713 title: String,
714 icon_name: String,
715 sink: u32,
716 volumes: ChannelVolumes,
717 map: Map,
718 muted: bool,
719 corked: bool,
721}
722
723impl StreamInfo {
724 fn read(info: &SinkInputInfo) -> StreamInfo {
725 use libpulse_binding::proplist::properties::{APPLICATION_ICON_NAME, APPLICATION_NAME};
726
727 let property = |key| info.proplist.get_str(key).unwrap_or_default();
728 StreamInfo {
729 index: info.index,
730 app_name: property(APPLICATION_NAME),
731 title: info.name.as_deref().unwrap_or_default().to_owned(),
732 icon_name: property(APPLICATION_ICON_NAME),
733 sink: info.sink,
734 volumes: info.volume,
735 map: info.channel_map,
736 muted: info.mute,
737 corked: info.corked,
738 }
739 }
740}
741
742#[derive(Clone, PartialEq)]
744pub(crate) struct Info {
745 index: u32,
746 name: String,
747 volumes: ChannelVolumes,
748 muted: bool,
749}
750
751impl Pulse {
752 fn connect(&mut self, server: Option<&str>) -> Result<(), String> {
755 let lock = Locked::new(&mut self.mainloop);
756 let mut context = Context::new(&*lock.0, "crabshell").ok_or("libpulse made no context")?;
757 let (sender, generation) = (Arc::clone(&self.sender), self.generation);
758 context.set_state_callback(Some(Box::new(on_pa_thread(move || {
759 let _ = sender.send((generation, Event::State));
760 }))));
761 let connected = context.connect(server, FlagSet::NOAUTOSPAWN, None);
763 self.context = Some(context);
764 connected.map_err(|error| format!("{error}"))
765 }
766
767 fn on_state(&mut self) -> Result<(), String> {
771 let lock = Locked::new(&mut self.mainloop);
772 let Some(context) = self.context.as_mut() else {
773 return Ok(());
774 };
775 match context.get_state() {
776 State::Ready if self.intro.is_none() => {
778 let (sender, generation) = (Arc::clone(&self.sender), self.generation);
779 let on_event = move |facility, _, index| {
780 let event = match facility {
781 Some(Facility::Server) => Event::Server,
782 Some(Facility::Sink) => Event::Sink(index),
783 Some(Facility::Source) => Event::Source,
784 Some(Facility::SinkInput) => Event::Stream,
785 _ => return,
786 };
787 let _ = sender.send((generation, event));
788 };
789 context.set_subscribe_callback(Some(Box::new(on_pa_thread(on_event))));
790 let interest = InterestMaskSet::SINK
791 | InterestMaskSet::SOURCE
792 | InterestMaskSet::SINK_INPUT
793 | InterestMaskSet::SERVER;
794 context.subscribe(interest, on_pa_thread(|_| {}));
795 self.intro = Some(context.introspect());
796 self.own_client = context.get_index();
797 drop(lock);
798 if std::mem::take(&mut self.down) {
799 tracing::info!("the audio server is back");
800 } else {
801 tracing::debug!("connected to the audio server");
802 }
803 self.read_default();
804 self.read_lists();
805 Ok(())
806 }
807 State::Failed | State::Terminated => Err(format!("{}", context.errno())),
808 _ => Ok(()),
809 }
810 }
811
812 fn when_ready(&mut self, call: impl FnOnce(&mut Introspector)) -> bool {
816 self.when_ready_with(|_, intro| call(intro))
817 }
818
819 fn when_ready_with(&mut self, call: impl FnOnce(&mut Context, &mut Introspector)) -> bool {
821 let _lock = Locked::new(&mut self.mainloop);
822 match (&mut self.context, &mut self.intro) {
823 (Some(context), Some(intro)) if context.get_state() == State::Ready => {
824 call(context, intro);
825 true
826 }
827 _ => false,
828 }
829 }
830
831 fn read_default(&mut self) {
833 let (sender, generation) = (Arc::clone(&self.sender), self.generation);
834 self.when_ready(|intro| {
835 intro.get_server_info(on_pa_thread(move |info: &ServerInfo| {
838 let name = |name: &Option<std::borrow::Cow<'_, str>>| {
839 let name = name.as_deref().filter(|name| !name.is_empty());
840 name.map(str::to_owned)
841 };
842 let _ = sender.send((generation, Event::Default(name(&info.default_sink_name))));
843 let source = Event::DefaultSource(name(&info.default_source_name));
844 let _ = sender.send((generation, source));
845 }));
846 });
847 }
848
849 fn read_sink(&mut self, name: Option<String>) {
851 let Some(name) = name else {
852 return self.show(None);
853 };
854 let (sender, generation) = (Arc::clone(&self.sender), self.generation);
855 self.when_ready(|intro| {
856 let mut found = None;
857 let on_result = move |result: ListResult<&SinkInfo>| match result {
858 ListResult::Item(info) => found = Info::read(info),
859 ListResult::End | ListResult::Error => {
860 let _ = sender.send((generation, Event::Info(found.take())));
861 }
862 };
863 intro.get_sink_info_by_name(&name, on_pa_thread(on_result));
864 });
865 }
866
867 fn read_lists(&mut self) {
869 self.read_sinks();
870 self.read_sources();
871 self.read_streams();
872 }
873
874 fn read_sinks(&mut self) {
875 let (sender, generation) = (Arc::clone(&self.sender), self.generation);
876 self.when_ready(|intro| {
877 let mut found = Vec::new();
878 let on_result = move |result: ListResult<&SinkInfo>| match result {
879 ListResult::Item(info) => {
880 let read = node(
881 info.index,
882 &info.name,
883 &info.description,
884 info.volume,
885 info.channel_map,
886 info.mute,
887 );
888 let monitor_source = info.monitor_source_name.as_deref().map(str::to_owned);
889 let running = info.state == SinkState::Running;
890 found.extend(read.map(|node| NodeInfo {
891 monitor_source,
892 running,
893 ..node
894 }));
895 }
896 ListResult::End => {
897 let _ = sender.send((generation, Event::Sinks(std::mem::take(&mut found))));
898 }
899 ListResult::Error => tracing::warn!("the audio server didn't list its sinks"),
901 };
902 intro.get_sink_info_list(on_pa_thread(on_result));
903 });
904 }
905
906 fn read_sources(&mut self) {
907 let (sender, generation) = (Arc::clone(&self.sender), self.generation);
908 self.when_ready(|intro| {
909 let mut found = Vec::new();
910 let on_result = move |result: ListResult<&SourceInfo>| match result {
911 ListResult::Item(info) => {
912 let read = node(
913 info.index,
914 &info.name,
915 &info.description,
916 info.volume,
917 info.channel_map,
918 info.mute,
919 );
920 let monitor = info.monitor_of_sink.is_some();
921 found.extend(read.map(|node| NodeInfo { monitor, ..node }));
922 }
923 ListResult::End => {
924 let _ = sender.send((generation, Event::Sources(std::mem::take(&mut found))));
925 }
926 ListResult::Error => tracing::warn!("the audio server didn't list its sources"),
927 };
928 intro.get_source_info_list(on_pa_thread(on_result));
929 });
930 }
931
932 fn read_streams(&mut self) {
933 let (sender, generation) = (Arc::clone(&self.sender), self.generation);
934 let own = self.own_client;
935 self.when_ready(|intro| {
936 let mut found = Vec::new();
937 let on_result = move |result: ListResult<&SinkInputInfo>| match result {
938 ListResult::Item(info)
939 if info.volume.is_valid() && (own.is_none() || info.client != own) =>
940 {
941 found.push(StreamInfo::read(info));
942 }
943 ListResult::Item(_) => {}
944 ListResult::End => {
945 let _ = sender.send((generation, Event::Streams(std::mem::take(&mut found))));
946 }
947 ListResult::Error => tracing::warn!("the audio server didn't list its streams"),
948 };
949 intro.get_sink_input_info_list(on_pa_thread(on_result));
950 });
951 }
952
953 fn show_lists(&mut self) {
956 let Nodes {
957 sinks,
958 sources,
959 streams,
960 default_source,
961 } = &self.nodes;
962 let capped = |nodes: &[NodeInfo]| -> Vec<AudioNode> {
963 nodes.iter().take(MAX_NODES).map(NodeInfo::node).collect()
964 };
965 let sink_name = |index| {
966 let sink = sinks.iter().find(|sink| sink.index == index);
967 sink.map_or(String::new(), |sink| sink.name.clone())
968 };
969 let streams = streams
970 .iter()
971 .take(MAX_NODES)
972 .map(|stream| {
973 let (volumes, channels) = each_channel(&stream.volumes, &stream.map);
974 AudioStream {
975 index: stream.index,
976 app_name: stream.app_name.clone(),
977 title: stream.title.clone(),
978 icon_name: stream.icon_name.clone(),
979 sink: sink_name(stream.sink),
980 volume_percent: percent(stream.volumes.avg()),
981 volumes,
982 channels,
983 muted: stream.muted,
984 }
985 })
986 .collect();
987 let default = default_source
988 .as_ref()
989 .and_then(|name| sources.iter().find(|source| source.name == *name))
990 .map(NodeInfo::node);
991 set_changed(self.lists.sinks, capped(sinks));
992 let listed: Vec<NodeInfo> = sources.iter().filter(|s| !s.monitor).cloned().collect();
995 set_changed(self.lists.sources, capped(&listed));
996 set_changed(self.lists.streams, streams);
997 set_changed(self.lists.default_source, default);
998 }
999
1000 fn set_default(&mut self, kind: Kind, name: &str) {
1001 let sent = self.when_ready_with(|context, _| {
1002 let done = on_pa_thread(|_| {});
1003 match kind {
1004 Kind::Sink => drop(context.set_default_sink(name, done)),
1005 Kind::Source => drop(context.set_default_source(name, done)),
1006 }
1007 });
1008 if !sent {
1009 tracing::debug!(name, "no audio server: the default stays");
1010 }
1011 }
1012
1013 fn set_node_volume(&mut self, kind: Kind, name: &str, percent: u32) {
1014 let nodes = match kind {
1015 Kind::Sink => &self.nodes.sinks,
1016 Kind::Source => &self.nodes.sources,
1017 };
1018 let Some(node) = nodes.iter().find(|node| node.name == name) else {
1019 return tracing::debug!(name, ?kind, "no such node: its volume stays");
1020 };
1021 let volumes = at(node.volumes, percent);
1022 self.when_ready(|intro| match kind {
1023 Kind::Sink => drop(intro.set_sink_volume_by_name(name, &volumes, None)),
1024 Kind::Source => drop(intro.set_source_volume_by_name(name, &volumes, None)),
1025 });
1026 }
1027
1028 fn set_node_volumes(&mut self, kind: Kind, name: &str, percents: &[u32]) {
1029 let nodes = match kind {
1030 Kind::Sink => &self.nodes.sinks,
1031 Kind::Source => &self.nodes.sources,
1032 };
1033 let Some(node) = nodes.iter().find(|node| node.name == name) else {
1034 return tracing::debug!(name, ?kind, "no such node: its volumes stay");
1035 };
1036 let Some(volumes) = each_at(node.volumes, percents) else {
1037 return tracing::warn!(
1038 name,
1039 ?kind,
1040 ?percents,
1041 "not one volume per channel: none set"
1042 );
1043 };
1044 self.when_ready(|intro| match kind {
1045 Kind::Sink => drop(intro.set_sink_volume_by_name(name, &volumes, None)),
1046 Kind::Source => drop(intro.set_source_volume_by_name(name, &volumes, None)),
1047 });
1048 }
1049
1050 fn set_node_mute(&mut self, kind: Kind, name: &str, muted: bool) {
1051 self.when_ready(|intro| match kind {
1052 Kind::Sink => drop(intro.set_sink_mute_by_name(name, muted, None)),
1053 Kind::Source => drop(intro.set_source_mute_by_name(name, muted, None)),
1054 });
1055 }
1056
1057 fn set_stream_volume(&mut self, index: u32, percent: u32) {
1058 let Some(stream) = self
1059 .nodes
1060 .streams
1061 .iter()
1062 .find(|stream| stream.index == index)
1063 else {
1064 return tracing::debug!(index, "no such stream: its volume stays");
1065 };
1066 let volumes = at(stream.volumes, percent);
1067 self.when_ready(|intro| drop(intro.set_sink_input_volume(index, &volumes, None)));
1068 }
1069
1070 fn set_stream_volumes(&mut self, index: u32, percents: &[u32]) {
1071 let streams = &self.nodes.streams;
1072 let Some(stream) = streams.iter().find(|stream| stream.index == index) else {
1073 return tracing::debug!(index, "no such stream: its volumes stay");
1074 };
1075 let Some(volumes) = each_at(stream.volumes, percents) else {
1076 return tracing::warn!(index, ?percents, "not one volume per channel: none set");
1077 };
1078 self.when_ready(|intro| drop(intro.set_sink_input_volume(index, &volumes, None)));
1079 }
1080
1081 fn set_stream_mute(&mut self, index: u32, muted: bool) {
1082 self.when_ready(|intro| drop(intro.set_sink_input_mute(index, muted, None)));
1083 }
1084
1085 fn move_stream(&mut self, index: u32, sink: &str) {
1086 self.when_ready(|intro| drop(intro.move_sink_input_by_name(index, sink, None)));
1087 }
1088
1089 fn show(&mut self, info: Option<Info>) {
1092 let stands = match (&self.asked, &info) {
1094 (Some((asked, _)), Some(read)) => read != asked && read.index == asked.index,
1095 _ => false,
1096 };
1097 if !stands {
1098 self.asked = None;
1099 }
1100 let sink = info.as_ref().map(Info::sink);
1101 self.shown = info;
1102 if self.sink.try_with(|shown| *shown != sink) == Some(true) {
1103 self.sink.set(sink);
1104 }
1105 }
1106
1107 fn base(&self) -> Option<Info> {
1110 match &self.asked {
1111 Some((asked, at)) if at.elapsed() < SETTLE => Some(asked.clone()),
1112 _ => self.shown.clone(),
1113 }
1114 }
1115
1116 fn change_volume(&mut self, percent: i32) {
1117 let Some(mut next) = self.base() else {
1118 return tracing::debug!("no default sink: the volume stays");
1119 };
1120 next.volumes = changed(next.volumes, percent);
1121 let sent = self.when_ready(|intro| {
1122 intro.set_sink_volume_by_name(&next.name, &next.volumes, None);
1123 });
1124 if sent {
1125 self.asked = Some((next, Instant::now()));
1126 } else {
1127 tracing::debug!("no audio server: the volume stays");
1128 }
1129 }
1130
1131 fn toggle_mute(&mut self) {
1132 let Some(mut next) = self.base() else {
1133 return tracing::debug!("no default sink: nothing to mute");
1134 };
1135 next.muted = !next.muted;
1136 let sent = self.when_ready(|intro| {
1137 intro.set_sink_mute_by_name(&next.name, next.muted, None);
1138 });
1139 if sent {
1140 self.asked = Some((next, Instant::now()));
1141 } else {
1142 tracing::debug!("no audio server: nothing to mute");
1143 }
1144 }
1145
1146 fn disconnect(&mut self) -> bool {
1149 let lock = Locked::new(&mut self.mainloop);
1150 peaks::close_all(&mut self.meters, &mut self.closing);
1151 self.sounds.clear();
1152 self.intro = None;
1153 if let Some(mut context) = self.context.take() {
1154 context.set_state_callback(None);
1156 context.set_subscribe_callback(None);
1157 context.disconnect();
1158 }
1159 drop(lock);
1160 self.generation += 1;
1161 self.show(None);
1162 self.nodes = Nodes::default();
1163 self.show_lists();
1164 !std::mem::replace(&mut self.down, true)
1165 }
1166}
1167
1168impl Drop for Pulse {
1169 fn drop(&mut self) {
1170 self.mainloop.stop();
1173 }
1174}
1175
1176impl Info {
1177 fn read(info: &SinkInfo) -> Option<Info> {
1180 let (Some(name), true) = (info.name.as_deref(), info.volume.is_valid()) else {
1181 tracing::warn!(
1182 index = info.index,
1183 "skipped a sink with no name or a bad volume"
1184 );
1185 return None;
1186 };
1187 Some(Info {
1188 index: info.index,
1189 name: name.to_owned(),
1190 volumes: info.volume,
1191 muted: info.mute,
1192 })
1193 }
1194
1195 fn sink(&self) -> Sink {
1196 Sink {
1197 name: self.name.clone(),
1198 volume_percent: percent(self.volumes.avg()),
1199 muted: self.muted,
1200 }
1201 }
1202}
1203
1204struct Locked<'a>(&'a mut Mainloop);
1207
1208impl<'a> Locked<'a> {
1209 fn new(mainloop: &'a mut Mainloop) -> Locked<'a> {
1210 mainloop.lock();
1211 Locked(mainloop)
1212 }
1213}
1214
1215impl Drop for Locked<'_> {
1216 fn drop(&mut self) {
1217 self.0.unlock();
1218 }
1219}
1220
1221fn on_pa_thread<F: Send + 'static>(callback: F) -> F {
1224 callback
1225}
1226
1227fn percent(volume: Volume) -> u32 {
1230 let norm = u64::from(Volume::NORMAL.0);
1231 ((u64::from(volume.0) * 100 + norm / 2) / norm) as u32
1233}
1234
1235fn changed(mut volumes: ChannelVolumes, delta: i32) -> ChannelVolumes {
1240 let norm = i64::from(Volume::NORMAL.0);
1241 let average = volumes.avg();
1242 let target = (i64::from(percent(average)) + i64::from(delta)).clamp(0, 100);
1243 let shift = (target * norm + 50) / 100 - i64::from(average.0);
1244 for volume in volumes.get_mut() {
1245 volume.0 = (i64::from(volume.0) + shift).clamp(0, norm) as u32;
1247 }
1248 volumes
1249}
1250
1251fn node(
1254 index: u32,
1255 name: &Option<std::borrow::Cow<'_, str>>,
1256 description: &Option<std::borrow::Cow<'_, str>>,
1257 volumes: ChannelVolumes,
1258 map: Map,
1259 muted: bool,
1260) -> Option<NodeInfo> {
1261 let name = name.as_deref().filter(|_| volumes.is_valid())?;
1262 Some(NodeInfo {
1263 index,
1264 name: name.to_owned(),
1265 description: description.as_deref().unwrap_or(name).to_owned(),
1266 volumes,
1267 map,
1268 muted,
1269 monitor: false,
1270 monitor_source: None,
1271 running: false,
1272 })
1273}
1274
1275fn each_channel(volumes: &ChannelVolumes, map: &Map) -> (Vec<u32>, Vec<AudioChannel>) {
1278 let max = usize::from(Map::CHANNELS_MAX);
1279 let percents: Vec<u32> = volumes
1280 .get()
1281 .iter()
1282 .take(max)
1283 .map(|v| percent(*v))
1284 .collect();
1285 let positions = map.get().iter().map(|&position| channel(position));
1286 let positions = positions.chain(std::iter::repeat(AudioChannel::Unknown));
1287 let channels = positions.take(percents.len()).collect();
1288 (percents, channels)
1289}
1290
1291fn channel(position: Position) -> AudioChannel {
1293 use AudioChannel as C;
1294 let aux = position as i32 - Position::Aux0 as i32;
1296 match position {
1297 Position::Mono => C::Mono,
1298 Position::FrontLeft => C::FrontLeft,
1299 Position::FrontRight => C::FrontRight,
1300 Position::FrontCenter => C::FrontCenter,
1301 Position::RearCenter => C::RearCenter,
1302 Position::RearLeft => C::RearLeft,
1303 Position::RearRight => C::RearRight,
1304 Position::Lfe => C::LowFrequencyEffects,
1305 Position::FrontLeftOfCenter => C::FrontLeftCenter,
1306 Position::FrontRightOfCenter => C::FrontRightCenter,
1307 Position::SideLeft => C::SideLeft,
1308 Position::SideRight => C::SideRight,
1309 Position::TopCenter => C::TopCenter,
1310 Position::TopFrontLeft => C::TopFrontLeft,
1311 Position::TopFrontRight => C::TopFrontRight,
1312 Position::TopFrontCenter => C::TopFrontCenter,
1313 Position::TopRearLeft => C::TopRearLeft,
1314 Position::TopRearRight => C::TopRearRight,
1315 Position::TopRearCenter => C::TopRearCenter,
1316 _ => match u8::try_from(aux) {
1317 Ok(aux) if aux < 32 => C::Aux(aux),
1318 _ => C::Unknown,
1319 },
1320 }
1321}
1322
1323fn each_at(mut volumes: ChannelVolumes, percents: &[u32]) -> Option<ChannelVolumes> {
1326 if percents.len() != usize::from(volumes.len()) {
1327 return None;
1328 }
1329 let norm = Volume::NORMAL.0;
1330 for (volume, percent) in volumes.get_mut().iter_mut().zip(percents) {
1331 *volume = Volume(((*percent).min(100) * norm + 50) / 100);
1333 }
1334 Some(volumes)
1335}
1336
1337fn at(volumes: ChannelVolumes, percent: u32) -> ChannelVolumes {
1340 let shown = self::percent(volumes.avg());
1341 changed(volumes, percent.min(100) as i32 - shown.min(10_000) as i32)
1343}