-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathlinux_dictation.rs
More file actions
355 lines (332 loc) · 12.1 KB
/
Copy pathlinux_dictation.rs
File metadata and controls
355 lines (332 loc) · 12.1 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
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, SyncSender, TrySendError};
use std::thread;
use std::time::{Duration, Instant};
use color_eyre::Result;
use color_eyre::eyre::eyre;
use crate::audio::{AudioInput, AudioInputEvent, CaptureInstant};
use crate::dictation::{DictationCapture, Finish};
use crate::events::{DictationPhase, EventLog, TranscriptPhase, VoiceEvent, VoiceState, now_ms};
use crate::feedback::{self, Tone};
use crate::linux_desktop::LinuxIndicator;
use crate::linux_input::{HotkeyEvent, LinuxHotkeyMonitor};
use crate::linux_paste::LinuxPaster;
use crate::linux_transcriber::LinuxTranscriber;
const UPDATE_INTERVAL: Duration = Duration::from_millis(20);
struct Job {
samples: Vec<f32>,
audio_ms: u64,
}
struct OutputWorker {
stop: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl Drop for OutputWorker {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
}
}
pub fn run(event_path: &Path, device: Option<&str>, shutdown: &AtomicBool) -> Result<()> {
let settings = crate::linux_settings::LinuxSettings::load()?;
let transcriber = LinuxTranscriber::load(&settings.transcription)?;
run_with_settings(event_path, device, shutdown, settings, transcriber)
}
pub fn run_with_transcriber(
event_path: &Path,
device: Option<&str>,
shutdown: &AtomicBool,
transcriber: LinuxTranscriber,
) -> Result<()> {
let settings = crate::linux_settings::LinuxSettings::load()?;
run_with_settings(event_path, device, shutdown, settings, transcriber)
}
fn run_with_settings(
event_path: &Path,
device: Option<&str>,
shutdown: &AtomicBool,
settings: crate::linux_settings::LinuxSettings,
transcriber: LinuxTranscriber,
) -> Result<()> {
feedback::set_volume(settings.sound_effect_volume);
if let Err(error) = feedback::preload() {
tracing::warn!(%error, "recording sounds are unavailable; continuing without feedback");
}
// Drop audio/hotkeys and close the job queue before joining slow output on
// every exit, including failures during startup or recording.
let mut output = OutputWorker {
stop: Arc::new(AtomicBool::new(false)),
worker: None,
};
let input = match device {
Some(name) => AudioInput::open_matching(name)?,
None => AudioInput::open(&[])?,
};
let hotkey_label = settings.dictation_hotkey.label();
let hotkey = LinuxHotkeyMonitor::start(settings.dictation_hotkey, settings.double_tap_lock)?;
let wayland_modifiers = hotkey.wayland_modifiers();
let indicator = LinuxIndicator::new();
let (jobs, job_receiver) = mpsc::sync_channel::<Job>(2);
let (result_sender, results) = mpsc::channel();
let worker_stop = output.stop.clone();
output.worker = Some(thread::spawn(move || {
let mut transcriber = transcriber;
let mut paster = LinuxPaster::new(
worker_stop.clone(),
settings.paste_with_shift,
wayland_modifiers,
);
while let Ok(job) = job_receiver.recv() {
if worker_stop.load(Ordering::Acquire) {
break;
}
let started = Instant::now();
let result = transcriber
.transcribe(&job.samples)
.map_err(|error| format!("{error:#}"))
.and_then(|text| {
let text = text.trim().to_string();
if text.is_empty() {
return Err("transcription was empty".into());
}
let paste_result = paster
.as_mut()
.map_err(|error| format!("{error:#}"))?
.paste(&text)
.map_err(|error| format!("{error:#}"));
paste_result.map(|()| text)
});
tracing::info!(
audio_ms = job.audio_ms,
elapsed_ms = started.elapsed().as_millis(),
"completed Linux dictation job"
);
if result_sender.send(result).is_err() {
break;
}
}
}));
let mut events = EventLog::create(event_path)?;
let mut capture = DictationCapture::new(input.sample_rate);
let mut recording = false;
let mut captured_through = CaptureInstant::ZERO;
let mut pending = 0_usize;
events.emit(&VoiceEvent::SessionStarted {
timestamp_ms: now_ms(),
})?;
emit_state(&mut events, VoiceState::Listening, &input.device_name)?;
println!(
"HEX dictation is ready on {}. Hold {} to dictate; Ctrl-C stops.",
input.device_name, hotkey_label
);
while !shutdown.load(Ordering::Relaxed) {
if let Ok(error) = hotkey.errors.try_recv() {
return Err(eyre!("Linux hotkey monitor stopped: {error}"));
}
while let Ok(action) = hotkey.events.try_recv() {
match action {
HotkeyEvent::Start if !recording => {
start_capture(&mut capture, captured_through, feedback::play);
recording = true;
events.dictation(DictationPhase::Started, "")?;
emit_state(&mut events, VoiceState::Dictating, &input.device_name)?;
}
HotkeyEvent::Finish if recording => {
recording = false;
submit_capture(
&mut capture,
captured_through,
&jobs,
&mut events,
&mut pending,
)?;
emit_state(
&mut events,
active_state(recording, pending),
&input.device_name,
)?;
}
HotkeyEvent::Cancel if recording => {
capture.cancel();
recording = false;
feedback::play(Tone::Cancel);
events.dictation(DictationPhase::Cancelled, "")?;
emit_state(
&mut events,
active_state(recording, pending),
&input.device_name,
)?;
}
_ => {}
}
}
while let Ok(result) = results.try_recv() {
pending = pending.saturating_sub(1);
match result {
Ok(text) => {
events.emit(&VoiceEvent::Transcript {
timestamp_ms: now_ms(),
phase: TranscriptPhase::Completed,
latency_ms: 0,
text: text.clone(),
})?;
events.dictation(DictationPhase::Pasted, text)?;
}
Err(error) => events.dictation(DictationPhase::Failed(error), "")?,
}
emit_state(
&mut events,
active_state(recording, pending),
&input.device_name,
)?;
}
indicator.update(recording, pending);
let chunk = match input.recv_timeout(UPDATE_INTERVAL) {
AudioInputEvent::Chunk {
samples,
captured_through: chunk_captured_through,
} => {
captured_through = chunk_captured_through;
samples
}
AudioInputEvent::Timeout => continue,
AudioInputEvent::StreamFailed(error) => {
return Err(eyre!("microphone stream stopped: {error}"));
}
};
if recording {
capture.ingest(&chunk, captured_through);
capture.become_intentional(captured_through);
} else {
capture.keep_warm(&chunk);
}
}
indicator.update(false, pending);
emit_state(&mut events, VoiceState::Stopping, &input.device_name)?;
output.stop.store(true, Ordering::Release);
drop(hotkey);
drop(input);
drop(jobs);
if output
.worker
.take()
.expect("dictation output worker exists")
.join()
.is_err()
{
return Err(eyre!("Linux dictation worker panicked"));
}
println!("Stopped.");
Ok(())
}
fn start_capture(
capture: &mut DictationCapture,
started_at: CaptureInstant,
play: impl FnOnce(Tone),
) {
capture.start(started_at);
play(Tone::DictationStart);
}
fn submit_capture(
capture: &mut DictationCapture,
ended_at: CaptureInstant,
jobs: &SyncSender<Job>,
events: &mut EventLog,
pending: &mut usize,
) -> Result<()> {
match capture.finish(ended_at) {
Finish::Discard => events.dictation(DictationPhase::Discarded, "")?,
Finish::Transcribe(clip) => {
feedback::play(Tone::DictationStop);
let audio_ms = clip.duration_ms();
let job = Job {
samples: clip.into_parakeet_samples(),
audio_ms,
};
match jobs.try_send(job) {
Ok(()) => {
*pending += 1;
events.dictation(DictationPhase::Transcribing, "")?;
}
Err(TrySendError::Full(_)) => events
.dictation(DictationPhase::Failed("dictation queue is full".into()), "")?,
Err(TrySendError::Disconnected(_)) => {
return Err(eyre!("dictation worker is unavailable"));
}
}
}
}
Ok(())
}
fn active_state(recording: bool, pending: usize) -> VoiceState {
if recording {
VoiceState::Dictating
} else if pending > 0 {
VoiceState::Transcribing
} else {
VoiceState::Listening
}
}
fn emit_state(events: &mut EventLog, state: VoiceState, device: &str) -> Result<()> {
events.emit(&VoiceEvent::State {
timestamp_ms: now_ms(),
state,
device: device.into(),
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn start_sound_precedes_audio_and_does_not_change_short_tap_discard() {
let mut capture = DictationCapture::new(16_000);
let started_at = CaptureInstant::from_nanos(60_000_000_000);
let mut sounds = Vec::new();
start_capture(&mut capture, started_at, |tone| sounds.push(tone));
assert!(capture.is_recording());
assert_eq!(sounds, [Tone::DictationStart]);
assert!(matches!(
capture.finish(started_at + Duration::from_millis(100)),
Finish::Discard
));
}
#[test]
fn cancelled_capture_keeps_pending_output_visible() {
assert_eq!(active_state(true, 2), VoiceState::Dictating);
assert_eq!(active_state(false, 2), VoiceState::Transcribing);
assert_eq!(active_state(false, 1), VoiceState::Transcribing);
assert_eq!(active_state(false, 0), VoiceState::Listening);
assert_eq!(active_state(true, 0), VoiceState::Dictating);
}
#[test]
fn output_guard_cancels_and_joins_even_on_listener_error() {
let stopped = Arc::new(AtomicBool::new(false));
let finished = Arc::new(AtomicBool::new(false));
let result: Result<()> = {
let mut output = OutputWorker {
stop: stopped.clone(),
worker: None,
};
let (_jobs, receiver) = mpsc::channel::<()>();
let stop = stopped.clone();
let completed = finished.clone();
output.worker = Some(thread::spawn(move || {
// The sender must close before the guard joins this worker.
assert!(receiver.recv().is_err());
while !stop.load(Ordering::Acquire) {
thread::yield_now();
}
completed.store(true, Ordering::Release);
}));
Err(eyre!("listener failure"))
};
assert!(result.is_err());
assert!(stopped.load(Ordering::Acquire));
assert!(finished.load(Ordering::Acquire));
}
}