1mod pod;
7#[cfg(test)]
8mod tests;
9
10use std::cell::{OnceCell, RefCell, RefMut};
11use std::collections::{BTreeMap, HashMap};
12use std::io::{ErrorKind, Read, Write};
13use std::os::fd::AsFd;
14use std::os::unix::net::UnixStream;
15use std::panic::{self, AssertUnwindSafe, Location};
16use std::path::Path;
17use std::rc::Rc;
18use std::sync::Once;
19
20use calloop::{Interest, RegistrationToken};
21use crabshell_reactive::{Memo, Owner, ReadSignal, Signal};
22use crabshell_ui::{Cx, IntoProp};
23
24use crate::Shared;
25use crate::dbus::set_changed;
26use crate::hyprland::{cut, open};
27use crate::lines::panic_message;
28use pod::{Bad, Builder, Entry, Fields, HEADER, MAX_MESSAGE};
29
30pub(crate) const MAX_OBJECTS: usize = 4096;
32
33const CORE: u32 = 0;
36const CLIENT: u32 = 1;
37const REGISTRY: u32 = 2;
38
39const CORE_VERSION: i32 = 3;
43const REGISTRY_VERSION: i32 = 3;
44const LINK_VERSION: u32 = 3;
45
46const NODE_TYPE: &[u8] = b"PipeWire:Interface:Node";
47const LINK_TYPE: &[u8] = b"PipeWire:Interface:Link";
48
49#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct PwNode {
53 pub id: u32,
56 pub name: String,
58 pub description: String,
60 pub media_class: String,
62 pub is_stream: bool,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub enum PwLinkState {
70 Error,
72 Unlinked,
74 Init,
76 Negotiating,
78 Allocating,
80 Paused,
82 Active,
84}
85
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub struct PwLink {
89 pub id: u32,
91 pub output_node: u32,
93 pub output_port: u32,
95 pub input_node: u32,
97 pub input_port: u32,
99 pub state: PwLinkState,
101}
102
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct PwLinkGroup {
106 pub output_node: u32,
108 pub input_node: u32,
110 pub state: PwLinkState,
112}
113
114#[derive(Clone)]
117pub struct PipeWire {
118 owner: Owner,
121 nodes: ReadSignal<Vec<PwNode>>,
122 links: ReadSignal<Vec<PwLink>>,
123 link_groups: ReadSignal<Vec<PwLinkGroup>>,
124 screencasts: ReadSignal<Vec<PwNode>>,
125 no_links: Memo<Vec<PwLinkGroup>>,
127}
128
129impl PipeWire {
130 pub fn nodes(&self) -> ReadSignal<Vec<PwNode>> {
132 self.nodes
133 }
134
135 pub fn links(&self) -> ReadSignal<Vec<PwLink>> {
137 self.links
138 }
139
140 pub fn link_groups(&self) -> ReadSignal<Vec<PwLinkGroup>> {
142 self.link_groups
143 }
144
145 #[track_caller]
156 pub fn node_links(&self, node: impl IntoProp<u32>) -> Memo<Vec<PwLinkGroup>> {
157 let at = Location::caller();
158 if self.owner.is_disposed() {
159 tracing::warn!(
160 "cx.pipewire().node_links (called at {at}) on a context that is gone gives nothing"
161 );
162 return self.no_links;
163 }
164 let (groups, node) = (self.link_groups, node.into_prop().shared());
165 self.owner.memo(move || {
166 let node = match panic::catch_unwind(AssertUnwindSafe(|| node())) {
167 Ok(node) => node,
168 Err(payload) => {
169 let message = panic_message(payload.as_ref());
170 tracing::error!(
171 "cx.pipewire().node_links (called at {at}) panicked choosing its node: {message}"
172 );
173 return Vec::new();
174 }
175 };
176 groups.with(|groups| {
177 let touches = |group: &&PwLinkGroup| group.output_node == node || group.input_node == node;
178 groups.iter().filter(touches).copied().collect()
179 })
180 })
181 }
182
183 pub fn screencasts(&self) -> ReadSignal<Vec<PwNode>> {
187 self.screencasts
188 }
189}
190
191pub(crate) fn pipewire(cx: &Cx) -> PipeWire {
193 let Some(service) = cx.service::<Service>() else {
194 static LOGGED: Once = Once::new();
195 LOGGED.call_once(|| {
196 tracing::warn!("cx.pipewire() needs the services the shell provides; it shows nothing");
197 });
198 return PipeWire {
199 owner: cx.owner(),
200 nodes: cx.signal(Vec::new()).read_only(),
201 links: cx.signal(Vec::new()).read_only(),
202 link_groups: cx.signal(Vec::new()).read_only(),
203 screencasts: cx.signal(Vec::new()).read_only(),
204 no_links: cx.memo(Vec::new),
205 };
206 };
207 let signals = service.start();
208 let no_links = *service
209 .no_links
210 .get_or_init(|| service.shared.root.memo(Vec::new));
211 PipeWire {
212 owner: cx.owner(),
213 nodes: signals.nodes.read_only(),
214 links: signals.links.read_only(),
215 link_groups: signals.link_groups.read_only(),
216 screencasts: signals.screencasts.read_only(),
217 no_links,
218 }
219}
220
221#[derive(Clone, Copy)]
222struct Signals {
223 nodes: Signal<Vec<PwNode>>,
224 links: Signal<Vec<PwLink>>,
225 link_groups: Signal<Vec<PwLinkGroup>>,
226 screencasts: Signal<Vec<PwNode>>,
227}
228
229pub(crate) struct Service {
231 shared: Rc<Shared>,
232 state: RefCell<Option<State>>,
233 no_links: OnceCell<Memo<Vec<PwLinkGroup>>>,
235}
236
237struct State {
238 signals: Signals,
239 connection: Option<Connection>,
240 reconnected: bool,
243}
244
245struct Connection {
246 stream: UnixStream,
247 reader: RegistrationToken,
248 writer: Option<RegistrationToken>,
250 inbox: Vec<u8>,
252 outbox: Vec<u8>,
253 seq: u32,
255 next_id: u32,
258 free_ids: Vec<u32>,
259 proxies: HashMap<u32, u32>,
261 graph: Graph,
262 opening: Opening,
263 full: bool,
265}
266
267#[derive(PartialEq, Eq)]
269enum Opening {
270 Syncing { seq: i32, bound: bool },
273 Open,
275}
276
277#[derive(Default)]
278struct Graph {
279 nodes: BTreeMap<u32, Node>,
280 links: BTreeMap<u32, Option<PwLink>>,
283}
284
285struct Node {
286 node: PwNode,
287 device: bool,
289}
290
291impl Service {
292 pub(crate) fn new(shared: Rc<Shared>) -> Service {
293 Service {
294 shared,
295 state: RefCell::new(None),
296 no_links: OnceCell::new(),
297 }
298 }
299
300 fn start(self: &Rc<Self>) -> Signals {
302 if self.state.borrow().is_none() {
303 let root = &self.shared.root;
304 let signals = Signals {
305 nodes: root.signal(Vec::new()),
306 links: root.signal(Vec::new()),
307 link_groups: root.signal(Vec::new()),
308 screencasts: root.signal(Vec::new()),
309 };
310 *self.state.borrow_mut() = Some(State {
311 signals,
312 connection: None,
313 reconnected: false,
314 });
315 match &self.shared.config.pipewire {
316 None => tracing::info!("no runtime directory, so there is no PipeWire to show"),
317 Some(path) => {
318 self.connect(path);
319 }
320 }
321 }
322 let state = self.state.borrow();
323 state.as_ref().expect("invariant: started above").signals
324 }
325
326 fn connect(self: &Rc<Self>, path: &Path) -> bool {
330 let Some(event_loop) = self.shared.event_loop() else {
331 return false;
332 };
333 let opened = open(path).and_then(|stream| {
334 let fd = stream.as_fd().try_clone_to_owned()?;
335 Ok((stream, fd))
336 });
337 let (stream, fd) = match opened {
338 Ok(opened) => opened,
339 Err(error) => {
340 let path = path.display();
341 tracing::warn!(%path, %error, "can't connect to PipeWire, so its graph stays empty");
342 return false;
343 }
344 };
345 let service = Rc::clone(self);
346 let Some(reader) =
347 event_loop.insert_fd(fd, Interest::READ, Box::new(move || service.on_readable()))
348 else {
349 return false;
350 };
351 let mut connection = Connection {
352 stream,
353 reader,
354 writer: None,
355 inbox: Vec::new(),
356 outbox: Vec::new(),
357 seq: 0,
358 next_id: REGISTRY + 1,
359 free_ids: Vec::new(),
360 proxies: HashMap::new(),
361 graph: Graph::default(),
362 opening: Opening::Open,
363 full: false,
364 };
365 connection.send(CORE, 1, Builder::default().int(CORE_VERSION));
366 let name = Builder::default()
367 .int(1)
368 .string("application.name")
369 .string("crabshell");
370 connection.send(CLIENT, 2, Builder::default().structure(name));
371 let registry = Builder::default().int(REGISTRY_VERSION).uint(REGISTRY);
372 connection.send(CORE, 5, registry);
373 connection.sync(false);
374 let mut state = self.state.borrow_mut();
375 let state = state
376 .as_mut()
377 .expect("invariant: started before connecting");
378 state.connection = Some(connection);
379 self.flush_with(state);
380 true
381 }
382
383 fn alive(&self) -> bool {
386 let state = self.state.borrow();
387 let alive = state
388 .as_ref()
389 .and_then(|state| state.signals.nodes.try_with(|_| ()));
390 alive.is_some()
391 }
392
393 fn on_readable(self: &Rc<Self>) {
396 if !self.alive() {
397 return self.close();
398 }
399 let mut chunk = [0; 64 * 1024];
400 let mut guard = self.state.borrow_mut();
401 let state = guard
402 .as_mut()
403 .expect("invariant: started before connecting");
404 let Some(connection) = state.connection.as_mut() else {
405 return;
406 };
407 match connection.stream.read(&mut chunk) {
408 Ok(0) => return self.closed(guard, "PipeWire closed the connection"),
409 Ok(read) => connection.inbox.extend_from_slice(&chunk[..read]),
410 Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {
411 return;
412 }
413 Err(error) => return self.closed(guard, &error.to_string()),
414 }
415 let inbox = std::mem::take(&mut connection.inbox);
416 let mut at = 0;
417 while let Some(header) = pod::header(&inbox[at..]) {
418 if header.size > MAX_MESSAGE {
419 return self.lost(state, "PipeWire sent a message over 1 MiB");
421 }
422 let Some(body) = inbox.get(at + HEADER..at + HEADER + header.size) else {
423 break;
424 };
425 at += HEADER + header.size;
426 if connection.opening == Opening::Open {
427 state.reconnected = false;
429 }
430 if let Err(Bad(why)) = connection.take(header.id, header.opcode, body) {
431 let (id, opcode) = (header.id, header.opcode);
432 tracing::warn!(id, opcode, why, "a bad message from PipeWire");
433 }
434 }
435 connection.inbox = inbox[at..].to_vec();
436 if connection.opening == Opening::Open {
437 connection.graph.show(state.signals);
438 }
439 self.flush_with(state);
440 }
441
442 fn flush(self: &Rc<Self>) {
444 if let Some(state) = self.state.borrow_mut().as_mut() {
445 self.flush_with(state);
446 }
447 }
448
449 fn flush_with(self: &Rc<Self>, state: &mut State) {
450 let (Some(connection), Some(event_loop)) =
451 (state.connection.as_mut(), self.shared.event_loop())
452 else {
453 return;
454 };
455 while !connection.outbox.is_empty() {
456 match connection.stream.write(&connection.outbox) {
457 Ok(written) => {
458 connection.outbox.drain(..written);
459 }
460 Err(error) if error.kind() == ErrorKind::Interrupted => {}
461 Err(error) if error.kind() == ErrorKind::WouldBlock => break,
462 Err(error) => {
463 tracing::debug!(%error, "can't write to PipeWire");
465 connection.outbox.clear();
466 }
467 }
468 }
469 if connection.outbox.len() > MAX_MESSAGE {
470 return self.lost(state, "PipeWire reads nothing the shell sends");
471 }
472 if connection.outbox.is_empty() {
473 if let Some(writer) = connection.writer.take() {
474 event_loop.remove(writer);
475 }
476 } else if connection.writer.is_none() {
477 let fd = match connection.stream.as_fd().try_clone_to_owned() {
478 Ok(fd) => fd,
479 Err(error) => return self.lost(state, &error.to_string()),
480 };
481 let service = Rc::clone(self);
482 let write = Box::new(move || service.flush());
483 connection.writer = event_loop.insert_fd(fd, Interest::WRITE, write);
484 }
485 }
486
487 fn closed(self: &Rc<Self>, mut guard: RefMut<'_, Option<State>>, why: &str) {
492 let state = guard
493 .as_mut()
494 .expect("invariant: started before connecting");
495 let path = self.shared.config.pipewire.as_deref();
496 let Some(path) = path.filter(|path| !state.reconnected && path.exists()) else {
497 return self.lost(state, why);
498 };
499 tracing::warn!(why, "PipeWire's connection ended; connecting again");
500 state.reconnected = true;
501 self.drop_connection(state);
502 drop(guard);
503 if !self.connect(path)
504 && let Some(state) = self.state.borrow_mut().as_mut()
505 {
506 self.lost(state, "PipeWire's socket can't be reached again");
507 }
508 }
509
510 fn lost(&self, state: &mut State, why: &str) {
512 tracing::warn!(why, "lost PipeWire; its graph is empty");
513 self.drop_connection(state);
514 Graph::default().show(state.signals);
515 }
516
517 fn close(&self) {
519 if let Some(state) = self.state.borrow_mut().as_mut() {
520 self.drop_connection(state);
521 }
522 }
523
524 fn drop_connection(&self, state: &mut State) {
525 if let (Some(connection), Some(event_loop)) =
526 (state.connection.take(), self.shared.event_loop())
527 {
528 event_loop.remove(connection.reader);
529 if let Some(writer) = connection.writer {
530 event_loop.remove(writer);
531 }
532 }
533 }
534}
535
536impl Connection {
537 fn send(&mut self, id: u32, opcode: u8, fields: Builder) {
538 pod::message(&mut self.outbox, id, opcode, self.seq, &fields.finish());
539 self.seq = self.seq.wrapping_add(1);
540 }
541
542 fn sync(&mut self, bound: bool) {
545 let seq = self.seq.cast_signed();
546 self.send(CORE, 2, Builder::default().uint(CORE).int(seq));
547 self.opening = Opening::Syncing { seq, bound };
548 }
549
550 fn take(&mut self, id: u32, opcode: u8, body: &[u8]) -> Result<(), Bad> {
552 let mut fields = Fields::of(body)?;
553 match (id, opcode) {
554 (CORE, 1) => {
556 let (_, seq) = (fields.uint()?, fields.int()?);
557 if let Opening::Syncing { seq: sent, bound } = self.opening
558 && seq == sent
559 {
560 match bound {
561 true => self.sync(false),
563 false => self.opening = Opening::Open,
564 }
565 }
566 }
567 (CORE, 2) => {
569 let (object, seq) = (fields.uint()?, fields.int()?);
570 self.send(CORE, 3, Builder::default().uint(object).int(seq));
571 }
572 (CORE, 3) => {
573 let (object, _, res) = (fields.uint()?, fields.int()?, fields.int()?);
574 let message = text(fields.text()?.unwrap_or_default());
575 tracing::warn!(object, res, message, "PipeWire sent an error");
576 }
577 (CORE, 4) => {
579 let object = fields.uint()?;
580 if object > REGISTRY && object < self.next_id && !self.free_ids.contains(&object) {
581 self.proxies.remove(&object);
582 self.free_ids.push(object);
583 }
584 }
585 (REGISTRY, 0) => {
587 let (global, _permissions) = (fields.uint()?, fields.int()?);
588 let kind = fields.text()?.unwrap_or_default();
589 let version = fields.uint()?;
590 let props = fields.dict()?;
591 self.global(global, kind, version, &props);
592 }
593 (REGISTRY, 1) => {
595 let global = fields.uint()?;
596 self.graph.nodes.remove(&global);
597 if self.graph.links.remove(&global).is_some() {
598 self.proxies.retain(|_, linked| *linked != global);
599 }
600 }
601 (proxy, 0) if self.proxies.contains_key(&proxy) => {
603 let global = self.proxies[&proxy];
604 let link = PwLink {
605 id: fields.uint()?,
606 output_node: fields.uint()?,
607 output_port: fields.uint()?,
608 input_node: fields.uint()?,
609 input_port: fields.uint()?,
610 state: {
611 let _change_mask = fields.long()?;
612 state(fields.int()?)?
613 },
614 };
615 if link.id != global {
616 return Err(Bad("a link's info for another link"));
617 }
618 if let Some(slot) = self.graph.links.get_mut(&global) {
619 *slot = Some(link);
620 }
621 }
622 _ => {}
624 }
625 Ok(())
626 }
627
628 fn global(&mut self, global: u32, kind: &[u8], version: u32, props: &[Entry<'_>]) {
631 if kind != NODE_TYPE && kind != LINK_TYPE {
632 return;
633 }
634 let known = self.graph.nodes.contains_key(&global) || self.graph.links.contains_key(&global);
635 if !known && self.graph.nodes.len() + self.graph.links.len() >= MAX_OBJECTS {
636 if !std::mem::replace(&mut self.full, true) {
637 tracing::warn!("PipeWire has more nodes and links than the {MAX_OBJECTS} kept");
638 }
639 return;
640 }
641 let prop = |key: &[u8]| {
642 let found = props.iter().find(|(name, _)| *name == key);
643 found.map(|(_, value)| text(value))
644 };
645 if kind == NODE_TYPE {
646 let name = prop(b"node.name").unwrap_or_default();
647 let description = prop(b"node.description")
648 .or_else(|| prop(b"node.nick"))
649 .unwrap_or_else(|| name.clone());
650 let media_class = prop(b"media.class").unwrap_or_default();
651 let node = PwNode {
652 id: global,
653 name,
654 description,
655 is_stream: media_class.starts_with("Stream/"),
656 media_class,
657 };
658 let device = prop(b"device.id").is_some();
659 self.graph.nodes.insert(global, Node { node, device });
660 } else if !known {
661 let proxy = self.free_ids.pop().unwrap_or_else(|| {
662 self.next_id += 1;
663 self.next_id - 1
664 });
665 let bind = Builder::default()
666 .uint(global)
667 .string("PipeWire:Interface:Link")
668 .uint(version.min(LINK_VERSION))
669 .uint(proxy);
670 self.send(REGISTRY, 1, bind);
671 self.proxies.insert(proxy, global);
672 self.graph.links.insert(global, None);
673 if let Opening::Syncing { bound, .. } = &mut self.opening {
674 *bound = true;
675 }
676 }
677 }
678}
679
680impl Graph {
681 fn show(&self, signals: Signals) {
683 let nodes = self.nodes.values().map(|node| node.node.clone()).collect();
684 set_changed(signals.nodes, nodes);
685 let links: Vec<PwLink> = self.links.values().flatten().copied().collect();
686 let mut groups: BTreeMap<(u32, u32), PwLinkState> = BTreeMap::new();
687 for link in &links {
688 let best = groups
689 .entry((link.output_node, link.input_node))
690 .or_insert(link.state);
691 *best = (*best).max(link.state);
692 }
693 let groups: Vec<PwLinkGroup> = groups
694 .into_iter()
695 .map(|((output_node, input_node), state)| PwLinkGroup {
696 output_node,
697 input_node,
698 state,
699 })
700 .collect();
701 let captured = |node: &&Node| {
702 node.node.media_class == "Video/Source"
703 && !node.device
704 && groups.iter().any(|group| group.output_node == node.node.id)
705 };
706 let screencasts = self.nodes.values().filter(captured);
707 set_changed(
708 signals.screencasts,
709 screencasts.map(|node| node.node.clone()).collect(),
710 );
711 set_changed(signals.links, links);
712 set_changed(signals.link_groups, groups);
713 }
714}
715
716fn state(raw: i32) -> Result<PwLinkState, Bad> {
718 Ok(match raw {
719 -2 => PwLinkState::Error,
720 -1 => PwLinkState::Unlinked,
721 0 => PwLinkState::Init,
722 1 => PwLinkState::Negotiating,
723 2 => PwLinkState::Allocating,
724 3 => PwLinkState::Paused,
725 4 => PwLinkState::Active,
726 _ => return Err(Bad("a link state PipeWire doesn't have")),
727 })
728}
729
730fn text(bytes: &[u8]) -> String {
732 cut(String::from_utf8_lossy(bytes).into_owned())
733}