Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,9 @@ from "CABLE Output".

The other flags work as on Linux; `--microphone-fifo` and the rounded-corner flags don't
apply. Dynamic resolution picks the largest display mode that fits the viewer's window,
and Windows restores the original mode when voxl exits.
and Windows restores the original mode when voxl exits. As on a Mac, the toolbar's
Display picker switches between monitors; displays are identified by their index
(`--display` order, primary first).

### HTTPS

Expand Down
24 changes: 17 additions & 7 deletions src/hub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,10 @@ pub struct Stats {
pub struct Hub {
#[cfg(target_os = "macos")]
pub display_req: Mutex<Option<crate::mac::DisplayRequest>>,
#[cfg(windows)]
pub display_req: Mutex<Option<crate::win::DisplayRequest>>,
/// Connections older than this may no longer inject input after a display switch.
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
pub input_floor: AtomicU64,
pub clients: Mutex<Vec<Arc<Client>>>,
pub next_id: AtomicU64,
Expand Down Expand Up @@ -270,9 +272,9 @@ pub struct Hub {
impl Hub {
pub fn new() -> Arc<Self> {
Arc::new(Hub {
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
display_req: Mutex::new(None),
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
input_floor: AtomicU64::new(0),
clients: Mutex::new(Vec::new()),
next_id: AtomicU64::new(1),
Expand Down Expand Up @@ -368,9 +370,17 @@ impl Hub {
}
}

/// Share the admission lock with input senders, so the barrier cannot overtake input.
#[cfg(target_os = "macos")]
pub fn pause_display_input(&self, id: u32, client: u64) -> Option<crate::mac::DisplayRequest> {
/// Share the admission lock with input senders, so the barrier cannot overtake
/// input. Returns the input sender and the barrier's receiver; the platform wraps
/// them in its own DisplayRequest for the video thread.
#[cfg(any(target_os = "macos", windows))]
pub fn pause_display_input(
&self,
client: u64,
) -> Option<(
std::sync::mpsc::Sender<crate::input::InputEvent>,
std::sync::mpsc::Receiver<()>,
)> {
let mut input = self.input.lock();
if client < self.input_floor.load(Ordering::Relaxed) {
return None;
Expand All @@ -391,6 +401,6 @@ impl Hub {
for client in self.clients.lock().drain(..) {
client.send(Out::Text("{\"t\":\"close\"}".into()));
}
Some(crate::mac::DisplayRequest { id, sender, ready })
Some((sender, ready))
}
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ async fn serve(a: HashMap<String, String>) {
.unwrap_or(4) as u32;
let vcfg = video::VideoConfig {
display: display.clone(),
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
enable_resize: truthy(a.get("enable-resize"), false) && !truthy(a.get("read-only"), false),
fps: range_max(a.get("framerate"), 60.0) as u32,
preset: a
Expand Down
6 changes: 3 additions & 3 deletions src/mac/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,10 @@ pub fn request_display(hub: &crate::hub::Hub, id: u32, client: u64) -> Result<bo
return Ok(false);
}
let mut pending = hub.display_req.lock();
let request = hub
.pause_display_input(id, client)
let (sender, ready) = hub
.pause_display_input(client)
.ok_or("display switch already in progress")?;
*pending = Some(request);
*pending = Some(DisplayRequest { id, sender, ready });
hub.wake();
Ok(true)
}
Expand Down
30 changes: 17 additions & 13 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,9 @@ async fn handle_socket(socket: WebSocket, s: AppState) {
let (tx, mut rx) = mpsc::unbounded_channel::<Out>();
let client = {
// New connections must not receive the old geometry during a display change.
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
let input = s.hub.input.lock();
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
if input.is_none() && s.hub.input_floor.load(Ordering::Relaxed) != 0 {
return;
}
Expand Down Expand Up @@ -306,11 +306,11 @@ fn num<T: std::str::FromStr>(it: &mut std::str::Split<'_, char>) -> Option<T> {

fn send_input(hub: &Hub, client: &Client, event: InputEvent) {
let input = hub.input.lock();
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
if client.id < hub.input_floor.load(Ordering::Relaxed) {
return;
}
#[cfg(not(target_os = "macos"))]
#[cfg(not(any(target_os = "macos", windows)))]
let _ = client;
if let Some(tx) = input.as_ref() {
let _ = tx.send(event);
Expand All @@ -333,10 +333,14 @@ fn handle_text(s: &AppState, c: &Arc<Client>, t: &str, rtts: &mut std::collectio
let input = |ev| send_input(&s.hub, c, ev);
let mut it = rest.split(',');
match cmd {
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
"ds" => {
if let Ok(id) = rest.parse() {
match crate::mac::request_display(&s.hub, id, c.id) {
#[cfg(target_os = "macos")]
let result = crate::mac::request_display(&s.hub, id, c.id);
#[cfg(windows)]
let result = crate::win::request_display(&s.hub, id, c.id);
match result {
Ok(true) => {}
result => {
if let Err(e) = result {
Expand Down Expand Up @@ -413,9 +417,9 @@ fn handle_text(s: &AppState, c: &Arc<Client>, t: &str, rtts: &mut std::collectio
// sz,w,h: the desktop size this client's window wants (dynamic resolution).
// The latest request wins; the video thread clamps it and applies it.
"sz" if s.resize => {
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
let input = s.hub.input.lock();
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
if input.is_none() || c.id < s.hub.input_floor.load(Ordering::Relaxed) {
return;
}
Expand Down Expand Up @@ -558,7 +562,7 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}

#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
#[test]
fn display_switch_drains_input_and_retires_old_connections() {
let hub = Hub::new();
Expand All @@ -567,7 +571,7 @@ mod tests {
let (out, _messages) = mpsc::unbounded_channel();
let old = hub.add_client(out);
send_input(&hub, &old, InputEvent::Move { x: 1, y: 2 });
let request = hub.pause_display_input(20, old.id).unwrap();
let (sender, ready) = hub.pause_display_input(old.id).unwrap();
assert!(
hub.clients.lock().is_empty(),
"old subscriptions were not retired"
Expand All @@ -592,14 +596,14 @@ mod tests {
"input entered while capture was changing"
);
done.send(()).unwrap();
request.ready.recv().unwrap();
*hub.input.lock() = Some(request.sender);
ready.recv().unwrap();
*hub.input.lock() = Some(sender);
send_input(&hub, &old, InputEvent::Move { x: 100, y: 200 });
assert!(
events.try_recv().is_err(),
"an old connection used the new geometry"
);
assert!(hub.pause_display_input(30, old.id).is_none());
assert!(hub.pause_display_input(old.id).is_none());
let (out, _messages) = mpsc::unbounded_channel();
let fresh = hub.add_client(out);
send_input(&hub, &fresh, InputEvent::Move { x: 3, y: 4 });
Expand Down
28 changes: 16 additions & 12 deletions src/video.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ use crate::convert::I420;
use crate::encoder::{Encoded, Encoder, EncoderConfig, Planes};
use crate::hub::wait_any;
use crate::hub::{Hub, Inflight, Out};
#[cfg(target_os = "macos")]
use crate::mac as platform;
#[cfg(windows)]
use crate::win as platform;
use bytes::Bytes;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
Expand All @@ -14,7 +18,7 @@ use std::time::{Duration, Instant};
#[derive(Clone)]
pub struct VideoConfig {
pub display: Option<String>,
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
pub enable_resize: bool,
pub fps: u32,
pub preset: String,
Expand Down Expand Up @@ -99,9 +103,9 @@ pub fn spawn(
}
drop(cap);
let _ = encode.join();
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
let display_request = hub.display_req.lock().take();
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
if let Some(request) = display_request {
// A resize for the old monitor must not be applied to the new one.
hub.resize_req.lock().take();
Expand Down Expand Up @@ -129,22 +133,22 @@ pub fn spawn(
Ok(())
}

#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
fn switch_display(
request: crate::mac::DisplayRequest,
request: platform::DisplayRequest,
cfg: &VideoConfig,
hub: &Arc<Hub>,
screen: &mut Option<crate::screen::Screen>,
) -> Result<Pipeline, String> {
let previous = crate::mac::display();
let previous = platform::display();
let mut open = |id| {
// Best effort: an app-only mode change is undone by macOS when voxl exits.
// Best effort: an app-only mode change is undone when voxl exits.
if let Some(mut old) = screen.take() {
if let Err(e) = old.restore() {
log::warn!("could not restore the previous display mode: {e}");
}
}
crate::mac::select_display(id)?;
platform::select_display(id)?;
*screen = if cfg.enable_resize {
crate::screen::Screen::open(None)
.inspect_err(|e| {
Expand Down Expand Up @@ -226,15 +230,15 @@ fn build(cfg: &VideoConfig, hub: &Arc<Hub>) -> Result<Pipeline, String> {
.name("encode".into())
.spawn(move || encode_loop(stripes, job_rx, ret_tx, hub2, crf, po_crf))
.unwrap();
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
{
let resizing = hub.resize_max.lock().is_some();
let mut extra = hub.hello_extra.lock();
extra.insert("displays".into(), crate::mac::display_info());
extra.insert("displays".into(), platform::display_info());
if resizing {
extra.insert(
"resize".into(),
serde_json::json!({ "scale": crate::mac::resize_scale() }),
serde_json::json!({ "scale": platform::resize_scale() }),
);
} else {
extra.remove("resize");
Expand Down Expand Up @@ -554,7 +558,7 @@ fn capture_loop(
let debug_marker = std::env::var("VOXL_DEBUG_MARKER").is_ok();

loop {
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", windows))]
if hub.display_req.lock().is_some() {
return Ok(());
}
Expand Down
6 changes: 6 additions & 0 deletions src/win/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub enum InputEvent {
/// Remote clipboard update, ordered with the key events around it.
Clipboard(super::desktop::ClipContent),
ReleaseAll,
/// Finish queued input on its original geometry before selecting another display.
DisplayBarrier(mpsc::Sender<()>),
/// Release everything before exit.
Shutdown,
}
Expand Down Expand Up @@ -360,6 +362,10 @@ impl Injector {
}
}
InputEvent::ReleaseAll | InputEvent::Shutdown => self.release_all(),
InputEvent::DisplayBarrier(done) => {
self.release_all();
let _ = done.send(());
}
}
}

Expand Down
71 changes: 70 additions & 1 deletion src/win/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,14 @@ pub static GEOMETRY: Mutex<Option<Geometry>> = Mutex::new(None);
struct Settings {
/// Index into `outputs()` (0 is the primary display).
display: usize,
/// --resize-scale, or None for the display's own scaling.
resize_scale: Option<f64>,
}

static SETTINGS: Mutex<Settings> = Mutex::new(Settings { display: 0 });
static SETTINGS: Mutex<Settings> = Mutex::new(Settings {
display: 0,
resize_scale: None,
});

/// One display attached to the desktop.
pub struct Output {
Expand Down Expand Up @@ -106,6 +111,58 @@ pub fn output() -> Option<Output> {
outputs().into_iter().nth(i)
}

pub struct DisplayRequest {
/// Index into `outputs()` of the display to stream.
pub id: u32,
pub sender: std::sync::mpsc::Sender<input::InputEvent>,
pub ready: std::sync::mpsc::Receiver<()>,
}

/// The streamed display: an index into `outputs()` (0 is the primary).
pub fn display() -> u32 {
SETTINGS.lock().display as u32
}

/// Stream display `id` (an index into `outputs()`): pauses input, retires the current
/// viewers and queues the switch for the video thread. Mirrors mac::request_display.
pub fn request_display(hub: &crate::hub::Hub, id: u32, client: u64) -> Result<bool, String> {
if id as usize >= outputs().len() {
return Err("display is no longer connected".into());
}
if id == display() {
return Ok(false);
}
let mut pending = hub.display_req.lock();
let (sender, ready) = hub
.pause_display_input(client)
.ok_or("display switch already in progress")?;
*pending = Some(DisplayRequest { id, sender, ready });
hub.wake();
Ok(true)
}

/// Point capture at display `id` (an index into `outputs()`).
pub fn select_display(id: u32) -> Result<(), String> {
if id as usize >= outputs().len() {
return Err("display is no longer connected".into());
}
SETTINGS.lock().display = id as usize;
Ok(())
}

/// The displays `hello` advertises to the viewer's picker.
pub fn display_info() -> serde_json::Value {
let displays: Vec<_> = outputs()
.iter()
.enumerate()
.map(|(i, _)| {
let suffix = if i == 0 { " · Main" } else { "" };
serde_json::json!({ "id": i as u32, "name": format!("Display {}{suffix}", i + 1) })
})
.collect();
serde_json::json!({ "selected": display(), "available": displays })
}

/// Reads the Windows options. Must run before anything opens a window or a device
/// context, so every coordinate is in physical pixels.
pub fn init(a: &HashMap<String, String>) {
Expand All @@ -127,6 +184,9 @@ pub fn init(a: &HashMap<String, String>) {
);
}
let mut s = SETTINGS.lock();
s.resize_scale = a
.get("resize-scale")
.and_then(|v| v.rsplit('-').next()?.trim().parse().ok());
// --display: an index (0 is the primary display); ":1" style values work too.
if let Some(n) = a
.get("display")
Expand All @@ -153,6 +213,15 @@ pub fn dpi_scale() -> f64 {
x as f64 / 96.0
}

/// Desktop pixels per CSS pixel to resize to: --resize-scale, else the display's
/// scaling (1.5 at 150%).
pub fn resize_scale() -> f64 {
if let Some(s) = SETTINGS.lock().resize_scale {
return s;
}
dpi_scale()
}

/// UTF-16 with a terminating zero, for wide-string APIs.
pub fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
Expand Down
Loading