screencapturekit 1.4.2

Safe Rust bindings for Apple's ScreenCaptureKit framework - screen and audio capture on macOS
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
<div align="center">
  <h1>ScreenCaptureKit-rs</h1>
</div>

<div align="center"><p>
    <a href="https://crates.io/crates/screencapturekit"><img alt="Crates.io" src="https://img.shields.io/crates/v/screencapturekit?style=for-the-badge&logo=rust&color=C9CBFF&logoColor=D9E0EE&labelColor=302D41" /></a>
    <a href="https://doom-fish.github.io/screencapturekit-rs/screencapturekit/"><img alt="Documentation" src="https://img.shields.io/badge/docs-GitHub%20Pages-blue?style=for-the-badge&logo=gitbook&color=8bd5ca&logoColor=D9E0EE&labelColor=302D41" /></a>
    <a href="https://github.com/doom-fish/screencapturekit-rs#license"><img alt="License" src="https://img.shields.io/crates/l/screencapturekit?style=for-the-badge&logo=apache&color=ee999f&logoColor=D9E0EE&labelColor=302D41" /></a>
    <a href="https://github.com/doom-fish/screencapturekit-rs/actions"><img alt="Build Status" src="https://img.shields.io/github/actions/workflow/status/doom-fish/screencapturekit-rs/ci.yml?branch=main&style=for-the-badge&logo=github&color=c69ff5&logoColor=D9E0EE&labelColor=302D41" /></a>
    <a href="https://github.com/doom-fish/screencapturekit-rs/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/doom-fish/screencapturekit-rs?style=for-the-badge&logo=starship&color=F5E0DC&logoColor=D9E0EE&labelColor=302D41" /></a>
</p></div>

> **๐Ÿ’ผ Looking for a hosted desktop recording API?**  
> Check out [Recall.ai]https://www.recall.ai/product/desktop-recording-sdk?utm_source=github&utm_medium=sponsorship&utm_campaign=screencapturekit-rs - an API for recording Zoom, Google Meet, Microsoft Teams, in-person meetings, and more.

Safe, idiomatic Rust bindings for Apple's [ScreenCaptureKit](https://developer.apple.com/documentation/screencapturekit) framework.

Capture screen content, windows, and applications with high performance and low overhead on macOS 12.3+.




## ๐Ÿ“‘ Table of Contents

- [Features]#-features
- [Installation]#-installation
- [Quick Start]#-quick-start
- [Key Concepts]#-key-concepts
- [Feature Flags]#-feature-flags
- [API Overview]#-api-overview
- [Examples]#-examples
- [Testing]#-testing
- [Architecture]#-architecture
- [Troubleshooting]#-troubleshooting
- [Platform Requirements]#-platform-requirements
- [Contributing]#-contributing
- [License]#-license

## โœจ Features

- ๐ŸŽฅ **Screen & Window Capture** - Capture displays, windows, or specific applications
- ๐Ÿ”Š **Audio Capture** - Capture system audio and microphone input
- โšก **Real-time Processing** - High-performance frame callbacks with custom dispatch queues
- ๐Ÿ—๏ธ **Builder Pattern API** - Clean, type-safe configuration with `::builder()`
- ๐Ÿ”„ **Async Support** - Runtime-agnostic async API (works with Tokio, async-std, smol, etc.)
- ๐ŸŽจ **IOSurface Access** - Zero-copy GPU texture access for Metal/OpenGL
- ๐Ÿ›ก๏ธ **Memory Safe** - Proper reference counting and leak-free by design
- ๐Ÿ“ฆ **Zero Dependencies** - No runtime dependencies (only dev dependencies for examples)



https://github.com/user-attachments/assets/8a272c48-7ec3-4132-9111-4602b4fa991d

## ๐Ÿ“ฆ Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
screencapturekit = "1"
```

For async support:

```toml
[dependencies]
screencapturekit = { version = "1", features = ["async"] }
```

For latest macOS features:

```toml
[dependencies]
screencapturekit = { version = "1", features = ["macos_26_0"] }
```

## ๐Ÿš€ Quick Start

### Basic Screen Capture

```rust
use screencapturekit::prelude::*;

struct Handler;

impl SCStreamOutputTrait for Handler {
    fn did_output_sample_buffer(&self, sample: CMSampleBuffer, _type: SCStreamOutputType) {
        println!("๐Ÿ“น Received frame at {:?}", sample.presentation_timestamp());
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Get available displays
    let content = SCShareableContent::get()?;
    let display = &content.displays()[0];
    
    // Configure capture
    let filter = SCContentFilter::builder()
        .display(display)
        .exclude_windows(&[])
        .build();
    
    let config = SCStreamConfiguration::new()
        .with_width(1920)
        .with_height(1080)
        .with_pixel_format(PixelFormat::BGRA);
    
    // Start streaming
    let mut stream = SCStream::new(&filter, &config);
    stream.add_output_handler(Handler, SCStreamOutputType::Screen);
    stream.start_capture()?;
    
    // Capture runs in background...
    std::thread::sleep(std::time::Duration::from_secs(5));
    
    stream.stop_capture()?;
    Ok(())
}
```

### Async Capture

```rust
use screencapturekit::async_api::{AsyncSCShareableContent, AsyncSCStream};
use screencapturekit::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Get content asynchronously
    let content = AsyncSCShareableContent::get().await?;
    let display = &content.displays()[0];
    
    // Create filter and config
    let filter = SCContentFilter::builder()
        .display(display)
        .exclude_windows(&[])
        .build();
    
    let config = SCStreamConfiguration::new()
        .with_width(1920)
        .with_height(1080);
    
    // Create async stream with frame buffer
    let stream = AsyncSCStream::new(&filter, &config, 30, SCStreamOutputType::Screen);
    stream.start_capture()?;
    
    // Capture frames asynchronously
    for _ in 0..10 {
        if let Some(frame) = stream.next().await {
            println!("๐Ÿ“น Got frame!");
        }
    }
    
    stream.stop_capture()?;
    Ok(())
}
```

### Window Capture with Audio

```rust
use screencapturekit::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let content = SCShareableContent::get()?;
    
    // Find a specific window
    let window = content.windows()
        .iter()
        .find(|w| w.title().as_deref() == Some("Safari"))
        .ok_or("Safari window not found")?;
    
    // Capture window with audio
    let filter = SCContentFilter::builder()
        .window(window)
        .build();
    
    let config = SCStreamConfiguration::new()
        .with_width(1920)
        .with_height(1080)
        .with_captures_audio(true)
        .with_sample_rate(48000)
        .with_channel_count(2);
    
    let mut stream = SCStream::new(&filter, &config);
    // Add handlers...
    stream.start_capture()?;
    
    Ok(())
}
```

### Content Picker (macOS 14.0+)

Use the system picker UI to let users choose what to capture:

```rust
use screencapturekit::content_sharing_picker::*;
use screencapturekit::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = SCContentSharingPickerConfiguration::new();
    
    // Show picker - callback receives result when user selects or cancels
    SCContentSharingPicker::show(&config, |outcome| {
        match outcome {
            SCPickerOutcome::Picked(result) => {
                // Get dimensions from the picked content
                let (width, height) = result.pixel_size();
                println!("Selected: {}x{} (scale: {})", width, height, result.scale());
                
                let stream_config = SCStreamConfiguration::new()
                    .with_width(width)
                    .with_height(height);
                
                // Get filter for streaming
                let filter = result.filter();
                let mut stream = SCStream::new(&filter, &stream_config);
                // ...
            }
            SCPickerOutcome::Cancelled => println!("User cancelled"),
            SCPickerOutcome::Error(e) => eprintln!("Error: {}", e),
        }
    });
    
    Ok(())
}
```

### Async Content Picker (macOS 14.0+)

Use the async version in async contexts to avoid blocking:

```rust
use screencapturekit::async_api::AsyncSCContentSharingPicker;
use screencapturekit::content_sharing_picker::*;
use screencapturekit::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = SCContentSharingPickerConfiguration::new();
    
    // Async picker - doesn't block the executor
    match AsyncSCContentSharingPicker::show(&config).await {
        SCPickerOutcome::Picked(result) => {
            let (width, height) = result.pixel_size();
            println!("Selected: {}x{}", width, height);
            
            let filter = result.filter();
            // Use filter with stream...
        }
        SCPickerOutcome::Cancelled => println!("User cancelled"),
        SCPickerOutcome::Error(e) => eprintln!("Error: {}", e),
    }
    
    Ok(())
}
```

## ๐ŸŽฏ Key Concepts

### Builder Pattern

Different types use slightly different patterns:

```rust
// Content filters use .builder() with .build()
let filter = SCContentFilter::builder()
    .display(&display)
    .exclude_windows(&windows)
    .build();

// Stream configuration uses ::new() with .with_*() chainable methods
let config = SCStreamConfiguration::new()
    .with_width(1920)
    .with_height(1080)
    .with_pixel_format(PixelFormat::BGRA)
    .with_captures_audio(true);

// Options for content retrieval
let content = SCShareableContent::with_options()
    .on_screen_windows_only(true)
    .exclude_desktop_windows(true)
    .get()?;
```

### Custom Dispatch Queues

Control callback threading with custom dispatch queues:

```rust
use screencapturekit::dispatch_queue::{DispatchQueue, DispatchQoS};

let queue = DispatchQueue::new("com.myapp.capture", DispatchQoS::UserInteractive);

stream.add_output_handler_with_queue(
    my_handler,
    SCStreamOutputType::Screen,
    Some(&queue)
);
```

**QoS Levels:**
- `Background` - Maintenance tasks
- `Utility` - Long-running tasks
- `Default` - Standard priority
- `UserInitiated` - User-initiated tasks
- `UserInteractive` - UI updates (highest priority)

### IOSurface Access

Zero-copy GPU texture access:

```rust
impl SCStreamOutputTrait for Handler {
    fn did_output_sample_buffer(&self, sample: CMSampleBuffer, _type: SCStreamOutputType) {
        if let Some(pixel_buffer) = sample.image_buffer() {
            if let Some(surface) = pixel_buffer.iosurface() {
                let width = surface.width();
                let height = surface.height();
                
                // Use with Metal/OpenGL...
                println!("IOSurface: {}x{}", width, height);
            }
        }
    }
}
```

### Metal Integration

Built-in Metal types for hardware-accelerated rendering without external crates:

```rust
use screencapturekit::output::metal::{
    MetalDevice, MetalLayer, MetalRenderPassDescriptor, MetalRenderPipelineDescriptor,
    MTLLoadAction, MTLStoreAction, MTLPrimitiveType, MTLPixelFormat,
    Uniforms, SHADER_SOURCE,
};
use screencapturekit::output::CVPixelBufferIOSurface;

// Get the system default Metal device
let device = MetalDevice::system_default().expect("No Metal device");
let command_queue = device.create_command_queue().unwrap();

// Compile built-in shaders (supports BGRA, YCbCr, UI overlays)
let library = device.create_library_with_source(SHADER_SOURCE)?;

// Create render pipeline for textured rendering
let vert_fn = library.get_function("vertex_fullscreen").unwrap();
let frag_fn = library.get_function("fragment_textured").unwrap();
let pipeline_desc = MetalRenderPipelineDescriptor::new();
pipeline_desc.set_vertex_function(&vert_fn);
pipeline_desc.set_fragment_function(&frag_fn);
pipeline_desc.set_color_attachment_pixel_format(0, MTLPixelFormat::BGRA8Unorm);
let pipeline = device.create_render_pipeline_state(&pipeline_desc).unwrap();

// In your frame handler - create textures and render
impl SCStreamOutputTrait for Handler {
    fn did_output_sample_buffer(&self, sample: CMSampleBuffer, _type: SCStreamOutputType) {
        if let Some(pixel_buffer) = sample.image_buffer() {
            if let Some(surface) = pixel_buffer.iosurface() {
                // Zero-copy texture creation from IOSurface
                if let Some(textures) = surface.create_metal_textures(&device) {
                    // Create uniforms for aspect-ratio-preserving rendering
                    let uniforms = Uniforms::from_captured_textures(
                        viewport_width, viewport_height, &textures
                    );
                    let uniform_buffer = device.create_buffer_with_data(&uniforms).unwrap();
                    
                    // Render to a CAMetalLayer drawable
                    let drawable = layer.next_drawable().unwrap();
                    let cmd_buffer = command_queue.command_buffer().unwrap();
                    
                    let render_pass = MetalRenderPassDescriptor::new();
                    render_pass.set_color_attachment_texture(0, &drawable.texture());
                    render_pass.set_color_attachment_load_action(0, MTLLoadAction::Clear);
                    render_pass.set_color_attachment_store_action(0, MTLStoreAction::Store);
                    
                    let encoder = cmd_buffer.render_command_encoder(&render_pass).unwrap();
                    encoder.set_render_pipeline_state(&pipeline);
                    encoder.set_vertex_buffer(&uniform_buffer, 0, 0);
                    encoder.set_fragment_texture(&textures.plane0, 0);
                    if let Some(ref plane1) = textures.plane1 {
                        encoder.set_fragment_texture(plane1, 1);  // CbCr for YCbCr
                    }
                    encoder.draw_primitives(MTLPrimitiveType::TriangleStrip, 0, 4);
                    encoder.end_encoding();
                    
                    cmd_buffer.present_drawable(&drawable);
                    cmd_buffer.commit();
                }
            }
        }
    }
}
```

**Built-in Shader Functions:**
- `vertex_fullscreen` - Aspect-ratio-preserving fullscreen quad
- `fragment_textured` - BGRA/L10R single-texture rendering
- `fragment_ycbcr` - YCbCr biplanar (420v/420f) to RGB conversion
- `vertex_colored` / `fragment_colored` - UI overlay rendering

**Metal Types:**
- `MetalDevice`, `MetalCommandQueue`, `MetalCommandBuffer`
- `MetalTexture`, `MetalBuffer`, `MetalLayer`, `MetalDrawable`
- `MetalRenderPipelineState`, `MetalRenderPassDescriptor`
- `CapturedTextures<T>` - Multi-plane texture container (Y + CbCr for YCbCr formats)

## ๐ŸŽ›๏ธ Feature Flags

### Core Features

| Feature | Description |
|---------|-------------|
| `async` | Runtime-agnostic async API (works with any executor) |

### macOS Version Features

Feature flags enable APIs for specific macOS versions. They are cumulative (enabling `macos_15_0` enables all earlier versions).

| Feature | macOS | APIs Enabled |
|---------|-------|--------------|
| `macos_13_0` | 13.0 Ventura | Audio capture, synchronization clock |
| `macos_14_0` | 14.0 Sonoma | Content picker, screenshots, content info |
| `macos_14_2` | 14.2 | Menu bar capture, child windows, presenter overlay |
| `macos_14_4` | 14.4 | Current process shareable content |
| `macos_15_0` | 15.0 Sequoia | Recording output, HDR capture, microphone |
| `macos_15_2` | 15.2 | Screenshot in rect, stream active/inactive delegates |
| `macos_26_0` | 26.0 | Advanced screenshot config, HDR screenshot output |

### Version-Specific Example

```rust
let mut config = SCStreamConfiguration::new()
    .with_width(1920)
    .with_height(1080);

#[cfg(feature = "macos_13_0")]
config.set_should_be_opaque(true);

#[cfg(feature = "macos_14_2")]
{
    config.set_ignores_shadows_single_window(true);
    config.set_includes_child_windows(false);
}
```

## ๐Ÿ“š API Overview

### Core Types

| Type | Description |
|------|-------------|
| [`SCShareableContent`] | Query available displays, windows, and applications |
| [`SCContentFilter`] | Define what to capture (display/window/app) |
| [`SCStreamConfiguration`] | Configure resolution, format, audio, etc. |
| [`SCStream`] | Main capture stream with output handlers |
| [`CMSampleBuffer`] | Frame data with timing and metadata |

[`SCShareableContent`]: https://doom-fish.github.io/screencapturekit-rs/screencapturekit/shareable_content/struct.SCShareableContent.html
[`SCContentFilter`]: https://doom-fish.github.io/screencapturekit-rs/screencapturekit/stream/content_filter/struct.SCContentFilter.html
[`SCStreamConfiguration`]: https://doom-fish.github.io/screencapturekit-rs/screencapturekit/stream/configuration/struct.SCStreamConfiguration.html
[`SCStream`]: https://doom-fish.github.io/screencapturekit-rs/screencapturekit/stream/sc_stream/struct.SCStream.html
[`CMSampleBuffer`]: https://doom-fish.github.io/screencapturekit-rs/screencapturekit/cm/struct.CMSampleBuffer.html

### Async API (requires `async` feature)

| Type | Description |
|------|-------------|
| `AsyncSCShareableContent` | Async content queries |
| `AsyncSCStream` | Async stream with frame iteration |
| `AsyncSCScreenshotManager` | Async screenshot capture (macOS 14.0+) |
| `AsyncSCContentSharingPicker` | Async content picker UI (macOS 14.0+) |

### Display & Window Types

| Type | Description |
|------|-------------|
| `SCDisplay` | Display information (resolution, ID, frame) |
| `SCWindow` | Window information (title, bounds, owner, layer) |
| `SCRunningApplication` | Application information (name, bundle ID, PID) |

### Media Types

| Type | Description |
|------|-------------|
| `CMSampleBuffer` | Sample buffer with timing and attachments |
| `CMTime` | High-precision timestamps with timescale |
| `IOSurface` | GPU-backed pixel buffers for zero-copy access |
| `CGImage` | Core Graphics images for screenshots |
| `CVPixelBuffer` | Core Video pixel buffer with lock guards |

### Metal Types (`metal` module)

| Type | Description |
|------|-------------|
| `MetalDevice` | Metal GPU device wrapper |
| `MetalTexture` | Metal texture with automatic retain/release |
| `MetalBuffer` | Vertex/uniform buffer |
| `MetalCommandQueue` / `MetalCommandBuffer` | Command submission |
| `MetalLayer` | `CAMetalLayer` for window rendering |
| `MetalRenderPipelineState` | Compiled render pipeline |
| `CapturedTextures<T>` | Multi-plane texture container (Y + CbCr for YCbCr) |
| `Uniforms` | Shader uniform structure matching `SHADER_SOURCE` |

### Configuration Types

| Type | Description |
|------|-------------|
| `PixelFormat` | BGRA, YCbCr420v, YCbCr420f, l10r (10-bit) |
| `SCPresenterOverlayAlertSetting` | Privacy alert behavior |
| `SCCaptureDynamicRange` | HDR/SDR modes (macOS 15.0+) |
| `SCScreenshotConfiguration` | Advanced screenshot config (macOS 26.0+) |
| `SCScreenshotDynamicRange` | SDR/HDR screenshot output (macOS 26.0+) |

## ๐Ÿƒ Examples

The [`examples/`](examples/) directory contains focused API demonstrations:

### Quick Start (Numbered by Complexity)
1. **`01_basic_capture.rs`** - Simplest screen capture
2. **`02_window_capture.rs`** - Capture specific windows
3. **`03_audio_capture.rs`** - Audio + video capture
4. **`04_pixel_access.rs`** - Read pixel data with `std::io::Cursor`
5. **`05_screenshot.rs`** - Single screenshot, HDR capture (macOS 14.0+, 26.0+)
6. **`06_iosurface.rs`** - Zero-copy GPU buffers
7. **`07_list_content.rs`** - List available content
8. **`08_async.rs`** - Async/await API with multiple examples
9. **`09_closure_handlers.rs`** - Closure-based handlers and delegates
10. **`10_recording_output.rs`** - Direct video file recording (macOS 15.0+)
11. **`11_content_picker.rs`** - System UI for content selection (macOS 14.0+)
12. **`12_stream_updates.rs`** - Dynamic config/filter updates
13. **`13_advanced_config.rs`** - HDR, presets, microphone (macOS 15.0+)
14. **`14_app_capture.rs`** - Application-based filtering
15. **`15_memory_leak_check.rs`** - Memory leak detection with `leaks`
16. **`16_full_metal_app/`** - Full Metal GUI application (macOS 14.0+)
17. **`17_metal_textures.rs`** - Metal texture creation from IOSurface

See [`examples/README.md`](examples/README.md) for detailed descriptions.

Run an example:

```bash
# Basic examples
cargo run --example 01_basic_capture
cargo run --example 09_closure_handlers
cargo run --example 12_stream_updates
cargo run --example 14_app_capture
cargo run --example 17_metal_textures

# Feature-gated examples
cargo run --example 05_screenshot --features macos_14_0
cargo run --example 08_async --features async
cargo run --example 10_recording_output --features macos_15_0
cargo run --example 11_content_picker --features macos_14_0
cargo run --example 13_advanced_config --features macos_15_0
cargo run --example 16_full_metal_app --features macos_14_0
```

## ๐Ÿงช Testing

### Run Tests

```bash
# All tests
cargo test

# With features
cargo test --features async
cargo test --all-features

# Specific test
cargo test test_stream_configuration
```

### Linting

```bash
cargo clippy --all-features -- -D warnings
cargo fmt --check
```

## ๐Ÿ—๏ธ Architecture

### Module Organization

```
screencapturekit/
โ”œโ”€โ”€ cm/                     # Core Media (CMSampleBuffer, CMTime, CVPixelBuffer)
โ”œโ”€โ”€ cg/                     # Core Graphics (CGRect, CGImage)
โ”œโ”€โ”€ stream/                 # Stream management
โ”‚   โ”œโ”€โ”€ configuration/      # SCStreamConfiguration
โ”‚   โ”œโ”€โ”€ content_filter/     # SCContentFilter
โ”‚   โ””โ”€โ”€ sc_stream/          # SCStream
โ”œโ”€โ”€ shareable_content/      # SCShareableContent, SCDisplay, SCWindow
โ”œโ”€โ”€ output/                 # Frame buffers and pixel data
โ”œโ”€โ”€ dispatch_queue/         # Custom dispatch queues
โ”œโ”€โ”€ error/                  # Error types
โ”œโ”€โ”€ screenshot_manager/     # SCScreenshotManager (macOS 14.0+)
โ”œโ”€โ”€ content_sharing_picker/ # SCContentSharingPicker (macOS 14.0+)
โ”œโ”€โ”€ recording_output/       # SCRecordingOutput (macOS 15.0+)
โ”œโ”€โ”€ async_api/              # Async wrappers (feature = "async")
โ”œโ”€โ”€ utils/                  # FFI strings, FourCharCode utilities
โ””โ”€โ”€ prelude/                # Convenience re-exports
```

### Memory Management

- **Reference Counting** - Proper CFRetain/CFRelease for all CoreFoundation types
- **RAII** - Automatic cleanup in Drop implementations
- **Thread Safety** - Safe to share across threads (where supported)
- **Leak Free** - Comprehensive leak tests ensure no memory leaks

## โ“ Troubleshooting

### Permission Denied / No Displays Found

**Problem**: `SCShareableContent::get()` returns an error or empty lists.

**Solution**: Grant screen recording permission:
1. Open **System Preferences** โ†’ **Privacy & Security** โ†’ **Screen Recording**
2. Add your app or Terminal to the list
3. Restart your application

For development, you may need to add Terminal.app to the allowed list.

### Entitlements for App Store / Notarization

**Problem**: App crashes or permissions fail after notarization.

**Solution**: Add required entitlements to your `entitlements.plist`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.screen-capture</key>
    <true/>
</dict>
</plist>
```

### Black Frames / No Video Data

**Problem**: Frames are received but contain no visible content.

**Solutions**:
1. Ensure the captured window/display is visible (not minimized)
2. Check that `pixel_format` matches your processing expectations
3. Verify the content filter includes the correct display/window
4. On Apple Silicon, ensure proper GPU access

### Audio Capture Not Working

**Problem**: Audio samples not received or empty.

**Solutions**:
1. Enable audio capture: `.with_captures_audio(true)`
2. Add an audio output handler: `stream.add_output_handler(handler, SCStreamOutputType::Audio)`
3. Verify `sample_rate` and `channel_count` are set correctly

### Build Errors

**Problem**: Compilation fails with Swift bridge errors.

**Solutions**:
1. Ensure Xcode Command Line Tools are installed: `xcode-select --install`
2. Clean and rebuild: `cargo clean && cargo build`
3. Check that you're on macOS (this crate is macOS-only)

## ๐Ÿ”ง Platform Requirements

- **macOS 12.3+** (Monterey) - Base ScreenCaptureKit support
- **macOS 13.0+** (Ventura) - Audio capture, synchronization clock
- **macOS 14.0+** (Sonoma) - Content picker, screenshots, content info
- **macOS 15.0+** (Sequoia) - Recording output, HDR capture, microphone
- **macOS 26.0+** (Tahoe) - Advanced screenshot config, HDR screenshot output

### Screen Recording Permission

Screen recording requires explicit user permission. For development:
- Terminal/IDE must be in **System Preferences** โ†’ **Privacy & Security** โ†’ **Screen Recording**

For distribution:
- Add `NSScreenCaptureUsageDescription` to your `Info.plist`
- Sign with appropriate entitlements for notarization

## ๐Ÿค Contributing

Contributions welcome! Please:

1. Follow existing code patterns (builder pattern with `::new()` and `.with_*()` methods)
2. Add tests for new functionality
3. Run `cargo test` and `cargo clippy`
4. Update documentation

## ๐Ÿ‘ฅ Contributors

Thanks to everyone who has contributed to this project!

- [Per Johansson](https://github.com/doom-fish) - Maintainer
- [Iason Paraskevopoulos](https://github.com/iasparaskev)
- [Kris Krolak](https://github.com/kriskrolak)
- [Tokuhiro Matsuno](https://github.com/tokuhirom)
- [Pranav Joglekar](https://github.com/pranavj1001)
- [Alex Jiao](https://github.com/uohzxela)
- [Charles](https://github.com/aizukanne)
- [bigduu](https://github.com/bigduu)

## ๐Ÿ“„ License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.