-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathrecording.rs
More file actions
245 lines (215 loc) · 7.73 KB
/
Copy pathrecording.rs
File metadata and controls
245 lines (215 loc) · 7.73 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
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
//! Recording capture logic (macOS 15.0+)
#[cfg(feature = "macos_15_0")]
use screencapturekit::recording_output::{
RecordingCallbacks, SCRecordingOutput, SCRecordingOutputCodec, SCRecordingOutputConfiguration,
SCRecordingOutputFileType,
};
#[cfg(feature = "macos_15_0")]
use screencapturekit::stream::sc_stream::SCStream;
#[cfg(feature = "macos_15_0")]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "macos_15_0")]
use std::sync::{Arc, Condvar, Mutex};
/// Recording configuration state
#[cfg(feature = "macos_15_0")]
#[derive(Debug, Clone)]
pub struct RecordingConfig {
pub codec: SCRecordingOutputCodec,
pub file_type: SCRecordingOutputFileType,
}
#[cfg(feature = "macos_15_0")]
impl Default for RecordingConfig {
fn default() -> Self {
Self {
codec: SCRecordingOutputCodec::H264,
file_type: SCRecordingOutputFileType::MP4,
}
}
}
#[cfg(feature = "macos_15_0")]
impl RecordingConfig {
pub fn new() -> Self {
Self::default()
}
/// Apply this config to a recording output configuration
pub fn apply_to(
&self,
config: SCRecordingOutputConfiguration,
) -> SCRecordingOutputConfiguration {
config
.with_video_codec(self.codec)
.with_output_file_type(self.file_type)
}
/// Get file extension based on file type
pub const fn file_extension(&self) -> &'static str {
match self.file_type {
SCRecordingOutputFileType::MP4 => "mp4",
SCRecordingOutputFileType::MOV => "mov",
}
}
}
/// Recording state manager
#[cfg(feature = "macos_15_0")]
pub struct RecordingState {
pub output: Option<SCRecordingOutput>,
pub path: Option<String>,
pub is_recording: Arc<AtomicBool>,
/// Signal when recording finishes (for waiting before opening file)
finish_signal: Arc<(Mutex<bool>, Condvar)>,
}
#[cfg(feature = "macos_15_0")]
impl RecordingState {
pub fn new() -> Self {
Self {
output: None,
path: None,
is_recording: Arc::new(AtomicBool::new(false)),
finish_signal: Arc::new((Mutex::new(false), Condvar::new())),
}
}
/// Check if currently recording
pub fn is_active(&self) -> bool {
self.is_recording.load(Ordering::Relaxed)
}
/// Start recording to a file
pub fn start(&mut self, stream: &SCStream, config: &RecordingConfig) -> Result<String, String> {
if self.is_active() {
return Err("Already recording".to_string());
}
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let path = format!("/tmp/recording_{}.{}", timestamp, config.file_extension());
let rec_config = config.apply_to(
SCRecordingOutputConfiguration::new().with_output_url(std::path::Path::new(&path)),
);
// Reset finish signal
{
let (lock, _) = &*self.finish_signal;
*lock.lock().unwrap() = false;
}
// Create delegate with finish callback
let finish_signal = Arc::clone(&self.finish_signal);
let path_for_callback = path.clone();
let delegate = RecordingCallbacks::new()
.on_start(|| {
println!("📹 Recording started");
})
.on_finish(move || {
println!("📹 Recording finished: {path_for_callback}");
let (lock, cvar) = &*finish_signal;
*lock.lock().unwrap() = true;
cvar.notify_all();
})
.on_fail(|error| {
eprintln!("❌ Recording failed: {error}");
});
match SCRecordingOutput::new_with_delegate(&rec_config, delegate) {
Some(rec) => match stream.add_recording_output(&rec) {
Ok(()) => {
println!("🔴 Recording to: {path}");
self.is_recording.store(true, Ordering::Relaxed);
self.output = Some(rec);
self.path = Some(path.clone());
Ok(path)
}
Err(e) => Err(format!("Failed to start recording: {e:?}")),
},
None => Err("Failed to create recording output".to_string()),
}
}
/// Stop recording and return the file path
pub fn stop(&mut self, stream: &SCStream) -> Option<String> {
if !self.is_active() {
return None;
}
if let Some(ref rec) = self.output {
println!("⏹️ Stopping recording...");
let _ = stream.remove_recording_output(rec);
}
self.is_recording.store(false, Ordering::Relaxed);
// Wait for recording to finish (with timeout)
{
let (lock, cvar) = &*self.finish_signal;
let mut finished = lock.lock().unwrap();
let timeout = std::time::Duration::from_secs(5);
while !*finished {
let result = cvar.wait_timeout(finished, timeout).unwrap();
finished = result.0;
if result.1.timed_out() {
println!("⚠️ Timeout waiting for recording to finish");
break;
}
}
drop(finished);
}
self.output = None;
let path = self.path.take();
if let Some(ref p) = path {
// Small delay to ensure file is fully written
std::thread::sleep(std::time::Duration::from_millis(100));
if std::path::Path::new(p).exists() {
println!("✅ Recording saved: {p}");
let _ = std::process::Command::new("open").arg(p).spawn();
} else {
println!("⚠️ Recording file not found: {p}");
}
}
path
}
/// Get the recording flag for UI display
pub fn recording_flag(&self) -> Arc<AtomicBool> {
Arc::clone(&self.is_recording)
}
}
#[cfg(feature = "macos_15_0")]
impl Default for RecordingState {
fn default() -> Self {
Self::new()
}
}
/// Recording config menu
#[cfg(feature = "macos_15_0")]
pub struct RecordingConfigMenu;
#[cfg(feature = "macos_15_0")]
impl RecordingConfigMenu {
pub const OPTIONS: &'static [&'static str] = &["Video Codec", "File Type"];
pub const fn option_count() -> usize {
Self::OPTIONS.len()
}
pub fn option_name(idx: usize) -> &'static str {
Self::OPTIONS.get(idx).unwrap_or(&"?")
}
pub fn option_value(config: &RecordingConfig, idx: usize) -> String {
match idx {
0 => match config.codec {
SCRecordingOutputCodec::H264 => "H.264".to_string(),
SCRecordingOutputCodec::HEVC => "HEVC".to_string(),
},
1 => match config.file_type {
SCRecordingOutputFileType::MP4 => "MP4".to_string(),
SCRecordingOutputFileType::MOV => "MOV".to_string(),
},
_ => "?".to_string(),
}
}
pub fn toggle_or_adjust(config: &mut RecordingConfig, idx: usize, _increase: bool) {
match idx {
0 => {
// Toggle codec
config.codec = match config.codec {
SCRecordingOutputCodec::H264 => SCRecordingOutputCodec::HEVC,
SCRecordingOutputCodec::HEVC => SCRecordingOutputCodec::H264,
};
}
1 => {
// Toggle file type
config.file_type = match config.file_type {
SCRecordingOutputFileType::MP4 => SCRecordingOutputFileType::MOV,
SCRecordingOutputFileType::MOV => SCRecordingOutputFileType::MP4,
};
}
_ => {}
}
}
}