scrcap 0.1.0-alpha.2

Screen and system-audio capture for Windows, macOS and Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicI32, Ordering},
    },
    thread::{self, JoinHandle},
    time::Duration,
};

use super::AtomicSize;
use super::delegate::{PickerObserver, StreamDelegate, VideoStreamOutput, ns_error};
use crate::{
    capture_desc::CaptureDescriptor,
    config::{CaptureConfig, Target},
    error::{CaptureError, Result, ScreenCaptureKitError, Unsupported},
    frame::{AudioFrame, VideoFrame},
};

use block2::RcBlock;
use crossbeam_channel::{Receiver, bounded};
use crossbeam_utils::sync::{Parker, Unparker};
use dispatch2::{DispatchQueue, DispatchQueueAttr};
use objc2::{
    AnyThread as _,
    rc::Retained,
    runtime::{AnyClass, ProtocolObject},
    sel,
};
use objc2_core_media::{CMTime, CMTimeFlags};
use objc2_foundation::{NSArray, NSError, NSNumber, NSObjectProtocol as _};
use objc2_screen_capture_kit::{
    SCContentFilter, SCContentSharingPicker, SCContentSharingPickerConfiguration, SCDisplay,
    SCShareableContent, SCShareableContentStyle, SCStream, SCStreamConfiguration,
    SCStreamOutputType, SCWindow,
};
use regex::Regex;
use tracing::error;

impl CaptureConfig {
    /// Spawns a thread to capture the screen and returns a `CaptureDesc`
    /// that can be used to control the capture.
    pub fn create(self) -> Result<CaptureDesc> {
        self.validate()?;
        let re = match &self.video.target {
            Target::WindowName(pattern) => Some(Regex::new(pattern)?),
            _ => None,
        };

        let (v_tx, v_rx) = bounded(self.video.channel_capacity);
        let (a_tx, a_rx) = match self.audio.as_ref() {
            Some(audio) => {
                let (tx, rx) = bounded(audio.channel_capacity);
                (Some(tx), Some(rx))
            }
            None => (None, None),
        };
        let size = Arc::new(AtomicSize::default());
        let parker = Parker::new();
        let unparker = parker.unparker().clone();
        let audio_desc = self.audio.as_ref().map(|_| CaptureAudioDesc {
            sample_rate: Arc::new(AtomicI32::new(0)),
        });
        let excluded: Vec<u32> = self
            .video
            .hide
            .iter()
            .filter_map(|id| u32::try_from(*id).ok())
            .collect();

        let (setup_tx, setup_rx) = bounded::<Result<()>>(1);

        let jh = thread::spawn({
            let size = size.clone();
            let sample_rate = audio_desc.as_ref().map(|desc| desc.sample_rate.clone());
            let target = self.video.target.clone();
            move || unsafe {
                let stopped = Arc::new(AtomicBool::new(false));
                // The delegate answers this too, so the wait below never needs a timeout.
                let (stop_tx, stop_rx) = bounded::<Option<CaptureError>>(1);
                #[allow(clippy::type_complexity)]
                let run = || -> Result<(
                    Retained<SCStream>,
                    Retained<StreamDelegate>,
                    Retained<VideoStreamOutput>,
                    bool,
                )> {
                    let (filter, width, height) = if target == Target::Pick {
                        present_picker(&excluded)?
                    } else {
                        let content = shareable_content()?;
                        content_filter(&content, &target, re.as_ref(), &excluded)?
                    };

                    // Deliberately no preset: the HDR ones change the dynamic range and colour
                    // space, which 8-bit BGRA cannot carry, and only exist on macOS 15.
                    let stream_config = SCStreamConfiguration::new();
                    stream_config.setWidth(width);
                    stream_config.setHeight(height);
                    // macOS 13+; on 12.3 the selector is missing and sending it aborts.
                    if stream_config.respondsToSelector(sel!(setCapturesAudio:)) {
                        stream_config.setCapturesAudio(self.audio.is_some());
                    } else if self.audio.is_some() {
                        return Err(Unsupported::Audio.into());
                    }
                    if stream_config.respondsToSelector(sel!(setCaptureMicrophone:)) {
                        stream_config.setCaptureMicrophone(false);
                    }
                    stream_config.setPixelFormat(u32::from_be_bytes(*b"BGRA"));
                    if let Some(fps) = self.video.fps.filter(|fps| *fps > 0) {
                        stream_config.setMinimumFrameInterval(CMTime {
                            value: 1,
                            timescale: fps as i32,
                            flags: CMTimeFlags::Valid,
                            epoch: 0,
                        });
                    }

                    let stream_delegate = StreamDelegate::new(
                        parker.unparker().clone(),
                        stopped.clone(),
                        stop_tx.clone(),
                    );
                    let stream = SCStream::initWithFilter_configuration_delegate(
                        SCStream::alloc(),
                        &filter,
                        &stream_config,
                        Some(ProtocolObject::from_ref(&*stream_delegate)),
                    );
                    // Before the output exists, so a real frame's size always lands after it.
                    size.store(width as u32, height as u32);
                    let output_delegrate =
                        VideoStreamOutput::new(v_tx, a_tx, size, sample_rate, self.video.fps);
                    let video_queue =
                        DispatchQueue::new("dev.scrcap.video", DispatchQueueAttr::SERIAL);
                    stream
                        .addStreamOutput_type_sampleHandlerQueue_error(
                            ProtocolObject::from_ref(&*output_delegrate),
                            SCStreamOutputType::Screen,
                            Some(&video_queue),
                        )
                        .map_err(|_| ScreenCaptureKitError::OutputAttach)?;
                    let has_audio = self.audio.is_some();
                    if has_audio {
                        let queue =
                            DispatchQueue::new("dev.scrcap.audio", DispatchQueueAttr::SERIAL);
                        stream
                            .addStreamOutput_type_sampleHandlerQueue_error(
                                ProtocolObject::from_ref(&*output_delegrate),
                                SCStreamOutputType::Audio,
                                Some(&queue),
                            )
                            .map_err(|_| ScreenCaptureKitError::OutputAttach)?;
                    }

                    let (start_tx, start_rx) = bounded(1);
                    stream.startCaptureWithCompletionHandler(Some(&RcBlock::new(
                        move |e: *mut NSError| {
                            let _ = start_tx.send((!e.is_null()).then(|| ns_error(&*e)));
                        },
                    )));
                    match start_rx.recv() {
                        Ok(Some(e)) => return Err(e),
                        Ok(None) => {}
                        Err(_) => return Err(CaptureError::WorkerGone),
                    }
                    Ok((stream, stream_delegate, output_delegrate, has_audio))
                };

                // `stream_delegate` is held to the end: ScreenCaptureKit does not keep its
                // delegate alive, and without it a stream that stops itself -- Stop Sharing,
                // an unplugged display -- would never unpark this thread or answer `stop_rx`.
                let (stream, stream_delegate, output_delegrate, has_audio) = match run() {
                    Ok(v) => {
                        let _ = setup_tx.send(Ok(()));
                        v
                    }
                    Err(e) => {
                        let _ = setup_tx.send(Err(e));
                        return;
                    }
                };

                parker.park();
                {
                    let output = ProtocolObject::from_ref(&*output_delegrate);
                    let _ =
                        stream.removeStreamOutput_type_error(output, SCStreamOutputType::Screen);
                    if has_audio {
                        let _ =
                            stream.removeStreamOutput_type_error(output, SCStreamOutputType::Audio);
                    }
                }
                // These own the senders; a consumer sees the end only once they drop.
                drop(output_delegrate);
                // Asking an already-stopped stream to stop can leave the completion handler
                // never firing, and it can stop itself right after this check -- which is why
                // the delegate answers `stop_rx` too.
                if !stopped.load(Ordering::Acquire) {
                    let stop_tx = stop_tx.clone();
                    stream.stopCaptureWithCompletionHandler(Some(&RcBlock::new(
                        move |e: *mut NSError| {
                            let _ = stop_tx.try_send((!e.is_null()).then(|| ns_error(&*e)));
                        },
                    )));
                }
                // Bounded, and not because the wait is expected to be slow: `stop_tx` is
                // still held here, so the channel can never close, and a `stopCapture`
                // whose completion block is simply dropped would park this thread for
                // good -- with `CaptureDesc::drop` joining it, that hangs the caller.
                match stop_rx.recv_timeout(Duration::from_secs(5)) {
                    Ok(Some(e)) => error!("failed to stop capture: {e}"),
                    Ok(None) => {}
                    Err(_) => error!("ScreenCaptureKit never answered the stop request"),
                }
                drop(stream_delegate);
            }
        });

        let setup = setup_rx.recv().unwrap_or(Err(CaptureError::WorkerGone));
        if let Err(e) = setup {
            let _ = jh.join();
            return Err(e);
        }

        Ok(CaptureDesc {
            jh: Some(jh),
            unparker,
            v_rx: Some(v_rx),
            a_rx,
            video_desc: CaptureVideoDesc { size },
            audio_desc,
        })
    }
}

/// Block on `getShareableContent`, which answers asynchronously on an internal queue.
unsafe fn shareable_content() -> Result<Retained<SCShareableContent>> {
    unsafe {
        let (tx, rx) = bounded(1);
        let block = RcBlock::new(move |shareable: *mut SCShareableContent, e: *mut NSError| {
            let _ = tx.send(if !e.is_null() {
                Err(ns_error(&*e))
            } else {
                Retained::retain(shareable).ok_or(ScreenCaptureKitError::NoShareableContent.into())
            });
        });
        SCShareableContent::getShareableContentWithCompletionHandler(&block);
        rx.recv().map_err(|_| CaptureError::WorkerGone)?
    }
}

unsafe fn present_picker(excluded: &[u32]) -> Result<(Retained<SCContentFilter>, usize, usize)> {
    unsafe {
        if AnyClass::get(c"SCContentSharingPicker").is_none() {
            return Err(Unsupported::Picker.into());
        }
        let (tx, rx) = bounded(1);
        let observer = PickerObserver::new(tx);
        let picker = SCContentSharingPicker::sharedPicker();
        // The picker is a process-wide singleton, so this configuration outlives the call
        // and would silently narrow the next one. Always install ours, always put back
        // what was there.
        let previous = picker.defaultConfiguration();
        let config = SCContentSharingPickerConfiguration::new();
        let ids: Vec<_> = excluded.iter().copied().map(NSNumber::new_u32).collect();
        config.setExcludedWindowIDs(&NSArray::from_retained_slice(&ids));
        picker.setDefaultConfiguration(&config);
        picker.addObserver(ProtocolObject::from_ref(&*observer));
        picker.setActive(true);
        picker.present();
        let filter = rx.recv().map_err(|_| CaptureError::WorkerGone);
        picker.setActive(false);
        picker.removeObserver(ProtocolObject::from_ref(&*observer));
        picker.setDefaultConfiguration(&previous);

        let filter = exclude_from_picked(filter??, excluded)?;
        let (width, height) = filter_size(&filter).ok_or(Unsupported::Picker)?;
        Ok((filter, width, height))
    }
}

/// Carry `hide` into the filter the picker handed back.
///
/// `excludedWindowIDs` only keeps a window out of the *picker*; the filter it returns for a
/// display still contains it. A display filter is therefore rebuilt with the exclusions,
/// and a window or application filter needs none -- it captures what the user named.
unsafe fn exclude_from_picked(
    filter: Retained<SCContentFilter>,
    excluded: &[u32],
) -> Result<Retained<SCContentFilter>> {
    unsafe {
        if excluded.is_empty() || filter.style() != SCShareableContentStyle::Display {
            return Ok(filter);
        }
        // `includedDisplays` is macOS 15.2+, the picker only 14.0+: sending it to an older
        // filter raises an uncaught unrecognized-selector exception.
        if !filter.respondsToSelector(sel!(includedDisplays)) {
            return Err(Unsupported::HideWindows.into());
        }
        let display = filter
            .includedDisplays()
            .firstObject()
            .ok_or(Unsupported::HideWindows)?;
        let content = shareable_content()?;
        Ok(SCContentFilter::initWithDisplay_excludingWindows(
            SCContentFilter::alloc(),
            &display,
            &NSArray::from_retained_slice(&windows_by_id(&content, excluded)),
        ))
    }
}

/// The `SCWindow`s the given `CGWindowID`s name, skipping any that are gone.
unsafe fn windows_by_id(content: &SCShareableContent, ids: &[u32]) -> Vec<Retained<SCWindow>> {
    unsafe {
        if ids.is_empty() {
            return Vec::new();
        }
        content
            .windows()
            .iter()
            .filter(|window| ids.contains(&window.windowID()))
            .collect()
    }
}

/// ScreenCaptureKit reports geometry in points, `SCStreamConfiguration` wants pixels.
/// Pixel dimensions of a filter, or `None` on a system whose `SCContentFilter` predates
/// these two selectors.
unsafe fn filter_size(filter: &SCContentFilter) -> Option<(usize, usize)> {
    unsafe {
        if !filter.respondsToSelector(sel!(contentRect))
            || !filter.respondsToSelector(sel!(pointPixelScale))
        {
            return None;
        }
        let rect = filter.contentRect();
        let scale = filter.pointPixelScale() as f64;
        Some((
            (rect.size.width * scale) as usize,
            (rect.size.height * scale) as usize,
        ))
    }
}

#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    /// The `CGDirectDisplayID` of the display with the menu bar, the one `SCDisplay::displayID`
    /// matches for `Target::Primary`.
    safe fn CGMainDisplayID() -> u32;
}

unsafe fn content_filter(
    shareable: &SCShareableContent,
    target: &Target,
    re: Option<&Regex>,
    excluded: &[u32],
) -> Result<(Retained<SCContentFilter>, usize, usize)> {
    unsafe {
        let excluded_windows = windows_by_id(shareable, excluded);
        // Point size kept as a fallback: `filter_size` needs selectors older systems lack.
        let from_display = |display: &SCDisplay| {
            (
                SCContentFilter::initWithDisplay_excludingWindows(
                    SCContentFilter::alloc(),
                    display,
                    &NSArray::from_retained_slice(&excluded_windows),
                ),
                (display.width() as usize, display.height() as usize),
            )
        };
        let from_window = |window: &SCWindow| {
            let frame = window.frame();
            (
                SCContentFilter::initWithDesktopIndependentWindow(SCContentFilter::alloc(), window),
                (frame.size.width as usize, frame.size.height as usize),
            )
        };
        let filter = match target {
            // `displays` has no documented order, so the first one is not necessarily main.
            Target::Primary => shareable
                .displays()
                .iter()
                .find(|display| display.displayID() == CGMainDisplayID())
                .map(|display| from_display(&display)),
            Target::Monitor(index) => usize::try_from(*index)
                .ok()
                .and_then(|index| {
                    let displays = shareable.displays();
                    (index < displays.len()).then(|| displays.objectAtIndex(index))
                })
                .map(|display| from_display(&display)),
            Target::Window(id) => u32::try_from(*id)
                .ok()
                .and_then(|id| shareable.windows().iter().find(|w| w.windowID() == id))
                .map(|window| from_window(&window)),
            Target::WindowName(_) => re.and_then(|re| {
                shareable
                    .windows()
                    .iter()
                    .find(|w| {
                        w.isOnScreen() && w.title().is_some_and(|t| re.is_match(&t.to_string()))
                    })
                    .map(|window| from_window(&window))
            }),
            Target::Pick => return Err(Unsupported::Picker.into()),
        };
        let (filter, points) = filter.ok_or(CaptureError::TargetNotFound)?;
        let (width, height) = filter_size(&filter).unwrap_or(points);
        Ok((filter, width, height))
    }
}

/// A description of the capture, including control and size.
///
/// Drop this descriptor to terminate the capture and clean up resources.
#[derive(Debug)]
pub struct CaptureDesc {
    unparker: Unparker,
    v_rx: Option<Receiver<VideoFrame>>,
    a_rx: Option<Receiver<AudioFrame>>,
    video_desc: CaptureVideoDesc,
    audio_desc: Option<CaptureAudioDesc>,
    jh: Option<JoinHandle<()>>,
}

#[derive(Debug)]
struct CaptureVideoDesc {
    size: Arc<AtomicSize>,
}

impl CaptureVideoDesc {
    fn size(&self) -> (u32, u32) {
        self.size.load()
    }
}

#[derive(Debug)]
struct CaptureAudioDesc {
    sample_rate: Arc<AtomicI32>,
}

impl CaptureAudioDesc {
    /// `None` until the first audio buffer settles the format: `0` is the unset state of the
    /// atomic, not a rate, and a caller is meant to tell the two apart.
    fn sample_rate(&self) -> Option<i32> {
        let rate = self.sample_rate.load(Ordering::Relaxed);
        (rate > 0).then_some(rate)
    }
}

impl TryFrom<CaptureConfig> for CaptureDesc {
    type Error = CaptureError;

    fn try_from(config: CaptureConfig) -> std::result::Result<Self, Self::Error> {
        config.create()
    }
}

impl CaptureDescriptor for CaptureDesc {
    fn terminate(&self) {
        self.unparker.unpark();
    }

    fn video(&self) -> &Receiver<VideoFrame> {
        self.v_rx.as_ref().unwrap()
    }

    fn audio(&self) -> Option<&Receiver<AudioFrame>> {
        self.a_rx.as_ref()
    }

    fn size(&self) -> (u32, u32) {
        self.video_desc.size()
    }

    fn sample_rate(&self) -> Option<i32> {
        self.audio_desc
            .as_ref()
            .and_then(|audio_desc| audio_desc.sample_rate())
    }
}

impl Drop for CaptureDesc {
    fn drop(&mut self) {
        self.terminate();
        let _ = self.v_rx.take();
        let _ = self.a_rx.take();
        if let Some(jh) = self.jh.take() {
            let _ = jh.join();
        }
    }
}