forked from Zackriya-Solutions/meetily
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecording_manager.rs
More file actions
615 lines (513 loc) · 23.6 KB
/
Copy pathrecording_manager.rs
File metadata and controls
615 lines (513 loc) · 23.6 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
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
use std::sync::Arc;
use tokio::sync::mpsc;
use anyhow::Result;
use log::{debug, error, info, warn};
use super::devices::{AudioDevice, list_audio_devices};
#[cfg(target_os = "macos")]
use super::devices::get_safe_recording_devices_macos;
#[cfg(not(target_os = "macos"))]
use super::devices::{default_input_device, default_output_device};
use super::recording_state::{RecordingState, AudioChunk, DeviceType as RecordingDeviceType};
use super::pipeline::AudioPipelineManager;
use super::stream::AudioStreamManager;
use super::recording_saver::RecordingSaver;
use super::device_monitor::{AudioDeviceMonitor, DeviceEvent, DeviceMonitorType};
/// Stream manager type enumeration
pub enum StreamManagerType {
Standard(AudioStreamManager),
}
/// Simplified recording manager that coordinates all audio components
pub struct RecordingManager {
state: Arc<RecordingState>,
stream_manager: AudioStreamManager,
pipeline_manager: AudioPipelineManager,
recording_saver: RecordingSaver,
device_monitor: Option<AudioDeviceMonitor>,
device_event_receiver: Option<mpsc::UnboundedReceiver<DeviceEvent>>,
}
// SAFETY: RecordingManager contains types that we've marked as Send
unsafe impl Send for RecordingManager {}
impl RecordingManager {
/// Create a new recording manager
pub fn new() -> Self {
let state = RecordingState::new();
let stream_manager = AudioStreamManager::new(state.clone());
let pipeline_manager = AudioPipelineManager::new();
let (device_monitor, device_event_receiver) = AudioDeviceMonitor::new();
Self {
state,
stream_manager,
pipeline_manager,
recording_saver: RecordingSaver::new(),
device_monitor: Some(device_monitor),
device_event_receiver: Some(device_event_receiver),
}
}
// Remove app handle storage for now - will be passed directly when saving
/// Start recording with specified devices
///
/// # Arguments
/// * `microphone_device` - Optional microphone device to use
/// * `system_device` - Optional system audio device to use
/// * `auto_save` - Whether to save audio checkpoints (true) or just transcripts/metadata (false)
pub async fn start_recording(
&mut self,
microphone_device: Option<Arc<AudioDevice>>,
system_device: Option<Arc<AudioDevice>>,
auto_save: bool,
) -> Result<mpsc::UnboundedReceiver<AudioChunk>> {
info!("Starting recording manager (auto_save: {})", auto_save);
// Set up transcription channel
let (transcription_sender, transcription_receiver) = mpsc::unbounded_channel::<AudioChunk>();
// CRITICAL FIX: Create recording sender for pre-mixed audio from pipeline
// Pipeline will mix mic + system audio professionally and send to this channel
// Pass auto_save to control whether audio checkpoints are created
let recording_sender = self.recording_saver.start_accumulation(auto_save);
// Start recording state first
self.state.start_recording()?;
// Get device information for adaptive mixing
// The pipeline uses device kind (Bluetooth vs Wired) to apply adaptive buffering:
// - Bluetooth: Larger buffers (80-200ms) to handle jitter
// - Wired: Smaller buffers (20-50ms) for low latency
let (mic_name, mic_kind) = if let Some(ref mic) = microphone_device {
let device_kind = super::device_detection::InputDeviceKind::detect(&mic.name, 512, 48000);
(mic.name.clone(), device_kind)
} else {
("No Microphone".to_string(), super::device_detection::InputDeviceKind::Unknown)
};
let (sys_name, sys_kind) = if let Some(ref sys) = system_device {
let device_kind = super::device_detection::InputDeviceKind::detect(&sys.name, 512, 48000);
(sys.name.clone(), device_kind)
} else {
("No System Audio".to_string(), super::device_detection::InputDeviceKind::Unknown)
};
// Update recording metadata with device information
self.recording_saver.set_device_info(
microphone_device.as_ref().map(|d| d.name.clone()),
system_device.as_ref().map(|d| d.name.clone())
);
// Start the audio processing pipeline with FFmpeg adaptive mixer
// Pipeline will: 1) Mix mic+system audio with adaptive buffering, 2) Send mixed to recording_sender,
// 3) Apply VAD and send speech segments to transcription
self.pipeline_manager.start(
self.state.clone(),
transcription_sender,
0, // Ignored - using dynamic sizing internally
48000, // 48kHz sample rate
Some(recording_sender), // CRITICAL: Pass recording sender to receive pre-mixed audio
mic_name,
mic_kind,
sys_name,
sys_kind,
)?;
// Give the pipeline a moment to fully initialize before starting streams
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
// Start audio streams - they send RAW unmixed chunks to pipeline for mixing
// Pipeline handles mixing and distribution to both recording and transcription
self.stream_manager.start_streams(microphone_device.clone(), system_device.clone(), None).await?;
// Start device monitoring to detect disconnects
if let Some(ref mut monitor) = self.device_monitor {
if let Err(e) = monitor.start_monitoring(microphone_device, system_device) {
warn!("Failed to start device monitoring: {}", e);
// Non-fatal - continue without monitoring
} else {
info!("✅ Device monitoring started");
}
}
info!("Recording manager started successfully with {} active streams",
self.stream_manager.active_stream_count());
Ok(transcription_receiver)
}
/// Start recording with default devices and auto_save setting
///
/// # Arguments
/// * `auto_save` - Whether to save audio checkpoints (true) or just transcripts/metadata (false)
///
/// # Platform-Specific Behavior
///
/// **macOS**: Uses smart device selection that automatically overrides
/// Bluetooth devices to built-in wired devices for stable, consistent sample rates.
/// This prevents Core Audio/ScreenCaptureKit from delivering variable sample rate
/// streams that cause sync issues when mixing mic + system audio.
///
/// **Windows/Linux**: Uses system default devices directly without override.
///
/// # macOS Bluetooth Override Strategy
///
/// - Microphone: If Bluetooth → Use built-in MacBook mic
/// - Speaker: If Bluetooth → Use built-in MacBook speaker (for ScreenCaptureKit)
/// - Each device is checked INDEPENDENTLY
///
/// Rationale: Bluetooth devices on macOS can have variable sample rates as Core Audio
/// and the Bluetooth stack may resample dynamically. Built-in devices provide
/// fixed, consistent sample rates for reliable audio mixing.
///
/// User still hears audio via Bluetooth (playback), but recording captures
/// via stable wired path for best quality.
pub async fn start_recording_with_defaults_and_auto_save(&mut self, auto_save: bool) -> Result<mpsc::UnboundedReceiver<AudioChunk>> {
#[cfg(target_os = "macos")]
{
info!("🎙️ [macOS] Starting recording with smart device selection (Bluetooth override enabled)");
// Get safe recording devices with automatic Bluetooth fallback
// This function handles all the detection and override logic for macOS
let (microphone_device, system_device) = get_safe_recording_devices_macos()?;
// Wrap in Arc for sharing across threads
let microphone_device = microphone_device.map(Arc::new);
let system_device = system_device.map(Arc::new);
// Ensure at least microphone is available
if microphone_device.is_none() {
return Err(anyhow::anyhow!("❌ No microphone device available for recording"));
}
// Start recording with selected devices and auto_save setting
self.start_recording(microphone_device, system_device, auto_save).await
}
#[cfg(not(target_os = "macos"))]
{
info!("Starting recording with default devices");
// Get default devices (no Bluetooth override on Windows/Linux)
let microphone_device = match default_input_device() {
Ok(device) => {
info!("Using default microphone: {}", device.name);
Some(Arc::new(device))
}
Err(e) => {
warn!("No default microphone available: {}", e);
None
}
};
let system_device = match default_output_device() {
Ok(device) => {
info!("Using default system audio: {}", device.name);
Some(Arc::new(device))
}
Err(e) => {
warn!("No default system audio available: {}", e);
None
}
};
// Ensure at least microphone is available
if microphone_device.is_none() {
return Err(anyhow::anyhow!("No microphone device available"));
}
self.start_recording(microphone_device, system_device, auto_save).await
}
}
/// Stop recording streams without saving (for use when waiting for transcription)
pub async fn stop_streams_only(&mut self) -> Result<()> {
info!("Stopping recording streams only");
// Stop device monitoring
if let Some(ref mut monitor) = self.device_monitor {
monitor.stop_monitoring().await;
}
// Stop recording state first
self.state.stop_recording();
// Stop audio streams
if let Err(e) = self.stream_manager.stop_streams() {
error!("Error stopping audio streams: {}", e);
}
// Stop audio pipeline
if let Err(e) = self.pipeline_manager.stop().await {
error!("Error stopping audio pipeline: {}", e);
}
debug!("Recording streams stopped successfully");
Ok(())
}
/// Stop streams and force immediate pipeline flush to process all accumulated audio
pub async fn stop_streams_and_force_flush(&mut self) -> Result<()> {
info!("🚀 Stopping recording streams with IMMEDIATE pipeline flush");
// CRITICAL: Stop device monitor FIRST to prevent continuous WASAPI polling on Windows
// This fixes the slow shutdown issue where device enumeration runs for 90+ seconds
if let Some(ref mut monitor) = self.device_monitor {
info!("Stopping device monitor first...");
monitor.stop_monitoring().await;
}
// Stop recording state first - this clears device references
self.state.stop_recording();
// Stop audio streams immediately
if let Err(e) = self.stream_manager.stop_streams() {
error!("Error stopping audio streams: {}", e);
}
// CRITICAL: Force pipeline to flush ALL accumulated audio before stopping
debug!("💨 Forcing pipeline to flush accumulated audio immediately");
if let Err(e) = self.pipeline_manager.force_flush_and_stop().await {
error!("Error during force flush: {}", e);
}
// CRITICAL: Full cleanup to release all Arc references and resources
// This ensures microphone is released even if Drop is delayed
self.state.cleanup();
info!("✅ Recording streams stopped with immediate flush completed");
Ok(())
}
/// Save recording after transcription is complete
pub async fn save_recording_only<R: tauri::Runtime>(&mut self, app: &tauri::AppHandle<R>) -> Result<()> {
debug!("Saving recording with transcript chunks");
// Get actual recording duration from state
let recording_duration = self.state.get_active_recording_duration();
info!("Recording duration from state: {:?}s", recording_duration);
// Save the recording with actual duration
match self.recording_saver.stop_and_save(app, recording_duration).await {
Ok(Some(file_path)) => {
info!("Recording saved successfully to: {}", file_path);
}
Ok(None) => {
debug!("Recording not saved (auto-save disabled or no audio data)");
}
Err(e) => {
error!("Failed to save recording: {}", e);
// Don't fail the stop operation if saving fails
}
}
debug!("Recording save operation completed");
Ok(())
}
/// Stop recording and save audio (legacy method)
pub async fn stop_recording<R: tauri::Runtime>(&mut self, app: &tauri::AppHandle<R>) -> Result<()> {
info!("Stopping recording manager");
// Get recording duration BEFORE stopping (important!)
let recording_duration = self.state.get_active_recording_duration();
info!("Recording duration before stop: {:?}s", recording_duration);
// Stop recording state first
self.state.stop_recording();
// Stop audio streams
if let Err(e) = self.stream_manager.stop_streams() {
error!("Error stopping audio streams: {}", e);
}
// Stop audio pipeline
if let Err(e) = self.pipeline_manager.stop().await {
error!("Error stopping audio pipeline: {}", e);
}
// Save the recording with actual duration
match self.recording_saver.stop_and_save(app, recording_duration).await {
Ok(Some(file_path)) => {
info!("Recording saved successfully to: {}", file_path);
}
Ok(None) => {
info!("Recording not saved (auto-save disabled or no audio data)");
}
Err(e) => {
error!("Failed to save recording: {}", e);
// Don't fail the stop operation if saving fails
}
}
info!("Recording manager stopped");
Ok(())
}
/// Get recording stats from the saver
pub fn get_recording_stats(&self) -> (usize, u32) {
self.recording_saver.get_stats()
}
/// Check if currently recording
pub fn is_recording(&self) -> bool {
self.state.is_recording()
}
/// Pause the current recording session
pub fn pause_recording(&self) -> Result<()> {
info!("Pausing recording");
self.state.pause_recording()
}
/// Resume the current recording session
pub fn resume_recording(&self) -> Result<()> {
info!("Resuming recording");
self.state.resume_recording()
}
/// Check if recording is currently paused
pub fn is_paused(&self) -> bool {
self.state.is_paused()
}
/// Check if recording is active (recording and not paused)
pub fn is_active(&self) -> bool {
self.state.is_active()
}
/// Get recording statistics
pub fn get_stats(&self) -> super::recording_state::RecordingStats {
self.state.get_stats()
}
/// Get recording duration
pub fn get_recording_duration(&self) -> Option<f64> {
self.state.get_recording_duration()
}
/// Get active recording duration (excluding pauses)
pub fn get_active_recording_duration(&self) -> Option<f64> {
self.state.get_active_recording_duration()
}
/// Get total pause duration
pub fn get_total_pause_duration(&self) -> f64 {
self.state.get_total_pause_duration()
}
/// Get current pause duration if paused
pub fn get_current_pause_duration(&self) -> Option<f64> {
self.state.get_current_pause_duration()
}
/// Get error information
pub fn get_error_info(&self) -> (u32, Option<super::recording_state::AudioError>) {
(self.state.get_error_count(), self.state.get_last_error())
}
/// Get active stream count
pub fn active_stream_count(&self) -> usize {
self.stream_manager.active_stream_count()
}
/// Set error callback for handling errors
pub fn set_error_callback<F>(&self, callback: F)
where
F: Fn(&super::recording_state::AudioError) + Send + Sync + 'static,
{
self.state.set_error_callback(callback);
}
/// Check if there's a fatal error
pub fn has_fatal_error(&self) -> bool {
self.state.has_fatal_error()
}
/// Set the meeting name for this recording session
pub fn set_meeting_name(&mut self, name: Option<String>) {
self.recording_saver.set_meeting_name(name);
}
/// Add a structured transcript segment to be saved later
pub fn add_transcript_segment(&self, segment: super::recording_saver::TranscriptSegment) {
self.recording_saver.add_transcript_segment(segment);
}
/// Add a transcript chunk to be saved later (legacy method)
pub fn add_transcript_chunk(&self, text: String) {
self.recording_saver.add_transcript_chunk(text);
}
/// Get accumulated transcript segments from current recording session
/// Used for syncing frontend state after page reload during active recording
pub fn get_transcript_segments(&self) -> Vec<super::recording_saver::TranscriptSegment> {
self.recording_saver.get_transcript_segments()
}
/// Get meeting name from current recording session
/// Used for syncing frontend state after page reload during active recording
pub fn get_meeting_name(&self) -> Option<String> {
self.recording_saver.get_meeting_name()
}
/// Cleanup all resources without saving
pub async fn cleanup_without_save(&mut self) {
if self.is_recording() {
debug!("Stopping recording without saving during cleanup");
// Stop recording state first
self.state.stop_recording();
// Stop audio streams
if let Err(e) = self.stream_manager.stop_streams() {
error!("Error stopping audio streams during cleanup: {}", e);
}
// Stop audio pipeline
if let Err(e) = self.pipeline_manager.stop().await {
error!("Error stopping audio pipeline during cleanup: {}", e);
}
}
self.state.cleanup();
}
/// Get the meeting folder path (if available)
/// Returns None if no meeting name was set or folder structure not initialized
pub fn get_meeting_folder(&self) -> Option<std::path::PathBuf> {
self.recording_saver.get_meeting_folder().map(|p| p.clone())
}
/// Check for device events (disconnects/reconnects)
/// Returns Some(DeviceEvent) if an event occurred, None otherwise
pub fn poll_device_events(&mut self) -> Option<DeviceEvent> {
if let Some(ref mut receiver) = self.device_event_receiver {
receiver.try_recv().ok()
} else {
None
}
}
/// Attempt to reconnect a disconnected device
/// Returns true if reconnection successful
pub async fn attempt_device_reconnect(&mut self, device_name: &str, device_type: DeviceMonitorType) -> Result<bool> {
info!("🔄 Attempting to reconnect device: {} ({:?})", device_name, device_type);
// List current devices
let available_devices = list_audio_devices().await?;
// Find the device by name
let device = available_devices.iter()
.find(|d| d.name == device_name)
.cloned();
if let Some(device) = device {
info!("✅ Device '{}' found, recreating stream...", device_name);
// Determine which device to reconnect based on type
let device_arc: Arc<AudioDevice> = Arc::new(device);
match device_type {
DeviceMonitorType::Microphone => {
// Stop existing mic stream and start new one
// We need to keep system audio running if it exists
let system_device = self.state.get_system_device();
// Restart streams with new microphone
self.stream_manager.stop_streams()?;
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
self.stream_manager.start_streams(Some(device_arc.clone()), system_device, None).await?;
self.state.set_microphone_device(device_arc);
info!("✅ Microphone reconnected successfully");
Ok(true)
}
DeviceMonitorType::SystemAudio => {
// Stop existing system audio stream and start new one
let microphone_device = self.state.get_microphone_device();
// Restart streams with new system audio
self.stream_manager.stop_streams()?;
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
self.stream_manager.start_streams(microphone_device, Some(device_arc.clone()), None).await?;
self.state.set_system_device(device_arc);
info!("✅ System audio reconnected successfully");
Ok(true)
}
}
} else {
warn!("❌ Device '{}' not yet available", device_name);
Ok(false)
}
}
/// Handle a device disconnect event
/// Pauses recording and attempts reconnection
pub async fn handle_device_disconnect(&mut self, device_name: String, device_type: DeviceMonitorType) {
warn!("📱 Device disconnected: {} ({:?})", device_name, device_type);
// Mark state as reconnecting (keeps recording alive but in waiting state)
let device = match device_type {
DeviceMonitorType::Microphone => self.state.get_microphone_device(),
DeviceMonitorType::SystemAudio => self.state.get_system_device(),
};
if let Some(device) = device {
let recording_device_type = match device_type {
DeviceMonitorType::Microphone => RecordingDeviceType::Microphone,
DeviceMonitorType::SystemAudio => RecordingDeviceType::System,
};
self.state.start_reconnecting(device, recording_device_type);
}
}
/// Handle a device reconnect event
pub async fn handle_device_reconnect(&mut self, device_name: String, device_type: DeviceMonitorType) -> Result<()> {
info!("📱 Device reconnected: {} ({:?})", device_name, device_type);
// Attempt to reconnect the device
match self.attempt_device_reconnect(&device_name, device_type).await {
Ok(true) => {
info!("✅ Successfully reconnected device: {}", device_name);
self.state.stop_reconnecting();
Ok(())
}
Ok(false) => {
warn!("Device reconnect attempt failed (device not yet available)");
Err(anyhow::anyhow!("Device not available"))
}
Err(e) => {
error!("Device reconnect failed: {}", e);
Err(e)
}
}
}
/// Check if currently attempting to reconnect
pub fn is_reconnecting(&self) -> bool {
self.state.is_reconnecting()
}
/// Get reference to recording state for external access
pub fn get_state(&self) -> &Arc<RecordingState> {
&self.state
}
}
impl Default for RecordingManager {
fn default() -> Self {
Self::new()
}
}
impl Drop for RecordingManager {
fn drop(&mut self) {
// Note: Can't call async cleanup in Drop, but streams have their own Drop implementations
self.state.cleanup();
}
}