9 changed files with 837 additions and 289 deletions
Generated
+674 -86
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -34,9 +34,9 @@ ureq = { version = "3", default-features = false, features = ["rustls"] }
toml = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] }
eframe = { version = "0.34.2", default-features = false, features = ["glow", "default_fonts", "wayland", "x11"], optional = true }
# Desktop notifications on viewer join/leave. Default features give the
# pure-Rust zbus backend (no system libdbus, no image crate).
notify-rust = { version = "4", optional = true }
tray-icon = { version = "0.24.0", optional = true }
notify-rust = { version = "4.17.0", optional = true }
gtk = { version = "0.18.2", optional = true }
[profile.release]
lto = "thin"
@@ -46,4 +46,4 @@ strip = "symbols"
[features]
# Opt-in graphical front-end (pixelpass --gui). Default-off so the headless
# build never pulls the GUI toolkit tree.
gui = ["dep:eframe", "dep:notify-rust"]
gui = ["dep:eframe", "dep:tray-icon", "dep:notify-rust", "dep:gtk"]
+2 -3
View File
@@ -83,9 +83,8 @@ pixelpass --gui
```
Host: pick quality / max-viewers / options, click **Start hosting**, and the
share code appears with a copy button. Connected viewers are listed with a
**Kick** button each, and a desktop notification fires as they join or leave.
View: paste a code, pick mpv or VLC, click **Connect** and the player launches.
share code appears with a copy button alongside a live viewer count. View:
paste a code, pick mpv or VLC, click **Connect** and the player launches.
The window is a thin driver — it runs the same headless `pixelpass` as a
child process and reads its event stream, so the GUI is purely additive and
+5 -2
View File
@@ -37,15 +37,18 @@ pub struct BandwidthEntry {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum BandwidthStatus {
#[default]
Unmeasured,
Measured,
Skipped,
Failed,
}
impl Default for BandwidthStatus {
fn default() -> Self {
Self::Unmeasured
}
}
fn default_status() -> BandwidthStatus {
BandwidthStatus::Unmeasured
+3 -9
View File
@@ -22,11 +22,7 @@ pub fn set_json(enabled: bool) {
JSON_ENABLED.store(enabled, Ordering::Relaxed);
}
/// Whether the JSON event stream is on — i.e. we're being driven by a
/// machine front-end (the `--gui` shell-out) rather than a human terminal.
/// Gates features that only make sense under that front-end, like the
/// stdin command channel the host reads `kick` requests from.
pub fn json_enabled() -> bool {
fn json_enabled() -> bool {
JSON_ENABLED.load(Ordering::Relaxed)
}
@@ -46,11 +42,9 @@ pub enum Event<'a> {
max_viewers: u32,
max_viewers_source: &'a str,
},
/// A viewer joined. `id` is the viewer's endpoint id; `active` is the new
/// total after the join.
/// A new viewer joined.
ViewerJoined { id: &'a str, active: u32, max: u32 },
/// A viewer left — disconnected on their own or kicked by the host. `id`
/// is the viewer's endpoint id; `active` is the new total after.
/// A viewer disconnected.
ViewerLeft { id: &'a str, active: u32, max: u32 },
/// Capture pipeline lifecycle (spawned on first viewer, torn down on last).
Capture { state: CaptureState },
+37 -52
View File
@@ -6,8 +6,8 @@
//! egui app drains each frame. stderr is captured into a small ring so a
//! failed launch (e.g. a missing gst plugin) can be surfaced in the window.
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -66,14 +66,10 @@ pub enum CaptureState {
const STDERR_TAIL_MAX: usize = 60;
pub struct ChildProc {
/// `Some` while the child is owned here; `Drop` takes it to hand off to a
/// detached reaper thread (see the `Drop` impl).
child: Option<Child>,
child: Child,
pub rx: Receiver<ChildEvent>,
stderr_tail: Arc<Mutex<Vec<String>>>,
/// Write end of the child's stdin, for the line-based command channel
/// (see [`ChildProc::send_command`]). `None` once it's been closed.
stdin: Option<ChildStdin>,
stdin: std::process::ChildStdin,
}
impl ChildProc {
@@ -83,15 +79,13 @@ impl ChildProc {
let exe = std::env::current_exe()?;
let mut child = Command::new(exe)
.args(args)
// Piped so we can send line commands (e.g. `kick <id>`); the host
// only reads it when driven this way (`--output json`).
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdin = child.stdin.take();
let (tx, rx) = std::sync::mpsc::channel();
let stdin = child.stdin.take().expect("stdin piped");
let stdout = child.stdout.take().expect("stdout piped");
std::thread::spawn(move || {
let reader = BufReader::new(stdout);
@@ -125,64 +119,55 @@ impl ChildProc {
});
Ok(Self {
child: Some(child),
child,
rx,
stderr_tail,
stdin,
})
}
/// Send one newline-terminated command to the child over its stdin (the
/// host parses these as `kick <endpoint-id>`). Best-effort: a closed pipe
/// (child already gone) just drops the command.
pub fn send_command(&mut self, cmd: &str) {
let Some(stdin) = self.stdin.as_mut() else {
return;
};
if let Err(e) = writeln!(stdin, "{cmd}") {
tracing::warn!("failed to send command to host child: {e}");
self.stdin = None; // pipe is dead; stop trying
}
}
/// Whether the child is still running.
pub fn is_alive(&mut self) -> bool {
matches!(self.child.as_mut().map(Child::try_wait), Some(Ok(None)))
matches!(self.child.try_wait(), Ok(None))
}
/// The last captured stderr lines, joined — for error display.
pub fn stderr_tail(&self) -> String {
self.stderr_tail.lock().unwrap().join("\n")
}
/// Send a newline-terminated command to the child.
pub fn send_command(&mut self, cmd: &str) {
use std::io::Write;
if let Err(e) = writeln!(self.stdin, "{cmd}") {
tracing::warn!("failed to send command to child: {e}");
}
}
/// Gracefully stop the child: SIGINT (so the host runs its ctrl-c teardown
/// — tears down capture, closes the endpoint), with a ~2 s grace period
/// before a hard kill. Idempotent.
pub fn stop(&mut self) {
if matches!(self.child.try_wait(), Ok(Some(_))) {
return; // already exited
}
let _ = kill(Pid::from_raw(self.child.id() as i32), Signal::SIGINT);
for _ in 0..40 {
if matches!(self.child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = self.child.kill();
let _ = self.child.wait();
}
}
impl Drop for ChildProc {
fn drop(&mut self) {
// Leaving a host/viewer screen, or closing the window, must not orphan
// a live child — but it must also not *block*. eframe runs this drop
// synchronously while it destroys the window, so a grace-period wait
// here freezes the window mid-close: the first click looks like it did
// nothing (the stream just drops) and the window only goes away on a
// second click. So SIGINT now — synchronously, so the host always gets
// its ctrl-c teardown (capture down, endpoint closed) even if we exit
// right after — then reap on a detached thread instead of waiting.
let Some(mut child) = self.child.take() else {
return;
};
if matches!(child.try_wait(), Ok(Some(_))) {
return; // already exited; nothing to signal or reap
}
let _ = kill(Pid::from_raw(child.id() as i32), Signal::SIGINT);
std::thread::spawn(move || {
for _ in 0..40 {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
});
// Closing the window (dropping the app, hence the session) must not
// orphan a live host child streaming to viewers.
self.stop();
}
}
@@ -237,7 +222,7 @@ mod tests {
}
#[test]
fn viewer_join_leave_round_trip() {
fn viewer_events_round_trips() {
assert!(matches!(
parse(Event::ViewerJoined { id: "nodeXYZ", active: 2, max: 4 }),
ChildEvent::ViewerJoined { id, active: 2, max: 4 } if id == "nodeXYZ"
+73 -50
View File
@@ -78,23 +78,6 @@ fn short_id(id: &str) -> String {
}
}
/// Fire a desktop notification, on a detached thread so the D-Bus round-trip
/// can't stall the egui frame. Best-effort: with no notification daemon it
/// just does nothing. (notify-rust talks D-Bus via pure-Rust zbus, so this
/// needs no system libdbus and no GTK event loop.)
fn notify(summary: &'static str, body: String) {
std::thread::spawn(move || {
if let Err(e) = notify_rust::Notification::new()
.appname("PixelPass")
.summary(summary)
.body(&body)
.show()
{
tracing::warn!("desktop notification failed: {e}");
}
});
}
/// Which screen the single window is currently showing.
#[derive(Default, PartialEq)]
enum Screen {
@@ -165,7 +148,6 @@ impl PlayerSel {
/// Host-screen state: the config form fields plus, once started, the running
/// child and the latest values parsed from its event stream.
#[derive(Default)]
struct HostState {
// form
quality: QualitySel,
@@ -186,9 +168,30 @@ struct HostState {
copied: bool,
last_refusal: Option<String>,
error: Option<String>,
/// Endpoint ids of the currently-connected viewers, in arrival order.
/// Drives the per-viewer list and its Kick buttons.
viewers: Vec<String>,
tray_icon: Option<tray_icon::TrayIcon>,
}
impl Default for HostState {
fn default() -> Self {
Self {
quality: QualitySel::default(),
max_viewers: 0,
no_hwencode: false,
window: false,
proc: None,
ticket: None,
info: None,
active: 0,
max: 0,
capturing: false,
copied: false,
last_refusal: None,
error: None,
viewers: Vec::new(),
tray_icon: None,
}
}
}
/// The host config summary echoed back by the child's `host_info` event.
@@ -232,6 +235,11 @@ impl eframe::App for PixelPassApp {
self.pump_host_events();
self.pump_viewer_events();
if let Ok(_event) = tray_icon::menu::MenuEvent::receiver().try_recv() {
// Only one menu item right now: "Stop Hosting"
self.stop_host();
}
match self.screen {
Screen::Menu => self.menu(ui),
Screen::Host => self.host(ui),
@@ -362,22 +370,18 @@ impl PixelPassApp {
ui.add_space(6.0);
ui.label(format!("Viewers: {} / {}", self.host.active, self.host.max));
// Per-viewer list with a Kick button each. Collect the click first so
// we're not borrowing self.host.viewers while we reach for the child.
let mut kick: Option<String> = None;
for id in &self.host.viewers {
ui.horizontal(|ui| {
ui.label(format!("• endpoint {}", short_id(id)));
if ui.small_button("Kick").clicked() {
kick = Some(id.clone());
}
});
}
if let Some(id) = kick
&& let Some(p) = &mut self.host.proc
{
p.send_command(&format!("kick {id}"));
if !self.host.viewers.is_empty() {
ui.add_space(4.0);
for id in &self.host.viewers.clone() {
ui.horizontal(|ui| {
ui.label(format!("{}", short_id(id)));
if ui.button("Kick").clicked() {
if let Some(p) = &mut self.host.proc {
p.send_command(&format!("kick {id}"));
}
}
});
}
}
if let Some(info) = &self.host.info {
@@ -470,7 +474,6 @@ impl PixelPassApp {
self.host.max = 0;
self.host.capturing = false;
self.host.copied = false;
self.host.viewers.clear();
let mut args = vec![
"--host".to_string(),
@@ -491,7 +494,28 @@ impl PixelPassApp {
}
match ChildProc::spawn(&args, ctx) {
Ok(p) => self.host.proc = Some(p),
Ok(p) => {
self.host.proc = Some(p);
#[cfg(target_os = "linux")]
if let Err(e) = gtk::init() {
tracing::warn!("Failed to initialize GTK for system tray: {e}");
}
use tray_icon::{TrayIconBuilder, menu::{Menu, MenuItem}};
let menu = Menu::new();
let _ = menu.append(&MenuItem::new("Stop Hosting", true, None));
let icon = tray_icon::Icon::from_rgba(vec![255, 0, 0, 255], 1, 1).unwrap();
if let Ok(tray) = TrayIconBuilder::new()
.with_title("PixelPass")
.with_tooltip("PixelPass Screen Sharing")
.with_icon(icon)
.with_menu(Box::new(menu))
.build()
{
self.host.tray_icon = Some(tray);
}
}
Err(e) => self.host.error = Some(format!("Couldn't start host: {e}")),
}
}
@@ -503,6 +527,7 @@ impl PixelPassApp {
self.host.ticket = None;
self.host.copied = false;
self.host.viewers.clear();
self.host.tray_icon = None;
}
/// Drain the host child's event channel into state, and detect an
@@ -567,23 +592,21 @@ impl PixelPassApp {
self.host.active = active;
self.host.max = max;
if !self.host.viewers.contains(&id) {
notify(
"PixelPass — viewer connected",
format!("endpoint {} is now watching ({active}/{max})", short_id(&id)),
);
self.host.viewers.push(id);
self.host.viewers.push(id.clone());
let _ = notify_rust::Notification::new()
.summary("PixelPass Viewer Connected")
.body(&format!("Viewer {} joined the stream.", short_id(&id)))
.show();
}
}
ChildEvent::ViewerLeft { id, active, max } => {
self.host.active = active;
self.host.max = max;
if self.host.viewers.iter().any(|v| v == &id) {
notify(
"PixelPass — viewer disconnected",
format!("endpoint {} left ({active}/{max})", short_id(&id)),
);
self.host.viewers.retain(|v| v != &id);
}
self.host.viewers.retain(|v| v != &id);
let _ = notify_rust::Notification::new()
.summary("PixelPass Viewer Disconnected")
.body(&format!("Viewer {} left the stream.", short_id(&id)))
.show();
}
ChildEvent::Capture { state } => {
self.host.capturing = matches!(state, child::CaptureState::Started);
+33 -77
View File
@@ -12,6 +12,7 @@ use iroh::{Endpoint, EndpointAddr};
use iroh_tickets::endpoint::EndpointTicket;
use std::collections::HashMap;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
@@ -24,16 +25,11 @@ use crate::common::{
use self::pipeline::CaptureHandle;
use self::quality::EffectiveQuality;
/// Messages from per-viewer tasks (and the GUI command channel) to the
/// capture supervisor.
// The shared `Viewer` suffix is the point — these are all viewer lifecycle
// messages — so keep the descriptive names.
#[allow(clippy::enum_variant_names)]
/// Messages from per-viewer tasks to the capture supervisor.
enum SupervisorMsg {
/// A new viewer wants in. Supervisor replies with the local capture HTTP
/// port to connect to, or an error string if the host is full or capture
/// spawn failed. `cancel` is the viewer's own token — the supervisor keeps
/// it so a later `KickViewer` can tear this viewer's stream down.
/// A new viewer wants in. Supervisor replies with the local capture
/// HTTP port to connect to, or an error string if the host is full or
/// capture spawn failed.
AddViewer {
id: String,
cancel: CancellationToken,
@@ -42,9 +38,7 @@ enum SupervisorMsg {
/// A viewer's session ended. Supervisor decrements the count and tears
/// down capture if it just hit zero.
RemoveViewer { id: String },
/// Host asked (via the GUI command channel) to disconnect a viewer by
/// endpoint id. Cancels that viewer's token; the normal teardown path then
/// emits the `ViewerLeft`.
/// Request to kick a specific viewer.
KickViewer { id: String },
}
@@ -127,14 +121,16 @@ pub async fn run(opts: HostOpts) -> Result<()> {
sup_rx,
));
// Command channel for the GUI front-end: read `kick <endpoint-id>` lines
// off stdin. Only when machine-driven (`--output json`) — a human host has
// nothing to type here, and we don't want to swallow terminal input. Runs
// on a plain OS thread (not a tokio task) so a read parked on stdin can't
// hold up runtime shutdown on Ctrl+C; the thread dies with the process.
if output::json_enabled() {
spawn_kick_listener(sup_tx.clone());
}
// Stdin listener for "kick <id>"
let stdin_sup_tx = sup_tx.clone();
tokio::spawn(async move {
let mut lines = BufReader::new(tokio::io::stdin()).lines();
while let Ok(Some(line)) = lines.next_line().await {
if let Some(id) = line.strip_prefix("kick ") {
let _ = stdin_sup_tx.send(SupervisorMsg::KickViewer { id: id.trim().to_string() }).await;
}
}
});
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
@@ -182,18 +178,11 @@ async fn handle_peer(
cancel: CancellationToken,
) {
let remote = conn.remote_id();
let id = remote.to_string();
// This viewer's own kill switch: the supervisor holds a clone so a `kick`
// can cancel it, and the stream select! below watches it.
let id_str = remote.to_string();
let peer_cancel = CancellationToken::new();
let (reply_tx, reply_rx) = oneshot::channel();
let add = SupervisorMsg::AddViewer {
id: id.clone(),
cancel: peer_cancel.clone(),
reply: reply_tx,
};
if sup_tx.send(add).await.is_err() {
if sup_tx.send(SupervisorMsg::AddViewer { id: id_str.clone(), cancel: peer_cancel.clone(), reply: reply_tx }).await.is_err() {
tracing::warn!(%remote, "supervisor channel closed; dropping peer");
return;
}
@@ -214,7 +203,7 @@ async fn handle_peer(
Ok(s) => s,
Err(e) => {
tracing::warn!(%remote, "accept_bi failed: {e:#}");
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
return;
}
};
@@ -225,7 +214,7 @@ async fn handle_peer(
Ok(t) => t,
Err(e) => {
tracing::warn!(%remote, "connect_to_capture failed: {e:#}");
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
return;
}
};
@@ -245,28 +234,7 @@ async fn handle_peer(
}
eprintln!("[pixelpass] viewer disconnected: {remote}");
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
}
/// Read `kick <endpoint-id>` lines off stdin and forward them to the
/// supervisor. Runs on a detached OS thread (see the call site for why). Ends
/// when stdin hits EOF (the GUI closed the pipe) or the supervisor is gone.
fn spawn_kick_listener(sup_tx: mpsc::Sender<SupervisorMsg>) {
use std::io::BufRead;
std::thread::spawn(move || {
let stdin = std::io::stdin();
for line in stdin.lock().lines().map_while(Result::ok) {
let Some(id) = line.trim().strip_prefix("kick ") else {
continue;
};
let msg = SupervisorMsg::KickViewer { id: id.trim().to_string() };
// blocking_send is valid here: this is a plain thread, not inside
// the tokio runtime. An Err means the supervisor closed — stop.
if sup_tx.blocking_send(msg).is_err() {
break;
}
}
});
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
}
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
@@ -281,15 +249,12 @@ async fn supervise(
mut rx: mpsc::Receiver<SupervisorMsg>,
) {
let mut handle: Option<CaptureHandle> = None;
// Active viewers, keyed by endpoint id, holding each one's kill switch.
// The count is just `viewers.len()`. (A given endpoint connecting twice is
// a non-case here: each viewer process uses a fresh ephemeral identity.)
let mut count: u32 = 0;
let mut viewers: HashMap<String, CancellationToken> = HashMap::new();
while let Some(msg) = rx.recv().await {
match msg {
SupervisorMsg::AddViewer { id, cancel, reply } => {
let count = viewers.len() as u32;
if count >= max_viewers {
let reason =
format!("host is full ({count} of {max_viewers} viewers connected)");
@@ -315,22 +280,18 @@ async fn supervise(
}
let port = handle.as_ref().expect("handle was just set").local_port();
count += 1;
viewers.insert(id.clone(), cancel);
let active = viewers.len() as u32;
let _ = reply.send(Ok(port));
output::emit(output::Event::ViewerJoined { id: &id, active, max: max_viewers });
tracing::info!(active, cap = max_viewers, "viewer joined");
output::emit(output::Event::ViewerJoined { id: &id, active: count, max: max_viewers });
tracing::info!(active = count, cap = max_viewers, "viewer joined");
}
SupervisorMsg::RemoveViewer { id } => {
// A given viewer task only ever sends RemoveViewer once, but the
// map remove is the source of truth either way.
if viewers.remove(&id).is_none() {
continue;
}
let active = viewers.len() as u32;
output::emit(output::Event::ViewerLeft { id: &id, active, max: max_viewers });
tracing::info!(active, cap = max_viewers, "viewer left");
if active == 0
viewers.remove(&id);
count = count.saturating_sub(1);
output::emit(output::Event::ViewerLeft { id: &id, active: count, max: max_viewers });
tracing::info!(active = count, cap = max_viewers, "viewer left");
if count == 0
&& let Some(h) = handle.take()
{
tracing::info!("last viewer left — tearing down capture");
@@ -341,14 +302,9 @@ async fn supervise(
}
}
SupervisorMsg::KickViewer { id } => {
match viewers.get(&id) {
// Cancel the viewer's token; its handle_peer select! wakes,
// sends RemoveViewer, and the leave is emitted there.
Some(cancel) => {
tracing::info!(%id, "kicking viewer");
cancel.cancel();
}
None => tracing::debug!(%id, "kick for unknown/already-gone viewer"),
if let Some(cancel) = viewers.get(&id) {
tracing::info!(%id, "kicking viewer");
cancel.cancel();
}
}
}
+6 -6
View File
@@ -13,7 +13,7 @@ pub async fn run(cli: Cli) -> Result<()> {
let theme = ColorfulTheme::default();
let choice = Select::with_theme(&theme)
.with_prompt("What do you want to do?")
.items([
.items(&[
"Host (share my screen)",
"View (watch someone else's screen)",
])
@@ -112,7 +112,7 @@ fn pick_quality(theme: &ColorfulTheme) -> Result<Quality> {
let choice = Select::with_theme(theme)
.with_prompt("What quality should the viewer(s) get?")
.items(items)
.items(&items)
.default(0)
.interact()?;
@@ -138,7 +138,7 @@ pub async fn run_reconfigure() -> Result<()> {
async fn preflight_if_needed(theme: &ColorfulTheme) {
let mut cfg = config::load().unwrap_or_default();
match cfg.bandwidth.status {
config::BandwidthStatus::Measured | config::BandwidthStatus::Skipped => (),
config::BandwidthStatus::Measured | config::BandwidthStatus::Skipped => return,
config::BandwidthStatus::Unmeasured => {
eprintln!();
eprintln!("First-time setup");
@@ -154,7 +154,7 @@ async fn preflight_if_needed(theme: &ColorfulTheme) {
let Ok(choice) = Select::with_theme(theme)
.with_prompt("What would you like to do?")
.items([
.items(&[
"Run the bandwidth test (recommended)",
"Skip — use the conservative default",
])
@@ -180,7 +180,7 @@ async fn preflight_if_needed(theme: &ColorfulTheme) {
eprintln!();
let Ok(choice) = Select::with_theme(theme)
.with_prompt("Last bandwidth test failed. Try again?")
.items([
.items(&[
"Yes — retry now",
"No — use the conservative default",
])
@@ -341,7 +341,7 @@ pub fn prompt_player() -> Result<Player> {
let theme = ColorfulTheme::default();
let choice = Select::with_theme(&theme)
.with_prompt("Connected. Pick a player to launch")
.items(["mpv", "VLC"])
.items(&["mpv", "VLC"])
.default(0)
.interact()?;
Ok(if choice == 0 { Player::Mpv } else { Player::Vlc })