i3status_rs/blocks/sound/
pipewire.rs

1use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
2
3use super::*;
4use crate::pipewire::{CLIENT, CommandKind, EventKind, PwSender};
5
6pub(super) struct Device {
7    device_kind: DeviceKind,
8    match_name: Option<String>,
9    id: Option<u32>,
10    name: String,
11    description: Option<String>,
12    active_port: Option<String>,
13    form_factor: Option<String>,
14    volume: Vec<f32>,
15    volume_avg: u32,
16    muted: bool,
17    updates: UnboundedReceiver<EventKind>,
18    command_sender: PwSender<CommandKind>,
19}
20
21impl Device {
22    pub(super) async fn new(device_kind: DeviceKind, match_name: Option<String>) -> Result<Self> {
23        let client = CLIENT.as_ref().error("Could not get client")?;
24
25        let (tx, rx) = unbounded_channel();
26        client.add_event_listener(tx);
27        let command_sender = client.add_command_listener();
28        let mut s = Self {
29            device_kind,
30            match_name,
31            id: None,
32            name: "".into(),
33            description: None,
34            active_port: None,
35            form_factor: None,
36            volume: Vec::new(),
37            volume_avg: 0,
38            muted: false,
39            updates: rx,
40            command_sender,
41        };
42        s.get_info().await?;
43        Ok(s)
44    }
45}
46
47#[async_trait]
48impl SoundDevice for Device {
49    fn volume(&self) -> u32 {
50        self.volume_avg
51    }
52
53    fn muted(&self) -> bool {
54        self.muted
55    }
56
57    fn output_name(&self) -> String {
58        self.name.clone()
59    }
60
61    fn output_description(&self) -> Option<String> {
62        self.description.clone()
63    }
64
65    fn active_port(&self) -> Option<String> {
66        self.active_port.clone()
67    }
68
69    fn form_factor(&self) -> Option<&str> {
70        self.form_factor.as_deref()
71    }
72
73    async fn get_info(&mut self) -> Result<()> {
74        let client = CLIENT.as_ref().error("Could not get client")?;
75        let data = client.data.lock().unwrap();
76
77        let name = if self.match_name.is_some() {
78            // If name is specified in the config, then match that node
79            &self.match_name
80        } else {
81            // Otherwise use the default metadata to determine the node name
82            match self.device_kind {
83                DeviceKind::Sink => &data.default_metadata.sink,
84                DeviceKind::Source => &data.default_metadata.source,
85            }
86        };
87
88        let Some(name) = name else {
89            //Metadata may not be ready yet
90            return Ok(());
91        };
92
93        if let Some((id, node)) = data.nodes.iter().find(|(_, node)| node.name == *name) {
94            self.id = Some(*id);
95            if let Some(volume) = &node.volume {
96                self.volume = volume.clone();
97                self.volume_avg = (volume.iter().sum::<f32>() / volume.len() as f32).round() as u32;
98            }
99            if let Some(muted) = node.muted {
100                self.muted = muted;
101            }
102            self.name = node.name.clone();
103            self.description = node.description.clone();
104            self.form_factor = node.form_factor.clone();
105
106            if let Some(device_id) = node.device_id
107                && let Some(direction) = node.direction
108                && let Some(directed_routes) = data.directed_routes.get(&device_id)
109                && let Some(route) = directed_routes.get_route(direction)
110            {
111                self.active_port = Some(route.name.clone());
112            }
113        } else {
114            self.id = None;
115        }
116
117        Ok(())
118    }
119
120    async fn set_volume(&mut self, step: i32, max_vol: Option<u32>) -> Result<()> {
121        if let Some(id) = self.id {
122            let volume = self
123                .volume
124                .iter()
125                .map(|&vol| {
126                    let uncapped_vol = 0_f32.max(vol + step as f32);
127                    if let Some(vol_cap) = max_vol {
128                        uncapped_vol.min(vol_cap as f32)
129                    } else {
130                        uncapped_vol
131                    }
132                })
133                .collect();
134
135            self.command_sender
136                .send(CommandKind::SetVolume(id, volume))
137                .map_err(|_| Error::new("Could not set volume"))?;
138        }
139        Ok(())
140    }
141
142    async fn toggle(&mut self) -> Result<()> {
143        if let Some(id) = self.id {
144            self.command_sender
145                .send(CommandKind::Mute(id, !self.muted))
146                .map_err(|_| Error::new("Could not toggle mute"))?;
147        }
148        Ok(())
149    }
150
151    async fn wait_for_update(&mut self) -> Result<()> {
152        while let Some(event) = self.updates.recv().await {
153            if event.intersects(
154                EventKind::DEFAULT_META_DATA_UPDATED
155                    | EventKind::DEVICE_ADDED
156                    | EventKind::DEVICE_PARAM_UPDATE
157                    | EventKind::DEVICE_REMOVED
158                    | EventKind::NODE_PARAM_UPDATE
159                    | EventKind::NODE_STATE_UPDATE
160                    | EventKind::PORT_ADDED
161                    | EventKind::PORT_REMOVED,
162            ) {
163                break;
164            }
165        }
166        Ok(())
167    }
168}