Skip to content

An open-source remote desktop application designed for self-hosting, as an alternative to TeamViewer.

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

Filip Klein5a64e7a61ff8
diff --git a/Cargo.lock b/Cargo.lock
index 0c99b8dc5..72edd2e10 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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",
diff --git a/Cargo.toml b/Cargo.toml
index 31cfcd446..238c07b59 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -283,6 +283,9 @@ name = "RustDesk"
identifier = "com.carriez.rustdesk"
icon = ["res/32x32.png", "res/128x128.png", "res/[email protected]"]
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]
diff --git a/flutter/macos/Runner/DebugProfile.entitlements b/flutter/macos/Runner/DebugProfile.entitlements
index b52c39df4..45d932d0d 100644
--- a/flutter/macos/Runner/DebugProfile.entitlements
+++ b/flutter/macos/Runner/DebugProfile.entitlements
@@ -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>
diff --git a/flutter/macos/Runner/Info.plist b/flutter/macos/Runner/Info.plist
index 36ca81e18..357007469 100644
--- a/flutter/macos/Runner/Info.plist
+++ b/flutter/macos/Runner/Info.plist
@@ -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>
diff --git a/flutter/macos/Runner/Release.entitlements b/flutter/macos/Runner/Release.entitlements
index 7f588d928..b3b4d853f 100644
--- a/flutter/macos/Runner/Release.entitlements
+++ b/flutter/macos/Runner/Release.entitlements
@@ -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>
diff --git a/libs/scrap/Cargo.toml b/libs/scrap/Cargo.toml
index 185c38f30..4fcde5103 100644
--- a/libs/scrap/Cargo.toml
+++ b/libs/scrap/Cargo.toml
@@ -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"] }
diff --git a/libs/scrap/src/common/camera.rs b/libs/scrap/src/common/camera.rs
index e31a37a27..7aae97345 100644
--- a/libs/scrap/src/common/camera.rs
+++ b/libs/scrap/src/common/camera.rs
@@ -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,
diff --git a/libs/scrap/src/common/quartz.rs b/libs/scrap/src/common/quartz.rs
index b6a63e826..519245e00 100644
--- a/libs/scrap/src/common/quartz.rs
+++ b/libs/scrap/src/common/quartz.rs
@@ -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,
+ }
}
}
diff --git a/res/osx_camera_info.plist b/res/osx_camera_info.plist
new file mode 100644
index 000000000..b183b7e4d
--- /dev/null
+++ b/res/osx_camera_info.plist
@@ -0,0 +1,2 @@
+<key>NSCameraUsageDescription</key>
+<string>Capture video from the camera for the purpose of remote camera viewing.</string>
diff --git a/src/server/connection.rs b/src/server/connection.rs
index 1abe6f4af..4fe8111f0 100644
--- a/src/server/connection.rs
+++ b/src/server/connection.rs
@@ -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")))]
{