mod pod;
#[cfg(test)]
mod tests;
use std::cell::{OnceCell, RefCell, RefMut};
use std::collections::{BTreeMap, HashMap};
use std::io::{ErrorKind, Read, Write};
use std::os::fd::AsFd;
use std::os::unix::net::UnixStream;
use std::panic::{self, AssertUnwindSafe, Location};
use std::path::Path;
use std::rc::Rc;
use std::sync::Once;
use calloop::{Interest, RegistrationToken};
use crabshell_reactive::{Memo, Owner, ReadSignal, Signal};
use crabshell_ui::{Cx, IntoProp};
use crate::Shared;
use crate::dbus::set_changed;
use crate::hyprland::{cut, open};
use crate::lines::panic_message;
use pod::{Bad, Builder, Entry, Fields, HEADER, MAX_MESSAGE};
pub(crate) const MAX_OBJECTS: usize = 4096;
const CORE: u32 = 0;
const CLIENT: u32 = 1;
const REGISTRY: u32 = 2;
const CORE_VERSION: i32 = 3;
const REGISTRY_VERSION: i32 = 3;
const LINK_VERSION: u32 = 3;
const NODE_TYPE: &[u8] = b"PipeWire:Interface:Node";
const LINK_TYPE: &[u8] = b"PipeWire:Interface:Link";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PwNode {
pub id: u32,
pub name: String,
pub description: String,
pub media_class: String,
pub is_stream: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PwLinkState {
Error,
Unlinked,
Init,
Negotiating,
Allocating,
Paused,
Active,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PwLink {
pub id: u32,
pub output_node: u32,
pub output_port: u32,
pub input_node: u32,
pub input_port: u32,
pub state: PwLinkState,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PwLinkGroup {
pub output_node: u32,
pub input_node: u32,
pub state: PwLinkState,
}
#[derive(Clone)]
pub struct PipeWire {
owner: Owner,
nodes: ReadSignal<Vec<PwNode>>,
links: ReadSignal<Vec<PwLink>>,
link_groups: ReadSignal<Vec<PwLinkGroup>>,
screencasts: ReadSignal<Vec<PwNode>>,
no_links: Memo<Vec<PwLinkGroup>>,
}
impl PipeWire {
pub fn nodes(&self) -> ReadSignal<Vec<PwNode>> {
self.nodes
}
pub fn links(&self) -> ReadSignal<Vec<PwLink>> {
self.links
}
pub fn link_groups(&self) -> ReadSignal<Vec<PwLinkGroup>> {
self.link_groups
}
#[track_caller]
pub fn node_links(&self, node: impl IntoProp<u32>) -> Memo<Vec<PwLinkGroup>> {
let at = Location::caller();
if self.owner.is_disposed() {
tracing::warn!(
"cx.pipewire().node_links (called at {at}) on a context that is gone gives nothing"
);
return self.no_links;
}
let (groups, node) = (self.link_groups, node.into_prop().shared());
self.owner.memo(move || {
let node = match panic::catch_unwind(AssertUnwindSafe(|| node())) {
Ok(node) => node,
Err(payload) => {
let message = panic_message(payload.as_ref());
tracing::error!(
"cx.pipewire().node_links (called at {at}) panicked choosing its node: {message}"
);
return Vec::new();
}
};
groups.with(|groups| {
let touches = |group: &&PwLinkGroup| group.output_node == node || group.input_node == node;
groups.iter().filter(touches).copied().collect()
})
})
}
pub fn screencasts(&self) -> ReadSignal<Vec<PwNode>> {
self.screencasts
}
}
pub(crate) fn pipewire(cx: &Cx) -> PipeWire {
let Some(service) = cx.service::<Service>() else {
static LOGGED: Once = Once::new();
LOGGED.call_once(|| {
tracing::warn!("cx.pipewire() needs the services the shell provides; it shows nothing");
});
return PipeWire {
owner: cx.owner(),
nodes: cx.signal(Vec::new()).read_only(),
links: cx.signal(Vec::new()).read_only(),
link_groups: cx.signal(Vec::new()).read_only(),
screencasts: cx.signal(Vec::new()).read_only(),
no_links: cx.memo(Vec::new),
};
};
let signals = service.start();
let no_links = *service
.no_links
.get_or_init(|| service.shared.root.memo(Vec::new));
PipeWire {
owner: cx.owner(),
nodes: signals.nodes.read_only(),
links: signals.links.read_only(),
link_groups: signals.link_groups.read_only(),
screencasts: signals.screencasts.read_only(),
no_links,
}
}
#[derive(Clone, Copy)]
struct Signals {
nodes: Signal<Vec<PwNode>>,
links: Signal<Vec<PwLink>>,
link_groups: Signal<Vec<PwLinkGroup>>,
screencasts: Signal<Vec<PwNode>>,
}
pub(crate) struct Service {
shared: Rc<Shared>,
state: RefCell<Option<State>>,
no_links: OnceCell<Memo<Vec<PwLinkGroup>>>,
}
struct State {
signals: Signals,
connection: Option<Connection>,
reconnected: bool,
}
struct Connection {
stream: UnixStream,
reader: RegistrationToken,
writer: Option<RegistrationToken>,
inbox: Vec<u8>,
outbox: Vec<u8>,
seq: u32,
next_id: u32,
free_ids: Vec<u32>,
proxies: HashMap<u32, u32>,
graph: Graph,
opening: Opening,
full: bool,
}
#[derive(PartialEq, Eq)]
enum Opening {
Syncing { seq: i32, bound: bool },
Open,
}
#[derive(Default)]
struct Graph {
nodes: BTreeMap<u32, Node>,
links: BTreeMap<u32, Option<PwLink>>,
}
struct Node {
node: PwNode,
device: bool,
}
impl Service {
pub(crate) fn new(shared: Rc<Shared>) -> Service {
Service {
shared,
state: RefCell::new(None),
no_links: OnceCell::new(),
}
}
fn start(self: &Rc<Self>) -> Signals {
if self.state.borrow().is_none() {
let root = &self.shared.root;
let signals = Signals {
nodes: root.signal(Vec::new()),
links: root.signal(Vec::new()),
link_groups: root.signal(Vec::new()),
screencasts: root.signal(Vec::new()),
};
*self.state.borrow_mut() = Some(State {
signals,
connection: None,
reconnected: false,
});
match &self.shared.config.pipewire {
None => tracing::info!("no runtime directory, so there is no PipeWire to show"),
Some(path) => {
self.connect(path);
}
}
}
let state = self.state.borrow();
state.as_ref().expect("invariant: started above").signals
}
fn connect(self: &Rc<Self>, path: &Path) -> bool {
let Some(event_loop) = self.shared.event_loop() else {
return false;
};
let opened = open(path).and_then(|stream| {
let fd = stream.as_fd().try_clone_to_owned()?;
Ok((stream, fd))
});
let (stream, fd) = match opened {
Ok(opened) => opened,
Err(error) => {
let path = path.display();
tracing::warn!(%path, %error, "can't connect to PipeWire, so its graph stays empty");
return false;
}
};
let service = Rc::clone(self);
let Some(reader) =
event_loop.insert_fd(fd, Interest::READ, Box::new(move || service.on_readable()))
else {
return false;
};
let mut connection = Connection {
stream,
reader,
writer: None,
inbox: Vec::new(),
outbox: Vec::new(),
seq: 0,
next_id: REGISTRY + 1,
free_ids: Vec::new(),
proxies: HashMap::new(),
graph: Graph::default(),
opening: Opening::Open,
full: false,
};
connection.send(CORE, 1, Builder::default().int(CORE_VERSION));
let name = Builder::default()
.int(1)
.string("application.name")
.string("crabshell");
connection.send(CLIENT, 2, Builder::default().structure(name));
let registry = Builder::default().int(REGISTRY_VERSION).uint(REGISTRY);
connection.send(CORE, 5, registry);
connection.sync(false);
let mut state = self.state.borrow_mut();
let state = state
.as_mut()
.expect("invariant: started before connecting");
state.connection = Some(connection);
self.flush_with(state);
true
}
fn alive(&self) -> bool {
let state = self.state.borrow();
let alive = state
.as_ref()
.and_then(|state| state.signals.nodes.try_with(|_| ()));
alive.is_some()
}
fn on_readable(self: &Rc<Self>) {
if !self.alive() {
return self.close();
}
let mut chunk = [0; 64 * 1024];
let mut guard = self.state.borrow_mut();
let state = guard
.as_mut()
.expect("invariant: started before connecting");
let Some(connection) = state.connection.as_mut() else {
return;
};
match connection.stream.read(&mut chunk) {
Ok(0) => return self.closed(guard, "PipeWire closed the connection"),
Ok(read) => connection.inbox.extend_from_slice(&chunk[..read]),
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {
return;
}
Err(error) => return self.closed(guard, &error.to_string()),
}
let inbox = std::mem::take(&mut connection.inbox);
let mut at = 0;
while let Some(header) = pod::header(&inbox[at..]) {
if header.size > MAX_MESSAGE {
return self.lost(state, "PipeWire sent a message over 1 MiB");
}
let Some(body) = inbox.get(at + HEADER..at + HEADER + header.size) else {
break;
};
at += HEADER + header.size;
if connection.opening == Opening::Open {
state.reconnected = false;
}
if let Err(Bad(why)) = connection.take(header.id, header.opcode, body) {
let (id, opcode) = (header.id, header.opcode);
tracing::warn!(id, opcode, why, "a bad message from PipeWire");
}
}
connection.inbox = inbox[at..].to_vec();
if connection.opening == Opening::Open {
connection.graph.show(state.signals);
}
self.flush_with(state);
}
fn flush(self: &Rc<Self>) {
if let Some(state) = self.state.borrow_mut().as_mut() {
self.flush_with(state);
}
}
fn flush_with(self: &Rc<Self>, state: &mut State) {
let (Some(connection), Some(event_loop)) =
(state.connection.as_mut(), self.shared.event_loop())
else {
return;
};
while !connection.outbox.is_empty() {
match connection.stream.write(&connection.outbox) {
Ok(written) => {
connection.outbox.drain(..written);
}
Err(error) if error.kind() == ErrorKind::Interrupted => {}
Err(error) if error.kind() == ErrorKind::WouldBlock => break,
Err(error) => {
tracing::debug!(%error, "can't write to PipeWire");
connection.outbox.clear();
}
}
}
if connection.outbox.len() > MAX_MESSAGE {
return self.lost(state, "PipeWire reads nothing the shell sends");
}
if connection.outbox.is_empty() {
if let Some(writer) = connection.writer.take() {
event_loop.remove(writer);
}
} else if connection.writer.is_none() {
let fd = match connection.stream.as_fd().try_clone_to_owned() {
Ok(fd) => fd,
Err(error) => return self.lost(state, &error.to_string()),
};
let service = Rc::clone(self);
let write = Box::new(move || service.flush());
connection.writer = event_loop.insert_fd(fd, Interest::WRITE, write);
}
}
fn closed(self: &Rc<Self>, mut guard: RefMut<'_, Option<State>>, why: &str) {
let state = guard
.as_mut()
.expect("invariant: started before connecting");
let path = self.shared.config.pipewire.as_deref();
let Some(path) = path.filter(|path| !state.reconnected && path.exists()) else {
return self.lost(state, why);
};
tracing::warn!(why, "PipeWire's connection ended; connecting again");
state.reconnected = true;
self.drop_connection(state);
drop(guard);
if !self.connect(path)
&& let Some(state) = self.state.borrow_mut().as_mut()
{
self.lost(state, "PipeWire's socket can't be reached again");
}
}
fn lost(&self, state: &mut State, why: &str) {
tracing::warn!(why, "lost PipeWire; its graph is empty");
self.drop_connection(state);
Graph::default().show(state.signals);
}
fn close(&self) {
if let Some(state) = self.state.borrow_mut().as_mut() {
self.drop_connection(state);
}
}
fn drop_connection(&self, state: &mut State) {
if let (Some(connection), Some(event_loop)) =
(state.connection.take(), self.shared.event_loop())
{
event_loop.remove(connection.reader);
if let Some(writer) = connection.writer {
event_loop.remove(writer);
}
}
}
}
impl Connection {
fn send(&mut self, id: u32, opcode: u8, fields: Builder) {
pod::message(&mut self.outbox, id, opcode, self.seq, &fields.finish());
self.seq = self.seq.wrapping_add(1);
}
fn sync(&mut self, bound: bool) {
let seq = self.seq.cast_signed();
self.send(CORE, 2, Builder::default().uint(CORE).int(seq));
self.opening = Opening::Syncing { seq, bound };
}
fn take(&mut self, id: u32, opcode: u8, body: &[u8]) -> Result<(), Bad> {
let mut fields = Fields::of(body)?;
match (id, opcode) {
(CORE, 1) => {
let (_, seq) = (fields.uint()?, fields.int()?);
if let Opening::Syncing { seq: sent, bound } = self.opening
&& seq == sent
{
match bound {
true => self.sync(false),
false => self.opening = Opening::Open,
}
}
}
(CORE, 2) => {
let (object, seq) = (fields.uint()?, fields.int()?);
self.send(CORE, 3, Builder::default().uint(object).int(seq));
}
(CORE, 3) => {
let (object, _, res) = (fields.uint()?, fields.int()?, fields.int()?);
let message = text(fields.text()?.unwrap_or_default());
tracing::warn!(object, res, message, "PipeWire sent an error");
}
(CORE, 4) => {
let object = fields.uint()?;
if object > REGISTRY && object < self.next_id && !self.free_ids.contains(&object) {
self.proxies.remove(&object);
self.free_ids.push(object);
}
}
(REGISTRY, 0) => {
let (global, _permissions) = (fields.uint()?, fields.int()?);
let kind = fields.text()?.unwrap_or_default();
let version = fields.uint()?;
let props = fields.dict()?;
self.global(global, kind, version, &props);
}
(REGISTRY, 1) => {
let global = fields.uint()?;
self.graph.nodes.remove(&global);
if self.graph.links.remove(&global).is_some() {
self.proxies.retain(|_, linked| *linked != global);
}
}
(proxy, 0) if self.proxies.contains_key(&proxy) => {
let global = self.proxies[&proxy];
let link = PwLink {
id: fields.uint()?,
output_node: fields.uint()?,
output_port: fields.uint()?,
input_node: fields.uint()?,
input_port: fields.uint()?,
state: {
let _change_mask = fields.long()?;
state(fields.int()?)?
},
};
if link.id != global {
return Err(Bad("a link's info for another link"));
}
if let Some(slot) = self.graph.links.get_mut(&global) {
*slot = Some(link);
}
}
_ => {}
}
Ok(())
}
fn global(&mut self, global: u32, kind: &[u8], version: u32, props: &[Entry<'_>]) {
if kind != NODE_TYPE && kind != LINK_TYPE {
return;
}
let known = self.graph.nodes.contains_key(&global) || self.graph.links.contains_key(&global);
if !known && self.graph.nodes.len() + self.graph.links.len() >= MAX_OBJECTS {
if !std::mem::replace(&mut self.full, true) {
tracing::warn!("PipeWire has more nodes and links than the {MAX_OBJECTS} kept");
}
return;
}
let prop = |key: &[u8]| {
let found = props.iter().find(|(name, _)| *name == key);
found.map(|(_, value)| text(value))
};
if kind == NODE_TYPE {
let name = prop(b"node.name").unwrap_or_default();
let description = prop(b"node.description")
.or_else(|| prop(b"node.nick"))
.unwrap_or_else(|| name.clone());
let media_class = prop(b"media.class").unwrap_or_default();
let node = PwNode {
id: global,
name,
description,
is_stream: media_class.starts_with("Stream/"),
media_class,
};
let device = prop(b"device.id").is_some();
self.graph.nodes.insert(global, Node { node, device });
} else if !known {
let proxy = self.free_ids.pop().unwrap_or_else(|| {
self.next_id += 1;
self.next_id - 1
});
let bind = Builder::default()
.uint(global)
.string("PipeWire:Interface:Link")
.uint(version.min(LINK_VERSION))
.uint(proxy);
self.send(REGISTRY, 1, bind);
self.proxies.insert(proxy, global);
self.graph.links.insert(global, None);
if let Opening::Syncing { bound, .. } = &mut self.opening {
*bound = true;
}
}
}
}
impl Graph {
fn show(&self, signals: Signals) {
let nodes = self.nodes.values().map(|node| node.node.clone()).collect();
set_changed(signals.nodes, nodes);
let links: Vec<PwLink> = self.links.values().flatten().copied().collect();
let mut groups: BTreeMap<(u32, u32), PwLinkState> = BTreeMap::new();
for link in &links {
let best = groups
.entry((link.output_node, link.input_node))
.or_insert(link.state);
*best = (*best).max(link.state);
}
let groups: Vec<PwLinkGroup> = groups
.into_iter()
.map(|((output_node, input_node), state)| PwLinkGroup {
output_node,
input_node,
state,
})
.collect();
let captured = |node: &&Node| {
node.node.media_class == "Video/Source"
&& !node.device
&& groups.iter().any(|group| group.output_node == node.node.id)
};
let screencasts = self.nodes.values().filter(captured);
set_changed(
signals.screencasts,
screencasts.map(|node| node.node.clone()).collect(),
);
set_changed(signals.links, links);
set_changed(signals.link_groups, groups);
}
}
fn state(raw: i32) -> Result<PwLinkState, Bad> {
Ok(match raw {
-2 => PwLinkState::Error,
-1 => PwLinkState::Unlinked,
0 => PwLinkState::Init,
1 => PwLinkState::Negotiating,
2 => PwLinkState::Allocating,
3 => PwLinkState::Paused,
4 => PwLinkState::Active,
_ => return Err(Bad("a link state PipeWire doesn't have")),
})
}
fn text(bytes: &[u8]) -> String {
cut(String::from_utf8_lossy(bytes).into_owned())
}