Skip to main content

crabshell_services/
pipewire.rs

1//! PipeWire's graph, its nodes and the links between them, over its
2//! native protocol on the socket `pipewire-0`. The shell says hello,
3//! asks for the registry, which lists every object, and binds each link
4//! for its state. libpulse still carries volume, sinks and meters.
5
6mod 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
30/// The most nodes and links kept together; the rest are left out.
31pub(crate) const MAX_OBJECTS: usize = 4096;
32
33/// The ids the protocol fixes: the core, this client, and the registry,
34/// which the shell names when it asks for it.
35const CORE: u32 = 0;
36const CLIENT: u32 = 1;
37const REGISTRY: u32 = 2;
38
39/// The interfaces' versions spoken: the core's, sent in its hello, and
40/// the registry's and links'. Core 4 only adds an event this client
41/// doesn't read.
42const 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/// One of PipeWire's nodes: a device's sink or source, or a program's
50/// stream.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct PwNode {
53  /// PipeWire's id for it, which the links name: the key to give
54  /// `children_keyed`. A new node may reuse a gone one's id.
55  pub id: u32,
56  /// Its `node.name`, such as `alsa_output.pci-0000_00_1f.3.analog-stereo`.
57  pub name: String,
58  /// Its `node.description`, else its `node.nick`, else its name.
59  pub description: String,
60  /// Its `media.class`, such as `Audio/Sink` or `Stream/Input/Video`.
61  pub media_class: String,
62  /// Whether it is a program's stream: its class starts with `Stream/`.
63  pub is_stream: bool,
64}
65
66/// Where a link is in being set up, as PipeWire says. The order is from
67/// worst to best.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub enum PwLinkState {
70  /// It failed.
71  Error,
72  /// Its ports were unlinked.
73  Unlinked,
74  /// It was just made.
75  Init,
76  /// Its ports are agreeing on a format.
77  Negotiating,
78  /// Its buffers are being made.
79  Allocating,
80  /// It is ready but nothing flows.
81  Paused,
82  /// Data flows through it.
83  Active,
84}
85
86/// A link from one node's output port to another's input port.
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub struct PwLink {
89  /// PipeWire's id for it.
90  pub id: u32,
91  /// The node it goes from.
92  pub output_node: u32,
93  /// The port of `output_node` it goes from.
94  pub output_port: u32,
95  /// The node it goes to.
96  pub input_node: u32,
97  /// The port of `input_node` it goes to.
98  pub input_port: u32,
99  /// Where it is in being set up.
100  pub state: PwLinkState,
101}
102
103/// The links from one node to another, one per channel, as one.
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct PwLinkGroup {
106  /// The node they go from.
107  pub output_node: u32,
108  /// The node they go to.
109  pub input_node: u32,
110  /// The best state among the links.
111  pub state: PwLinkState,
112}
113
114/// The PipeWire service, from `cx.pipewire()`. A clone is cheap and
115/// shares the one connection.
116#[derive(Clone)]
117pub struct PipeWire {
118  /// The asking context's owner, which [`node_links`](Self::node_links)'s
119  /// memos go with.
120  owner: Owner,
121  nodes: ReadSignal<Vec<PwNode>>,
122  links: ReadSignal<Vec<PwLink>>,
123  link_groups: ReadSignal<Vec<PwLinkGroup>>,
124  screencasts: ReadSignal<Vec<PwNode>>,
125  /// Empty and never set, for a tracker on a context that went.
126  no_links: Memo<Vec<PwLinkGroup>>,
127}
128
129impl PipeWire {
130  /// Every node, by id. Empty while PipeWire isn't connected.
131  pub fn nodes(&self) -> ReadSignal<Vec<PwNode>> {
132    self.nodes
133  }
134
135  /// Every link whose state PipeWire has said, by id.
136  pub fn links(&self) -> ReadSignal<Vec<PwLink>> {
137    self.links
138  }
139
140  /// The links folded per output node and input node, by those ids.
141  pub fn link_groups(&self) -> ReadSignal<Vec<PwLinkGroup>> {
142    self.link_groups
143  }
144
145  /// The link groups to or from `node`, as Quickshell's
146  /// `PwNodeLinkTracker`. `node` takes an id or a closure returning one,
147  /// so one tracker follows a changing node.
148  ///
149  /// The memo belongs to the context `cx.pipewire()` was called on, so
150  /// call `cx.pipewire()` inside the row that shows it, and the memo goes
151  /// with the row. A panic in the closure is logged with where
152  /// `node_links` was called and gives no groups until what it read
153  /// changes. Called on a handle whose context went, it logs that and
154  /// gives no groups.
155  #[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  /// The video sources a program made, such as a screen-share portal's,
184  /// that another node captures: a `Video/Source` node with no
185  /// `device.id`, so not a camera, linked to at least one node.
186  pub fn screencasts(&self) -> ReadSignal<Vec<PwNode>> {
187    self.screencasts
188  }
189}
190
191/// `cx.pipewire()`.
192pub(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
229/// The one PipeWire connection of a shell, started on first use.
230pub(crate) struct Service {
231  shared: Rc<Shared>,
232  state: RefCell<Option<State>>,
233  /// What a tracker on a context that went gives, made with the signals.
234  no_links: OnceCell<Memo<Vec<PwLinkGroup>>>,
235}
236
237struct State {
238  signals: Signals,
239  connection: Option<Connection>,
240  /// Whether the shell connected again since PipeWire last sent anything
241  /// past the graph it gives a new client.
242  reconnected: bool,
243}
244
245struct Connection {
246  stream: UnixStream,
247  reader: RegistrationToken,
248  /// Waits for room in the socket while it holds back part of `outbox`.
249  writer: Option<RegistrationToken>,
250  /// What was read past the last whole message.
251  inbox: Vec<u8>,
252  outbox: Vec<u8>,
253  /// The next message's sequence number.
254  seq: u32,
255  /// The next proxy id never used, and those PipeWire gave back. PipeWire
256  /// takes a new id only if it is one of those or the next.
257  next_id: u32,
258  free_ids: Vec<u32>,
259  /// Each bound link's proxy id, to its global id.
260  proxies: HashMap<u32, u32>,
261  graph: Graph,
262  opening: Opening,
263  /// Whether the cap on objects was logged.
264  full: bool,
265}
266
267/// How far the graph PipeWire gives a new client has come.
268#[derive(PartialEq, Eq)]
269enum Opening {
270  /// Waiting for the answer to the sync numbered this. `bound` says a link
271  /// was bound since it was sent, whose info would come after it.
272  Syncing { seq: i32, bound: bool },
273  /// All of it came, so it shows.
274  Open,
275}
276
277#[derive(Default)]
278struct Graph {
279  nodes: BTreeMap<u32, Node>,
280  /// Every link the registry listed, by global id, with what its info
281  /// said once it came.
282  links: BTreeMap<u32, Option<PwLink>>,
283}
284
285struct Node {
286  node: PwNode,
287  /// Whether a device made it, as a camera's or a sound card's.
288  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  /// The signals, connecting to PipeWire if this is the first ask.
301  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  /// Connects and asks for the graph. A failure is logged and never
327  /// retried, so a stale socket never wakes the shell. `false` if it
328  /// failed.
329  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  /// Whether the signals are still there: their owner, the root, isn't
384  /// disposed.
385  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  /// Reads what came, takes in each whole message, answers what needs an
394  /// answer, and shows the graph once all of it has come.
395  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        // Reconnecting would only read it again.
420        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        // Past the graph, so a later close is worth a reconnect.
428        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  /// Writes what the socket takes, and waits for room for the rest.
443  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          // PipeWire went; reading sees it end, and decides what follows.
464          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  /// The connection ended for `why`. While the socket is there, this
488  /// connects once again and keeps the graph shown until the new one has
489  /// come. A connection that ends again before PipeWire sent anything
490  /// past its graph is lost.
491  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  /// Drops the connection and empties the graph.
511  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  /// Closes the connection for good, once the signals are gone.
518  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  /// Asks the core to answer once everything sent before has been
543  /// handled.
544  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  /// Takes in one message for the object `id`.
551  fn take(&mut self, id: u32, opcode: u8, body: &[u8]) -> Result<(), Bad> {
552    let mut fields = Fields::of(body)?;
553    match (id, opcode) {
554      // Done, the answer to a sync.
555      (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            // Their infos come before the answer to a sync sent now.
562            true => self.sync(false),
563            false => self.opening = Opening::Open,
564          }
565        }
566      }
567      // Ping, answered with a pong.
568      (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      // RemoveId: PipeWire let go of a proxy, so its id may be reused.
578      (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      // Global.
586      (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      // GlobalRemove.
594      (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      // A bound link's info.
602      (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      // The core's and this client's infos, and what else comes.
623      _ => {}
624    }
625    Ok(())
626  }
627
628  /// Takes in a global the registry announced: a node is kept, a link
629  /// bound for its info, and anything else skipped.
630  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  /// Sets each signal whose value changed.
682  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
716/// A link's state as PipeWire numbers it.
717fn 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
730/// A text from PipeWire, cut to 4 KiB.
731fn text(bytes: &[u8]) -> String {
732  cut(String::from_utf8_lossy(bytes).into_owned())
733}