macOS: implement View Camera (remote camera viewing) (#17135)

* Update connection.rs

Added camera support for macOS

* scrap: enable nokhwa camera deps and cfg for macOS (frame path still TODO)

* scrap: allow PixelBuffer from raw bytes on macOS for camera frames

* macOS: request camera permission via nokhwa, add NSCameraUsageDescription

* macOS: add camera entitlement

* nokhwa: fix macOS bi-planar (NV12) camera frames via vendored patch

* nokhwa: point at filipklein5/nokhwa fix branch instead of vendoring

Replaces the vendored libs/nokhwa copy (~16.5k lines) with a git
dependency override pointing at the macOS NV12 fix on
filipklein5/nokhwa#macos-nv12-fix, submitted upstream as
rustdesk-org/nokhwa PR (see Cargo.toml comment). Keeps this PR's diff
focused on the macOS camera support itself.

* nokhwa: link to upstream PR #7

* address CodeRabbit review on #17135

- connection.rs: move the macOS camera-permission wait (can block up to
  30s) off the Tokio worker via spawn_blocking, so send_logon_response_
  and_keep_alive stays responsive to input/heartbeats while it's pending.
- camera.rs: build the non-Linux camera list in a local Vec and swap it
  into SYNC_CAMERA_DISPLAYS only after enumeration succeeds, instead of
  pushing into the shared cache mid-loop. A create_camera failure
  partway through no longer leaves the cache holding a stale prefix
  that disagrees with the Err this function returns (pre-existing on
  Windows; macOS now exercises the same path).
- Cargo.toml + res/osx_camera_info.plist: add NSCameraUsageDescription
  to the legacy Sciter macOS bundle via cargo-bundle's
  osx_info_plist_exts, so that build path (unlike the Flutter one)
  doesn't get killed at the camera permission prompt for lacking it.

* nokhwa: bump to 8920ff8 (420v + review fixes, rustdesk-org/nokhwa#7)

* keep non-macOS camera paths unchanged

- camera.rs: drop the SYNC_CAMERA_DISPLAYS local-vector rework of the
  non-Linux loop; it also changed Windows and fixes a pre-existing
  issue, so it belongs in a separate PR.
- connection.rs: use spawn_blocking for Cameras::all_info() on macOS
  only (the permission wait is macOS-specific); other platforms keep the
  original call.

* macOS: only advertise/use View Camera when AVCaptureDeviceDiscoverySession exists

nokhwa's AVFoundation query uses AVCaptureDeviceDiscoverySession, which
exists only on macOS 10.15+; on 10.14 hosts class! panics and the
release profile aborts the server. Probe the class at runtime:
- connection.rs: advertise support_view_camera on macOS only if present
  (the windows/linux line is back to its original form).
- camera.rs: all_info()/exists()/create_camera() return no cameras (or
  an error) when it is missing.
Also bumps nokhwa to 0a8bf56 (recv_timeout in the macOS frame_raw).

* nokhwa: bump to 5439c78 (releases the configuration lock, rustdesk-org/nokhwa#7)

* nokhwa: bump to d390711 (hold the configuration lock only while starting the stream, rustdesk-org/nokhwa#7)

* nokhwa: bump to a509e0e (configure() closure unlocks on every path, rustdesk-org/nokhwa#7)

* nokhwa: bump to 5bd00f5 (configure() takes &Self, can't swap the unlocked device, rustdesk-org/nokhwa#7)

* nokhwa: drop the [patch] now that rustdesk-org/nokhwa#7 is merged

rustdesk-org/nokhwa#7 merged into fix_from_raw_parts at 137a327.
Cargo.toml's existing git dependency now resolves there directly, so
the temporary [patch] to filipklein5/nokhwa is no longer needed.

* quartz.rs: drop PixelBuffer::from_frame, inline the screen constructor

The screen-capture call site now constructs PixelSource::Screen
directly, as it did before this feature (just with the new field
names). The extra from_frame helper only existed to wrap that one
call, which AGENTS.md asks to avoid: the screen path shouldn't change
shape just because camera.rs needs PixelBuffer::new.

* address maintainer review round 3

- camera.rs: gate exists() and create_camera() on macOS on
  nokhwa::nokhwa_check() too, not just is_camera_supported(). Without
  it, a denied/timed-out permission let exists() report a camera
  anyway, so the server started the camera0 video service and spammed
  unthrottled errors while touching AVFoundation without permission.
  all_info() always runs ensure_macos_camera_permission() first during
  login, so by the time these run the permission state is settled.
- connection.rs: log the Err from Cameras::all_info() (permission
  denied / timed out) before falling back to an empty Vec, instead of
  dropping it silently via unwrap_or_default().
- camera.rs: remove the FIXME above the PixelBuffer::new call; it's
  stale now that macOS implements it.
- quartz.rs: PixelBuffer::new computes stride from pixfmt.bytes_per_pixel()
  instead of hardcoding width * 4, so non-32bpp formats get a correct
  stride too.

* nokhwa: bump to f149b07 (rustdesk-org/nokhwa#8 merged, fixes macOS 10.14 launch crash)
This commit is contained in:
Filip Klein authored and GitHub committed 2026-11-23 00:38:35 +08:00
1 parent 90f3fb136b
commit 5a64e7a61f
10 files changed
+139 -30

No files matched your search

Generated
+6 -5
View File
@@ -5046,7 +5046,7 @@ dependencies = [
[[package]]
name = "nokhwa"
version = "0.10.7"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#c2f74662b6ce117f7f94301693fdfadc0b1ec91a"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#f149b074d081004920495f04444503a2379ca795"
dependencies = [
"flume",
"image 0.25.1",
@@ -5061,7 +5061,7 @@ dependencies = [
[[package]]
name = "nokhwa-bindings-linux"
version = "0.1.1"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#c2f74662b6ce117f7f94301693fdfadc0b1ec91a"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#f149b074d081004920495f04444503a2379ca795"
dependencies = [
"nokhwa-core",
"v4l",
@@ -5070,7 +5070,7 @@ dependencies = [
[[package]]
name = "nokhwa-bindings-macos"
version = "0.2.2"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#c2f74662b6ce117f7f94301693fdfadc0b1ec91a"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#f149b074d081004920495f04444503a2379ca795"
dependencies = [
"block",
"cocoa-foundation",
@@ -5086,7 +5086,7 @@ dependencies = [
[[package]]
name = "nokhwa-bindings-windows"
version = "0.4.2"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#c2f74662b6ce117f7f94301693fdfadc0b1ec91a"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#f149b074d081004920495f04444503a2379ca795"
dependencies = [
"dlopen",
"lazy_static",
@@ -5098,7 +5098,7 @@ dependencies = [
[[package]]
name = "nokhwa-core"
version = "0.1.5"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#c2f74662b6ce117f7f94301693fdfadc0b1ec91a"
source = "git+https://github.com/rustdesk-org/nokhwa.git?branch=fix_from_raw_parts#f149b074d081004920495f04444503a2379ca795"
dependencies = [
"bytes",
"image 0.25.1",
@@ -7413,6 +7413,7 @@ dependencies = [
"ndk-context",
"nokhwa",
"num_cpus",
"objc",
"pkg-config",
"quest",
"repng",
+3
View File
@@ -283,6 +283,9 @@ name = "RustDesk"
identifier = "com.carriez.rustdesk"
icon = ["res/32x32.png", "res/128x128.png", "res/128x128@2x.png"]
osx_minimum_system_version = "10.14"
# View Camera needs NSCameraUsageDescription or macOS kills the process at the
# camera permission prompt; the Flutter bundle gets it via its own Info.plist.
osx_info_plist_exts = ["res/osx_camera_info.plist"]
#https://github.com/johnthagen/min-sized-rust
[profile.release]
@@ -6,6 +6,8 @@
<false/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
<key>com.apple.security.device.audio-input</key>
<true/>
<key>com.apple.security.network.server</key>
+2
View File
@@ -41,6 +41,8 @@
<string>$(PRODUCT_COPYRIGHT)</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSCameraUsageDescription</key>
<string>Capture video from the camera for the purpose of remote camera viewing.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Record the sound from microphone for the purpose of the remote desktop.</string>
<key>NSPrincipalClass</key>
@@ -6,6 +6,8 @@
<false/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
<key>com.apple.security.device.audio-input</key>
<true/>
<key>com.apple.security.network.client</key>
+2 -1
View File
@@ -42,6 +42,7 @@ features = ["dxgi", "dxgi1_2", "dxgi1_5", "dxgi1_6", "d3d11", "winuser", "winerr
[target.'cfg(target_os = "macos")'.dependencies]
block = "0.1"
objc = "0.2"
[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.13"
@@ -74,6 +75,6 @@ zbus = { version = "3.15", optional = true }
git = "https://github.com/rustdesk-org/hwcodec"
optional = true
[target.'cfg(any(target_os = "windows", target_os = "linux"))'.dependencies]
[target.'cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))'.dependencies]
nokhwa = { git = "https://github.com/rustdesk-org/nokhwa.git", branch = "fix_from_raw_parts", features = ["input-native"] }
+58 -13
View File
@@ -3,7 +3,7 @@ use std::{
sync::{Arc, Mutex},
};
#[cfg(any(target_os = "windows", target_os = "linux"))]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
use nokhwa::{
pixel_format::RgbAFormat,
query,
@@ -18,7 +18,7 @@ use crate::AdapterDevice;
use crate::common::{bail, ResultType};
use crate::{Frame, TraitCapturer};
#[cfg(any(target_os = "windows", target_os = "linux"))]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
use crate::{PixelBuffer, Pixfmt};
pub const PRIMARY_CAMERA_IDX: usize = 0;
@@ -26,7 +26,7 @@ lazy_static::lazy_static! {
static ref SYNC_CAMERA_DISPLAYS: Arc<Mutex<Vec<DisplayInfo>>> = Arc::new(Mutex::new(Vec::new()));
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
const CAMERA_NOT_SUPPORTED: &str = "This platform doesn't support camera yet";
pub struct Cameras;
@@ -36,9 +36,43 @@ pub fn primary_camera_exists() -> bool {
Cameras::exists(PRIMARY_CAMERA_IDX)
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
/// nokhwa's AVFoundation query uses `AVCaptureDeviceDiscoverySession`, which exists only on
/// macOS 10.15+. Without it `class!` panics, and the release profile aborts the process.
#[cfg(target_os = "macos")]
pub fn is_camera_supported() -> bool {
objc::runtime::Class::get("AVCaptureDeviceDiscoverySession").is_some()
}
/// AVFoundation requires the camera permission to be requested (and granted) before any
/// other nokhwa call. Blocks up to 30s while the system prompt is shown.
#[cfg(target_os = "macos")]
fn ensure_macos_camera_permission() -> ResultType<()> {
if nokhwa::nokhwa_check() {
return Ok(());
}
let (tx, rx) = std::sync::mpsc::channel();
let tx = Mutex::new(tx);
nokhwa::nokhwa_initialize(move |granted| {
if let Ok(tx) = tx.lock() {
let _ = tx.send(granted);
}
});
match rx.recv_timeout(std::time::Duration::from_secs(30)) {
Ok(true) => Ok(()),
Ok(false) => bail!("Camera permission denied"),
Err(_) => bail!("Timed out waiting for camera permission"),
}
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
impl Cameras {
pub fn all_info() -> ResultType<Vec<DisplayInfo>> {
#[cfg(target_os = "macos")]
if !is_camera_supported() {
return Ok(Vec::new());
}
#[cfg(target_os = "macos")]
ensure_macos_camera_permission()?;
match query(ApiBackend::Auto) {
Ok(cameras) => {
let mut camera_displays = SYNC_CAMERA_DISPLAYS.lock().unwrap();
@@ -116,6 +150,10 @@ impl Cameras {
}
pub fn exists(index: usize) -> bool {
#[cfg(target_os = "macos")]
if !is_camera_supported() || !nokhwa::nokhwa_check() {
return false;
}
match query(ApiBackend::Auto) {
Ok(cameras) => index < cameras.len(),
_ => return false,
@@ -123,6 +161,14 @@ impl Cameras {
}
fn create_camera(index: &CameraIndex) -> ResultType<Camera> {
#[cfg(target_os = "macos")]
if !is_camera_supported() {
bail!("Camera is not supported on this macOS version");
}
#[cfg(target_os = "macos")]
if !nokhwa::nokhwa_check() {
bail!("Camera permission not granted");
}
let format_type = if cfg!(target_os = "linux") {
RequestedFormatType::None
} else {
@@ -158,7 +204,7 @@ impl Cameras {
}
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
impl Cameras {
pub fn all_info() -> ResultType<Vec<DisplayInfo>> {
return Ok(Vec::new());
@@ -181,18 +227,18 @@ impl Cameras {
}
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub struct CameraCapturer {
camera: Camera,
data: Vec<u8>,
last_data: Vec<u8>, // for faster compare and copy
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
pub struct CameraCapturer;
impl CameraCapturer {
#[cfg(any(target_os = "windows", target_os = "linux"))]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
fn new(current: usize) -> ResultType<Self> {
let index = CameraIndex::Index(current as u32);
let camera = Cameras::create_camera(&index)?;
@@ -204,14 +250,14 @@ impl CameraCapturer {
}
#[allow(dead_code)]
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
fn new(_current: usize) -> ResultType<Self> {
bail!(CAMERA_NOT_SUPPORTED);
}
}
impl TraitCapturer for CameraCapturer {
#[cfg(any(target_os = "windows", target_os = "linux"))]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
fn frame<'a>(&'a mut self, _timeout: std::time::Duration) -> std::io::Result<Frame<'a>> {
// TODO: move this check outside `frame`.
if !self.camera.is_stream_open() {
@@ -228,9 +274,8 @@ impl TraitCapturer for CameraCapturer {
Ok(decoded) => {
self.data = decoded.as_raw().to_vec();
crate::would_block_if_equal(&mut self.last_data, &self.data)?;
// FIXME: macos's PixelBuffer cannot be directly created from bytes slice.
cfg_if::cfg_if! {
if #[cfg(any(target_os = "linux", target_os = "windows"))] {
if #[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))] {
Ok(Frame::PixelBuffer(PixelBuffer::new(
&self.data,
Pixfmt::RGBA,
@@ -258,7 +303,7 @@ impl TraitCapturer for CameraCapturer {
}
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
fn frame<'a>(&'a mut self, _timeout: std::time::Duration) -> std::io::Result<Frame<'a>> {
Err(io::Error::new(
io::ErrorKind::Other,
+39 -10
View File
@@ -1,5 +1,4 @@
use crate::{quartz, Frame, Pixfmt};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, TryLockError};
use std::{io, mem};
@@ -56,8 +55,7 @@ impl crate::TraitCapturer for Capturer {
crate::would_block_if_equal(&mut self.saved_raw_data, frame.inner())?;
frame.surface_to_bgra(self.height());
Ok(Frame::PixelBuffer(PixelBuffer {
frame,
data: PhantomData,
source: PixelSource::Screen(frame),
width: self.width(),
height: self.height(),
}))
@@ -74,16 +72,43 @@ impl crate::TraitCapturer for Capturer {
}
}
enum PixelSource<'a> {
Screen(quartz::Frame),
Bytes {
data: &'a [u8],
pixfmt: Pixfmt,
stride: usize,
},
}
pub struct PixelBuffer<'a> {
frame: quartz::Frame,
data: PhantomData<&'a [u8]>,
source: PixelSource<'a>,
width: usize,
height: usize,
}
impl<'a> PixelBuffer<'a> {
/// Wraps tightly packed data (e.g. RGBA from a camera).
pub fn new(data: &'a [u8], pixfmt: Pixfmt, width: usize, height: usize) -> Self {
let stride = width * pixfmt.bytes_per_pixel();
PixelBuffer {
source: PixelSource::Bytes {
data,
pixfmt,
stride,
},
width,
height,
}
}
}
impl<'a> crate::TraitPixelBuffer for PixelBuffer<'a> {
fn data(&self) -> &[u8] {
&*self.frame
match &self.source {
PixelSource::Screen(frame) => &**frame,
PixelSource::Bytes { data, .. } => data,
}
}
fn width(&self) -> usize {
@@ -95,13 +120,17 @@ impl<'a> crate::TraitPixelBuffer for PixelBuffer<'a> {
}
fn stride(&self) -> Vec<usize> {
let mut v = Vec::new();
v.push(self.frame.stride());
v
match &self.source {
PixelSource::Screen(frame) => vec![frame.stride()],
PixelSource::Bytes { stride, .. } => vec![*stride],
}
}
fn pixfmt(&self) -> Pixfmt {
Pixfmt::BGRA
match &self.source {
PixelSource::Screen(_) => Pixfmt::BGRA,
PixelSource::Bytes { pixfmt, .. } => *pixfmt,
}
}
}
+2
View File
@@ -0,0 +1,2 @@
<key>NSCameraUsageDescription</key>
<string>Capture video from the camera for the purpose of remote camera viewing.</string>
+23 -1
View File
@@ -2058,6 +2058,10 @@ impl Connection {
{
platform_additions.insert("support_view_camera".into(), json!(true));
}
#[cfg(target_os = "macos")]
if camera::is_camera_supported() {
platform_additions.insert("support_view_camera".into(), json!(true));
}
#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
if !platform_additions.is_empty() {
@@ -2153,7 +2157,25 @@ impl Connection {
log::info!("peer info supported_encoding: {:?}", supported_encoding);
pi.encoding = Some(supported_encoding).into();
pi.displays = camera::Cameras::all_info().unwrap_or(Vec::new());
// On macOS this can block for up to 30s waiting on the camera permission prompt, so
// keep it off the Tokio worker.
#[cfg(target_os = "macos")]
{
pi.displays = tokio::task::spawn_blocking(camera::Cameras::all_info)
.await
.unwrap_or_else(|e| {
log::error!("camera all_info task panicked: {}", e);
Ok(Vec::new())
})
.unwrap_or_else(|e| {
log::error!("camera all_info error: {}", e);
Vec::new()
});
}
#[cfg(not(target_os = "macos"))]
{
pi.displays = camera::Cameras::all_info().unwrap_or(Vec::new());
}
pi.current_display = camera::PRIMARY_CAMERA_IDX as _;
#[cfg(not(any(target_os = "android", target_os = "ios")))]
{