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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Screenshot manager tests (macOS 14.0+)

#![cfg(feature = "macos_14_0")]

use screencapturekit::screenshot_manager::{CGImage, CGImageExt, SCScreenshotManager};
use screencapturekit::shareable_content::SCShareableContent;
use screencapturekit::stream::configuration::SCStreamConfiguration;
use screencapturekit::stream::content_filter::SCContentFilter;

// Initialize CoreGraphics to prevent CGS_REQUIRE_INIT crashes in CI
fn cg_init_for_headless_ci() {
    extern "C" {
        fn sc_initialize_core_graphics();
    }
    unsafe { sc_initialize_core_graphics() }
}

macro_rules! require_display {
    ($content:expr, $display:ident) => {
        let displays = $content.displays();
        let Some($display) = displays.first() else {
            eprintln!("skip: no displays available");
            return;
        };
    };
}

fn has_capturable_display() -> bool {
    SCShareableContent::get().is_ok_and(|content| !content.displays().is_empty())
}

#[test]
fn test_screenshot_manager_type() {
    // Just verify the type exists and can be referenced
    let _ = SCScreenshotManager;
}

#[test]
fn test_capture_image() {
    cg_init_for_headless_ci();
    let content = SCShareableContent::get().expect("Failed to get shareable content");
    require_display!(content, display);

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

    let config = SCStreamConfiguration::new()
        .with_width(640)
        .with_height(480);

    let result = SCScreenshotManager::capture_image(&filter, &config);

    if let Ok(image) = result {
        assert!(image.width() > 0);
        assert!(image.height() > 0);
    }
    // Note: May fail if screen recording permission not granted
}

#[test]
fn test_capture_sample_buffer() {
    cg_init_for_headless_ci();
    let content = SCShareableContent::get().expect("Failed to get shareable content");
    require_display!(content, display);

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

    let config = SCStreamConfiguration::new()
        .with_width(640)
        .with_height(480);

    let result = SCScreenshotManager::capture_sample_buffer(&filter, &config);
    // Note: May fail if screen recording permission not granted
    if let Ok(buffer) = result {
        // The buffer should have a presentation timestamp
        let _pts = buffer.presentation_timestamp();
    }
}

#[test]
fn test_cgimage_send_sync() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}
    assert_send::<CGImage>();
    assert_sync::<CGImage>();
}

#[test]
fn test_cgimage_rgba_data() {
    cg_init_for_headless_ci();
    let content = SCShareableContent::get().expect("Failed to get shareable content");
    require_display!(content, display);

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

    let config = SCStreamConfiguration::new()
        .with_width(100)
        .with_height(100);

    if let Ok(image) = SCScreenshotManager::capture_image(&filter, &config) {
        if let Ok(data) = image.rgba_data() {
            // RGBA is 4 bytes per pixel
            let expected_min_size = image.width() * image.height() * 4;
            assert!(data.len() >= expected_min_size);
        }
    }
}

#[test]
fn test_cgimage_bgra_matches_rgba_byteswap() {
    // Both rgba_data() and bgra_data() should write width*height*4 bytes,
    // and bgra[i*4..] must equal [rgba[i*4+2], rgba[i*4+1], rgba[i*4], rgba[i*4+3]]
    // for every pixel — i.e. the BGRA path is the byte-for-byte channel
    // permutation of the RGBA path. If this regresses we'd silently ship a
    // broken format to BGRA consumers.
    cg_init_for_headless_ci();
    let Ok(content) = SCShareableContent::get() else {
        return;
    };
    require_display!(content, display);

    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();
    let config = SCStreamConfiguration::new().with_width(64).with_height(64);

    let Ok(image) = SCScreenshotManager::capture_image(&filter, &config) else {
        return;
    };
    let Ok(rgba) = image.rgba_data() else { return };
    let Ok(bgra) = image.bgra_data() else { return };

    assert_eq!(
        rgba.len(),
        bgra.len(),
        "RGBA and BGRA buffers must match in size"
    );
    assert_eq!(rgba.len(), image.width() * image.height() * 4);

    // Verify channel permutation on every 4-byte pixel.
    let mismatches = rgba
        .chunks_exact(4)
        .zip(bgra.chunks_exact(4))
        .filter(|(rgba_px, bgra_px)| {
            // RGBA = [R, G, B, A]; BGRA = [B, G, R, A].
            rgba_px[0] != bgra_px[2]
                || rgba_px[1] != bgra_px[1]
                || rgba_px[2] != bgra_px[0]
                || rgba_px[3] != bgra_px[3]
        })
        .count();
    let total = rgba.len() / 4;
    // Allow up to 0.5% mismatched pixels — both paths go through CGContext.draw
    // which can produce minor rounding deltas in alpha-premultiplication
    // depending on sub-pixel layout. Anything more than that means the channel
    // layout is genuinely wrong, not a rounding issue.
    let tolerance = total / 200 + 1;
    assert!(
        mismatches <= tolerance,
        "BGRA layout doesn't match RGBA byte-swap: {mismatches}/{total} pixels differ (tolerance {tolerance})"
    );
}

#[test]
fn test_cgimage_data_into_buffer_apis() {
    cg_init_for_headless_ci();
    let Ok(content) = SCShareableContent::get() else {
        return;
    };
    require_display!(content, display);
    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();
    let config = SCStreamConfiguration::new().with_width(64).with_height(64);
    let Ok(image) = SCScreenshotManager::capture_image(&filter, &config) else {
        return;
    };

    let total_bytes = image.width() * image.height() * 4;

    // 1. Both APIs must report the same total byte count and succeed. We
    // intentionally do NOT assert byte-for-byte equality between rgba_data
    // and rgba_data_into — even though they hit the same Swift FFI on the
    // same CGImage, observed behaviour across macOS versions is that
    // CGContext.draw on a separately-captured frame can produce slightly
    // different pixel values (cursor blink, animation frame, etc.). The
    // safety contract is "writes exactly width*height*4 bytes into the
    // destination" and that's what we check here.
    let rgba_owned = image.rgba_data().expect("rgba_data");
    assert_eq!(rgba_owned.len(), total_bytes);

    let mut rgba_buf = vec![0u8; total_bytes];
    let written = image.rgba_data_into(&mut rgba_buf).expect("rgba_data_into");
    assert_eq!(written, total_bytes);

    let bgra_owned = image.bgra_data().expect("bgra_data");
    assert_eq!(bgra_owned.len(), total_bytes);

    let mut bgra_buf = vec![0u8; total_bytes];
    let written = image.bgra_data_into(&mut bgra_buf).expect("bgra_data_into");
    assert_eq!(written, total_bytes);

    // 2. Two consecutive into-buffer calls on the *same buffer* must produce
    // identical output (the FFI is deterministic for a given destination
    // initialisation; we control both ends here).
    let mut a = vec![0u8; total_bytes];
    let mut b = vec![0u8; total_bytes];
    image.bgra_data_into(&mut a).expect("a");
    image.bgra_data_into(&mut b).expect("b");
    assert_eq!(a, b, "deterministic output for identical destination state");

    // 3. A too-small buffer must be rejected — no out-of-bounds writes.
    let mut small = vec![0u8; total_bytes - 1];
    assert!(
        image.rgba_data_into(&mut small).is_err(),
        "rgba_data_into must reject undersized destination"
    );
    assert!(
        image.bgra_data_into(&mut small).is_err(),
        "bgra_data_into must reject undersized destination"
    );

    // 4. An over-sized buffer should still work; only the first N bytes are
    // touched and the rest is left at whatever the caller had.
    let sentinel = 0xCDu8;
    let mut large = vec![sentinel; total_bytes + 16];
    let written = image.bgra_data_into(&mut large).expect("oversize ok");
    assert_eq!(written, total_bytes);
    assert!(
        large[total_bytes..].iter().all(|&b| b == sentinel),
        "bytes past the rendered region must not be touched"
    );
}

// MARK: - New Screenshot Features (macOS 15.2+)

#[test]
#[cfg(feature = "macos_15_2")]
fn test_capture_image_in_rect() {
    use screencapturekit::cg::CGRect;
    cg_init_for_headless_ci();
    if !has_capturable_display() {
        eprintln!("skip: no displays available");
        return;
    }

    // Capture a specific region of the screen
    let rect = CGRect::new(0.0, 0.0, 640.0, 480.0);
    let result = SCScreenshotManager::capture_image_in_rect(rect);

    match result {
        Ok(image) => {
            assert!(image.width() > 0);
            assert!(image.height() > 0);
            println!(
                "✓ Captured image in rect: {}x{}",
                image.width(),
                image.height()
            );
        }
        Err(e) => {
            // Expected on macOS < 15.2 or without permission
            println!("âš  capture_image_in_rect not available: {e}");
        }
    }
}

#[test]
#[cfg(feature = "macos_15_2")]
fn test_capture_image_in_rect_small_region() {
    use screencapturekit::cg::CGRect;
    cg_init_for_headless_ci();
    if !has_capturable_display() {
        eprintln!("skip: no displays available");
        return;
    }

    // Capture a small 100x100 region
    let rect = CGRect::new(100.0, 100.0, 100.0, 100.0);
    let result = SCScreenshotManager::capture_image_in_rect(rect);

    match result {
        Ok(image) => {
            println!(
                "✓ Captured small region: {}x{}",
                image.width(),
                image.height()
            );
        }
        Err(_) => {
            println!("âš  capture_image_in_rect not available");
        }
    }
}

// MARK: - Advanced Screenshot Configuration (macOS 26.0+)

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_creation() {
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;

    let config = SCScreenshotConfiguration::new();
    assert!(!config.as_ptr().is_null());
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_builder() {
    use screencapturekit::cg::CGRect;
    use screencapturekit::screenshot_manager::{
        SCScreenshotConfiguration, SCScreenshotDisplayIntent, SCScreenshotDynamicRange,
    };

    let config = SCScreenshotConfiguration::new()
        .with_width(1920)
        .with_height(1080)
        .with_shows_cursor(true)
        .with_source_rect(CGRect::new(0.0, 0.0, 1920.0, 1080.0))
        .with_destination_rect(CGRect::new(0.0, 0.0, 1920.0, 1080.0))
        .with_ignore_shadows(true)
        .with_ignore_clipping(false)
        .with_include_child_windows(true)
        .with_display_intent(SCScreenshotDisplayIntent::Canonical)
        .with_dynamic_range(SCScreenshotDynamicRange::SDR);

    assert!(!config.as_ptr().is_null());
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_hdr() {
    use screencapturekit::screenshot_manager::{
        SCScreenshotConfiguration, SCScreenshotDynamicRange,
    };

    // Test each dynamic range option
    let sdr_config =
        SCScreenshotConfiguration::new().with_dynamic_range(SCScreenshotDynamicRange::SDR);
    assert!(!sdr_config.as_ptr().is_null());

    let hdr_config =
        SCScreenshotConfiguration::new().with_dynamic_range(SCScreenshotDynamicRange::HDR);
    assert!(!hdr_config.as_ptr().is_null());

    let both_config = SCScreenshotConfiguration::new()
        .with_dynamic_range(SCScreenshotDynamicRange::BothSDRAndHDR);
    assert!(!both_config.as_ptr().is_null());
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_file_path() {
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;

    let config = SCScreenshotConfiguration::new().with_file_path("/tmp/test_screenshot.png");
    assert!(!config.as_ptr().is_null());
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_send_sync() {
    use screencapturekit::screenshot_manager::{SCScreenshotConfiguration, SCScreenshotOutput};

    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    assert_send::<SCScreenshotConfiguration>();
    assert_sync::<SCScreenshotConfiguration>();
    assert_send::<SCScreenshotOutput>();
    assert_sync::<SCScreenshotOutput>();
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_display_intent_enum() {
    use screencapturekit::screenshot_manager::SCScreenshotDisplayIntent;

    assert_eq!(SCScreenshotDisplayIntent::Canonical as i32, 0);
    assert_eq!(SCScreenshotDisplayIntent::Local as i32, 1);

    // Test default
    let default = SCScreenshotDisplayIntent::default();
    assert_eq!(default, SCScreenshotDisplayIntent::Canonical);
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_dynamic_range_enum() {
    use screencapturekit::screenshot_manager::SCScreenshotDynamicRange;

    assert_eq!(SCScreenshotDynamicRange::SDR as i32, 0);
    assert_eq!(SCScreenshotDynamicRange::HDR as i32, 1);
    assert_eq!(SCScreenshotDynamicRange::BothSDRAndHDR as i32, 2);

    // Test default
    let default = SCScreenshotDynamicRange::default();
    assert_eq!(default, SCScreenshotDynamicRange::SDR);
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_capture_screenshot_with_configuration() {
    use screencapturekit::screenshot_manager::{
        SCScreenshotConfiguration, SCScreenshotDynamicRange,
    };

    cg_init_for_headless_ci();
    let content = SCShareableContent::get().expect("Failed to get shareable content");
    require_display!(content, display);

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

    let config = SCScreenshotConfiguration::new()
        .with_width(640)
        .with_height(480)
        .with_shows_cursor(true)
        .with_dynamic_range(SCScreenshotDynamicRange::SDR);

    let result = SCScreenshotManager::capture_screenshot(&filter, &config);

    match result {
        Ok(output) => {
            // Should have at least SDR image
            if let Some(sdr) = output.sdr_image() {
                assert!(sdr.width() > 0);
                assert!(sdr.height() > 0);
                println!(
                    "✓ Advanced screenshot SDR: {}x{}",
                    sdr.width(),
                    sdr.height()
                );
            }
        }
        Err(e) => {
            // Expected on macOS < 26.0 or without permission
            println!("âš  capture_screenshot not available: {e}");
        }
    }
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_capture_screenshot_in_rect_with_configuration() {
    use screencapturekit::cg::CGRect;
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;

    cg_init_for_headless_ci();

    let rect = CGRect::new(0.0, 0.0, 640.0, 480.0);
    let config = SCScreenshotConfiguration::new()
        .with_width(640)
        .with_height(480);

    let result = SCScreenshotManager::capture_screenshot_in_rect(rect, &config);

    match result {
        Ok(output) => {
            if let Some(image) = output.sdr_image() {
                assert!(image.width() > 0);
                println!(
                    "✓ Advanced screenshot in rect: {}x{}",
                    image.width(),
                    image.height()
                );
            }
        }
        Err(e) => {
            println!("âš  capture_screenshot_in_rect not available: {e}");
        }
    }
}

// MARK: - SCScreenshotConfiguration getters (macOS 26.0+)

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_scalar_getters_round_trip() {
    use screencapturekit::screenshot_manager::{
        SCScreenshotConfiguration, SCScreenshotDisplayIntent, SCScreenshotDynamicRange,
    };

    let config = SCScreenshotConfiguration::new()
        .with_width(1920)
        .with_height(1080)
        .with_shows_cursor(true)
        .with_ignore_shadows(true)
        .with_ignore_clipping(true)
        .with_include_child_windows(true)
        .with_display_intent(SCScreenshotDisplayIntent::Local)
        .with_dynamic_range(SCScreenshotDynamicRange::BothSDRAndHDR);

    assert_eq!(config.width(), 1920);
    assert_eq!(config.height(), 1080);
    assert!(config.shows_cursor());
    assert!(config.ignore_shadows());
    assert!(config.ignore_clipping());
    assert!(config.include_child_windows());
    assert_eq!(
        config.display_intent(),
        Some(SCScreenshotDisplayIntent::Local)
    );
    assert_eq!(
        config.dynamic_range(),
        Some(SCScreenshotDynamicRange::BothSDRAndHDR)
    );
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_rect_getters_round_trip() {
    use screencapturekit::cg::CGRect;
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;

    let source = CGRect::new(10.0, 20.0, 640.0, 480.0);
    let destination = CGRect::new(0.0, 0.0, 1280.0, 960.0);

    let config = SCScreenshotConfiguration::new()
        .with_source_rect(source)
        .with_destination_rect(destination);

    let read_source = config.source_rect();
    assert!((read_source.origin.x - source.origin.x).abs() < f64::EPSILON);
    assert!((read_source.origin.y - source.origin.y).abs() < f64::EPSILON);
    assert!((read_source.size.width - source.size.width).abs() < f64::EPSILON);
    assert!((read_source.size.height - source.size.height).abs() < f64::EPSILON);

    let read_destination = config.destination_rect();
    assert!((read_destination.size.width - destination.size.width).abs() < f64::EPSILON);
    assert!((read_destination.size.height - destination.size.height).abs() < f64::EPSILON);
}

/// The path must survive the round trip byte-for-byte. The previous
/// `String`-based accessor decoded lossily and used a fixed-size buffer.
#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_file_path_round_trip() {
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;
    use std::path::PathBuf;

    let dir = std::env::temp_dir();
    let path: PathBuf = dir.join("screencapturekit round trip.png");

    let config = SCScreenshotConfiguration::new().with_file_path(&path);
    assert_eq!(config.file_path().as_deref(), Some(path.as_path()));

    let cleared = config.without_file_path();
    assert_eq!(cleared.file_path(), None);

    let mut config = SCScreenshotConfiguration::new().with_file_path(&path);
    config.clear_file_path();
    assert_eq!(config.file_path(), None);
}

/// A long path must not be truncated into a different, valid-looking path.
#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_long_file_path_survives() {
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;

    let long_name = "x".repeat(200);
    let path = std::env::temp_dir().join(format!("{long_name}.png"));

    let config = SCScreenshotConfiguration::new().with_file_path(&path);
    assert_eq!(config.file_path().as_deref(), Some(path.as_path()));
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_rejects_interior_nul_path() {
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;

    let mut config = SCScreenshotConfiguration::new();
    assert!(
        config.try_set_file_path("/tmp/bad\0name.png").is_err(),
        "interior NUL path must be rejected"
    );
    assert_eq!(config.file_path(), None);
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_rejects_non_utf8_path() {
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;
    use std::os::unix::ffi::OsStringExt;

    let path = std::path::PathBuf::from(std::ffi::OsString::from_vec(
        b"/tmp/screenshot-\xff.png".to_vec(),
    ));
    let mut config = SCScreenshotConfiguration::new();
    assert!(config.try_set_file_path(path).is_err());
    assert_eq!(config.file_path(), None);
}

#[test]
#[cfg(feature = "macos_26_0")]
fn test_screenshot_configuration_content_type_round_trip() {
    use screencapturekit::screenshot_manager::SCScreenshotConfiguration;

    let supported = SCScreenshotConfiguration::supported_content_types();
    assert!(
        !supported.is_empty(),
        "SCScreenshotConfiguration reported no supported content types"
    );

    let config = SCScreenshotConfiguration::new().with_content_type("public.png");
    assert_eq!(config.content_type().as_deref(), Some("public.png"));
}