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
//! Memory safety tests
//!
//! These tests verify proper memory management across the library.
//! Run with: `cargo test --test memory_tests --features "macos_14_0"`
//!
//! For comprehensive leak detection using macOS `leaks` command,
//! run the `15_memory_leak_check` example instead:
//! `cargo run --example 15_memory_leak_check`

#![allow(clippy::items_after_statements)]

use screencapturekit::prelude::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

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

/// Test that `SCShareableContent` properly releases memory
#[test]
fn test_shareable_content_drop() {
    init_cg();
    // Create and drop multiple times to check for leaks
    for _ in 0..10 {
        let content = SCShareableContent::get().expect("Failed to get content");
        let _displays = content.displays();
        let _windows = content.windows();
        let _apps = content.applications();
        // content dropped here
    }
}

/// Test that cloning and dropping works correctly
#[test]
fn test_clone_and_drop() {
    init_cg();
    let content = SCShareableContent::get().expect("Failed to get content");

    // Clone displays multiple times
    let displays = content.displays();
    if let Some(display) = displays.first() {
        let clones: Vec<_> = (0..100).map(|_| display.clone()).collect();
        drop(clones);

        // Original should still be valid
        let _ = display.display_id();
    }

    // Clone windows multiple times
    let windows = content.windows();
    if let Some(window) = windows.first() {
        let clones: Vec<_> = (0..100).map(|_| window.clone()).collect();
        drop(clones);

        // Original should still be valid
        let _ = window.window_id();
    }
}

/// Test `SCContentFilter` memory management
#[test]
fn test_content_filter_memory() {
    init_cg();
    let content = SCShareableContent::get().expect("Failed to get content");
    let displays = content.displays();

    if let Some(display) = displays.first() {
        // Create many filters
        let filters: Vec<_> = (0..50)
            .map(|_| {
                SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build()
            })
            .collect();

        // Clone filters
        let cloned: Vec<_> = filters.clone();

        drop(cloned);
        drop(filters);
    }
}

/// Test `SCStreamConfiguration` memory management
#[test]
fn test_stream_configuration_memory() {
    // Create many configurations
    let configs: Vec<_> = (0..100)
        .map(|i: i32| {
            SCStreamConfiguration::new()
                .with_width(1920)
                .with_height(1080)
                .with_fps(30 + (i.unsigned_abs() % 30))
                .with_shows_cursor(true)
                .with_captures_audio(true)
        })
        .collect();

    // Clone configurations
    let cloned: Vec<_> = configs.clone();

    drop(cloned);
    drop(configs);
}

/// Test that stream creation and destruction doesn't leak
#[test]
fn test_stream_lifecycle() {
    init_cg();
    let content = SCShareableContent::get().expect("Failed to get content");
    let displays = content.displays();

    if let Some(display) = displays.first() {
        let filter = SCContentFilter::create()
            .with_display(display)
            .with_excluding_windows(&[])
            .build();

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

        // Create and drop streams multiple times
        for _ in 0..5 {
            let stream = SCStream::new(&filter, &config);
            drop(stream);
        }
    }
}

/// Test handler registration and cleanup
#[test]
fn test_handler_registration_cleanup() {
    init_cg();
    struct TestHandler {
        count: Arc<AtomicUsize>,
    }

    impl SCStreamOutputTrait for TestHandler {
        fn did_output_sample_buffer(&self, _sample: CMSampleBuffer, _of_type: SCStreamOutputType) {
            self.count.fetch_add(1, Ordering::Relaxed);
        }
    }

    let content = SCShareableContent::get().expect("Failed to get content");
    let displays = content.displays();

    if let Some(display) = displays.first() {
        let filter = SCContentFilter::create()
            .with_display(display)
            .with_excluding_windows(&[])
            .build();

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

        // Register and remove handlers multiple times
        for _ in 0..10 {
            let mut stream = SCStream::new(&filter, &config);
            let count = Arc::new(AtomicUsize::new(0));

            let handler = TestHandler {
                count: count.clone(),
            };
            let id = stream.add_output_handler(handler, SCStreamOutputType::Screen);

            // Remove handler
            if let Some(handler_id) = id {
                stream.remove_output_handler(handler_id, SCStreamOutputType::Screen);
            }

            drop(stream);
        }
    }
}

/// Test closure handler memory management
#[test]
fn test_closure_handler_memory() {
    init_cg();
    let content = SCShareableContent::get().expect("Failed to get content");
    let displays = content.displays();

    if let Some(display) = displays.first() {
        let filter = SCContentFilter::create()
            .with_display(display)
            .with_excluding_windows(&[])
            .build();

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

        for _ in 0..10 {
            let mut stream = SCStream::new(&filter, &config);
            let count = Arc::new(AtomicUsize::new(0));
            let count_clone = count.clone();

            stream.add_output_handler(
                move |_sample: CMSampleBuffer, _of_type: SCStreamOutputType| {
                    count_clone.fetch_add(1, Ordering::Relaxed);
                },
                SCStreamOutputType::Screen,
            );

            drop(stream);
            // count should be droppable after stream is dropped
            drop(count);
        }
    }
}

/// Test `CGRect` and geometry types don't leak
#[test]
fn test_geometry_types() {
    use screencapturekit::cg::{CGPoint, CGRect, CGSize};

    // These are Copy types, but let's verify they work correctly
    for _ in 0..1000 {
        let point = CGPoint { x: 100.0, y: 200.0 };
        let size = CGSize {
            width: 1920.0,
            height: 1080.0,
        };
        let rect = CGRect::new(point.x, point.y, size.width, size.height);

        let _ = rect.origin.x;
        let _ = rect.origin.y;
        let _ = rect.size.width;
        let _ = rect.size.height;
    }
}

/// Test `CMTime` doesn't leak
#[test]
fn test_cmtime_memory() {
    use screencapturekit::cm::CMTime;

    for _ in 0..1000 {
        let time = CMTime::new(1, 30);
        let _ = time.as_seconds();
        let _ = time.is_valid();

        let time2 = CMTime::new(0, 1);
        let _ = time2.is_zero();
    }
}

/// Test `DispatchQueue` memory management
#[test]
fn test_dispatch_queue_memory() {
    use screencapturekit::dispatch_queue::{DispatchQoS, DispatchQueue};

    for i in 0..20 {
        let queue = DispatchQueue::new(&format!("com.test.queue.{i}"), DispatchQoS::Default);
        let cloned = queue.clone();
        drop(cloned);
        drop(queue);
    }
}

/// Test that multiple streams with handlers don't leak
#[test]
fn test_multiple_streams_memory() {
    init_cg();
    let content = SCShareableContent::get().expect("Failed to get content");
    let displays = content.displays();

    if let Some(display) = displays.first() {
        let filter = SCContentFilter::create()
            .with_display(display)
            .with_excluding_windows(&[])
            .build();

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

        // Create multiple streams simultaneously
        let streams: Vec<_> = (0..5)
            .map(|_| {
                let mut stream = SCStream::new(&filter, &config);
                let count = Arc::new(AtomicUsize::new(0));
                let count_clone = count.clone();

                stream.add_output_handler(
                    move |_: CMSampleBuffer, _: SCStreamOutputType| {
                        count_clone.fetch_add(1, Ordering::Relaxed);
                    },
                    SCStreamOutputType::Screen,
                );

                (stream, count)
            })
            .collect();

        // Drop all streams
        drop(streams);
    }
}

/// Test window filter creation doesn't leak
#[test]
fn test_window_filter_memory() {
    init_cg();
    let content = SCShareableContent::get().expect("Failed to get content");
    let windows = content.windows();

    if let Some(window) = windows.first() {
        // Create many window filters
        let filters: Vec<_> = (0..50)
            .map(|_| SCContentFilter::create().with_window(window).build())
            .collect();

        drop(filters);
    }
}

/// Test that audio configuration doesn't leak
#[test]
#[cfg(feature = "macos_15_0")]
fn test_audio_config_memory() {
    for _ in 0..100 {
        let config = SCStreamConfiguration::new()
            .with_captures_audio(true)
            .with_sample_rate(48000)
            .with_channel_count(2)
            .with_captures_microphone(true)
            .with_excludes_current_process_audio(true);

        let _ = config.captures_audio();
        let _ = config.sample_rate();
        let _ = config.channel_count();

        drop(config);
    }
}

#[cfg(feature = "macos_14_0")]
mod macos_14_tests {
    use super::*;
    use screencapturekit::shareable_content::SCShareableContentInfo;

    /// Test `SCShareableContentInfo` memory management
    #[test]
    fn test_content_info_memory() {
        init_cg();
        let content = SCShareableContent::get().expect("Failed to get content");
        let displays = content.displays();

        if let Some(display) = displays.first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();

            // Create and drop content info multiple times
            for _ in 0..20 {
                if let Some(info) = SCShareableContentInfo::for_filter(&filter) {
                    let _ = info.style();
                    let _ = info.point_pixel_scale();
                    let _ = info.pixel_size();
                    // info dropped here
                }
            }
        }
    }

    /// Test `SCContentSharingPickerConfiguration` memory
    #[test]
    fn test_picker_config_memory() {
        use screencapturekit::content_sharing_picker::{
            SCContentSharingPickerConfiguration, SCContentSharingPickerMode,
        };

        for _ in 0..50 {
            let mut config = SCContentSharingPickerConfiguration::new();
            config.set_allowed_picker_modes(&[
                SCContentSharingPickerMode::SingleWindow,
                SCContentSharingPickerMode::SingleDisplay,
            ]);

            let cloned = config.clone();
            drop(cloned);
            drop(config);
        }
    }
}

#[cfg(feature = "macos_15_0")]
mod macos_15_tests {
    /// Test `SCRecordingOutputConfiguration` memory
    #[test]
    fn test_recording_config_memory() {
        use screencapturekit::recording_output::{
            SCRecordingOutputCodec, SCRecordingOutputConfiguration, SCRecordingOutputFileType,
        };

        for _ in 0..50 {
            let config = SCRecordingOutputConfiguration::new()
                .with_video_codec(SCRecordingOutputCodec::H264)
                .with_output_file_type(SCRecordingOutputFileType::MP4);

            let _ = config.video_codec();
            let _ = config.output_file_type();

            let cloned = config.clone();
            drop(cloned);
            drop(config);
        }
    }
}

/// Soak test for the `MetalTexture` retain/release balance (`Clone`).
///
/// A double-free / over-release would crash and a leak would grow unbounded, so
/// thousands of clone/drop cycles on a real IOSurface-backed texture exercise
/// the retain path deterministically — no capture permission required. This is
/// a regression guard for the `Clone for MetalTexture` retain fix.
#[test]
fn test_metal_texture_clone_soak() {
    use screencapturekit::cm::IOSurface;
    use screencapturekit::metal::{IOSurfaceMetalExt, MetalDevice};

    let Some(device) = MetalDevice::system_default() else {
        eprintln!("skipping: no Metal device in this environment");
        return;
    };
    // 0x4247_5241 == 'BGRA'.
    let surface = IOSurface::create(64, 64, 0x4247_5241, 4).expect("Failed to create IOSurface");
    let textures = surface
        .create_metal_textures(&device)
        .expect("Failed to create textures");

    for _ in 0..10_000 {
        let clones: Vec<_> = (0..8).map(|_| textures.plane0.clone()).collect();
        drop(clones);
    }

    // The original must still be valid after all of the clone/drop churn.
    assert_eq!(textures.plane0.width(), 64);
    assert_eq!(textures.plane0.height(), 64);
    assert!(!textures.plane0.as_ptr().is_null());
}