Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e39251189 | ||
|
|
c2d04b35ba | ||
|
|
b4be8deb46 |
Generated
+674
-86
File diff suppressed because it is too large
Load Diff
+4
-4
@@ -34,9 +34,9 @@ ureq = { version = "3", default-features = false, features = ["rustls"] }
|
|||||||
toml = "1"
|
toml = "1"
|
||||||
chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] }
|
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 }
|
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
|
tray-icon = { version = "0.24.0", optional = true }
|
||||||
# pure-Rust zbus backend (no system libdbus, no image crate).
|
notify-rust = { version = "4.17.0", optional = true }
|
||||||
notify-rust = { version = "4", optional = true }
|
gtk = { version = "0.18.2", optional = true }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = "thin"
|
lto = "thin"
|
||||||
@@ -46,4 +46,4 @@ strip = "symbols"
|
|||||||
[features]
|
[features]
|
||||||
# Opt-in graphical front-end (pixelpass --gui). Default-off so the headless
|
# Opt-in graphical front-end (pixelpass --gui). Default-off so the headless
|
||||||
# build never pulls the GUI toolkit tree.
|
# build never pulls the GUI toolkit tree.
|
||||||
gui = ["dep:eframe", "dep:notify-rust"]
|
gui = ["dep:eframe", "dep:tray-icon", "dep:notify-rust", "dep:gtk"]
|
||||||
|
|||||||
@@ -22,11 +22,7 @@ pub fn set_json(enabled: bool) {
|
|||||||
JSON_ENABLED.store(enabled, Ordering::Relaxed);
|
JSON_ENABLED.store(enabled, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the JSON event stream is on — i.e. we're being driven by a
|
fn json_enabled() -> bool {
|
||||||
/// 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 {
|
|
||||||
JSON_ENABLED.load(Ordering::Relaxed)
|
JSON_ENABLED.load(Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,11 +42,9 @@ pub enum Event<'a> {
|
|||||||
max_viewers: u32,
|
max_viewers: u32,
|
||||||
max_viewers_source: &'a str,
|
max_viewers_source: &'a str,
|
||||||
},
|
},
|
||||||
/// A viewer joined. `id` is the viewer's endpoint id; `active` is the new
|
/// A new viewer joined.
|
||||||
/// total after the join.
|
|
||||||
ViewerJoined { id: &'a str, active: u32, max: u32 },
|
ViewerJoined { id: &'a str, active: u32, max: u32 },
|
||||||
/// A viewer left — disconnected on their own or kicked by the host. `id`
|
/// A viewer disconnected.
|
||||||
/// is the viewer's endpoint id; `active` is the new total after.
|
|
||||||
ViewerLeft { id: &'a str, active: u32, max: u32 },
|
ViewerLeft { id: &'a str, active: u32, max: u32 },
|
||||||
/// Capture pipeline lifecycle (spawned on first viewer, torn down on last).
|
/// Capture pipeline lifecycle (spawned on first viewer, torn down on last).
|
||||||
Capture { state: CaptureState },
|
Capture { state: CaptureState },
|
||||||
|
|||||||
+13
-22
@@ -6,8 +6,8 @@
|
|||||||
//! egui app drains each frame. stderr is captured into a small ring so a
|
//! 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.
|
//! failed launch (e.g. a missing gst plugin) can be surfaced in the window.
|
||||||
|
|
||||||
use std::io::{BufRead, BufReader, Write};
|
use std::io::{BufRead, BufReader};
|
||||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
use std::process::{Child, Command, Stdio};
|
||||||
use std::sync::mpsc::Receiver;
|
use std::sync::mpsc::Receiver;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -69,9 +69,7 @@ pub struct ChildProc {
|
|||||||
child: Child,
|
child: Child,
|
||||||
pub rx: Receiver<ChildEvent>,
|
pub rx: Receiver<ChildEvent>,
|
||||||
stderr_tail: Arc<Mutex<Vec<String>>>,
|
stderr_tail: Arc<Mutex<Vec<String>>>,
|
||||||
/// Write end of the child's stdin, for the line-based command channel
|
stdin: std::process::ChildStdin,
|
||||||
/// (see [`ChildProc::send_command`]). `None` once it's been closed.
|
|
||||||
stdin: Option<ChildStdin>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ChildProc {
|
impl ChildProc {
|
||||||
@@ -81,15 +79,13 @@ impl ChildProc {
|
|||||||
let exe = std::env::current_exe()?;
|
let exe = std::env::current_exe()?;
|
||||||
let mut child = Command::new(exe)
|
let mut child = Command::new(exe)
|
||||||
.args(args)
|
.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())
|
.stdin(Stdio::piped())
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
.stderr(Stdio::piped())
|
.stderr(Stdio::piped())
|
||||||
.spawn()?;
|
.spawn()?;
|
||||||
|
|
||||||
let stdin = child.stdin.take();
|
|
||||||
let (tx, rx) = std::sync::mpsc::channel();
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
let stdin = child.stdin.take().expect("stdin piped");
|
||||||
let stdout = child.stdout.take().expect("stdout piped");
|
let stdout = child.stdout.take().expect("stdout piped");
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
let reader = BufReader::new(stdout);
|
let reader = BufReader::new(stdout);
|
||||||
@@ -130,19 +126,6 @@ impl ChildProc {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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.
|
/// Whether the child is still running.
|
||||||
pub fn is_alive(&mut self) -> bool {
|
pub fn is_alive(&mut self) -> bool {
|
||||||
matches!(self.child.try_wait(), Ok(None))
|
matches!(self.child.try_wait(), Ok(None))
|
||||||
@@ -153,6 +136,14 @@ impl ChildProc {
|
|||||||
self.stderr_tail.lock().unwrap().join("\n")
|
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
|
/// 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
|
/// — tears down capture, closes the endpoint), with a ~2 s grace period
|
||||||
/// before a hard kill. Idempotent.
|
/// before a hard kill. Idempotent.
|
||||||
@@ -231,7 +222,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn viewer_join_leave_round_trip() {
|
fn viewer_events_round_trips() {
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
parse(Event::ViewerJoined { id: "nodeXYZ", active: 2, max: 4 }),
|
parse(Event::ViewerJoined { id: "nodeXYZ", active: 2, max: 4 }),
|
||||||
ChildEvent::ViewerJoined { id, active: 2, max: 4 } if id == "nodeXYZ"
|
ChildEvent::ViewerJoined { id, active: 2, max: 4 } if id == "nodeXYZ"
|
||||||
|
|||||||
+47
-44
@@ -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.
|
/// Which screen the single window is currently showing.
|
||||||
#[derive(Default, PartialEq)]
|
#[derive(Default, PartialEq)]
|
||||||
enum Screen {
|
enum Screen {
|
||||||
@@ -185,9 +168,8 @@ struct HostState {
|
|||||||
copied: bool,
|
copied: bool,
|
||||||
last_refusal: Option<String>,
|
last_refusal: Option<String>,
|
||||||
error: 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>,
|
viewers: Vec<String>,
|
||||||
|
tray_icon: Option<tray_icon::TrayIcon>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for HostState {
|
impl Default for HostState {
|
||||||
@@ -207,6 +189,7 @@ impl Default for HostState {
|
|||||||
last_refusal: None,
|
last_refusal: None,
|
||||||
error: None,
|
error: None,
|
||||||
viewers: Vec::new(),
|
viewers: Vec::new(),
|
||||||
|
tray_icon: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -252,6 +235,11 @@ impl eframe::App for PixelPassApp {
|
|||||||
self.pump_host_events();
|
self.pump_host_events();
|
||||||
self.pump_viewer_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 {
|
match self.screen {
|
||||||
Screen::Menu => self.menu(ui),
|
Screen::Menu => self.menu(ui),
|
||||||
Screen::Host => self.host(ui),
|
Screen::Host => self.host(ui),
|
||||||
@@ -382,22 +370,18 @@ impl PixelPassApp {
|
|||||||
|
|
||||||
ui.add_space(6.0);
|
ui.add_space(6.0);
|
||||||
ui.label(format!("Viewers: {} / {}", self.host.active, self.host.max));
|
ui.label(format!("Viewers: {} / {}", self.host.active, self.host.max));
|
||||||
|
if !self.host.viewers.is_empty() {
|
||||||
// Per-viewer list with a Kick button each. Collect the click first so
|
ui.add_space(4.0);
|
||||||
// we're not borrowing self.host.viewers while we reach for the child.
|
for id in &self.host.viewers.clone() {
|
||||||
let mut kick: Option<String> = None;
|
|
||||||
for id in &self.host.viewers {
|
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
ui.label(format!("• endpoint {}", short_id(id)));
|
ui.label(format!("• {}", short_id(id)));
|
||||||
if ui.small_button("Kick").clicked() {
|
if ui.button("Kick").clicked() {
|
||||||
kick = Some(id.clone());
|
if let Some(p) = &mut self.host.proc {
|
||||||
|
p.send_command(&format!("kick {id}"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if let Some(id) = kick
|
|
||||||
&& let Some(p) = &mut self.host.proc
|
|
||||||
{
|
|
||||||
p.send_command(&format!("kick {id}"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(info) = &self.host.info {
|
if let Some(info) = &self.host.info {
|
||||||
@@ -490,7 +474,6 @@ impl PixelPassApp {
|
|||||||
self.host.max = 0;
|
self.host.max = 0;
|
||||||
self.host.capturing = false;
|
self.host.capturing = false;
|
||||||
self.host.copied = false;
|
self.host.copied = false;
|
||||||
self.host.viewers.clear();
|
|
||||||
|
|
||||||
let mut args = vec![
|
let mut args = vec![
|
||||||
"--host".to_string(),
|
"--host".to_string(),
|
||||||
@@ -511,7 +494,28 @@ impl PixelPassApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match ChildProc::spawn(&args, ctx) {
|
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}")),
|
Err(e) => self.host.error = Some(format!("Couldn't start host: {e}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -523,6 +527,7 @@ impl PixelPassApp {
|
|||||||
self.host.ticket = None;
|
self.host.ticket = None;
|
||||||
self.host.copied = false;
|
self.host.copied = false;
|
||||||
self.host.viewers.clear();
|
self.host.viewers.clear();
|
||||||
|
self.host.tray_icon = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drain the host child's event channel into state, and detect an
|
/// Drain the host child's event channel into state, and detect an
|
||||||
@@ -587,23 +592,21 @@ impl PixelPassApp {
|
|||||||
self.host.active = active;
|
self.host.active = active;
|
||||||
self.host.max = max;
|
self.host.max = max;
|
||||||
if !self.host.viewers.contains(&id) {
|
if !self.host.viewers.contains(&id) {
|
||||||
notify(
|
self.host.viewers.push(id.clone());
|
||||||
"PixelPass — viewer connected",
|
let _ = notify_rust::Notification::new()
|
||||||
format!("endpoint {} is now watching ({active}/{max})", short_id(&id)),
|
.summary("PixelPass Viewer Connected")
|
||||||
);
|
.body(&format!("Viewer {} joined the stream.", short_id(&id)))
|
||||||
self.host.viewers.push(id);
|
.show();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ChildEvent::ViewerLeft { id, active, max } => {
|
ChildEvent::ViewerLeft { id, active, max } => {
|
||||||
self.host.active = active;
|
self.host.active = active;
|
||||||
self.host.max = max;
|
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 } => {
|
ChildEvent::Capture { state } => {
|
||||||
self.host.capturing = matches!(state, child::CaptureState::Started);
|
self.host.capturing = matches!(state, child::CaptureState::Started);
|
||||||
|
|||||||
+30
-74
@@ -12,6 +12,7 @@ use iroh::{Endpoint, EndpointAddr};
|
|||||||
use iroh_tickets::endpoint::EndpointTicket;
|
use iroh_tickets::endpoint::EndpointTicket;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||||
use tokio::sync::{mpsc, oneshot};
|
use tokio::sync::{mpsc, oneshot};
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
@@ -24,16 +25,11 @@ use crate::common::{
|
|||||||
use self::pipeline::CaptureHandle;
|
use self::pipeline::CaptureHandle;
|
||||||
use self::quality::EffectiveQuality;
|
use self::quality::EffectiveQuality;
|
||||||
|
|
||||||
/// Messages from per-viewer tasks (and the GUI command channel) to the
|
/// Messages from per-viewer tasks to the capture supervisor.
|
||||||
/// 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)]
|
|
||||||
enum SupervisorMsg {
|
enum SupervisorMsg {
|
||||||
/// A new viewer wants in. Supervisor replies with the local capture HTTP
|
/// A new viewer wants in. Supervisor replies with the local capture
|
||||||
/// port to connect to, or an error string if the host is full or capture
|
/// HTTP port to connect to, or an error string if the host is full or
|
||||||
/// spawn failed. `cancel` is the viewer's own token — the supervisor keeps
|
/// capture spawn failed.
|
||||||
/// it so a later `KickViewer` can tear this viewer's stream down.
|
|
||||||
AddViewer {
|
AddViewer {
|
||||||
id: String,
|
id: String,
|
||||||
cancel: CancellationToken,
|
cancel: CancellationToken,
|
||||||
@@ -42,9 +38,7 @@ enum SupervisorMsg {
|
|||||||
/// A viewer's session ended. Supervisor decrements the count and tears
|
/// A viewer's session ended. Supervisor decrements the count and tears
|
||||||
/// down capture if it just hit zero.
|
/// down capture if it just hit zero.
|
||||||
RemoveViewer { id: String },
|
RemoveViewer { id: String },
|
||||||
/// Host asked (via the GUI command channel) to disconnect a viewer by
|
/// Request to kick a specific viewer.
|
||||||
/// endpoint id. Cancels that viewer's token; the normal teardown path then
|
|
||||||
/// emits the `ViewerLeft`.
|
|
||||||
KickViewer { id: String },
|
KickViewer { id: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,14 +121,16 @@ pub async fn run(opts: HostOpts) -> Result<()> {
|
|||||||
sup_rx,
|
sup_rx,
|
||||||
));
|
));
|
||||||
|
|
||||||
// Command channel for the GUI front-end: read `kick <endpoint-id>` lines
|
// Stdin listener for "kick <id>"
|
||||||
// off stdin. Only when machine-driven (`--output json`) — a human host has
|
let stdin_sup_tx = sup_tx.clone();
|
||||||
// nothing to type here, and we don't want to swallow terminal input. Runs
|
tokio::spawn(async move {
|
||||||
// on a plain OS thread (not a tokio task) so a read parked on stdin can't
|
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||||
// hold up runtime shutdown on Ctrl+C; the thread dies with the process.
|
while let Ok(Some(line)) = lines.next_line().await {
|
||||||
if output::json_enabled() {
|
if let Some(id) = line.strip_prefix("kick ") {
|
||||||
spawn_kick_listener(sup_tx.clone());
|
let _ = stdin_sup_tx.send(SupervisorMsg::KickViewer { id: id.trim().to_string() }).await;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
|
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
|
||||||
|
|
||||||
@@ -182,18 +178,11 @@ async fn handle_peer(
|
|||||||
cancel: CancellationToken,
|
cancel: CancellationToken,
|
||||||
) {
|
) {
|
||||||
let remote = conn.remote_id();
|
let remote = conn.remote_id();
|
||||||
let id = remote.to_string();
|
let id_str = 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 peer_cancel = CancellationToken::new();
|
let peer_cancel = CancellationToken::new();
|
||||||
|
|
||||||
let (reply_tx, reply_rx) = oneshot::channel();
|
let (reply_tx, reply_rx) = oneshot::channel();
|
||||||
let add = SupervisorMsg::AddViewer {
|
if sup_tx.send(SupervisorMsg::AddViewer { id: id_str.clone(), cancel: peer_cancel.clone(), reply: reply_tx }).await.is_err() {
|
||||||
id: id.clone(),
|
|
||||||
cancel: peer_cancel.clone(),
|
|
||||||
reply: reply_tx,
|
|
||||||
};
|
|
||||||
if sup_tx.send(add).await.is_err() {
|
|
||||||
tracing::warn!(%remote, "supervisor channel closed; dropping peer");
|
tracing::warn!(%remote, "supervisor channel closed; dropping peer");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -214,7 +203,7 @@ async fn handle_peer(
|
|||||||
Ok(s) => s,
|
Ok(s) => s,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!(%remote, "accept_bi failed: {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;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -225,7 +214,7 @@ async fn handle_peer(
|
|||||||
Ok(t) => t,
|
Ok(t) => t,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!(%remote, "connect_to_capture failed: {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;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -245,28 +234,7 @@ async fn handle_peer(
|
|||||||
}
|
}
|
||||||
|
|
||||||
eprintln!("[pixelpass] viewer disconnected: {remote}");
|
eprintln!("[pixelpass] viewer disconnected: {remote}");
|
||||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
|
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
|
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
|
||||||
@@ -281,15 +249,12 @@ async fn supervise(
|
|||||||
mut rx: mpsc::Receiver<SupervisorMsg>,
|
mut rx: mpsc::Receiver<SupervisorMsg>,
|
||||||
) {
|
) {
|
||||||
let mut handle: Option<CaptureHandle> = None;
|
let mut handle: Option<CaptureHandle> = None;
|
||||||
// Active viewers, keyed by endpoint id, holding each one's kill switch.
|
let mut count: u32 = 0;
|
||||||
// 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 viewers: HashMap<String, CancellationToken> = HashMap::new();
|
let mut viewers: HashMap<String, CancellationToken> = HashMap::new();
|
||||||
|
|
||||||
while let Some(msg) = rx.recv().await {
|
while let Some(msg) = rx.recv().await {
|
||||||
match msg {
|
match msg {
|
||||||
SupervisorMsg::AddViewer { id, cancel, reply } => {
|
SupervisorMsg::AddViewer { id, cancel, reply } => {
|
||||||
let count = viewers.len() as u32;
|
|
||||||
if count >= max_viewers {
|
if count >= max_viewers {
|
||||||
let reason =
|
let reason =
|
||||||
format!("host is full ({count} of {max_viewers} viewers connected)");
|
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();
|
let port = handle.as_ref().expect("handle was just set").local_port();
|
||||||
|
count += 1;
|
||||||
viewers.insert(id.clone(), cancel);
|
viewers.insert(id.clone(), cancel);
|
||||||
let active = viewers.len() as u32;
|
|
||||||
let _ = reply.send(Ok(port));
|
let _ = reply.send(Ok(port));
|
||||||
output::emit(output::Event::ViewerJoined { id: &id, active, max: max_viewers });
|
output::emit(output::Event::ViewerJoined { id: &id, active: count, max: max_viewers });
|
||||||
tracing::info!(active, cap = max_viewers, "viewer joined");
|
tracing::info!(active = count, cap = max_viewers, "viewer joined");
|
||||||
}
|
}
|
||||||
SupervisorMsg::RemoveViewer { id } => {
|
SupervisorMsg::RemoveViewer { id } => {
|
||||||
// A given viewer task only ever sends RemoveViewer once, but the
|
viewers.remove(&id);
|
||||||
// map remove is the source of truth either way.
|
count = count.saturating_sub(1);
|
||||||
if viewers.remove(&id).is_none() {
|
output::emit(output::Event::ViewerLeft { id: &id, active: count, max: max_viewers });
|
||||||
continue;
|
tracing::info!(active = count, cap = max_viewers, "viewer left");
|
||||||
}
|
if count == 0
|
||||||
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
|
|
||||||
&& let Some(h) = handle.take()
|
&& let Some(h) = handle.take()
|
||||||
{
|
{
|
||||||
tracing::info!("last viewer left — tearing down capture");
|
tracing::info!("last viewer left — tearing down capture");
|
||||||
@@ -341,15 +302,10 @@ async fn supervise(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
SupervisorMsg::KickViewer { id } => {
|
SupervisorMsg::KickViewer { id } => {
|
||||||
match viewers.get(&id) {
|
if let Some(cancel) = 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");
|
tracing::info!(%id, "kicking viewer");
|
||||||
cancel.cancel();
|
cancel.cancel();
|
||||||
}
|
}
|
||||||
None => tracing::debug!(%id, "kick for unknown/already-gone viewer"),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user