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
//! Memory Leak Detection Example
//!
//! This example demonstrates how to check for memory leaks using macOS's `leaks` tool.
//! It creates and destroys streams multiple times, then uses the `leaks` command to
//! verify no memory is leaked.
//!
//! # Tested API Surface
//! - `SCShareableContent`: displays, windows, applications
//! - `SCContentFilter`: all filter types (display, window, app inclusion/exclusion)
//! - `SCStreamConfiguration`: video, audio, microphone settings
//! - `SCStream`: start/stop, output handlers for all types
//! - `SCDisplay`, `SCWindow`, `SCRunningApplication`: property access
//!
//! # Usage
//! ```sh
//! cargo run --example 15_memory_leak_check
//! ```
//!
//! # Note
//! This uses the macOS `leaks` command which requires running as a standalone process.
//! Some Apple framework leaks in `ScreenCaptureKit` itself are expected and ignored.

use screencapturekit::{
    cg::CGRect,
    cm::CMSampleBuffer,
    shareable_content::{SCRunningApplication, SCShareableContent, SCWindow},
    stream::{
        configuration::{pixel_format::PixelFormat, SCStreamConfiguration},
        content_filter::SCContentFilter,
        output_trait::SCStreamOutputTrait,
        output_type::SCStreamOutputType,
        SCStream,
    },
};
use std::{
    process::Command,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    thread,
    time::Duration,
};

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

/// Handler that tracks sample counts for all output types
#[allow(clippy::struct_field_names)]
struct LeakTestHandler {
    screen_samples: AtomicUsize,
    audio_samples: AtomicUsize,
    #[cfg(feature = "macos_15_0")]
    mic_samples: AtomicUsize,
}

impl LeakTestHandler {
    const fn new() -> Self {
        Self {
            screen_samples: AtomicUsize::new(0),
            audio_samples: AtomicUsize::new(0),
            #[cfg(feature = "macos_15_0")]
            mic_samples: AtomicUsize::new(0),
        }
    }

    fn report(&self) {
        let screen = self.screen_samples.load(Ordering::Relaxed);
        let audio = self.audio_samples.load(Ordering::Relaxed);
        #[cfg(feature = "macos_15_0")]
        let mic = self.mic_samples.load(Ordering::Relaxed);

        #[cfg(feature = "macos_15_0")]
        println!("    Samples: screen={screen}, audio={audio}, mic={mic}");
        #[cfg(not(feature = "macos_15_0"))]
        println!("    Samples: screen={screen}, audio={audio}");
    }
}

impl SCStreamOutputTrait for LeakTestHandler {
    fn did_output_sample_buffer(&self, sample: CMSampleBuffer, of_type: SCStreamOutputType) {
        // Access sample properties to ensure they're valid
        let _timestamp = sample.presentation_timestamp();
        let _duration = sample.duration();

        match of_type {
            SCStreamOutputType::Screen => {
                self.screen_samples.fetch_add(1, Ordering::Relaxed);
            }
            SCStreamOutputType::Audio => {
                self.audio_samples.fetch_add(1, Ordering::Relaxed);
            }
            #[cfg(feature = "macos_15_0")]
            SCStreamOutputType::Microphone => {
                self.mic_samples.fetch_add(1, Ordering::Relaxed);
            }
            #[cfg(not(feature = "macos_15_0"))]
            _ => {}
        }
    }
}

/// Wrapper to share handler across output types
struct SharedHandler(Arc<LeakTestHandler>);

impl SCStreamOutputTrait for SharedHandler {
    fn did_output_sample_buffer(&self, sample: CMSampleBuffer, of_type: SCStreamOutputType) {
        self.0.did_output_sample_buffer(sample, of_type);
    }
}

fn main() {
    // Initialize CoreGraphics first
    init_cg();

    println!("🔍 Memory Leak Detection Test");
    println!("==============================\n");

    let iterations = 3;
    let capture_duration = Duration::from_millis(500);

    println!("Configuration:");
    println!("  • Iterations: {iterations}");
    println!("  • Capture duration per iteration: {capture_duration:?}");
    println!();

    // Test shareable content queries (exercises SCDisplay, SCWindow, SCRunningApplication)
    println!("📋 Testing SCShareableContent queries...");
    test_shareable_content_queries();

    // Test different filter types
    println!("\n📹 Testing different filter configurations...\n");

    for i in 1..=iterations {
        println!("--- Iteration {i}/{iterations} ---\n");

        // Test 1: Display with excluded windows (audio + video)
        println!("  1️⃣  Display filter (exclude windows, audio enabled)");
        test_capture_with_filter(FilterType::DisplayExcludeWindows, &capture_duration);

        // Test 2: Display with included windows
        println!("  2️⃣  Display filter (include windows)");
        test_capture_with_filter(FilterType::DisplayIncludeWindows, &capture_duration);

        // Test 3: Display with excluded apps
        println!("  3️⃣  Display filter (exclude apps)");
        test_capture_with_filter(FilterType::DisplayExcludeApps, &capture_duration);

        // Test 4: Display with included apps
        println!("  4️⃣  Display filter (include apps)");
        test_capture_with_filter(FilterType::DisplayIncludeApps, &capture_duration);

        // Test 5: Single window capture
        println!("  5️⃣  Single window filter");
        test_capture_with_filter(FilterType::SingleWindow, &capture_duration);

        // Test 6: Full config with microphone (macOS 15+)
        #[cfg(feature = "macos_15_0")]
        {
            println!("  6️⃣  Full config (audio + microphone)");
            test_capture_with_filter(FilterType::FullConfigWithMic, &capture_duration);
        }

        println!();
    }

    // Test configuration variations
    println!("⚙️  Testing configuration variations...");
    test_configuration_variations();

    println!("\n🧪 Running leak analysis...\n");

    // Run the macOS leaks command
    let result = check_for_leaks();

    match result {
        LeakResult::NoLeaks => {
            println!("✅ No memory leaks detected!");
        }
        LeakResult::AppleFrameworkLeaksOnly(count) => {
            println!("⚠️  Apple framework leaks detected: {count} leaks (ignored)");
            println!("   These are bugs in Apple's ScreenCaptureKit, not our code.");
            // Don't fail - these are Apple's bugs we can't fix
        }
        LeakResult::LeaksDetected(details) => {
            println!("❌ Memory leaks detected in our code!");
            println!("\nDetails:\n{details}");
            std::process::exit(1);
        }
        LeakResult::Error(msg) => {
            println!("⚠️  Could not run leak check: {msg}");
            std::process::exit(2);
        }
        LeakResult::NotDebuggable => {
            println!("⚠️  Process is not debuggable (security restriction)");
            println!("   To run leak check locally, try one of:");
            println!("   • Run with sudo");
            println!("   • Disable SIP (not recommended for production machines)");
            println!("   • Code sign binary with get-task-allow entitlement");
            // Don't fail CI for this - the memory tests cover the same ground
            println!("\n✅ Memory tests passed (leak check skipped due to security)");
        }
    }
}

#[derive(Clone, Copy)]
enum FilterType {
    DisplayExcludeWindows,
    DisplayIncludeWindows,
    DisplayExcludeApps,
    DisplayIncludeApps,
    SingleWindow,
    #[cfg(feature = "macos_15_0")]
    FullConfigWithMic,
}

/// Test querying shareable content - exercises property access on all types
fn test_shareable_content_queries() {
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("⚠️  Skipping content queries — screen recording permission required.");
            eprintln!(
                "    Grant permission via System Settings → Privacy & Security → Screen Recording."
            );
            eprintln!("    Underlying error: {e:?}");
            return;
        }
    };

    // Test displays
    let displays = content.displays();
    println!("  Found {} display(s)", displays.len());
    for display in &displays {
        let _id = display.display_id();
        let _width = display.width();
        let _height = display.height();
        let _frame = display.frame();
    }

    // Test windows
    let windows = content.windows();
    println!("  Found {} window(s)", windows.len());
    for window in windows.iter().take(10) {
        let _id = window.window_id();
        let _title = window.title();
        let _frame = window.frame();
        let _on_screen = window.is_on_screen();
        let _layer = window.window_layer();
        let _app = window.owning_application();
    }

    // Test applications
    let apps = content.applications();
    println!("  Found {} application(s)", apps.len());
    for app in apps.iter().take(10) {
        let _name = app.application_name();
        let _bundle_id = app.bundle_identifier();
        let _pid = app.process_id();
    }
}

/// Helper to collect window refs
fn collect_window_refs(windows: &[SCWindow], count: usize) -> Vec<&SCWindow> {
    windows.iter().take(count).collect()
}

/// Helper to collect app refs
fn collect_app_refs(apps: &[SCRunningApplication], count: usize) -> Vec<&SCRunningApplication> {
    apps.iter().take(count).collect()
}

/// Test different filter configurations
#[allow(clippy::too_many_lines)]
fn test_capture_with_filter(filter_type: FilterType, duration: &Duration) {
    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!(
                "⚠️  Skipping capture-with-filter test — screen recording permission required."
            );
            eprintln!("    Underlying error: {e:?}");
            return;
        }
    };
    let displays = content.displays();
    let Some(display) = displays.first() else {
        eprintln!("⚠️  No displays available — skipping capture-with-filter test.");
        return;
    };
    let windows = content.windows();
    let apps = content.applications();

    let handler = Arc::new(LeakTestHandler::new());

    let filter = match filter_type {
        FilterType::DisplayExcludeWindows => {
            let exclude = collect_window_refs(&windows, 5);
            SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&exclude)
                .build()
        }
        FilterType::DisplayIncludeWindows => {
            let include = collect_window_refs(&windows, 3);
            SCContentFilter::create()
                .with_display(display)
                .with_including_windows(&include)
                .build()
        }
        FilterType::DisplayExcludeApps => {
            let exclude_apps = collect_app_refs(&apps, 2);
            let except_windows = collect_window_refs(&windows, 1);
            SCContentFilter::create()
                .with_display(display)
                .with_excluding_applications(&exclude_apps, &except_windows)
                .build()
        }
        FilterType::DisplayIncludeApps => {
            let include_apps = collect_app_refs(&apps, 3);
            let except_windows = collect_window_refs(&windows, 1);
            SCContentFilter::create()
                .with_display(display)
                .with_including_applications(&include_apps, &except_windows)
                .build()
        }
        FilterType::SingleWindow => {
            let window = windows
                .iter()
                .find(|w| w.is_on_screen())
                .unwrap_or(&windows[0]);
            SCContentFilter::create().with_window(window).build()
        }
        #[cfg(feature = "macos_15_0")]
        FilterType::FullConfigWithMic => SCContentFilter::create()
            .with_display(display)
            .with_excluding_windows(&[])
            .build(),
    };

    // Test filter properties (macOS 14.0+)
    #[cfg(feature = "macos_14_2")]
    let _rect = filter.content_rect();
    #[cfg(feature = "macos_14_0")]
    let _scale = filter.point_pixel_scale();

    // Configure based on filter type
    let config = match filter_type {
        #[cfg(feature = "macos_15_0")]
        FilterType::FullConfigWithMic => SCStreamConfiguration::new()
            .with_width(320)
            .with_height(240)
            .with_pixel_format(PixelFormat::BGRA)
            .with_captures_audio(true)
            .with_captures_microphone(true)
            .with_sample_rate(48000)
            .with_channel_count(2),
        _ => SCStreamConfiguration::new()
            .with_width(320)
            .with_height(240)
            .with_pixel_format(PixelFormat::BGRA)
            .with_captures_audio(true)
            .with_sample_rate(24000)
            .with_channel_count(2),
    };

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

    // Add output handlers for all types using SharedHandler wrapper
    stream.add_output_handler(SharedHandler(handler.clone()), SCStreamOutputType::Screen);
    stream.add_output_handler(SharedHandler(handler.clone()), SCStreamOutputType::Audio);

    #[cfg(feature = "macos_15_0")]
    if matches!(filter_type, FilterType::FullConfigWithMic) {
        stream.add_output_handler(
            SharedHandler(handler.clone()),
            SCStreamOutputType::Microphone,
        );
    }

    if let Err(e) = stream.start_capture() {
        eprintln!("    ⚠️  Failed to start: {e}");
        return;
    }

    thread::sleep(*duration);

    if let Err(e) = stream.stop_capture() {
        eprintln!("    ⚠️  Failed to stop: {e}");
    }

    handler.report();
    drop(stream);
    println!("    ✓ Done");
}

/// Test various configuration settings
fn test_configuration_variations() {
    let configs = [
        // Minimal config
        SCStreamConfiguration::new().with_width(64).with_height(64),
        // Different pixel formats
        SCStreamConfiguration::new()
            .with_width(128)
            .with_height(128)
            .with_pixel_format(PixelFormat::YCbCr_420v),
        // With source/destination rects
        SCStreamConfiguration::new()
            .with_width(256)
            .with_height(256)
            .with_source_rect(CGRect::new(0.0, 0.0, 100.0, 100.0))
            .with_destination_rect(CGRect::new(0.0, 0.0, 256.0, 256.0))
            .with_scales_to_fit(true),
        // High quality config
        SCStreamConfiguration::new()
            .with_width(1920)
            .with_height(1080)
            .with_shows_cursor(true)
            .with_queue_depth(8),
        // Audio only config
        SCStreamConfiguration::new()
            .with_width(100)
            .with_height(100)
            .with_captures_audio(true)
            .with_sample_rate(48000)
            .with_channel_count(2),
    ];

    println!("  Testing {} configuration variations...", configs.len());

    for (i, _config) in configs.iter().enumerate() {
        // Just create and drop the configs to test for leaks
        println!("    Config {}: ✓", i + 1);
    }
}

enum LeakResult {
    NoLeaks,
    AppleFrameworkLeaksOnly(usize),
    LeaksDetected(String),
    NotDebuggable,
    Error(String),
}

fn check_for_leaks() -> LeakResult {
    let pid = std::process::id();

    let output = match Command::new("leaks")
        .args([pid.to_string(), "-c".to_string()])
        .output()
    {
        Ok(output) => output,
        Err(e) => return LeakResult::Error(format!("Failed to execute leaks command: {e}")),
    };

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Check for security restriction (process not debuggable)
    if stderr.contains("not debuggable") || stderr.contains("security restrictions") {
        return LeakResult::NotDebuggable;
    }

    // Print raw output for debugging
    if !stdout.is_empty() {
        println!("leaks stdout:\n{stdout}");
    }
    if !stderr.is_empty() {
        println!("leaks stderr:\n{stderr}");
    }

    // Check for no leaks
    if stdout.contains("0 leaks for 0 total leaked bytes") {
        return LeakResult::NoLeaks;
    }

    // Parse leak count from output like "Process 21326: 56 leaks for 2688 total leaked bytes"
    let leak_count = stdout
        .lines()
        .find(|line| line.contains("leaks for") && line.contains("total leaked bytes"))
        .and_then(|line| {
            // Find the number before "leaks for"
            line.split("leaks for")
                .next()
                .and_then(|prefix| prefix.split_whitespace().last())
                .and_then(|s| s.parse::<usize>().ok())
        })
        .unwrap_or(0);

    // Check if all leaks are from Apple frameworks (not our code)
    let apple_framework_leaks = stdout.contains("CMCapture")
        || stdout.contains("FigRemoteOperationReceiver")
        || stdout.contains("SCStream(SCContentSharing)")
        || stdout.contains("CoreMedia")
        || stdout.contains("VideoToolbox");

    let our_code_leaks = stdout.contains("screencapturekit");

    if apple_framework_leaks && !our_code_leaks {
        return LeakResult::AppleFrameworkLeaksOnly(leak_count);
    }

    LeakResult::LeaksDetected(stdout.to_string())
}