Skip to content
Draft
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: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,10 @@ apps that should hear you.
The other flags work as on Linux; `--audio-device-name`, `--microphone-fifo` and the
rounded-corner flags don't apply.

With `--enable-resize --restore-display-on-disconnect`, voxl saves the display mode
before the first resize. It restores that mode after the last client disconnects and
a short reconnect period. A mode chosen outside voxl after its last resize stays in place.

### Windows

voxl also streams a Windows desktop (Windows 10 or later), with every feature of the
Expand Down
3 changes: 3 additions & 0 deletions src/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ Desktop (this Mac's screen):
(default false)
--resize-scale display pixels per CSS pixel (default: the
capture scale)
--restore-display-on-disconnect
restore the mode before the first resize when
the last viewer leaves (default false)
--read-only viewers only watch (default false)
--show-cursor include the host cursor in the video stream
(default: true with --read-only, else false)
Expand Down
98 changes: 97 additions & 1 deletion src/hub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use parking_lot::Mutex;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
#[cfg(target_os = "macos")]
use std::time::Duration;
use std::time::Instant;
use tokio::sync::mpsc;

Expand Down Expand Up @@ -240,6 +242,11 @@ pub struct Hub {
/// Connections older than this may no longer inject input after a display switch.
#[cfg(target_os = "macos")]
pub input_floor: AtomicU64,
#[cfg(target_os = "macos")]
pub restore_display_on_disconnect: AtomicBool,
/// Updated while holding the clients lock, so viewer admission and restore agree.
#[cfg(target_os = "macos")]
last_client_left: Mutex<Option<Instant>>,
pub clients: Mutex<Vec<Arc<Client>>>,
pub next_id: AtomicU64,
pub stats: Stats,
Expand Down Expand Up @@ -274,6 +281,10 @@ impl Hub {
display_req: Mutex::new(None),
#[cfg(target_os = "macos")]
input_floor: AtomicU64::new(0),
#[cfg(target_os = "macos")]
restore_display_on_disconnect: AtomicBool::new(false),
#[cfg(target_os = "macos")]
last_client_left: Mutex::new(None),
clients: Mutex::new(Vec::new()),
next_id: AtomicU64::new(1),
stats: Stats::default(),
Expand Down Expand Up @@ -327,10 +338,46 @@ impl Hub {
}

pub fn remove_client(&self, id: u64) {
self.clients.lock().retain(|c| c.id != id);
{
let mut clients = self.clients.lock();
#[cfg(target_os = "macos")]
let had_clients = !clients.is_empty();
clients.retain(|c| c.id != id);
#[cfg(target_os = "macos")]
if self.restore_display_on_disconnect.load(Ordering::Relaxed)
&& had_clients
&& clients.is_empty()
{
// Don't let a size request from the old connection apply to the next.
self.resize_req.lock().take();
*self.last_client_left.lock() = Some(Instant::now());
}
}
self.wake();
}

#[cfg(target_os = "macos")]
fn display_is_idle(&self, clients: &[Arc<Client>]) -> bool {
clients.is_empty()
&& self
.last_client_left
.lock()
.is_some_and(|left| left.elapsed() >= Duration::from_millis(500))
}

#[cfg(target_os = "macos")]
pub fn display_restore_due(&self) -> bool {
self.display_is_idle(&self.clients.lock())
}

#[cfg(target_os = "macos")]
pub fn restore_idle_display<T>(&self, restore: impl FnOnce() -> T) -> Option<T> {
// Recheck after the capture pipeline drained, and keep admission serialized
// until the mode change is complete.
let clients = self.clients.lock();
self.display_is_idle(&clients).then(restore)
}

pub fn video_clients(&self) -> Vec<Arc<Client>> {
self.clients
.lock()
Expand Down Expand Up @@ -394,3 +441,52 @@ impl Hub {
Some(crate::mac::DisplayRequest { id, sender, ready })
}
}

#[cfg(all(test, target_os = "macos"))]
mod display_restore_tests {
use super::*;

#[test]
fn restore_waits_for_the_last_client_even_if_video_is_paused() {
let hub = Hub::new();
hub.restore_display_on_disconnect
.store(true, Ordering::Relaxed);
let (tx, _rx) = mpsc::unbounded_channel();
let first = hub.add_client(tx.clone());
let paused = hub.add_client(tx.clone());
first.video.store(true, Ordering::Relaxed);
*hub.resize_req.lock() = Some((800, 600));
hub.remove_client(first.id);

assert!(hub.video_clients().is_empty());
assert!(!hub.display_restore_due());
assert_eq!(*hub.resize_req.lock(), Some((800, 600)));

hub.remove_client(paused.id);
assert!(hub.resize_req.lock().is_none());
*hub.last_client_left.lock() = Some(Instant::now() - Duration::from_secs(1));
assert!(hub.display_restore_due());

// A fast reconnect after the capture thread queued the restore cancels it.
let reconnect = hub.add_client(tx);
assert!(hub
.restore_idle_display(|| panic!("viewer is connected"))
.is_none());
let previous_disconnect = hub.last_client_left.lock().unwrap();
hub.remove_client(reconnect.id);
assert!(hub.last_client_left.lock().unwrap() > previous_disconnect);
*hub.last_client_left.lock() = Some(Instant::now() - Duration::from_secs(1));
assert_eq!(hub.restore_idle_display(|| "restored"), Some("restored"));
}

#[test]
fn disconnect_leaves_pending_resize_alone_when_restore_is_disabled() {
let hub = Hub::new();
let (tx, _rx) = mpsc::unbounded_channel();
let client = hub.add_client(tx);
*hub.resize_req.lock() = Some((800, 600));
hub.remove_client(client.id);
assert_eq!(*hub.resize_req.lock(), Some((800, 600)));
assert!(!hub.display_restore_due());
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ async fn serve(a: HashMap<String, String>) {
display: display.clone(),
#[cfg(target_os = "macos")]
enable_resize: truthy(a.get("enable-resize"), false) && !truthy(a.get("read-only"), false),
#[cfg(target_os = "macos")]
restore_display_on_disconnect: truthy(a.get("restore-display-on-disconnect"), false),
fps: range_max(a.get("framerate"), 60.0) as u32,
preset: a
.get("preset")
Expand Down
89 changes: 71 additions & 18 deletions src/mac/screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ struct Mode {
pub struct Screen {
display: u32,
original: Mode,
resized: bool,
last_resize: Option<i32>,
restore_on_disconnect: bool,
idle_restore_failed: bool,
modes: Vec<Mode>,
max: (u32, u32),
current: (u32, u32),
Expand All @@ -48,20 +50,11 @@ impl Screen {
pub fn open(_display: Option<&str>) -> Result<Self, String> {
let display = super::display();
let mut modes: Vec<Mode> = Vec::new();
let original;
let original = Mode::current(display)?;
unsafe {
let cur = CGDisplayCopyDisplayMode(display);
if cur.is_null() {
return Err("no display mode".into());
}
let hidpi = CGDisplayModeGetPixelWidth(cur) > CGDisplayModeGetWidth(cur);
let current = (CGDisplayModeGetWidth(cur), CGDisplayModeGetHeight(cur));
let rate = CGDisplayModeGetRefreshRate(cur);
original = Mode {
mode: cur,
points: current,
size: super::size_for(current.0 as f64, current.1 as f64),
};
let current = original.points;
let hidpi = CGDisplayModeGetPixelWidth(original.mode) > current.0;
let rate = CGDisplayModeGetRefreshRate(original.mode);
let key = kCGDisplayShowDuplicateLowResolutionModes;
let opts = objc2_core_foundation::CFDictionary::from_slices(
&[&*(key as *const objc2_core_foundation::CFString)],
Expand Down Expand Up @@ -118,7 +111,9 @@ impl Screen {
Ok(Screen {
display,
original,
resized: false,
last_resize: None,
restore_on_disconnect: false,
idle_restore_failed: false,
modes,
max,
current: super::capture_size(display),
Expand All @@ -133,6 +128,22 @@ impl Screen {
fit(w, h, self.max)
}

pub fn restore_on_disconnect(&mut self, enabled: bool) {
self.restore_on_disconnect = enabled;
}

pub fn needs_idle_restore(&self) -> bool {
self.last_resize.is_some() && !self.idle_restore_failed
}

pub fn restore_after_disconnect(&mut self) -> Result<(), String> {
let result = self.restore();
// A disconnected display may refuse its old mode. Keep the snapshot for
// an explicit display switch, but do not continuously rebuild capture.
self.idle_restore_failed = result.is_err();
result
}

pub fn resize(&mut self, w: u32, h: u32) -> Result<(), String> {
let want = self.fit(w, h);
self.current = super::capture_size(self.display);
Expand All @@ -144,8 +155,17 @@ impl Screen {
.iter()
.find(|m| m.size == want)
.ok_or("no such mode")?;
// Save the live mode, since the user could change it after voxl started.
// Keep it only if this resize actually succeeds.
let previous = (self.restore_on_disconnect && self.last_resize.is_none())
.then(|| Mode::current(self.display))
.transpose()?;
set_mode(self.display, m)?;
self.resized = true;
if let Some(previous) = previous {
self.original = previous;
}
self.last_resize = Some(m.id());
self.idle_restore_failed = false;
self.current = want;
log::info!(
"display set to {}x{} points ({}x{} streamed)",
Expand All @@ -158,15 +178,48 @@ impl Screen {
}

pub fn restore(&mut self) -> Result<(), String> {
if self.resized {
if let Some(last_resize) = self.last_resize {
// A change made outside voxl after its last resize takes precedence.
if self.restore_on_disconnect && Mode::current(self.display)?.id() != last_resize {
self.last_resize = None;
return Ok(());
}
set_mode(self.display, &self.original)?;
self.current = self.original.size;
self.resized = false;
self.last_resize = None;
if self.restore_on_disconnect {
log::info!(
"restored display to {}x{} points",
self.original.points.0,
self.original.points.1
);
}
}
Ok(())
}
}

impl Mode {
fn current(display: u32) -> Result<Self, String> {
unsafe {
let mode = CGDisplayCopyDisplayMode(display);
if mode.is_null() {
return Err("no display mode".into());
}
let points = (CGDisplayModeGetWidth(mode), CGDisplayModeGetHeight(mode));
Ok(Self {
mode,
points,
size: super::size_for(points.0 as f64, points.1 as f64),
})
}
}

fn id(&self) -> i32 {
unsafe { CGDisplayModeGetIODisplayModeID(self.mode) }
}
}

fn set_mode(display: u32, m: &Mode) -> Result<(), String> {
unsafe {
let mut cfg: CGDisplayConfigRef = std::ptr::null_mut();
Expand Down
Loading