Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
675f25f266 | ||
|
|
e54d625f2a | ||
|
|
f926dbea4e | ||
|
|
24e0d0e799 |
Generated
+86
-674
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 }
|
||||||
tray-icon = { version = "0.24.0", optional = true }
|
# Desktop notifications on viewer join/leave. Default features give the
|
||||||
notify-rust = { version = "4.17.0", optional = true }
|
# pure-Rust zbus backend (no system libdbus, no image crate).
|
||||||
gtk = { version = "0.18.2", optional = true }
|
notify-rust = { version = "4", 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:tray-icon", "dep:notify-rust", "dep:gtk"]
|
gui = ["dep:eframe", "dep:notify-rust"]
|
||||||
|
|||||||
@@ -83,8 +83,9 @@ pixelpass --gui
|
|||||||
```
|
```
|
||||||
|
|
||||||
Host: pick quality / max-viewers / options, click **Start hosting**, and the
|
Host: pick quality / max-viewers / options, click **Start hosting**, and the
|
||||||
share code appears with a copy button alongside a live viewer count. View:
|
share code appears with a copy button. Connected viewers are listed with a
|
||||||
paste a code, pick mpv or VLC, click **Connect** and the player launches.
|
**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.
|
||||||
|
|
||||||
The window is a thin driver — it runs the same headless `pixelpass` as a
|
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
|
child process and reads its event stream, so the GUI is purely additive and
|
||||||
|
|||||||
@@ -37,18 +37,15 @@ pub struct BandwidthEntry {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
|
#[derive(Default)]
|
||||||
pub enum BandwidthStatus {
|
pub enum BandwidthStatus {
|
||||||
|
#[default]
|
||||||
Unmeasured,
|
Unmeasured,
|
||||||
Measured,
|
Measured,
|
||||||
Skipped,
|
Skipped,
|
||||||
Failed,
|
Failed,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for BandwidthStatus {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::Unmeasured
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_status() -> BandwidthStatus {
|
fn default_status() -> BandwidthStatus {
|
||||||
BandwidthStatus::Unmeasured
|
BandwidthStatus::Unmeasured
|
||||||
|
|||||||
@@ -22,7 +22,11 @@ pub fn set_json(enabled: bool) {
|
|||||||
JSON_ENABLED.store(enabled, Ordering::Relaxed);
|
JSON_ENABLED.store(enabled, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn json_enabled() -> bool {
|
/// 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 {
|
||||||
JSON_ENABLED.load(Ordering::Relaxed)
|
JSON_ENABLED.load(Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,9 +46,11 @@ pub enum Event<'a> {
|
|||||||
max_viewers: u32,
|
max_viewers: u32,
|
||||||
max_viewers_source: &'a str,
|
max_viewers_source: &'a str,
|
||||||
},
|
},
|
||||||
/// A new viewer joined.
|
/// A viewer joined. `id` is the viewer's endpoint id; `active` is the new
|
||||||
|
/// total after the join.
|
||||||
ViewerJoined { id: &'a str, active: u32, max: u32 },
|
ViewerJoined { id: &'a str, active: u32, max: u32 },
|
||||||
/// A viewer disconnected.
|
/// 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.
|
||||||
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 },
|
||||||
|
|||||||
+52
-37
@@ -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};
|
use std::io::{BufRead, BufReader, Write};
|
||||||
use std::process::{Child, Command, Stdio};
|
use std::process::{Child, ChildStdin, 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;
|
||||||
@@ -66,10 +66,14 @@ pub enum CaptureState {
|
|||||||
const STDERR_TAIL_MAX: usize = 60;
|
const STDERR_TAIL_MAX: usize = 60;
|
||||||
|
|
||||||
pub struct ChildProc {
|
pub struct ChildProc {
|
||||||
child: Child,
|
/// `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>,
|
||||||
pub rx: Receiver<ChildEvent>,
|
pub rx: Receiver<ChildEvent>,
|
||||||
stderr_tail: Arc<Mutex<Vec<String>>>,
|
stderr_tail: Arc<Mutex<Vec<String>>>,
|
||||||
stdin: std::process::ChildStdin,
|
/// 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ChildProc {
|
impl ChildProc {
|
||||||
@@ -79,13 +83,15 @@ 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);
|
||||||
@@ -119,55 +125,64 @@ impl ChildProc {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
child,
|
child: Some(child),
|
||||||
rx,
|
rx,
|
||||||
stderr_tail,
|
stderr_tail,
|
||||||
stdin,
|
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.
|
/// 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.as_mut().map(Child::try_wait), Some(Ok(None)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The last captured stderr lines, joined — for error display.
|
/// The last captured stderr lines, joined — for error display.
|
||||||
pub fn stderr_tail(&self) -> String {
|
pub fn stderr_tail(&self) -> String {
|
||||||
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
|
|
||||||
/// — 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 {
|
impl Drop for ChildProc {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Closing the window (dropping the app, hence the session) must not
|
// Leaving a host/viewer screen, or closing the window, must not orphan
|
||||||
// orphan a live host child streaming to viewers.
|
// a live child — but it must also not *block*. eframe runs this drop
|
||||||
self.stop();
|
// 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();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,7 +237,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn viewer_events_round_trips() {
|
fn viewer_join_leave_round_trip() {
|
||||||
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"
|
||||||
|
|||||||
+50
-73
@@ -78,6 +78,23 @@ 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 {
|
||||||
@@ -148,6 +165,7 @@ impl PlayerSel {
|
|||||||
|
|
||||||
/// Host-screen state: the config form fields plus, once started, the running
|
/// Host-screen state: the config form fields plus, once started, the running
|
||||||
/// child and the latest values parsed from its event stream.
|
/// child and the latest values parsed from its event stream.
|
||||||
|
#[derive(Default)]
|
||||||
struct HostState {
|
struct HostState {
|
||||||
// form
|
// form
|
||||||
quality: QualitySel,
|
quality: QualitySel,
|
||||||
@@ -168,30 +186,9 @@ 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 {
|
|
||||||
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.
|
/// The host config summary echoed back by the child's `host_info` event.
|
||||||
@@ -235,11 +232,6 @@ 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),
|
||||||
@@ -370,18 +362,22 @@ 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() {
|
|
||||||
ui.add_space(4.0);
|
// Per-viewer list with a Kick button each. Collect the click first so
|
||||||
for id in &self.host.viewers.clone() {
|
// we're not borrowing self.host.viewers while we reach for the child.
|
||||||
ui.horizontal(|ui| {
|
let mut kick: Option<String> = None;
|
||||||
ui.label(format!("• {}", short_id(id)));
|
for id in &self.host.viewers {
|
||||||
if ui.button("Kick").clicked() {
|
ui.horizontal(|ui| {
|
||||||
if let Some(p) = &mut self.host.proc {
|
ui.label(format!("• endpoint {}", short_id(id)));
|
||||||
p.send_command(&format!("kick {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 let Some(info) = &self.host.info {
|
if let Some(info) = &self.host.info {
|
||||||
@@ -474,6 +470,7 @@ 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(),
|
||||||
@@ -494,28 +491,7 @@ impl PixelPassApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match ChildProc::spawn(&args, ctx) {
|
match ChildProc::spawn(&args, ctx) {
|
||||||
Ok(p) => {
|
Ok(p) => self.host.proc = Some(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}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -527,7 +503,6 @@ 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
|
||||||
@@ -592,21 +567,23 @@ 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) {
|
||||||
self.host.viewers.push(id.clone());
|
notify(
|
||||||
let _ = notify_rust::Notification::new()
|
"PixelPass — viewer connected",
|
||||||
.summary("PixelPass Viewer Connected")
|
format!("endpoint {} is now watching ({active}/{max})", short_id(&id)),
|
||||||
.body(&format!("Viewer {} joined the stream.", short_id(&id)))
|
);
|
||||||
.show();
|
self.host.viewers.push(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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;
|
||||||
self.host.viewers.retain(|v| v != &id);
|
if self.host.viewers.iter().any(|v| v == &id) {
|
||||||
let _ = notify_rust::Notification::new()
|
notify(
|
||||||
.summary("PixelPass Viewer Disconnected")
|
"PixelPass — viewer disconnected",
|
||||||
.body(&format!("Viewer {} left the stream.", short_id(&id)))
|
format!("endpoint {} left ({active}/{max})", short_id(&id)),
|
||||||
.show();
|
);
|
||||||
|
self.host.viewers.retain(|v| v != &id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ChildEvent::Capture { state } => {
|
ChildEvent::Capture { state } => {
|
||||||
self.host.capturing = matches!(state, child::CaptureState::Started);
|
self.host.capturing = matches!(state, child::CaptureState::Started);
|
||||||
|
|||||||
+77
-33
@@ -12,7 +12,6 @@ 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;
|
||||||
|
|
||||||
@@ -25,11 +24,16 @@ use crate::common::{
|
|||||||
use self::pipeline::CaptureHandle;
|
use self::pipeline::CaptureHandle;
|
||||||
use self::quality::EffectiveQuality;
|
use self::quality::EffectiveQuality;
|
||||||
|
|
||||||
/// Messages from per-viewer tasks to the capture supervisor.
|
/// 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)]
|
||||||
enum SupervisorMsg {
|
enum SupervisorMsg {
|
||||||
/// A new viewer wants in. Supervisor replies with the local capture
|
/// A new viewer wants in. Supervisor replies with the local capture HTTP
|
||||||
/// HTTP port to connect to, or an error string if the host is full or
|
/// port to connect to, or an error string if the host is full or capture
|
||||||
/// capture spawn failed.
|
/// spawn failed. `cancel` is the viewer's own token — the supervisor keeps
|
||||||
|
/// it so a later `KickViewer` can tear this viewer's stream down.
|
||||||
AddViewer {
|
AddViewer {
|
||||||
id: String,
|
id: String,
|
||||||
cancel: CancellationToken,
|
cancel: CancellationToken,
|
||||||
@@ -38,7 +42,9 @@ 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 },
|
||||||
/// Request to kick a specific viewer.
|
/// 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`.
|
||||||
KickViewer { id: String },
|
KickViewer { id: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,16 +127,14 @@ pub async fn run(opts: HostOpts) -> Result<()> {
|
|||||||
sup_rx,
|
sup_rx,
|
||||||
));
|
));
|
||||||
|
|
||||||
// Stdin listener for "kick <id>"
|
// Command channel for the GUI front-end: read `kick <endpoint-id>` lines
|
||||||
let stdin_sup_tx = sup_tx.clone();
|
// off stdin. Only when machine-driven (`--output json`) — a human host has
|
||||||
tokio::spawn(async move {
|
// nothing to type here, and we don't want to swallow terminal input. Runs
|
||||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
// on a plain OS thread (not a tokio task) so a read parked on stdin can't
|
||||||
while let Ok(Some(line)) = lines.next_line().await {
|
// hold up runtime shutdown on Ctrl+C; the thread dies with the process.
|
||||||
if let Some(id) = line.strip_prefix("kick ") {
|
if output::json_enabled() {
|
||||||
let _ = stdin_sup_tx.send(SupervisorMsg::KickViewer { id: id.trim().to_string() }).await;
|
spawn_kick_listener(sup_tx.clone());
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
|
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
|
||||||
|
|
||||||
@@ -178,11 +182,18 @@ async fn handle_peer(
|
|||||||
cancel: CancellationToken,
|
cancel: CancellationToken,
|
||||||
) {
|
) {
|
||||||
let remote = conn.remote_id();
|
let remote = conn.remote_id();
|
||||||
let id_str = remote.to_string();
|
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 peer_cancel = CancellationToken::new();
|
let peer_cancel = CancellationToken::new();
|
||||||
|
|
||||||
let (reply_tx, reply_rx) = oneshot::channel();
|
let (reply_tx, reply_rx) = oneshot::channel();
|
||||||
if sup_tx.send(SupervisorMsg::AddViewer { id: id_str.clone(), cancel: peer_cancel.clone(), reply: reply_tx }).await.is_err() {
|
let add = SupervisorMsg::AddViewer {
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
@@ -203,7 +214,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: id_str }).await;
|
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -214,7 +225,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: id_str }).await;
|
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -234,7 +245,28 @@ async fn handle_peer(
|
|||||||
}
|
}
|
||||||
|
|
||||||
eprintln!("[pixelpass] viewer disconnected: {remote}");
|
eprintln!("[pixelpass] viewer disconnected: {remote}");
|
||||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
|
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
|
||||||
@@ -249,12 +281,15 @@ 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;
|
||||||
let mut count: u32 = 0;
|
// 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 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)");
|
||||||
@@ -280,18 +315,22 @@ 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: count, max: max_viewers });
|
output::emit(output::Event::ViewerJoined { id: &id, active, max: max_viewers });
|
||||||
tracing::info!(active = count, cap = max_viewers, "viewer joined");
|
tracing::info!(active, cap = max_viewers, "viewer joined");
|
||||||
}
|
}
|
||||||
SupervisorMsg::RemoveViewer { id } => {
|
SupervisorMsg::RemoveViewer { id } => {
|
||||||
viewers.remove(&id);
|
// A given viewer task only ever sends RemoveViewer once, but the
|
||||||
count = count.saturating_sub(1);
|
// map remove is the source of truth either way.
|
||||||
output::emit(output::Event::ViewerLeft { id: &id, active: count, max: max_viewers });
|
if viewers.remove(&id).is_none() {
|
||||||
tracing::info!(active = count, cap = max_viewers, "viewer left");
|
continue;
|
||||||
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");
|
||||||
@@ -302,9 +341,14 @@ async fn supervise(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
SupervisorMsg::KickViewer { id } => {
|
SupervisorMsg::KickViewer { id } => {
|
||||||
if let Some(cancel) = viewers.get(&id) {
|
match viewers.get(&id) {
|
||||||
tracing::info!(%id, "kicking viewer");
|
// Cancel the viewer's token; its handle_peer select! wakes,
|
||||||
cancel.cancel();
|
// 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"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -13,7 +13,7 @@ pub async fn run(cli: Cli) -> Result<()> {
|
|||||||
let theme = ColorfulTheme::default();
|
let theme = ColorfulTheme::default();
|
||||||
let choice = Select::with_theme(&theme)
|
let choice = Select::with_theme(&theme)
|
||||||
.with_prompt("What do you want to do?")
|
.with_prompt("What do you want to do?")
|
||||||
.items(&[
|
.items([
|
||||||
"Host (share my screen)",
|
"Host (share my screen)",
|
||||||
"View (watch someone else's screen)",
|
"View (watch someone else's screen)",
|
||||||
])
|
])
|
||||||
@@ -112,7 +112,7 @@ fn pick_quality(theme: &ColorfulTheme) -> Result<Quality> {
|
|||||||
|
|
||||||
let choice = Select::with_theme(theme)
|
let choice = Select::with_theme(theme)
|
||||||
.with_prompt("What quality should the viewer(s) get?")
|
.with_prompt("What quality should the viewer(s) get?")
|
||||||
.items(&items)
|
.items(items)
|
||||||
.default(0)
|
.default(0)
|
||||||
.interact()?;
|
.interact()?;
|
||||||
|
|
||||||
@@ -138,7 +138,7 @@ pub async fn run_reconfigure() -> Result<()> {
|
|||||||
async fn preflight_if_needed(theme: &ColorfulTheme) {
|
async fn preflight_if_needed(theme: &ColorfulTheme) {
|
||||||
let mut cfg = config::load().unwrap_or_default();
|
let mut cfg = config::load().unwrap_or_default();
|
||||||
match cfg.bandwidth.status {
|
match cfg.bandwidth.status {
|
||||||
config::BandwidthStatus::Measured | config::BandwidthStatus::Skipped => return,
|
config::BandwidthStatus::Measured | config::BandwidthStatus::Skipped => (),
|
||||||
config::BandwidthStatus::Unmeasured => {
|
config::BandwidthStatus::Unmeasured => {
|
||||||
eprintln!();
|
eprintln!();
|
||||||
eprintln!("First-time setup");
|
eprintln!("First-time setup");
|
||||||
@@ -154,7 +154,7 @@ async fn preflight_if_needed(theme: &ColorfulTheme) {
|
|||||||
|
|
||||||
let Ok(choice) = Select::with_theme(theme)
|
let Ok(choice) = Select::with_theme(theme)
|
||||||
.with_prompt("What would you like to do?")
|
.with_prompt("What would you like to do?")
|
||||||
.items(&[
|
.items([
|
||||||
"Run the bandwidth test (recommended)",
|
"Run the bandwidth test (recommended)",
|
||||||
"Skip — use the conservative default",
|
"Skip — use the conservative default",
|
||||||
])
|
])
|
||||||
@@ -180,7 +180,7 @@ async fn preflight_if_needed(theme: &ColorfulTheme) {
|
|||||||
eprintln!();
|
eprintln!();
|
||||||
let Ok(choice) = Select::with_theme(theme)
|
let Ok(choice) = Select::with_theme(theme)
|
||||||
.with_prompt("Last bandwidth test failed. Try again?")
|
.with_prompt("Last bandwidth test failed. Try again?")
|
||||||
.items(&[
|
.items([
|
||||||
"Yes — retry now",
|
"Yes — retry now",
|
||||||
"No — use the conservative default",
|
"No — use the conservative default",
|
||||||
])
|
])
|
||||||
@@ -341,7 +341,7 @@ pub fn prompt_player() -> Result<Player> {
|
|||||||
let theme = ColorfulTheme::default();
|
let theme = ColorfulTheme::default();
|
||||||
let choice = Select::with_theme(&theme)
|
let choice = Select::with_theme(&theme)
|
||||||
.with_prompt("Connected. Pick a player to launch")
|
.with_prompt("Connected. Pick a player to launch")
|
||||||
.items(&["mpv", "VLC"])
|
.items(["mpv", "VLC"])
|
||||||
.default(0)
|
.default(0)
|
||||||
.interact()?;
|
.interact()?;
|
||||||
Ok(if choice == 0 { Player::Mpv } else { Player::Vlc })
|
Ok(if choice == 0 { Player::Mpv } else { Player::Vlc })
|
||||||
|
|||||||
Reference in New Issue
Block a user