Repository navigation
Expand file tree
/
Copy pathengine.rs
More file actions
2158 lines (2011 loc) · 78.7 KB
/
Copy pathengine.rs
File metadata and controls
2158 lines (2011 loc) · 78.7 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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The thread that owns the loaded GGUF model and runs all of its inference.
//!
//! A capture that the model can stream is fed while the shortcut is held, so
//! release only decodes the last second or two of audio. Every finish carries
//! the complete clip: a stream that failed, stalled, or produced no text is
//! replaced by an offline transcription of that clip, and a model or device
//! that cannot stream always takes the offline path. Commands are handled in
//! order on one thread, because a live stream holds the model's compute lease.
use std::collections::VecDeque;
mod streaming;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use color_eyre::eyre::{Result, eyre};
use transcribe_cpp::CancelToken;
/// The model the engine owns: macOS keeps its warm, switchable transcriber
use streaming::*;
/// (GGUF or Apple Speech); Linux and Windows load one GGUF model.
#[cfg(target_os = "macos")]
pub(crate) type Model = crate::transcription::WarmTranscriber;
#[cfg(not(target_os = "macos"))]
pub(crate) type Model = crate::transcription::local_transcriber::LocalTranscriber;
/// Transcribes a complete 16 kHz clip offline on the engine thread.
pub(crate) type Offline = Box<dyn FnOnce(&mut Model, Vec<f32>) -> Result<String, String> + Send>;
/// Low-priority work on the model, such as a meeting chunk. It receives
/// `None` instead of the model when dictation claimed the engine first.
pub(crate) type Background = Box<dyn FnOnce(Option<&mut Model>) + Send>;
/// A healthy finish decodes at most a couple of seconds of buffered audio.
/// Past this the stream is aborted and the clip is transcribed offline.
const STREAM_FINISH_DEADLINE: Duration = Duration::from_millis(1_500);
/// Audio fed past the clip's trimmed end (a release handled late) that the
/// stream may still keep. Beyond it, the offline clip is authoritative.
const MAX_OVERFED_SAMPLES: usize = 16_000 / 4;
/// How long a job may run once the engine starts it, before the clip's own
/// share. It covers activating and prewarming the largest model inside the
/// job (macOS loads a new selection there). Time queued behind other work is
/// never counted: the deadline only catches a wedged engine, never a slow one.
const JOB_DEADLINE: Duration = Duration::from_secs(180);
/// Run time allowed per second of audio: two passes (voice-delimited
/// dictation retranscribes without its control phrase) on a CPU-only device
/// up to four times slower than real time.
const JOB_SECONDS_PER_AUDIO_SECOND: u32 = 8;
/// How often a waiter whose job has not started checks whether the job ahead
/// of it timed out, leaving the engine wedged.
const QUEUE_POLL: Duration = Duration::from_millis(250);
/// How often an idle engine looks again at Labs › Unload model when idle.
const IDLE_RECHECK: Duration = Duration::from_secs(30);
/// How long dropping the engine waits for its thread. A native run that cannot
/// be aborted is left to finish on its own.
const SHUTDOWN_DEADLINE: Duration = Duration::from_secs(10);
#[derive(Clone, Copy)]
struct Deadlines {
stream_finish: Duration,
job: Duration,
job_seconds_per_audio_second: u32,
shutdown: Duration,
}
impl Deadlines {
const PRODUCTION: Self = Self {
stream_finish: STREAM_FINISH_DEADLINE,
job: JOB_DEADLINE,
job_seconds_per_audio_second: JOB_SECONDS_PER_AUDIO_SECOND,
shutdown: SHUTDOWN_DEADLINE,
};
fn job_for(&self, samples: usize) -> Duration {
self.job
+ Duration::from_secs_f64(samples as f64 / 16_000.0) * self.job_seconds_per_audio_second
}
}
pub(crate) enum Command {
Begin {
stream: u64,
/// Aborts this stream only.
cancel: CancelToken,
/// Where the stream publishes its text after each feed, when live
/// text is on (Labs).
partials: Option<Partials>,
},
Feed {
stream: u64,
samples: Vec<f32>,
},
Cancel {
stream: u64,
},
Finish {
stream: Option<u64>,
clip: Vec<f32>,
offline: Offline,
job: Job,
},
/// An offline run that waits for an open live stream to end instead of
/// interrupting it, such as a capture's word chunk or a `/streams`
/// window. Like a finish it is a dictation request, so background work
/// sent before it yields.
Foreground {
clip: Vec<f32>,
offline: Offline,
job: Job,
},
/// A live stream that gives way to dictation (`/streams`): any dictation
/// request closes it, and while a dictation stream is open it is refused
/// instead of interrupting it.
BeginYielding {
stream: u64,
cancel: CancelToken,
yielding: Yielding,
},
/// Finalizes a yielding stream, or answers [`PREEMPTED`] at once when it
/// is no longer open. It never runs anything offline.
FinishYielding {
stream: u64,
reply: SyncSender<Result<String, String>>,
},
/// Work that needs the model itself, such as loading or switching it.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
Run(Box<dyn FnOnce(&mut Model) + Send>),
Background {
/// The dictation generation when the work was submitted.
generation: u64,
work: Background,
},
Shutdown,
}
/// Why a yielding stream ended without its text: dictation needed the engine.
pub(crate) const PREEMPTED: &str = "the stream gave way to dictation";
/// A live stream's text so far, as the model reports it after each feed.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Partial {
/// The prefix the model has committed; it only grows within one stream.
pub stable: String,
/// The model's volatile hypothesis after `stable`.
pub tentative: String,
}
/// One stream's latest partial text, shared between the worker that
/// publishes it and the stream's owner. Each stream has its own, so a new
/// capture never reads an older one's text.
#[derive(Clone, Default)]
pub(crate) struct Partials(Arc<Mutex<Published>>);
#[derive(Default)]
struct Published {
/// Bumped by each change, so an owner can tell what it has not seen.
seq: u64,
partial: Option<Partial>,
}
impl Partials {
/// Publishes `partial`; returns whether it changed the text.
pub(crate) fn publish(&self, partial: Partial) -> bool {
let mut published = self.0.lock().unwrap_or_else(|error| error.into_inner());
if published.partial.as_ref() == Some(&partial) {
return false;
}
published.seq += 1;
published.partial = Some(partial);
true
}
fn latest(&self) -> Option<Partial> {
self.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.partial
.clone()
}
/// The latest partial when it is newer than `seen`, which it advances.
fn newer_than(&self, seen: &mut u64) -> Option<Partial> {
let published = self.0.lock().unwrap_or_else(|error| error.into_inner());
if published.seq <= *seen {
return None;
}
*seen = published.seq;
published.partial.clone()
}
}
/// What the worker shares with a yielding stream's owner: whether the stream
/// is still open on the engine, and its latest partial text.
#[derive(Clone)]
pub(crate) struct Yielding {
open: Arc<AtomicBool>,
/// Samples the model has consumed.
consumed: Arc<AtomicUsize>,
partials: Partials,
}
impl Yielding {
fn new() -> Self {
Self {
open: Arc::new(AtomicBool::new(true)),
consumed: Arc::default(),
partials: Partials::default(),
}
}
fn close(&self) {
self.open.store(false, Ordering::Release);
}
}
/// A live stream that gives way to dictation (`/streams`). Unlike a
/// [`LiveStream`] it is not a dictation request: background work sent before
/// it still runs, and any dictation request closes it. Feed it 16 kHz audio,
/// then [`Self::finish`] it or drop it to cancel.
pub(crate) struct YieldingStream {
id: u64,
cancel: CancelToken,
yielding: Yielding,
sent: usize,
finished: bool,
commands: Sender<Command>,
}
impl YieldingStream {
/// Whether the stream is still open on the engine. Once dictation closes
/// it, its audio must be transcribed some other way.
pub(crate) fn open(&self) -> bool {
self.yielding.open.load(Ordering::Acquire)
}
pub(crate) fn feed(&mut self, samples: &[f32]) {
if samples.is_empty() || !self.open() {
return;
}
self.sent += samples.len();
let _ = self.commands.send(Command::Feed {
stream: self.id,
samples: samples.to_vec(),
});
}
/// Samples sent that the model has not consumed yet. Keeping this small
/// keeps a dictation request from queueing behind a pile of feeds.
pub(crate) fn in_flight(&self) -> usize {
self.sent
.saturating_sub(self.yielding.consumed.load(Ordering::Acquire))
}
/// The model's latest text for the audio fed so far.
pub(crate) fn partial(&self) -> Option<Partial> {
self.yielding.partials.latest()
}
/// Finalizes the stream within `deadline`. It fails with [`PREEMPTED`]
/// when dictation closed it first, and is aborted when the engine does
/// not reach it in time; either way nothing was lost but this text.
pub(crate) fn finish(mut self, deadline: Duration) -> Result<String, String> {
self.finished = true;
if !self.open() {
return Err(PREEMPTED.into());
}
let (reply, receiver) = mpsc::sync_channel(1);
if self
.commands
.send(Command::FinishYielding {
stream: self.id,
reply,
})
.is_err()
{
return Err("transcription engine stopped".into());
}
match receiver.recv_timeout(deadline) {
Ok(result) => result,
Err(RecvTimeoutError::Timeout) => {
self.cancel.cancel();
Err("the stream missed its finish deadline".into())
}
Err(RecvTimeoutError::Disconnected) => Err("transcription engine stopped".into()),
}
}
}
impl Drop for YieldingStream {
fn drop(&mut self) {
if !self.finished {
let _ = self.commands.send(Command::Cancel { stream: self.id });
}
}
}
/// One finish request as the worker sees it: its own cancellation, so a
/// timeout aborts this job and never a later capture, and its reply.
pub(crate) struct Job {
cancel: CancelToken,
reply: Sender<Reply>,
}
impl Job {
fn start(&self) {
let _ = self.reply.send(Reply::Started);
}
fn finish(self, result: Result<Transcribed, String>) {
let _ = self.reply.send(Reply::Done(result));
}
}
enum Reply {
/// The engine began this job; its deadline starts now.
Started,
Done(Result<Transcribed, String>),
}
#[derive(Debug)]
pub struct Transcribed {
pub text: String,
pub source: Source,
/// Time from the finish request to the final text.
pub finish_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
Stream,
Offline,
/// The stream could not be used; the reason is logged with the result.
Fallback(String),
}
impl Source {
pub fn label(&self) -> &str {
match self {
Self::Stream => "stream",
Self::Offline => "offline",
Self::Fallback(_) => "fallback",
}
}
}
/// The token of the job or stream the worker is running, so dropping the
/// engine aborts it. Work entered after the engine stops starts cancelled.
#[derive(Clone, Default)]
struct Running(Arc<Mutex<RunningState>>);
#[derive(Default)]
struct RunningState {
stopping: bool,
cancel: Option<CancelToken>,
}
impl Running {
fn enter(&self, cancel: &CancelToken) {
let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
if state.stopping {
cancel.cancel();
}
state.cancel = Some(cancel.clone());
}
fn stop(&self) {
let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
state.stopping = true;
if let Some(cancel) = &state.cancel {
cancel.cancel();
}
}
}
pub struct TranscriptionEngine {
commands: Sender<Command>,
running: Running,
/// Set when a job misses its deadline and cleared when the worker starts
/// another: jobs queued behind a wedged run fail instead of waiting.
stalled: Arc<AtomicBool>,
/// Dictation requests sent so far. Background work submitted before a
/// newer request yields to it.
requests: Arc<AtomicU64>,
/// Whether the loaded model can stream on its device.
streams: Arc<AtomicBool>,
/// Whether dictation streams publish their text as they go, asked as
/// each stream begins: Labs › Live text, or a
/// [`crate::dictation::live_text::Demand`].
live_text: fn() -> bool,
held: Held,
/// Whether the worker is running a dictation stream or finish.
dictating: Arc<AtomicBool>,
next_stream: AtomicU64,
deadlines: Deadlines,
thread: Option<JoinHandle<()>>,
}
/// The GGUF selection the engine's model held after its last command.
type Held = Arc<Mutex<Option<crate::transcription::models::TranscriptionSelection>>>;
/// A live stream for one capture. Feed it the capture's 16 kHz audio in order,
/// then either [`TranscriptionEngine::finish`] or drop it to cancel.
pub struct LiveStream {
id: u64,
cancel: CancelToken,
fed: usize,
finished: bool,
commands: Sender<Command>,
/// The stream's text so far, with live text on, and the last version
/// [`Self::take_partial`] returned.
partials: Option<(Partials, u64)>,
}
impl LiveStream {
/// Total samples handed to the stream so far.
pub fn fed(&self) -> usize {
self.fed
}
/// The model's text for the audio fed so far, when it changed since the
/// last call. Always `None` without live text. It is provisional: the
/// finish may replace it entirely, so it is only ever shown, never
/// pasted or kept.
pub fn take_partial(&mut self) -> Option<Partial> {
let (partials, seen) = self.partials.as_mut()?;
partials.newer_than(seen)
}
pub fn feed(&mut self, samples: &[f32]) {
if samples.is_empty() {
return;
}
self.fed += samples.len();
let _ = self.commands.send(Command::Feed {
stream: self.id,
samples: samples.to_vec(),
});
}
}
impl Drop for LiveStream {
fn drop(&mut self) {
if !self.finished {
let _ = self.commands.send(Command::Cancel { stream: self.id });
}
}
}
/// A finish in flight. Waiting enforces the stream deadline from the caller's
/// side, so a stalled native stream cannot hold the paste forever, then bounds
/// the job once the engine starts it, so a wedged run fails instead.
pub struct PendingTranscript {
reply: Receiver<Reply>,
cancel: CancelToken,
stream_cancel: Option<CancelToken>,
stalled: Arc<AtomicBool>,
/// How long the job may run once started: its allowance plus the clip's.
job: Duration,
stream_finish: Duration,
}
impl PendingTranscript {
pub fn wait(self) -> Result<Transcribed, String> {
let mut stream_deadline = self
.stream_cancel
.as_ref()
.map(|_| Instant::now() + self.stream_finish);
let mut job_deadline: Option<Instant> = None;
loop {
let now = Instant::now();
let timeout = [stream_deadline, job_deadline]
.into_iter()
.flatten()
.min()
.map_or(QUEUE_POLL, |deadline| {
deadline.saturating_duration_since(now).min(QUEUE_POLL)
});
match self.reply.recv_timeout(timeout) {
Ok(Reply::Done(result)) => return result,
Ok(Reply::Started) => job_deadline = Some(Instant::now() + self.job),
Err(RecvTimeoutError::Disconnected) => {
return Err("transcription engine stopped".into());
}
Err(RecvTimeoutError::Timeout) => {
let now = Instant::now();
if let (Some(deadline), Some(stream)) = (stream_deadline, &self.stream_cancel)
&& now >= deadline
{
tracing::warn!("live stream missed its finish deadline; aborting it");
stream.cancel();
stream_deadline = None;
}
if job_deadline.is_some_and(|deadline| now >= deadline) {
tracing::error!(
deadline_ms = self.job.as_millis() as u64,
"transcription missed its deadline; failing the job"
);
self.stalled.store(true, Ordering::Release);
self.abandon();
return Err("transcription timed out".into());
}
if job_deadline.is_none() && self.stalled.load(Ordering::Acquire) {
tracing::error!("transcription engine is stuck; failing a queued job");
self.abandon();
return Err("transcription engine is stuck".into());
}
}
}
}
}
/// Aborts this job's run, or skips it if the engine has not reached it.
fn abandon(&self) {
self.cancel.cancel();
if let Some(stream) = &self.stream_cancel {
stream.cancel();
}
}
}
impl TranscriptionEngine {
pub fn start(model: Model) -> Result<Self> {
let streams = Arc::new(AtomicBool::new(model.stream_options().is_some()));
let (commands, receiver) = mpsc::channel();
let requests = Arc::new(AtomicU64::new(0));
let running = Running::default();
let stalled = Arc::new(AtomicBool::new(false));
let held = Held::new(Mutex::new(model.gguf_selection().cloned()));
let dictating = Arc::new(AtomicBool::new(false));
let worker = Worker {
model: Some(model),
parked: None,
idle_since: Instant::now(),
running: running.clone(),
stalled: stalled.clone(),
streams: streams.clone(),
requests: requests.clone(),
held: held.clone(),
dictating: dictating.clone(),
};
let thread = thread::Builder::new()
.name("transcription-engine".into())
.spawn(move || worker.run(receiver))?;
Ok(Self {
commands,
running,
stalled,
requests,
streams,
live_text: || crate::labs::live_text() || crate::dictation::live_text::demanded(),
held,
dictating,
next_stream: AtomicU64::new(0),
deadlines: Deadlines::PRODUCTION,
thread: Some(thread),
})
}
/// An engine without a worker whose model always streams; tests read the
/// commands it would have handled.
#[cfg(test)]
pub(crate) fn for_test() -> (Self, Receiver<Command>) {
let (commands, receiver) = mpsc::channel();
let engine = Self {
commands,
running: Running::default(),
stalled: Arc::default(),
requests: Arc::default(),
streams: Arc::new(AtomicBool::new(true)),
live_text: || false,
held: Held::default(),
dictating: Arc::default(),
next_stream: AtomicU64::new(0),
deadlines: Deadlines::PRODUCTION,
thread: None,
};
(engine, receiver)
}
/// Like [`Self::for_test`] for a model that cannot stream.
#[cfg(test)]
pub(crate) fn for_test_without_streaming() -> (Self, Receiver<Command>) {
let (engine, receiver) = Self::for_test();
engine.streams.store(false, Ordering::Release);
(engine, receiver)
}
#[cfg(test)]
fn with_deadlines(mut self, deadlines: Deadlines) -> Self {
self.deadlines = deadlines;
self
}
/// Turns live text on, as Labs does.
#[cfg(test)]
pub(crate) fn with_live_text(mut self) -> Self {
self.live_text = || true;
self
}
/// Opens a live stream when the loaded model can stream on this device.
pub fn begin(&self) -> Option<LiveStream> {
if !self.streams.load(Ordering::Acquire) {
return None;
}
let id = self.next_stream.fetch_add(1, Ordering::Relaxed) + 1;
let cancel = CancelToken::new();
let partials = (self.live_text)().then(Partials::default);
self.requests.fetch_add(1, Ordering::AcqRel);
self.commands
.send(Command::Begin {
stream: id,
cancel: cancel.clone(),
partials: partials.clone(),
})
.ok()?;
Some(LiveStream {
id,
cancel,
fed: 0,
finished: false,
commands: self.commands.clone(),
partials: partials.map(|partials| (partials, 0)),
})
}
/// Opens a stream that gives way to dictation, when the loaded model can
/// stream on this device. See [`YieldingStream`].
pub(crate) fn begin_yielding(&self) -> Option<YieldingStream> {
if !self.streams.load(Ordering::Acquire) {
return None;
}
let id = self.next_stream.fetch_add(1, Ordering::Relaxed) + 1;
let cancel = CancelToken::new();
let yielding = Yielding::new();
self.commands
.send(Command::BeginYielding {
stream: id,
cancel: cancel.clone(),
yielding: yielding.clone(),
})
.ok()?;
Some(YieldingStream {
id,
cancel,
yielding,
sent: 0,
finished: false,
commands: self.commands.clone(),
})
}
/// Whether the loaded model can stream on its device.
pub(crate) fn streams(&self) -> bool {
self.streams.load(Ordering::Acquire)
}
/// Finishes a capture with its complete 16 kHz clip. Without a stream,
/// or when the stream is unusable, the clip is transcribed offline.
#[cfg(not(target_os = "macos"))]
pub fn finish(&self, stream: Option<LiveStream>, clip: Vec<f32>) -> Result<PendingTranscript> {
self.finish_with(
stream,
clip,
Box::new(|model, clip| {
// Labs › Skip long pauses, asked as the run starts.
let mut clip = whole_clip(clip, crate::labs::skip_pauses());
crate::dictation::pad_for_parakeet(&mut clip);
model
.transcribe(&clip)
.map_err(|error| format!("{error:#}"))
}),
)
}
/// Like `finish`, with the caller's offline transcription of the clip.
pub fn finish_with(
&self,
stream: Option<LiveStream>,
clip: Vec<f32>,
offline: Offline,
) -> Result<PendingTranscript> {
let (stream, stream_cancel) = match stream {
Some(mut stream) => {
stream.finished = true;
(Some(stream.id), Some(stream.cancel.clone()))
}
None => (None, None),
};
self.request(clip.len(), stream_cancel, |job| Command::Finish {
stream,
clip,
offline,
job,
})
}
/// Transcribes `clip` offline after every command already sent, without
/// ever interrupting a live stream: one open when it arrives finishes
/// first. Background work sent before it yields, as to a finish.
pub fn foreground(&self, clip: Vec<f32>, offline: Offline) -> Result<PendingTranscript> {
self.request(clip.len(), None, |job| Command::Foreground {
clip,
offline,
job,
})
}
fn request(
&self,
samples: usize,
stream_cancel: Option<CancelToken>,
command: impl FnOnce(Job) -> Command,
) -> Result<PendingTranscript> {
let (reply, receiver) = mpsc::channel();
let cancel = CancelToken::new();
let job = self.deadlines.job_for(samples);
self.requests.fetch_add(1, Ordering::AcqRel);
self.commands
.send(command(Job {
cancel: cancel.clone(),
reply,
}))
.map_err(|_| eyre!("transcription engine stopped"))?;
Ok(PendingTranscript {
reply: receiver,
cancel,
stream_cancel,
stalled: self.stalled.clone(),
job,
stream_finish: self.deadlines.stream_finish,
})
}
/// Runs `work` with the model, after every command already sent. A live
/// stream is closed first; its finish then takes the offline path.
#[cfg(target_os = "macos")]
pub fn run(&self, work: impl FnOnce(&mut Model) + Send + 'static) -> Result<()> {
self.commands
.send(Command::Run(Box::new(work)))
.map_err(|_| eyre!("transcription engine stopped"))
}
/// Runs `work` with the model unless a dictation request was sent first or
/// a live stream is open, and returns `None` when one was. A request sent
/// while `work` runs waits for it: transcribe.cpp cannot abort a Metal run.
pub fn background<R: Send + 'static>(
&self,
work: impl FnOnce(&mut Model) -> R + Send + 'static,
) -> Result<Option<R>> {
let (reply, receiver) = mpsc::channel();
let generation = self.requests.load(Ordering::Acquire);
self.commands
.send(Command::Background {
generation,
work: Box::new(move |model| {
let _ = reply.send(model.map(work));
}),
})
.map_err(|_| eyre!("transcription engine stopped"))?;
receiver
.recv()
.map_err(|_| eyre!("transcription engine stopped"))
}
/// Drops the engine on its own thread, so replacing the model from the
/// hotkey loop never waits on a run still in flight.
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub fn retire(self) {
let spawned = thread::Builder::new()
.name("transcription-engine-retire".into())
.spawn(move || drop(self));
if let Err(error) = spawned {
tracing::warn!(%error, "could not retire the old transcription engine in the background");
}
}
/// Makes this the engine that meeting transcription and the local API share.
pub fn share(self: &Arc<Self>) {
*SHARED.lock().unwrap_or_else(|error| error.into_inner()) = Arc::downgrade(self);
}
/// The running app's engine, when one is shared.
pub fn shared() -> Option<Arc<Self>> {
SHARED
.lock()
.unwrap_or_else(|error| error.into_inner())
.upgrade()
}
/// Whether the model holds the GGUF `selection` as of its last finished
/// command. Readable while dictation runs, unlike the model itself.
pub(crate) fn holds(
&self,
selection: &crate::transcription::models::TranscriptionSelection,
) -> bool {
self.held
.lock()
.unwrap_or_else(|error| error.into_inner())
.as_ref()
== Some(selection)
}
}
impl TranscriptionEngine {
/// The GGUF selection the model held after its last finished command.
pub(crate) fn held_selection(
&self,
) -> Option<crate::transcription::models::TranscriptionSelection> {
self.held
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone()
}
}
/// Whether a dictation or a meeting records, so an idle model stays loaded:
/// both hold idle-sleep prevention while they record, and a macOS capture
/// counts from its press.
fn recording() -> bool {
crate::audio::idle_sleep::held() || dictation_busy()
}
/// The model `selection` loads into, prewarmed, as the engine held it.
#[cfg(target_os = "macos")]
fn reload(selection: &crate::transcription::models::TranscriptionSelection) -> Result<Model> {
let mut model = Model::default();
model.activate(selection)?.prewarm()?;
Ok(model)
}
#[cfg(not(target_os = "macos"))]
fn reload(selection: &crate::transcription::models::TranscriptionSelection) -> Result<Model> {
Model::load(selection)
}
static SHARED: std::sync::Mutex<std::sync::Weak<TranscriptionEngine>> =
std::sync::Mutex::new(std::sync::Weak::new());
/// Whether dictation is capturing or transcribing, so host audio and
/// background work give way to it. macOS counts a capture from its press;
/// Linux and Windows count the shared engine's dictation streams and finishes.
pub(crate) fn dictation_busy() -> bool {
#[cfg(target_os = "macos")]
let capturing = crate::parakeet::dictation_busy();
#[cfg(not(target_os = "macos"))]
let capturing = false;
capturing
|| TranscriptionEngine::shared()
.is_some_and(|engine| engine.dictating.load(Ordering::Acquire))
}
/// A model the engine can hold: the GGUF transcriber on macOS, the one local
/// GGUF model on Linux and Windows.
#[cfg(target_os = "macos")]
pub(crate) type HeldModel = crate::transcription::Transcriber;
#[cfg(not(target_os = "macos"))]
pub(crate) type HeldModel = crate::transcription::local_transcriber::LocalTranscriber;
/// The engine's model when it is the GGUF `selection`, never loading or
/// switching one.
pub(crate) fn held<'a>(
model: &'a mut Model,
selection: &crate::transcription::models::TranscriptionSelection,
) -> Option<&'a mut HeldModel> {
#[cfg(target_os = "macos")]
let model = model
.active()
.filter(|model| matches!(model, crate::transcription::Transcriber::Gguf(_)))?;
model.matches_selection(selection).then_some(model)
}
/// Transcribes a complete 16 kHz clip with a held model, padded as a
/// dictation's clip is.
pub(crate) fn transcribe_clip(model: &mut HeldModel, samples: Vec<f32>) -> Result<String> {
#[cfg(target_os = "macos")]
return model.transcribe(samples);
#[cfg(not(target_os = "macos"))]
model.transcribe_clip(samples)
}
impl Drop for TranscriptionEngine {
fn drop(&mut self) {
self.running.stop();
// A live stream's sender may outlive the engine; stop explicitly.
let _ = self.commands.send(Command::Shutdown);
let Some(thread) = self.thread.take() else {
return;
};
let deadline = Instant::now() + self.deadlines.shutdown;
while !thread.is_finished() && Instant::now() < deadline {
thread::sleep(Duration::from_millis(5));
}
if thread.is_finished() {
let _ = thread.join();
} else {
tracing::error!("transcription engine did not stop in time; leaving it running");
}
}
}
struct Worker {
/// `None` while unloaded for idleness (Labs › Unload model when idle) or
/// after its reload failed.
model: Option<Model>,
/// What an unloaded model reloads, before the next command that needs it.
parked: Option<crate::transcription::models::TranscriptionSelection>,
/// When the last command ended.
idle_since: Instant,
running: Running,
stalled: Arc<AtomicBool>,
streams: Arc<AtomicBool>,
requests: Arc<AtomicU64>,
held: Held,
dictating: Arc<AtomicBool>,
}
/// How a live stream ended inside the worker.
enum StreamEnd {
/// A finish for this stream: the final text, or why the stream is unusable.
Finished {
result: Result<String, String>,
clip: Vec<f32>,
offline: Offline,
job: Job,
started: Instant,
},
Cancelled,
/// Another command arrived first; it is handled after the stream closes.
Interrupted(Command),
Disconnected,
}
impl Worker {
fn run(mut self, commands: Receiver<Command>) {
// Commands received while a stream was open, handled before new ones.
let mut next = VecDeque::new();
loop {
let Some(command) = next.pop_front().or_else(|| self.wait(&commands)) else {
return;
};
match command {
Command::Begin {
stream,
cancel,
partials,
} => {
self.dictating.store(true, Ordering::Release);
crate::dictation::vocabulary::for_dictation(|| {
self.stream(stream, &cancel, partials.as_ref(), &commands, &mut next);
});
self.dictating.store(false, Ordering::Release);
}
Command::BeginYielding {
stream,
cancel,
yielding,
} => {
// Anything already waiting comes first.
if next.is_empty() {
self.yielding_stream(stream, &cancel, &yielding, &commands, &mut next);
}
yielding.close();
}
Command::FinishYielding { reply, .. } => {
let _ = reply.send(Err(PREEMPTED.into()));
}
Command::Finish {
stream,
clip,
offline,
job,
} => {
let source = match stream {
// The stream was already closed: its begin failed or
// another command interrupted it.
Some(_) => Source::Fallback("the live stream was not available".into()),
None => Source::Offline,
};
self.dictating.store(true, Ordering::Release);
crate::dictation::vocabulary::for_dictation(|| {
self.run_offline(clip, offline, source, job);
});
self.dictating.store(false, Ordering::Release);
}
Command::Foreground { clip, offline, job } => {
self.run_offline(clip, offline, Source::Offline, job);
}
Command::Run(work) => {
if let Some(model) = self.model() {
work(model);
}
self.publish_streams();
}
Command::Background { generation, work } => {
let current = self.requests.load(Ordering::Acquire) == generation;