screencapturekit 9.0.1

Safe Rust bindings for Apple's ScreenCaptureKit framework - screen and audio capture on macOS
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use screencapturekit::cm::CMSampleBufferExt;
use screencapturekit::{
    cv::CVPixelBufferLockFlags,
    shareable_content::SCShareableContent,
    stream::{
        configuration::SCStreamConfiguration, content_filter::SCContentFilter,
        output_trait::SCStreamOutputTrait, output_type::SCStreamOutputType, SCStream,
    },
    CMSampleBuffer,
};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Test output handler that collects video samples
struct VideoTestOutput {
    samples: Arc<Mutex<Vec<CMSampleBuffer>>>,
}

impl SCStreamOutputTrait for VideoTestOutput {
    fn did_output_sample_buffer(
        &self,
        sample_buffer: CMSampleBuffer,
        _of_type: SCStreamOutputType,
    ) {
        if let Ok(mut guard) = self.samples.lock() {
            guard.push(sample_buffer);
        }
    }
}

/// Test output handler that collects audio samples
struct AudioTestOutput {
    samples: Arc<Mutex<Vec<CMSampleBuffer>>>,
}

impl SCStreamOutputTrait for AudioTestOutput {
    fn did_output_sample_buffer(
        &self,
        sample_buffer: CMSampleBuffer,
        _of_type: SCStreamOutputType,
    ) {
        if let Ok(mut guard) = self.samples.lock() {
            guard.push(sample_buffer);
        }
    }
}

#[test]
fn test_video_capture() {
    // Get shareable content
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: Screen recording permission required!");
            println!("   Go to: System Settings → Privacy & Security → Screen Recording");
            println!("   Error: {e:?}");
            return; // Skip test gracefully
        }
    };

    let displays = content.displays();

    if displays.is_empty() {
        eprintln!("SKIP: No displays available - skipping test");
        return;
    }

    let display = &displays[0];

    // Create configuration for video
    let mut config = SCStreamConfiguration::default();
    config.set_width(1920);
    config.set_height(1080);
    config.set_captures_audio(false);

    // Create filter for the display
    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();

    // Create stream
    let mut stream = SCStream::new(&filter, &config);

    // Add video output handler
    let samples = Arc::new(Mutex::new(Vec::new()));
    let output = VideoTestOutput {
        samples: samples.clone(),
    };

    stream.add_output_handler(output, SCStreamOutputType::Screen);

    // Start capture
    stream.start_capture().expect("Failed to start capture");

    // Wait for some frames
    std::thread::sleep(Duration::from_secs(2));

    // Stop capture
    stream.stop_capture().expect("Failed to stop capture");

    // Verify we got frames
    let collected_samples = samples.lock().unwrap();

    if collected_samples.is_empty() {
        eprintln!(
            "SKIP: No video samples captured - this may be due to permissions or environment"
        );
        return; // Skip assertion to avoid false negatives
    }

    println!("Captured {} video samples", collected_samples.len());

    // Verify sample properties
    if let Some(sample) = collected_samples.first() {
        if let Some(image_buffer) = sample.image_buffer() {
            let width = image_buffer.width();
            let height = image_buffer.height();

            println!("Video frame size: {width}x{height}");
            assert!(width > 0, "Invalid video width");
            assert!(height > 0, "Invalid video height");
        } else {
            eprintln!("SKIP: First sample has no image buffer (may be idle frame)");
        }
    }
}

#[test]
fn test_audio_capture() {
    // Get shareable content
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: Screen recording permission required!");
            println!("   Error: {e:?}");
            return;
        }
    };

    let displays = content.displays();

    if displays.is_empty() {
        eprintln!("SKIP: No displays available - skipping test");
        return;
    }

    let display = &displays[0];

    // Create configuration for audio
    let mut config = SCStreamConfiguration::default();
    config.set_captures_audio(true);

    // Create filter for the display
    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();

    // Create stream
    let mut stream = SCStream::new(&filter, &config);

    // Add audio output handler
    let samples = Arc::new(Mutex::new(Vec::new()));
    let output = AudioTestOutput {
        samples: samples.clone(),
    };

    stream.add_output_handler(output, SCStreamOutputType::Audio);

    // Start capture
    stream.start_capture().expect("Failed to start capture");

    // Wait for some audio samples
    std::thread::sleep(Duration::from_secs(3));

    // Stop capture
    stream.stop_capture().expect("Failed to stop capture");

    // Verify we got audio samples
    let collected_samples = samples.lock().unwrap();

    if collected_samples.is_empty() {
        eprintln!("SKIP: No audio samples captured (OK if no audio was playing)");
        return;
    }

    println!("Captured {} audio samples", collected_samples.len());

    // Verify audio buffer properties (may be empty if no audio playing)
    let mut samples_with_data = 0;
    for sample in collected_samples.iter() {
        if let Some(audio_buffer_list) = sample.audio_buffer_list() {
            let num_buffers = audio_buffer_list.num_buffers();
            if num_buffers > 0 {
                samples_with_data += 1;
                if let Some(buffer) = audio_buffer_list.buffer(0) {
                    let data_size = buffer.data_byte_size();
                    println!("Audio buffer: {num_buffers} buffers, {data_size} bytes");
                }
            }
        }
    }

    let total_samples = collected_samples.len();
    drop(collected_samples);

    println!("Audio samples with buffer data: {samples_with_data}/{total_samples}");
    // Note: samples_with_data may be 0 if no audio was playing during capture
}

#[test]
fn test_video_and_audio_capture() {
    // Get shareable content
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: Screen recording permission required!");
            println!("   Error: {e:?}");
            return;
        }
    };

    let displays = content.displays();

    if displays.is_empty() {
        eprintln!("SKIP: No displays available - skipping test");
        return;
    }

    let display = &displays[0];

    // Create configuration for both video and audio
    let mut config = SCStreamConfiguration::default();
    config.set_width(1280);
    config.set_height(720);
    config.set_captures_audio(true);

    // Create filter for the display
    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();

    // Create stream
    let mut stream = SCStream::new(&filter, &config);

    // Add video output handler
    let video_samples = Arc::new(Mutex::new(Vec::new()));
    let video_output = VideoTestOutput {
        samples: video_samples.clone(),
    };
    stream.add_output_handler(video_output, SCStreamOutputType::Screen);

    // Add audio output handler
    let audio_samples = Arc::new(Mutex::new(Vec::new()));
    let audio_output = AudioTestOutput {
        samples: audio_samples.clone(),
    };
    stream.add_output_handler(audio_output, SCStreamOutputType::Audio);

    // Start capture
    stream.start_capture().expect("Failed to start capture");

    // Wait for samples
    std::thread::sleep(Duration::from_secs(3));

    // Stop capture
    stream.stop_capture().expect("Failed to stop capture");

    // Verify we got both video and audio samples
    let video_count = video_samples.lock().unwrap().len();
    let audio_count = audio_samples.lock().unwrap().len();

    println!("Captured {video_count} video samples and {audio_count} audio samples");

    if video_count == 0 {
        eprintln!("SKIP: No video samples captured - may be due to permissions");
        return;
    }

    if audio_count == 0 {
        eprintln!("SKIP: No audio samples captured (OK if no audio was playing)");
    }
}

#[test]
fn test_pixel_buffer_locking() {
    // Get shareable content
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: Screen recording permission required!");
            println!("   Error: {e:?}");
            return;
        }
    };

    let displays = content.displays();

    if displays.is_empty() {
        eprintln!("SKIP: No displays available - skipping test");
        return;
    }

    let display = &displays[0];

    // Create configuration
    let mut config = SCStreamConfiguration::default();
    config.set_width(640);
    config.set_height(480);

    // Create filter and stream
    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();
    let mut stream = SCStream::new(&filter, &config);

    // Add output handler
    let samples = Arc::new(Mutex::new(Vec::new()));
    let output = VideoTestOutput {
        samples: samples.clone(),
    };
    stream.add_output_handler(output, SCStreamOutputType::Screen);

    // Start capture
    stream.start_capture().expect("Failed to start capture");

    // Wait for one frame
    std::thread::sleep(Duration::from_millis(500));

    // Stop capture
    stream.stop_capture().expect("Failed to stop capture");

    // Test pixel buffer locking
    let collected_samples = samples.lock().unwrap();
    if let Some(sample) = collected_samples.first() {
        let Some(pixel_buffer) = sample.image_buffer() else {
            eprintln!("SKIP: First sample has no image buffer (may be idle frame)");
            return;
        };

        // Test read lock
        {
            let lock_guard = pixel_buffer
                .lock(CVPixelBufferLockFlags::READ_ONLY)
                .expect("Failed to lock base address for reading");

            let base_address = lock_guard.base_address();
            assert!(!base_address.is_null(), "Base address is null");

            let width = pixel_buffer.width();
            let height = pixel_buffer.height();
            let bytes_per_row = pixel_buffer.bytes_per_row();

            println!("Locked pixel buffer: {width}x{height}, {bytes_per_row} bytes/row");

            // Lock guard automatically unlocks when dropped
        }

        // Test write lock
        {
            let mut lock_guard = pixel_buffer
                .lock(CVPixelBufferLockFlags::NONE)
                .expect("Failed to lock base address for writing");

            let base_address_mut = lock_guard.base_address_mut();
            assert!(
                base_address_mut.is_some(),
                "Mutable base address should be available for read-write lock"
            );
            assert!(
                !base_address_mut.unwrap().is_null(),
                "Mutable base address is null"
            );

            // Lock guard automatically unlocks when dropped
        }

        println!("Pixel buffer locking test passed");
    }
}

#[test]
fn test_iosurface_backed_buffer() {
    // Get shareable content
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("SKIP: Screen recording permission required!");
            println!("   Error: {e:?}");
            return;
        }
    };
    let displays = content.displays();

    let Some(display) = displays.first() else {
        eprintln!("SKIP: No displays available");
        return;
    };

    // Create configuration
    let mut config = SCStreamConfiguration::default();
    config.set_width(1920);
    config.set_height(1080);

    // Create filter and stream
    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();
    let mut stream = SCStream::new(&filter, &config);

    // Add output handler
    let samples = Arc::new(Mutex::new(Vec::new()));
    let output = VideoTestOutput {
        samples: samples.clone(),
    };
    stream.add_output_handler(output, SCStreamOutputType::Screen);

    // Start capture
    stream.start_capture().expect("Failed to start capture");

    // Wait for one frame
    std::thread::sleep(Duration::from_millis(500));

    // Stop capture
    stream.stop_capture().expect("Failed to stop capture");

    // Test IOSurface backing
    let collected_samples = samples.lock().unwrap();
    if let Some(sample) = collected_samples.first() {
        let Some(pixel_buffer) = sample.image_buffer() else {
            eprintln!("SKIP: First sample has no image buffer (may be idle frame)");
            return;
        };

        // Check if backed by IOSurface
        let iosurface = pixel_buffer.io_surface();
        assert!(iosurface.is_some(), "Pixel buffer is not IOSurface-backed");

        if let Some(surface) = iosurface {
            let width = surface.width();
            let height = surface.height();
            let bytes_per_row = surface.bytes_per_row();

            println!("IOSurface: {width}x{height}, {bytes_per_row} bytes/row");
            assert!(width > 0, "Invalid IOSurface width");
            assert!(height > 0, "Invalid IOSurface height");
            assert!(bytes_per_row > 0, "Invalid IOSurface bytes per row");
        }
    }
}

#[test]
fn test_shareable_content_below_window() {
    // Get shareable content to find a reference window
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Skipping test: {e}");
            return;
        }
    };

    let windows = content.windows();
    if windows.is_empty() {
        eprintln!("Skipping test: no windows available");
        return;
    }

    // Use the first window as reference
    let reference_window = &windows[0];

    // Get content below this window
    let result = SCShareableContent::create()
        .with_exclude_desktop_windows(false)
        .below_window(reference_window);

    match result {
        Ok(below_content) => {
            println!(
                "Found {} windows below reference window",
                below_content.windows().len()
            );
        }
        Err(e) => {
            eprintln!("Below window query failed (may be expected): {e}");
        }
    }
}

#[test]
fn test_shareable_content_above_window() {
    // Get shareable content to find a reference window
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Skipping test: {e}");
            return;
        }
    };

    let windows = content.windows();
    if windows.is_empty() {
        eprintln!("Skipping test: no windows available");
        return;
    }

    // Use the first window as reference
    let reference_window = &windows[0];

    // Get content above this window
    let result = SCShareableContent::create()
        .with_exclude_desktop_windows(false)
        .above_window(reference_window);

    match result {
        Ok(above_content) => {
            println!(
                "Found {} windows above reference window",
                above_content.windows().len()
            );
        }
        Err(e) => {
            eprintln!("Above window query failed (may be expected): {e}");
        }
    }
}

#[cfg(feature = "macos_14_4")]
#[test]
fn test_shareable_content_current_process() {
    // Get shareable content for current process only
    let result = SCShareableContent::current_process();

    match result {
        Ok(content) => {
            println!(
                "Current process content: {} displays, {} windows, {} apps",
                content.displays().len(),
                content.windows().len(),
                content.applications().len()
            );
        }
        Err(e) => {
            eprintln!("Current process content query failed: {e}");
        }
    }
}