-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy path14_app_capture.rs
More file actions
213 lines (185 loc) · 6.67 KB
/
Copy path14_app_capture.rs
File metadata and controls
213 lines (185 loc) · 6.67 KB
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
//! Application-Based Capture
//!
//! Demonstrates capturing specific applications.
//! This example shows:
//! - Filtering by application
//! - Including/excluding specific apps
//! - Capturing multiple applications
//!
//! Run with: `cargo run --example 14_app_capture --features macos_14_0`
//!
//! ## Performance note
//!
//! The "list app + count its windows" pattern at the top is O(apps × windows)
//! — with the per-element accessor pattern that's `apps × windows × 2` FFI
//! calls (`.owning_application()` + `.process_id()` per window). On a
//! 36-app / 220-window system that's ~16k FFI calls just to print the
//! header. We use [`SCShareableContent::snapshot`] instead, which fetches
//! every owning-app index in a single batched FFI round-trip and lets us
//! count windows per app in pure Rust (`Counter` over snapshot rows).
use screencapturekit::prelude::*;
use screencapturekit::shareable_content::{
ApplicationSnapshot, SCRunningApplication, WindowSnapshot,
};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
type ExampleResult = Result<(), Box<dyn std::error::Error>>;
struct FrameCounter {
count: Arc<AtomicUsize>,
}
impl SCStreamOutputTrait for FrameCounter {
fn did_output_sample_buffer(&self, _sample: CMSampleBuffer, of_type: SCStreamOutputType) {
if matches!(of_type, SCStreamOutputType::Screen) {
let n = self.count.fetch_add(1, Ordering::Relaxed);
if n % 30 == 0 {
println!("📹 Frame {n}");
}
}
}
}
fn main() -> ExampleResult {
println!("📱 Application-Based Capture\n");
let content = SCShareableContent::get()?;
let snapshot = content
.snapshot()
.ok_or("Could not collect content snapshot")?;
if snapshot.displays.is_empty() {
return Err("No displays found".into());
}
print_running_applications(&snapshot.applications, &snapshot.windows);
let Some(target_idx) = select_target_app(&snapshot.applications) else {
println!("⚠️ No applications found");
return Ok(());
};
let app_snap = &snapshot.applications[target_idx];
println!(
"\n🎯 Target: {} ({})",
app_snap.application_name, app_snap.bundle_identifier
);
let live_apps = content.applications();
let live_displays = content.displays();
let display = live_displays.first().ok_or("display vanished")?;
let live_app = find_live_app(&live_apps, app_snap.process_id)?;
let include_filter = demo_single_app_filters(display, live_app, app_snap);
demo_multi_app_filter(
display,
&live_apps,
&snapshot.applications,
&snapshot.windows,
);
run_capture_demo(&include_filter, &app_snap.application_name)?;
Ok(())
}
fn print_running_applications(app_snaps: &[ApplicationSnapshot], window_snaps: &[WindowSnapshot]) {
let mut windows_per_app: HashMap<usize, usize> = HashMap::new();
for window in window_snaps {
if let Some(idx) = window.owning_app_index {
*windows_per_app.entry(idx).or_insert(0) += 1;
}
}
println!("📋 Running Applications:");
for (i, app) in app_snaps.iter().take(10).enumerate() {
let window_count = windows_per_app.get(&i).copied().unwrap_or(0);
println!(
" {}. {} (PID: {}, Windows: {})",
i + 1,
app.application_name,
app.process_id,
window_count
);
}
}
fn select_target_app(app_snaps: &[ApplicationSnapshot]) -> Option<usize> {
app_snaps
.iter()
.position(|app| app.application_name.contains("Finder"))
.or(if app_snaps.is_empty() { None } else { Some(0) })
}
fn find_live_app(
live_apps: &[SCRunningApplication],
process_id: i32,
) -> Result<&SCRunningApplication, Box<dyn std::error::Error>> {
live_apps
.iter()
.find(|app| app.process_id() == process_id)
.ok_or_else(|| "live app vanished between snapshot and lookup".into())
}
fn demo_single_app_filters(
display: &SCDisplay,
live_app: &SCRunningApplication,
app_snap: &ApplicationSnapshot,
) -> SCContentFilter {
println!("\n📦 Option A: Include specific application");
let include_filter = SCContentFilter::create()
.with_display(display)
.with_including_applications(&[live_app], &[])
.build();
println!(
" Filter created: include only {}",
app_snap.application_name
);
println!("\n📦 Option B: Exclude specific application");
let _exclude_filter = SCContentFilter::create()
.with_display(display)
.with_excluding_applications(&[live_app], &[])
.build();
println!(" Filter created: exclude {}", app_snap.application_name);
include_filter
}
fn demo_multi_app_filter(
display: &SCDisplay,
live_apps: &[SCRunningApplication],
app_snaps: &[ApplicationSnapshot],
window_snaps: &[WindowSnapshot],
) {
println!("\n📦 Option C: Multiple applications");
let visible_app_indices: Vec<usize> = (0..app_snaps.len())
.filter(|i| {
window_snaps
.iter()
.any(|window| window.is_on_screen && window.owning_app_index == Some(*i))
})
.take(3)
.collect();
let multi_apps: Vec<&_> = visible_app_indices
.iter()
.filter_map(|i| {
let pid = app_snaps[*i].process_id;
live_apps.iter().find(|app| app.process_id() == pid)
})
.collect();
if !multi_apps.is_empty() {
let _multi_filter = SCContentFilter::create()
.with_display(display)
.with_including_applications(&multi_apps, &[])
.build();
println!(" Filter created for {} apps:", multi_apps.len());
for &i in &visible_app_indices {
println!(" • {}", app_snaps[i].application_name);
}
}
}
fn run_capture_demo(include_filter: &SCContentFilter, app_name: &str) -> ExampleResult {
println!("\n▶️ Starting capture (include filter)...");
let config = SCStreamConfiguration::new()
.with_width(1920)
.with_height(1080)
.with_pixel_format(PixelFormat::BGRA);
let count = Arc::new(AtomicUsize::new(0));
let handler = FrameCounter {
count: Arc::clone(&count),
};
let mut stream = SCStream::new(include_filter, &config);
stream.add_output_handler(handler, SCStreamOutputType::Screen);
stream.start_capture()?;
std::thread::sleep(std::time::Duration::from_secs(3));
stream.stop_capture()?;
println!("\n⏹️ Capture stopped");
println!(
"✅ Captured {} frames of {}",
count.load(Ordering::Relaxed),
app_name
);
Ok(())
}