Skip to main content

crabshell_services/
audio.rs

1//! Audio: the default sink's volume and mute, and every sink, source and
2//! app stream with theirs, from the PulseAudio server, which
3//! pipewire-pulse serves on PipeWire systems.
4//!
5//! libpulse runs its mainloop on a thread of its own. Every libpulse call
6//! from this side runs on the main thread under the mainloop's lock.
7//! libpulse's callbacks run on its thread and only send a message over a
8//! calloop channel, so the signal is set on the main thread like any other.
9
10use 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
40/// How long the service waits before each reconnect.
41pub(crate) const RETRY: Duration = Duration::from_secs(2);
42
43/// How long the service keeps trying, from startup and from each drop of
44/// a working connection.
45pub(crate) const RETRY_FOR: Duration = Duration::from_secs(60);
46
47/// How long a command's result stands in for the server's reads.
48pub(crate) const SETTLE: Duration = Duration::from_millis(250);
49
50/// The most sinks, sources or streams kept, each.
51const MAX_NODES: usize = 128;
52
53/// Where the audio server is.
54pub(crate) struct Server {
55  /// In libpulse's server syntax. `None` for libpulse's default, which
56  /// `PULSE_SERVER` and client.conf can set.
57  pub(crate) address: Option<String>,
58  /// How long to wait before each reconnect: [`RETRY`], less in tests.
59  pub(crate) retry: Duration,
60  /// How long to keep trying: [`RETRY_FOR`], less in tests.
61  pub(crate) retry_for: Duration,
62}
63
64/// The default sink: where sound goes unless an app picks another.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Sink {
67  /// Its name on the server, such as
68  /// `alsa_output.pci-0000_03_00.6.analog-stereo`.
69  pub name: String,
70  /// The average of its channels' volumes, rounded as `pactl` rounds
71  /// them. 100 is full volume, and other apps can set more.
72  pub volume_percent: u32,
73  /// Whether it is muted.
74  pub muted: bool,
75}
76
77/// A sink or a source: where sound goes out, such as speakers, or comes
78/// in, such as a microphone.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct AudioNode {
81  /// Its name on the server, which the setters take.
82  pub name: String,
83  /// What a person calls it, such as `Built-in Audio Analog Stereo`.
84  pub description: String,
85  /// The average of its channels' volumes, as [`Sink`]'s.
86  pub volume_percent: u32,
87  /// Each channel's volume, rounded as `volume_percent` is, in the order
88  /// of `channels`.
89  pub volumes: Vec<u32>,
90  /// Where each channel plays, such as [`AudioChannel::FrontLeft`]. As
91  /// long as `volumes`.
92  pub channels: Vec<AudioChannel>,
93  /// Whether it is muted.
94  pub muted: bool,
95}
96
97/// An app playing sound: one of the server's sink inputs.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct AudioStream {
100  /// The server's number for it, which the setters take.
101  pub index: u32,
102  /// The app's name, such as `Firefox`.
103  pub app_name: String,
104  /// What it plays, such as a tab's title.
105  pub title: String,
106  /// The app's icon name, or `""`.
107  pub icon_name: String,
108  /// The name of the sink it plays to.
109  pub sink: String,
110  /// The average of its channels' volumes, as [`Sink`]'s.
111  pub volume_percent: u32,
112  /// Each channel's volume, as [`AudioNode::volumes`].
113  pub volumes: Vec<u32>,
114  /// Where each channel plays, as [`AudioNode::channels`].
115  pub channels: Vec<AudioChannel>,
116  /// Whether it is muted.
117  pub muted: bool,
118}
119
120/// Where a channel plays, as PulseAudio's channel map names it, with
121/// Quickshell's names for `PwAudioChannel`.
122#[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  /// An auxiliary channel, 0 to 31.
138  Aux(u8),
139  TopCenter,
140  TopFrontLeft,
141  TopFrontRight,
142  TopFrontCenter,
143  TopRearLeft,
144  TopRearRight,
145  TopRearCenter,
146  /// A position the server didn't give.
147  Unknown,
148}
149
150/// The audio service, from `cx.audio()`. Cloning it is cheap.
151#[derive(Clone)]
152pub struct Audio {
153  sink: ReadSignal<Option<Sink>>,
154  lists: ReadLists,
155  /// The asking context's, which owns its peak meters.
156  owner: Owner,
157  /// Empty and never set, for a meter that can't record.
158  no_peaks: ReadSignal<Vec<f32>>,
159  /// `None` on a context the shell didn't set up.
160  service: Option<Rc<AudioService>>,
161}
162
163impl Audio {
164  /// The default sink. `None` while there is no audio server or the
165  /// server has no sink. Every caller gets the same signal.
166  pub fn default_sink(&self) -> ReadSignal<Option<Sink>> {
167    self.sink
168  }
169
170  /// Changes the default sink's volume by `percent`, louder when
171  /// positive, and keeps it within 0-100%, so a step from above 100%
172  /// lands on 100%. Every channel moves by the same amount, keeping their
173  /// balance, except that one reaching 0% or 100% stops there. With no
174  /// sink or no server it does nothing.
175  pub fn change_volume(&self, percent: i32) {
176    self.command(|pulse| pulse.change_volume(percent));
177  }
178
179  /// Mutes the default sink, or unmutes it. With no sink or no server it
180  /// does nothing.
181  pub fn toggle_mute(&self) {
182    self.command(Pulse::toggle_mute);
183  }
184
185  /// Every sink, in the server's order. Empty while there is no server.
186  pub fn sinks(&self) -> ReadSignal<Vec<AudioNode>> {
187    self.lists.sinks
188  }
189
190  /// Every source except sinks' monitors, in the server's order.
191  pub fn sources(&self) -> ReadSignal<Vec<AudioNode>> {
192    self.lists.sources
193  }
194
195  /// The default source, where a call's microphone sound comes from.
196  pub fn default_source(&self) -> ReadSignal<Option<AudioNode>> {
197    self.lists.default_source
198  }
199
200  /// Every app playing sound, in the server's order.
201  pub fn streams(&self) -> ReadSignal<Vec<AudioStream>> {
202    self.lists.streams
203  }
204
205  /// Makes the sink called `name` the default.
206  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  /// Makes the source called `name` the default.
212  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  /// Sets every channel of the sink called `name` to `percent`, at most
218  /// 100.
219  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  /// Sets each channel of the sink called `name` to its own percent, at
225  /// most 100, in the order of [`AudioNode::channels`], as a balance
226  /// slider does. A list of another length than the sink's channels is
227  /// logged and not sent.
228  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  /// Mutes the sink called `name`, or unmutes it.
234  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  /// Sets every channel of the source called `name` to `percent`, at most
240  /// 100.
241  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  /// Sets each channel of the source called `name`, as
247  /// [`set_sink_volumes`](Self::set_sink_volumes) does a sink's.
248  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  /// Mutes the source called `name`, or unmutes it, as a microphone
254  /// button does.
255  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  /// Sets every channel of the stream numbered `index` to `percent`, at
261  /// most 100.
262  pub fn set_stream_volume(&self, index: u32, percent: u32) {
263    self.command(move |pulse| pulse.set_stream_volume(index, percent));
264  }
265
266  /// Sets each channel of the stream numbered `index`, as
267  /// [`set_sink_volumes`](Self::set_sink_volumes) does a sink's.
268  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  /// Mutes the stream numbered `index`, or unmutes it.
274  pub fn set_stream_mute(&self, index: u32, muted: bool) {
275    self.command(move |pulse| pulse.set_stream_mute(index, muted));
276  }
277
278  /// Moves the stream numbered `index` to play to the sink called `sink`.
279  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
296/// `cx.audio()`.
297pub(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/// The lists the service shows, as signals to set or read.
320#[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/// A sink or a source, for the setters both have.
346#[derive(Clone, Copy, Debug)]
347enum Kind {
348  Sink,
349  Source,
350}
351
352/// The audio service of one shell. It connects on first use.
353pub(crate) struct AudioService {
354  shared: Rc<Shared>,
355  /// The default sink, under the root owner. Made on first use.
356  sink: OnceCell<Signal<Option<Sink>>>,
357  /// The sinks, sources and streams, made with `sink`.
358  lists: OnceCell<ListSignals>,
359  /// libpulse, from first use on. `None` before that, and if libpulse
360  /// couldn't start its thread.
361  pulse: RefCell<Option<Pulse>>,
362  /// The peak meters configs hold, recording or not.
363  meters: RefCell<Vec<peaks::Wanted>>,
364  next_meter: Cell<u64>,
365  /// What a meter that can't record shows, made with `sink`.
366  no_peaks: OnceCell<Signal<Vec<f32>>>,
367  bad_sounds: RefCell<sound::BadSounds>,
368  /// Sounds played before libpulse connected.
369  waiting_sounds: RefCell<sound::Waiting>,
370}
371
372/// What libpulse's thread sends: the generation of the context it came
373/// from, and what happened.
374pub(crate) type Message = (u32, Event);
375
376pub(crate) enum Event {
377  /// The context's state changed.
378  State,
379  /// The server changed, maybe its default sink.
380  Server,
381  /// The sink with this index changed.
382  Sink(u32),
383  /// The server's default sink name.
384  Default(Option<String>),
385  /// The server's default source name.
386  DefaultSource(Option<String>),
387  /// A source changed.
388  Source,
389  /// A stream changed.
390  Stream,
391  /// Every sink, read.
392  Sinks(Vec<NodeInfo>),
393  /// Every source but monitors, read.
394  Sources(Vec<NodeInfo>),
395  /// Every stream, read.
396  Streams(Vec<StreamInfo>),
397  /// The sink asked for by name, or `None` for no such sink.
398  Info(Option<Info>),
399  /// The peak meter with this id has peaks to read.
400  Peaks(u64),
401  /// The peak meter with this id changed its state.
402  MeterState(u64),
403  /// A closing peak meter's stream changed its state.
404  Closing,
405  /// The sound with this id changed its state or wants samples.
406  Sound(u64),
407  /// The server played the sound with this id.
408  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      // On the loop's next turn, so `cx.audio()` never waits on libpulse.
429      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  /// Starts libpulse's thread and the first connection. Neither waits
454  /// for the server.
455  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    // From here on, dropping `pulse` stops libpulse's thread.
480    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  /// Connects to the server, or tries again later.
508  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    // The root is gone, and the shell with it.
514    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    // A message from a context that is gone is stale.
525    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  /// Shows the lists as last read, and moves the peak meters to match.
576  fn show_lists(&self, pulse: &mut Pulse) {
577    pulse.show_lists();
578    pulse.sync_meters(&self.meters.borrow());
579  }
580
581  /// Drops the connection, shows no sink and tries again every `retry`
582  /// until `retry_for` has passed since startup, or since a working
583  /// connection dropped. Logs once per outage, not on every try, and
584  /// once on giving up.
585  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    // It was ready, so the server was there: give it a new while.
595    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      // No timer from here on, so audio never wakes the shell again.
606      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  /// Runs `f` from the event loop once, `delay` from now.
614  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
627/// One shell's libpulse objects and what they last told us. It stays on
628/// the main thread: `Mainloop` holds an `Rc`, so the compiler won't let it
629/// go to another.
630struct Pulse {
631  // Declared before `mainloop`, so they drop before it, the streams
632  // before their context.
633  meters: Vec<peaks::Meter>,
634  /// Streams of meters closed before the server made them, waiting to be.
635  closing: Vec<peaks::Recording>,
636  sounds: Vec<sound::Sound>,
637  next_sound: u64,
638  /// This connection's client index, whose own streams, its sounds,
639  /// aren't listed.
640  own_client: Option<u32>,
641  intro: Option<Introspector>,
642  context: Option<Context>,
643  mainloop: Mainloop,
644  /// Shared by every callback. Each `Sender` wakes the loop when it
645  /// drops, so a callback that holds its own would wake the shell when
646  /// libpulse drops it, with nothing to read.
647  sender: Arc<Sender<Message>>,
648  /// Bumped when a context goes, so the messages it left behind are
649  /// dropped.
650  generation: u32,
651  /// The default sink as last read.
652  shown: Option<Info>,
653  /// The default sink as the last command left it, and when that was
654  /// sent. pipewire-pulse answers a read sent right after a set with the
655  /// sink as it was before, so commands build on this instead until a
656  /// read echoes it or [`SETTLE`] passes.
657  asked: Option<(Info, Instant)>,
658  sink: Signal<Option<Sink>>,
659  lists: ListSignals,
660  /// Every sink, source and stream as last read.
661  nodes: Nodes,
662  /// Whether the server is gone and that was logged.
663  down: bool,
664  /// When the service stops trying to connect, if it can't.
665  retry_until: Instant,
666}
667
668/// Every sink, source and stream as libpulse last reported them.
669#[derive(Default)]
670struct Nodes {
671  sinks: Vec<NodeInfo>,
672  sources: Vec<NodeInfo>,
673  streams: Vec<StreamInfo>,
674  default_source: Option<String>,
675}
676
677/// A sink or source as libpulse reported it.
678#[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  /// A sink's monitor: a source, but not one listed.
687  monitor: bool,
688  /// The name of a sink's monitor, which a peak meter records.
689  monitor_source: Option<String>,
690  /// Whether a sink plays: an idle one sends its meters nothing.
691  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/// A sink input as libpulse reported it.
709#[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  /// Paused: it sends its meters nothing.
720  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/// The default sink as libpulse reported it.
743#[derive(Clone, PartialEq)]
744pub(crate) struct Info {
745  index: u32,
746  name: String,
747  volumes: ChannelVolumes,
748  muted: bool,
749}
750
751impl Pulse {
752  /// Makes a context and starts connecting it to `server`, or to
753  /// libpulse's default for `None`.
754  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    // NOAUTOSPAWN: a retry must never start a daemon next to pipewire-pulse.
762    let connected = context.connect(server, FlagSet::NOAUTOSPAWN, None);
763    self.context = Some(context);
764    connected.map_err(|error| format!("{error}"))
765  }
766
767  /// Acts on the context's new state. Once it is ready, subscribes to
768  /// sink and server events and reads the default sink. `Err` when the
769  /// connection failed or ended.
770  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      // Several queued messages can each find it ready.
777      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  /// Runs `call` under the lock if the context is ready, and says
813  /// whether it ran. libpulse returns no operation from a context that
814  /// isn't, and the binding panics on that.
815  fn when_ready(&mut self, call: impl FnOnce(&mut Introspector)) -> bool {
816    self.when_ready_with(|_, intro| call(intro))
817  }
818
819  /// [`when_ready`](Self::when_ready), with the context too.
820  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  /// Asks the server for its default sink's name.
832  fn read_default(&mut self) {
833    let (sender, generation) = (Arc::clone(&self.sender), self.generation);
834    self.when_ready(|intro| {
835      // shortcut: on an error reply libpulse-binding panics on its thread instead of calling
836      // this, and the panic hook prints it raw; logging it needs the C API, so `unsafe`.
837      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  /// Asks for the sink called `name`, or shows none.
850  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  /// Asks for every sink, source and stream.
868  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        // The last list stays.
900        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  /// Shows the lists as last read, capped. Each signal is set only when
954  /// what it shows changed.
955  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    // A sink's monitor isn't a source a person picks, though it can be
993    // the default, as while recording what plays.
994    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  /// Shows `info`, or no sink. The signal is set only when that changes
1090  /// what the bar shows, since every set repaints.
1091  fn show(&mut self, info: Option<Info>) {
1092    // An echo of the last command, or another sink, ends its stand-in.
1093    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  /// What the next command builds on: the last one's result while it
1108  /// stands in, or else the last read.
1109  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  /// Drops the context and shows no sink. `true` when this starts an
1147  /// outage.
1148  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      // Cleared first: disconnecting calls the state callback.
1155      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    // Unlocked, as libpulse asks. Once its thread is gone, the context
1171    // and introspector drop with nothing running beside them.
1172    self.mainloop.stop();
1173  }
1174}
1175
1176impl Info {
1177  /// Copies what we need out of libpulse's `info`, which lives only for
1178  /// the callback. A sink with no name or a bad volume is skipped.
1179  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
1204/// The mainloop's lock, held until this drops. libpulse's thread waits for
1205/// it, so it must be let go even on an early return or a panic.
1206struct 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
1221/// libpulse runs its callbacks on its own thread but doesn't ask for
1222/// `Send`. Wrapping each one in this makes the compiler check it.
1223fn on_pa_thread<F: Send + 'static>(callback: F) -> F {
1224  callback
1225}
1226
1227/// The percent `pactl get-sink-volume` shows for `volume`: 100 is
1228/// `PA_VOLUME_NORM`, and halves round up.
1229fn percent(volume: Volume) -> u32 {
1230  let norm = u64::from(Volume::NORMAL.0);
1231  // At most u32::MAX * 100 / norm, which fits.
1232  ((u64::from(volume.0) * 100 + norm / 2) / norm) as u32
1233}
1234
1235/// `volumes` changed by `delta` percent. Every channel moves by the amount
1236/// that puts their average on the shown percent plus `delta`, kept within
1237/// 0-100%. A channel that would pass 0% or 100% stops there, and then the
1238/// average falls short of that.
1239fn 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    // Within 0..=norm, which fits.
1246    volume.0 = (i64::from(volume.0) + shift).clamp(0, norm) as u32;
1247  }
1248  volumes
1249}
1250
1251/// A sink or source as libpulse reported it, unless it has no name or a
1252/// bad volume.
1253fn 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
1275/// Each channel's percent and position, at most `PA_CHANNELS_MAX` of
1276/// them. A position the map lacks is unknown, so both are as long.
1277fn 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
1291/// Quickshell's name for a PulseAudio channel position.
1292fn channel(position: Position) -> AudioChannel {
1293  use AudioChannel as C;
1294  // Aux0 to Aux31 are numbered in a row.
1295  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
1323/// `volumes` with each channel at its own percent, at most 100, or `None`
1324/// when `percents` doesn't have one per channel.
1325fn 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    // Rounded as pactl sets a percent; at most 100 * norm + 50, which fits.
1332    *volume = Volume(((*percent).min(100) * norm + 50) / 100);
1333  }
1334  Some(volumes)
1335}
1336
1337/// `volumes` moved so their average is `percent`, at most 100, keeping
1338/// the channels' balance as [`changed`] does.
1339fn at(volumes: ChannelVolumes, percent: u32) -> ChannelVolumes {
1340  let shown = self::percent(volumes.avg());
1341  // Both at most a few thousand, which fit.
1342  changed(volumes, percent.min(100) as i32 - shown.min(10_000) as i32)
1343}