fix(macos): sharing a window opens the system window picker (#97)
Co-authored-by: Gemini Neon <noreply@google.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@@ -9,13 +9,16 @@ rustflags = ["-C", "target-feature=+crt-static"]
9
9
linker = "clang"
10
10
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
11
11
12
# macOS 14 is the minimum: screen and window sharing use ScreenCaptureKit's
13
# SCContentSharingPicker (macOS 14+). Ignored by other targets; an exported
14
# MACOSX_DEPLOYMENT_TARGET still wins. scripts/build-macos.sh exports the same
15
# default for release builds: keep both in sync.
16
[env]
17
MACOSX_DEPLOYMENT_TARGET = "14.0"
18
12
19
# libwebrtc's ObjC categories (NSString+StdString, RTCVideoCodecInfo, ...) live in unlinked
13
20
# objects of the prebuilt static lib; without -ObjC the app aborts in a C++ static initializer
14
21
# (RTCH264ProfileLevelId.mm) before main. webrtc-sys already passes -ObjC, but a dependency's
15
# link flags never reach the final binary. The x86_64 prebuilt also autolinks a Swift runtime
16
# dylib (@rpath/libswiftCoreMedia.dylib) that lives in the dyld shared cache only.
22
# link flags never reach the final binary.
17
23
[target.aarch64-apple-darwin]
18
rustflags = ["-C", "link-arg=-ObjC", "-C", "link-arg=-Wl,-rpath,/usr/lib/swift"]
19
20
[target.x86_64-apple-darwin]
21
rustflags = ["-C", "link-arg=-ObjC", "-C", "link-arg=-Wl,-rpath,/usr/lib/swift"]
24
rustflags = ["-C", "link-arg=-ObjC"]
@@ -9,13 +9,16 @@ rustflags = ["-C", "target-feature=+crt-static"]9
linker = "clang"9
linker = "clang"10
rustflags = ["-C", "link-arg=-fuse-ld=mold"]10
rustflags = ["-C", "link-arg=-fuse-ld=mold"]11
11
12
# macOS 14 is the minimum: screen and window sharing use ScreenCaptureKit's13
# SCContentSharingPicker (macOS 14+). Ignored by other targets; an exported14
# MACOSX_DEPLOYMENT_TARGET still wins. scripts/build-macos.sh exports the same15
# default for release builds: keep both in sync.16
[env]17
MACOSX_DEPLOYMENT_TARGET = "14.0"18
12
# libwebrtc's ObjC categories (NSString+StdString, RTCVideoCodecInfo, ...) live in unlinked19
# libwebrtc's ObjC categories (NSString+StdString, RTCVideoCodecInfo, ...) live in unlinked13
# objects of the prebuilt static lib; without -ObjC the app aborts in a C++ static initializer20
# objects of the prebuilt static lib; without -ObjC the app aborts in a C++ static initializer14
# (RTCH264ProfileLevelId.mm) before main. webrtc-sys already passes -ObjC, but a dependency's21
# (RTCH264ProfileLevelId.mm) before main. webrtc-sys already passes -ObjC, but a dependency's15
# link flags never reach the final binary. The x86_64 prebuilt also autolinks a Swift runtime22
# link flags never reach the final binary.16
# dylib (@rpath/libswiftCoreMedia.dylib) that lives in the dyld shared cache only.17
[target.aarch64-apple-darwin]23
[target.aarch64-apple-darwin]18
rustflags = ["-C", "link-arg=-ObjC", "-C", "link-arg=-Wl,-rpath,/usr/lib/swift"]24
rustflags = ["-C", "link-arg=-ObjC"]19
20
[target.x86_64-apple-darwin]21
rustflags = ["-C", "link-arg=-ObjC", "-C", "link-arg=-Wl,-rpath,/usr/lib/swift"]@@ -1,5 +1,5 @@
1
# Builds per README "Quick start": `cargo build -p app`, plus the universal macOS
2
# binary from scripts/build-macos.sh and the Linux packages from
1
# Builds per README "Quick start": `cargo build -p app`, plus the Apple Silicon
2
# macOS .app from scripts/build-macos.sh and the Linux packages from
3
3
# packaging/linux/package.sh. Tests live in test.yml; this file only packages the
4
4
# artifacts.
5
5
name: Build
@@ -200,16 +200,15 @@ jobs:
200
200
with:
201
201
key: build
202
202
203
# scripts/build-macos.sh builds the arm64 and x86_64 slices, lipos them into
204
# one universal binary and wraps it in a .app with the icon (README "Quick
205
# start"); it installs the x86_64 rustup target itself and needs Xcode CLT only.
203
# scripts/build-macos.sh builds the aarch64-apple-darwin binary and wraps
204
# it in a .app with the icon (README "Quick start"); it needs Xcode CLT only.
206
205
- name: Build
207
206
run: scripts/build-macos.sh crates/app teams
208
207
209
208
- uses: actions/upload-artifact@v7
210
209
with:
211
210
name: teams-macos
212
path: target/universal/release/teams-macos.zip
211
path: target/aarch64-apple-darwin/release/teams-macos.zip
213
212
214
213
release:
215
214
name: Release
@@ -295,7 +294,7 @@ jobs:
295
294
fi
296
295
take dist/teams-windows-amd64/teams.exe "release/rusty-teams-$ver-windows-amd64.exe" "windows-amd64"
297
296
take dist/teams-windows-arm64/teams.exe "release/rusty-teams-$ver-windows-arm64.exe" "windows-arm64"
298
take dist/teams-macos/teams-macos.zip "release/rusty-teams-$ver-macos-universal.zip" "macos"
297
take dist/teams-macos/teams-macos.zip "release/rusty-teams-$ver-macos-arm64.zip" "macos"
299
298
shopt -s nullglob
300
299
packages=(dist/teams-linux-packages/*)
301
300
if (( ${#packages[@]} )); then
@@ -1,5 +1,5 @@1
# Builds per README "Quick start": `cargo build -p app`, plus the universal macOS1
# Builds per README "Quick start": `cargo build -p app`, plus the Apple Silicon2
# binary from scripts/build-macos.sh and the Linux packages from2
# macOS .app from scripts/build-macos.sh and the Linux packages from3
# packaging/linux/package.sh. Tests live in test.yml; this file only packages the3
# packaging/linux/package.sh. Tests live in test.yml; this file only packages the4
# artifacts.4
# artifacts.5
name: Build5
name: Build@@ -200,16 +200,15 @@ jobs:200
with:200
with:201
key: build201
key: build202
202
203
# scripts/build-macos.sh builds the arm64 and x86_64 slices, lipos them into203
# scripts/build-macos.sh builds the aarch64-apple-darwin binary and wraps204
# one universal binary and wraps it in a .app with the icon (README "Quick204
# it in a .app with the icon (README "Quick start"); it needs Xcode CLT only.205
# start"); it installs the x86_64 rustup target itself and needs Xcode CLT only.206
- name: Build205
- name: Build207
run: scripts/build-macos.sh crates/app teams206
run: scripts/build-macos.sh crates/app teams208
207
209
- uses: actions/upload-artifact@v7208
- uses: actions/upload-artifact@v7210
with:209
with:211
name: teams-macos210
name: teams-macos212
path: target/universal/release/teams-macos.zip211
path: target/aarch64-apple-darwin/release/teams-macos.zip213
212
214
release:213
release:215
name: Release214
name: Release@@ -295,7 +294,7 @@ jobs:295
fi294
fi296
take dist/teams-windows-amd64/teams.exe "release/rusty-teams-$ver-windows-amd64.exe" "windows-amd64"295
take dist/teams-windows-amd64/teams.exe "release/rusty-teams-$ver-windows-amd64.exe" "windows-amd64"297
take dist/teams-windows-arm64/teams.exe "release/rusty-teams-$ver-windows-arm64.exe" "windows-arm64"296
take dist/teams-windows-arm64/teams.exe "release/rusty-teams-$ver-windows-arm64.exe" "windows-arm64"298
take dist/teams-macos/teams-macos.zip "release/rusty-teams-$ver-macos-universal.zip" "macos"297
take dist/teams-macos/teams-macos.zip "release/rusty-teams-$ver-macos-arm64.zip" "macos"299
shopt -s nullglob298
shopt -s nullglob300
packages=(dist/teams-linux-packages/*)299
packages=(dist/teams-linux-packages/*)301
if (( ${#packages[@]} )); then300
if (( ${#packages[@]} )); then@@ -15,3 +15,4 @@ docs/design/islands/*
15
15
docs/research/*
16
16
!docs/research/internal-endpoints.md
17
17
dist/
18
.DS_Store
@@ -15,3 +15,4 @@ docs/design/islands/*15
docs/research/*15
docs/research/*16
!docs/research/internal-endpoints.md16
!docs/research/internal-endpoints.md17
dist/17
dist/18
.DS_Store@@ -92,7 +92,7 @@
92
92
|---|---|---|---|
93
93
| Support | Main target | Supported | Supported |
94
94
| Sign-in | Embedded WebView2 | Your browser, headless | Your browser, headless |
95
| Download | `.exe` | `.tar.gz`, self-installs to the app menu | Universal `.app` (arm64 + x86_64) |
95
| Download | `.exe` | `.tar.gz`, self-installs to the app menu | `.app` (Apple Silicon, macOS 14+) |
96
96
| Tray icon | Yes | StatusNotifierItem | Menu bar |
97
97
| Updates | Quiet download, idle restart | Asks when installed under `~/.local`; otherwise opens the release page | Opens the release page |
98
98
@@ -161,7 +161,7 @@ Without these env vars the calendar stays Outlook-only.
161
161
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
162
162
| Against Chrome on a debug port | `cargo run -p app -- --endpoint http://127.0.0.1:9222` |
163
163
| Windows exe from WSL/Linux | `scripts/build-windows.sh crates/app teams` |
164
| macOS .app (universal arm64 + x86_64), Xcode CLT only | `scripts/build-macos.sh crates/app teams` |
164
| macOS .app (Apple Silicon, macOS 14+), Xcode CLT only | `scripts/build-macos.sh crates/app teams` |
165
165
| Linux AppImage, deb, rpm and tar.gz in `dist/release` (needs [nfpm](https://nfpm.goreleaser.com) for deb/rpm) | `packaging/linux/package.sh` |
166
166
| Tests | `cargo test` |
167
167
| Headless screenshot (Xvfb, xdotool, xclip, mesa-vulkan-drivers) | `cargo build -p app && scripts/headless-shot.sh shot.png -- "mousemove 450 740" "click 1" "type hello"` |
@@ -92,7 +92,7 @@92
|---|---|---|---|92
|---|---|---|---|93
| Support | Main target | Supported | Supported |93
| Support | Main target | Supported | Supported |94
| Sign-in | Embedded WebView2 | Your browser, headless | Your browser, headless |94
| Sign-in | Embedded WebView2 | Your browser, headless | Your browser, headless |95
| Download | `.exe` | `.tar.gz`, self-installs to the app menu | Universal `.app` (arm64 + x86_64) |95
| Download | `.exe` | `.tar.gz`, self-installs to the app menu | `.app` (Apple Silicon, macOS 14+) |96
| Tray icon | Yes | StatusNotifierItem | Menu bar |96
| Tray icon | Yes | StatusNotifierItem | Menu bar |97
| Updates | Quiet download, idle restart | Asks when installed under `~/.local`; otherwise opens the release page | Opens the release page |97
| Updates | Quiet download, idle restart | Asks when installed under `~/.local`; otherwise opens the release page | Opens the release page |98
98
@@ -161,7 +161,7 @@ Without these env vars the calendar stays Outlook-only.161
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |161
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |162
| Against Chrome on a debug port | `cargo run -p app -- --endpoint http://127.0.0.1:9222` |162
| Against Chrome on a debug port | `cargo run -p app -- --endpoint http://127.0.0.1:9222` |163
| Windows exe from WSL/Linux | `scripts/build-windows.sh crates/app teams` |163
| Windows exe from WSL/Linux | `scripts/build-windows.sh crates/app teams` |164
| macOS .app (universal arm64 + x86_64), Xcode CLT only | `scripts/build-macos.sh crates/app teams` |164
| macOS .app (Apple Silicon, macOS 14+), Xcode CLT only | `scripts/build-macos.sh crates/app teams` |165
| Linux AppImage, deb, rpm and tar.gz in `dist/release` (needs [nfpm](https://nfpm.goreleaser.com) for deb/rpm) | `packaging/linux/package.sh` |165
| Linux AppImage, deb, rpm and tar.gz in `dist/release` (needs [nfpm](https://nfpm.goreleaser.com) for deb/rpm) | `packaging/linux/package.sh` |166
| Tests | `cargo test` |166
| Tests | `cargo test` |167
| Headless screenshot (Xvfb, xdotool, xclip, mesa-vulkan-drivers) | `cargo build -p app && scripts/headless-shot.sh shot.png -- "mousemove 450 740" "click 1" "type hello"` |167
| Headless screenshot (Xvfb, xdotool, xclip, mesa-vulkan-drivers) | `cargo build -p app && scripts/headless-shot.sh shot.png -- "mousemove 450 740" "click 1" "type hello"` |@@ -952,6 +952,9 @@ calls:
952
952
portal_unavailable:
953
953
en: Screen sharing needs a desktop portal on this system
954
954
de: Bildschirmfreigabe benötigt auf diesem System ein Desktop-Portal
955
share_source_gone:
956
en: The shared source is no longer available
957
de: Die freigegebene Quelle ist nicht mehr verfügbar
955
958
files_later:
956
959
en: Files can be added once the chat exists.
957
960
de: Dateien können hinzugefügt werden, sobald der Chat existiert.
@@ -952,6 +952,9 @@ calls:952
portal_unavailable:952
portal_unavailable:953
en: Screen sharing needs a desktop portal on this system953
en: Screen sharing needs a desktop portal on this system954
de: Bildschirmfreigabe benötigt auf diesem System ein Desktop-Portal954
de: Bildschirmfreigabe benötigt auf diesem System ein Desktop-Portal955
share_source_gone:956
en: The shared source is no longer available957
de: Die freigegebene Quelle ist nicht mehr verfügbar955
files_later:958
files_later:956
en: Files can be added once the chat exists.959
en: Files can be added once the chat exists.957
de: Dateien können hinzugefügt werden, sobald der Chat existiert.960
de: Dateien können hinzugefügt werden, sobald der Chat existiert.@@ -9,6 +9,7 @@ pub const SHARE_QUEUED_NOTICE: &str = "calls.notice.share_queued";
9
9
pub const SHARE_REFUSED_NOTICE: &str = "calls.notice.share_refused";
10
10
pub const NOT_CONNECTED_FOR_VIDEO: &str = "calls.notice.video_starts_once_connected";
11
11
pub const PORTAL_UNAVAILABLE_NOTICE: &str = "calls.notice.portal_unavailable";
12
pub const SHARE_SOURCE_GONE_NOTICE: &str = "calls.notice.share_source_gone";
12
13
pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";
13
14
pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";
14
15
pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";
@@ -75,6 +76,7 @@ mod tests {
75
76
"calls.notice.video_starts_once_connected"
76
77
);
77
78
assert_eq!(PORTAL_UNAVAILABLE_NOTICE, "calls.notice.portal_unavailable");
79
assert_eq!(SHARE_SOURCE_GONE_NOTICE, "calls.notice.share_source_gone");
78
80
assert_eq!(CALL_TRANSFERRED_NOTICE, "calls.notice.call_transferred");
79
81
assert_eq!(TRANSFER_FAILED_NOTICE, "calls.notice.transfer_failed");
80
82
assert_eq!(
@@ -9,6 +9,7 @@ pub const SHARE_QUEUED_NOTICE: &str = "calls.notice.share_queued";9
pub const SHARE_REFUSED_NOTICE: &str = "calls.notice.share_refused";9
pub const SHARE_REFUSED_NOTICE: &str = "calls.notice.share_refused";10
pub const NOT_CONNECTED_FOR_VIDEO: &str = "calls.notice.video_starts_once_connected";10
pub const NOT_CONNECTED_FOR_VIDEO: &str = "calls.notice.video_starts_once_connected";11
pub const PORTAL_UNAVAILABLE_NOTICE: &str = "calls.notice.portal_unavailable";11
pub const PORTAL_UNAVAILABLE_NOTICE: &str = "calls.notice.portal_unavailable";12
pub const SHARE_SOURCE_GONE_NOTICE: &str = "calls.notice.share_source_gone";12
pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";13
pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";13
pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";14
pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";14
pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";15
pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";@@ -75,6 +76,7 @@ mod tests {75
"calls.notice.video_starts_once_connected"76
"calls.notice.video_starts_once_connected"76
);77
);77
assert_eq!(PORTAL_UNAVAILABLE_NOTICE, "calls.notice.portal_unavailable");78
assert_eq!(PORTAL_UNAVAILABLE_NOTICE, "calls.notice.portal_unavailable");79
assert_eq!(SHARE_SOURCE_GONE_NOTICE, "calls.notice.share_source_gone");78
assert_eq!(CALL_TRANSFERRED_NOTICE, "calls.notice.call_transferred");80
assert_eq!(CALL_TRANSFERRED_NOTICE, "calls.notice.call_transferred");79
assert_eq!(TRANSFER_FAILED_NOTICE, "calls.notice.transfer_failed");81
assert_eq!(TRANSFER_FAILED_NOTICE, "calls.notice.transfer_failed");80
assert_eq!(82
assert_eq!(@@ -271,18 +271,34 @@ fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buf
271
271
buffer
272
272
}
273
273
274
/// `ended` runs at most once, when the share stops on its own: with the reason
275
/// to show, or with `None` when the user stopped it outside the app.
274
276
pub fn start_screen_capture(
275
277
wanted: ShareSource,
276
278
fps: Arc<AtomicU32>,
277
279
mut deliver: impl FnMut(I420Buffer) + Send + 'static,
278
failed: impl FnOnce(String) + Send + 'static,
280
ended: impl FnOnce(Option<String>) + Send + 'static,
279
281
) -> Result<Capture> {
280
282
if current_share_picker() == SharePicker::Portal {
281
return start_portal_capture(wanted.kind, fps, deliver, move |follow| {
282
if let PortalFollowUp::Notice(text) = follow {
283
failed(text.to_owned());
284
}
285
});
283
let ended = Arc::new(Mutex::new(Some(ended)));
284
let failed = ended.clone();
285
return start_portal_capture(
286
wanted.kind,
287
fps,
288
deliver,
289
move |follow| {
290
if let PortalFollowUp::Notice(text) = follow
291
&& let Some(failed) = take_once(&failed)
292
{
293
failed(Some(text.to_owned()));
294
}
295
},
296
move |reason| {
297
if let Some(ended) = take_once(&ended) {
298
ended(reason);
299
}
300
},
301
);
286
302
}
287
303
Capture::spawn_thread("screen-capture", move |stop| {
288
304
let Some(source) = sources_of(wanted.kind)
@@ -290,10 +306,10 @@ pub fn start_screen_capture(
290
306
.find(|(source, _)| source.id == wanted.id)
291
307
.map(|(_, raw)| raw)
292
308
else {
293
return failed("the shared source is gone".to_owned());
309
return ended(Some("the shared source is gone".to_owned()));
294
310
};
295
311
let Some(mut capturer) = capturer(wanted.kind) else {
296
return failed("screen capture is not available".to_owned());
312
return ended(Some("screen capture is not available".to_owned()));
297
313
};
298
314
let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();
299
315
let gone_mark = gone_since.clone();
@@ -301,7 +317,7 @@ pub fn start_screen_capture(
301
317
let frame = match result {
302
318
Ok(frame) => frame,
303
319
Err(error) => {
304
if matches!(error, CaptureError::Permanent)
320
if matches!(error, CaptureError::Permanent | CaptureError::SourceGone)
305
321
&& let Ok(mut since) = gone_mark.lock()
306
322
{
307
323
since.get_or_insert_with(Instant::now);
@@ -324,7 +340,7 @@ pub fn start_screen_capture(
324
340
.lock()
325
341
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));
326
342
if gone {
327
return failed("the shared source is gone".to_owned());
343
return ended(Some("the shared source is gone".to_owned()));
328
344
}
329
345
pump_messages();
330
346
capturer.capture_frame();
@@ -335,6 +351,10 @@ pub fn start_screen_capture(
335
351
.map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
336
352
}
337
353
354
fn take_once<F>(slot: &Mutex<Option<F>>) -> Option<F> {
355
slot.lock().ok()?.take()
356
}
357
338
358
/// Where the share menu gets its sources. Wayland and macOS use a system dialog.
339
359
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340
360
pub enum SharePicker {
@@ -368,7 +388,7 @@ pub fn share_sources_for_menu(picker: SharePicker, sources: Vec<ShareSource>) ->
368
388
}
369
389
}
370
390
371
pub use crate::notices::PORTAL_UNAVAILABLE_NOTICE;
391
pub use crate::notices::{PORTAL_UNAVAILABLE_NOTICE, SHARE_SOURCE_GONE_NOTICE};
372
392
373
393
#[derive(Debug, Clone, PartialEq, Eq)]
374
394
pub enum PortalFollowUp {
@@ -388,24 +408,63 @@ pub fn portal_follow_up(event: PortalPickerEvent, source: Option<ShareSource>) -
388
408
}
389
409
}
390
410
411
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
412
enum PickerOutcome {
413
Portal(PortalPickerEvent),
414
SourceGone,
415
}
416
417
fn picker_follow_up(outcome: PickerOutcome, source: Option<ShareSource>) -> PortalFollowUp {
418
match outcome {
419
PickerOutcome::Portal(event) => portal_follow_up(event, source),
420
PickerOutcome::SourceGone => PortalFollowUp::Notice(SHARE_SOURCE_GONE_NOTICE),
421
}
422
}
423
391
424
/// What a frame result says about a system picker without a delegated
392
/// controller (macOS). Frames start once a source is picked. A cancel, or a
393
/// picker that fails to start, turns into a permanent error.
425
/// controller (macOS). Frames start once a source is picked. A cancel turns
426
/// into `Cancelled`, a disappearing source turns into `SourceGone`, and a
427
/// capture that fails to start turns into `Failed`.
394
428
fn picker_event_from_frame<T>(
395
429
result: &std::result::Result<T, CaptureError>,
396
) -> Option<PortalPickerEvent> {
430
) -> Option<PickerOutcome> {
397
431
match result {
398
Ok(_) => Some(PortalPickerEvent::Selected),
399
Err(CaptureError::Permanent) => Some(PortalPickerEvent::Cancelled),
432
Ok(_) => Some(PickerOutcome::Portal(PortalPickerEvent::Selected)),
433
Err(CaptureError::Permanent | CaptureError::StoppedByUser) => {
434
Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))
435
}
436
Err(CaptureError::SourceGone) => Some(PickerOutcome::SourceGone),
437
Err(CaptureError::StartFailed | CaptureError::Interrupted) => {
438
Some(PickerOutcome::Portal(PortalPickerEvent::Failed))
439
}
400
440
Err(CaptureError::Temporary) => None,
401
441
}
402
442
}
403
443
444
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445
enum ActiveShareStop {
446
Quiet,
447
Notice(&'static str),
448
}
449
450
/// Classifies an error received while a portal share is active.
451
fn active_portal_error(error: CaptureError) -> Option<ActiveShareStop> {
452
match error {
453
CaptureError::StoppedByUser => Some(ActiveShareStop::Quiet),
454
CaptureError::StartFailed | CaptureError::Interrupted => {
455
Some(ActiveShareStop::Notice("macOS stopped the capture"))
456
}
457
CaptureError::Permanent => Some(ActiveShareStop::Notice("the system stopped the capture")),
458
CaptureError::Temporary | CaptureError::SourceGone => None,
459
}
460
}
461
404
462
pub(crate) fn start_portal_capture(
405
463
kind: ShareKind,
406
464
fps: Arc<AtomicU32>,
407
465
mut deliver: impl FnMut(I420Buffer) + Send + 'static,
408
466
outcome: impl FnOnce(PortalFollowUp) + Send + 'static,
467
ended: impl FnOnce(Option<String>) + Send + 'static,
409
468
) -> Result<Capture> {
410
469
Capture::spawn_thread("portal-share", move |stop| {
411
470
libwebrtc::desktop_capturer::ensure_shared_glib_loop();
@@ -413,6 +472,8 @@ pub(crate) fn start_portal_capture(
413
472
outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
414
473
return;
415
474
};
475
let mut last_fps = fps.load(Ordering::Relaxed).max(1);
476
capturer.set_max_frame_rate(last_fps);
416
477
// The Wayland portal reports the pick through a delegated picker. The
417
478
// macOS system picker has none: it opens in `start_capture` and the
418
479
// outcome shows in the frame results.
@@ -425,6 +486,12 @@ pub(crate) fn start_portal_capture(
425
486
let frame_events = (!delegated).then(|| sender.clone());
426
487
let selected = Arc::new(AtomicBool::new(false));
427
488
let gate = selected.clone();
489
// A closed window gets the same grace as in the source list: it may
490
// reopen, and the remote side keeps the last frame meanwhile.
491
let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();
492
let gone_mark = gone_since.clone();
493
let active_end: Arc<Mutex<Option<ActiveShareStop>>> = Arc::default();
494
let end_mark = active_end.clone();
428
495
capturer.start_capture(None, move |result| {
429
496
if !gate.load(Ordering::SeqCst) {
430
497
let Some(events) = &frame_events else { return };
@@ -432,20 +499,44 @@ pub(crate) fn start_portal_capture(
432
499
return;
433
500
};
434
501
let _ = events.send(event);
435
if event != PortalPickerEvent::Selected {
502
if event != PickerOutcome::Portal(PortalPickerEvent::Selected) {
436
503
return;
437
504
}
438
505
gate.store(true, Ordering::SeqCst);
439
506
}
440
let Ok(frame) = result else { return };
441
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
442
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) {
443
deliver(picture);
507
match result {
508
Ok(frame) => {
509
if let Ok(mut since) = gone_mark.lock() {
510
*since = None;
511
}
512
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
513
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride())
514
{
515
deliver(picture);
516
}
517
}
518
Err(CaptureError::Temporary) => {
519
if let Ok(mut since) = gone_mark.lock() {
520
*since = None;
521
}
522
}
523
Err(CaptureError::SourceGone) => {
524
if let Ok(mut since) = gone_mark.lock() {
525
since.get_or_insert_with(Instant::now);
526
}
527
}
528
Err(error) => {
529
if let Some(stop_reason) = active_portal_error(error)
530
&& let Ok(mut slot) = end_mark.lock()
531
{
532
slot.get_or_insert(stop_reason);
533
}
534
}
444
535
}
445
536
});
446
537
if delegated {
447
538
capturer.watch_picker(move |event| {
448
let _ = sender.send(event);
539
let _ = sender.send(PickerOutcome::Portal(event));
449
540
});
450
541
capturer.ensure_picker_visible();
451
542
}
@@ -471,7 +562,7 @@ pub(crate) fn start_portal_capture(
471
562
// The portal already bound this stream. Looking the source up again, or
472
563
// selecting that id, is what used to tear the stream down and report
473
564
// "the shared source is gone".
474
let source = if event == PortalPickerEvent::Selected {
565
let source = if event == PickerOutcome::Portal(PortalPickerEvent::Selected) {
475
566
selected.store(true, Ordering::SeqCst);
476
567
Some(ShareSource {
477
568
id: 0,
@@ -481,16 +572,41 @@ pub(crate) fn start_portal_capture(
481
572
} else {
482
573
None
483
574
};
484
let follow = portal_follow_up(event, source);
575
let follow = picker_follow_up(event, source);
485
576
if !matches!(follow, PortalFollowUp::Share(_)) {
486
577
outcome(follow);
487
578
return;
488
579
}
489
capturer.capture_frame();
580
if delegated {
581
capturer.capture_frame();
582
}
490
583
outcome(follow);
491
while !stop.load(Ordering::SeqCst) {
584
let reason = loop {
585
if stop.load(Ordering::SeqCst) {
586
return;
587
}
588
let target_fps = fps.load(Ordering::Relaxed).max(1);
589
if target_fps != last_fps {
590
capturer.set_max_frame_rate(target_fps);
591
last_fps = target_fps;
592
}
492
593
capturer.capture_frame();
493
std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
594
if let Some(end) = active_end.lock().ok().and_then(|mut slot| slot.take()) {
595
break match end {
596
ActiveShareStop::Quiet => None,
597
ActiveShareStop::Notice(text) => Some(text),
598
};
599
}
600
let gone = gone_since
601
.lock()
602
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));
603
if gone {
604
break Some("the shared source is gone");
605
}
606
std::thread::sleep(Duration::from_secs(1) / target_fps);
607
};
608
if !stop.load(Ordering::SeqCst) {
609
ended(reason.map(str::to_owned));
494
610
}
495
611
})
496
612
.map_err(|error| Error::Webrtc(format!("portal thread: {error}")))
@@ -531,17 +647,59 @@ mod tests {
531
647
fn frames_report_the_macos_picker_outcome() {
532
648
assert_eq!(
533
649
picker_event_from_frame(&Ok(())),
534
Some(PortalPickerEvent::Selected)
650
Some(PickerOutcome::Portal(PortalPickerEvent::Selected))
535
651
);
536
652
assert_eq!(
537
653
picker_event_from_frame::<()>(&Err(CaptureError::Permanent)),
538
Some(PortalPickerEvent::Cancelled)
654
Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))
655
);
656
assert_eq!(
657
picker_event_from_frame::<()>(&Err(CaptureError::StoppedByUser)),
658
Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))
659
);
660
assert_eq!(
661
picker_event_from_frame::<()>(&Err(CaptureError::StartFailed)),
662
Some(PickerOutcome::Portal(PortalPickerEvent::Failed))
663
);
664
assert_eq!(
665
picker_event_from_frame::<()>(&Err(CaptureError::SourceGone)),
666
Some(PickerOutcome::SourceGone)
667
);
668
assert_eq!(
669
picker_follow_up(PickerOutcome::SourceGone, None),
670
PortalFollowUp::Notice(SHARE_SOURCE_GONE_NOTICE)
671
);
672
assert_eq!(
673
picker_event_from_frame::<()>(&Err(CaptureError::Interrupted)),
674
Some(PickerOutcome::Portal(PortalPickerEvent::Failed))
539
675
);
540
676
assert_eq!(
541
677
picker_event_from_frame::<()>(&Err(CaptureError::Temporary)),
542
678
None
543
679
);
544
680
}
681
682
#[test]
683
fn active_portal_errors_separate_user_stop_from_failures() {
684
assert_eq!(
685
active_portal_error(CaptureError::StoppedByUser),
686
Some(ActiveShareStop::Quiet)
687
);
688
assert_eq!(
689
active_portal_error(CaptureError::Interrupted),
690
Some(ActiveShareStop::Notice("macOS stopped the capture"))
691
);
692
assert_eq!(
693
active_portal_error(CaptureError::StartFailed),
694
Some(ActiveShareStop::Notice("macOS stopped the capture"))
695
);
696
assert_eq!(
697
active_portal_error(CaptureError::Permanent),
698
Some(ActiveShareStop::Notice("the system stopped the capture"))
699
);
700
assert_eq!(active_portal_error(CaptureError::SourceGone), None);
701
assert_eq!(active_portal_error(CaptureError::Temporary), None);
702
}
545
703
}
546
704
547
705
#[cfg(test)]
@@ -629,6 +787,19 @@ mod portal_share_tests {
629
787
}
630
788
}
631
789
790
#[cfg(all(test, target_os = "macos"))]
791
mod macos_window_capturer_tests {
792
use super::{ShareKind, capturer};
793
794
#[test]
795
fn macos_sck_window_capturer_creates_without_opening_picker() {
796
// Creating the window capturer on macOS 14+ binds the ScreenCaptureKit
797
// single-window backend without invoking SCContentSharingPicker until start.
798
let mut window_capturer = capturer(ShareKind::Window).expect("macOS window capturer");
799
window_capturer.set_max_frame_rate(15);
800
}
801
}
802
632
803
#[cfg(all(test, target_os = "linux"))]
633
804
mod portal_loop_tests {
634
805
#[test]
@@ -667,6 +838,7 @@ mod portal_smoke {
667
838
eprintln!("PORTAL_FOLLOW={follow:?}");
668
839
let _ = sender.send(follow);
669
840
},
841
|_| {},
670
842
)
671
843
.expect("portal thread");
672
844
let follow = receiver
@@ -271,18 +271,34 @@ fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buf271
buffer271
buffer272
}272
}273
273
274
/// `ended` runs at most once, when the share stops on its own: with the reason275
/// to show, or with `None` when the user stopped it outside the app.274
pub fn start_screen_capture(276
pub fn start_screen_capture(275
wanted: ShareSource,277
wanted: ShareSource,276
fps: Arc<AtomicU32>,278
fps: Arc<AtomicU32>,277
mut deliver: impl FnMut(I420Buffer) + Send + 'static,279
mut deliver: impl FnMut(I420Buffer) + Send + 'static,278
failed: impl FnOnce(String) + Send + 'static,280
ended: impl FnOnce(Option<String>) + Send + 'static,279
) -> Result<Capture> {281
) -> Result<Capture> {280
if current_share_picker() == SharePicker::Portal {282
if current_share_picker() == SharePicker::Portal {281
return start_portal_capture(wanted.kind, fps, deliver, move |follow| {283
let ended = Arc::new(Mutex::new(Some(ended)));282
if let PortalFollowUp::Notice(text) = follow {284
let failed = ended.clone();283
failed(text.to_owned());285
return start_portal_capture(284
}286
wanted.kind,285
});287
fps,288
deliver,289
move |follow| {290
if let PortalFollowUp::Notice(text) = follow291
&& let Some(failed) = take_once(&failed)292
{293
failed(Some(text.to_owned()));294
}295
},296
move |reason| {297
if let Some(ended) = take_once(&ended) {298
ended(reason);299
}300
},301
);286
}302
}287
Capture::spawn_thread("screen-capture", move |stop| {303
Capture::spawn_thread("screen-capture", move |stop| {288
let Some(source) = sources_of(wanted.kind)304
let Some(source) = sources_of(wanted.kind)@@ -290,10 +306,10 @@ pub fn start_screen_capture(290
.find(|(source, _)| source.id == wanted.id)306
.find(|(source, _)| source.id == wanted.id)291
.map(|(_, raw)| raw)307
.map(|(_, raw)| raw)292
else {308
else {293
return failed("the shared source is gone".to_owned());309
return ended(Some("the shared source is gone".to_owned()));294
};310
};295
let Some(mut capturer) = capturer(wanted.kind) else {311
let Some(mut capturer) = capturer(wanted.kind) else {296
return failed("screen capture is not available".to_owned());312
return ended(Some("screen capture is not available".to_owned()));297
};313
};298
let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();314
let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();299
let gone_mark = gone_since.clone();315
let gone_mark = gone_since.clone();@@ -301,7 +317,7 @@ pub fn start_screen_capture(301
let frame = match result {317
let frame = match result {302
Ok(frame) => frame,318
Ok(frame) => frame,303
Err(error) => {319
Err(error) => {304
if matches!(error, CaptureError::Permanent)320
if matches!(error, CaptureError::Permanent | CaptureError::SourceGone)305
&& let Ok(mut since) = gone_mark.lock()321
&& let Ok(mut since) = gone_mark.lock()306
{322
{307
since.get_or_insert_with(Instant::now);323
since.get_or_insert_with(Instant::now);@@ -324,7 +340,7 @@ pub fn start_screen_capture(324
.lock()340
.lock()325
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));341
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));326
if gone {342
if gone {327
return failed("the shared source is gone".to_owned());343
return ended(Some("the shared source is gone".to_owned()));328
}344
}329
pump_messages();345
pump_messages();330
capturer.capture_frame();346
capturer.capture_frame();@@ -335,6 +351,10 @@ pub fn start_screen_capture(335
.map_err(|error| Error::Webrtc(format!("screen thread: {error}")))351
.map_err(|error| Error::Webrtc(format!("screen thread: {error}")))336
}352
}337
353
354
fn take_once<F>(slot: &Mutex<Option<F>>) -> Option<F> {355
slot.lock().ok()?.take()356
}357
338
/// Where the share menu gets its sources. Wayland and macOS use a system dialog.358
/// Where the share menu gets its sources. Wayland and macOS use a system dialog.339
#[derive(Debug, Clone, Copy, PartialEq, Eq)]359
#[derive(Debug, Clone, Copy, PartialEq, Eq)]340
pub enum SharePicker {360
pub enum SharePicker {@@ -368,7 +388,7 @@ pub fn share_sources_for_menu(picker: SharePicker, sources: Vec<ShareSource>) ->368
}388
}369
}389
}370
390
371
pub use crate::notices::PORTAL_UNAVAILABLE_NOTICE;391
pub use crate::notices::{PORTAL_UNAVAILABLE_NOTICE, SHARE_SOURCE_GONE_NOTICE};372
392
373
#[derive(Debug, Clone, PartialEq, Eq)]393
#[derive(Debug, Clone, PartialEq, Eq)]374
pub enum PortalFollowUp {394
pub enum PortalFollowUp {@@ -388,24 +408,63 @@ pub fn portal_follow_up(event: PortalPickerEvent, source: Option<ShareSource>) -388
}408
}389
}409
}390
410
411
#[derive(Debug, Clone, Copy, PartialEq, Eq)]412
enum PickerOutcome {413
Portal(PortalPickerEvent),414
SourceGone,415
}416
417
fn picker_follow_up(outcome: PickerOutcome, source: Option<ShareSource>) -> PortalFollowUp {418
match outcome {419
PickerOutcome::Portal(event) => portal_follow_up(event, source),420
PickerOutcome::SourceGone => PortalFollowUp::Notice(SHARE_SOURCE_GONE_NOTICE),421
}422
}423
391
/// What a frame result says about a system picker without a delegated424
/// What a frame result says about a system picker without a delegated392
/// controller (macOS). Frames start once a source is picked. A cancel, or a425
/// controller (macOS). Frames start once a source is picked. A cancel turns393
/// picker that fails to start, turns into a permanent error.426
/// into `Cancelled`, a disappearing source turns into `SourceGone`, and a427
/// capture that fails to start turns into `Failed`.394
fn picker_event_from_frame<T>(428
fn picker_event_from_frame<T>(395
result: &std::result::Result<T, CaptureError>,429
result: &std::result::Result<T, CaptureError>,396
) -> Option<PortalPickerEvent> {430
) -> Option<PickerOutcome> {397
match result {431
match result {398
Ok(_) => Some(PortalPickerEvent::Selected),432
Ok(_) => Some(PickerOutcome::Portal(PortalPickerEvent::Selected)),399
Err(CaptureError::Permanent) => Some(PortalPickerEvent::Cancelled),433
Err(CaptureError::Permanent | CaptureError::StoppedByUser) => {434
Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))435
}436
Err(CaptureError::SourceGone) => Some(PickerOutcome::SourceGone),437
Err(CaptureError::StartFailed | CaptureError::Interrupted) => {438
Some(PickerOutcome::Portal(PortalPickerEvent::Failed))439
}400
Err(CaptureError::Temporary) => None,440
Err(CaptureError::Temporary) => None,401
}441
}402
}442
}403
443
444
#[derive(Debug, Clone, Copy, PartialEq, Eq)]445
enum ActiveShareStop {446
Quiet,447
Notice(&'static str),448
}449
450
/// Classifies an error received while a portal share is active.451
fn active_portal_error(error: CaptureError) -> Option<ActiveShareStop> {452
match error {453
CaptureError::StoppedByUser => Some(ActiveShareStop::Quiet),454
CaptureError::StartFailed | CaptureError::Interrupted => {455
Some(ActiveShareStop::Notice("macOS stopped the capture"))456
}457
CaptureError::Permanent => Some(ActiveShareStop::Notice("the system stopped the capture")),458
CaptureError::Temporary | CaptureError::SourceGone => None,459
}460
}461
404
pub(crate) fn start_portal_capture(462
pub(crate) fn start_portal_capture(405
kind: ShareKind,463
kind: ShareKind,406
fps: Arc<AtomicU32>,464
fps: Arc<AtomicU32>,407
mut deliver: impl FnMut(I420Buffer) + Send + 'static,465
mut deliver: impl FnMut(I420Buffer) + Send + 'static,408
outcome: impl FnOnce(PortalFollowUp) + Send + 'static,466
outcome: impl FnOnce(PortalFollowUp) + Send + 'static,467
ended: impl FnOnce(Option<String>) + Send + 'static,409
) -> Result<Capture> {468
) -> Result<Capture> {410
Capture::spawn_thread("portal-share", move |stop| {469
Capture::spawn_thread("portal-share", move |stop| {411
libwebrtc::desktop_capturer::ensure_shared_glib_loop();470
libwebrtc::desktop_capturer::ensure_shared_glib_loop();@@ -413,6 +472,8 @@ pub(crate) fn start_portal_capture(413
outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));472
outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));414
return;473
return;415
};474
};475
let mut last_fps = fps.load(Ordering::Relaxed).max(1);476
capturer.set_max_frame_rate(last_fps);416
// The Wayland portal reports the pick through a delegated picker. The477
// The Wayland portal reports the pick through a delegated picker. The417
// macOS system picker has none: it opens in `start_capture` and the478
// macOS system picker has none: it opens in `start_capture` and the418
// outcome shows in the frame results.479
// outcome shows in the frame results.@@ -425,6 +486,12 @@ pub(crate) fn start_portal_capture(425
let frame_events = (!delegated).then(|| sender.clone());486
let frame_events = (!delegated).then(|| sender.clone());426
let selected = Arc::new(AtomicBool::new(false));487
let selected = Arc::new(AtomicBool::new(false));427
let gate = selected.clone();488
let gate = selected.clone();489
// A closed window gets the same grace as in the source list: it may490
// reopen, and the remote side keeps the last frame meanwhile.491
let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();492
let gone_mark = gone_since.clone();493
let active_end: Arc<Mutex<Option<ActiveShareStop>>> = Arc::default();494
let end_mark = active_end.clone();428
capturer.start_capture(None, move |result| {495
capturer.start_capture(None, move |result| {429
if !gate.load(Ordering::SeqCst) {496
if !gate.load(Ordering::SeqCst) {430
let Some(events) = &frame_events else { return };497
let Some(events) = &frame_events else { return };@@ -432,20 +499,44 @@ pub(crate) fn start_portal_capture(432
return;499
return;433
};500
};434
let _ = events.send(event);501
let _ = events.send(event);435
if event != PortalPickerEvent::Selected {502
if event != PickerOutcome::Portal(PortalPickerEvent::Selected) {436
return;503
return;437
}504
}438
gate.store(true, Ordering::SeqCst);505
gate.store(true, Ordering::SeqCst);439
}506
}440
let Ok(frame) = result else { return };507
match result {441
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);508
Ok(frame) => {442
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) {509
if let Ok(mut since) = gone_mark.lock() {443
deliver(picture);510
*since = None;511
}512
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);513
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride())514
{515
deliver(picture);516
}517
}518
Err(CaptureError::Temporary) => {519
if let Ok(mut since) = gone_mark.lock() {520
*since = None;521
}522
}523
Err(CaptureError::SourceGone) => {524
if let Ok(mut since) = gone_mark.lock() {525
since.get_or_insert_with(Instant::now);526
}527
}528
Err(error) => {529
if let Some(stop_reason) = active_portal_error(error)530
&& let Ok(mut slot) = end_mark.lock()531
{532
slot.get_or_insert(stop_reason);533
}534
}444
}535
}445
});536
});446
if delegated {537
if delegated {447
capturer.watch_picker(move |event| {538
capturer.watch_picker(move |event| {448
let _ = sender.send(event);539
let _ = sender.send(PickerOutcome::Portal(event));449
});540
});450
capturer.ensure_picker_visible();541
capturer.ensure_picker_visible();451
}542
}@@ -471,7 +562,7 @@ pub(crate) fn start_portal_capture(471
// The portal already bound this stream. Looking the source up again, or562
// The portal already bound this stream. Looking the source up again, or472
// selecting that id, is what used to tear the stream down and report563
// selecting that id, is what used to tear the stream down and report473
// "the shared source is gone".564
// "the shared source is gone".474
let source = if event == PortalPickerEvent::Selected {565
let source = if event == PickerOutcome::Portal(PortalPickerEvent::Selected) {475
selected.store(true, Ordering::SeqCst);566
selected.store(true, Ordering::SeqCst);476
Some(ShareSource {567
Some(ShareSource {477
id: 0,568
id: 0,@@ -481,16 +572,41 @@ pub(crate) fn start_portal_capture(481
} else {572
} else {482
None573
None483
};574
};484
let follow = portal_follow_up(event, source);575
let follow = picker_follow_up(event, source);485
if !matches!(follow, PortalFollowUp::Share(_)) {576
if !matches!(follow, PortalFollowUp::Share(_)) {486
outcome(follow);577
outcome(follow);487
return;578
return;488
}579
}489
capturer.capture_frame();580
if delegated {581
capturer.capture_frame();582
}490
outcome(follow);583
outcome(follow);491
while !stop.load(Ordering::SeqCst) {584
let reason = loop {585
if stop.load(Ordering::SeqCst) {586
return;587
}588
let target_fps = fps.load(Ordering::Relaxed).max(1);589
if target_fps != last_fps {590
capturer.set_max_frame_rate(target_fps);591
last_fps = target_fps;592
}492
capturer.capture_frame();593
capturer.capture_frame();493
std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));594
if let Some(end) = active_end.lock().ok().and_then(|mut slot| slot.take()) {595
break match end {596
ActiveShareStop::Quiet => None,597
ActiveShareStop::Notice(text) => Some(text),598
};599
}600
let gone = gone_since601
.lock()602
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));603
if gone {604
break Some("the shared source is gone");605
}606
std::thread::sleep(Duration::from_secs(1) / target_fps);607
};608
if !stop.load(Ordering::SeqCst) {609
ended(reason.map(str::to_owned));494
}610
}495
})611
})496
.map_err(|error| Error::Webrtc(format!("portal thread: {error}")))612
.map_err(|error| Error::Webrtc(format!("portal thread: {error}")))@@ -531,17 +647,59 @@ mod tests {531
fn frames_report_the_macos_picker_outcome() {647
fn frames_report_the_macos_picker_outcome() {532
assert_eq!(648
assert_eq!(533
picker_event_from_frame(&Ok(())),649
picker_event_from_frame(&Ok(())),534
Some(PortalPickerEvent::Selected)650
Some(PickerOutcome::Portal(PortalPickerEvent::Selected))535
);651
);536
assert_eq!(652
assert_eq!(537
picker_event_from_frame::<()>(&Err(CaptureError::Permanent)),653
picker_event_from_frame::<()>(&Err(CaptureError::Permanent)),538
Some(PortalPickerEvent::Cancelled)654
Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))655
);656
assert_eq!(657
picker_event_from_frame::<()>(&Err(CaptureError::StoppedByUser)),658
Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))659
);660
assert_eq!(661
picker_event_from_frame::<()>(&Err(CaptureError::StartFailed)),662
Some(PickerOutcome::Portal(PortalPickerEvent::Failed))663
);664
assert_eq!(665
picker_event_from_frame::<()>(&Err(CaptureError::SourceGone)),666
Some(PickerOutcome::SourceGone)667
);668
assert_eq!(669
picker_follow_up(PickerOutcome::SourceGone, None),670
PortalFollowUp::Notice(SHARE_SOURCE_GONE_NOTICE)671
);672
assert_eq!(673
picker_event_from_frame::<()>(&Err(CaptureError::Interrupted)),674
Some(PickerOutcome::Portal(PortalPickerEvent::Failed))539
);675
);540
assert_eq!(676
assert_eq!(541
picker_event_from_frame::<()>(&Err(CaptureError::Temporary)),677
picker_event_from_frame::<()>(&Err(CaptureError::Temporary)),542
None678
None543
);679
);544
}680
}681
682
#[test]683
fn active_portal_errors_separate_user_stop_from_failures() {684
assert_eq!(685
active_portal_error(CaptureError::StoppedByUser),686
Some(ActiveShareStop::Quiet)687
);688
assert_eq!(689
active_portal_error(CaptureError::Interrupted),690
Some(ActiveShareStop::Notice("macOS stopped the capture"))691
);692
assert_eq!(693
active_portal_error(CaptureError::StartFailed),694
Some(ActiveShareStop::Notice("macOS stopped the capture"))695
);696
assert_eq!(697
active_portal_error(CaptureError::Permanent),698
Some(ActiveShareStop::Notice("the system stopped the capture"))699
);700
assert_eq!(active_portal_error(CaptureError::SourceGone), None);701
assert_eq!(active_portal_error(CaptureError::Temporary), None);702
}545
}703
}546
704
547
#[cfg(test)]705
#[cfg(test)]@@ -629,6 +787,19 @@ mod portal_share_tests {629
}787
}630
}788
}631
789
790
#[cfg(all(test, target_os = "macos"))]791
mod macos_window_capturer_tests {792
use super::{ShareKind, capturer};793
794
#[test]795
fn macos_sck_window_capturer_creates_without_opening_picker() {796
// Creating the window capturer on macOS 14+ binds the ScreenCaptureKit797
// single-window backend without invoking SCContentSharingPicker until start.798
let mut window_capturer = capturer(ShareKind::Window).expect("macOS window capturer");799
window_capturer.set_max_frame_rate(15);800
}801
}802
632
#[cfg(all(test, target_os = "linux"))]803
#[cfg(all(test, target_os = "linux"))]633
mod portal_loop_tests {804
mod portal_loop_tests {634
#[test]805
#[test]@@ -667,6 +838,7 @@ mod portal_smoke {667
eprintln!("PORTAL_FOLLOW={follow:?}");838
eprintln!("PORTAL_FOLLOW={follow:?}");668
let _ = sender.send(follow);839
let _ = sender.send(follow);669
},840
},841
|_| {},670
)842
)671
.expect("portal thread");843
.expect("portal thread");672
let follow = receiver844
let follow = receiver@@ -672,12 +672,26 @@ impl LocalVideo {
672
672
generation: &Arc<AtomicU64>,
673
673
switch_off: CallCommand,
674
674
) -> impl FnOnce(String) + Send + 'static {
675
let report = self.report_end(notice_key, generation, switch_off);
676
move |reason| report(Some(reason))
677
}
678
679
/// Like `report_failure`, but `None` switches off without a notice: the
680
/// user ended it outside the app.
681
fn report_end(
682
&self,
683
notice_key: &'static str,
684
generation: &Arc<AtomicU64>,
685
switch_off: CallCommand,
686
) -> impl FnOnce(Option<String>) + Send + 'static {
675
687
let updates = self.updates.clone();
676
688
let commands = self.commands.clone();
677
689
let started = generation.fetch_add(1, Ordering::SeqCst) + 1;
678
690
let generation = generation.clone();
679
691
move |reason| {
680
let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
692
if let Some(reason) = reason {
693
let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
694
}
681
695
if generation.load(Ordering::SeqCst) == started
682
696
&& let Some(commands) = commands
683
697
{
@@ -819,6 +833,13 @@ impl LocalVideo {
819
833
self.screen.capture = None;
820
834
let mut sink = self.screen_sink();
821
835
let updates = self.updates.clone();
836
// `stop_share` moves the generation on, so only an end the app did not
837
// ask for switches the share off.
838
let ended = self.report_end(
839
SCREEN_SHARE_STOPPED_NOTICE,
840
&self.share_generation,
841
CallCommand::StopShare,
842
);
822
843
let capture = start_portal_capture(
823
844
kind,
824
845
self.share_fps.clone(),
@@ -835,6 +856,7 @@ impl LocalVideo {
835
856
let _ = commands.send(CallCommand::AbandonPortalShare);
836
857
}
837
858
},
859
ended,
838
860
)?;
839
861
self.portal_armed = true;
840
862
self.screen.capture = Some(capture);
@@ -865,7 +887,7 @@ impl LocalVideo {
865
887
source.clone(),
866
888
self.share_fps.clone(),
867
889
move |buffer| sink.push(buffer),
868
self.report_failure(
890
self.report_end(
869
891
SCREEN_SHARE_STOPPED_NOTICE,
870
892
&self.share_generation,
871
893
CallCommand::StopShare,
@@ -672,12 +672,26 @@ impl LocalVideo {672
generation: &Arc<AtomicU64>,672
generation: &Arc<AtomicU64>,673
switch_off: CallCommand,673
switch_off: CallCommand,674
) -> impl FnOnce(String) + Send + 'static {674
) -> impl FnOnce(String) + Send + 'static {675
let report = self.report_end(notice_key, generation, switch_off);676
move |reason| report(Some(reason))677
}678
679
/// Like `report_failure`, but `None` switches off without a notice: the680
/// user ended it outside the app.681
fn report_end(682
&self,683
notice_key: &'static str,684
generation: &Arc<AtomicU64>,685
switch_off: CallCommand,686
) -> impl FnOnce(Option<String>) + Send + 'static {675
let updates = self.updates.clone();687
let updates = self.updates.clone();676
let commands = self.commands.clone();688
let commands = self.commands.clone();677
let started = generation.fetch_add(1, Ordering::SeqCst) + 1;689
let started = generation.fetch_add(1, Ordering::SeqCst) + 1;678
let generation = generation.clone();690
let generation = generation.clone();679
move |reason| {691
move |reason| {680
let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));692
if let Some(reason) = reason {693
let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));694
}681
if generation.load(Ordering::SeqCst) == started695
if generation.load(Ordering::SeqCst) == started682
&& let Some(commands) = commands696
&& let Some(commands) = commands683
{697
{@@ -819,6 +833,13 @@ impl LocalVideo {819
self.screen.capture = None;833
self.screen.capture = None;820
let mut sink = self.screen_sink();834
let mut sink = self.screen_sink();821
let updates = self.updates.clone();835
let updates = self.updates.clone();836
// `stop_share` moves the generation on, so only an end the app did not837
// ask for switches the share off.838
let ended = self.report_end(839
SCREEN_SHARE_STOPPED_NOTICE,840
&self.share_generation,841
CallCommand::StopShare,842
);822
let capture = start_portal_capture(843
let capture = start_portal_capture(823
kind,844
kind,824
self.share_fps.clone(),845
self.share_fps.clone(),@@ -835,6 +856,7 @@ impl LocalVideo {835
let _ = commands.send(CallCommand::AbandonPortalShare);856
let _ = commands.send(CallCommand::AbandonPortalShare);836
}857
}837
},858
},859
ended,838
)?;860
)?;839
self.portal_armed = true;861
self.portal_armed = true;840
self.screen.capture = Some(capture);862
self.screen.capture = Some(capture);@@ -865,7 +887,7 @@ impl LocalVideo {865
source.clone(),887
source.clone(),866
self.share_fps.clone(),888
self.share_fps.clone(),867
move |buffer| sink.push(buffer),889
move |buffer| sink.push(buffer),868
self.report_failure(890
self.report_end(869
SCREEN_SHARE_STOPPED_NOTICE,891
SCREEN_SHARE_STOPPED_NOTICE,870
&self.share_generation,892
&self.share_generation,871
CallCommand::StopShare,893
CallCommand::StopShare,@@ -25,7 +25,7 @@ Run on a real Mac (`.app` from `scripts/build-macos.sh` or a release zip). Unit
25
25
26
26
## Packaging
27
27
28
1. Unsigned local build: TCC prompts for mic / camera / screen when first used.
28
1. Ad hoc signed local build (no `MACOS_CODESIGN_IDENTITY`): TCC prompts for mic / camera / screen when first used. Each rebuild changes the code hash, so macOS may ask again; `tccutil reset ScreenCapture org.rusty-teams.teams` (or `Camera` / `Microphone`) clears a stale entry.
29
29
2. Signed + notarized build (when `MACOS_CODESIGN_IDENTITY` / `MACOS_NOTARY_PROFILE` are set): Gatekeeper opens without a right-click override.
30
30
31
31
## Report
@@ -25,7 +25,7 @@ Run on a real Mac (`.app` from `scripts/build-macos.sh` or a release zip). Unit25
25
26
## Packaging26
## Packaging27
27
28
1. Unsigned local build: TCC prompts for mic / camera / screen when first used.28
1. Ad hoc signed local build (no `MACOS_CODESIGN_IDENTITY`): TCC prompts for mic / camera / screen when first used. Each rebuild changes the code hash, so macOS may ask again; `tccutil reset ScreenCapture org.rusty-teams.teams` (or `Camera` / `Microphone`) clears a stale entry.29
2. Signed + notarized build (when `MACOS_CODESIGN_IDENTITY` / `MACOS_NOTARY_PROFILE` are set): Gatekeeper opens without a right-click override.29
2. Signed + notarized build (when `MACOS_CODESIGN_IDENTITY` / `MACOS_NOTARY_PROFILE` are set): Gatekeeper opens without a right-click override.30
30
31
## Report31
## Report@@ -1,12 +1,12 @@
1
1
#!/usr/bin/env bash
2
# Build a universal macOS binary (arm64 + x86_64) from a crate. Needs Xcode CLT only.
2
# Build an Apple Silicon (arm64) macOS binary from a crate. Needs Xcode CLT only.
3
3
# Wraps it in a .app bundle (icon, Info.plist) and zips that for distribution.
4
4
# The published artifact is the `.app` zip. There is no in-app Mach-O swap.
5
5
#
6
6
# Optional signing / notarization when Apple credentials are present:
7
7
# MACOS_CODESIGN_IDENTITY e.g. "Developer ID Application: …"
8
8
# MACOS_NOTARY_PROFILE notarytool keychain profile (from `xcrun notarytool store-credentials`)
9
# Without those env vars the .app stays unsigned (fine for local / internal RC).
9
# Without those env vars the .app is ad-hoc signed (fine for local / internal RC).
10
10
#
11
11
# Usage: scripts/build-macos.sh [crate-dir, default crates/app] [binary-or-example-name, default: the crate's only binary]
12
12
set -euo pipefail
@@ -14,11 +14,25 @@ repoRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
14
14
crateDir="$(realpath "${1:-$repoRoot/crates/app}")"
15
15
binaryName="${2:-}"
16
16
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$repoRoot/target}"
17
# Keep in sync with .cargo/config.toml. macOS 14 is the minimum: screen and
18
# window sharing use SCContentSharingPicker. Info.plist's LSMinimumSystemVersion uses it.
19
deploymentTarget="${MACOSX_DEPLOYMENT_TARGET:-14.0}"
20
case "$deploymentTarget" in
21
*.*.*) deploymentTarget="${deploymentTarget%.0}" ;;
22
*.*) ;;
23
*) deploymentTarget="$deploymentTarget.0" ;;
24
esac
25
deploymentMajor="${deploymentTarget%%.*}"
26
if ! [[ "$deploymentMajor" =~ ^[0-9]+$ ]] || [ "$deploymentMajor" -lt 14 ]; then
27
echo "error: MACOSX_DEPLOYMENT_TARGET=$deploymentTarget, the app needs macOS 14.0 or later" >&2
28
exit 1
29
fi
30
export MACOSX_DEPLOYMENT_TARGET="$deploymentTarget"
17
31
export PATH="$HOME/.cargo/bin:$PATH"
18
32
entitlements="$repoRoot/scripts/macos/RustyTeams.entitlements"
19
targets=(aarch64-apple-darwin x86_64-apple-darwin)
33
target="aarch64-apple-darwin"
20
34
21
rustup target add "${targets[@]}" >/dev/null
35
rustup target add "$target" >/dev/null
22
36
23
37
buildArguments=(build --release)
24
38
slicePathInTarget="release"
@@ -29,27 +43,26 @@ elif [ -n "$binaryName" ]; then
29
43
buildArguments+=(--bin "$binaryName")
30
44
fi
31
45
32
for target in "${targets[@]}"; do
33
(cd "$crateDir" && cargo "${buildArguments[@]}" --target "$target")
34
done
46
(cd "$crateDir" && cargo "${buildArguments[@]}" --target "$target")
35
47
36
slices=()
37
for target in "${targets[@]}"; do
38
sliceDirectory="$CARGO_TARGET_DIR/$target/$slicePathInTarget"
39
if [ -n "$binaryName" ]; then
40
slices+=("$sliceDirectory/$binaryName")
41
else
42
candidates=("$sliceDirectory"/*)
43
[ "${#candidates[@]}" -eq 1 ] && [ -f "${candidates[0]}" ] ||
44
{ echo "more than one binary in $sliceDirectory, pass the name" >&2; exit 1; }
45
slices+=("${candidates[0]}")
46
fi
47
done
48
sliceDirectory="$CARGO_TARGET_DIR/$target/$slicePathInTarget"
49
if [ -n "$binaryName" ]; then
50
output="$sliceDirectory/$binaryName"
51
else
52
candidates=("$sliceDirectory"/*)
53
[ "${#candidates[@]}" -eq 1 ] && [ -f "${candidates[0]}" ] ||
54
{ echo "more than one binary in $sliceDirectory, pass the name" >&2; exit 1; }
55
output="${candidates[0]}"
56
fi
48
57
49
outputDirectory="$CARGO_TARGET_DIR/universal/release"
58
minos="$(vtool -arch arm64 -show-build "$output" | awk '$1 == "minos" { print $2 }')"
59
if [ "$minos" != "$MACOSX_DEPLOYMENT_TARGET" ]; then
60
echo "error: arm64 binary targets macOS ${minos:-unknown}, expected $MACOSX_DEPLOYMENT_TARGET" >&2
61
exit 1
62
fi
63
64
outputDirectory="$CARGO_TARGET_DIR/$target/release"
50
65
mkdir -p "$outputDirectory"
51
output="$outputDirectory/$(basename "${slices[0]}")"
52
lipo -create -output "$output" "${slices[@]}"
53
66
54
67
# Wrap the binary in a .app so Finder and the Dock treat it as an application:
55
68
# double-clickable, with the icon, and with the camera / microphone / screen
@@ -81,6 +94,8 @@ cat > "$app/Contents/Info.plist" <<PLIST
81
94
<string>$version</string>
82
95
<key>CFBundleVersion</key>
83
96
<string>$version</string>
97
<key>LSMinimumSystemVersion</key>
98
<string>$MACOSX_DEPLOYMENT_TARGET</string>
84
99
<key>NSHighResolutionCapable</key>
85
100
<true/>
86
101
<key>NSMicrophoneUsageDescription</key>
@@ -106,7 +121,10 @@ cp "$iconset/icon_64x64.png" "$iconset/icon_32x32@2x.png"
106
121
cp "$iconset/icon_256x256.png" "$iconset/icon_128x128@2x.png"
107
122
iconutil -c icns "$iconset" -o "$app/Contents/Resources/icon.icns"
108
123
109
# Developer ID signing when a certificate is configured in the build environment.
124
# Developer ID signing when a certificate is configured in the build environment;
125
# otherwise ad-hoc sign the bundle so the CodeDirectory is bound to Info.plist
126
# (CFBundleIdentifier) instead of leaving the arm64 binary linker-signed (which
127
# breaks TCC matching on Apple Silicon).
110
128
if [ -n "${MACOS_CODESIGN_IDENTITY:-}" ]; then
111
129
echo "codesign with $MACOS_CODESIGN_IDENTITY"
112
130
codesign --force --options runtime --timestamp \
@@ -118,6 +136,10 @@ if [ -n "${MACOS_CODESIGN_IDENTITY:-}" ]; then
118
136
--sign "$MACOS_CODESIGN_IDENTITY" \
119
137
"$app"
120
138
codesign --verify --deep --strict --verbose=2 "$app"
139
else
140
echo "codesign ad-hoc (-)"
141
codesign --force --sign - "$app"
142
codesign --verify --deep --strict --verbose=2 "$app"
121
143
fi
122
144
123
145
# ditto keeps the bundle intact (plain zip would not); the result is the .app release asset.
@@ -1,12 +1,12 @@1
#!/usr/bin/env bash1
#!/usr/bin/env bash2
# Build a universal macOS binary (arm64 + x86_64) from a crate. Needs Xcode CLT only.2
# Build an Apple Silicon (arm64) macOS binary from a crate. Needs Xcode CLT only.3
# Wraps it in a .app bundle (icon, Info.plist) and zips that for distribution.3
# Wraps it in a .app bundle (icon, Info.plist) and zips that for distribution.4
# The published artifact is the `.app` zip. There is no in-app Mach-O swap.4
# The published artifact is the `.app` zip. There is no in-app Mach-O swap.5
#5
#6
# Optional signing / notarization when Apple credentials are present:6
# Optional signing / notarization when Apple credentials are present:7
# MACOS_CODESIGN_IDENTITY e.g. "Developer ID Application: …"7
# MACOS_CODESIGN_IDENTITY e.g. "Developer ID Application: …"8
# MACOS_NOTARY_PROFILE notarytool keychain profile (from `xcrun notarytool store-credentials`)8
# MACOS_NOTARY_PROFILE notarytool keychain profile (from `xcrun notarytool store-credentials`)9
# Without those env vars the .app stays unsigned (fine for local / internal RC).9
# Without those env vars the .app is ad-hoc signed (fine for local / internal RC).10
#10
#11
# Usage: scripts/build-macos.sh [crate-dir, default crates/app] [binary-or-example-name, default: the crate's only binary]11
# Usage: scripts/build-macos.sh [crate-dir, default crates/app] [binary-or-example-name, default: the crate's only binary]12
set -euo pipefail12
set -euo pipefail@@ -14,11 +14,25 @@ repoRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"14
crateDir="$(realpath "${1:-$repoRoot/crates/app}")"14
crateDir="$(realpath "${1:-$repoRoot/crates/app}")"15
binaryName="${2:-}"15
binaryName="${2:-}"16
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$repoRoot/target}"16
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$repoRoot/target}"17
# Keep in sync with .cargo/config.toml. macOS 14 is the minimum: screen and18
# window sharing use SCContentSharingPicker. Info.plist's LSMinimumSystemVersion uses it.19
deploymentTarget="${MACOSX_DEPLOYMENT_TARGET:-14.0}"20
case "$deploymentTarget" in21
*.*.*) deploymentTarget="${deploymentTarget%.0}" ;;22
*.*) ;;23
*) deploymentTarget="$deploymentTarget.0" ;;24
esac25
deploymentMajor="${deploymentTarget%%.*}"26
if ! [[ "$deploymentMajor" =~ ^[0-9]+$ ]] || [ "$deploymentMajor" -lt 14 ]; then27
echo "error: MACOSX_DEPLOYMENT_TARGET=$deploymentTarget, the app needs macOS 14.0 or later" >&228
exit 129
fi30
export MACOSX_DEPLOYMENT_TARGET="$deploymentTarget"17
export PATH="$HOME/.cargo/bin:$PATH"31
export PATH="$HOME/.cargo/bin:$PATH"18
entitlements="$repoRoot/scripts/macos/RustyTeams.entitlements"32
entitlements="$repoRoot/scripts/macos/RustyTeams.entitlements"19
targets=(aarch64-apple-darwin x86_64-apple-darwin)33
target="aarch64-apple-darwin"20
34
21
rustup target add "${targets[@]}" >/dev/null35
rustup target add "$target" >/dev/null22
36
23
buildArguments=(build --release)37
buildArguments=(build --release)24
slicePathInTarget="release"38
slicePathInTarget="release"@@ -29,27 +43,26 @@ elif [ -n "$binaryName" ]; then29
buildArguments+=(--bin "$binaryName")43
buildArguments+=(--bin "$binaryName")30
fi44
fi31
45
32
for target in "${targets[@]}"; do46
(cd "$crateDir" && cargo "${buildArguments[@]}" --target "$target")33
(cd "$crateDir" && cargo "${buildArguments[@]}" --target "$target")34
done35
47
36
slices=()48
sliceDirectory="$CARGO_TARGET_DIR/$target/$slicePathInTarget"37
for target in "${targets[@]}"; do49
if [ -n "$binaryName" ]; then38
sliceDirectory="$CARGO_TARGET_DIR/$target/$slicePathInTarget"50
output="$sliceDirectory/$binaryName"39
if [ -n "$binaryName" ]; then51
else40
slices+=("$sliceDirectory/$binaryName")52
candidates=("$sliceDirectory"/*)41
else53
[ "${#candidates[@]}" -eq 1 ] && [ -f "${candidates[0]}" ] ||42
candidates=("$sliceDirectory"/*)54
{ echo "more than one binary in $sliceDirectory, pass the name" >&2; exit 1; }43
[ "${#candidates[@]}" -eq 1 ] && [ -f "${candidates[0]}" ] ||55
output="${candidates[0]}"44
{ echo "more than one binary in $sliceDirectory, pass the name" >&2; exit 1; }56
fi45
slices+=("${candidates[0]}")46
fi47
done48
57
49
outputDirectory="$CARGO_TARGET_DIR/universal/release"58
minos="$(vtool -arch arm64 -show-build "$output" | awk '$1 == "minos" { print $2 }')"59
if [ "$minos" != "$MACOSX_DEPLOYMENT_TARGET" ]; then60
echo "error: arm64 binary targets macOS ${minos:-unknown}, expected $MACOSX_DEPLOYMENT_TARGET" >&261
exit 162
fi63
64
outputDirectory="$CARGO_TARGET_DIR/$target/release"50
mkdir -p "$outputDirectory"65
mkdir -p "$outputDirectory"51
output="$outputDirectory/$(basename "${slices[0]}")"52
lipo -create -output "$output" "${slices[@]}"53
66
54
# Wrap the binary in a .app so Finder and the Dock treat it as an application:67
# Wrap the binary in a .app so Finder and the Dock treat it as an application:55
# double-clickable, with the icon, and with the camera / microphone / screen68
# double-clickable, with the icon, and with the camera / microphone / screen@@ -81,6 +94,8 @@ cat > "$app/Contents/Info.plist" <<PLIST81
<string>$version</string>94
<string>$version</string>82
<key>CFBundleVersion</key>95
<key>CFBundleVersion</key>83
<string>$version</string>96
<string>$version</string>97
<key>LSMinimumSystemVersion</key>98
<string>$MACOSX_DEPLOYMENT_TARGET</string>84
<key>NSHighResolutionCapable</key>99
<key>NSHighResolutionCapable</key>85
<true/>100
<true/>86
<key>NSMicrophoneUsageDescription</key>101
<key>NSMicrophoneUsageDescription</key>@@ -106,7 +121,10 @@ cp "$iconset/icon_64x64.png" "$iconset/icon_32x32@2x.png"106
cp "$iconset/icon_256x256.png" "$iconset/icon_128x128@2x.png"121
cp "$iconset/icon_256x256.png" "$iconset/icon_128x128@2x.png"107
iconutil -c icns "$iconset" -o "$app/Contents/Resources/icon.icns"122
iconutil -c icns "$iconset" -o "$app/Contents/Resources/icon.icns"108
123
109
# Developer ID signing when a certificate is configured in the build environment.124
# Developer ID signing when a certificate is configured in the build environment;125
# otherwise ad-hoc sign the bundle so the CodeDirectory is bound to Info.plist126
# (CFBundleIdentifier) instead of leaving the arm64 binary linker-signed (which127
# breaks TCC matching on Apple Silicon).110
if [ -n "${MACOS_CODESIGN_IDENTITY:-}" ]; then128
if [ -n "${MACOS_CODESIGN_IDENTITY:-}" ]; then111
echo "codesign with $MACOS_CODESIGN_IDENTITY"129
echo "codesign with $MACOS_CODESIGN_IDENTITY"112
codesign --force --options runtime --timestamp \130
codesign --force --options runtime --timestamp \@@ -118,6 +136,10 @@ if [ -n "${MACOS_CODESIGN_IDENTITY:-}" ]; then118
--sign "$MACOS_CODESIGN_IDENTITY" \136
--sign "$MACOS_CODESIGN_IDENTITY" \119
"$app"137
"$app"120
codesign --verify --deep --strict --verbose=2 "$app"138
codesign --verify --deep --strict --verbose=2 "$app"139
else140
echo "codesign ad-hoc (-)"141
codesign --force --sign - "$app"142
codesign --verify --deep --strict --verbose=2 "$app"121
fi143
fi122
144
123
# ditto keeps the bundle intact (plain zip would not); the result is the .app release asset.145
# ditto keeps the bundle intact (plain zip would not); the result is the .app release asset.@@ -69,11 +69,11 @@
69
69
<a class="btn btn-solid" href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg>Download latest</a>
70
70
<p class="note hud faint" id="os-note">Pick your platform below</p>
71
71
<a class="tlink hud" style="margin-top:16px" href="https://github.com/danieldaeschle/rusty-teams">About Rusty Teams <svg class="icon " aria-hidden="true"><use href="#i-arrow-up-right"/></svg></a></div></div>
72
<div class="blockB" data-reveal><p class="hud faint">Option 2 · Standalone</p><h3 class="display h3l">One file, <span class="hl">no setup.</span></h3><p class="t">Every release ships a Windows build, Linux AppImage, deb, rpm and tar.gz, and a universal macOS .app for Apple silicon and Intel.</p></div>
72
<div class="blockB" data-reveal><p class="hud faint">Option 2 · Standalone</p><h3 class="display h3l">One file, <span class="hl">no setup.</span></h3><p class="t">Every release ships a Windows build, Linux AppImage, deb, rpm and tar.gz, and a macOS .app for Apple Silicon (macOS 14+).</p></div>
73
73
<div class="hgrid plat">
74
74
<article data-os="windows"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">01</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-windows"/></svg></span><h3 class="display h3">Windows</h3></div><p class="t14">Main target</p><p class="d14">Sign-in runs through an embedded WebView2, so single sign-on with your Windows account usually just works.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get for Windows</a></div></article>
75
75
<article data-os="linux"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">02</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-terminal"/></svg></span><h3 class="display h3">Linux</h3></div><p class="t14">AppImage, deb, rpm, tar.gz</p><p class="d14">Uses your Chromium- or Firefox-based browser in the background. Offers to install itself and adds a menu entry.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get AppImage</a><p class="hud faint oth">Other files for Linux</p><ul class="files"><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">AppImage</span><span class="d">Runs anywhere, no install</span><span class="f">AppImage</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Debian and Ubuntu</span><span class="d">deb package</span><span class="f">deb</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Fedora and openSUSE</span><span class="d">rpm package</span><span class="f">rpm</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Tarball</span><span class="d">Unpack and run</span><span class="f">tar.gz</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li></ul></div></article>
76
<article data-os="mac"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">03</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-apple"/></svg></span><h3 class="display h3">macOS</h3></div><p class="t14">Universal .app, arm64 and x86_64</p><p class="d14">Starts your default Chromium- or Firefox-based browser on its own. Screen share uses the system dialog.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get for macOS</a></div></article>
76
<article data-os="mac"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">03</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-apple"/></svg></span><h3 class="display h3">macOS</h3></div><p class="t14">Apple Silicon .app, macOS 14+</p><p class="d14">Starts your default Chromium- or Firefox-based browser on its own. Screen share uses the system dialog.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get for macOS</a></div></article>
77
77
</div>
78
78
<div class="hgrid rel">
79
79
<div data-reveal><p class="hud faint">Release</p><h3 class="display h3l">Always the <span class="hl">latest.</span></h3><p class="t">Versioned builds for every platform live on GitHub releases, with the changelog next to them.</p>
@@ -69,11 +69,11 @@69
<a class="btn btn-solid" href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg>Download latest</a>69
<a class="btn btn-solid" href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg>Download latest</a>70
<p class="note hud faint" id="os-note">Pick your platform below</p>70
<p class="note hud faint" id="os-note">Pick your platform below</p>71
<a class="tlink hud" style="margin-top:16px" href="https://github.com/danieldaeschle/rusty-teams">About Rusty Teams <svg class="icon " aria-hidden="true"><use href="#i-arrow-up-right"/></svg></a></div></div>71
<a class="tlink hud" style="margin-top:16px" href="https://github.com/danieldaeschle/rusty-teams">About Rusty Teams <svg class="icon " aria-hidden="true"><use href="#i-arrow-up-right"/></svg></a></div></div>72
<div class="blockB" data-reveal><p class="hud faint">Option 2 · Standalone</p><h3 class="display h3l">One file, <span class="hl">no setup.</span></h3><p class="t">Every release ships a Windows build, Linux AppImage, deb, rpm and tar.gz, and a universal macOS .app for Apple silicon and Intel.</p></div>72
<div class="blockB" data-reveal><p class="hud faint">Option 2 · Standalone</p><h3 class="display h3l">One file, <span class="hl">no setup.</span></h3><p class="t">Every release ships a Windows build, Linux AppImage, deb, rpm and tar.gz, and a macOS .app for Apple Silicon (macOS 14+).</p></div>73
<div class="hgrid plat">73
<div class="hgrid plat">74
<article data-os="windows"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">01</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-windows"/></svg></span><h3 class="display h3">Windows</h3></div><p class="t14">Main target</p><p class="d14">Sign-in runs through an embedded WebView2, so single sign-on with your Windows account usually just works.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get for Windows</a></div></article>74
<article data-os="windows"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">01</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-windows"/></svg></span><h3 class="display h3">Windows</h3></div><p class="t14">Main target</p><p class="d14">Sign-in runs through an embedded WebView2, so single sign-on with your Windows account usually just works.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get for Windows</a></div></article>75
<article data-os="linux"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">02</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-terminal"/></svg></span><h3 class="display h3">Linux</h3></div><p class="t14">AppImage, deb, rpm, tar.gz</p><p class="d14">Uses your Chromium- or Firefox-based browser in the background. Offers to install itself and adds a menu entry.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get AppImage</a><p class="hud faint oth">Other files for Linux</p><ul class="files"><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">AppImage</span><span class="d">Runs anywhere, no install</span><span class="f">AppImage</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Debian and Ubuntu</span><span class="d">deb package</span><span class="f">deb</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Fedora and openSUSE</span><span class="d">rpm package</span><span class="f">rpm</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Tarball</span><span class="d">Unpack and run</span><span class="f">tar.gz</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li></ul></div></article>75
<article data-os="linux"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">02</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-terminal"/></svg></span><h3 class="display h3">Linux</h3></div><p class="t14">AppImage, deb, rpm, tar.gz</p><p class="d14">Uses your Chromium- or Firefox-based browser in the background. Offers to install itself and adds a menu entry.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get AppImage</a><p class="hud faint oth">Other files for Linux</p><ul class="files"><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">AppImage</span><span class="d">Runs anywhere, no install</span><span class="f">AppImage</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Debian and Ubuntu</span><span class="d">deb package</span><span class="f">deb</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Fedora and openSUSE</span><span class="d">rpm package</span><span class="f">rpm</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li><li><a href="https://github.com/danieldaeschle/rusty-teams/releases/latest"><span><span class="t">Tarball</span><span class="d">Unpack and run</span><span class="f">tar.gz</span></span><svg class="icon " aria-hidden="true"><use href="#i-download"/></svg></a></li></ul></div></article>76
<article data-os="mac"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">03</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-apple"/></svg></span><h3 class="display h3">macOS</h3></div><p class="t14">Universal .app, arm64 and x86_64</p><p class="d14">Starts your default Chromium- or Firefox-based browser on its own. Screen share uses the system dialog.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get for macOS</a></div></article>76
<article data-os="mac"><div class="hd"><span class="hud muted plabel">Platform</span><span class="hud faint">03</span></div><div class="bd"><div class="row-h"><span class="ibox"><svg class="icon " aria-hidden="true"><use href="#i-apple"/></svg></span><h3 class="display h3">macOS</h3></div><p class="t14">Apple Silicon .app, macOS 14+</p><p class="d14">Starts your default Chromium- or Firefox-based browser on its own. Screen share uses the system dialog.</p><a class="btn btn-out btn-sm" data-primary href="https://github.com/danieldaeschle/rusty-teams/releases/latest">Get for macOS</a></div></article>77
</div>77
</div>78
<div class="hgrid rel">78
<div class="hgrid rel">79
<div data-reveal><p class="hud faint">Release</p><h3 class="display h3l">Always the <span class="hl">latest.</span></h3><p class="t">Versioned builds for every platform live on GitHub releases, with the changelog next to them.</p>79
<div data-reveal><p class="hud faint">Release</p><h3 class="display h3l">Always the <span class="hl">latest.</span></h3><p class="t">Versioned builds for every platform live on GitHub releases, with the changelog next to them.</p>@@ -149,6 +149,11 @@ impl DesktopCapturer {
149
149
self.handle.capture_frame();
150
150
}
151
151
152
/// Sets the target maximum frame rate for the capturer (best effort).
153
pub fn set_max_frame_rate(&mut self, max_fps: u32) {
154
self.handle.set_max_frame_rate(max_fps);
155
}
156
152
157
/// Retrieves a list of available capture sources.
153
158
///
154
159
/// Returns a list of screens or windows that can be captured, depending
@@ -260,10 +265,18 @@ impl std::fmt::Display for CaptureSource {
260
265
}
261
266
}
262
267
263
#[derive(Debug, PartialEq)]
268
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264
269
pub enum CaptureError {
265
270
Temporary,
266
271
Permanent,
272
/// The picker or capture stream failed to start.
273
StartFailed,
274
/// Sharing was stopped from the system UI, such as the macOS menu bar.
275
StoppedByUser,
276
/// The shared source is closed or gone (on macOS 15.2+ it may reopen).
277
SourceGone,
278
/// The OS stopped the capture stream for another reason.
279
Interrupted,
267
280
}
268
281
269
282
/// Outcome of a desktop-owned source picker.
@@ -282,6 +295,10 @@ fn capture_result_from_sys(
282
295
Err(error) => Err(match error {
283
296
imp_dc::CaptureError::Temporary => CaptureError::Temporary,
284
297
imp_dc::CaptureError::Permanent => CaptureError::Permanent,
298
imp_dc::CaptureError::StartFailed => CaptureError::StartFailed,
299
imp_dc::CaptureError::StoppedByUser => CaptureError::StoppedByUser,
300
imp_dc::CaptureError::SourceGone => CaptureError::SourceGone,
301
imp_dc::CaptureError::Interrupted => CaptureError::Interrupted,
285
302
}),
286
303
}
287
304
}
@@ -149,6 +149,11 @@ impl DesktopCapturer {149
self.handle.capture_frame();149
self.handle.capture_frame();150
}150
}151
151
152
/// Sets the target maximum frame rate for the capturer (best effort).153
pub fn set_max_frame_rate(&mut self, max_fps: u32) {154
self.handle.set_max_frame_rate(max_fps);155
}156
152
/// Retrieves a list of available capture sources.157
/// Retrieves a list of available capture sources.153
///158
///154
/// Returns a list of screens or windows that can be captured, depending159
/// Returns a list of screens or windows that can be captured, depending@@ -260,10 +265,18 @@ impl std::fmt::Display for CaptureSource {260
}265
}261
}266
}262
267
263
#[derive(Debug, PartialEq)]268
#[derive(Debug, Clone, Copy, PartialEq, Eq)]264
pub enum CaptureError {269
pub enum CaptureError {265
Temporary,270
Temporary,266
Permanent,271
Permanent,272
/// The picker or capture stream failed to start.273
StartFailed,274
/// Sharing was stopped from the system UI, such as the macOS menu bar.275
StoppedByUser,276
/// The shared source is closed or gone (on macOS 15.2+ it may reopen).277
SourceGone,278
/// The OS stopped the capture stream for another reason.279
Interrupted,267
}280
}268
281
269
/// Outcome of a desktop-owned source picker.282
/// Outcome of a desktop-owned source picker.@@ -282,6 +295,10 @@ fn capture_result_from_sys(282
Err(error) => Err(match error {295
Err(error) => Err(match error {283
imp_dc::CaptureError::Temporary => CaptureError::Temporary,296
imp_dc::CaptureError::Temporary => CaptureError::Temporary,284
imp_dc::CaptureError::Permanent => CaptureError::Permanent,297
imp_dc::CaptureError::Permanent => CaptureError::Permanent,298
imp_dc::CaptureError::StartFailed => CaptureError::StartFailed,299
imp_dc::CaptureError::StoppedByUser => CaptureError::StoppedByUser,300
imp_dc::CaptureError::SourceGone => CaptureError::SourceGone,301
imp_dc::CaptureError::Interrupted => CaptureError::Interrupted,285
}),302
}),286
}303
}287
}304
}@@ -144,6 +144,10 @@ impl DesktopCapturer {
144
144
self.sys_handle.capture_frame();
145
145
}
146
146
147
pub(crate) fn set_max_frame_rate(&self, max_fps: u32) {
148
self.sys_handle.set_max_frame_rate(max_fps);
149
}
150
147
151
pub(crate) fn start<T>(&mut self, callback: T)
148
152
where
149
153
T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static,
@@ -248,6 +252,10 @@ where
248
252
Err(error) => Err(match error {
249
253
sys_dc::CaptureError::Temporary => CaptureError::Temporary,
250
254
sys_dc::CaptureError::Permanent => CaptureError::Permanent,
255
sys_dc::CaptureError::StartFailed => CaptureError::StartFailed,
256
sys_dc::CaptureError::StoppedByUser => CaptureError::StoppedByUser,
257
sys_dc::CaptureError::SourceGone => CaptureError::SourceGone,
258
sys_dc::CaptureError::Interrupted => CaptureError::Interrupted,
251
259
}),
252
260
}
253
261
}
@@ -287,4 +295,8 @@ impl CaptureSource {
287
295
pub(crate) enum CaptureError {
288
296
Temporary,
289
297
Permanent,
298
StartFailed,
299
StoppedByUser,
300
SourceGone,
301
Interrupted,
290
302
}
@@ -144,6 +144,10 @@ impl DesktopCapturer {144
self.sys_handle.capture_frame();144
self.sys_handle.capture_frame();145
}145
}146
146
147
pub(crate) fn set_max_frame_rate(&self, max_fps: u32) {148
self.sys_handle.set_max_frame_rate(max_fps);149
}150
147
pub(crate) fn start<T>(&mut self, callback: T)151
pub(crate) fn start<T>(&mut self, callback: T)148
where152
where149
T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static,153
T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static,@@ -248,6 +252,10 @@ where248
Err(error) => Err(match error {252
Err(error) => Err(match error {249
sys_dc::CaptureError::Temporary => CaptureError::Temporary,253
sys_dc::CaptureError::Temporary => CaptureError::Temporary,250
sys_dc::CaptureError::Permanent => CaptureError::Permanent,254
sys_dc::CaptureError::Permanent => CaptureError::Permanent,255
sys_dc::CaptureError::StartFailed => CaptureError::StartFailed,256
sys_dc::CaptureError::StoppedByUser => CaptureError::StoppedByUser,257
sys_dc::CaptureError::SourceGone => CaptureError::SourceGone,258
sys_dc::CaptureError::Interrupted => CaptureError::Interrupted,251
}),259
}),252
}260
}253
}261
}@@ -287,4 +295,8 @@ impl CaptureSource {287
pub(crate) enum CaptureError {295
pub(crate) enum CaptureError {288
Temporary,296
Temporary,289
Permanent,297
Permanent,298
StartFailed,299
StoppedByUser,300
SourceGone,301
Interrupted,290
}302
}@@ -334,7 +334,7 @@ fn main() {
334
334
println!("cargo:rustc-link-lib=framework=IOSurface");
335
335
println!("cargo:rustc-link-lib=framework=ScreenCaptureKit");
336
336
337
configure_darwin_sysroot(&mut builder);
337
let sysroot = configure_darwin_sysroot(&mut builder);
338
338
339
339
builder
340
340
.file("src/objc_video_factory.mm")
@@ -342,6 +342,29 @@ fn main() {
342
342
.flag("-stdlib=libc++")
343
343
.flag("-std=c++20")
344
344
.flag("-Wno-nullability-completeness");
345
346
let mut sck_builder = cc::Build::new();
347
sck_builder
348
.cpp(true)
349
.file("src/sck_window_capturer.mm")
350
.includes(&[
351
path::PathBuf::from("./include"),
352
webrtc_include.clone(),
353
webrtc_include.join("third_party/abseil-cpp/"),
354
webrtc_include.join("third_party/libyuv/include/"),
355
webrtc_include.join("third_party/libc++/"),
356
webrtc_include.join("sdk/objc"),
357
webrtc_include.join("sdk/objc/base"),
358
])
359
.flag(format!("-isysroot{}", sysroot))
360
.flag("-stdlib=libc++")
361
.flag("-std=c++20")
362
.flag("-fobjc-arc")
363
.flag("-Wno-nullability-completeness");
364
for (key, value) in webrtc_sys_build::webrtc_defines() {
365
sck_builder.define(key.as_str(), value.as_deref());
366
}
367
sck_builder.warnings(false).compile("webrtcsys-sck-window");
345
368
}
346
369
"ios" => {
347
370
println!("cargo:rustc-link-lib=framework=Foundation");
@@ -431,7 +454,7 @@ fn get_output_path() -> PathBuf {
431
454
return PathBuf::from(path);
432
455
}
433
456
434
fn configure_darwin_sysroot(builder: &mut cc::Build) {
457
fn configure_darwin_sysroot(builder: &mut cc::Build) -> String {
435
458
let target_os = webrtc_sys_build::target_os();
436
459
437
460
let sdk = match target_os.as_str() {
@@ -454,7 +477,7 @@ fn configure_darwin_sysroot(builder: &mut cc::Build) {
454
477
let sysroot = Command::new("xcrun").args(["--sdk", sdk, "--show-sdk-path"]).output().unwrap();
455
478
456
479
let sysroot = String::from_utf8_lossy(&sysroot.stdout);
457
let sysroot = sysroot.trim();
480
let sysroot = sysroot.trim().to_owned();
458
481
459
482
let search_dirs = Command::new("cc").arg("--print-search-dirs").output().unwrap();
460
483
@@ -468,6 +491,7 @@ fn configure_darwin_sysroot(builder: &mut cc::Build) {
468
491
}
469
492
470
493
builder.flag(format!("-isysroot{}", sysroot).as_str());
494
sysroot
471
495
}
472
496
473
497
fn configure_android_sysroot(builder: &mut cc::Build) {
@@ -334,7 +334,7 @@ fn main() {334
println!("cargo:rustc-link-lib=framework=IOSurface");334
println!("cargo:rustc-link-lib=framework=IOSurface");335
println!("cargo:rustc-link-lib=framework=ScreenCaptureKit");335
println!("cargo:rustc-link-lib=framework=ScreenCaptureKit");336
336
337
configure_darwin_sysroot(&mut builder);337
let sysroot = configure_darwin_sysroot(&mut builder);338
338
339
builder339
builder340
.file("src/objc_video_factory.mm")340
.file("src/objc_video_factory.mm")@@ -342,6 +342,29 @@ fn main() {342
.flag("-stdlib=libc++")342
.flag("-stdlib=libc++")343
.flag("-std=c++20")343
.flag("-std=c++20")344
.flag("-Wno-nullability-completeness");344
.flag("-Wno-nullability-completeness");345
346
let mut sck_builder = cc::Build::new();347
sck_builder348
.cpp(true)349
.file("src/sck_window_capturer.mm")350
.includes(&[351
path::PathBuf::from("./include"),352
webrtc_include.clone(),353
webrtc_include.join("third_party/abseil-cpp/"),354
webrtc_include.join("third_party/libyuv/include/"),355
webrtc_include.join("third_party/libc++/"),356
webrtc_include.join("sdk/objc"),357
webrtc_include.join("sdk/objc/base"),358
])359
.flag(format!("-isysroot{}", sysroot))360
.flag("-stdlib=libc++")361
.flag("-std=c++20")362
.flag("-fobjc-arc")363
.flag("-Wno-nullability-completeness");364
for (key, value) in webrtc_sys_build::webrtc_defines() {365
sck_builder.define(key.as_str(), value.as_deref());366
}367
sck_builder.warnings(false).compile("webrtcsys-sck-window");345
}368
}346
"ios" => {369
"ios" => {347
println!("cargo:rustc-link-lib=framework=Foundation");370
println!("cargo:rustc-link-lib=framework=Foundation");@@ -431,7 +454,7 @@ fn get_output_path() -> PathBuf {431
return PathBuf::from(path);454
return PathBuf::from(path);432
}455
}433
456
434
fn configure_darwin_sysroot(builder: &mut cc::Build) {457
fn configure_darwin_sysroot(builder: &mut cc::Build) -> String {435
let target_os = webrtc_sys_build::target_os();458
let target_os = webrtc_sys_build::target_os();436
459
437
let sdk = match target_os.as_str() {460
let sdk = match target_os.as_str() {@@ -454,7 +477,7 @@ fn configure_darwin_sysroot(builder: &mut cc::Build) {454
let sysroot = Command::new("xcrun").args(["--sdk", sdk, "--show-sdk-path"]).output().unwrap();477
let sysroot = Command::new("xcrun").args(["--sdk", sdk, "--show-sdk-path"]).output().unwrap();455
478
456
let sysroot = String::from_utf8_lossy(&sysroot.stdout);479
let sysroot = String::from_utf8_lossy(&sysroot.stdout);457
let sysroot = sysroot.trim();480
let sysroot = sysroot.trim().to_owned();458
481
459
let search_dirs = Command::new("cc").arg("--print-search-dirs").output().unwrap();482
let search_dirs = Command::new("cc").arg("--print-search-dirs").output().unwrap();460
483
@@ -468,6 +491,7 @@ fn configure_darwin_sysroot(builder: &mut cc::Build) {468
}491
}469
492
470
builder.flag(format!("-isysroot{}", sysroot).as_str());493
builder.flag(format!("-isysroot{}", sysroot).as_str());494
sysroot471
}495
}472
496
473
fn configure_android_sysroot(builder: &mut cc::Build) {497
fn configure_android_sysroot(builder: &mut cc::Build) {@@ -15,10 +15,14 @@
15
15
*/
16
16
17
17
#pragma once
18
#include <cstdint>
18
19
#include <memory>
19
20
20
21
#include "modules/desktop_capture/desktop_capturer.h"
21
22
#include "rust/cxx.h"
23
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
24
#include "livekit/sck_window_capturer.h"
25
#endif
22
26
23
27
namespace livekit_ffi {
24
28
class DesktopFrame;
@@ -35,8 +39,16 @@ namespace livekit_ffi {
35
39
class DesktopCapturer : public webrtc::DesktopCapturer::Callback,
36
40
public webrtc::DelegatedSourceListController::Observer {
37
41
public:
42
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
43
explicit DesktopCapturer(std::unique_ptr<webrtc::DesktopCapturer> capturer,
44
SckWindowCapturer* sck_window_capturer = nullptr)
45
: capturer(std::move(capturer)),
46
sck_window_capturer(sck_window_capturer),
47
callback(std::nullopt) {}
48
#else
38
49
explicit DesktopCapturer(std::unique_ptr<webrtc::DesktopCapturer> capturer)
39
50
: capturer(std::move(capturer)), callback(std::nullopt) {}
51
#endif
40
52
~DesktopCapturer() override;
41
53
42
54
void OnCaptureResult(webrtc::DesktopCapturer::Result result,
@@ -49,6 +61,9 @@ class DesktopCapturer : public webrtc::DesktopCapturer::Callback,
49
61
bool select_source(uint64_t id) const { return capturer->SelectSource(id); }
50
62
void start(rust::Box<DesktopCapturerCallbackWrapper> callback);
51
63
void capture_frame() const { capturer->CaptureFrame(); }
64
void set_max_frame_rate(uint32_t max_fps) const {
65
capturer->SetMaxFrameRate(max_fps);
66
}
52
67
bool has_delegated_picker() const;
53
68
void observe_picker(rust::Box<PortalPickerCallbackWrapper> callback);
54
69
void ensure_picker_visible();
@@ -58,6 +73,9 @@ class DesktopCapturer : public webrtc::DesktopCapturer::Callback,
58
73
webrtc::DelegatedSourceListController* picker_controller() const;
59
74
60
75
std::unique_ptr<webrtc::DesktopCapturer> capturer;
76
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
77
SckWindowCapturer* sck_window_capturer = nullptr;
78
#endif
61
79
std::optional<rust::Box<DesktopCapturerCallbackWrapper>> callback;
62
80
std::optional<rust::Box<PortalPickerCallbackWrapper>> picker;
63
81
};
@@ -15,10 +15,14 @@15
*/15
*/16
16
17
#pragma once17
#pragma once18
#include <cstdint>18
#include <memory>19
#include <memory>19
20
20
#include "modules/desktop_capture/desktop_capturer.h"21
#include "modules/desktop_capture/desktop_capturer.h"21
#include "rust/cxx.h"22
#include "rust/cxx.h"23
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)24
#include "livekit/sck_window_capturer.h"25
#endif22
26
23
namespace livekit_ffi {27
namespace livekit_ffi {24
class DesktopFrame;28
class DesktopFrame;@@ -35,8 +39,16 @@ namespace livekit_ffi {35
class DesktopCapturer : public webrtc::DesktopCapturer::Callback,39
class DesktopCapturer : public webrtc::DesktopCapturer::Callback,36
public webrtc::DelegatedSourceListController::Observer {40
public webrtc::DelegatedSourceListController::Observer {37
public:41
public:42
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)43
explicit DesktopCapturer(std::unique_ptr<webrtc::DesktopCapturer> capturer,44
SckWindowCapturer* sck_window_capturer = nullptr)45
: capturer(std::move(capturer)),46
sck_window_capturer(sck_window_capturer),47
callback(std::nullopt) {}48
#else38
explicit DesktopCapturer(std::unique_ptr<webrtc::DesktopCapturer> capturer)49
explicit DesktopCapturer(std::unique_ptr<webrtc::DesktopCapturer> capturer)39
: capturer(std::move(capturer)), callback(std::nullopt) {}50
: capturer(std::move(capturer)), callback(std::nullopt) {}51
#endif40
~DesktopCapturer() override;52
~DesktopCapturer() override;41
53
42
void OnCaptureResult(webrtc::DesktopCapturer::Result result,54
void OnCaptureResult(webrtc::DesktopCapturer::Result result,@@ -49,6 +61,9 @@ class DesktopCapturer : public webrtc::DesktopCapturer::Callback,49
bool select_source(uint64_t id) const { return capturer->SelectSource(id); }61
bool select_source(uint64_t id) const { return capturer->SelectSource(id); }50
void start(rust::Box<DesktopCapturerCallbackWrapper> callback);62
void start(rust::Box<DesktopCapturerCallbackWrapper> callback);51
void capture_frame() const { capturer->CaptureFrame(); }63
void capture_frame() const { capturer->CaptureFrame(); }64
void set_max_frame_rate(uint32_t max_fps) const {65
capturer->SetMaxFrameRate(max_fps);66
}52
bool has_delegated_picker() const;67
bool has_delegated_picker() const;53
void observe_picker(rust::Box<PortalPickerCallbackWrapper> callback);68
void observe_picker(rust::Box<PortalPickerCallbackWrapper> callback);54
void ensure_picker_visible();69
void ensure_picker_visible();@@ -58,6 +73,9 @@ class DesktopCapturer : public webrtc::DesktopCapturer::Callback,58
webrtc::DelegatedSourceListController* picker_controller() const;73
webrtc::DelegatedSourceListController* picker_controller() const;59
74
60
std::unique_ptr<webrtc::DesktopCapturer> capturer;75
std::unique_ptr<webrtc::DesktopCapturer> capturer;76
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)77
SckWindowCapturer* sck_window_capturer = nullptr;78
#endif61
std::optional<rust::Box<DesktopCapturerCallbackWrapper>> callback;79
std::optional<rust::Box<DesktopCapturerCallbackWrapper>> callback;62
std::optional<rust::Box<PortalPickerCallbackWrapper>> picker;80
std::optional<rust::Box<PortalPickerCallbackWrapper>> picker;63
};81
};@@ -0,0 +1,51 @@
1
/*
2
* Copyright 2025 LiveKit, Inc.
3
*
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
7
*
8
* http://www.apache.org/licenses/LICENSE-2.0
9
*
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
15
*/
16
17
#pragma once
18
19
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
20
21
#include <memory>
22
23
#include "modules/desktop_capture/desktop_capture_options.h"
24
#include "modules/desktop_capture/desktop_capturer.h"
25
26
namespace livekit_ffi {
27
28
enum class SckCaptureStatus {
29
kActive,
30
kPickerCancelled,
31
kStartFailed,
32
kStoppedByUser,
33
kWindowGone,
34
kInterrupted,
35
};
36
37
// ScreenCaptureKit single-window DesktopCapturer backed by
38
// SCContentSharingPicker. WebRTC's DesktopCapturer::CreateWindowCapturer on
39
// macOS only creates legacy WindowCapturerMac (CGWindowList without a system
40
// picker).
41
class SckWindowCapturer : public webrtc::DesktopCapturer {
42
public:
43
virtual SckCaptureStatus last_status() const = 0;
44
};
45
46
std::unique_ptr<SckWindowCapturer> CreateSckWindowCapturer(
47
const webrtc::DesktopCaptureOptions& options);
48
49
} // namespace livekit_ffi
50
51
#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
@@ -0,0 +1,51 @@1
/*2
* Copyright 2025 LiveKit, Inc.3
*4
* Licensed under the Apache License, Version 2.0 (the "License");5
* you may not use this file except in compliance with the License.6
* You may obtain a copy of the License at7
*8
* http://www.apache.org/licenses/LICENSE-2.09
*10
* Unless required by applicable law or agreed to in writing, software11
* distributed under the License is distributed on an "AS IS" BASIS,12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13
* See the License for the specific language governing permissions and14
* limitations under the License.15
*/16
17
#pragma once18
19
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)20
21
#include <memory>22
23
#include "modules/desktop_capture/desktop_capture_options.h"24
#include "modules/desktop_capture/desktop_capturer.h"25
26
namespace livekit_ffi {27
28
enum class SckCaptureStatus {29
kActive,30
kPickerCancelled,31
kStartFailed,32
kStoppedByUser,33
kWindowGone,34
kInterrupted,35
};36
37
// ScreenCaptureKit single-window DesktopCapturer backed by38
// SCContentSharingPicker. WebRTC's DesktopCapturer::CreateWindowCapturer on39
// macOS only creates legacy WindowCapturerMac (CGWindowList without a system40
// picker).41
class SckWindowCapturer : public webrtc::DesktopCapturer {42
public:43
virtual SckCaptureStatus last_status() const = 0;44
};45
46
std::unique_ptr<SckWindowCapturer> CreateSckWindowCapturer(47
const webrtc::DesktopCaptureOptions& options);48
49
} // namespace livekit_ffi50
51
#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)@@ -54,10 +54,22 @@ std::unique_ptr<DesktopCapturer> new_desktop_capturer(
54
54
webrtc_options.set_prefer_cursor_embedded(options.include_cursor);
55
55
56
56
std::unique_ptr<webrtc::DesktopCapturer> capturer = nullptr;
57
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
58
SckWindowCapturer* sck_window = nullptr;
59
#endif
57
60
switch (options.source_type) {
58
61
case SourceType::Window:
62
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
63
{
64
auto window_capturer = CreateSckWindowCapturer(webrtc_options);
65
sck_window = window_capturer.get();
66
capturer = std::move(window_capturer);
67
break;
68
}
69
#else
59
70
capturer = webrtc::DesktopCapturer::CreateWindowCapturer(webrtc_options);
60
71
break;
72
#endif
61
73
case SourceType::Screen:
62
74
capturer = webrtc::DesktopCapturer::CreateScreenCapturer(webrtc_options);
63
75
break;
@@ -71,7 +83,11 @@ std::unique_ptr<DesktopCapturer> new_desktop_capturer(
71
83
if (!capturer) {
72
84
return nullptr;
73
85
}
86
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
87
return std::make_unique<DesktopCapturer>(std::move(capturer), sck_window);
88
#else
74
89
return std::make_unique<DesktopCapturer>(std::move(capturer));
90
#endif
75
91
}
76
92
77
93
DesktopCapturer::~DesktopCapturer() {
@@ -153,6 +169,29 @@ void DesktopCapturer::OnCaptureResult(
153
169
default:
154
170
break;
155
171
}
172
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
173
if (sck_window_capturer && ret_result != CaptureResult::Success) {
174
switch (sck_window_capturer->last_status()) {
175
case SckCaptureStatus::kStartFailed:
176
ret_result = CaptureResult::StartFailed;
177
break;
178
case SckCaptureStatus::kStoppedByUser:
179
ret_result = CaptureResult::StoppedByUser;
180
break;
181
case SckCaptureStatus::kWindowGone:
182
ret_result = CaptureResult::SourceGone;
183
break;
184
case SckCaptureStatus::kInterrupted:
185
ret_result = CaptureResult::Interrupted;
186
break;
187
case SckCaptureStatus::kPickerCancelled:
188
ret_result = CaptureResult::ErrorPermanent;
189
break;
190
case SckCaptureStatus::kActive:
191
break;
192
}
193
}
194
#endif
156
195
if (callback) {
157
196
(*callback)->on_capture_result(
158
197
ret_result, std::make_unique<DesktopFrame>(std::move(frame)));
@@ -54,10 +54,22 @@ std::unique_ptr<DesktopCapturer> new_desktop_capturer(54
webrtc_options.set_prefer_cursor_embedded(options.include_cursor);54
webrtc_options.set_prefer_cursor_embedded(options.include_cursor);55
55
56
std::unique_ptr<webrtc::DesktopCapturer> capturer = nullptr;56
std::unique_ptr<webrtc::DesktopCapturer> capturer = nullptr;57
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)58
SckWindowCapturer* sck_window = nullptr;59
#endif57
switch (options.source_type) {60
switch (options.source_type) {58
case SourceType::Window:61
case SourceType::Window:62
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)63
{64
auto window_capturer = CreateSckWindowCapturer(webrtc_options);65
sck_window = window_capturer.get();66
capturer = std::move(window_capturer);67
break;68
}69
#else59
capturer = webrtc::DesktopCapturer::CreateWindowCapturer(webrtc_options);70
capturer = webrtc::DesktopCapturer::CreateWindowCapturer(webrtc_options);60
break;71
break;72
#endif61
case SourceType::Screen:73
case SourceType::Screen:62
capturer = webrtc::DesktopCapturer::CreateScreenCapturer(webrtc_options);74
capturer = webrtc::DesktopCapturer::CreateScreenCapturer(webrtc_options);63
break;75
break;@@ -71,7 +83,11 @@ std::unique_ptr<DesktopCapturer> new_desktop_capturer(71
if (!capturer) {83
if (!capturer) {72
return nullptr;84
return nullptr;73
}85
}86
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)87
return std::make_unique<DesktopCapturer>(std::move(capturer), sck_window);88
#else74
return std::make_unique<DesktopCapturer>(std::move(capturer));89
return std::make_unique<DesktopCapturer>(std::move(capturer));90
#endif75
}91
}76
92
77
DesktopCapturer::~DesktopCapturer() {93
DesktopCapturer::~DesktopCapturer() {@@ -153,6 +169,29 @@ void DesktopCapturer::OnCaptureResult(153
default:169
default:154
break;170
break;155
}171
}172
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)173
if (sck_window_capturer && ret_result != CaptureResult::Success) {174
switch (sck_window_capturer->last_status()) {175
case SckCaptureStatus::kStartFailed:176
ret_result = CaptureResult::StartFailed;177
break;178
case SckCaptureStatus::kStoppedByUser:179
ret_result = CaptureResult::StoppedByUser;180
break;181
case SckCaptureStatus::kWindowGone:182
ret_result = CaptureResult::SourceGone;183
break;184
case SckCaptureStatus::kInterrupted:185
ret_result = CaptureResult::Interrupted;186
break;187
case SckCaptureStatus::kPickerCancelled:188
ret_result = CaptureResult::ErrorPermanent;189
break;190
case SckCaptureStatus::kActive:191
break;192
}193
}194
#endif156
if (callback) {195
if (callback) {157
(*callback)->on_capture_result(196
(*callback)->on_capture_result(158
ret_result, std::make_unique<DesktopFrame>(std::move(frame)));197
ret_result, std::make_unique<DesktopFrame>(std::move(frame)));@@ -44,6 +44,10 @@ pub mod ffi {
44
44
Success,
45
45
ErrorTemporary,
46
46
ErrorPermanent,
47
StartFailed,
48
StoppedByUser,
49
SourceGone,
50
Interrupted,
47
51
}
48
52
49
53
unsafe extern "C++" {
@@ -54,6 +58,7 @@ pub mod ffi {
54
58
55
59
fn new_desktop_capturer(options: DesktopCapturerOptions) -> UniquePtr<DesktopCapturer>;
56
60
fn capture_frame(self: &DesktopCapturer);
61
fn set_max_frame_rate(self: &DesktopCapturer, max_fps: u32);
57
62
fn get_source_list(self: &DesktopCapturer) -> Vec<Source>;
58
63
fn select_source(self: &DesktopCapturer, id: u64) -> bool;
59
64
fn start(self: Pin<&mut DesktopCapturer>, callback: Box<DesktopCapturerCallbackWrapper>);
@@ -92,10 +97,14 @@ pub mod ffi {
92
97
93
98
impl_thread_safety!(ffi::DesktopCapturer, Send + Sync);
94
99
95
#[derive(Debug, PartialEq)]
100
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96
101
pub enum CaptureError {
97
102
Temporary,
98
103
Permanent,
104
StartFailed,
105
StoppedByUser,
106
SourceGone,
107
Interrupted,
99
108
}
100
109
101
110
pub trait DesktopCapturerCallback: Send {
@@ -120,6 +129,18 @@ impl DesktopCapturerCallbackWrapper {
120
129
CaptureResult::ErrorPermanent => {
121
130
self.callback.on_capture_result(Err(CaptureError::Permanent))
122
131
}
132
CaptureResult::StartFailed => {
133
self.callback.on_capture_result(Err(CaptureError::StartFailed))
134
}
135
CaptureResult::StoppedByUser => {
136
self.callback.on_capture_result(Err(CaptureError::StoppedByUser))
137
}
138
CaptureResult::SourceGone => {
139
self.callback.on_capture_result(Err(CaptureError::SourceGone))
140
}
141
CaptureResult::Interrupted => {
142
self.callback.on_capture_result(Err(CaptureError::Interrupted))
143
}
123
144
_ => self.callback.on_capture_result(Err(CaptureError::Permanent)),
124
145
}
125
146
}
@@ -44,6 +44,10 @@ pub mod ffi {44
Success,44
Success,45
ErrorTemporary,45
ErrorTemporary,46
ErrorPermanent,46
ErrorPermanent,47
StartFailed,48
StoppedByUser,49
SourceGone,50
Interrupted,47
}51
}48
52
49
unsafe extern "C++" {53
unsafe extern "C++" {@@ -54,6 +58,7 @@ pub mod ffi {54
58
55
fn new_desktop_capturer(options: DesktopCapturerOptions) -> UniquePtr<DesktopCapturer>;59
fn new_desktop_capturer(options: DesktopCapturerOptions) -> UniquePtr<DesktopCapturer>;56
fn capture_frame(self: &DesktopCapturer);60
fn capture_frame(self: &DesktopCapturer);61
fn set_max_frame_rate(self: &DesktopCapturer, max_fps: u32);57
fn get_source_list(self: &DesktopCapturer) -> Vec<Source>;62
fn get_source_list(self: &DesktopCapturer) -> Vec<Source>;58
fn select_source(self: &DesktopCapturer, id: u64) -> bool;63
fn select_source(self: &DesktopCapturer, id: u64) -> bool;59
fn start(self: Pin<&mut DesktopCapturer>, callback: Box<DesktopCapturerCallbackWrapper>);64
fn start(self: Pin<&mut DesktopCapturer>, callback: Box<DesktopCapturerCallbackWrapper>);@@ -92,10 +97,14 @@ pub mod ffi {92
97
93
impl_thread_safety!(ffi::DesktopCapturer, Send + Sync);98
impl_thread_safety!(ffi::DesktopCapturer, Send + Sync);94
99
95
#[derive(Debug, PartialEq)]100
#[derive(Debug, Clone, Copy, PartialEq, Eq)]96
pub enum CaptureError {101
pub enum CaptureError {97
Temporary,102
Temporary,98
Permanent,103
Permanent,104
StartFailed,105
StoppedByUser,106
SourceGone,107
Interrupted,99
}108
}100
109
101
pub trait DesktopCapturerCallback: Send {110
pub trait DesktopCapturerCallback: Send {@@ -120,6 +129,18 @@ impl DesktopCapturerCallbackWrapper {120
CaptureResult::ErrorPermanent => {129
CaptureResult::ErrorPermanent => {121
self.callback.on_capture_result(Err(CaptureError::Permanent))130
self.callback.on_capture_result(Err(CaptureError::Permanent))122
}131
}132
CaptureResult::StartFailed => {133
self.callback.on_capture_result(Err(CaptureError::StartFailed))134
}135
CaptureResult::StoppedByUser => {136
self.callback.on_capture_result(Err(CaptureError::StoppedByUser))137
}138
CaptureResult::SourceGone => {139
self.callback.on_capture_result(Err(CaptureError::SourceGone))140
}141
CaptureResult::Interrupted => {142
self.callback.on_capture_result(Err(CaptureError::Interrupted))143
}123
_ => self.callback.on_capture_result(Err(CaptureError::Permanent)),144
_ => self.callback.on_capture_result(Err(CaptureError::Permanent)),124
}145
}125
}146
}@@ -0,0 +1,809 @@
1
/*
2
* Copyright 2025 LiveKit, Inc.
3
*
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
7
*
8
* http://www.apache.org/licenses/LICENSE-2.0
9
*
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
15
*/
16
17
#include "livekit/sck_window_capturer.h"
18
19
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
20
21
#import <CoreGraphics/CoreGraphics.h>
22
#import <CoreMedia/CoreMedia.h>
23
#import <CoreVideo/CoreVideo.h>
24
#import <Foundation/Foundation.h>
25
#import <IOSurface/IOSurface.h>
26
#import <ScreenCaptureKit/ScreenCaptureKit.h>
27
#import <dispatch/dispatch.h>
28
29
#include <climits>
30
#include <cmath>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <memory>
35
#include <utility>
36
37
#include "modules/desktop_capture/desktop_frame.h"
38
#include "modules/desktop_capture/desktop_geometry.h"
39
#include "modules/desktop_capture/mac/sck_picker_handle.h"
40
41
namespace {
42
43
constexpr size_t kMinCaptureDimension = 2;
44
constexpr size_t kMaxCaptureDimension = 16384;
45
constexpr uint32_t kDefaultMaxFps = 30;
46
47
livekit_ffi::SckCaptureStatus status_for_stop_error(NSError* error) {
48
if ([error.domain isEqualToString:SCStreamErrorDomain]) {
49
if (error.code == SCStreamErrorUserStopped) {
50
return livekit_ffi::SckCaptureStatus::kStoppedByUser;
51
}
52
if (error.code == SCStreamErrorNoCaptureSource) {
53
return livekit_ffi::SckCaptureStatus::kWindowGone;
54
}
55
}
56
return livekit_ffi::SckCaptureStatus::kInterrupted;
57
}
58
59
size_t clamp_dimension(double pixels) {
60
if (!std::isfinite(pixels) || pixels < static_cast<double>(kMinCaptureDimension)) {
61
return kMinCaptureDimension;
62
}
63
if (pixels > static_cast<double>(kMaxCaptureDimension)) {
64
return kMaxCaptureDimension;
65
}
66
return static_cast<size_t>(std::llround(pixels));
67
}
68
69
double clamp_double(double value, double lo, double hi) {
70
if (value < lo) {
71
return lo;
72
}
73
if (value > hi) {
74
return hi;
75
}
76
return value;
77
}
78
79
} // namespace
80
81
@interface LiveKitMacWindowSession
82
: NSObject <SCStreamDelegate, SCStreamOutput, SCContentSharingPickerObserver>
83
- (instancetype)initWithMaxFps:(uint32_t)maxFps includeCursor:(BOOL)includeCursor;
84
- (void)startPickerWithPicker:(SCContentSharingPicker*)picker;
85
- (void)setMaxFps:(uint32_t)maxFps;
86
- (BOOL)pollFrame:(std::unique_ptr<webrtc::DesktopFrame>*)outFrame
87
status:(livekit_ffi::SckCaptureStatus*)outStatus;
88
- (void)stop;
89
@end
90
91
@implementation LiveKitMacWindowSession {
92
BOOL _stopped;
93
BOOL _pickerCancelled;
94
BOOL _pickerFailed;
95
// Set when ScreenCaptureKit stops the running stream; kActive while running.
96
livekit_ffi::SckCaptureStatus _endStatus;
97
// The shared window is closed (macOS 15.2+). It may come back.
98
BOOL _windowClosed;
99
BOOL _includeCursor;
100
uint32_t _maxFps;
101
SCStream* _stream;
102
SCContentFilter* _filter;
103
size_t _configuredWidth;
104
size_t _configuredHeight;
105
IOSurfaceRef _latestSurface;
106
CGRect _latestCropRect;
107
dispatch_queue_t _captureQueue;
108
// Guarded by @synchronized(self): read on the main queue when presenting and
109
// cleared in stop.
110
SCContentSharingPicker* _picker;
111
SCContentSharingPickerConfiguration* _previousPickerConfig;
112
BOOL _savedPickerConfig;
113
// Serializes all updateContentFilter and updateConfiguration calls on _stream.
114
// replayd checks each updateConfiguration against the picked content; one sent
115
// before the picked filter is in place fails that check and falls back to the
116
// Screen Recording permission. At most one async update runs at a time, and a
117
// pending filter always runs before any configuration change (size or fps).
118
BOOL _streamOpInFlight;
119
BOOL _filterUpdateInFlight;
120
SCContentFilter* _pendingFilter;
121
BOOL _configDirty;
122
}
123
124
- (instancetype)initWithMaxFps:(uint32_t)maxFps includeCursor:(BOOL)includeCursor {
125
self = [super init];
126
if (self) {
127
_endStatus = livekit_ffi::SckCaptureStatus::kActive;
128
_maxFps = maxFps;
129
_includeCursor = includeCursor;
130
_captureQueue = dispatch_queue_create("org.rusty-teams.sck-window", DISPATCH_QUEUE_SERIAL);
131
}
132
return self;
133
}
134
135
- (void)dealloc {
136
if (_latestSurface != NULL) {
137
IOSurfaceDecrementUseCount(_latestSurface);
138
CFRelease(_latestSurface);
139
_latestSurface = NULL;
140
}
141
}
142
143
- (SCStreamConfiguration*)buildConfigWithWidth:(size_t)width
144
height:(size_t)height
145
maxFps:(uint32_t)maxFps
146
includeCursor:(BOOL)includeCursor {
147
SCStreamConfiguration* config = [[SCStreamConfiguration alloc] init];
148
config.pixelFormat = kCVPixelFormatType_32BGRA;
149
config.colorSpaceName = kCGColorSpaceSRGB;
150
config.showsCursor = includeCursor;
151
config.captureResolution = SCCaptureResolutionBest;
152
config.width = width < kMinCaptureDimension ? kMinCaptureDimension : width;
153
config.height = height < kMinCaptureDimension ? kMinCaptureDimension : height;
154
config.minimumFrameInterval =
155
maxFps > 0 ? CMTimeMake(1, static_cast<int32_t>(maxFps)) : kCMTimeZero;
156
return config;
157
}
158
159
// `picker` comes from a webrtc::SckPickerHandle, which owns its `active` and
160
// `maximumStreamCount` properties. They are shared with WebRTC's own SCK
161
// capturer, so this session must not change them.
162
- (void)startPickerWithPicker:(SCContentSharingPicker*)picker {
163
@synchronized(self) {
164
if (_stopped) {
165
return;
166
}
167
_picker = picker;
168
_previousPickerConfig = [picker.defaultConfiguration copy];
169
_savedPickerConfig = YES;
170
}
171
[picker addObserver:self];
172
SCContentSharingPickerConfiguration* config = [[SCContentSharingPickerConfiguration alloc] init];
173
config.allowedPickerModes = SCContentSharingPickerModeSingleWindow;
174
config.allowsChangingSelectedContent = YES;
175
picker.defaultConfiguration = config;
176
177
// ScreenCaptureKit presents the picker on the main queue. Async avoids
178
// deadlocking if the main thread stops the capture and joins portal-share.
179
__weak LiveKitMacWindowSession* weakSelf = self;
180
dispatch_async(dispatch_get_main_queue(), ^{
181
LiveKitMacWindowSession* strongSelf = weakSelf;
182
if (strongSelf == nil) {
183
return;
184
}
185
SCContentSharingPicker* activePicker = nil;
186
@synchronized(strongSelf) {
187
if (strongSelf->_stopped) {
188
return;
189
}
190
activePicker = strongSelf->_picker;
191
}
192
if (activePicker != nil) {
193
[activePicker presentPickerUsingContentStyle:SCShareableContentStyleWindow];
194
}
195
});
196
}
197
198
- (void)drainStreamUpdates {
199
[self runNextStreamUpdateCompletingOp:NO wasFilter:NO forStream:nil filterError:nil];
200
}
201
202
// Transitions directly from a completing async SCStream op to the next queued
203
// update under one @synchronized(self) acquisition, so no resize frame can slip
204
// in between a picked filter update and its matching configuration update.
205
- (void)runNextStreamUpdateCompletingOp:(BOOL)completingOp
206
wasFilter:(BOOL)wasFilter
207
forStream:(nullable SCStream*)completedStream
208
filterError:(nullable NSError*)filterError {
209
SCStream* stream = nil;
210
SCContentFilter* filterToApply = nil;
211
SCStreamConfiguration* configToApply = nil;
212
213
@synchronized(self) {
214
if (completingOp) {
215
_streamOpInFlight = NO;
216
if (wasFilter) {
217
_filterUpdateInFlight = NO;
218
}
219
if (_stopped || _pickerFailed || completedStream == nil || _stream != completedStream) {
220
return;
221
}
222
if (wasFilter && filterError != nil) {
223
_pickerFailed = YES;
224
_pendingFilter = nil;
225
_configDirty = NO;
226
return;
227
}
228
} else if (_stopped || _pickerFailed || _stream == nil || _streamOpInFlight) {
229
return;
230
}
231
232
stream = _stream;
233
if (_pendingFilter != nil) {
234
filterToApply = _pendingFilter;
235
_pendingFilter = nil;
236
_streamOpInFlight = YES;
237
_filterUpdateInFlight = YES;
238
} else if (_configDirty && _configuredWidth >= kMinCaptureDimension &&
239
_configuredHeight >= kMinCaptureDimension) {
240
_configDirty = NO;
241
configToApply = [self buildConfigWithWidth:_configuredWidth
242
height:_configuredHeight
243
maxFps:_maxFps
244
includeCursor:_includeCursor];
245
_streamOpInFlight = YES;
246
} else {
247
return;
248
}
249
}
250
251
// Weak: the stream keeps this handler until the update completes.
252
__weak LiveKitMacWindowSession* weakSelf = self;
253
__weak SCStream* weakStream = stream;
254
if (filterToApply != nil) {
255
[stream updateContentFilter:filterToApply
256
completionHandler:^(NSError* _Nullable error) {
257
LiveKitMacWindowSession* strongSelf = weakSelf;
258
if (strongSelf == nil) {
259
return;
260
}
261
[strongSelf runNextStreamUpdateCompletingOp:YES
262
wasFilter:YES
263
forStream:weakStream
264
filterError:error];
265
}];
266
return;
267
}
268
269
[stream updateConfiguration:configToApply
270
completionHandler:^(NSError* _Nullable configError) {
271
(void)configError;
272
LiveKitMacWindowSession* strongSelf = weakSelf;
273
if (strongSelf == nil) {
274
return;
275
}
276
[strongSelf runNextStreamUpdateCompletingOp:YES
277
wasFilter:NO
278
forStream:weakStream
279
filterError:nil];
280
}];
281
}
282
283
- (void)setMaxFps:(uint32_t)maxFps {
284
BOOL shouldDrain = NO;
285
@synchronized(self) {
286
if (_stopped || _pickerFailed || _maxFps == maxFps) {
287
return;
288
}
289
_maxFps = maxFps;
290
if (_stream != nil && _configuredWidth >= kMinCaptureDimension &&
291
_configuredHeight >= kMinCaptureDimension) {
292
_configDirty = YES;
293
shouldDrain = !_streamOpInFlight;
294
}
295
}
296
if (shouldDrain) {
297
[self drainStreamUpdates];
298
}
299
}
300
301
- (BOOL)pollFrame:(std::unique_ptr<webrtc::DesktopFrame>*)outFrame
302
status:(livekit_ffi::SckCaptureStatus*)outStatus {
303
*outFrame = nullptr;
304
*outStatus = livekit_ffi::SckCaptureStatus::kActive;
305
306
IOSurfaceRef surface = NULL;
307
CGRect crop = CGRectZero;
308
@synchronized(self) {
309
if (_stopped) {
310
*outStatus = livekit_ffi::SckCaptureStatus::kPickerCancelled;
311
return NO;
312
}
313
if (_pickerFailed) {
314
*outStatus = livekit_ffi::SckCaptureStatus::kStartFailed;
315
return NO;
316
}
317
if (_pickerCancelled) {
318
*outStatus = livekit_ffi::SckCaptureStatus::kPickerCancelled;
319
return NO;
320
}
321
if (_endStatus != livekit_ffi::SckCaptureStatus::kActive) {
322
*outStatus = _endStatus;
323
return NO;
324
}
325
if (_windowClosed) {
326
*outStatus = livekit_ffi::SckCaptureStatus::kWindowGone;
327
return NO;
328
}
329
if (_latestSurface == NULL) {
330
*outStatus = livekit_ffi::SckCaptureStatus::kActive;
331
return NO;
332
}
333
surface = _latestSurface;
334
crop = _latestCropRect;
335
CFRetain(surface);
336
IOSurfaceIncrementUseCount(surface);
337
}
338
339
BOOL captured = NO;
340
if (IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL) == kIOReturnSuccess) {
341
const uint8_t* base = static_cast<const uint8_t*>(IOSurfaceGetBaseAddress(surface));
342
size_t surfW = IOSurfaceGetWidth(surface);
343
size_t surfH = IOSurfaceGetHeight(surface);
344
size_t stride = IOSurfaceGetBytesPerRow(surface);
345
size_t bpp = IOSurfaceGetBytesPerElement(surface);
346
if (base != NULL && bpp == 4 && surfW >= kMinCaptureDimension &&
347
surfH >= kMinCaptureDimension && stride >= surfW * 4) {
348
size_t x = 0;
349
size_t y = 0;
350
size_t w = surfW;
351
size_t h = surfH;
352
if (!CGRectIsEmpty(crop)) {
353
size_t cx = static_cast<size_t>(crop.origin.x);
354
size_t cy = static_cast<size_t>(crop.origin.y);
355
size_t cw = static_cast<size_t>(crop.size.width);
356
size_t ch = static_cast<size_t>(crop.size.height);
357
if (cx < surfW && cy < surfH && cw >= kMinCaptureDimension && ch >= kMinCaptureDimension &&
358
cx + cw <= surfW && cy + ch <= surfH) {
359
x = cx;
360
y = cy;
361
w = cw;
362
h = ch;
363
}
364
}
365
size_t offset = y * stride + x * 4;
366
size_t totalBytes = surfH * stride;
367
if (offset < totalBytes) {
368
size_t availableBytes = totalBytes - offset;
369
size_t rowBytes = w * 4;
370
size_t minNeeded = (h - 1) * stride + rowBytes;
371
if (w <= INT_MAX && h <= INT_MAX && stride <= INT_MAX && availableBytes >= minNeeded) {
372
auto frame = std::make_unique<webrtc::BasicDesktopFrame>(
373
webrtc::DesktopSize(static_cast<int>(w), static_cast<int>(h)));
374
frame->CopyPixelsFrom(
375
base + offset,
376
static_cast<int>(stride),
377
webrtc::DesktopRect::MakeWH(static_cast<int>(w), static_cast<int>(h)));
378
frame->set_may_contain_cursor(_includeCursor ? true : false);
379
*outFrame = std::move(frame);
380
captured = YES;
381
}
382
}
383
}
384
IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL);
385
}
386
387
IOSurfaceDecrementUseCount(surface);
388
CFRelease(surface);
389
return captured;
390
}
391
392
- (void)stop {
393
SCStream* streamToStop = nil;
394
SCContentSharingPicker* picker = nil;
395
SCContentSharingPickerConfiguration* previousConfig = nil;
396
BOOL restoreConfig = NO;
397
IOSurfaceRef surfaceToRelease = NULL;
398
@synchronized(self) {
399
if (_stopped) {
400
return;
401
}
402
_stopped = YES;
403
streamToStop = _stream;
404
_stream = nil;
405
_filter = nil;
406
_pendingFilter = nil;
407
_configDirty = NO;
408
picker = _picker;
409
_picker = nil;
410
previousConfig = _previousPickerConfig;
411
_previousPickerConfig = nil;
412
restoreConfig = _savedPickerConfig;
413
_savedPickerConfig = NO;
414
surfaceToRelease = _latestSurface;
415
_latestSurface = NULL;
416
}
417
418
if (picker != nil) {
419
[picker removeObserver:self];
420
if (restoreConfig) {
421
picker.defaultConfiguration = previousConfig != nil ?
422
previousConfig :
423
[[SCContentSharingPickerConfiguration alloc] init];
424
}
425
}
426
if (streamToStop != nil) {
427
[streamToStop removeStreamOutput:self type:SCStreamOutputTypeScreen error:nil];
428
[streamToStop stopCaptureWithCompletionHandler:nil];
429
}
430
431
if (surfaceToRelease != NULL) {
432
IOSurfaceDecrementUseCount(surfaceToRelease);
433
CFRelease(surfaceToRelease);
434
}
435
}
436
437
- (void)maybeReconfigureWidth:(size_t)desiredW height:(size_t)desiredH {
438
BOOL shouldDrain = NO;
439
@synchronized(self) {
440
// Do not overwrite dimensions or send a configuration update while a newly
441
// picked filter is waiting or in flight; its completion applies the new
442
// window's size and later frames resize from there.
443
if (_stopped || _pickerFailed || _stream == nil || _pendingFilter != nil ||
444
_filterUpdateInFlight) {
445
return;
446
}
447
long dw = static_cast<long>(desiredW) - static_cast<long>(_configuredWidth);
448
long dh = static_cast<long>(desiredH) - static_cast<long>(_configuredHeight);
449
if (std::labs(dw) < 2 && std::labs(dh) < 2) {
450
return;
451
}
452
_configuredWidth = desiredW;
453
_configuredHeight = desiredH;
454
_configDirty = YES;
455
shouldDrain = !_streamOpInFlight;
456
}
457
if (shouldDrain) {
458
[self drainStreamUpdates];
459
}
460
}
461
462
- (void)contentSharingPicker:(SCContentSharingPicker*)picker
463
didUpdateWithFilter:(SCContentFilter*)filter
464
forStream:(nullable SCStream*)stream {
465
(void)picker;
466
BOOL updateExisting = NO;
467
SCStream* newStream = nil;
468
SCStreamConfiguration* config = nil;
469
dispatch_queue_t queue = nil;
470
471
@synchronized(self) {
472
if (_stopped || _pickerFailed) {
473
return;
474
}
475
if (stream != nil && stream != _stream) {
476
return;
477
}
478
479
CGRect contentRect = filter.contentRect;
480
double scale = filter.pointPixelScale > 0.0f ? filter.pointPixelScale : 1.0;
481
size_t width = clamp_dimension(contentRect.size.width * scale);
482
size_t height = clamp_dimension(contentRect.size.height * scale);
483
484
_filter = filter;
485
_windowClosed = NO;
486
_configuredWidth = width;
487
_configuredHeight = height;
488
489
if (_stream != nil) {
490
_pendingFilter = filter;
491
_configDirty = YES;
492
updateExisting = YES;
493
} else {
494
config = [self buildConfigWithWidth:width
495
height:height
496
maxFps:_maxFps
497
includeCursor:_includeCursor];
498
newStream = [[SCStream alloc] initWithFilter:filter configuration:config delegate:self];
499
_stream = newStream;
500
queue = _captureQueue;
501
}
502
}
503
504
if (updateExisting) {
505
[self drainStreamUpdates];
506
return;
507
}
508
509
if (newStream == nil) {
510
@synchronized(self) {
511
_pickerFailed = YES;
512
}
513
return;
514
}
515
516
// Rely on `picker.defaultConfiguration` rather than calling
517
// `[picker setConfiguration:forStream:]`: mutating the per-stream picker
518
// configuration dispatches an async `updateStream:withContentFilter:` IPC
519
// whose filter no longer matches the picker-authorized filter in `replayd`,
520
// causing `verifyContentPickerFilter:` to fail and trigger spurious Screen
521
// Recording TCC prompts on macOS 27.
522
523
NSError* error = nil;
524
BOOL added = [newStream addStreamOutput:self
525
type:SCStreamOutputTypeScreen
526
sampleHandlerQueue:queue
527
error:&error];
528
if (!added || error != nil) {
529
@synchronized(self) {
530
_pickerFailed = YES;
531
}
532
return;
533
}
534
535
__weak LiveKitMacWindowSession* weakSelf = self;
536
[newStream startCaptureWithCompletionHandler:^(NSError* _Nullable startError) {
537
if (startError == nil) {
538
return;
539
}
540
LiveKitMacWindowSession* strongSelf = weakSelf;
541
if (strongSelf == nil) {
542
return;
543
}
544
// A capture that never starts is a failure to report, not a cancel.
545
@synchronized(strongSelf) {
546
strongSelf->_pickerFailed = YES;
547
}
548
}];
549
}
550
551
- (void)contentSharingPicker:(SCContentSharingPicker*)picker
552
didCancelForStream:(nullable SCStream*)stream {
553
(void)picker;
554
@synchronized(self) {
555
if (_stopped || _pickerFailed) {
556
return;
557
}
558
// Only treat cancelling the initial picker as cancellation; cancelling a
559
// mid-share "Change Window" sheet keeps the active capture running.
560
if (stream == nil && _stream == nil) {
561
_pickerCancelled = YES;
562
}
563
}
564
}
565
566
- (void)contentSharingPickerStartDidFailWithError:(NSError*)error {
567
(void)error;
568
@synchronized(self) {
569
if (!_stopped && _stream == nil) {
570
_pickerFailed = YES;
571
}
572
}
573
}
574
575
- (void)stream:(SCStream*)stream
576
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
577
ofType:(SCStreamOutputType)type {
578
(void)stream;
579
if (type != SCStreamOutputTypeScreen) {
580
return;
581
}
582
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
583
if (imageBuffer == NULL) {
584
return;
585
}
586
IOSurfaceRef ioSurface = CVPixelBufferGetIOSurface(imageBuffer);
587
if (ioSurface == NULL) {
588
return;
589
}
590
CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, false);
591
if (attachments == NULL || CFArrayGetCount(attachments) == 0) {
592
return;
593
}
594
NSDictionary* dict = (__bridge NSDictionary*)CFArrayGetValueAtIndex(attachments, 0);
595
if (dict == nil) {
596
return;
597
}
598
599
NSNumber* statusNum = dict[SCStreamFrameInfoStatus];
600
if (statusNum == nil) {
601
return;
602
}
603
NSInteger status = [statusNum integerValue];
604
if (status != SCFrameStatusComplete && status != SCFrameStatusStarted) {
605
return;
606
}
607
608
double scaleFactor = 1.0;
609
NSNumber* scaleNum = dict[SCStreamFrameInfoScaleFactor];
610
if (scaleNum != nil && [scaleNum doubleValue] > 0.0) {
611
scaleFactor = [scaleNum doubleValue];
612
}
613
614
double contentScale = 1.0;
615
NSNumber* contentScaleNum = dict[SCStreamFrameInfoContentScale];
616
if (contentScaleNum != nil && [contentScaleNum doubleValue] > 0.0) {
617
contentScale = [contentScaleNum doubleValue];
618
}
619
620
CGRect contentRect = CGRectZero;
621
id rectObj = dict[SCStreamFrameInfoContentRect];
622
if (rectObj != nil) {
623
if (!CGRectMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)rectObj, &contentRect)) {
624
contentRect = CGRectZero;
625
}
626
}
627
628
size_t surfW = IOSurfaceGetWidth(ioSurface);
629
size_t surfH = IOSurfaceGetHeight(ioSurface);
630
CGRect cropRect = CGRectZero;
631
if (!CGRectIsEmpty(contentRect) && surfW >= kMinCaptureDimension &&
632
surfH >= kMinCaptureDimension) {
633
double rx = std::floor(contentRect.origin.x * scaleFactor);
634
double ry = std::floor(contentRect.origin.y * scaleFactor);
635
double rw = static_cast<double>(std::llround(contentRect.size.width * scaleFactor));
636
double rh = static_cast<double>(std::llround(contentRect.size.height * scaleFactor));
637
rx = clamp_double(rx, 0.0, static_cast<double>(surfW));
638
ry = clamp_double(ry, 0.0, static_cast<double>(surfH));
639
rw = clamp_double(rw, 0.0, static_cast<double>(surfW) - rx);
640
rh = clamp_double(rh, 0.0, static_cast<double>(surfH) - ry);
641
if (rw >= static_cast<double>(kMinCaptureDimension) &&
642
rh >= static_cast<double>(kMinCaptureDimension)) {
643
cropRect = CGRectMake(rx, ry, rw, rh);
644
}
645
}
646
647
if (!CGRectIsEmpty(contentRect)) {
648
size_t desiredW = clamp_dimension((contentRect.size.width / contentScale) * scaleFactor);
649
size_t desiredH = clamp_dimension((contentRect.size.height / contentScale) * scaleFactor);
650
[self maybeReconfigureWidth:desiredW height:desiredH];
651
}
652
653
IOSurfaceRef oldSurface = NULL;
654
@synchronized(self) {
655
if (_stopped || _pickerFailed) {
656
return;
657
}
658
CFRetain(ioSurface);
659
IOSurfaceIncrementUseCount(ioSurface);
660
oldSurface = _latestSurface;
661
_latestSurface = ioSurface;
662
_latestCropRect = cropRect;
663
}
664
665
if (oldSurface != NULL) {
666
IOSurfaceDecrementUseCount(oldSurface);
667
CFRelease(oldSurface);
668
}
669
}
670
671
// Stopping from the menu bar arrives as SCStreamErrorUserStopped.
672
- (void)stream:(SCStream*)stream didStopWithError:(NSError*)error {
673
@synchronized(self) {
674
if (!_stopped && stream == _stream && _endStatus == livekit_ffi::SckCaptureStatus::kActive) {
675
_endStatus = status_for_stop_error(error);
676
}
677
}
678
}
679
680
// macOS 15.2+: every shared window was closed. The stream keeps running and
681
// would otherwise repeat the last frame.
682
- (void)streamDidBecomeInactive:(SCStream*)stream {
683
@synchronized(self) {
684
if (!_stopped && stream == _stream) {
685
_windowClosed = YES;
686
}
687
}
688
}
689
690
- (void)streamDidBecomeActive:(SCStream*)stream {
691
@synchronized(self) {
692
if (stream == _stream) {
693
_windowClosed = NO;
694
}
695
}
696
}
697
698
@end
699
700
namespace livekit_ffi {
701
702
namespace {
703
704
class SckWindowCapturerImpl final : public SckWindowCapturer {
705
public:
706
explicit SckWindowCapturerImpl(const webrtc::DesktopCaptureOptions& options)
707
: include_cursor_(options.prefer_cursor_embedded()) {}
708
709
~SckWindowCapturerImpl() override {
710
@autoreleasepool {
711
if (session_ != nil) {
712
[session_ stop];
713
session_ = nil;
714
}
715
// After the session has stopped its stream and left the picker: the
716
// last handle released deactivates the shared picker.
717
picker_handle_.reset();
718
}
719
}
720
721
void Start(Callback* callback) override {
722
callback_ = callback;
723
@autoreleasepool {
724
if (session_ != nil) {
725
[session_ stop];
726
session_ = nil;
727
}
728
// Like WebRTC's ScreenCapturerSck, keep one handle for the capturer's
729
// lifetime; each session runs at most one stream at a time.
730
if (!picker_handle_) {
731
picker_handle_ = webrtc::CreateSckPickerHandle();
732
}
733
if (!picker_handle_) {
734
// The shared picker reached its stream limit. With no session,
735
// CaptureFrame() reports kStartFailed.
736
return;
737
}
738
session_ = [[LiveKitMacWindowSession alloc] initWithMaxFps:max_fps_
739
includeCursor:include_cursor_ ? YES : NO];
740
[session_ startPickerWithPicker:picker_handle_->GetPicker()];
741
}
742
}
743
744
void SetMaxFrameRate(uint32_t max_frame_rate) override {
745
max_fps_ = max_frame_rate;
746
@autoreleasepool {
747
if (session_ != nil) {
748
[session_ setMaxFps:max_fps_];
749
}
750
}
751
}
752
753
void CaptureFrame() override {
754
if (!callback_) {
755
return;
756
}
757
@autoreleasepool {
758
if (session_ == nil) {
759
last_status_ = SckCaptureStatus::kStartFailed;
760
callback_->OnCaptureResult(Result::ERROR_PERMANENT, nullptr);
761
return;
762
}
763
std::unique_ptr<webrtc::DesktopFrame> frame;
764
SckCaptureStatus status = SckCaptureStatus::kActive;
765
if ([session_ pollFrame:&frame status:&status] && frame) {
766
last_status_ = SckCaptureStatus::kActive;
767
callback_->OnCaptureResult(Result::SUCCESS, std::move(frame));
768
return;
769
}
770
last_status_ = status;
771
if (status == SckCaptureStatus::kActive || status == SckCaptureStatus::kWindowGone) {
772
callback_->OnCaptureResult(Result::ERROR_TEMPORARY, nullptr);
773
} else {
774
callback_->OnCaptureResult(Result::ERROR_PERMANENT, nullptr);
775
}
776
}
777
}
778
779
bool GetSourceList(SourceList* sources) override {
780
if (sources) {
781
sources->clear();
782
}
783
return true;
784
}
785
786
bool SelectSource(SourceId /*id*/) override { return true; }
787
788
SckCaptureStatus last_status() const override { return last_status_; }
789
790
private:
791
bool include_cursor_ = true;
792
uint32_t max_fps_ = kDefaultMaxFps;
793
Callback* callback_ = nullptr;
794
SckCaptureStatus last_status_ = SckCaptureStatus::kActive;
795
// Created and released on the capturer thread, as SckPickerHandle requires.
796
std::unique_ptr<webrtc::SckPickerHandleInterface> picker_handle_;
797
LiveKitMacWindowSession* session_ = nil;
798
};
799
800
} // namespace
801
802
std::unique_ptr<SckWindowCapturer> CreateSckWindowCapturer(
803
const webrtc::DesktopCaptureOptions& options) {
804
return std::make_unique<SckWindowCapturerImpl>(options);
805
}
806
807
} // namespace livekit_ffi
808
809
#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
@@ -0,0 +1,809 @@1
/*2
* Copyright 2025 LiveKit, Inc.3
*4
* Licensed under the Apache License, Version 2.0 (the "License");5
* you may not use this file except in compliance with the License.6
* You may obtain a copy of the License at7
*8
* http://www.apache.org/licenses/LICENSE-2.09
*10
* Unless required by applicable law or agreed to in writing, software11
* distributed under the License is distributed on an "AS IS" BASIS,12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13
* See the License for the specific language governing permissions and14
* limitations under the License.15
*/16
17
#include "livekit/sck_window_capturer.h"18
19
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)20
21
#import <CoreGraphics/CoreGraphics.h>22
#import <CoreMedia/CoreMedia.h>23
#import <CoreVideo/CoreVideo.h>24
#import <Foundation/Foundation.h>25
#import <IOSurface/IOSurface.h>26
#import <ScreenCaptureKit/ScreenCaptureKit.h>27
#import <dispatch/dispatch.h>28
29
#include <climits>30
#include <cmath>31
#include <cstddef>32
#include <cstdint>33
#include <cstdlib>34
#include <memory>35
#include <utility>36
37
#include "modules/desktop_capture/desktop_frame.h"38
#include "modules/desktop_capture/desktop_geometry.h"39
#include "modules/desktop_capture/mac/sck_picker_handle.h"40
41
namespace {42
43
constexpr size_t kMinCaptureDimension = 2;44
constexpr size_t kMaxCaptureDimension = 16384;45
constexpr uint32_t kDefaultMaxFps = 30;46
47
livekit_ffi::SckCaptureStatus status_for_stop_error(NSError* error) {48
if ([error.domain isEqualToString:SCStreamErrorDomain]) {49
if (error.code == SCStreamErrorUserStopped) {50
return livekit_ffi::SckCaptureStatus::kStoppedByUser;51
}52
if (error.code == SCStreamErrorNoCaptureSource) {53
return livekit_ffi::SckCaptureStatus::kWindowGone;54
}55
}56
return livekit_ffi::SckCaptureStatus::kInterrupted;57
}58
59
size_t clamp_dimension(double pixels) {60
if (!std::isfinite(pixels) || pixels < static_cast<double>(kMinCaptureDimension)) {61
return kMinCaptureDimension;62
}63
if (pixels > static_cast<double>(kMaxCaptureDimension)) {64
return kMaxCaptureDimension;65
}66
return static_cast<size_t>(std::llround(pixels));67
}68
69
double clamp_double(double value, double lo, double hi) {70
if (value < lo) {71
return lo;72
}73
if (value > hi) {74
return hi;75
}76
return value;77
}78
79
} // namespace80
81
@interface LiveKitMacWindowSession82
: NSObject <SCStreamDelegate, SCStreamOutput, SCContentSharingPickerObserver>83
- (instancetype)initWithMaxFps:(uint32_t)maxFps includeCursor:(BOOL)includeCursor;84
- (void)startPickerWithPicker:(SCContentSharingPicker*)picker;85
- (void)setMaxFps:(uint32_t)maxFps;86
- (BOOL)pollFrame:(std::unique_ptr<webrtc::DesktopFrame>*)outFrame87
status:(livekit_ffi::SckCaptureStatus*)outStatus;88
- (void)stop;89
@end90
91
@implementation LiveKitMacWindowSession {92
BOOL _stopped;93
BOOL _pickerCancelled;94
BOOL _pickerFailed;95
// Set when ScreenCaptureKit stops the running stream; kActive while running.96
livekit_ffi::SckCaptureStatus _endStatus;97
// The shared window is closed (macOS 15.2+). It may come back.98
BOOL _windowClosed;99
BOOL _includeCursor;100
uint32_t _maxFps;101
SCStream* _stream;102
SCContentFilter* _filter;103
size_t _configuredWidth;104
size_t _configuredHeight;105
IOSurfaceRef _latestSurface;106
CGRect _latestCropRect;107
dispatch_queue_t _captureQueue;108
// Guarded by @synchronized(self): read on the main queue when presenting and109
// cleared in stop.110
SCContentSharingPicker* _picker;111
SCContentSharingPickerConfiguration* _previousPickerConfig;112
BOOL _savedPickerConfig;113
// Serializes all updateContentFilter and updateConfiguration calls on _stream.114
// replayd checks each updateConfiguration against the picked content; one sent115
// before the picked filter is in place fails that check and falls back to the116
// Screen Recording permission. At most one async update runs at a time, and a117
// pending filter always runs before any configuration change (size or fps).118
BOOL _streamOpInFlight;119
BOOL _filterUpdateInFlight;120
SCContentFilter* _pendingFilter;121
BOOL _configDirty;122
}123
124
- (instancetype)initWithMaxFps:(uint32_t)maxFps includeCursor:(BOOL)includeCursor {125
self = [super init];126
if (self) {127
_endStatus = livekit_ffi::SckCaptureStatus::kActive;128
_maxFps = maxFps;129
_includeCursor = includeCursor;130
_captureQueue = dispatch_queue_create("org.rusty-teams.sck-window", DISPATCH_QUEUE_SERIAL);131
}132
return self;133
}134
135
- (void)dealloc {136
if (_latestSurface != NULL) {137
IOSurfaceDecrementUseCount(_latestSurface);138
CFRelease(_latestSurface);139
_latestSurface = NULL;140
}141
}142
143
- (SCStreamConfiguration*)buildConfigWithWidth:(size_t)width144
height:(size_t)height145
maxFps:(uint32_t)maxFps146
includeCursor:(BOOL)includeCursor {147
SCStreamConfiguration* config = [[SCStreamConfiguration alloc] init];148
config.pixelFormat = kCVPixelFormatType_32BGRA;149
config.colorSpaceName = kCGColorSpaceSRGB;150
config.showsCursor = includeCursor;151
config.captureResolution = SCCaptureResolutionBest;152
config.width = width < kMinCaptureDimension ? kMinCaptureDimension : width;153
config.height = height < kMinCaptureDimension ? kMinCaptureDimension : height;154
config.minimumFrameInterval =155
maxFps > 0 ? CMTimeMake(1, static_cast<int32_t>(maxFps)) : kCMTimeZero;156
return config;157
}158
159
// `picker` comes from a webrtc::SckPickerHandle, which owns its `active` and160
// `maximumStreamCount` properties. They are shared with WebRTC's own SCK161
// capturer, so this session must not change them.162
- (void)startPickerWithPicker:(SCContentSharingPicker*)picker {163
@synchronized(self) {164
if (_stopped) {165
return;166
}167
_picker = picker;168
_previousPickerConfig = [picker.defaultConfiguration copy];169
_savedPickerConfig = YES;170
}171
[picker addObserver:self];172
SCContentSharingPickerConfiguration* config = [[SCContentSharingPickerConfiguration alloc] init];173
config.allowedPickerModes = SCContentSharingPickerModeSingleWindow;174
config.allowsChangingSelectedContent = YES;175
picker.defaultConfiguration = config;176
177
// ScreenCaptureKit presents the picker on the main queue. Async avoids178
// deadlocking if the main thread stops the capture and joins portal-share.179
__weak LiveKitMacWindowSession* weakSelf = self;180
dispatch_async(dispatch_get_main_queue(), ^{181
LiveKitMacWindowSession* strongSelf = weakSelf;182
if (strongSelf == nil) {183
return;184
}185
SCContentSharingPicker* activePicker = nil;186
@synchronized(strongSelf) {187
if (strongSelf->_stopped) {188
return;189
}190
activePicker = strongSelf->_picker;191
}192
if (activePicker != nil) {193
[activePicker presentPickerUsingContentStyle:SCShareableContentStyleWindow];194
}195
});196
}197
198
- (void)drainStreamUpdates {199
[self runNextStreamUpdateCompletingOp:NO wasFilter:NO forStream:nil filterError:nil];200
}201
202
// Transitions directly from a completing async SCStream op to the next queued203
// update under one @synchronized(self) acquisition, so no resize frame can slip204
// in between a picked filter update and its matching configuration update.205
- (void)runNextStreamUpdateCompletingOp:(BOOL)completingOp206
wasFilter:(BOOL)wasFilter207
forStream:(nullable SCStream*)completedStream208
filterError:(nullable NSError*)filterError {209
SCStream* stream = nil;210
SCContentFilter* filterToApply = nil;211
SCStreamConfiguration* configToApply = nil;212
213
@synchronized(self) {214
if (completingOp) {215
_streamOpInFlight = NO;216
if (wasFilter) {217
_filterUpdateInFlight = NO;218
}219
if (_stopped || _pickerFailed || completedStream == nil || _stream != completedStream) {220
return;221
}222
if (wasFilter && filterError != nil) {223
_pickerFailed = YES;224
_pendingFilter = nil;225
_configDirty = NO;226
return;227
}228
} else if (_stopped || _pickerFailed || _stream == nil || _streamOpInFlight) {229
return;230
}231
232
stream = _stream;233
if (_pendingFilter != nil) {234
filterToApply = _pendingFilter;235
_pendingFilter = nil;236
_streamOpInFlight = YES;237
_filterUpdateInFlight = YES;238
} else if (_configDirty && _configuredWidth >= kMinCaptureDimension &&239
_configuredHeight >= kMinCaptureDimension) {240
_configDirty = NO;241
configToApply = [self buildConfigWithWidth:_configuredWidth242
height:_configuredHeight243
maxFps:_maxFps244
includeCursor:_includeCursor];245
_streamOpInFlight = YES;246
} else {247
return;248
}249
}250
251
// Weak: the stream keeps this handler until the update completes.252
__weak LiveKitMacWindowSession* weakSelf = self;253
__weak SCStream* weakStream = stream;254
if (filterToApply != nil) {255
[stream updateContentFilter:filterToApply256
completionHandler:^(NSError* _Nullable error) {257
LiveKitMacWindowSession* strongSelf = weakSelf;258
if (strongSelf == nil) {259
return;260
}261
[strongSelf runNextStreamUpdateCompletingOp:YES262
wasFilter:YES263
forStream:weakStream264
filterError:error];265
}];266
return;267
}268
269
[stream updateConfiguration:configToApply270
completionHandler:^(NSError* _Nullable configError) {271
(void)configError;272
LiveKitMacWindowSession* strongSelf = weakSelf;273
if (strongSelf == nil) {274
return;275
}276
[strongSelf runNextStreamUpdateCompletingOp:YES277
wasFilter:NO278
forStream:weakStream279
filterError:nil];280
}];281
}282
283
- (void)setMaxFps:(uint32_t)maxFps {284
BOOL shouldDrain = NO;285
@synchronized(self) {286
if (_stopped || _pickerFailed || _maxFps == maxFps) {287
return;288
}289
_maxFps = maxFps;290
if (_stream != nil && _configuredWidth >= kMinCaptureDimension &&291
_configuredHeight >= kMinCaptureDimension) {292
_configDirty = YES;293
shouldDrain = !_streamOpInFlight;294
}295
}296
if (shouldDrain) {297
[self drainStreamUpdates];298
}299
}300
301
- (BOOL)pollFrame:(std::unique_ptr<webrtc::DesktopFrame>*)outFrame302
status:(livekit_ffi::SckCaptureStatus*)outStatus {303
*outFrame = nullptr;304
*outStatus = livekit_ffi::SckCaptureStatus::kActive;305
306
IOSurfaceRef surface = NULL;307
CGRect crop = CGRectZero;308
@synchronized(self) {309
if (_stopped) {310
*outStatus = livekit_ffi::SckCaptureStatus::kPickerCancelled;311
return NO;312
}313
if (_pickerFailed) {314
*outStatus = livekit_ffi::SckCaptureStatus::kStartFailed;315
return NO;316
}317
if (_pickerCancelled) {318
*outStatus = livekit_ffi::SckCaptureStatus::kPickerCancelled;319
return NO;320
}321
if (_endStatus != livekit_ffi::SckCaptureStatus::kActive) {322
*outStatus = _endStatus;323
return NO;324
}325
if (_windowClosed) {326
*outStatus = livekit_ffi::SckCaptureStatus::kWindowGone;327
return NO;328
}329
if (_latestSurface == NULL) {330
*outStatus = livekit_ffi::SckCaptureStatus::kActive;331
return NO;332
}333
surface = _latestSurface;334
crop = _latestCropRect;335
CFRetain(surface);336
IOSurfaceIncrementUseCount(surface);337
}338
339
BOOL captured = NO;340
if (IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL) == kIOReturnSuccess) {341
const uint8_t* base = static_cast<const uint8_t*>(IOSurfaceGetBaseAddress(surface));342
size_t surfW = IOSurfaceGetWidth(surface);343
size_t surfH = IOSurfaceGetHeight(surface);344
size_t stride = IOSurfaceGetBytesPerRow(surface);345
size_t bpp = IOSurfaceGetBytesPerElement(surface);346
if (base != NULL && bpp == 4 && surfW >= kMinCaptureDimension &&347
surfH >= kMinCaptureDimension && stride >= surfW * 4) {348
size_t x = 0;349
size_t y = 0;350
size_t w = surfW;351
size_t h = surfH;352
if (!CGRectIsEmpty(crop)) {353
size_t cx = static_cast<size_t>(crop.origin.x);354
size_t cy = static_cast<size_t>(crop.origin.y);355
size_t cw = static_cast<size_t>(crop.size.width);356
size_t ch = static_cast<size_t>(crop.size.height);357
if (cx < surfW && cy < surfH && cw >= kMinCaptureDimension && ch >= kMinCaptureDimension &&358
cx + cw <= surfW && cy + ch <= surfH) {359
x = cx;360
y = cy;361
w = cw;362
h = ch;363
}364
}365
size_t offset = y * stride + x * 4;366
size_t totalBytes = surfH * stride;367
if (offset < totalBytes) {368
size_t availableBytes = totalBytes - offset;369
size_t rowBytes = w * 4;370
size_t minNeeded = (h - 1) * stride + rowBytes;371
if (w <= INT_MAX && h <= INT_MAX && stride <= INT_MAX && availableBytes >= minNeeded) {372
auto frame = std::make_unique<webrtc::BasicDesktopFrame>(373
webrtc::DesktopSize(static_cast<int>(w), static_cast<int>(h)));374
frame->CopyPixelsFrom(375
base + offset,376
static_cast<int>(stride),377
webrtc::DesktopRect::MakeWH(static_cast<int>(w), static_cast<int>(h)));378
frame->set_may_contain_cursor(_includeCursor ? true : false);379
*outFrame = std::move(frame);380
captured = YES;381
}382
}383
}384
IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL);385
}386
387
IOSurfaceDecrementUseCount(surface);388
CFRelease(surface);389
return captured;390
}391
392
- (void)stop {393
SCStream* streamToStop = nil;394
SCContentSharingPicker* picker = nil;395
SCContentSharingPickerConfiguration* previousConfig = nil;396
BOOL restoreConfig = NO;397
IOSurfaceRef surfaceToRelease = NULL;398
@synchronized(self) {399
if (_stopped) {400
return;401
}402
_stopped = YES;403
streamToStop = _stream;404
_stream = nil;405
_filter = nil;406
_pendingFilter = nil;407
_configDirty = NO;408
picker = _picker;409
_picker = nil;410
previousConfig = _previousPickerConfig;411
_previousPickerConfig = nil;412
restoreConfig = _savedPickerConfig;413
_savedPickerConfig = NO;414
surfaceToRelease = _latestSurface;415
_latestSurface = NULL;416
}417
418
if (picker != nil) {419
[picker removeObserver:self];420
if (restoreConfig) {421
picker.defaultConfiguration = previousConfig != nil ?422
previousConfig :423
[[SCContentSharingPickerConfiguration alloc] init];424
}425
}426
if (streamToStop != nil) {427
[streamToStop removeStreamOutput:self type:SCStreamOutputTypeScreen error:nil];428
[streamToStop stopCaptureWithCompletionHandler:nil];429
}430
431
if (surfaceToRelease != NULL) {432
IOSurfaceDecrementUseCount(surfaceToRelease);433
CFRelease(surfaceToRelease);434
}435
}436
437
- (void)maybeReconfigureWidth:(size_t)desiredW height:(size_t)desiredH {438
BOOL shouldDrain = NO;439
@synchronized(self) {440
// Do not overwrite dimensions or send a configuration update while a newly441
// picked filter is waiting or in flight; its completion applies the new442
// window's size and later frames resize from there.443
if (_stopped || _pickerFailed || _stream == nil || _pendingFilter != nil ||444
_filterUpdateInFlight) {445
return;446
}447
long dw = static_cast<long>(desiredW) - static_cast<long>(_configuredWidth);448
long dh = static_cast<long>(desiredH) - static_cast<long>(_configuredHeight);449
if (std::labs(dw) < 2 && std::labs(dh) < 2) {450
return;451
}452
_configuredWidth = desiredW;453
_configuredHeight = desiredH;454
_configDirty = YES;455
shouldDrain = !_streamOpInFlight;456
}457
if (shouldDrain) {458
[self drainStreamUpdates];459
}460
}461
462
- (void)contentSharingPicker:(SCContentSharingPicker*)picker463
didUpdateWithFilter:(SCContentFilter*)filter464
forStream:(nullable SCStream*)stream {465
(void)picker;466
BOOL updateExisting = NO;467
SCStream* newStream = nil;468
SCStreamConfiguration* config = nil;469
dispatch_queue_t queue = nil;470
471
@synchronized(self) {472
if (_stopped || _pickerFailed) {473
return;474
}475
if (stream != nil && stream != _stream) {476
return;477
}478
479
CGRect contentRect = filter.contentRect;480
double scale = filter.pointPixelScale > 0.0f ? filter.pointPixelScale : 1.0;481
size_t width = clamp_dimension(contentRect.size.width * scale);482
size_t height = clamp_dimension(contentRect.size.height * scale);483
484
_filter = filter;485
_windowClosed = NO;486
_configuredWidth = width;487
_configuredHeight = height;488
489
if (_stream != nil) {490
_pendingFilter = filter;491
_configDirty = YES;492
updateExisting = YES;493
} else {494
config = [self buildConfigWithWidth:width495
height:height496
maxFps:_maxFps497
includeCursor:_includeCursor];498
newStream = [[SCStream alloc] initWithFilter:filter configuration:config delegate:self];499
_stream = newStream;500
queue = _captureQueue;501
}502
}503
504
if (updateExisting) {505
[self drainStreamUpdates];506
return;507
}508
509
if (newStream == nil) {510
@synchronized(self) {511
_pickerFailed = YES;512
}513
return;514
}515
516
// Rely on `picker.defaultConfiguration` rather than calling517
// `[picker setConfiguration:forStream:]`: mutating the per-stream picker518
// configuration dispatches an async `updateStream:withContentFilter:` IPC519
// whose filter no longer matches the picker-authorized filter in `replayd`,520
// causing `verifyContentPickerFilter:` to fail and trigger spurious Screen521
// Recording TCC prompts on macOS 27.522
523
NSError* error = nil;524
BOOL added = [newStream addStreamOutput:self525
type:SCStreamOutputTypeScreen526
sampleHandlerQueue:queue527
error:&error];528
if (!added || error != nil) {529
@synchronized(self) {530
_pickerFailed = YES;531
}532
return;533
}534
535
__weak LiveKitMacWindowSession* weakSelf = self;536
[newStream startCaptureWithCompletionHandler:^(NSError* _Nullable startError) {537
if (startError == nil) {538
return;539
}540
LiveKitMacWindowSession* strongSelf = weakSelf;541
if (strongSelf == nil) {542
return;543
}544
// A capture that never starts is a failure to report, not a cancel.545
@synchronized(strongSelf) {546
strongSelf->_pickerFailed = YES;547
}548
}];549
}550
551
- (void)contentSharingPicker:(SCContentSharingPicker*)picker552
didCancelForStream:(nullable SCStream*)stream {553
(void)picker;554
@synchronized(self) {555
if (_stopped || _pickerFailed) {556
return;557
}558
// Only treat cancelling the initial picker as cancellation; cancelling a559
// mid-share "Change Window" sheet keeps the active capture running.560
if (stream == nil && _stream == nil) {561
_pickerCancelled = YES;562
}563
}564
}565
566
- (void)contentSharingPickerStartDidFailWithError:(NSError*)error {567
(void)error;568
@synchronized(self) {569
if (!_stopped && _stream == nil) {570
_pickerFailed = YES;571
}572
}573
}574
575
- (void)stream:(SCStream*)stream576
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer577
ofType:(SCStreamOutputType)type {578
(void)stream;579
if (type != SCStreamOutputTypeScreen) {580
return;581
}582
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);583
if (imageBuffer == NULL) {584
return;585
}586
IOSurfaceRef ioSurface = CVPixelBufferGetIOSurface(imageBuffer);587
if (ioSurface == NULL) {588
return;589
}590
CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, false);591
if (attachments == NULL || CFArrayGetCount(attachments) == 0) {592
return;593
}594
NSDictionary* dict = (__bridge NSDictionary*)CFArrayGetValueAtIndex(attachments, 0);595
if (dict == nil) {596
return;597
}598
599
NSNumber* statusNum = dict[SCStreamFrameInfoStatus];600
if (statusNum == nil) {601
return;602
}603
NSInteger status = [statusNum integerValue];604
if (status != SCFrameStatusComplete && status != SCFrameStatusStarted) {605
return;606
}607
608
double scaleFactor = 1.0;609
NSNumber* scaleNum = dict[SCStreamFrameInfoScaleFactor];610
if (scaleNum != nil && [scaleNum doubleValue] > 0.0) {611
scaleFactor = [scaleNum doubleValue];612
}613
614
double contentScale = 1.0;615
NSNumber* contentScaleNum = dict[SCStreamFrameInfoContentScale];616
if (contentScaleNum != nil && [contentScaleNum doubleValue] > 0.0) {617
contentScale = [contentScaleNum doubleValue];618
}619
620
CGRect contentRect = CGRectZero;621
id rectObj = dict[SCStreamFrameInfoContentRect];622
if (rectObj != nil) {623
if (!CGRectMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)rectObj, &contentRect)) {624
contentRect = CGRectZero;625
}626
}627
628
size_t surfW = IOSurfaceGetWidth(ioSurface);629
size_t surfH = IOSurfaceGetHeight(ioSurface);630
CGRect cropRect = CGRectZero;631
if (!CGRectIsEmpty(contentRect) && surfW >= kMinCaptureDimension &&632
surfH >= kMinCaptureDimension) {633
double rx = std::floor(contentRect.origin.x * scaleFactor);634
double ry = std::floor(contentRect.origin.y * scaleFactor);635
double rw = static_cast<double>(std::llround(contentRect.size.width * scaleFactor));636
double rh = static_cast<double>(std::llround(contentRect.size.height * scaleFactor));637
rx = clamp_double(rx, 0.0, static_cast<double>(surfW));638
ry = clamp_double(ry, 0.0, static_cast<double>(surfH));639
rw = clamp_double(rw, 0.0, static_cast<double>(surfW) - rx);640
rh = clamp_double(rh, 0.0, static_cast<double>(surfH) - ry);641
if (rw >= static_cast<double>(kMinCaptureDimension) &&642
rh >= static_cast<double>(kMinCaptureDimension)) {643
cropRect = CGRectMake(rx, ry, rw, rh);644
}645
}646
647
if (!CGRectIsEmpty(contentRect)) {648
size_t desiredW = clamp_dimension((contentRect.size.width / contentScale) * scaleFactor);649
size_t desiredH = clamp_dimension((contentRect.size.height / contentScale) * scaleFactor);650
[self maybeReconfigureWidth:desiredW height:desiredH];651
}652
653
IOSurfaceRef oldSurface = NULL;654
@synchronized(self) {655
if (_stopped || _pickerFailed) {656
return;657
}658
CFRetain(ioSurface);659
IOSurfaceIncrementUseCount(ioSurface);660
oldSurface = _latestSurface;661
_latestSurface = ioSurface;662
_latestCropRect = cropRect;663
}664
665
if (oldSurface != NULL) {666
IOSurfaceDecrementUseCount(oldSurface);667
CFRelease(oldSurface);668
}669
}670
671
// Stopping from the menu bar arrives as SCStreamErrorUserStopped.672
- (void)stream:(SCStream*)stream didStopWithError:(NSError*)error {673
@synchronized(self) {674
if (!_stopped && stream == _stream && _endStatus == livekit_ffi::SckCaptureStatus::kActive) {675
_endStatus = status_for_stop_error(error);676
}677
}678
}679
680
// macOS 15.2+: every shared window was closed. The stream keeps running and681
// would otherwise repeat the last frame.682
- (void)streamDidBecomeInactive:(SCStream*)stream {683
@synchronized(self) {684
if (!_stopped && stream == _stream) {685
_windowClosed = YES;686
}687
}688
}689
690
- (void)streamDidBecomeActive:(SCStream*)stream {691
@synchronized(self) {692
if (stream == _stream) {693
_windowClosed = NO;694
}695
}696
}697
698
@end699
700
namespace livekit_ffi {701
702
namespace {703
704
class SckWindowCapturerImpl final : public SckWindowCapturer {705
public:706
explicit SckWindowCapturerImpl(const webrtc::DesktopCaptureOptions& options)707
: include_cursor_(options.prefer_cursor_embedded()) {}708
709
~SckWindowCapturerImpl() override {710
@autoreleasepool {711
if (session_ != nil) {712
[session_ stop];713
session_ = nil;714
}715
// After the session has stopped its stream and left the picker: the716
// last handle released deactivates the shared picker.717
picker_handle_.reset();718
}719
}720
721
void Start(Callback* callback) override {722
callback_ = callback;723
@autoreleasepool {724
if (session_ != nil) {725
[session_ stop];726
session_ = nil;727
}728
// Like WebRTC's ScreenCapturerSck, keep one handle for the capturer's729
// lifetime; each session runs at most one stream at a time.730
if (!picker_handle_) {731
picker_handle_ = webrtc::CreateSckPickerHandle();732
}733
if (!picker_handle_) {734
// The shared picker reached its stream limit. With no session,735
// CaptureFrame() reports kStartFailed.736
return;737
}738
session_ = [[LiveKitMacWindowSession alloc] initWithMaxFps:max_fps_739
includeCursor:include_cursor_ ? YES : NO];740
[session_ startPickerWithPicker:picker_handle_->GetPicker()];741
}742
}743
744
void SetMaxFrameRate(uint32_t max_frame_rate) override {745
max_fps_ = max_frame_rate;746
@autoreleasepool {747
if (session_ != nil) {748
[session_ setMaxFps:max_fps_];749
}750
}751
}752
753
void CaptureFrame() override {754
if (!callback_) {755
return;756
}757
@autoreleasepool {758
if (session_ == nil) {759
last_status_ = SckCaptureStatus::kStartFailed;760
callback_->OnCaptureResult(Result::ERROR_PERMANENT, nullptr);761
return;762
}763
std::unique_ptr<webrtc::DesktopFrame> frame;764
SckCaptureStatus status = SckCaptureStatus::kActive;765
if ([session_ pollFrame:&frame status:&status] && frame) {766
last_status_ = SckCaptureStatus::kActive;767
callback_->OnCaptureResult(Result::SUCCESS, std::move(frame));768
return;769
}770
last_status_ = status;771
if (status == SckCaptureStatus::kActive || status == SckCaptureStatus::kWindowGone) {772
callback_->OnCaptureResult(Result::ERROR_TEMPORARY, nullptr);773
} else {774
callback_->OnCaptureResult(Result::ERROR_PERMANENT, nullptr);775
}776
}777
}778
779
bool GetSourceList(SourceList* sources) override {780
if (sources) {781
sources->clear();782
}783
return true;784
}785
786
bool SelectSource(SourceId /*id*/) override { return true; }787
788
SckCaptureStatus last_status() const override { return last_status_; }789
790
private:791
bool include_cursor_ = true;792
uint32_t max_fps_ = kDefaultMaxFps;793
Callback* callback_ = nullptr;794
SckCaptureStatus last_status_ = SckCaptureStatus::kActive;795
// Created and released on the capturer thread, as SckPickerHandle requires.796
std::unique_ptr<webrtc::SckPickerHandleInterface> picker_handle_;797
LiveKitMacWindowSession* session_ = nil;798
};799
800
} // namespace801
802
std::unique_ptr<SckWindowCapturer> CreateSckWindowCapturer(803
const webrtc::DesktopCaptureOptions& options) {804
return std::make_unique<SckWindowCapturerImpl>(options);805
}806
807
} // namespace livekit_ffi808
809
#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)