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
// src/hotkey_service.rs
//
// This module handles global hotkey registration and event handling.
use crate::audio::stream_manager::AudioStreamManager;
use crate::audio_state::RecordingState;
use crate::config::AppConfig;
use crate::providers::TranscriptionProvider;
use crate::shutdown_handler::{ExitPriority, ShutdownManager};
use anyhow::Result;
use global_hotkey::{
hotkey::{HotKey, Modifiers},
GlobalHotKeyEvent, GlobalHotKeyManager,
};
use tower::ServiceExt;
use tower::Service;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tokio::sync::{broadcast, mpsc, Mutex as TokioMutex};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
// Import crossbeam error types
use crossbeam_channel::RecvTimeoutError;
/// Context needed for the hotkey service to start pipeline tasks
pub struct AppContext {
pub stream_manager: Arc<TokioMutex<AudioStreamManager>>,
pub provider: Arc<TokioMutex<Box<dyn TranscriptionProvider + Send + Sync>>>,
pub pipeline_cancel_token: Mutex<Option<CancellationToken>>,
pub pipeline_handle: Mutex<Option<JoinHandle<()>>>,
pub config: AppConfig,
}
pub struct HotkeyService {
manager: GlobalHotKeyManager,
recording_state: Arc<RecordingState>,
registered_hotkeys: Vec<HotKey>,
shutdown_rx: broadcast::Receiver<()>,
app_context: Option<Arc<AppContext>>,
blocking_thread: Mutex<Option<std::thread::JoinHandle<()>>>,
thread_running: Arc<AtomicBool>,
}
impl HotkeyService {
pub fn new(
recording_state: Arc<RecordingState>,
shutdown_rx: broadcast::Receiver<()>,
) -> Result<Self> {
let manager = GlobalHotKeyManager::new()?;
Ok(Self {
manager,
recording_state,
registered_hotkeys: Vec::new(),
shutdown_rx,
app_context: None,
blocking_thread: Mutex::new(None),
thread_running: Arc::new(AtomicBool::new(false)),
})
}
pub fn register_hotkey(&mut self, hotkey_str: &str) -> Result<()> {
let hotkey = HotKey::from_str(hotkey_str)?;
self.manager.register(hotkey.clone())?;
self.registered_hotkeys.push(hotkey);
Ok(())
}
/// Set the application context for pipeline operations
pub fn set_app_context(&mut self, context: Arc<AppContext>) {
self.app_context = Some(context);
}
pub async fn run(&self) {
info!("Hotkey service started");
let event_receiver = GlobalHotKeyEvent::receiver();
// Forward blocking hotkey events into an async channel
let (async_tx, mut async_rx) = mpsc::unbounded_channel();
let mut shutdown_rx = self.shutdown_rx.resubscribe();
// Set the thread running flag
self.thread_running.store(true, Ordering::SeqCst);
// Create a clone of the termination flag for the thread
let thread_running = self.thread_running.clone();
let blocking_thread = std::thread::spawn(move || {
tracing::info!("[hotkey_blocking_thread] Started");
// Use a separate thread to receive hotkey events
let event_thread = std::thread::spawn(move || {
while thread_running.load(Ordering::SeqCst) {
// Use a timeout to periodically check the termination flag
match event_receiver.recv_timeout(Duration::from_millis(100)) {
Ok(event) => {
if !thread_running.load(Ordering::SeqCst) {
break;
}
let _ = async_tx.send(event);
}
Err(RecvTimeoutError::Timeout) => {
// Just a timeout, check the termination flag and continue
continue;
}
Err(RecvTimeoutError::Disconnected) => {
// Channel disconnected, exit the loop
break;
}
}
}
tracing::info!("[hotkey_event_thread] Exiting");
});
// Wait for the event thread to finish
let _ = event_thread.join();
tracing::info!("[hotkey_blocking_thread] Exiting");
});
*self.blocking_thread.lock().unwrap() = Some(blocking_thread);
// Process events or exit on shutdown
loop {
tokio::select! {
_ = shutdown_rx.recv() => {
info!("Hotkey service received shutdown signal");
// Signal the blocking thread to terminate
self.thread_running.store(false, Ordering::SeqCst);
break;
}
maybe_event = async_rx.recv() => {
match maybe_event {
Some(event) => {
if event.state == global_hotkey::HotKeyState::Pressed {
debug!("Hotkey pressed");
let is_now_active = self.recording_state.toggle();
info!(
"Recording {}",
if is_now_active { "started" } else { "paused" }
);
// Start or stop pipeline tasks if app context is available
if let Some(app_context) = &self.app_context {
if is_now_active {
self.start_pipeline_task(app_context).await;
} else {
self.stop_pipeline_task(app_context).await;
}
}
}
}
None => {
// Channel closed, exit the loop
self.thread_running.store(false, Ordering::SeqCst);
break;
}
}
}
}
}
info!("Hotkey service stopped");
}
/// Start the pipeline task when hotkey is pressed
async fn start_pipeline_task(&self, app_context: &Arc<AppContext>) {
// Only start if no pipeline is running
let mut token_guard = app_context.pipeline_cancel_token.lock().unwrap();
let mut handle_guard = app_context.pipeline_handle.lock().unwrap();
if token_guard.is_none() && handle_guard.is_none() {
// Create new cancellation token
let token = CancellationToken::new();
*token_guard = Some(token.clone());
// Get audio receiver
let stream_manager = &app_context.stream_manager;
let bcast_receiver = match stream_manager.lock().await.get_receiver() {
Some(receiver) => receiver,
None => {
error!("Failed to get audio receiver from stream manager");
return;
}
};
// Set up pipeline
use crate::audio::constants::{SAMPLE_RATE, CHUNK_DURATION_MS};
use crate::pipeline::chunking::ChunkingManager;
use crate::pipeline::layers::wav_conversion::WavConversionLayer;
use crate::pipeline::services::transcription::TranscriptionService;
use crate::pipeline::types::{AudioChunk, AudioRequest, AudioResponse, ProcessedData};
use crate::platform::{EnigoTextInserter, InsertOptions, PlatformTextInserterHandler};
use crate::transcription::result_handler::TranscriptionResultHandler;
use std::time::{Duration, SystemTime};
use tower::ServiceBuilder;
// Set up channels
let (mpsc_tx, mut mpsc_rx) = mpsc::channel(8);
let mut bcast_receiver_clone = bcast_receiver.resubscribe();
// Forward audio chunks
tokio::spawn(async move {
while let Ok(chunk) = bcast_receiver_clone.recv().await {
if mpsc_tx.send(chunk).await.is_err() {
break;
}
}
});
// Set up text inserter
let provider = app_context.provider.clone();
let inserter = match EnigoTextInserter::new() {
Ok(inserter) => Box::new(inserter),
Err(e) => {
error!("Failed to create text inserter: {}", e);
return;
}
};
let handler = Arc::new(TokioMutex::new(
Box::new(PlatformTextInserterHandler::new(inserter)) as Box<dyn TranscriptionResultHandler + Send + Sync>
));
let config = app_context.config.clone();
info!("Hotkey pressed: starting pipeline task");
// Start pipeline task
let pipeline_handle = tokio::spawn(async move {
let mut chunking_manager = ChunkingManager::new(SAMPLE_RATE, Duration::from_millis(CHUNK_DURATION_MS));
let mut pipeline_service = ServiceBuilder::new()
.layer(WavConversionLayer)
.service(TranscriptionService::new(provider.clone()));
loop {
tokio::select! {
_ = token.cancelled() => {
info!("Pipeline driver received shutdown signal");
break;
}
opt = mpsc_rx.recv() => {
match opt {
Some(samples) => {
let chunks = chunking_manager.add_samples(&samples);
for complete_chunk in chunks {
let audio_chunk = AudioChunk {
timestamp: SystemTime::now(),
data: complete_chunk,
is_speech: None,
};
let request = AudioRequest(audio_chunk);
if let Err(e) = pipeline_service.ready().await {
error!("Pipeline service not ready: {}", e);
continue;
}
match pipeline_service.call(request).await {
Ok(AudioResponse { result_data: ProcessedData::Transcription(text), .. }) => {
let options = InsertOptions {
auto_capitalize: config.auto_capitalize,
auto_punctuate: config.auto_punctuate,
..Default::default()
};
let mut guard = handler.lock().await;
if let Err(e) = guard.handle_result(&text, options) {
error!("Failed to handle transcription result: {}", e);
}
}
Ok(AudioResponse { result_data: other_data, .. }) => {
debug!("Received non-transcription data: {:?}", other_data);
}
Err(e) => {
error!("Pipeline call failed: {}", e);
}
}
}
}
None => {
info!("Audio source channel closed");
break;
}
}
}
}
}
info!("Pipeline driver task finished.");
});
*handle_guard = Some(pipeline_handle);
}
}
/// Stop the pipeline task when hotkey is released
async fn stop_pipeline_task(&self, app_context: &Arc<AppContext>) {
let mut token_guard = app_context.pipeline_cancel_token.lock().unwrap();
let mut handle_guard = app_context.pipeline_handle.lock().unwrap();
// Cancel the task if running
if let Some(token) = token_guard.take() {
token.cancel();
info!("Hotkey released: cancellation signal sent to pipeline");
}
// Wait for task to complete
if let Some(handle) = handle_guard.take() {
use tokio::time::{timeout, Duration};
match timeout(Duration::from_secs(2), handle).await {
Ok(Ok(_)) => info!("Pipeline task finished after cancellation"),
Ok(Err(e)) => error!("Pipeline task panicked: {}", e),
Err(_) => warn!("Timeout waiting for pipeline task to finish"),
}
}
}
/// Register a shutdown handler for the hotkey service
pub fn register_shutdown_handler(service: Arc<Self>, shutdown_manager: &ShutdownManager) {
shutdown_manager.register(
"Stop hotkey service",
ExitPriority::Normal,
move || async move {
// Signal the blocking thread to terminate
service.thread_running.store(false, Ordering::SeqCst);
// Unregister all hotkeys
if let Err(e) = service.manager.unregister_all(&service.registered_hotkeys) {
debug!("Failed to unregister hotkeys during shutdown: {}", e);
}
// Take ownership of the thread handle outside of the async block
let handle = {
let mut guard = service.blocking_thread.lock().unwrap();
guard.take()
};
// If we have a handle, join it with a timeout
if let Some(handle) = handle {
// Create a oneshot channel to signal when the join is complete
let (tx, rx) = tokio::sync::oneshot::channel();
// Spawn a thread to join the blocking thread
std::thread::spawn(move || {
let join_result = handle.join();
let _ = tx.send(join_result);
});
// Wait for the join with a timeout
match tokio::time::timeout(Duration::from_secs(2), rx).await {
Ok(Ok(Ok(()))) => debug!("Hotkey blocking thread joined successfully"),
Ok(Ok(Err(e))) => error!("Hotkey blocking thread panicked: {:?}", e),
Ok(Err(_)) => error!("Failed to receive join result"),
Err(_) => warn!("Timeout waiting for hotkey blocking thread to join"),
}
}
info!("Hotkey service shutdown handler completed");
},
);
}
}